Place objects by running the pack's placement graph

- IrisObject.place runs the pack's resolved placement graph, Iris's
  built-in placement modules included, with IrisApi's PlacementRunner
  (ModuleObjectPlacement). The engine runtime no longer resolves
  placement lifecycle plans.
- Writes go to an ObjectPlacerEdit, a buffer over the Iris object placer
  that reads its own writes and reaches the placer only on commit: blocks,
  then tile data and iris:marker markers, then the caller's listener. A
  rejected placement writes nothing.
- The placement area is every column the object reaches in any rotation,
  moved by its translation and surface warp, widened by one block and the
  pipeline's reach, at any height.
- Each placement's seed mixes the world seed with the object key and the
  requested position. Without an engine one draw from the caller's random
  stands in for the world seed.
- Built-in stages read Iris's own placement inputs from IrisPlacement,
  bound on the placing thread while the graph runs.
- Gson decodes the module settings of every object placement in pack
  JSON, snippet placements included.
- Platform keys without a namespace read as Minecraft's.
- The built-in API package moved to the default module's source tree.
This commit is contained in:
piexel committed 2026-10-08 08:33:48 +02:00
1 parent da71e0e921
commit 529d70b14a
32 files changed
+1586 -461

No files matched your search

@@ -1,30 +0,0 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* The public face of Iris's built-in modules: their stage constants and the settings and output types
* of those stages. {@link art.arcane.iris.core.modules.IrisModuleHost} exposes this package, with its
* subpackages, to pack modules, so a pack jar can {@code requires(...)} a built-in stage and read its
* output. Everything here is part of what packs compile against.
* <p>
* Keep implementation out of it: stage bodies and anything that uses Iris internals live in the
* built-in module classes outside this package, which packs cannot see. One subpackage per built-in
* module, named after the module path, such as {@code art.arcane.iris.builtin.deposit} for
* {@code iris:deposit}.
*/
package art.arcane.iris.builtin;
@@ -31,6 +31,7 @@ import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.core.modules.ObjectPlacementSettingsReader;
import art.arcane.iris.core.modules.PackModuleSet;
import art.arcane.iris.core.pack.PackDirectoryResolver;
import art.arcane.iris.engine.data.cache.AtomicCache;
@@ -474,6 +475,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
.addDeserializationExclusionStrategy(this)
.addSerializationExclusionStrategy(this)
.setStrictness(Strictness.LENIENT)
.registerTypeAdapterFactory(new ObjectPlacementSettingsReader(() -> modules.settings()))
.registerTypeAdapterFactory(this)
.registerTypeAdapter(MantleFlag.class, new MantleFlagAdapter())
.setPrettyPrinting();
@@ -0,0 +1,64 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.engine.object.prefab.TileData;
import com.volmit.object.BlockEntityData;
import com.volmit.resource.ResourceId;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
/**
* Iris's tile data as IrisApi block entity payloads, in the binary form Iris objects store them in. Iris
* reads no other format, so a payload of another format or version fails rather than being dropped.
*/
public final class BlockEntities {
public static final ResourceId TILE_FORMAT = ResourceId.parse("iris:tile");
public static final int TILE_FORMAT_VERSION = 1;
private BlockEntities() {
}
public static BlockEntityData of(TileData tile) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
tile.toBinary(out);
} catch (IOException failure) {
throw new UncheckedIOException("Cannot store the tile data of " + tile.getMaterialKey(), failure);
}
return new BlockEntityData(TILE_FORMAT, TILE_FORMAT_VERSION, bytes.toByteArray());
}
public static TileData tileOf(BlockEntityData entity) {
if (!entity.format().equals(TILE_FORMAT) || entity.version() != TILE_FORMAT_VERSION) {
throw new IllegalArgumentException("Iris stores block entities of format " + TILE_FORMAT + " version "
+ TILE_FORMAT_VERSION + " only, not " + entity.format() + " version " + entity.version());
}
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(entity.payload()))) {
return TileData.read(in);
} catch (IOException failure) {
throw new UncheckedIOException("Cannot read a block entity of format " + TILE_FORMAT, failure);
}
}
}
@@ -22,8 +22,6 @@ import art.arcane.iris.spi.PlatformBlockState;
import com.volmit.block.BlockState;
import com.volmit.hunk.Hunk;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
@@ -32,17 +30,13 @@ import java.util.function.Function;
* invocation, since a chunk repeats few states many times.
*/
final class BlockStateHunk implements Hunk<BlockState> {
private static final BlockState AIR = BlockState.parse("minecraft:air");
private final art.arcane.iris.util.project.hunk.Hunk<PlatformBlockState> blocks;
private final Function<String, PlatformBlockState> platformStates;
private final Map<PlatformBlockState, BlockState> read = new HashMap<>();
private final Map<BlockState, PlatformBlockState> written = new HashMap<>();
private final PlatformBlockStates states;
/** {@code platformStates} turns a block state key into the platform's state, such as {@code B::getState}. */
BlockStateHunk(art.arcane.iris.util.project.hunk.Hunk<PlatformBlockState> blocks, Function<String, PlatformBlockState> platformStates) {
this.blocks = blocks;
this.platformStates = platformStates;
this.states = new PlatformBlockStates(platformStates);
}
@Override
@@ -63,11 +57,7 @@ final class BlockStateHunk implements Hunk<BlockState> {
@Override
public BlockState get(int x, int y, int z) {
requireInside(x, y, z);
PlatformBlockState state = blocks.get(x, y, z);
if (state == null) {
return AIR;
}
return read.computeIfAbsent(state, platform -> BlockState.parse(platform.key()));
return states.toApi(blocks.get(x, y, z));
}
@Override
@@ -76,7 +66,7 @@ final class BlockStateHunk implements Hunk<BlockState> {
if (value == null) {
throw new NullPointerException("Block hunks hold no null states; write minecraft:air for empty space");
}
blocks.set(x, y, z, written.computeIfAbsent(value, state -> platformStates.apply(state.key())));
blocks.set(x, y, z, states.toPlatform(value));
}
private void requireInside(int x, int y, int z) {
@@ -18,6 +18,7 @@
package art.arcane.iris.core.modules;
import art.arcane.iris.engine.object.placement.PlacementModules;
import art.arcane.iris.spi.IrisPlatforms;
import com.volmit.IrisModule;
import com.volmit.host.ModuleHost;
@@ -37,7 +38,6 @@ public final class IrisModuleHost {
static final String RESERVED_NAMESPACE = "iris";
private static final String[] JAR_COPY_FOLDER = {"cache", "module-jars"};
private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir";
private static final List<IrisModule> BUILT_IN_MODULES = List.of();
private IrisModuleHost() {
}
@@ -46,8 +46,13 @@ public final class IrisModuleHost {
return Holder.HOST;
}
/** The modules every pack loads before its own: Iris's built-in features. */
public static List<IrisModule> builtInModules() {
return PlacementModules.all();
}
private static ModuleHost build() {
return ModuleHost.of(BUILT_IN_MODULES)
return ModuleHost.of(builtInModules())
.exposing(BUILT_IN_API_PACKAGE)
.reservingNamespaces(RESERVED_NAMESPACE)
.reservingFields(ModuleTargets.reservedFields())
@@ -0,0 +1,133 @@
/*
* 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.core.modules;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.terrain.carving.CarveResult;
import com.volmit.world.BlockPosition;
import java.util.function.Supplier;
/**
* Iris's own inputs of the object placement being run: the placement settings, object, placer and cave
* that IrisApi does not describe. Iris's built-in placement stages read them through {@link #current()},
* bound on the placing thread while the placement graph runs; pack modules cannot see this class.
*/
public final class IrisPlacement {
private static final ScopedValue<IrisPlacement> CURRENT = ScopedValue.newInstance();
private static final int NOT_ANCHORED = Integer.MIN_VALUE;
private final IrisObject object;
private final IrisObjectPlacement config;
private final IObjectPlacer placer;
private final CarveResult cave;
private final int x;
private final int requestedY;
private final int z;
private final IrisData data;
private final PlatformBlockStates states;
private final ObjectPlacerEdit edit;
private int anchorY = NOT_ANCHORED;
IrisPlacement(IrisObject object, IrisObjectPlacement config, IObjectPlacer placer, CarveResult cave,
int x, int requestedY, int z, IrisData data, PlatformBlockStates states, ObjectPlacerEdit edit) {
this.object = object;
this.config = config;
this.placer = placer;
this.cave = cave;
this.x = x;
this.requestedY = requestedY;
this.z = z;
this.data = data;
this.states = states;
this.edit = edit;
}
/** The placement running on this thread. */
public static IrisPlacement current() {
if (!CURRENT.isBound()) {
throw new IllegalStateException("No Iris object placement is running on this thread");
}
return CURRENT.get();
}
<T> T runBound(Supplier<T> placement) {
return ScopedValue.where(CURRENT, this).call(placement::get);
}
public IrisObject object() {
return object;
}
/** The settings as the caller passed them; the built-in preparation may derive others for this placement. */
public IrisObjectPlacement config() {
return config;
}
public IObjectPlacer placer() {
return placer;
}
/** The cave the object is placed in, or null outside caves. */
public CarveResult cave() {
return cave;
}
public int x() {
return x;
}
/** The height the caller asked for, negative when the placement samples it. */
public int requestedY() {
return requestedY;
}
public int z() {
return z;
}
public IrisData data() {
return data;
}
/** Converts block states for this placement. */
public PlatformBlockStates states() {
return states;
}
/** Reports a buffered write as one of the object's own blocks, which Iris's placement listener hears after the commit. */
public void objectBlockWritten(BlockPosition position) {
edit.recordObjectBlock(position);
}
/** Reports the height the object was anchored at, which the placement returns to its caller. */
public void anchoredAt(int y) {
anchorY = y;
}
int anchorY() {
if (anchorY == NOT_ANCHORED) {
throw new IllegalStateException("The placement graph placed " + object.getLoadKey() + " without anchoring it");
}
return anchorY;
}
}
@@ -0,0 +1,100 @@
/*
* 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.core.modules;
import com.volmit.config.FeatureSettings;
import com.volmit.mantle.BlockBox;
import com.volmit.object.ObjectTransformer;
import com.volmit.placement.PlacementContext;
import com.volmit.resource.PackResources;
import com.volmit.world.BiomeSample;
import com.volmit.world.BlockView;
import com.volmit.world.TerrainSample;
import com.volmit.world.TerrainSampler;
/** The read-only IrisApi inputs of one Iris object placement. */
final class IrisPlacementInputs implements PlacementContext {
private static final String NOT_BRIDGED = " is not bridged to Iris yet; modules cannot use it until a built-in port needs it";
private final long worldSeed;
private final TerrainSampler terrain;
private final FeatureSettings settings;
private final BlockView blocks;
IrisPlacementInputs(long worldSeed, TerrainSampler terrain, FeatureSettings settings, BlockView blocks) {
this.worldSeed = worldSeed;
this.terrain = terrain;
this.settings = settings;
this.blocks = blocks;
}
/** For placements without an engine, such as pasting an object into a world Iris does not generate. */
static TerrainSampler noTerrain(BlockBox bounds) {
return new TerrainSampler() {
@Override
public BlockBox bounds() {
return bounds;
}
@Override
public TerrainSample column(int worldX, int worldZ) {
throw withoutEngine();
}
@Override
public BiomeSample biome(int worldX, int worldY, int worldZ) {
throw withoutEngine();
}
};
}
private static UnsupportedOperationException withoutEngine() {
return new UnsupportedOperationException("This placement runs without an Iris engine, so it has no terrain to sample");
}
@Override
public TerrainSampler terrain() {
return terrain;
}
@Override
public FeatureSettings settings() {
return settings;
}
@Override
public ObjectTransformer objects() {
throw new UnsupportedOperationException("Object transforms for placement stages" + NOT_BRIDGED);
}
@Override
public BlockView blocks() {
return blocks;
}
@Override
public long worldSeed() {
return worldSeed;
}
@Override
public PackResources resources() {
throw new UnsupportedOperationException("Pack resources for placement stages" + NOT_BRIDGED);
}
}
@@ -29,8 +29,9 @@ import java.util.Optional;
import java.util.OptionalInt;
/**
* Iris's terrain streams for one chunk invocation. The streams are computed, not prepared, so the
* bounds are only the area the pipeline's reach may touch: the chunk widened by it, at full height.
* Iris's terrain streams for one invocation. The streams are computed, not prepared, so the bounds are
* only the area the invocation may touch: a chunk or a placement widened by the pipeline's reach, at
* full height.
*/
final class IrisTerrainSampler implements TerrainSampler {
private static final int CHUNK_WIDTH_BLOCKS = 16;
@@ -39,12 +40,17 @@ final class IrisTerrainSampler implements TerrainSampler {
private final PackResourceIds ids;
private final BlockBox bounds;
/** The chunk at {@code originX}, {@code originZ} widened by {@code reachBlocks}, over the full world height. */
IrisTerrainSampler(Engine engine, PackResourceIds ids, int originX, int originZ, int reachBlocks) {
this(engine, ids, originX - reachBlocks, originZ - reachBlocks,
originX + CHUNK_WIDTH_BLOCKS + reachBlocks, originZ + CHUNK_WIDTH_BLOCKS + reachBlocks);
}
/** Columns from the minima, inclusive, to the maxima, exclusive, over the full world height. */
IrisTerrainSampler(Engine engine, PackResourceIds ids, int minX, int minZ, int maxX, int maxZ) {
this.engine = engine;
this.ids = ids;
this.bounds = new BlockBox(
originX - reachBlocks, engine.getMinHeight(), originZ - reachBlocks,
originX + CHUNK_WIDTH_BLOCKS + reachBlocks, engine.getMinHeight() + engine.getHeight(), originZ + CHUNK_WIDTH_BLOCKS + reachBlocks);
this.bounds = new BlockBox(minX, engine.getMinHeight(), minZ, maxX, engine.getMinHeight() + engine.getHeight(), maxZ);
}
@Override
@@ -0,0 +1,124 @@
/*
* 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.core.modules;
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.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.prefab.IrisObjectShaping;
import art.arcane.iris.engine.object.terrain.carving.CarveResult;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.config.FeatureSettings;
import com.volmit.host.PlacementOutcome;
import com.volmit.host.PlacementRunner;
import com.volmit.host.ResolvedGraph;
import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import com.volmit.world.TerrainSampler;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* Places an Iris object by running the pack's placement graph, Iris's built-in placement stages included,
* with IrisApi's {@link PlacementRunner}. The writes are buffered and reach the placer only when no stage
* rejects the placement.
* <p>
* Each stage draws from its own stream of one seed per placement, from the world seed and the placement's
* identity: the object and the requested position. Without an engine there is no world seed, so one draw
* from the caller's random stands in for it.
*/
public final class ModuleObjectPlacement {
private static final String UNNAMED_OBJECT = "unnamed";
private ModuleObjectPlacement() {
}
/**
* @param requestedY the height to place at, or a negative value for the placement to sample it
* @param listener hears each of the object's own blocks once the placement is written; null for none
* @param cave the cave the object is placed in, or null outside caves
*/
public static ObjectPlacementResult place(IrisObject object, int x, int requestedY, int z, IObjectPlacer placer,
IrisObjectPlacement config, RNG rng,
BiConsumer<art.arcane.volmlib.util.math.BlockPosition, PlatformBlockState> listener,
CarveResult cave, IrisData data) {
Objects.requireNonNull(placer, "Object placer is required.");
Objects.requireNonNull(config, "Object placement config is required.");
Objects.requireNonNull(rng, "Object placement RNG is required.");
Objects.requireNonNull(data, "Object placement data is required.");
ResolvedGraph graph = data.getModules().pack().placement();
GeneratedObject geometry = geometryOf(object, config);
BlockBox area = PlacementArea.around(geometry, config, x, z, graph.reach().blocks());
PlatformBlockStates states = new PlatformBlockStates(ModuleObjectPlacement::platformState);
ObjectPlacerEdit edit = new ObjectPlacerEdit(placer, area, states, listener);
IrisPlacement placement = new IrisPlacement(object, config, placer, cave, x, requestedY, z, data, states, edit);
PackResourceIds ids = new PackResourceIds(data.getDataFolder());
String objectKey = keyOf(object);
Engine engine = placer.getEngine();
long worldSeed = engine != null ? engine.getSeedManager().getSeed() : rng.nextLong();
ResourceId source = ids.of("object", objectKey);
PlacementRequest request = new PlacementRequest(ids.of("placement/" + objectKey + "/" + x + "/" + requestedY + "/" + z),
geometry, new BlockPosition(x, requestedY, z));
IrisPlacementInputs inputs = new IrisPlacementInputs(worldSeed, terrain(engine, ids, area),
new PlacementModuleSettings(worldSettings(engine, ids), config.getModuleSettings(), source),
new PlacerBlockView(placer, area, states));
long seed = ModuleSeeds.placement(worldSeed, objectKey, x, requestedY, z);
PlacementOutcome outcome = placement.runBound(() -> new PlacementRunner(graph)
.place(request, edit, inputs, seed, config.getModuleSettings().configured()));
return outcome.isPlaced()
? ObjectPlacementResult.placed(placement.anchorY())
: ObjectPlacementResult.rejected(outcome.rejection().orElseThrow());
}
/** Smart boring adds the object's bored air, so it has to happen before the geometry is read. */
private static GeneratedObject geometryOf(IrisObject object, IrisObjectPlacement config) {
if (config.isSmartBore()) {
IrisObjectShaping.ensureSmartBored(object);
}
return object.getGeometry();
}
private static TerrainSampler terrain(Engine engine, PackResourceIds ids, BlockBox area) {
if (engine == null) {
return IrisPlacementInputs.noTerrain(area);
}
return new IrisTerrainSampler(engine, ids, area.minX(), area.minZ(), area.maxX(), area.maxZ());
}
private static FeatureSettings worldSettings(Engine engine, PackResourceIds ids) {
return engine == null ? PlacementModuleSettings.noWorld() : new ChunkModuleSettings(engine, ids);
}
/** Resolved by the platform bound now, so a rebound platform never answers with another's states. */
private static PlatformBlockState platformState(String key) {
return IrisPlatforms.get().registries().block(key);
}
private static String keyOf(IrisObject object) {
return object.getLoadKey() == null ? UNNAMED_OBJECT : object.getLoadKey();
}
}
@@ -18,18 +18,37 @@
package art.arcane.iris.core.modules;
import java.nio.charset.StandardCharsets;
/**
* The seed of one module chunk invocation, from the world seed and the chunk position. IrisApi derives
* each stage's stream from it and the stage id.
* The seed of one module invocation: a chunk from the world seed and the chunk position, a placement
* from the world seed and the placement's identity. IrisApi derives each stage's stream from it and the
* stage id.
*/
final class ModuleSeeds {
private static final long CHUNK_X_MULTIPLIER = 0x9E3779B97F4A7C15L;
private static final long CHUNK_Z_MULTIPLIER = 0xC2B2AE3D27D4EB4FL;
private static final long X_MULTIPLIER = 0x9E3779B97F4A7C15L;
private static final long Z_MULTIPLIER = 0xC2B2AE3D27D4EB4FL;
private static final long Y_MULTIPLIER = 0x165667B19E3779F9L;
private static final long FNV_OFFSET_BASIS = 0xCBF29CE484222325L;
private static final long FNV_PRIME = 0x100000001B3L;
private ModuleSeeds() {
}
static long chunk(long worldSeed, int chunkX, int chunkZ) {
return worldSeed ^ (chunkX * CHUNK_X_MULTIPLIER) ^ (chunkZ * CHUNK_Z_MULTIPLIER);
return worldSeed ^ (chunkX * X_MULTIPLIER) ^ (chunkZ * Z_MULTIPLIER);
}
/** {@code y} is the requested height, negative when the placement samples it. */
static long placement(long worldSeed, String objectKey, int x, int y, int z) {
return worldSeed ^ fnv1a(objectKey) ^ (x * X_MULTIPLIER) ^ (y * Y_MULTIPLIER) ^ (z * Z_MULTIPLIER);
}
private static long fnv1a(String text) {
long hash = FNV_OFFSET_BASIS;
for (byte value : text.getBytes(StandardCharsets.UTF_8)) {
hash = (hash ^ (value & 0xFF)) * FNV_PRIME;
}
return hash;
}
}
@@ -0,0 +1,94 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.math.IrisBlockVector;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import com.volmit.world.BlockPosition;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* An Iris object as IrisApi geometry. Iris keys an object's blocks by their offset from its center, so
* those offsets are the local positions and the anchor is the origin. Tile data travels as block entities.
*/
public final class ObjectGeometry {
private static final BlockPosition CENTER = new BlockPosition(0, 0, 0);
private static final BlockState UNREADABLE_BLOCK = BlockState.parse("minecraft:cave_air");
private static final BlockBox EMPTY = new BlockBox(0, 0, 0, 0, 0, 0);
private ObjectGeometry() {
}
/** Reads the object under its read lock. A block Iris cannot read becomes cave air, as Iris places it. */
public static GeneratedObject of(IrisObject object) {
object.readLock.lock();
try {
List<ObjectBlock> blocks = blocksOf(object);
return new GeneratedObject(boundsOf(blocks), CENTER, blocks, List.of());
} finally {
object.readLock.unlock();
}
}
private static List<ObjectBlock> blocksOf(IrisObject object) {
Map<BlockPosition, ObjectBlock> blocks = new LinkedHashMap<>();
for (Map.Entry<IrisBlockVector, PlatformBlockState> entry : object.blocks) {
BlockPosition position = positionOf(entry.getKey());
TileData tile = object.states.get(entry.getKey());
blocks.put(position, new ObjectBlock(position, stateOf(entry.getValue()), Optional.ofNullable(tile).map(BlockEntities::of)));
}
return List.copyOf(blocks.values());
}
private static BlockPosition positionOf(IrisBlockVector offset) {
return new BlockPosition((int) Math.round(offset.getX()), (int) Math.round(offset.getY()), (int) Math.round(offset.getZ()));
}
private static BlockState stateOf(PlatformBlockState state) {
return state == null ? UNREADABLE_BLOCK : BlockState.parse(PlatformBlockStates.namespaced(state.key()));
}
private static BlockBox boundsOf(List<ObjectBlock> blocks) {
if (blocks.isEmpty()) {
return EMPTY;
}
int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE, maxZ = Integer.MIN_VALUE;
for (ObjectBlock block : blocks) {
BlockPosition position = block.position();
minX = Math.min(minX, position.x());
minY = Math.min(minY, position.y());
minZ = Math.min(minZ, position.z());
maxX = Math.max(maxX, position.x());
maxY = Math.max(maxY, position.y());
maxZ = Math.max(maxZ, position.z());
}
return new BlockBox(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1);
}
}
@@ -0,0 +1,43 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import java.util.Optional;
/** One object placement: the height it was anchored at, or why it was rejected. */
public record ObjectPlacementResult(int height, Optional<String> rejection) {
private static final int REJECTED_HEIGHT = -1;
static ObjectPlacementResult placed(int height) {
return new ObjectPlacementResult(height, Optional.empty());
}
static ObjectPlacementResult rejected(String reason) {
return new ObjectPlacementResult(REJECTED_HEIGHT, Optional.of(reason));
}
public boolean isPlaced() {
return rejection.isEmpty();
}
/** The height, or -1 for a rejected placement, as Iris's placement callers expect. */
public int heightOrRejected() {
return height;
}
}
@@ -0,0 +1,76 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.volmit.FeatureAttachment.Target;
import java.io.IOException;
import java.util.function.Supplier;
/**
* Decodes the module settings of every object placement Gson reads, wherever pack JSON nests one, into
* {@link IrisObjectPlacement#getModuleSettings()}. Register it before the factory that resolves snippets:
* Gson asks later registrations first, so that factory reads a snippet reference and this one decodes the
* snippet's JSON.
*/
public final class ObjectPlacementSettingsReader implements TypeAdapterFactory {
private final Supplier<ModuleSettingsDecoder> decoder;
/** {@code decoder} is asked for on the first placement read, so reading no placement loads no modules. */
public ObjectPlacementSettingsReader(Supplier<ModuleSettingsDecoder> decoder) {
this.decoder = decoder;
}
@Override
@SuppressWarnings("unchecked") // The type is checked to be IrisObjectPlacement.
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (type.getRawType() != IrisObjectPlacement.class) {
return null;
}
TypeAdapter<IrisObjectPlacement> placements = gson.getDelegateAdapter(this, (TypeToken<IrisObjectPlacement>) type);
TypeAdapter<JsonElement> elements = gson.getAdapter(JsonElement.class);
return (TypeAdapter<T>) new TypeAdapter<IrisObjectPlacement>() {
@Override
public void write(JsonWriter out, IrisObjectPlacement placement) throws IOException {
placements.write(out, placement);
}
@Override
public IrisObjectPlacement read(JsonReader in) throws IOException {
String path = in.getPath();
JsonElement json = elements.read(in);
IrisObjectPlacement placement = placements.fromJsonTree(json);
if (placement != null && json.isJsonObject()) {
placement.setModuleSettings(decoder.get().decode(Target.OBJECT_PLACEMENT,
new JSONObject(json.toString()), "object placement at " + path));
}
return placement;
}
};
}
}
@@ -0,0 +1,162 @@
/*
* 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.core.modules;
import art.arcane.iris.builtin.blocks.ObjectMarkers;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.matter.MatterMarker;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
import com.volmit.mantle.Mantle;
import com.volmit.placement.PlacedBlock;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementEdit;
import com.volmit.world.BlockPosition;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* One placement's writes, buffered over an Iris object placer until IrisApi commits them. Reads see the
* buffered writes. Committing writes blocks in the order they were first set, then their tile data and
* markers, then reports the object's own blocks to the caller's listener. The placer offers no rollback,
* so a placer that fails part way through a commit keeps the writes before the failure.
*/
final class ObjectPlacerEdit implements PlacementEdit {
private enum State { OPEN, COMMITTED, FAILED, CLOSED }
private final IObjectPlacer placer;
private final BlockBox bounds;
private final PlatformBlockStates states;
private final BiConsumer<art.arcane.volmlib.util.math.BlockPosition, PlatformBlockState> listener;
private final Map<BlockPosition, PlacedBlock> blocks = new LinkedHashMap<>();
private final List<PlacedMarker> markers = new ArrayList<>();
private final List<BlockPosition> objectBlocks = new ArrayList<>();
private State state = State.OPEN;
/** {@code listener} hears each object block after the commit, as Iris placements report them; null for none. */
ObjectPlacerEdit(IObjectPlacer placer, BlockBox bounds, PlatformBlockStates states,
BiConsumer<art.arcane.volmlib.util.math.BlockPosition, PlatformBlockState> listener) {
this.placer = placer;
this.bounds = bounds;
this.states = states;
this.listener = listener;
}
@Override
public BlockBox bounds() {
requireOpen();
return bounds;
}
@Override
public BlockState get(int x, int y, int z) {
requireInside(x, y, z);
PlacedBlock buffered = blocks.get(new BlockPosition(x, y, z));
return buffered != null ? buffered.state() : states.toApi(placer.get(x, y, z));
}
@Override
public void set(PlacedBlock block) {
BlockPosition position = block.position();
requireInside(position.x(), position.y(), position.z());
blocks.put(position, block);
}
@Override
public void marker(PlacedMarker marker) {
BlockPosition position = marker.position();
requireInside(position.x(), position.y(), position.z());
ObjectMarkers.requireIrisMarker(marker);
markers.add(marker);
}
@Override
public Mantle mantle() {
requireOpen();
throw new UnsupportedOperationException("Mantle access from placement stages is not bridged to Iris yet");
}
/** Marks a buffered write as one of the object's own blocks, which the listener hears after the commit. */
void recordObjectBlock(BlockPosition position) {
requireOpen();
objectBlocks.add(position);
}
@Override
public void commit() {
requireOpen();
state = State.FAILED;
writeBlocks();
writeMarkers();
reportObjectBlocks();
state = State.COMMITTED;
}
@Override
public void close() {
blocks.clear();
markers.clear();
objectBlocks.clear();
state = State.CLOSED;
}
private void writeBlocks() {
for (PlacedBlock block : blocks.values()) {
BlockPosition position = block.position();
placer.set(position.x(), position.y(), position.z(), states.toPlatform(block.state()));
block.blockEntity().ifPresent(entity -> placer.setTile(position.x(), position.y(), position.z(), BlockEntities.tileOf(entity)));
}
}
private void writeMarkers() {
for (PlacedMarker marker : markers) {
BlockPosition position = marker.position();
placer.setData(position.x(), position.y(), position.z(), new MatterMarker(ObjectMarkers.markerKey(marker)));
}
}
private void reportObjectBlocks() {
if (listener == null) {
return;
}
for (BlockPosition position : objectBlocks) {
PlacedBlock written = blocks.get(position);
listener.accept(new art.arcane.volmlib.util.math.BlockPosition(position.x(), position.y(), position.z()),
states.toPlatform(written.state()));
}
}
private void requireInside(int x, int y, int z) {
if (!bounds().contains(x, y, z)) {
throw new IndexOutOfBoundsException("Block " + x + ", " + y + ", " + z + " is outside the placement area " + bounds);
}
}
private void requireOpen() {
if (state != State.OPEN) {
throw new IllegalStateException("The placement edit is " + state.name().toLowerCase(Locale.ROOT));
}
}
}
@@ -0,0 +1,66 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.prefab.IrisObjectTranslate;
import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject;
/**
* The columns one object placement may read and write: every column the object reaches in any rotation
* around its anchor, moved by its translation and surface warp, widened by one block for neighbor reads and
* by the placement pipeline's reach. Heights are not bounded; the placer keeps writes inside its world.
*/
final class PlacementArea {
private static final int NEIGHBOR_READ_BLOCKS = 1;
private PlacementArea() {
}
static BlockBox around(GeneratedObject object, IrisObjectPlacement config, int x, int z, int pipelineReachBlocks) {
int reach = rotationRadius(object.bounds()) + translationLength(config.getTranslate())
+ warpMargin(config.getWarp()) + NEIGHBOR_READ_BLOCKS + pipelineReachBlocks;
return new BlockBox(x - reach, Integer.MIN_VALUE, z - reach, x + reach + 1, Integer.MAX_VALUE, z + reach + 1);
}
/** The farthest any block of {@code bounds} lies from the origin, which rotations turn around. */
private static int rotationRadius(BlockBox bounds) {
long x = farthest(bounds.minX(), bounds.maxX());
long y = farthest(bounds.minY(), bounds.maxY());
long z = farthest(bounds.minZ(), bounds.maxZ());
return (int) Math.ceil(Math.sqrt(x * x + y * y + z * z));
}
private static long farthest(int min, int maxExclusive) {
return Math.max(Math.abs((long) min), Math.abs((long) maxExclusive - 1));
}
private static int translationLength(IrisObjectTranslate translate) {
long x = translate.getX();
long y = translate.getY();
long z = translate.getZ();
return (int) Math.ceil(Math.sqrt(x * x + y * y + z * z));
}
private static int warpMargin(IrisGeneratorStyle warp) {
return warp.isFlat() ? 0 : (int) Math.ceil(Math.abs(warp.getMultiplier()) / 2D);
}
}
@@ -0,0 +1,64 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings;
import com.volmit.resource.ResourceId;
import java.util.List;
/**
* Module settings during one object placement: the placement's own at {@link Target#OBJECT_PLACEMENT},
* the world's at every other target. A placement without an engine sees no world settings.
*/
final class PlacementModuleSettings implements FeatureSettings {
private static final FeatureSettings NO_WORLD = new FeatureSettings() {
@Override
public <F extends IrisFeature> List<Entry<F>> at(Class<F> featureType, Target target, int worldX, int worldY, int worldZ) {
return List.of();
}
};
private final FeatureSettings world;
private final ModuleSettings placement;
private final ResourceId source;
/** {@code source} names the placement, such as the object it places. */
PlacementModuleSettings(FeatureSettings world, ModuleSettings placement, ResourceId source) {
this.world = world;
this.placement = placement;
this.source = source;
}
static FeatureSettings noWorld() {
return NO_WORLD;
}
@Override
public <F extends IrisFeature> List<Entry<F>> at(Class<F> featureType, Target target, int worldX, int worldY, int worldZ) {
if (target != Target.OBJECT_PLACEMENT) {
return world.at(featureType, target, worldX, worldY, worldZ);
}
return placement.find(featureType)
.map(value -> List.of(new Entry<>(source, source, value)))
.orElse(List.of());
}
}
@@ -0,0 +1,50 @@
/*
* 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.core.modules;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
import com.volmit.world.BlockView;
/** The blocks an Iris object placer holds before a placement's writes, within the placement area. */
final class PlacerBlockView implements BlockView {
private final IObjectPlacer placer;
private final BlockBox bounds;
private final PlatformBlockStates states;
PlacerBlockView(IObjectPlacer placer, BlockBox bounds, PlatformBlockStates states) {
this.placer = placer;
this.bounds = bounds;
this.states = states;
}
@Override
public BlockBox bounds() {
return bounds;
}
@Override
public BlockState get(int worldX, int worldY, int worldZ) {
if (!bounds.contains(worldX, worldY, worldZ)) {
throw new IndexOutOfBoundsException("Block " + worldX + ", " + worldY + ", " + worldZ + " is outside the placement area " + bounds);
}
return states.toApi(placer.get(worldX, worldY, worldZ));
}
}
@@ -0,0 +1,69 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.spi.PlatformBlockState;
import com.volmit.block.BlockState;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* Converts between IrisApi block states and the platform's through their keys, remembering each
* conversion. Meant for one invocation, which repeats few states many times; not thread-safe.
*/
public final class PlatformBlockStates {
public static final BlockState AIR = BlockState.parse("minecraft:air");
private static final String MINECRAFT_NAMESPACE = "minecraft";
private static final char NAMESPACE_SEPARATOR = ':';
private static final char PROPERTIES_START = '[';
private final Function<String, PlatformBlockState> platformStates;
private final Map<PlatformBlockState, BlockState> read = new HashMap<>();
private final Map<BlockState, PlatformBlockState> written = new HashMap<>();
/** {@code platformStates} turns a block state key into the platform's state, such as {@code B::getState}. */
public PlatformBlockStates(Function<String, PlatformBlockState> platformStates) {
this.platformStates = platformStates;
}
/**
* Iris leaves unset blocks null, which IrisApi forbids, so they read as air. A key without a namespace
* is Minecraft's, as Minecraft reads it.
*/
public BlockState toApi(PlatformBlockState state) {
if (state == null) {
return AIR;
}
return read.computeIfAbsent(state, platform -> BlockState.parse(namespaced(platform.key())));
}
public PlatformBlockState toPlatform(BlockState state) {
return written.computeIfAbsent(state, api -> platformStates.apply(api.key()));
}
/** {@code key} with Minecraft's namespace when it names none, as Minecraft reads such keys. */
public static String namespaced(String key) {
int namespaceEnd = key.indexOf(NAMESPACE_SEPARATOR);
int propertiesStart = key.indexOf(PROPERTIES_START);
boolean hasNamespace = namespaceEnd >= 0 && (propertiesStart < 0 || namespaceEnd < propertiesStart);
return hasNamespace ? key : MINECRAFT_NAMESPACE + NAMESPACE_SEPARATOR + key;
}
}
@@ -67,8 +67,7 @@ final class EngineHotloader {
nextComplex = assembly.complex;
assembly.upperContext = engine.runtimeBuilder.buildUpperContext();
BiomeMaxes biomeMaxes = engine.runtimeBuilder.computeBiomeMaxes();
next = previous.withComplex(assembly.cacheId, assembly.complex, assembly.upperContext, biomeMaxes,
assembly.placementLifecycles);
next = previous.withComplex(assembly.cacheId, assembly.complex, assembly.upperContext, biomeMaxes);
} finally {
engine.runtimeAssembly.remove();
}
@@ -22,7 +22,6 @@ import art.arcane.iris.engine.framework.EngineEffects;
import art.arcane.iris.engine.framework.EngineMode;
import art.arcane.iris.engine.framework.EngineTarget;
import art.arcane.iris.engine.framework.EngineWorldManager;
import art.arcane.iris.engine.object.placement.PlacementLifecycles;
import java.util.concurrent.CompletableFuture;
@@ -39,15 +38,13 @@ record EngineRuntime(
EngineMode mode,
EngineWorldManager worldManager,
CompletableFuture<Long> hash32,
BiomeMaxes biomeMaxes,
PlacementLifecycles placementLifecycles
BiomeMaxes biomeMaxes
) {
EngineRuntime withComplex(
int nextCacheId,
IrisComplex nextComplex,
UpperDimensionContext nextUpperContext,
BiomeMaxes nextBiomeMaxes,
PlacementLifecycles nextPlacementLifecycles
BiomeMaxes nextBiomeMaxes
) {
return new EngineRuntime(
nextCacheId,
@@ -58,8 +55,7 @@ record EngineRuntime(
mode,
worldManager,
hash32,
nextBiomeMaxes,
nextPlacementLifecycles);
nextBiomeMaxes);
}
record BiomeMaxes(double objectDensity, double layerDensity, double decoratorDensity) {
@@ -35,7 +35,6 @@ import art.arcane.iris.engine.object.decoration.IrisDecorator;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.world.dimension.IrisDimensionMode;
import art.arcane.iris.engine.object.world.dimension.IrisDimensionModeType;
import art.arcane.iris.engine.object.placement.PlacementLifecycles;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.util.project.context.IrisContext;
@@ -301,12 +300,10 @@ final class EngineRuntimeBuilder {
EngineMode mode;
EngineWorldManager worldManager;
CompletableFuture<Long> hash32;
final PlacementLifecycles placementLifecycles;
RuntimeAssembly(int cacheId, EngineTarget target) {
this.cacheId = cacheId;
this.target = target;
this.placementLifecycles = PlacementLifecycles.resolve();
}
EngineRuntime freeze(BiomeMaxes biomeMaxes) {
@@ -322,8 +319,7 @@ final class EngineRuntimeBuilder {
mode,
worldManager,
hash32,
biomeMaxes,
placementLifecycles);
biomeMaxes);
}
}
}
@@ -18,7 +18,6 @@
package art.arcane.iris.engine;
import art.arcane.iris.engine.object.placement.PlacementLifecycles;
import art.arcane.iris.engine.EngineBackgroundTasks.BackgroundTaskDrain;
import art.arcane.iris.engine.EngineRuntimeBuilder.RuntimeAssembly;
import art.arcane.iris.engine.framework.Engine;
@@ -501,19 +500,6 @@ public class IrisEngine implements Engine {
return current == null ? null : current.complex();
}
@Override
public art.arcane.iris.engine.object.placement.PlacementLifecycles getPlacementLifecycles() {
RuntimeAssembly assembly = runtimeAssembly.get();
if (assembly != null) {
return assembly.placementLifecycles;
}
EngineRuntime current = runtime;
if (current == null) {
throw new IllegalStateException("Placement requires an active Iris runtime.");
}
return current.placementLifecycles();
}
@Override
public EngineTarget getTarget() {
RuntimeAssembly assembly = runtimeAssembly.get();
@@ -20,7 +20,6 @@ package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.placement.PlacementLifecycles;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.engine.framework.render.RenderType;
import art.arcane.iris.engine.framework.render.Renderer;
@@ -85,10 +84,6 @@ import java.util.stream.Collectors;
public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, Hotloadable {
IrisComplex getComplex();
default art.arcane.iris.engine.object.placement.PlacementLifecycles getPlacementLifecycles() {
return art.arcane.iris.engine.object.placement.PlacementLifecycles.defaults();
}
default @Nullable UpperDimensionContext getUpperContext() {
return null;
}
@@ -0,0 +1,53 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.core.loader.IrisData;
import com.volmit.host.LoadedPack;
import com.volmit.host.ResolvedGraph;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
public class BuiltInPlacementGraphTest {
private static final List<String> EXPECTED_ORDER = List.of(
"iris:prepare/slope", "iris:prepare/transforms", "iris:anchor/height", "iris:validate/surface",
"iris:validate/limits", "iris:validate/structures", "iris:validate/collisions", "iris:anchor/final",
"iris:bore/clear", "iris:blocks/write", "iris:stilt/layers", "iris:blocks/markers",
"iris:blocks/complete", "iris:stilt/fill", "iris:vacuum/terrain", "iris:snow/cover");
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void writesTheObjectAndFindsItsStiltLayersInOneBlockPass() throws IOException {
try (LoadedPack pack = BuiltInPlacementPack.serve(mock(IrisData.class), folder, List.of())) {
ResolvedGraph graph = pack.placement();
assertEquals(graph.describe(), EXPECTED_ORDER, graph.stages().stream().map(stage -> stage.stage().id().toString()).toList());
assertEquals(graph.describe(), 1, graph.blockPasses().size());
}
}
}
@@ -0,0 +1,58 @@
/*
* 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.core.modules;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.SeedManager;
import com.volmit.IrisModule;
import com.volmit.host.LoadedPack;
import com.volmit.host.ModuleHost;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Test packs whose placement graph is Iris's built-in modules followed by the given pack modules. */
public final class BuiltInPlacementPack {
private BuiltInPlacementPack() {
}
/** Loads the pack and lets the mocked {@code data} serve it, as a pack's data serves its modules. Close it after the test. */
public static LoadedPack serve(IrisData data, TemporaryFolder folder, List<IrisModule> packModules) throws IOException {
List<IrisModule> modules = Stream.concat(IrisModuleHost.builtInModules().stream(), packModules.stream()).toList();
LoadedPack pack = LoadedPack.load(folder.newFolder().toPath(), ModuleHost.of(modules).copyingJarsTo(folder.newFolder().toPath()));
PackModuleSet moduleSet = mock(PackModuleSet.class);
when(moduleSet.pack()).thenReturn(pack);
when(data.getModules()).thenReturn(moduleSet);
when(data.getDataFolder()).thenReturn(folder.getRoot());
return pack;
}
/** Placements into a world of {@code engine} derive their seeds from its world seed. */
public static void seedWorld(Engine engine, long seed) {
SeedManager seeds = mock(SeedManager.class);
when(seeds.getSeed()).thenReturn(seed);
when(engine.getSeedManager()).thenReturn(seeds);
}
}
@@ -0,0 +1,182 @@
/*
* 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.core.modules;
import art.arcane.iris.builtin.anchor.AnchorStages;
import art.arcane.iris.builtin.blocks.BlocksStages;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.placement.ObjectPlaceMode;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.volmlib.util.math.RNG;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.config.Feature;
import com.volmit.host.LoadedPack;
import com.volmit.placement.PlacedBlock;
import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.world.BlockPosition;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Module settings that object placements declare in pack JSON, decoded and activating placement stages. */
public class ObjectPlacementModuleSettingsTest {
private static final int SURFACE_Y = 80;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private IrisData data;
private LoadedPack pack;
private Gson gson;
@Feature(id = "example:glow", name = "Glow", targets = Target.OBJECT_PLACEMENT)
public static final class GlowSettings implements IrisFeature {
private String block = "minecraft:glowstone";
}
/** Puts the configured block on the object once it is written, where placements declare glow. */
public static final class GlowModule implements IrisModule {
private static final PlacementStage<Void> TOP = Stage.placement("example:glow/top");
@Override
public ModuleInfo info() {
return ModuleInfo.of("example:glow", "Glow", "1");
}
@Override
public void install(StageGraph graph) {
graph.define(TOP).when(GlowSettings.class).requires(BlocksStages.COMPLETE, AnchorStages.FINAL).run((context, glow) -> {
int y = context.output(AnchorStages.FINAL).y() + 1;
context.access().set(new PlacedBlock(new BlockPosition(0, y, 0), com.volmit.block.BlockState.parse(glow.block), Optional.empty()));
});
}
}
/** Holds placements the way a biome does. */
private static final class Holder {
private List<IrisObjectPlacement> objects;
}
@Before
public void loadPack() throws IOException {
IrisPlatforms.unbind();
PlatformRegistries registries = mock(PlatformRegistries.class);
Map<String, PlatformBlockState> states = new HashMap<>();
when(registries.block(anyString())).thenAnswer(call -> states.computeIfAbsent(
PlatformBlockStates.namespaced(call.<String>getArgument(0).toLowerCase()), ObjectPlacementModuleSettingsTest::state));
IrisPlatform platform = mock(IrisPlatform.class);
when(platform.registries()).thenReturn(registries);
IrisPlatforms.bind(platform);
data = mock(IrisData.class);
pack = BuiltInPlacementPack.serve(data, folder, List.of(new GlowModule()));
ModuleSettingsDecoder decoder = new ModuleSettingsDecoder(pack.catalog(), folder.getRoot().toPath());
gson = new GsonBuilder().registerTypeAdapterFactory(new ObjectPlacementSettingsReader(() -> decoder)).create();
}
@After
public void closePack() {
pack.close();
IrisPlatforms.unbind();
}
@Test
public void decodesTheSettingsOfEveryNestedPlacement() {
Holder holder = gson.fromJson("{\"objects\": [{\"place\": [\"tree\"], \"example:glow\": {\"block\": \"minecraft:sea_lantern\"}},"
+ " {\"place\": [\"rock\"]}]}", Holder.class);
assertEquals("minecraft:sea_lantern", holder.objects.get(0).getModuleSettings().find(GlowSettings.class).orElseThrow().block);
assertSame(ModuleSettings.NONE, holder.objects.get(1).getModuleSettings());
}
@Test
public void copiesOfAPlacementKeepItsSettings() {
IrisObjectPlacement placement = gson.fromJson("{\"place\": [\"tree\"], \"example:glow\": {}}", IrisObjectPlacement.class);
assertSame(placement.getModuleSettings(), placement.toPlacement("rock").getModuleSettings());
}
@Test
public void aPlacementsSettingsActivateItsStages() {
IObjectPlacer declaring = placer();
IObjectPlacer silent = placer();
place(gson.fromJson("{\"example:glow\": {}}", IrisObjectPlacement.class), declaring);
place(gson.fromJson("{}", IrisObjectPlacement.class), silent);
verify(declaring).set(eq(0), eq(SURFACE_Y + 1), eq(0), any());
verify(silent, never()).set(eq(0), eq(SURFACE_Y + 1), eq(0), any());
}
private void place(IrisObjectPlacement placement, IObjectPlacer placer) {
placement.setMode(ObjectPlaceMode.CENTER_HEIGHT);
placement.setRequireSurfaceSupport(false);
IrisObject object = new IrisObject(1, 1, 1);
object.setUnsigned(0, 0, 0, IrisPlatforms.get().registries().block("minecraft:stone"));
ModuleObjectPlacement.place(object, 0, SURFACE_Y, 0, placer, placement, new RNG(1), null, null, data);
}
private static IObjectPlacer placer() {
IObjectPlacer placer = mock(IObjectPlacer.class);
when(placer.getHighest(anyInt(), anyInt(), any(), anyBoolean())).thenReturn(SURFACE_Y);
return placer;
}
private static PlatformBlockState state(String key) {
PlatformBlockState state = mock(PlatformBlockState.class);
when(state.key()).thenReturn(key);
when(state.materialKey()).thenReturn(key);
when(state.isSolid()).thenReturn(!key.contains("air"));
when(state.isOccluding()).thenReturn(!key.contains("air"));
return state;
}
}
@@ -1,55 +0,0 @@
package art.arcane.iris.engine;
import art.arcane.iris.engine.framework.EngineEffects;
import art.arcane.iris.engine.framework.EngineMode;
import art.arcane.iris.engine.framework.EngineTarget;
import art.arcane.iris.engine.framework.EngineWorldManager;
import art.arcane.iris.engine.object.placement.ObjectPlaceMode;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
public class EnginePlacementLifecycleTest {
@Test
public void runtimeAssemblyResolvesBeforePublicationAndKeepsOldPlansIntact() {
var initial = assembly(1);
EngineRuntime previous = initial.freeze(new EngineRuntime.BiomeMaxes(0, 0, 0));
var replacement = assembly(2);
EngineRuntime next = replacement.freeze(new EngineRuntime.BiomeMaxes(0, 0, 0));
assertSame(initial.placementLifecycles, previous.placementLifecycles());
assertSame(replacement.placementLifecycles, next.placementLifecycles());
for (ObjectPlaceMode mode : ObjectPlaceMode.values()) {
assertNotNull(next.placementLifecycles().get(mode));
assertNotSame(previous.placementLifecycles().get(mode), next.placementLifecycles().get(mode));
}
assertSame(initial.placementLifecycles, previous.placementLifecycles());
}
@Test
public void complexReplacementCarriesNewPlansAlongsideTheNewComplex() {
var initial = assembly(1);
EngineRuntime previous = initial.freeze(new EngineRuntime.BiomeMaxes(0, 0, 0));
var replacement = assembly(2);
EngineRuntime next = previous.withComplex(2, replacement.complex, null,
new EngineRuntime.BiomeMaxes(1, 1, 1), replacement.placementLifecycles);
assertSame(replacement.placementLifecycles, next.placementLifecycles());
assertSame(replacement.complex, next.complex());
assertSame(previous.worldManager(), next.worldManager());
assertSame(initial.placementLifecycles, previous.placementLifecycles());
}
private EngineRuntimeBuilder.RuntimeAssembly assembly(int id) {
var assembly = new EngineRuntimeBuilder.RuntimeAssembly(id, mock(EngineTarget.class));
assembly.complex = mock(IrisComplex.class);
assembly.effects = mock(EngineEffects.class);
assembly.mode = mock(EngineMode.class);
assembly.worldManager = mock(EngineWorldManager.class);
assembly.hash32 = CompletableFuture.completedFuture(0L);
return assembly;
}
}
@@ -7,20 +7,18 @@ import art.arcane.iris.engine.object.placement.IrisSlopeClip;
import art.arcane.iris.engine.object.placement.IrisStiltSettings;
import art.arcane.iris.engine.object.placement.IrisVacuumSettings;
import art.arcane.iris.engine.object.placement.ObjectPlaceMode;
import art.arcane.iris.engine.object.placement.PlacementContext;
import art.arcane.iris.engine.object.placement.PlacementLifecycleBuilder;
import art.arcane.iris.engine.object.placement.PlacementLifecycleDependency;
import art.arcane.iris.engine.object.placement.PlacementLifecycles;
import art.arcane.iris.engine.object.placement.PlacementModuleAnchor;
import art.arcane.iris.engine.object.placement.PlacementStage;
import art.arcane.iris.engine.object.placement.PlacementState;
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.prefab.TileData;
import art.arcane.iris.engine.object.terrain.carving.CarveResult;
import art.arcane.iris.engine.object.terrain.carving.CarvingMode;
import art.arcane.iris.builtin.blocks.BlocksStages;
import art.arcane.iris.builtin.bore.BoreStages;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.BuiltInPlacementPack;
import art.arcane.iris.core.modules.ModuleObjectPlacement;
import art.arcane.iris.core.modules.ObjectPlacementResult;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeStructureVolume;
@@ -32,14 +30,27 @@ import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.util.project.stream.ProceduralStream;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.block.BlockState;
import com.volmit.host.LoadedPack;
import com.volmit.placement.PlacedBlock;
import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.world.BlockPosition;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -52,40 +63,61 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class IrisObjectPlacementRunnerRegressionTest {
public class IrisObjectPlacementRegressionTest {
private static final int ANCHOR_Y = 80;
private static final String SNOW_LAYER = "minecraft:snow[layers=1]";
private static final String CAVE_AIR = "minecraft:cave_air";
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private final Map<String, PlatformBlockState> registryStates = new HashMap<>();
private IrisData data;
private Engine engine;
private PlatformBlockState solid;
private PlatformBlockState schematicAir;
private LoadedPack pack;
@Before
public void bindPlatform() {
public void bindPlatform() throws IOException {
IrisPlatforms.unbind();
PlatformRegistries registries = mock(PlatformRegistries.class);
Map<String, PlatformBlockState> registryStates = new HashMap<>();
when(registries.block(anyString())).thenAnswer(invocation -> {
String key = invocation.getArgument(0);
return registryStates.computeIfAbsent(key, value -> state(value.toLowerCase(), !value.toLowerCase().contains("air")));
});
when(registries.block(anyString())).thenAnswer(invocation -> registryState(invocation.getArgument(0)));
IrisPlatform platform = mock(IrisPlatform.class);
when(platform.registries()).thenReturn(registries);
IrisPlatforms.bind(platform);
engine = mock(Engine.class);
when(engine.getHeight()).thenReturn(256);
BuiltInPlacementPack.seedWorld(engine, 7L);
data = mock(IrisData.class);
when(data.getEngine()).thenReturn(engine);
solid = state("minecraft:stone", true);
schematicAir = state("minecraft:air", false);
usePack(List.of());
solid = registryState("minecraft:stone");
schematicAir = registryState("minecraft:air");
}
@After
public void unbindPlatform() {
pack.close();
IrisPlatforms.unbind();
}
/** Placements run Iris's built-in modules followed by {@code packModules}, as a pack's placement graph does. */
private void usePack(List<IrisModule> packModules) throws IOException {
if (pack != null) {
pack.close();
}
pack = BuiltInPlacementPack.serve(data, folder, packModules);
}
/** Platform states by key, the way a registry answers them; keys without a namespace are Minecraft's. */
private PlatformBlockState registryState(String key) {
String normalized = key.toLowerCase();
String namespaced = normalized.contains(":") ? normalized : "minecraft:" + normalized;
return registryStates.computeIfAbsent(namespaced, value -> state(value, !value.contains("air")));
}
@Test
public void placementFailurePropagatesToTheCaller() {
RecordingPlacer placer = new RecordingPlacer(null);
@@ -104,14 +136,16 @@ public class IrisObjectPlacementRunnerRegressionTest {
RecordingPlacer placer = new RecordingPlacer(null);
IrisObjectPlacement placement = placement();
placement.setBore(true);
placement.setBoreExtendMaxY(1);
placement.setRotation(IrisObjectRotation.of(0, 90, 0));
placement.setTranslate(new IrisObjectTranslate().setX(4).setYRandom(3));
int resultY = lineObject(3).place(0, ANCHOR_Y, 0, placer, placement, new RNG(2L), data);
List<BlockWrite> airWrites = placer.writesOf(IrisObject.States.AIR);
assertFalse(airWrites.isEmpty());
assertTrue(airWrites.stream().allMatch(write -> write.y() >= resultY && write.y() <= resultY));
// The object's own blocks replace the bored air below, so only the extension stays air.
List<BlockWrite> airWrites = placer.writesOf(CAVE_AIR);
assertEquals(3, airWrites.size());
assertTrue(airWrites.stream().allMatch(write -> write.y() == resultY + 1));
assertTrue(airWrites.stream().allMatch(write -> write.x() == 0));
assertTrue(airWrites.stream().allMatch(write -> write.z() <= -3 && write.z() >= -5));
}
@@ -162,7 +196,7 @@ public class IrisObjectPlacementRunnerRegressionTest {
object.place(0, ANCHOR_Y, 0, placer, placement, new RNG(2L), data);
List<BlockWrite> snowWrites = placer.writesOf(IrisObject.States.SNOW_LAYERS[0]);
List<BlockWrite> snowWrites = placer.writesOf(SNOW_LAYER);
assertEquals(1, snowWrites.size());
assertEquals(ANCHOR_Y, snowWrites.get(0).y());
}
@@ -183,9 +217,7 @@ public class IrisObjectPlacementRunnerRegressionTest {
PlatformBlockState cachedState = object.getBlocks().get(object.getSigned(0, 0, 0));
assertSame(IrisObject.States.VAIR, cachedState);
if (IrisObject.States.VAIR != IrisObject.States.VAIR_DEBUG) {
assertTrue(cachedState != IrisObject.States.VAIR_DEBUG);
}
assertEquals(BlockState.parse(IrisObject.States.VAIR.key()), object.getGeometry().blocks().getFirst().state());
}
@Test
@@ -215,8 +247,8 @@ public class IrisObjectPlacementRunnerRegressionTest {
// Every bottom column reaches the ground after rotation and translation.
for (int z = -5; z <= -3; z++) {
assertSame(solid, placer.get(0, ANCHOR_Y, z));
assertSame(solid, placer.get(0, ANCHOR_Y + 3, z));
assertEquals(solid.key(), placer.get(0, ANCHOR_Y, z).key());
assertEquals(solid.key(), placer.get(0, ANCHOR_Y + 3, z).key());
}
assertTrue(placer.writes().stream().allMatch(write -> write.x() == 0));
}
@@ -232,8 +264,8 @@ public class IrisObjectPlacementRunnerRegressionTest {
boxObject(1, 3, 1).place(0, ANCHOR_Y, 0, placer, config, new RNG(2L), data);
assertSame(solid, placer.get(0, 82, 0));
assertSame(solid, placer.get(0, 89, 0));
assertEquals(solid.key(), placer.get(0, 82, 0).key());
assertEquals(solid.key(), placer.get(0, 89, 0).key());
assertTrue(placer.writes().stream().noneMatch(write -> write.y() < 82 || write.y() >= 90));
}
@@ -248,7 +280,7 @@ public class IrisObjectPlacementRunnerRegressionTest {
lineObject(1).place(0, ANCHOR_Y, 0, placer, config, new RNG(2L), data);
for (int y = 76; y <= ANCHOR_Y; y++) {
assertSame(solid, placer.get(0, y, 0));
assertEquals(solid.key(), placer.get(0, y, 0).key());
}
assertTrue(placer.writes().stream().noneMatch(write -> write.y() <= 75));
}
@@ -275,22 +307,94 @@ public class IrisObjectPlacementRunnerRegressionTest {
}
@Test
public void runnerUsesTheEnginePlanAndCompletesTheBlockPassBeforeAfterBlocks() {
public void packStagesSeeTheWrittenObjectAndCommitWithIt() throws IOException {
List<Integer> writtenSizes = new ArrayList<>();
usePack(List.of(new CapModule(writtenSizes)));
RecordingPlacer placer = new RecordingPlacer(engine);
PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder();
ObjectPlaceMode.CENTER_HEIGHT.install(builder);
builder.add(new PlacementLifecycleDependency("test.offset"), PlacementStage.HEIGHT,
(context, state, ignored) -> state.y += 5, PlacementModuleAnchor.HEIGHT);
List<Integer> finishedSizes = new ArrayList<>();
builder.add(new PlacementLifecycleDependency("test.finished"), PlacementStage.AFTER_BLOCKS,
(context, state, ignored) -> finishedSizes.add(placer.writes().size()));
PlacementLifecycles plans = mock(PlacementLifecycles.class);
when(plans.get(ObjectPlaceMode.CENTER_HEIGHT)).thenReturn(builder.build());
when(engine.getPlacementLifecycles()).thenReturn(plans);
assertEquals(ANCHOR_Y + 5, lineObject(3).place(0, ANCHOR_Y, 0, placer, placement(), new RNG(2L), data));
assertEquals(List.of(3), finishedSizes);
assertTrue(placer.writes().stream().allMatch(write -> write.y() == ANCHOR_Y + 5));
assertEquals(ANCHOR_Y, lineObject(3).place(0, ANCHOR_Y, 0, placer, placement(), new RNG(2L), data));
assertEquals(List.of(3), writtenSizes);
assertEquals(4, placer.writes().size());
assertEquals(solid.key(), placer.get(0, ANCHOR_Y + 1, 0).key());
}
@Test
public void aRejectingPackStageDiscardsEveryEarlierWrite() throws IOException {
usePack(List.of(new VetoModule()));
RecordingPlacer placer = new RecordingPlacer(engine);
ObjectPlacementResult result = place(placement().setBore(true), ANCHOR_Y, placer, null);
assertEquals(Optional.of("veto"), result.rejection());
assertEquals(-1, result.heightOrRejected());
assertTrue(placer.writes().isEmpty());
}
@Test
public void withoutAnEngineThePlacementDrawsItsSeedOnceFromTheCallersRandom() {
RNG rng = new RNG(91);
RNG expected = new RNG(91);
expected.nextLong();
IrisObjectPlacement config = placement();
config.setTranslate(new IrisObjectTranslate().setYRandom(3));
lineObject(1).place(0, ANCHOR_Y, 0, new RecordingPlacer(null), config, rng, data);
assertEquals(expected.nextLong(), rng.nextLong());
}
@Test
public void withAnEngineTheSamePlacementPlacesTheSameWayWithoutTheCallersRandom() {
IrisObjectPlacement config = placement();
config.setTranslate(new IrisObjectTranslate().setYRandom(20));
RNG rng = new RNG(91);
int first = lineObject(1).place(5, ANCHOR_Y, 5, new RecordingPlacer(engine), config, rng, data);
int second = lineObject(1).place(5, ANCHOR_Y, 5, new RecordingPlacer(engine), config, new RNG(3), data);
assertEquals(first, second);
assertEquals(new RNG(91).nextLong(), rng.nextLong());
}
/** Puts a block on top of the object once it is written, reporting how many blocks the object wrote. */
private static final class CapModule implements IrisModule {
private static final PlacementStage<Void> CAP = Stage.placement("test:cap/top");
private final List<Integer> writtenSizes;
private CapModule(List<Integer> writtenSizes) {
this.writtenSizes = writtenSizes;
}
@Override
public ModuleInfo info() {
return ModuleInfo.of("test:cap", "Cap", "1");
}
@Override
public void install(StageGraph graph) {
graph.define(CAP).requires(BlocksStages.COMPLETE, BlocksStages.WRITE).run(context -> {
List<PlacedBlock> written = context.output(BlocksStages.WRITE).blocks();
writtenSizes.add(written.size());
BlockPosition first = written.getFirst().position();
context.access().set(new PlacedBlock(new BlockPosition(0, first.y() + 1, 0), written.getFirst().state(), Optional.empty()));
});
}
}
/** Rejects every placement after it is bored and written. */
private static final class VetoModule implements IrisModule {
private static final PlacementStage<Void> VETO = Stage.placement("test:veto/all");
@Override
public ModuleInfo info() {
return ModuleInfo.of("test:veto", "Veto", "1");
}
@Override
public void install(StageGraph graph) {
graph.define(VETO).requires(BoreStages.CLEAR, BlocksStages.COMPLETE).run(context -> context.reject("veto"));
}
}
@Test
@@ -325,13 +429,13 @@ public class IrisObjectPlacementRunnerRegressionTest {
}
case "height-clamp" -> config.getClamp().setMaximumHeight(ANCHOR_Y - 1);
}
PlacementState result = execute(config, anchor, placer, cave);
assertEquals(reason, result.getRejection());
ObjectPlacementResult result = place(config, anchor, placer, cave);
assertEquals(Optional.of(reason), result.rejection());
assertEquals(-1, result.heightOrRejected());
assertTrue(reason, placer.writes().isEmpty());
config.setForcePlace(true);
assertFalse(reason, execute(config, anchor, placer, cave).isRejected());
assertTrue(reason, place(config, anchor, placer, cave).isPlaced());
assertFalse(reason, placer.writes().isEmpty());
}
}
@@ -343,11 +447,11 @@ public class IrisObjectPlacementRunnerRegressionTest {
RecordingPlacer placer = new RecordingPlacer(engine);
IrisObjectPlacement config = placement().setForcePlace(true).setBore(true).setSnow(0.1);
assertEquals("native-structure", execute(config, ANCHOR_Y, placer, null).getRejection());
assertEquals(Optional.of("native-structure"), place(config, ANCHOR_Y, placer, null).rejection());
assertTrue(placer.writes().isEmpty());
config.setMode(ObjectPlaceMode.STRUCTURE_PIECE);
assertEquals(ANCHOR_Y, execute(config, ANCHOR_Y, placer, null).heightOrRejected());
assertEquals(ANCHOR_Y, place(config, ANCHOR_Y, placer, null).heightOrRejected());
assertFalse(placer.writes().isEmpty());
}
@@ -359,16 +463,16 @@ public class IrisObjectPlacementRunnerRegressionTest {
IrisObjectPlacement config = placement().setBore(true);
config.getForbiddenCollisions().add("forbidden");
assertEquals("object-collision", execute(config, ANCHOR_Y, placer, null).getRejection());
assertEquals(Optional.of("object-collision"), place(config, ANCHOR_Y, placer, null).rejection());
assertTrue(placer.writes().isEmpty());
config.getAllowedCollisions().add("forbidden");
assertFalse(execute(config, ANCHOR_Y, placer, null).isRejected());
assertTrue(place(config, ANCHOR_Y, placer, null).isPlaced());
assertFalse(placer.writes().isEmpty());
config.getAllowedCollisions().clear();
config.setForcePlace(true);
assertFalse(execute(config, ANCHOR_Y, new RecordingPlacer(engine), null).isRejected());
assertTrue(place(config, ANCHOR_Y, new RecordingPlacer(engine), null).isPlaced());
}
@Test
@@ -379,7 +483,7 @@ public class IrisObjectPlacementRunnerRegressionTest {
config.getForbiddenCollisions().add("forbidden");
assertEquals("Object placement requires active Iris data for collision settings.",
assertThrows(IllegalStateException.class,
() -> execute(config, ANCHOR_Y, placer, null)).getMessage());
() -> place(config, ANCHOR_Y, placer, null)).getMessage());
assertTrue(placer.writes().isEmpty());
}
@@ -397,42 +501,8 @@ public class IrisObjectPlacementRunnerRegressionTest {
List<BlockWrite> center = placer.writes().stream().filter(write -> write.x() == 0 && write.z() == 0).toList();
assertEquals(List.of(82, 81, 83), center.stream().map(BlockWrite::y).toList());
assertSame(solid, center.get(0).state());
assertSame(IrisObject.States.SNOW_LAYERS[0], center.get(2).state());
}
@Test
public void preparationPreservesRandomDrawsForPlacementAndLaterCallers() {
for (int range : List.of(-3, 0, 3)) {
RNG rng = new RNG(91);
RNG expected = new RNG(91);
expected.imax();
expected.imax();
expected.imax();
int offset = range > 0 ? expected.i(0, range) : range < 0 ? expected.i(range, 0) : 0;
IrisObjectPlacement config = placement().setBore(true);
config.setTranslate(new IrisObjectTranslate().setYRandom(range));
assertEquals(ANCHOR_Y + offset,
lineObject(1).place(0, ANCHOR_Y, 0, new RecordingPlacer(null), config, rng, data));
assertEquals(expected.nextLong(), rng.nextLong());
}
}
@Test
public void heightmapPreparationKeepsItsSeedDrawBeforeRotation() {
RNG rng = new RNG(91);
RNG expected = new RNG(91);
expected.nextLong();
expected.imax();
expected.imax();
expected.imax();
RecordingPlacer placer = new RecordingPlacer(null);
IrisObjectPlacement config = placement();
config.setHeightmap(new IrisNoiseGenerator(false).setOffsetY(93));
assertEquals(93, lineObject(1).place(0, -1, 0, placer, config, rng, data));
assertTrue(placer.sampledColumns().isEmpty());
assertEquals(expected.nextLong(), rng.nextLong());
assertEquals(solid.key(), center.get(0).state().key());
assertEquals(SNOW_LAYER, center.get(2).state().key());
}
@Test
@@ -474,9 +544,8 @@ public class IrisObjectPlacementRunnerRegressionTest {
assertEquals(List.of(-1, 0, 1), placer.writes().stream().map(BlockWrite::z).sorted().toList());
}
private PlacementState execute(IrisObjectPlacement config, int y, RecordingPlacer placer, CarveResult cave) {
return PlacementLifecycles.defaults().get(config.getMode()).execute(
new PlacementContext(config, data, placer, cave, new RNG(2L), lineObject(1), 0, 0, y, null));
private ObjectPlacementResult place(IrisObjectPlacement config, int y, RecordingPlacer placer, CarveResult cave) {
return ModuleObjectPlacement.place(lineObject(1), 0, y, 0, placer, config, new RNG(2L), null, cave, data);
}
private IrisObject lineObject(int width) {
@@ -541,8 +610,8 @@ public class IrisObjectPlacementRunnerRegressionTest {
return writes;
}
private List<BlockWrite> writesOf(PlatformBlockState state) {
return writes.stream().filter(write -> write.state() == state).toList();
private List<BlockWrite> writesOf(String key) {
return writes.stream().filter(write -> write.state().key().equals(key)).toList();
}
private List<String> sampledColumns() {
@@ -1,6 +1,5 @@
package art.arcane.iris.engine.object.placement;
import art.arcane.iris.engine.object.placement.ObjectBlockPass;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
@@ -9,20 +8,20 @@ import static org.junit.Assert.assertTrue;
public class IrisObjectStructurePieceAirTest {
@Test
public void explicitAirPlacesOnlyForRawStructurePieces() {
assertTrue(ObjectBlockPass.shouldPlaceObjectBlock(true, true, false));
assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(false, true, false));
assertTrue(BlocksModule.shouldPlaceObjectBlock(true, true, false));
assertFalse(BlocksModule.shouldPlaceObjectBlock(false, true, false));
}
@Test
public void ordinaryObjectAirRemainsNondestructive() {
assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(false, true, false));
assertTrue(ObjectBlockPass.shouldPlaceObjectBlock(false, false, false));
assertFalse(BlocksModule.shouldPlaceObjectBlock(false, true, false));
assertTrue(BlocksModule.shouldPlaceObjectBlock(false, false, false));
}
@Test
public void vineReplacementRemainsRejectedForEveryPlacementMode() {
assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(false, false, true));
assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(true, false, true));
assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(true, true, true));
assertFalse(BlocksModule.shouldPlaceObjectBlock(false, false, true));
assertFalse(BlocksModule.shouldPlaceObjectBlock(true, false, true));
assertFalse(BlocksModule.shouldPlaceObjectBlock(true, true, true));
}
}
@@ -9,6 +9,8 @@ import art.arcane.iris.engine.object.prefab.IrisObjectTranslate;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.engine.object.terrain.carving.CarvingMode;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.BuiltInPlacementPack;
import com.volmit.host.LoadedPack;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.spi.IrisPlatform;
@@ -19,8 +21,12 @@ import art.arcane.iris.util.project.stream.ProceduralStream;
import art.arcane.volmlib.util.math.RNG;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.util.List;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -40,11 +46,15 @@ import static org.mockito.Mockito.when;
public class IrisObjectSurfaceSupportPlacementTest {
private static final int SURFACE_Y = 80;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private IrisData data;
private Engine engine;
private LoadedPack pack;
@Before
public void bindPlatform() {
public void bindPlatform() throws IOException {
IrisPlatforms.unbind();
PlatformRegistries registries = mock(PlatformRegistries.class);
// IrisObject caches built-in states across test fixtures; every registry answer must be usable.
@@ -72,12 +82,15 @@ public class IrisObjectSurfaceSupportPlacementTest {
engine = mock(Engine.class);
when(engine.getHeight()).thenReturn(256);
when(engine.getComplex()).thenReturn(complex);
BuiltInPlacementPack.seedWorld(engine, 7L);
data = mock(IrisData.class);
when(data.getEngine()).thenReturn(engine);
pack = BuiltInPlacementPack.serve(data, folder, List.of());
}
@After
public void unbindPlatform() {
pack.close();
IrisPlatforms.unbind();
}
@@ -1,215 +0,0 @@
package art.arcane.iris.engine.object.placement;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.placement.ObjectPlaceMode;
import art.arcane.iris.engine.object.placement.PlacementContext;
import art.arcane.iris.engine.object.placement.PlacementLifecycle;
import art.arcane.iris.engine.object.placement.PlacementLifecycleBuilder;
import art.arcane.iris.engine.object.placement.PlacementLifecycleDependency;
import art.arcane.iris.engine.object.placement.PlacementLifecycles;
import art.arcane.iris.engine.object.placement.PlacementModule;
import art.arcane.iris.engine.object.placement.PlacementModuleHeight;
import art.arcane.iris.engine.object.placement.PlacementModulePreparation;
import art.arcane.iris.engine.object.placement.PlacementModuleSlope;
import art.arcane.iris.engine.object.placement.PlacementStage;
import art.arcane.iris.engine.object.placement.PlacementState;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.util.common.math.Vector3i;
import art.arcane.volmlib.util.math.RNG;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
public class PlacementLifecycleTest {
private static PlacementLifecycleDependency id(String name) {
return new PlacementLifecycleDependency(name);
}
@Test
public void resolvesDependenciesAcrossModulesRegardlessOfInstallOrder() {
List<String> calls = new ArrayList<>();
PlacementModule consumer = builder -> builder.add(id("consumer"), PlacementStage.HEIGHT,
(context, state, ignored) -> calls.add("consumer"), id("provider"));
PlacementModule provider = builder -> builder.add(id("provider"), PlacementStage.HEIGHT,
(context, state, ignored) -> calls.add("provider"));
PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder();
consumer.install(builder);
provider.install(builder);
builder.add(id("independent"), PlacementStage.HEIGHT,
(context, state, ignored) -> calls.add("independent"));
PlacementLifecycle plan = builder.build();
assertTrue(calls.isEmpty());
plan.run(PlacementStage.HEIGHT, null, new PlacementState(0, null), null);
assertEquals(List.of("provider", "consumer", "independent"), calls);
}
@Test
public void rejectsMissingDuplicateCyclicAndBackwardDependencies() {
PlacementLifecycleBuilder missing = new PlacementLifecycleBuilder();
missing.add(id("stilt"), PlacementStage.AFTER_BLOCKS, (c, s, v) -> {}, id("bounds"));
String message = assertThrows(IllegalArgumentException.class, missing::build).getMessage();
assertTrue(message.contains("stilt"));
assertTrue(message.contains("bounds"));
PlacementLifecycleBuilder duplicate = new PlacementLifecycleBuilder();
duplicate.add(id("a"), PlacementStage.HEIGHT, (c, s, v) -> {});
assertThrows(IllegalArgumentException.class,
() -> duplicate.add(id("a"), PlacementStage.HEIGHT, (c, s, v) -> {}));
PlacementLifecycleBuilder cyclic = new PlacementLifecycleBuilder();
cyclic.add(id("a"), PlacementStage.HEIGHT, (c, s, v) -> {}, id("b"));
cyclic.add(id("b"), PlacementStage.HEIGHT, (c, s, v) -> {}, id("a"));
message = assertThrows(IllegalArgumentException.class, cyclic::build).getMessage();
assertTrue(message.contains("cycle"));
assertTrue(message.contains("a"));
assertTrue(message.contains("b"));
PlacementLifecycleBuilder backward = new PlacementLifecycleBuilder();
backward.add(id("height"), PlacementStage.HEIGHT, (c, s, v) -> {}, id("fill"));
backward.add(id("fill"), PlacementStage.AFTER_BLOCKS, (c, s, v) -> {});
assertTrue(assertThrows(IllegalArgumentException.class, backward::build)
.getMessage().contains("later step"));
}
@Test
public void rejectsSelfDependencyAndAcceptsRepeatedPrerequisite() {
PlacementLifecycleBuilder self = new PlacementLifecycleBuilder();
self.add(id("self"), PlacementStage.HEIGHT, (c, s, v) -> {}, id("self"));
assertThrows(IllegalArgumentException.class, self::build);
PlacementLifecycleBuilder repeated = new PlacementLifecycleBuilder();
repeated.add(id("a"), PlacementStage.HEIGHT, (c, s, v) -> s.y++);
repeated.add(id("b"), PlacementStage.HEIGHT, (c, s, v) -> s.y *= 2, id("a"), id("a"));
PlacementState state = new PlacementState(2, null);
repeated.build().run(PlacementStage.HEIGHT, null, state, null);
assertEquals(6, state.y);
}
@Test
public void plansAreSnapshotsAndFailuresPropagateWithoutRunningDependents() {
List<String> calls = new ArrayList<>();
PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder();
builder.add(id("first"), PlacementStage.HEIGHT, (c, s, v) -> calls.add("first"));
PlacementLifecycle original = builder.build();
IllegalStateException failure = new IllegalStateException("failed placement");
builder.add(id("failure"), PlacementStage.HEIGHT, (c, s, v) -> { throw failure; }, id("first"));
builder.add(id("dependent"), PlacementStage.HEIGHT, (c, s, v) -> calls.add("dependent"), id("failure"));
original.run(PlacementStage.HEIGHT, null, new PlacementState(0, null), null);
assertEquals(List.of("first"), calls);
assertSame(failure, assertThrows(IllegalStateException.class,
() -> builder.build().run(PlacementStage.HEIGHT, null, new PlacementState(0, null), null)));
assertEquals(List.of("first", "first"), calls);
}
@Test
public void everyModeResolvesAndRuntimePlansAreIndependent() {
PlacementLifecycles first = PlacementLifecycles.resolve();
PlacementLifecycles second = PlacementLifecycles.resolve();
for (ObjectPlaceMode mode : ObjectPlaceMode.values()) {
assertNotNull(first.get(mode));
assertNotSame(first.get(mode), second.get(mode));
}
}
@Test
public void resolvesLongDependencyChainsWithoutRecursiveTraversal() {
PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder();
for (int i = 9999; i >= 0; i--) {
builder.add(id("step-" + i), PlacementStage.HEIGHT, (c, s, v) -> s.y++,
i == 0 ? new PlacementLifecycleDependency[0]
: new PlacementLifecycleDependency[]{id("step-" + (i - 1))});
}
PlacementState state = new PlacementState(0, null);
builder.build().run(PlacementStage.HEIGHT, null, state, null);
assertEquals(10000, state.y);
}
@Test
public void sharedHeightPlanKeepsConcurrentPlacementStateSeparate() throws Exception {
PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder();
new PlacementModulePreparation().install(builder);
new PlacementModuleSlope().install(builder);
new PlacementModuleHeight(PlacementModuleHeight.Mode.MAX, false).install(builder);
PlacementLifecycle plan = builder.build();
CountDownLatch sampled = new CountDownLatch(2);
try (var executor = Executors.newFixedThreadPool(2)) {
var first = executor.submit(() -> sample(plan, 10, sampled));
var second = executor.submit(() -> sample(plan, 100, sampled));
assertEquals(11, (int) first.get(10, TimeUnit.SECONDS));
assertEquals(101, (int) second.get(10, TimeUnit.SECONDS));
}
}
private int sample(PlacementLifecycle plan, int x, CountDownLatch sampled) throws Exception {
IObjectPlacer placer = mock(IObjectPlacer.class);
when(placer.getHighest(anyInt(), anyInt(), any(), anyBoolean())).thenAnswer(call -> {
sampled.countDown();
assertTrue(sampled.await(5, TimeUnit.SECONDS));
return call.<Integer>getArgument(0);
});
IrisObjectPlacement config = new IrisObjectPlacement().setForcePlace(true);
IrisObject object = mock(IrisObject.class);
when(object.getCenter()).thenReturn(new Vector3i(1, 0, 0));
when(object.getW()).thenReturn(3);
when(object.getH()).thenReturn(1);
when(object.getD()).thenReturn(1);
PlacementContext context = new PlacementContext(config, mock(IrisData.class), placer, null,
new RNG(1), object, x, 0, -1, null);
PlacementState state = new PlacementState(context);
plan.run(PlacementStage.PREPARE, context, state, null);
plan.run(PlacementStage.HEIGHT, context, state, null);
return state.y;
}
@Test
public void guardOwnsTheForcePlaceExemption() {
PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder();
builder.add(id("guard"), PlacementStage.HEIGHT, (c, s, v) -> {
if (!s.config.isForcePlace()) {
s.reject("guard");
}
});
builder.add(id("dependent"), PlacementStage.HEIGHT, (c, s, v) -> s.y = 99, id("guard"));
PlacementLifecycle plan = builder.build();
IrisObjectPlacement config = new IrisObjectPlacement();
PlacementContext context = new PlacementContext(config, mock(IrisData.class), mock(IObjectPlacer.class),
null, new RNG(1), mock(IrisObject.class), 0, 0, -1, null);
PlacementState rejected = new PlacementState(context);
plan.run(PlacementStage.HEIGHT, context, rejected, null);
assertEquals(-1, rejected.heightOrRejected());
assertEquals("guard", rejected.getRejection());
config.setForcePlace(true);
PlacementState forced = new PlacementState(context);
plan.run(PlacementStage.HEIGHT, context, forced, null);
assertEquals(99, forced.y);
}
@Test
public void rejectionIsTerminalAcrossPhasesEvenWithForcePlace() {
PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder();
List<String> calls = new ArrayList<>();
builder.add(id("reject"), PlacementStage.VALIDATE, (c, s, v) -> s.reject("protected"));
builder.add(id("bore"), PlacementStage.BEFORE_BLOCKS, (c, s, v) -> calls.add("bore"));
builder.add(id("blocks"), PlacementStage.BLOCKS, (c, s, v) -> calls.add("blocks"));
builder.add(id("finish"), PlacementStage.AFTER_BLOCKS, (c, s, v) -> calls.add("finish"));
PlacementContext context = new PlacementContext(new IrisObjectPlacement().setForcePlace(true),
mock(IrisData.class), mock(IObjectPlacer.class), null, new RNG(1),
mock(IrisObject.class), 0, 0, 80, null);
PlacementState result = builder.build().execute(context);
assertEquals(-1, result.heightOrRejected());
result.reject("later reason");
assertEquals("protected", result.getRejection());
assertTrue(calls.isEmpty());
}
}
@@ -7,6 +7,8 @@ import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.BuiltInPlacementPack;
import com.volmit.host.LoadedPack;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeStructureVolume;
@@ -19,8 +21,11 @@ import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -37,12 +42,16 @@ import static org.mockito.Mockito.when;
public class NativeStructureObjectVetoTest {
private static final int SURFACE_Y = 80;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private IrisData data;
private Engine engine;
private LoadedPack pack;
private PlatformBlockState log;
@Before
public void bindPlatform() {
public void bindPlatform() throws IOException {
IrisPlatforms.unbind();
PlatformRegistries registries = mock(PlatformRegistries.class);
// IrisObject caches built-in states across test fixtures; every registry answer must be usable.
@@ -72,12 +81,15 @@ public class NativeStructureObjectVetoTest {
when(engine.getComplex()).thenReturn(complex);
when(engine.getDimension()).thenReturn(mock(IrisDimension.class));
volumes();
BuiltInPlacementPack.seedWorld(engine, 7L);
data = mock(IrisData.class);
when(data.getEngine()).thenReturn(engine);
pack = BuiltInPlacementPack.serve(data, folder, List.of());
}
@After
public void unbindPlatform() {
pack.close();
IrisPlatforms.unbind();
}