Merge feat/structure-jigsaw-modules into port/v3-features

Structure placement and jigsaw now live in the built-in modules jar, on top of the port's weighted picking, studio tooling
and procedural object work.

api/CONTRACTS.md keeps both sides' rows: the weighted entries and the studio bake and scene creation types from the port,
and VanillaStructureContext.world, Argument.reading, PlatformStructures, tool worlds and the services lookup from the
structure move.

PackModuleResourceKindTest installs the built-in modules jar into its castle pack, as the structure move requires, and
writes the dimension and region lists as weighted entries, as the port requires.

StructurePlacing takes the structure move's version. Its int sentinel for a sampled height is replaced by an explicit
sampledHeight flag that calls ObjectRun.automatic, and explicit pieces pass their world Y minus the world's minimum, so an
explicit world Y below zero stays a height (e3dd61c17).

StructureOutputPinTest.everyScenarioPlacesThePinnedStructures is re-baselined for the underground scenario's writes hash
only (9176f55f60410c117cdd9d5e to 1025f82c04539d4881a0e92b): pieces at world Y -1 are now placed there instead of on the
surface. The start count, the piece hash and every other scenario are unchanged.
This commit is contained in:
piexel committed 2026-11-10 14:33:49 +01:00
commit 2889274291
514 files changed
+29979 -15110

No files matched your search

@@ -47,6 +47,10 @@ import art.arcane.iris.core.lifecycle.WorldLifecycleService;
import art.arcane.iris.core.runtime.BukkitEnginePlatformHooks;
import art.arcane.iris.core.runtime.WorldDeletionQueue;
import art.arcane.iris.core.runtime.WorldRuntimeControlService;
import art.arcane.iris.core.toolworld.BukkitToolWorldService;
import art.arcane.iris.core.structure.BukkitPlatformStructures;
import art.arcane.iris.core.tooling.ToolWorldsHost;
import com.volmit.tooling.PlatformStructures;
import art.arcane.iris.api.terrain.IrisTerrainService;
import art.arcane.iris.core.link.CustomBlockSource;
import art.arcane.iris.core.link.IrisPapiInstaller;
@@ -72,7 +76,6 @@ import art.arcane.iris.core.service.IrisEngineSVC;
import art.arcane.iris.core.service.IrisIntegrationService;
import art.arcane.iris.core.service.IrisProtocolService;
import art.arcane.iris.core.service.IrisTerrainSVC;
import art.arcane.iris.core.service.JigsawStudioService;
import art.arcane.iris.core.service.LogFilterSVC;
import art.arcane.iris.core.service.MultiverseSVC;
import art.arcane.iris.core.service.ObjectSVC;
@@ -645,7 +648,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
new EditSVC(),
new ObjectSVC(),
new ObjectStudioSaveService(),
new JigsawStudioService(),
new StudioSVC(),
new DatapackStructureScopeSVC(),
new IrisEngineSVC(),
@@ -655,6 +657,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
new EntityRiseSVC(),
new WandSVC(),
new BoardSVC(),
new BukkitToolWorldService(),
new IrisIntegrationService(),
new MultiverseSVC(),
new IrisProtocolService(),
@@ -670,6 +673,8 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
services.put(serviceType, i);
IrisServices.register(serviceType, i);
}
IrisServices.register(ToolWorldsHost.class, services.get(BukkitToolWorldService.class));
IrisServices.register(PlatformStructures.class, new BukkitPlatformStructures());
IrisServices.register(BlockEditAccess.class, services.get(EditSVC.class));
IrisServices.register(CustomBlockSource.class, services.get(ExternalDataSVC.class));
IrisServices.register(PreservationRegistry.class, services.get(PreservationSVC.class));
@@ -998,14 +1003,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
private void quiesceRuntimeForServerShutdown(String reason) {
serverStopTeardownDeferred.set(true);
JigsawStudioService jigsawStudioService = IrisServices.getOrNull(JigsawStudioService.class);
if (jigsawStudioService != null) {
try {
jigsawStudioService.quiesceForServerShutdown();
} catch (Throwable e) {
Iris.reportError("Failed to quiesce Jigsaw Studio before server shutdown.", e);
}
}
StudioSVC studioService = IrisServices.getOrNull(StudioSVC.class);
if (studioService != null) {
studioService.quiesceDownloadsForShutdown();
@@ -86,8 +86,6 @@ public class CommandIris implements DirectorExecutor {
private CommandStudio studio;
private CommandPregen pregen;
private CommandObject object;
private CommandStructure structure;
private CommandJigsaw jigsaw;
private CommandWhat what;
private CommandEdit edit;
private CommandDeveloper developer;
@@ -1,71 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.commands;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.structure.BulkStructureImporter;
import art.arcane.iris.core.structure.StructureCaptureImporter;
import art.arcane.iris.core.structure.StructureImporter;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.util.common.director.DirectorExecutor;
import art.arcane.volmlib.util.director.DirectorOrigin;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
import art.arcane.iris.core.localization.IrisLanguage;
import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.iris.core.localization.BukkitCommandMessagesExtended;
@Director(name = "structure", aliases = {"struct", "str"}, description = "Iris structure tools (index, import, info)", descriptionKey = "iris.director.commandstructure.director.iris_structure_tools_index_import_info")
public class CommandStructure implements DirectorExecutor {
@Director(name = "import", description = "Import EVERY structure - vanilla AND ingested datapacks - into this pack as editable Iris resources, always overwriting. Rebuilds jigsaw structures (villages, outposts, datapack jigsaws) as editable pool/piece graphs, imports every structure template NBT as an object, and assembles the multi-template structures (shipwrecks, ruined portals, ocean ruins, nether fossils). Run after ingesting a datapack and restarting. Regenerate chunks or use a fresh world for the imported copies to place.", descriptionKey = "iris.director.commandstructure.director.import_every_structure_vanilla_ingested_datapacks_into_this_pack_as_editable_iris", aliases = {"import-all", "reimport", "imp", "all"}, origin = DirectorOrigin.BOTH)
public void importAll(
@Param(description = "The dimension whose pack to import into", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_import_into", aliases = "dim")
IrisDimension dimension
) {
IrisData data = dimension.getLoader();
if (data == null) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_2, MessageArgument.untrusted("value", dimension.getLoadKey())));
return;
}
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_IMPORTING_ALL_VANILLA_DATAPACK_STRUCTURES_INTO_OVERWRITE, MessageArgument.untrusted("value", dimension.getLoadKey())));
BulkStructureImporter.Report jigsaws = BulkStructureImporter.importAllVanilla(data, StructureImporter.Mode.OVERWRITE, true, sender());
BulkStructureImporter.Report templates = BulkStructureImporter.importAllTemplates(data, StructureImporter.Mode.OVERWRITE, sender());
BulkStructureImporter.Report groups = BulkStructureImporter.importTemplateGroups(data, StructureImporter.Mode.OVERWRITE, sender());
StructureCaptureImporter.Report captured = StructureCaptureImporter.importStructures(
data, StructureImporter.Mode.OVERWRITE, sender(), jigsaws.captureCandidates());
int imported = jigsaws.imported() + templates.imported() + groups.imported() + captured.imported();
int failed = jigsaws.failed() + templates.failed() + groups.failed() + captured.failed();
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_IMPORT_COMPLETE_STRUCTURES_OBJECTS_WRITTEN_FAILED, MessageArgument.untrusted("imported", imported), MessageArgument.untrusted("failed", failed)));
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_REFERENCE_THEM_FROM_BIOME_REGION_DIMENSION_STRUCTURES_LIST_RUN_IRIS));
}
@Director(name = "capture", description = "Capture live registered structures into editable Iris objects by generating each one in a throwaway scratch world and reading back its blocks. This standalone command overwrites its owned outputs; structures wider/taller than the capture cap and anything that will not generate in a flat overworld are skipped. Each captured structure becomes a single-piece Iris structure you can place from a biome/region/dimension 'structures' list. /iris structure import runs a restricted final capture pass only for non-jigsaw structures that have no loadable NBT template.", descriptionKey = "iris.director.commandstructure.director.capture_code_generated_structures_that_have_no_nbt_template_swamp_huts_igloos", aliases = {"cap"}, origin = DirectorOrigin.BOTH)
public void capture(
@Param(description = "The dimension whose pack to capture into", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_capture_into", aliases = "dim")
IrisDimension dimension
) {
IrisData data = dimension.getLoader();
if (data == null) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_3, MessageArgument.untrusted("value", dimension.getLoadKey())));
return;
}
StructureCaptureImporter.Report report = StructureCaptureImporter.importAllStructures(data, StructureImporter.Mode.OVERWRITE, sender());
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_CAPTURED_STRUCTURES_PLACE_THEM_FROM_STRUCTURES_LIST_REGENERATE_CHUNKS_DELETE, MessageArgument.untrusted("value", report.imported())));
}
}
@@ -19,6 +19,7 @@
package art.arcane.iris.core.service;
import art.arcane.iris.core.project.IrisProject;
import art.arcane.iris.core.toolworld.BukkitToolWorldService;
import art.arcane.iris.core.tooling.IrisServedPack;
import art.arcane.iris.core.tooling.SenderWorld;
import art.arcane.iris.core.tooling.ServedPack;
@@ -30,6 +31,7 @@ import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.util.common.format.C;
import art.arcane.iris.util.common.plugin.VolmitSender;
import art.arcane.iris.util.common.scheduling.J;
import com.volmit.tooling.world.ToolPlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -39,13 +41,13 @@ import java.util.Optional;
* A Bukkit sender of a tooling command. It reads the world the sender stands in and the open studio when it is built, which
* the adapter does on the thread that received the command, and delivers messages on the sender's own thread.
*/
final class BukkitToolingSender implements ToolingSender {
public final class BukkitToolingSender implements ToolingSender {
private final CommandSender sender;
private final VolmitSender messages;
private final Optional<SenderWorld> world;
private final Optional<ServedPack> openStudioPack;
BukkitToolingSender(CommandSender sender) {
public BukkitToolingSender(CommandSender sender) {
this.sender = sender;
this.messages = new VolmitSender(sender);
this.world = standingWorld(sender);
@@ -77,6 +79,15 @@ final class BukkitToolingSender implements ToolingSender {
return type.isInstance(sender) ? Optional.of(type.cast(sender)) : Optional.empty();
}
@Override
public Optional<ToolPlayer> player() {
BukkitToolWorldService toolWorlds = IrisServices.getOrNull(BukkitToolWorldService.class);
if (!(sender instanceof Player player) || toolWorlds == null) {
return Optional.empty();
}
return Optional.of(toolWorlds.playerOf(player));
}
@Override
public boolean isOperator() {
return sender.hasPermission(CommandSVC.ROOT_PERMISSION);
@@ -0,0 +1,165 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure;
import art.arcane.iris.core.modules.BlockEntities;
import art.arcane.iris.core.modules.PlatformBlockStates;
import art.arcane.iris.core.nms.INMS;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.util.common.plugin.VolmitSender;
import art.arcane.iris.util.common.scheduling.J;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.CapturedStructure;
import com.volmit.tooling.PlatformStructures;
import com.volmit.tooling.TemplateBlock;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/** A throwaway Bukkit world structures are generated in one after another, one cell of a grid each, and removed on close. */
final class BukkitCaptureArea implements PlatformStructures.CaptureArea {
private static final int CELL_STRIDE = 128;
private static final int CELL_COLUMNS = 8;
private static final long REGION_TIMEOUT_SECONDS = 30L;
private final World world;
private final VolmitSender sender;
private int nextCell;
BukkitCaptureArea(World world, VolmitSender sender) {
this.world = world;
this.sender = sender;
}
@Override
public Optional<CapturedStructure> capture(ResourceId structure, long seed, int maxSpan) {
int cellIndex = nextCell++;
int originX = (cellIndex % CELL_COLUMNS) * CELL_STRIDE;
int originZ = (cellIndex / CELL_COLUMNS) * CELL_STRIDE;
int anchorChunkX = (originX + CELL_STRIDE / 2) >> 4;
int anchorChunkZ = (originZ + CELL_STRIDE / 2) >> 4;
String key = structure.toString();
AtomicReference<CapturedStructure> capturedRef = new AtomicReference<>();
AtomicReference<Throwable> errorRef = new AtomicReference<>();
CountDownLatch latch = new CountDownLatch(1);
boolean scheduled = J.runRegion(world, anchorChunkX, anchorChunkZ, () -> {
try {
capturedRef.set(placeAndRead(key, anchorChunkX, anchorChunkZ, seed, maxSpan));
} catch (Throwable e) {
errorRef.set(e);
} finally {
latch.countDown();
}
});
if (!scheduled) {
throw captureFailure(key, anchorChunkX, anchorChunkZ, "region task was not accepted", null);
}
try {
if (!latch.await(REGION_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
throw captureFailure(key, anchorChunkX, anchorChunkZ,
"region task did not complete within " + REGION_TIMEOUT_SECONDS + " seconds", null);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw captureFailure(key, anchorChunkX, anchorChunkZ, "interrupted while waiting for the region task", e);
}
Throwable error = errorRef.get();
if (error != null) {
throw captureFailure(key, anchorChunkX, anchorChunkZ, "platform placement failed", error);
}
return Optional.ofNullable(capturedRef.get());
}
private CapturedStructure placeAndRead(String key, int anchorChunkX, int anchorChunkZ, long seed, int maxSpan) {
int[] box = INMS.get().placeStructure(world, anchorChunkX, anchorChunkZ, key, seed, maxSpan);
if (box == null) {
return null;
}
int width = box[3] - box[0] + 1;
int height = box[4] - box[1] + 1;
int depth = box[5] - box[2] + 1;
if (width <= 0 || height <= 0 || depth <= 0) {
return null;
}
List<TemplateBlock> blocks = new ArrayList<>();
for (int dx = 0; dx < width; dx++) {
for (int dy = 0; dy < height; dy++) {
for (int dz = 0; dz < depth; dz++) {
Block block = world.getBlockAt(box[0] + dx, box[1] + dy, box[2] + dz);
if (block.getType() == Material.AIR) {
continue;
}
blocks.add(blockOf(block, dx, dy, dz));
}
}
}
unloadChunksOf(box);
return blocks.isEmpty() ? null : new CapturedStructure(new BlockPosition(width, height, depth), blocks);
}
private static TemplateBlock blockOf(Block block, int x, int y, int z) {
BlockState state = BlockState.parse(
PlatformBlockStates.namespaced(BukkitBlockState.of(block.getBlockData()).key()));
TileData tile = TileData.getTileState(block, false);
Optional<BlockEntityData> blockEntity = tile == null ? Optional.empty() : Optional.of(BlockEntities.of(tile));
return TemplateBlock.of(new BlockPosition(x, y, z), state, blockEntity);
}
private void unloadChunksOf(int[] box) {
int minCX = box[0] >> 4;
int maxCX = box[3] >> 4;
int minCZ = box[2] >> 4;
int maxCZ = box[5] >> 4;
for (int cx = minCX; cx <= maxCX; cx++) {
for (int cz = minCZ; cz <= maxCZ; cz++) {
try {
world.unloadChunk(cx, cz, false);
} catch (Throwable ignored) {
}
}
}
}
@Override
public void close() {
FeatureImporter.destroyScratchWorld(world, sender);
}
static IllegalStateException captureFailure(String key, int chunkX, int chunkZ, String detail, Throwable cause) {
String message = "Structure capture failed for '" + key + "' at chunk "
+ chunkX + "," + chunkZ + ": " + detail;
return cause == null ? new IllegalStateException(message) : new IllegalStateException(message, cause);
}
}
@@ -0,0 +1,319 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure;
import art.arcane.iris.core.nms.INMS;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.util.common.plugin.VolmitSender;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.JigsawStructureInfo;
import com.volmit.tooling.PlatformStructures;
import com.volmit.tooling.Sender;
import com.volmit.tooling.StructureAccessException;
import com.volmit.tooling.StructureTemplate;
import com.volmit.tooling.TemplatePool;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.TreeSet;
import java.util.function.Predicate;
/**
* The structures of a Bukkit server: its registered structures and structure sets through the NMS binding, the
* jigsaw structures and template pools through the server's registries, the templates through Bukkit's structure
* manager and the server's resource manager, and structure capture through the NMS binding in a scratch world.
*/
public final class BukkitPlatformStructures implements PlatformStructures {
private static final String STRUCTURE_TEMPLATE_FOLDER = "structure";
private static final String TEMPLATE_FILE_SUFFIX = ".nbt";
private static final String JIGSAW_STRUCTURE_CLASS_SUFFIX = "JigsawStructure";
@Override
public List<ResourceId> templates() {
try {
return enumerateTemplateKeys();
} catch (Exception e) {
throw new StructureAccessException(ServerReflection.failureDetail(e), true, e);
}
}
@Override
public Optional<StructureTemplate> template(ResourceId id) {
return BukkitTemplateReader.read(Bukkit.getStructureManager().loadStructure(new NamespacedKey(id.namespace(), id.path())));
}
@Override
public List<ResourceId> structures() {
return idsOf(INMS.get().getStructureKeys());
}
@Override
public List<ResourceId> structureSets() {
return idsOf(INMS.get().getStructureSetKeys());
}
@Override
public Optional<JigsawStructureInfo> jigsaw(ResourceId structureKey) {
Object registryAccess = registryAccess();
Object structureRegistry;
Object structure;
try {
structureRegistry = ServerReflection.lookupRegistry(registryAccess, "STRUCTURE");
structure = ServerReflection.registryGet(structureRegistry, structureKey);
} catch (Throwable e) {
throw new StructureAccessException("Failed to read jigsaw structure graph: " + e, true, e);
}
if (structure == null || !structure.getClass().getName().endsWith(JIGSAW_STRUCTURE_CLASS_SUFFIX)) {
return Optional.empty();
}
Object startPool;
int maxDepth;
int maxDistanceFromCenter;
try {
startPool = ServerReflection.unwrapHolder(ServerReflection.invoke(structure, "getStartPool"));
maxDepth = ServerReflection.readIntMember(structure, "maxDepth");
maxDistanceFromCenter = ServerReflection.readIntMember(structure, "maxDistanceFromCenter");
} catch (Throwable e) {
throw new StructureAccessException("Failed to read jigsaw structure graph: " + e, true, e);
}
Object templatePoolRegistry = templatePoolRegistry(registryAccess);
String startPoolKey;
try {
startPoolKey = ServerReflection.registryKeyOf(templatePoolRegistry, startPool);
} catch (Throwable e) {
throw new StructureAccessException("Could not resolve the start pool key for " + structureKey + ": " + e, true, e);
}
if (startPoolKey == null) {
throw new StructureAccessException("Could not resolve the start pool key for " + structureKey, false);
}
return Optional.of(new JigsawStructureInfo(
ResourceId.parse(startPoolKey),
maxDepth,
maxDistanceFromCenter,
Bukkit.getBukkitVersion(),
new NamespacedKey(structureKey.namespace(), structureKey.path()).hashCode()));
}
@Override
public Optional<TemplatePool> pool(ResourceId poolKey) {
Object server;
Object structureManager;
Object registry;
Object pool;
try {
server = ServerReflection.minecraftServer();
structureManager = ServerReflection.invoke(server, "getStructureManager");
registry = templatePoolRegistry(registryAccess());
pool = ServerReflection.registryGet(registry, poolKey);
} catch (StructureAccessException e) {
throw e;
} catch (Throwable e) {
throw new StructureAccessException("pool " + poolKey + ": " + e.getMessage(), true, e);
}
if (pool == null) {
return Optional.empty();
}
Optional<ResourceId> fallback = Optional.empty();
Optional<String> fallbackFailure = Optional.empty();
try {
Object fallbackPool = ServerReflection.unwrapHolder(ServerReflection.invoke(pool, "getFallback"));
String fallbackKey = ServerReflection.registryKeyOf(registry, fallbackPool);
fallback = Optional.ofNullable(fallbackKey).map(ResourceId::parse);
} catch (Throwable e) {
fallbackFailure = Optional.of(ServerReflection.failureDetail(e));
}
List<?> templates;
try {
templates = (List<?>) ServerReflection.invoke(pool, "getTemplates");
} catch (Throwable e) {
throw new StructureAccessException("templates " + poolKey + ": " + e.getMessage(), true, e);
}
List<TemplatePool.Member> members = new ArrayList<>();
for (Object pair : templates) {
members.add(PoolElementReader.memberOf(pair, structureManager));
}
return Optional.of(new TemplatePool(members, fallback, fallbackFailure));
}
@Override
public boolean supportsCapture() {
return INMS.get().supportsStructureCapture();
}
@Override
public Optional<CaptureArea> openCaptureArea(Sender sender) {
VolmitSender messages = messagesOf(sender);
World scratch = FeatureImporter.createScratchWorld(messages);
return scratch == null ? Optional.empty() : Optional.of(new BukkitCaptureArea(scratch, messages));
}
private static VolmitSender messagesOf(Sender sender) {
return sender.extension(CommandSender.class).map(VolmitSender::new).orElseGet(BukkitPlatform::console);
}
private static Object registryAccess() {
Object server;
try {
server = ServerReflection.minecraftServer();
} catch (Throwable e) {
throw new StructureAccessException("Failed to access server registries via reflection: " + e, true, e);
}
Object registryAccess = ServerReflection.resolveRegistryAccess(server);
if (registryAccess == null) {
throw new StructureAccessException("Could not resolve RegistryAccess from the server", true);
}
return registryAccess;
}
private static Object templatePoolRegistry(Object registryAccess) {
try {
return ServerReflection.lookupRegistry(registryAccess, "TEMPLATE_POOL");
} catch (Throwable e) {
throw new StructureAccessException("Failed to access TEMPLATE_POOL registry: " + e, true, e);
}
}
private static List<ResourceId> idsOf(Iterable<String> keys) {
TreeSet<ResourceId> ids = new TreeSet<>();
for (String key : keys) {
if (key == null || key.isBlank()) {
continue;
}
try {
ids.add(ResourceId.parse(key.toLowerCase(Locale.ROOT)));
} catch (IllegalArgumentException invalidKey) {
continue;
}
}
return new ArrayList<>(ids);
}
private static List<ResourceId> enumerateTemplateKeys() throws Exception {
Object server = ServerReflection.minecraftServer();
Object resourceManager = resolveResourceManager(server);
if (resourceManager == null) {
throw new IllegalStateException("Could not resolve the server ResourceManager via reflection");
}
Method listResources = null;
for (Method m : resourceManager.getClass().getMethods()) {
if (m.getName().equals("listResources") && m.getParameterCount() == 2
&& m.getParameterTypes()[0] == String.class
&& m.getParameterTypes()[1] == Predicate.class
&& Map.class.isAssignableFrom(m.getReturnType())) {
listResources = m;
break;
}
}
if (listResources == null) {
throw new NoSuchMethodException("listResources(String, Predicate) on " + resourceManager.getClass().getName());
}
listResources.setAccessible(true);
Predicate<Object> endsWithNbt = location -> {
String path = identifierPath(location);
return path != null && path.endsWith(TEMPLATE_FILE_SUFFIX);
};
Object resultMap = listResources.invoke(resourceManager, STRUCTURE_TEMPLATE_FOLDER, endsWithNbt);
TreeSet<String> keys = new TreeSet<>();
if (resultMap instanceof Map<?, ?> map) {
for (Object location : map.keySet()) {
String namespace = identifierNamespace(location);
String path = identifierPath(location);
if (namespace == null || path == null) {
continue;
}
String stripped = path;
if (stripped.startsWith(STRUCTURE_TEMPLATE_FOLDER + "/")) {
stripped = stripped.substring((STRUCTURE_TEMPLATE_FOLDER + "/").length());
}
if (stripped.endsWith(TEMPLATE_FILE_SUFFIX)) {
stripped = stripped.substring(0, stripped.length() - TEMPLATE_FILE_SUFFIX.length());
}
if (stripped.isEmpty()) {
continue;
}
keys.add(namespace + ":" + stripped);
}
}
return idsOf(keys);
}
private static Object resolveResourceManager(Object server) {
try {
Class<?> resourceManagerClass = Class.forName("net.minecraft.server.packs.resources.ResourceManager");
Method getter = null;
for (Method m : server.getClass().getMethods()) {
if (m.getName().equals("getResourceManager") && m.getParameterCount() == 0
&& resourceManagerClass.isAssignableFrom(m.getReturnType())) {
getter = m;
break;
}
}
if (getter == null) {
for (Method m : server.getClass().getMethods()) {
if (m.getParameterCount() == 0 && resourceManagerClass.isAssignableFrom(m.getReturnType())) {
getter = m;
break;
}
}
}
if (getter == null) {
return null;
}
getter.setAccessible(true);
return getter.invoke(server);
} catch (Throwable e) {
return null;
}
}
private static String identifierNamespace(Object location) {
try {
Method m = location.getClass().getMethod("getNamespace");
m.setAccessible(true);
Object value = m.invoke(location);
return value == null ? null : value.toString();
} catch (Throwable e) {
return null;
}
}
private static String identifierPath(Object location) {
try {
Method m = location.getClass().getMethod("getPath");
m.setAccessible(true);
Object value = m.invoke(location);
return value == null ? null : value.toString();
} catch (Throwable e) {
return null;
}
}
}
@@ -0,0 +1,111 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure;
import art.arcane.iris.core.modules.BlockEntities;
import art.arcane.iris.core.modules.PlatformBlockStates;
import art.arcane.iris.engine.object.prefab.LegacyTileData;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.spi.IrisLogging;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import com.volmit.tooling.StructureTemplate;
import com.volmit.tooling.TemplateBlock;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import org.bukkit.structure.Palette;
import org.bukkit.structure.Structure;
import org.bukkit.util.BlockVector;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/** Reads a Bukkit {@link Structure} as a {@link StructureTemplate}: its size, and the blocks of its first palette. */
final class BukkitTemplateReader {
private static final String FINAL_STATE_NBT_KEY = "final_state";
private BukkitTemplateReader() {
}
/** The template; empty when the structure holds no palette. */
static Optional<StructureTemplate> read(Structure structure) {
if (structure == null || structure.getPalettes().isEmpty()) {
return Optional.empty();
}
BlockVector size = structure.getSize();
Palette palette = structure.getPalettes().get(0);
List<TemplateBlock> blocks = new ArrayList<>();
for (org.bukkit.block.BlockState block : palette.getBlocks()) {
blocks.add(blockOf(block));
}
return Optional.of(new StructureTemplate(
new BlockPosition(size.getBlockX(), size.getBlockY(), size.getBlockZ()),
structure.getPaletteCount(),
structure.getEntityCount(),
blocks));
}
private static TemplateBlock blockOf(org.bukkit.block.BlockState block) {
Location location = block.getLocation();
BlockPosition position = new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ());
BlockData data = block.getBlockData();
Material material = data.getMaterial();
BlockState state = BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(data).key()));
if (material == Material.JIGSAW) {
return new TemplateBlock(position, state, Optional.empty(), readJigsawFinalState(block));
}
if (material == Material.STRUCTURE_BLOCK || material == Material.STRUCTURE_VOID) {
return TemplateBlock.of(position, state, Optional.empty());
}
return TemplateBlock.of(position, state, blockEntityOf(block));
}
private static Optional<BlockEntityData> blockEntityOf(org.bukkit.block.BlockState block) {
try {
LegacyTileData tile = LegacyTileData.fromBukkit(block);
return tile == null ? Optional.empty() : Optional.of(BlockEntities.of(tile));
} catch (Throwable e) {
IrisLogging.reportError(e);
return Optional.empty();
}
}
private static Optional<String> readJigsawFinalState(org.bukkit.block.BlockState block) {
try {
Object nbt = block.getClass().getMethod("getSnapshotNBT").invoke(block);
if (nbt == null) {
return Optional.empty();
}
Object res = nbt.getClass().getMethod("getString", String.class).invoke(nbt, FINAL_STATE_NBT_KEY);
String finalState = null;
if (res instanceof String s) {
finalState = s;
} else if (res instanceof Optional<?> o && o.isPresent()) {
finalState = String.valueOf(o.get());
}
return finalState == null || finalState.isBlank() ? Optional.empty() : Optional.of(finalState);
} catch (Throwable e) {
IrisLogging.reportError(e);
return Optional.empty();
}
}
}
@@ -0,0 +1,261 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure;
import com.volmit.geometry.BlockFace;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.StructureAccessException;
import com.volmit.tooling.TemplatePool;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.function.LongSupplier;
/** Reads the members of a registered template pool by reflection: their weights, templates and jigsaw connectors. */
final class PoolElementReader {
private static final String LIST_POOL_ELEMENT_SUFFIX = "ListPoolElement";
private static final String DEFAULT_FRONT = "north";
private static final String DEFAULT_TOP = "up";
private static final String FINAL_STATE_NBT_KEY = "final_state";
private PoolElementReader() {
}
/** The member of a pool for the pair the pool lists it as: its element and weight. */
static TemplatePool.Member memberOf(Object pair, Object structureManager) {
Object element;
int weight;
try {
element = ServerReflection.invoke(pair, "getFirst");
Object second = ServerReflection.invoke(pair, "getSecond");
weight = second instanceof Number ? Math.max(1, ((Number) second).intValue()) : 1;
} catch (Throwable e) {
return new TemplatePool.Unreadable(TemplatePool.Part.ENTRY, ServerReflection.failureDetail(e));
}
if (element == null) {
return new TemplatePool.Absent();
}
PoolElementResolution resolution;
try {
resolution = resolvePoolElement(element);
} catch (Throwable e) {
return new TemplatePool.Unreadable(TemplatePool.Part.TEMPLATE_LOCATION, ServerReflection.failureDetail(e));
}
String type = resolution.physicalElement() == null
? element.getClass().getSimpleName()
: resolution.physicalElement().getClass().getSimpleName();
Optional<ResourceId> template;
try {
template = Optional.ofNullable(resolution.templateLocation()).map(PoolElementReader::templateId);
} catch (IllegalArgumentException invalidLocation) {
return new TemplatePool.Unreadable(TemplatePool.Part.TEMPLATE_LOCATION,
"invalid piece key " + resolution.templateLocation());
}
return new TemplatePool.Element(weight, type, template, resolution.listLevels(), resolution.omittedElements(),
shuffleSeeds -> readConnectors(element, structureManager, shuffleSeeds));
}
private static ResourceId templateId(String location) {
return ResourceId.parse(location.toLowerCase(Locale.ROOT));
}
private static TemplatePool.Connectors readConnectors(Object element, Object structureManager, LongSupplier shuffleSeeds) {
try {
Object zero = ServerReflection.staticField("net.minecraft.core.BlockPos", "ZERO");
Object rotationNone = ServerReflection.staticField("net.minecraft.world.level.block.Rotation", "NONE");
Method m = ServerReflection.findMethod(element.getClass(), "getShuffledJigsawBlocks", 4);
if (m == null) {
return new TemplatePool.Connectors(TemplatePool.Availability.UNAVAILABLE, List.of());
}
m.setAccessible(true);
Object random = ServerReflection.freshRandomSource(shuffleSeeds.getAsLong());
List<?> blocks = (List<?>) m.invoke(element, structureManager, zero, rotationNone, random);
if (blocks == null) {
return new TemplatePool.Connectors(TemplatePool.Availability.NO_COLLECTION, List.of());
}
List<TemplatePool.Connector> connectors = new ArrayList<>();
for (Object jigsaw : blocks) {
connectors.add(connectorOf(jigsaw));
}
return new TemplatePool.Connectors(TemplatePool.Availability.READ, connectors);
} catch (Throwable e) {
throw new StructureAccessException(ServerReflection.failureDetail(e), true, e);
}
}
private static TemplatePool.Connector connectorOf(Object jigsaw) {
try {
return connectorFrom(jigsaw);
} catch (Throwable e) {
return new TemplatePool.UnreadableConnector(ServerReflection.failureDetail(e));
}
}
static TemplatePool.JigsawConnector connectorFrom(Object jigsaw) throws Exception {
Object info = ServerReflection.invoke(jigsaw, "info");
Object pos = ServerReflection.invoke(info, "pos");
Object blockState = ServerReflection.invoke(info, "state");
BlockPosition position = new BlockPosition(
ServerReflection.readInt(pos, "getX"),
ServerReflection.readInt(pos, "getY"),
ServerReflection.readInt(pos, "getZ"));
Object poolKey = ServerReflection.invoke(jigsaw, "pool");
String poolId = ServerReflection.identifierString(ServerReflection.invoke(poolKey, "identifier"));
String name = ServerReflection.identifierString(ServerReflection.invoke(jigsaw, "name"));
String target = ServerReflection.identifierString(ServerReflection.invoke(jigsaw, "target"));
Object jointType = ServerReflection.invoke(jigsaw, "jointType");
BlockFace front = faceOf(frontFacing(blockState));
BlockFace top = faceOf(topFacing(blockState));
Optional<ResourceId> pool = poolId == null || poolId.isEmpty() ? Optional.empty() : Optional.of(ResourceId.parse(poolId));
ConnectorMetadata metadata = readConnectorMetadata(jigsaw, info);
boolean aligned = jointType != null && jointType.toString().toUpperCase(Locale.ROOT).contains("ALIGN");
return new TemplatePool.JigsawConnector(
position,
front,
top,
pool,
name,
target,
aligned,
metadata.finalState(),
metadata.selectionPriority(),
metadata.placementPriority());
}
static ConnectorMetadata readConnectorMetadata(Object jigsaw, Object info) throws Exception {
String finalState = readNbtString(ServerReflection.invoke(info, "nbt"), FINAL_STATE_NBT_KEY);
return new ConnectorMetadata(
finalState == null || finalState.isBlank() ? Optional.empty() : Optional.of(finalState),
readIntAccessor(jigsaw, "selectionPriority"),
readIntAccessor(jigsaw, "placementPriority"));
}
record ConnectorMetadata(Optional<String> finalState, int selectionPriority, int placementPriority) {
}
static BlockFace faceOf(String facing) {
return switch (facing) {
case "up" -> BlockFace.UP;
case "down" -> BlockFace.DOWN;
case "south" -> BlockFace.SOUTH;
case "east" -> BlockFace.EAST;
case "west" -> BlockFace.WEST;
default -> BlockFace.NORTH;
};
}
private static String readNbtString(Object nbt, String key) throws Exception {
if (nbt == null) {
return null;
}
Method method = ServerReflection.findMethod(nbt.getClass(), "getString", 1);
if (method == null) {
throw new NoSuchMethodException("getString(String) on " + nbt.getClass().getName());
}
method.setAccessible(true);
Object value = method.invoke(nbt, key);
if (value instanceof String string) {
return string;
}
if (value instanceof Optional<?> optional) {
return optional.isPresent() ? String.valueOf(optional.get()) : null;
}
return value == null ? null : String.valueOf(value);
}
private static int readIntAccessor(Object value, String accessor) throws Exception {
Method method = ServerReflection.findMethod(value.getClass(), accessor);
if (method == null) {
throw new NoSuchMethodException(accessor + "() on " + value.getClass().getName());
}
method.setAccessible(true);
Object result = method.invoke(value);
if (result instanceof Number number) {
return number.intValue();
}
throw new IllegalStateException(accessor + " on " + value.getClass().getName() + " is not numeric");
}
private static String frontFacing(Object blockState) throws Exception {
return facing(blockState, "getFrontFacing", DEFAULT_FRONT);
}
private static String topFacing(Object blockState) throws Exception {
return facing(blockState, "getTopFacing", DEFAULT_TOP);
}
private static String facing(Object blockState, String jigsawBlockMethod, String fallback) throws Exception {
Class<?> jigsawBlock = Class.forName("net.minecraft.world.level.block.JigsawBlock");
Method read = jigsawBlock.getMethod(jigsawBlockMethod, Class.forName("net.minecraft.world.level.block.state.BlockState"));
Object direction = read.invoke(null, blockState);
if (direction == null) {
return fallback;
}
Method getName = direction.getClass().getMethod("getName");
getName.setAccessible(true);
return String.valueOf(getName.invoke(direction)).toLowerCase();
}
private static String templateLocationOf(Object element) throws Exception {
Method m = ServerReflection.findMethod(element.getClass(), "getTemplateLocation");
if (m == null) {
return null;
}
m.setAccessible(true);
Object id = m.invoke(element);
return ServerReflection.identifierString(id);
}
static PoolElementResolution resolvePoolElement(Object element) throws Exception {
if (element == null) {
return new PoolElementResolution(null, null, 0, 0);
}
if (!element.getClass().getSimpleName().endsWith(LIST_POOL_ELEMENT_SUFFIX)) {
return new PoolElementResolution(element, templateLocationOf(element), 0, 0);
}
Object rawElements = ServerReflection.invoke(element, "getElements");
if (!(rawElements instanceof List<?> elements)) {
throw new IllegalStateException("getElements on " + element.getClass().getName() + " is not a list");
}
if (elements.isEmpty()) {
return new PoolElementResolution(null, null, 1, 0);
}
PoolElementResolution primary = resolvePoolElement(elements.getFirst());
return new PoolElementResolution(
primary.physicalElement(),
primary.templateLocation(),
primary.listLevels() + 1,
primary.omittedElements() + elements.size() - 1
);
}
record PoolElementResolution(
Object physicalElement,
String templateLocation,
int listLevels,
int omittedElements
) {
}
}
@@ -0,0 +1,302 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure;
import art.arcane.iris.spi.IrisLogging;
import com.volmit.resource.ResourceId;
import org.bukkit.Bukkit;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Optional;
/**
* Reads the server's registries and resource manager by reflection, because they are version-bound server internals
* that Paper's api does not reach. Every lookup finds its members by name, so a server version that renamed one fails the
* read with the member's name instead of failing to link.
*/
final class ServerReflection {
private ServerReflection() {
}
/** The server's {@code MinecraftServer}. */
static Object minecraftServer() throws Exception {
Object craftServer = Bukkit.getServer();
Object dedicated = invoke(craftServer, "getHandle");
return invoke(dedicated, "getServer");
}
static Object resolveRegistryAccess(Object server) {
try {
Class<?> frozen = Class.forName("net.minecraft.core.RegistryAccess$Frozen");
for (Method m : server.getClass().getMethods()) {
if (m.getParameterCount() == 0 && frozen.isAssignableFrom(m.getReturnType())) {
m.setAccessible(true);
Object o = m.invoke(server);
if (o != null) {
return o;
}
}
}
Class<?> ra = Class.forName("net.minecraft.core.RegistryAccess");
for (Method m : server.getClass().getMethods()) {
if (m.getParameterCount() == 0 && ra.isAssignableFrom(m.getReturnType())) {
m.setAccessible(true);
Object o = m.invoke(server);
if (o != null) {
return o;
}
}
}
} catch (Throwable e) {
IrisLogging.reportError(e);
}
return null;
}
static Object lookupRegistry(Object registryAccess, String registryName) throws Exception {
Class<?> registries = Class.forName("net.minecraft.core.registries.Registries");
Object resourceKey = registries.getField(registryName).get(null);
Class<?> registryClass = Class.forName("net.minecraft.core.Registry");
Method registryOverload = null;
for (Method m : registryAccess.getClass().getMethods()) {
if (m.getName().equals("lookupOrThrow") && m.getParameterCount() == 1
&& m.getParameterTypes()[0].getName().endsWith("ResourceKey")
&& registryClass.isAssignableFrom(m.getReturnType())) {
registryOverload = m;
break;
}
}
if (registryOverload == null) {
for (Method m : registryAccess.getClass().getMethods()) {
if (m.getName().equals("lookupOrThrow") && m.getParameterCount() == 1
&& m.getParameterTypes()[0].getName().endsWith("ResourceKey")) {
registryOverload = m;
break;
}
}
}
if (registryOverload == null) {
throw new NoSuchMethodException("lookupOrThrow(ResourceKey) on " + registryAccess.getClass().getName());
}
registryOverload.setAccessible(true);
return registryOverload.invoke(registryAccess, resourceKey);
}
static Object registryGet(Object registry, ResourceId key) throws Exception {
Object id = identifierOf(key);
for (Method m : registry.getClass().getMethods()) {
if (m.getName().equals("getValue") && m.getParameterCount() == 1 && m.getParameterTypes()[0].getName().endsWith("Identifier")) {
m.setAccessible(true);
return m.invoke(registry, id);
}
}
for (Method m : registry.getClass().getMethods()) {
if (m.getName().equals("getOptional") && m.getParameterCount() == 1 && m.getParameterTypes()[0].getName().endsWith("Identifier")) {
m.setAccessible(true);
return unwrapOptional(m.invoke(registry, id));
}
}
return null;
}
static String registryKeyOf(Object registry, Object value) throws Exception {
if (value == null) {
return null;
}
for (Method m : registry.getClass().getMethods()) {
if (m.getName().equals("getKey") && m.getParameterCount() == 1) {
m.setAccessible(true);
Object id = m.invoke(registry, value);
String s = identifierString(id);
if (s != null) {
return s;
}
}
}
return null;
}
static Object identifierOf(ResourceId key) throws Exception {
Class<?> identifier = Class.forName("net.minecraft.resources.Identifier");
try {
Method fromNamespaceAndPath = identifier.getMethod("fromNamespaceAndPath", String.class, String.class);
return fromNamespaceAndPath.invoke(null, key.namespace(), key.path());
} catch (NoSuchMethodException e) {
Method withDefaultNamespace = identifier.getMethod("parse", String.class);
return withDefaultNamespace.invoke(null, key.toString());
}
}
static String identifierString(Object id) {
if (id == null) {
return null;
}
try {
Method getNamespace = id.getClass().getMethod("getNamespace");
Method getPath = id.getClass().getMethod("getPath");
getNamespace.setAccessible(true);
getPath.setAccessible(true);
return getNamespace.invoke(id) + ":" + getPath.invoke(id);
} catch (Throwable e) {
return id.toString();
}
}
static Object unwrapHolder(Object holder) {
if (holder == null) {
return null;
}
try {
Method value = findMethod(holder.getClass(), "value");
if (value != null) {
value.setAccessible(true);
return value.invoke(holder);
}
} catch (Throwable ignored) {
}
return holder;
}
static Object unwrapOptional(Object opt) {
if (opt == null) {
return null;
}
if (opt instanceof Optional<?> o) {
return o.orElse(null);
}
return opt;
}
static int readIntMember(Object value, String memberName) throws Exception {
Class<?> type = value.getClass();
while (type != null) {
try {
Field field = type.getDeclaredField(memberName);
field.setAccessible(true);
return coerceInt(field.get(value), memberName, value);
} catch (NoSuchFieldException ignored) {
type = type.getSuperclass();
}
}
Method method = findMethod(value.getClass(), memberName);
if (method != null) {
method.setAccessible(true);
return coerceInt(method.invoke(value), memberName, value);
}
throw new NoSuchFieldException(memberName + " on " + value.getClass().getName());
}
/**
* Members that are plain numbers on one server build are wrapper objects on another
* (JigsawStructure.maxDistanceFromCenter became a MaxDistance{horizontal, vertical} record).
* Numbers pass through; a wrapper contributes its horizontal component, else its largest
* integral component, so a distance bound is never under-read.
*/
private static int coerceInt(Object member, String memberName, Object owner) throws Exception {
if (member instanceof Number n) {
return n.intValue();
}
if (member == null) {
throw new NoSuchFieldException(memberName + " on " + owner.getClass().getName() + " is null");
}
Method horizontal = findMethod(member.getClass(), "horizontal");
if (horizontal != null && Number.class.isAssignableFrom(boxedType(horizontal.getReturnType()))) {
horizontal.setAccessible(true);
return ((Number) horizontal.invoke(member)).intValue();
}
Integer widest = null;
for (Field component : member.getClass().getDeclaredFields()) {
if (Modifier.isStatic(component.getModifiers())
|| !Number.class.isAssignableFrom(boxedType(component.getType()))) {
continue;
}
component.setAccessible(true);
Object componentValue = component.get(member);
if (componentValue instanceof Number n && (widest == null || n.intValue() > widest)) {
widest = n.intValue();
}
}
if (widest != null) {
return widest;
}
throw new NoSuchFieldException(memberName + " on " + owner.getClass().getName()
+ " is a " + member.getClass().getName() + " with no integral component");
}
private static Class<?> boxedType(Class<?> type) {
return type == int.class ? Integer.class : type;
}
static int readInt(Object o, String method) throws Exception {
Method m = o.getClass().getMethod(method);
m.setAccessible(true);
return ((Number) m.invoke(o)).intValue();
}
static Object staticField(String className, String fieldName) throws Exception {
Class<?> c = Class.forName(className);
Field f = c.getField(fieldName);
return f.get(null);
}
static Object invoke(Object target, String method) throws Exception {
Method m = findMethod(target.getClass(), method);
if (m == null) {
throw new NoSuchMethodException(method + " on " + target.getClass().getName());
}
m.setAccessible(true);
return m.invoke(target);
}
static Method findMethod(Class<?> type, String name) {
return findMethod(type, name, 0);
}
static Method findMethod(Class<?> type, String name, int parameterCount) {
Class<?> c = type;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (m.getName().equals(name) && m.getParameterCount() == parameterCount) {
return m;
}
}
c = c.getSuperclass();
}
for (Method m : type.getMethods()) {
if (m.getName().equals(name) && m.getParameterCount() == parameterCount) {
return m;
}
}
return null;
}
static Object freshRandomSource(long seed) throws Exception {
Class<?> randomSource = Class.forName("net.minecraft.util.RandomSource");
Method create = randomSource.getMethod("create", long.class);
return create.invoke(null, seed);
}
/** The message a failed read shows: the failure's message, else its class name. */
static String failureDetail(Throwable failure) {
String message = failure.getMessage();
return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message;
}
}
@@ -0,0 +1,99 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.toolworld;
import art.arcane.iris.core.modules.BlockEntities;
import art.arcane.iris.engine.object.prefab.TileData;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockFace;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import java.util.Optional;
/** Blocks, positions and block entities between the tool world api and Bukkit. */
final class BukkitToolBlocks {
private BukkitToolBlocks() {
}
static BlockPosition positionOf(Block block) {
return new BlockPosition(block.getX(), block.getY(), block.getZ());
}
static BlockPosition positionOf(Location location) {
return new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
static Block blockAt(World world, BlockPosition at) {
return world.getBlockAt(at.x(), at.y(), at.z());
}
/** The complete state of {@code data}, with every property. */
static BlockState stateOf(BlockData data) {
return BlockState.parse(data.getAsString());
}
/**
* The platform's data for {@code state}.
*
* @throws IllegalArgumentException when the platform has no such block or property
*/
static BlockData dataOf(BlockState state) {
return Bukkit.createBlockData(state.key());
}
/** The block entity of {@code block}; empty for a block without one. */
static Optional<BlockEntityData> blockEntityOf(Block block) {
return Optional.ofNullable(TileData.getTileState(block, false)).map(BlockEntities::of);
}
/**
* Writes {@code data} into the block entity of {@code block}, which must already be the block it was made for.
*
* @throws IllegalArgumentException when the block cannot take it, or the data is not in the format Iris stores
*/
static void applyBlockEntity(Block block, BlockEntityData data) {
TileData tile = BlockEntities.tileOf(data);
if (!TileData.setTileState(block, tile)) {
throw new IllegalArgumentException("The block " + block.getType() + " at " + block.getX() + ", " + block.getY()
+ ", " + block.getZ() + " cannot take block entity data of " + tile.getMaterialKey());
}
}
/** The api face for a Bukkit face; empty for the diagonals and for {@code SELF}. */
static Optional<BlockFace> faceOf(org.bukkit.block.BlockFace face) {
if (face == null) {
return Optional.empty();
}
return switch (face) {
case UP -> Optional.of(BlockFace.UP);
case DOWN -> Optional.of(BlockFace.DOWN);
case NORTH -> Optional.of(BlockFace.NORTH);
case SOUTH -> Optional.of(BlockFace.SOUTH);
case EAST -> Optional.of(BlockFace.EAST);
case WEST -> Optional.of(BlockFace.WEST);
default -> Optional.empty();
};
}
}
@@ -0,0 +1,107 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.toolworld;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.world.ToolItem;
import com.volmit.tooling.world.ToolText;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import java.util.List;
import java.util.Optional;
/**
* {@link ToolItem}s as Bukkit item stacks. The payload is a string in the item's persistent data; its presence is what
* makes a stack a tool item, so an empty payload is stored as an empty string.
*/
final class BukkitToolItems {
static final NamespacedKey PAYLOAD_KEY = new NamespacedKey("iris", "tool_payload");
private BukkitToolItems() {
}
/**
* A new stack of {@code item}. The name and lore are set as legacy strings, the way a plugin sets text on an item
* with the platform's own calls, so the stack shows what such a stack always showed.
*/
@SuppressWarnings("deprecation")
static ItemStack create(ToolItem item) {
Material material = Material.matchMaterial(item.item().toString());
if (material == null || !material.isItem()) {
throw new IllegalArgumentException("The platform has no item " + item.item());
}
ItemStack stack = new ItemStack(material);
ItemMeta meta = stack.getItemMeta();
if (meta == null) {
throw new IllegalStateException("The item " + item.item() + " cannot carry a name or a payload");
}
if (!item.name().isEmpty()) {
meta.setDisplayName(BukkitToolText.legacy(item.name()));
}
if (!item.lore().isEmpty()) {
meta.setLore(item.lore().stream().map(BukkitToolText::legacy).toList());
}
if (item.glowing()) {
meta.setEnchantmentGlintOverride(true);
}
meta.getPersistentDataContainer().set(PAYLOAD_KEY, PersistentDataType.STRING, item.payload());
if (!stack.setItemMeta(meta)) {
throw new IllegalStateException("The metadata of tool item " + item.item() + " was rejected");
}
return stack;
}
/** The tool item {@code stack} is; empty for nothing, air or a stack without the tool payload. */
static Optional<ToolItem> read(ItemStack stack) {
if (stack == null || stack.getType() == Material.AIR || !stack.hasItemMeta()) {
return Optional.empty();
}
ItemMeta meta = stack.getItemMeta();
if (meta == null) {
return Optional.empty();
}
PersistentDataContainer data = meta.getPersistentDataContainer();
String payload = data.get(PAYLOAD_KEY, PersistentDataType.STRING);
if (payload == null) {
return Optional.empty();
}
return Optional.of(new ToolItem(
ResourceId.parse(stack.getType().getKey().toString()),
meta.hasDisplayName() ? plainText(meta.displayName()) : ToolText.EMPTY,
meta.hasLore() ? lore(meta) : List.of(),
Boolean.TRUE.equals(meta.getEnchantmentGlintOverride()),
payload));
}
private static List<ToolText> lore(ItemMeta meta) {
List<Component> lines = meta.lore();
return lines == null ? List.of() : lines.stream().map(BukkitToolItems::plainText).toList();
}
private static ToolText plainText(Component component) {
return component == null ? ToolText.EMPTY : ToolText.plain(PlainTextComponentSerializer.plainText().serialize(component));
}
}
@@ -0,0 +1,172 @@
/*
* 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.toolworld;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.data.MaterialBlock;
import art.arcane.volmlib.util.inventorygui.UIElement;
import art.arcane.volmlib.util.inventorygui.UIPaneDecorator;
import art.arcane.volmlib.util.inventorygui.UIWindow;
import art.arcane.volmlib.util.inventorygui.WindowResolution;
import com.volmit.tooling.world.MenuButton;
import com.volmit.tooling.world.MenuClick;
import com.volmit.tooling.world.ToolItem;
import com.volmit.tooling.world.ToolMenu;
import com.volmit.tooling.world.ToolText;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/** The chest menus tools open for players, as VolmLib inventory windows. */
final class BukkitToolMenus {
private static final int MAX_TITLE_LENGTH = 32;
private static final int SLOTS_PER_ROW = ToolMenu.SLOTS_PER_ROW;
private static final int CENTER_SLOT_OFFSET = SLOTS_PER_ROW / 2;
private final Map<UUID, OpenMenu> windows = new ConcurrentHashMap<>();
/**
* The window a player has open and what it was opened with. A menu with the rows and title of the open one fills the
* same window, as a page of buttons changing under the player's cursor; the close handler is the latest menu's.
*/
private static final class OpenMenu {
private final UIWindow window;
private final int rows;
private final String title;
private volatile Runnable onClose;
private OpenMenu(UIWindow window, int rows, String title, Runnable onClose) {
this.window = window;
this.rows = rows;
this.title = title;
this.onClose = onClose;
}
private boolean showsSameFrame(ToolMenu menu) {
return rows == menu.rows() && title.equals(shortened(menu.title()));
}
}
/** Opens {@code menu} for {@code viewer}, replacing the one they had. Runs on the viewer's thread. */
void open(BukkitToolPlayer viewer, ToolMenu menu) {
Player player = viewer.bukkit();
OpenMenu open = windows.get(player.getUniqueId());
if (open != null && open.showsSameFrame(menu)) {
fill(open, viewer, menu);
return;
}
close(player);
UUID playerId = player.getUniqueId();
UIWindow window = new UIWindow(BukkitPlatform.volmitPlugin(), player);
OpenMenu created = new OpenMenu(window, menu.rows(), shortened(menu.title()), menu.onClose());
window.setResolution(WindowResolution.W9_H6);
window.setViewportHeight(menu.rows());
window.setDecorator(new UIPaneDecorator(Material.BLACK_STAINED_GLASS_PANE));
window.setTitle(created.title);
window.onClosed(closed -> {
windows.remove(playerId, created);
runGuarded(created.onClose, "menu close handler of " + player.getName());
});
window.batch(() -> addButtons(window, viewer, menu));
windows.put(playerId, created);
window.open();
}
/** Puts the buttons of {@code menu} in the window {@code open} holds, telling the menu it replaces that it closed. */
private void fill(OpenMenu open, BukkitToolPlayer viewer, ToolMenu menu) {
Runnable replaced = open.onClose;
open.onClose = menu.onClose();
open.window.batch(() -> {
open.window.clearElements();
addButtons(open.window, viewer, menu);
});
runGuarded(replaced, "menu close handler of " + viewer.name());
}
private static void addButtons(UIWindow window, BukkitToolPlayer viewer, ToolMenu menu) {
for (MenuButton button : menu.buttons()) {
window.setElement(positionOf(button.slot()), button.slot() / SLOTS_PER_ROW, element(viewer, button));
}
}
/** Closes the player's menu; does nothing when none is open. Runs on the player's thread. */
void close(Player player) {
OpenMenu open = windows.remove(player.getUniqueId());
if (open != null) {
open.window.close();
}
}
void forget(UUID playerId) {
windows.remove(playerId);
}
private static UIElement element(BukkitToolPlayer viewer, MenuButton button) {
ToolItem icon = button.icon();
Material material = Material.matchMaterial(icon.item().toString());
if (material == null || !material.isItem()) {
throw new IllegalArgumentException("The platform has no item " + icon.item());
}
UIElement element = new UIElement("slot-" + button.slot())
.setMaterial(new MaterialBlock(material))
.setName(BukkitToolText.legacy(icon.name()))
.setEnchanted(icon.glowing());
icon.lore().forEach(line -> element.addLore(BukkitToolText.legacy(line)));
element.onLeftClick(clicked -> click(viewer, button, false, false));
element.onRightClick(clicked -> click(viewer, button, true, false));
element.onShiftLeftClick(clicked -> click(viewer, button, false, true));
element.onShiftRightClick(clicked -> click(viewer, button, true, true));
element.onMiddleClick(clicked -> runGuarded(
() -> button.action().accept(new MenuClick(viewer, false, false, true)),
"menu button of " + viewer.name()));
return element;
}
private static void click(BukkitToolPlayer viewer, MenuButton button, boolean right, boolean shift) {
runGuarded(() -> button.action().accept(new MenuClick(viewer, right, shift)), "menu button of " + viewer.name());
}
/** The window counts positions from its middle column, left of it negative; a slot counts from the left. */
static int positionOf(int slot) {
return slot % SLOTS_PER_ROW - CENTER_SLOT_OFFSET;
}
/** The title in the legacy codes the window takes, cut to what it can show without leaving half a code. */
static String shortened(ToolText title) {
String legacy = BukkitToolText.legacy(title);
if (legacy.length() <= MAX_TITLE_LENGTH) {
return legacy;
}
String cut = legacy.substring(0, MAX_TITLE_LENGTH);
return cut.endsWith("§") ? cut.substring(0, MAX_TITLE_LENGTH - 1) : cut;
}
private static void runGuarded(Runnable task, String what) {
try {
task.run();
} catch (RuntimeException failure) {
IrisLogging.reportError("A tool failed in the " + what + ".", failure);
}
}
}
@@ -0,0 +1,253 @@
/*
* 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.toolworld;
import art.arcane.iris.core.service.BoardSVC;
import art.arcane.iris.core.service.BukkitToolingSender;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.plugin.ComponentMessenger;
import art.arcane.volmlib.util.plugin.ComponentText;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.Sender;
import com.volmit.tooling.world.Particle;
import com.volmit.tooling.world.ToolItem;
import com.volmit.tooling.world.ToolMenu;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolText;
import com.volmit.tooling.world.ToolWorld;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/** A Bukkit player as a tool sees them. Readers must run on the player's thread; changes hop there by themselves. */
final class BukkitToolPlayer implements ToolPlayer {
private final Player player;
private final OpenToolWorlds worlds;
private final ToolPlayers players;
private final BukkitToolMenus menus;
BukkitToolPlayer(Player player, OpenToolWorlds worlds, ToolPlayers players, BukkitToolMenus menus) {
this.player = player;
this.worlds = worlds;
this.players = players;
this.menus = menus;
}
Player bukkit() {
return player;
}
@Override
public UUID id() {
return player.getUniqueId();
}
@Override
public String name() {
return player.getName();
}
@Override
public Sender sender() {
return new BukkitToolingSender(player);
}
@Override
public Optional<ToolWorld> world() {
return worlds.forWorld(player.getWorld()).map(world -> world);
}
@Override
public BlockPosition position() {
return BukkitToolBlocks.positionOf(player.getLocation());
}
@Override
public float yaw() {
return player.getLocation().getYaw();
}
@Override
public float pitch() {
return player.getLocation().getPitch();
}
@Override
public Optional<BlockPosition> targetBlock(int maxDistance) {
return Optional.ofNullable(player.getTargetBlockExact(maxDistance)).map(BukkitToolBlocks::positionOf);
}
@Override
public boolean sneaking() {
return player.isSneaking();
}
@Override
public void run(Runnable task) {
J.runEntity(player, task);
}
@Override
public CompletableFuture<Boolean> teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch) {
if (!(world instanceof BukkitToolWorld target)) {
return CompletableFuture.failedFuture(new IllegalArgumentException("Not a tool world of this platform: " + world));
}
CompletableFuture<Boolean> arrived = new CompletableFuture<>();
boolean scheduled = J.runEntity(player, () -> BukkitPlatform
.teleportAsync(player, new Location(target.bukkit(), x, y, z, yaw, pitch))
.whenComplete((success, failure) -> {
if (failure != null) {
arrived.completeExceptionally(failure);
} else {
arrived.complete(Boolean.TRUE.equals(success));
}
}));
if (!scheduled) {
arrived.complete(false);
}
return arrived;
}
@Override
public void creative(boolean on) {
J.runEntity(player, () -> {
if (on) {
players.rememberModeBeforeCreative(player);
player.setGameMode(GameMode.CREATIVE);
return;
}
players.restoreGameMode(player);
});
}
@Override
public void message(ToolText text) {
J.runEntity(player, () -> ComponentMessenger.send(player, ComponentText.component(BukkitToolText.component(text))));
}
@Override
public void actionBar(ToolText text) {
J.runEntity(player, () -> player.sendActionBar(BukkitToolText.component(text)));
}
@Override
public void sound(ResourceId sound, float volume, float pitch) {
J.runEntity(player, () -> player.playSound(player.getLocation(), sound.toString(), volume, pitch));
}
@Override
public void sidebar(ToolText title, List<ToolText> lines) {
BoardSVC board = IrisServices.getOrNull(BoardSVC.class);
if (board == null) {
return;
}
J.runEntity(player, () -> board.applyToolSidebar(player,
new BoardSVC.ToolSidebar(player.getWorld().getUID(), title, lines)));
}
@Override
public void hideSidebar() {
BoardSVC board = IrisServices.getOrNull(BoardSVC.class);
if (board != null) {
board.clearToolSidebar(player);
}
}
@Override
public void particles(List<Particle> dust) {
List<Particle> specks = List.copyOf(dust);
J.runEntity(player, () -> specks.forEach(this::showDust));
}
@Override
public boolean give(ToolItem item) {
ItemStack stack = BukkitToolItems.create(item);
if (J.isOwnedByCurrentRegion(player)) {
return player.getInventory().addItem(stack).isEmpty();
}
J.runEntity(player, () -> player.getInventory().addItem(stack));
return true;
}
@Override
public Optional<ToolItem> held() {
return BukkitToolItems.read(player.getInventory().getItemInMainHand());
}
@Override
public void openMenu(ToolMenu menu) {
J.runEntity(player, () -> menus.open(this, menu));
}
@Override
public void closeMenu() {
J.runEntity(player, () -> menus.close(player));
}
/**
* Sends the player to where they were before they entered a tool world, or to the spawn of the main world when that
* is not known any more, and gives back the game mode they had. Completes with whether they arrived.
*/
CompletableFuture<Boolean> returnToOrigin() {
CompletableFuture<Boolean> returned = new CompletableFuture<>();
boolean scheduled = J.runEntity(player, () -> {
menus.close(player);
players.restoreGameMode(player);
Location destination = players.takeOrigin(player)
.filter(this::isOutsideToolWorlds)
.orElseGet(() -> Bukkit.getWorlds().getFirst().getSpawnLocation());
BukkitPlatform.teleportAsync(player, destination).whenComplete((success, failure) -> {
if (failure != null) {
returned.completeExceptionally(failure);
} else {
returned.complete(Boolean.TRUE.equals(success));
}
});
});
if (!scheduled) {
returned.complete(false);
}
return returned;
}
private boolean isOutsideToolWorlds(Location location) {
return location.getWorld() != null && worlds.forWorld(location.getWorld()).isEmpty();
}
private void showDust(Particle speck) {
org.bukkit.Particle.DustOptions options = new org.bukkit.Particle.DustOptions(Color.fromRGB(speck.rgb()), speck.size());
player.spawnParticle(org.bukkit.Particle.DUST, speck.x(), speck.y(), speck.z(), 1, 0.0D, 0.0D, 0.0D, 0.0D, options);
}
@Override
public String toString() {
return "tool player " + player.getName();
}
}
@@ -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.toolworld;
import com.volmit.tooling.world.TextColor;
import com.volmit.tooling.world.ToolText;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import java.util.EnumMap;
import java.util.Map;
/** {@link ToolText} as the text Bukkit shows: an Adventure component, or the legacy string the platform's older calls take. */
final class BukkitToolText {
private static final char SECTION = '§';
private static final Map<TextColor, NamedTextColor> COLORS = new EnumMap<>(Map.ofEntries(
Map.entry(TextColor.BLACK, NamedTextColor.BLACK),
Map.entry(TextColor.DARK_BLUE, NamedTextColor.DARK_BLUE),
Map.entry(TextColor.DARK_GREEN, NamedTextColor.DARK_GREEN),
Map.entry(TextColor.DARK_AQUA, NamedTextColor.DARK_AQUA),
Map.entry(TextColor.DARK_RED, NamedTextColor.DARK_RED),
Map.entry(TextColor.DARK_PURPLE, NamedTextColor.DARK_PURPLE),
Map.entry(TextColor.GOLD, NamedTextColor.GOLD),
Map.entry(TextColor.GRAY, NamedTextColor.GRAY),
Map.entry(TextColor.DARK_GRAY, NamedTextColor.DARK_GRAY),
Map.entry(TextColor.BLUE, NamedTextColor.BLUE),
Map.entry(TextColor.GREEN, NamedTextColor.GREEN),
Map.entry(TextColor.AQUA, NamedTextColor.AQUA),
Map.entry(TextColor.RED, NamedTextColor.RED),
Map.entry(TextColor.LIGHT_PURPLE, NamedTextColor.LIGHT_PURPLE),
Map.entry(TextColor.YELLOW, NamedTextColor.YELLOW),
Map.entry(TextColor.WHITE, NamedTextColor.WHITE)));
private BukkitToolText() {
}
static Component component(ToolText text) {
TextComponent.Builder whole = Component.text();
for (ToolText.Span span : text.spans()) {
Component piece = Component.text(span.text());
if (span.color() != null) {
piece = piece.color(COLORS.get(span.color()));
}
piece = piece
.decoration(TextDecoration.BOLD, span.bold() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET)
.decoration(TextDecoration.ITALIC, span.italic() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET)
.decoration(TextDecoration.STRIKETHROUGH,
span.strikethrough() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET);
whole.append(piece);
}
return whole.build();
}
/** The legacy string of {@code text}: formatting signs for the colour and style of each span, a reset between uncoloured ones. */
static String legacy(ToolText text) {
StringBuilder legacy = new StringBuilder();
for (ToolText.Span span : text.spans()) {
if (span.color() != null) {
legacy.append(SECTION).append(span.color().code());
} else if (!legacy.isEmpty()) {
legacy.append(SECTION).append('r');
}
if (span.bold()) {
legacy.append(SECTION).append('l');
}
if (span.italic()) {
legacy.append(SECTION).append('o');
}
if (span.strikethrough()) {
legacy.append(SECTION).append('m');
}
legacy.append(span.text());
}
return legacy.toString();
}
}
@@ -0,0 +1,408 @@
/*
* 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.toolworld;
import art.arcane.iris.core.nms.INMS;
import art.arcane.iris.core.project.IrisProject;
import art.arcane.iris.core.runtime.InPlaceChunkRegenerator;
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
import art.arcane.iris.core.runtime.StudioPainterSlots;
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity;
import art.arcane.iris.core.runtime.StudioSlotOccupant;
import art.arcane.iris.core.service.StudioSVC;
import art.arcane.iris.engine.data.chunk.TerrainChunk;
import art.arcane.iris.engine.platform.studio.TerrainChunkCanvas;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.util.common.scheduling.J;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.geometry.ChunkPos;
import com.volmit.object.BlockEntityData;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolWorld;
import com.volmit.tooling.world.ToolWorldListener;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* One tool world on Bukkit: a studio world whose chunks come from the tool's painter. It exists, registered, from before
* Bukkit creates the world until the world is unloaded; {@link #bind} gives it the Bukkit world once that exists.
*/
final class BukkitToolWorld implements ToolWorld, StudioSlotOccupant {
private static final int CHUNK_SHIFT = 4;
private final String packName;
private final String name;
private final String storageName;
private final ToolWorldListener listener;
private final StudioPainterSlots.Slot slot;
private final PendingBlockEntities pending;
private final ToolWorldPresence presence = new ToolWorldPresence();
private final OpenToolWorlds registry;
private final ToolPlayers players;
private final AtomicBoolean closing = new AtomicBoolean();
private final AtomicBoolean gone = new AtomicBoolean();
private final CompletableFuture<Void> closed = new CompletableFuture<>();
private final IrisProject project;
private volatile World world;
BukkitToolWorld(
String packName,
String name,
String storageName,
ToolWorldListener listener,
StudioPainterSlots.Slot slot,
PendingBlockEntities pending,
OpenToolWorlds registry,
ToolPlayers players
) {
this.packName = packName;
this.name = name;
this.storageName = storageName;
this.listener = listener;
this.slot = slot;
this.pending = pending;
this.registry = registry;
this.players = players;
this.project = new IrisProject(new File(workspaceFolder(), packName));
}
/** The studio project this world is, as the studio service shows the open studio to its commands. */
@Override
public IrisProject project() {
return project;
}
private static File workspaceFolder() {
StudioSVC studios = IrisServices.getOrNull(StudioSVC.class);
return studios == null ? new File(".") : studios.getWorkspaceFolder();
}
String packName() {
return packName;
}
/** The logical name of the world's storage, which the generator finds its painter by. */
String storageName() {
return storageName;
}
/** Gives the world its Bukkit world, once Bukkit has created it. */
void bind(World created) {
world = Objects.requireNonNull(created, "created");
registry.bound(this);
}
boolean isBound() {
return world != null;
}
UUID worldId() {
return bukkit().getUID();
}
World bukkit() {
World bound = world;
if (bound == null) {
throw new IllegalStateException("The tool world " + name + " is not created yet");
}
return bound;
}
ToolWorldPresence presence() {
return presence;
}
@Override
public String name() {
return name;
}
@Override
public int minY() {
return bukkit().getMinHeight();
}
@Override
public int maxY() {
return bukkit().getMaxHeight();
}
@Override
public List<ToolPlayer> players() {
return bukkit().getPlayers().stream().<ToolPlayer>map(players::of).toList();
}
@Override
public boolean owns(BlockPosition at) {
return J.isOwnedByCurrentRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT);
}
@Override
public void run(BlockPosition at, Runnable task) {
World target = bukkit();
Runnable guarded = () -> runGuarded(task, "task at " + at);
if (!J.runRegion(target, at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, guarded)) {
IrisLogging.warn("Tool world %s could not schedule a task at %s.", name, at);
}
}
@Override
public <T> CompletableFuture<T> call(BlockPosition at, Supplier<T> task) {
CompletableFuture<T> result = new CompletableFuture<>();
boolean scheduled = J.runRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, () -> {
try {
result.complete(task.get());
} catch (Throwable failure) {
result.completeExceptionally(failure);
}
});
if (!scheduled) {
result.completeExceptionally(new IllegalStateException("Tool world " + name + " could not schedule a task at " + at));
}
return result;
}
@Override
public BlockState block(BlockPosition at) {
return BukkitToolBlocks.stateOf(ownedBlock(at).getBlockData());
}
@Override
public Optional<BlockEntityData> blockEntity(BlockPosition at) {
return BukkitToolBlocks.blockEntityOf(ownedBlock(at));
}
@Override
public void setBlock(BlockPosition at, BlockState state, Optional<BlockEntityData> data) {
Block block = ownedBlock(at);
block.setBlockData(BukkitToolBlocks.dataOf(state), false);
data.ifPresent(entity -> BukkitToolBlocks.applyBlockEntity(block, entity));
}
@Override
public boolean loaded(ChunkPos chunk) {
return bukkit().isChunkLoaded(chunk.x(), chunk.z());
}
@Override
public CompletableFuture<Void> repaint(Collection<ChunkPos> chunks) {
if (isClosed()) {
return CompletableFuture.failedFuture(new IllegalStateException("Tool world " + name + " is closed"));
}
List<CompletableFuture<Void>> repaints = chunks.stream().distinct().map(this::repaintChunk).toList();
return CompletableFuture.allOf(repaints.toArray(CompletableFuture[]::new));
}
@Override
public CompletableFuture<Void> close() {
if (!closing.compareAndSet(false, true)) {
return closed;
}
sendPlayersBack()
.thenCompose(ignored -> StudioOpenCoordinator.get().closeToolWorld(bukkit(), project))
.whenComplete((result, failure) -> finishClose(result, failure));
return closed;
}
@Override
public Optional<String> closeRefusal() {
try {
return listener.closeRefusal();
} catch (Throwable failure) {
IrisLogging.reportError("The listener of tool world " + name + " failed.", failure);
return Optional.empty();
}
}
@Override
public CompletableFuture<Void> prepareReplacement(Optional<UUID> requestedBy) {
Optional<ToolPlayer> by = requestedBy.map(Bukkit::getPlayer).map(players::of);
try {
return listener.closing(by);
} catch (Throwable failure) {
IrisLogging.reportError("The listener of tool world " + name + " failed.", failure);
return CompletableFuture.completedFuture(null);
}
}
/** The tool's listener asked, with {@code fallback} as the answer when it throws. Runs on the caller's thread. */
boolean ask(Function<ToolWorldListener, Boolean> question, boolean fallback) {
try {
return question.apply(listener);
} catch (Throwable failure) {
IrisLogging.reportError("The listener of tool world " + name + " failed.", failure);
return fallback;
}
}
/** Tells the listener something. Runs on the caller's thread. */
void tell(Consumer<ToolWorldListener> news) {
ask(listener -> {
news.accept(listener);
return true;
}, true);
}
/** A chunk of the world loaded: writes the block entities its paint asked for, then tells the tool. */
void chunkLoaded(Chunk chunk) {
for (PaintedBlockEntity entity : pending.take(chunk.getX(), chunk.getZ())) {
applyPainted(chunk, entity);
}
tell(toolListener -> toolListener.chunkLoaded(chunk.getX(), chunk.getZ()));
}
/** Bukkit unloaded the world, whoever asked: it is gone for the tool and for the host. */
void unloaded() {
if (!gone.compareAndSet(false, true)) {
return;
}
StudioPainterSlots.remove(storageName);
registry.unregister(this);
releaseStudioSlot();
tell(ToolWorldListener::closed);
}
private void releaseStudioSlot() {
StudioSVC studios = IrisServices.getOrNull(StudioSVC.class);
if (studios != null) {
studios.releaseStudioSlot(this);
}
}
/** Called by the opener when creating the world failed: nothing of it is left to unload. */
void abandon() {
StudioPainterSlots.remove(storageName);
registry.unregister(this);
}
private void finishClose(StudioOpenCoordinator.StudioCloseResult result, Throwable failure) {
unloaded();
Throwable cause = failure != null ? unwrap(failure) : result == null ? null : result.failureCause();
if (cause == null) {
closed.complete(null);
return;
}
closed.completeExceptionally(cause);
}
private CompletableFuture<Void> sendPlayersBack() {
List<CompletableFuture<Boolean>> departures = bukkit().getPlayers().stream()
.map(player -> players.of(player).returnToOrigin())
.toList();
return CompletableFuture.allOf(departures.toArray(CompletableFuture[]::new));
}
private record Repainted(TerrainChunk terrain, TerrainChunkCanvas canvas) {
}
private CompletableFuture<Void> repaintChunk(ChunkPos position) {
World target = bukkit();
AtomicReference<Repainted> repainted = new AtomicReference<>();
CompletableFuture<Void> painting = J.afut(() -> repainted.set(paintAgain(target, position)));
CompletableFuture<Chunk> loading = target.getChunkAtAsync(position.x(), position.z());
return painting.thenCombine(loading, (ignored, chunk) -> chunk)
.thenCompose(chunk -> J.runRegionFuture(target, position.x(), position.z(),
() -> writeRepainted(target, chunk, repainted.get())));
}
private Repainted paintAgain(World target, ChunkPos position) {
TerrainChunk terrain = TerrainChunk.create(target);
TerrainChunkCanvas canvas = TerrainChunkCanvas.onPlatform(terrain);
slot.painter().paint(position.x(), position.z(), canvas);
return new Repainted(terrain, canvas);
}
private void writeRepainted(World target, Chunk chunk, Repainted repainted) {
if (!INMS.get().applyChunkBlocks(chunk, repainted.terrain())) {
InPlaceChunkRegenerator.applyBlockDiffs(chunk, repainted.terrain().getChunkData(),
target.getMinHeight(), target.getMaxHeight());
}
repainted.canvas().blockEntities().forEach(entity -> applyPainted(chunk, entity));
target.refreshChunk(chunk.getX(), chunk.getZ());
}
private void applyPainted(Chunk chunk, PaintedBlockEntity entity) {
Block block = chunk.getBlock(entity.x(), entity.y(), entity.z());
try {
BukkitToolBlocks.applyBlockEntity(block, entity.data());
} catch (RuntimeException failure) {
IrisLogging.reportError("Tool world " + name + " could not write a block entity at "
+ block.getX() + ", " + block.getY() + ", " + block.getZ() + ".", failure);
}
}
private Block ownedBlock(BlockPosition at) {
requireOpen();
if (!owns(at)) {
throw new IllegalStateException("The calling thread does not own " + at + " in tool world " + name);
}
return BukkitToolBlocks.blockAt(bukkit(), at);
}
private void requireOpen() {
if (isClosed()) {
throw new IllegalStateException("Tool world " + name + " is closed");
}
bukkit();
}
private boolean isClosed() {
return closing.get() || gone.get();
}
private void runGuarded(Runnable task, String what) {
try {
task.run();
} catch (Throwable failure) {
IrisLogging.reportError("A task of tool world " + name + " failed: " + what + ".", failure);
}
}
private static Throwable unwrap(Throwable failure) {
Throwable cursor = failure;
while (cursor instanceof CompletionException && cursor.getCause() != null) {
cursor = cursor.getCause();
}
return cursor;
}
@Override
public String toString() {
return "tool world " + name;
}
}
@@ -0,0 +1,86 @@
/*
* 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.toolworld;
import art.arcane.iris.core.tooling.ToolWorldsHost;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.common.plugin.IrisService;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolWorlds;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Tool worlds on Bukkit: the platform side of {@code com.volmit.tooling.world}. It keeps the open tool worlds and the
* tool players, listens for the events that concern them ({@link ToolWorldEvents}), and hands each pack its
* {@link ToolWorlds} through {@link ToolWorldsHost}, which core reaches it by.
*/
public final class BukkitToolWorldService implements IrisService, ToolWorldsHost {
private static final long CLOSING_WAIT_SECONDS = 30L;
private final OpenToolWorlds worlds = new OpenToolWorlds();
private final ToolPlayers players = new ToolPlayers(worlds);
private final ToolWorldEvents events = new ToolWorldEvents(worlds, players);
@Override
public void onEnable() {
Bukkit.getPluginManager().registerEvents(events, BukkitPlatform.plugin());
}
@Override
public void onDisable() {
HandlerList.unregisterAll(events);
List<BukkitToolWorld> open = worlds.all();
awaitClosing(open);
open.forEach(BukkitToolWorld::unloaded);
}
/** Lets every tool hear that its world is closing, as a replacement does, so it can save what it holds before the world is gone. */
private static void awaitClosing(List<BukkitToolWorld> open) {
CompletableFuture<?>[] closing = open.stream()
.map(world -> world.prepareReplacement(Optional.empty()))
.toArray(CompletableFuture[]::new);
try {
CompletableFuture.allOf(closing).get(CLOSING_WAIT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
} catch (ExecutionException | TimeoutException notReady) {
IrisLogging.reportError("A tool world was not ready to close when Iris stopped.", notReady);
}
}
@Override
public ToolWorlds worldsOf(String packName) {
return new BukkitToolWorlds(packName, worlds, players);
}
/** The tool player for {@code player}, the same object for as long as the player is online. */
public ToolPlayer playerOf(Player player) {
return players.of(player);
}
}
@@ -0,0 +1,117 @@
/*
* 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.toolworld;
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
import art.arcane.iris.core.runtime.StudioPainterSlots;
import art.arcane.iris.core.service.StudioSVC;
import art.arcane.iris.spi.IrisServices;
import com.volmit.tooling.world.ToolWorld;
import com.volmit.tooling.world.ToolWorldDenied;
import com.volmit.tooling.world.ToolWorldSpec;
import com.volmit.tooling.world.ToolWorlds;
import org.bukkit.World;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
/**
* The tool worlds of one pack on Bukkit. A tool world is created through the studio's own world creation, with the
* tool's painter installed first so that even the first chunk is the tool's.
*/
final class BukkitToolWorlds implements ToolWorlds {
private static final String STORAGE_NAME_PREFIX = "iris-";
private static final long TOOL_WORLD_SEED = 1337L;
private final String packName;
private final OpenToolWorlds registry;
private final ToolPlayers players;
BukkitToolWorlds(String packName, OpenToolWorlds registry, ToolPlayers players) {
this.packName = packName;
this.registry = registry;
this.players = players;
}
@Override
public CompletableFuture<ToolWorld> open(ToolWorldSpec spec) {
Optional<String> denial = StudioSVC.packAdmissionDenial(packName, StudioOpenCoordinator.StudioOpenKind.TOOL);
if (denial.isPresent()) {
return CompletableFuture.failedFuture(new ToolWorldDenied(denial.get()));
}
PendingBlockEntities pending = new PendingBlockEntities();
StudioPainterSlots.Slot slot = new StudioPainterSlots.Slot(spec.painter(), pending::add);
String storageName = STORAGE_NAME_PREFIX + UUID.randomUUID();
BukkitToolWorld toolWorld = new BukkitToolWorld(packName, spec.name(), storageName, spec.listener(), slot, pending,
registry, players);
if (!registry.register(toolWorld)) {
return CompletableFuture.failedFuture(new IllegalStateException(
"A tool world called " + spec.name() + " is open already in pack " + packName));
}
StudioPainterSlots.install(storageName, slot);
CompletableFuture<ToolWorld> opened = new CompletableFuture<>();
IrisServices.get(StudioSVC.class).occupyStudioSlot(
toolWorld,
() -> StudioOpenCoordinator.get().open(openRequest(storageName, toolWorld))
).whenComplete((result, failure) -> {
if (failure != null) {
toolWorld.abandon();
opened.completeExceptionally(unwrap(failure));
return;
}
opened.complete(toolWorld);
});
return opened;
}
@Override
public Optional<ToolWorld> find(String name) {
return registry.forName(packName, name).filter(BukkitToolWorld::isBound).map(world -> world);
}
private StudioOpenCoordinator.StudioOpenRequest openRequest(String storageName, BukkitToolWorld toolWorld) {
return new StudioOpenCoordinator.StudioOpenRequest(
packName,
toolWorld.project(),
null,
TOOL_WORLD_SEED,
storageName,
null,
StudioOpenCoordinator.StudioOpenKind.TOOL,
false,
null,
world -> prepare(toolWorld, world),
System.nanoTime());
}
private static void prepare(BukkitToolWorld toolWorld, World created) {
toolWorld.bind(created);
ToolWorldRules.apply(created);
}
private static Throwable unwrap(Throwable failure) {
Throwable cursor = failure;
while (cursor instanceof CompletionException && cursor.getCause() != null) {
cursor = cursor.getCause();
}
return cursor;
}
}
@@ -0,0 +1,95 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.toolworld;
import art.arcane.iris.core.IrisWorldStorage;
import org.bukkit.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* The tool worlds that are open or opening: found by the Bukkit world they live in, and by the tool's name for them
* within a pack. A world is registered before Bukkit has created it, since chunks load while it is created; until it
* is bound to its Bukkit world it is found by the logical name of its storage, which the creator fixes beforehand.
*/
final class OpenToolWorlds {
private final Map<String, BukkitToolWorld> byStorageName = new ConcurrentHashMap<>();
private final Map<UUID, BukkitToolWorld> byWorldId = new ConcurrentHashMap<>();
private final Map<String, BukkitToolWorld> byPackAndName = new ConcurrentHashMap<>();
/**
* Registers {@code world} under its storage name and the name its tool gave it.
*
* @return whether the tool's name was free; when it is not, nothing is registered
*/
boolean register(BukkitToolWorld world) {
if (byPackAndName.putIfAbsent(packAndName(world.packName(), world.name()), world) != null) {
return false;
}
byStorageName.put(world.storageName(), world);
return true;
}
/** Records the Bukkit world of {@code world}, which is bound already. */
void bound(BukkitToolWorld world) {
byWorldId.put(world.worldId(), world);
}
void unregister(BukkitToolWorld world) {
byStorageName.remove(world.storageName(), world);
byPackAndName.remove(packAndName(world.packName(), world.name()), world);
if (world.isBound()) {
byWorldId.remove(world.worldId(), world);
}
}
/** The tool world that {@code world} is; empty for every other world. */
Optional<BukkitToolWorld> forWorld(World world) {
if (world == null) {
return Optional.empty();
}
BukkitToolWorld bound = byWorldId.get(world.getUID());
return bound != null ? Optional.of(bound) : forOpeningWorld(world);
}
Optional<BukkitToolWorld> forName(String packName, String name) {
return Optional.ofNullable(byPackAndName.get(packAndName(packName, name)));
}
List<BukkitToolWorld> all() {
return new ArrayList<>(byStorageName.values());
}
private Optional<BukkitToolWorld> forOpeningWorld(World world) {
boolean anyOpening = byStorageName.values().stream().anyMatch(candidate -> !candidate.isBound());
if (!anyOpening) {
return Optional.empty();
}
return Optional.ofNullable(byStorageName.get(IrisWorldStorage.logicalName(world)));
}
private static String packAndName(String packName, String name) {
return packName + "/" + name;
}
}
@@ -0,0 +1,51 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.toolworld;
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity;
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedChunk;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* The block entities a painter asked for in chunks that are generated but not loaded yet. A chunk is painted on a
* generation thread and its block entities can only be written once it is live, so they wait here for its load.
*/
final class PendingBlockEntities {
private static final int INT_BITS = 32;
private final Map<Long, List<PaintedBlockEntity>> byChunk = new ConcurrentHashMap<>();
/** Keeps what a paint of a chunk asked for; a later paint of the same chunk replaces it. */
void add(PaintedChunk painted) {
byChunk.put(chunkKey(painted.chunkX(), painted.chunkZ()), painted.blockEntities());
}
/** Hands over what waits for the chunk, once; empty when nothing does. */
List<PaintedBlockEntity> take(int chunkX, int chunkZ) {
List<PaintedBlockEntity> waiting = byChunk.remove(chunkKey(chunkX, chunkZ));
return waiting == null ? List.of() : waiting;
}
private static long chunkKey(int chunkX, int chunkZ) {
return ((long) chunkX << INT_BITS) | (chunkZ & 0xFFFFFFFFL);
}
}
@@ -0,0 +1,84 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.toolworld;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* The tool players: one {@link BukkitToolPlayer} for each online player, and what the host remembers about them while
* they are in tool worlds, which is where they came from and the game mode they had before a tool made them creative.
*/
final class ToolPlayers {
private final OpenToolWorlds worlds;
private final BukkitToolMenus menus = new BukkitToolMenus();
private final Map<UUID, BukkitToolPlayer> players = new ConcurrentHashMap<>();
private final Map<UUID, Location> origins = new ConcurrentHashMap<>();
private final Map<UUID, GameMode> modesBeforeCreative = new ConcurrentHashMap<>();
ToolPlayers(OpenToolWorlds worlds) {
this.worlds = worlds;
}
BukkitToolPlayer of(Player player) {
return players.computeIfAbsent(player.getUniqueId(), id -> new BukkitToolPlayer(player, worlds, this, menus));
}
/** Forgets everything about a player who left the server. */
void forget(Player player) {
UUID id = player.getUniqueId();
players.remove(id);
origins.remove(id);
modesBeforeCreative.remove(id);
menus.forget(id);
}
/** Remembers where a player was before their first step into a tool world; later steps keep the first. */
void rememberOrigin(Player player, Location origin) {
origins.putIfAbsent(player.getUniqueId(), origin.clone());
}
/** Hands over where the player came from, once. */
Optional<Location> takeOrigin(Player player) {
return Optional.ofNullable(origins.remove(player.getUniqueId()));
}
/** Remembers the game mode of a player a tool makes creative; the first mode is kept while they stay creative. */
void rememberModeBeforeCreative(Player player) {
modesBeforeCreative.putIfAbsent(player.getUniqueId(), player.getGameMode());
}
/** Gives a player the game mode they had before a tool made them creative; does nothing when none did. */
void restoreGameMode(Player player) {
GameMode previous = modesBeforeCreative.remove(player.getUniqueId());
if (previous != null) {
player.setGameMode(previous);
}
}
BukkitToolMenus menus() {
return menus;
}
}
@@ -0,0 +1,593 @@
/*
* 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.toolworld;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.tooling.world.BlockChange;
import com.volmit.tooling.world.BlockChange.Cause;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolUse;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockCookEvent;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockMultiPlaceEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.BrewingStartEvent;
import org.bukkit.event.block.CrafterCraftEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.inventory.BrewEvent;
import org.bukkit.event.inventory.BrewingStandFuelEvent;
import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.event.inventory.FurnaceStartSmeltEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.FurnaceSmeltEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryPickupItemEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.inventory.BlockInventoryHolder;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* The one listener that maps Bukkit's events onto {@link com.volmit.tooling.world.ToolWorldListener}, for tool worlds
* only. Every handler first asks whether the event happens in a tool world and does nothing when it does not. The
* priorities and {@code ignoreCancelled} flags are those of the jigsaw studio's own handlers: decisions at HIGHEST so
* that other plugins have had their say, observations at MONITOR.
*/
public final class ToolWorldEvents implements Listener {
private static final String COMMAND_PREFIX = "/";
private final OpenToolWorlds worlds;
private final ToolPlayers players;
ToolWorldEvents(OpenToolWorlds worlds, ToolPlayers players) {
this.worlds = worlds;
this.players = players;
}
// Block changes: the tool decides, `false` cancels.
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Block placed = event.getBlockPlaced();
allowOrCancel(event, Cause.PLACE, placed.getWorld(), List.of(positionOf(placed)), Optional.of(event.getPlayer()),
Optional.of(BukkitToolBlocks.stateOf(placed.getBlockData())));
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockMultiPlace(BlockMultiPlaceEvent event) {
List<BlockPosition> replaced = event.getReplacedBlockStates().stream()
.map(state -> positionOf(state.getBlock())).toList();
allowOrCancel(event, Cause.PLACE, event.getBlock().getWorld(), replaced, Optional.of(event.getPlayer()), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
allowOrCancel(event, Cause.BREAK, event.getBlock(), Optional.of(event.getPlayer()));
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBucketEmpty(PlayerBucketEmptyEvent event) {
allowOrCancel(event, Cause.BUCKET, event.getBlockClicked().getRelative(event.getBlockFace()), Optional.of(event.getPlayer()));
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBucketFill(PlayerBucketFillEvent event) {
allowOrCancel(event, Cause.BUCKET, event.getBlockClicked(), Optional.of(event.getPlayer()));
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
allowOrCancel(event, Cause.PHYSICS, event.getBlock().getWorld(),
List.of(positionOf(event.getBlock()), positionOf(event.getSource())), Optional.empty(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
allowOrCancel(event, Cause.FLUID, event.getBlock().getWorld(),
List.of(positionOf(event.getBlock()), positionOf(event.getToBlock())), Optional.empty(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockGrow(BlockGrowEvent event) {
allowOrCancel(event, Cause.GROWTH, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onStructureGrow(StructureGrowEvent event) {
World world = event.getLocation().getWorld();
List<BlockPosition> grown = event.getBlocks().stream().map(state -> positionOf(state.getBlock())).toList();
if (!grown.isEmpty()) {
allowOrCancel(event, Cause.GROWTH, world, grown, Optional.ofNullable(event.getPlayer()), Optional.empty());
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
allowOrCancel(event, Cause.FIRE, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBlockRedstone(BlockRedstoneEvent event) {
Block block = event.getBlock();
if (!isAllowed(Cause.REDSTONE, block.getWorld(), List.of(positionOf(block)), Optional.empty(), Optional.empty())) {
event.setNewCurrent(event.getOldCurrent());
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPistonExtend(BlockPistonExtendEvent event) {
allowPistonOrCancel(event, event.getBlock(), event.getBlocks(), event.getDirection());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPistonRetract(BlockPistonRetractEvent event) {
allowPistonOrCancel(event, event.getBlock(), event.getBlocks(), event.getDirection());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent event) {
keepAllowedBlocks(event.getBlock().getWorld(), event.blockList());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
keepAllowedBlocks(event.getEntity().getWorld(), event.blockList());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Optional<Player> actor = event.getEntity() instanceof Player player ? Optional.of(player) : Optional.empty();
allowOrCancel(event, Cause.ENTITY, event.getBlock(), actor);
}
// Containers and machines.
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryDrag(InventoryDragEvent event) {
allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryMove(InventoryMoveItemEvent event) {
allowContainerOrCancel(event, event.getSource(), null);
if (!event.isCancelled()) {
allowContainerOrCancel(event, event.getDestination(), null);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryPickup(InventoryPickupItemEvent event) {
allowContainerOrCancel(event, event.getInventory(), null);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockCook(BlockCookEvent event) {
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFurnaceBurn(FurnaceBurnEvent event) {
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFurnaceSmelt(FurnaceSmeltEvent event) {
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBrew(BrewEvent event) {
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBrewingStandFuel(BrewingStandFuelEvent event) {
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event) {
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCrafterCraft(CrafterCraftEvent event) {
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
}
// What changed inside containers and machines, told after the fact.
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryClose(InventoryCloseEvent event) {
Player player = event.getPlayer() instanceof Player closer ? closer : null;
tellContainerChanged(containerBlocks(event.getView().getTopInventory()), Optional.ofNullable(player));
}
@EventHandler(priority = EventPriority.MONITOR)
public void onFurnaceStartSmelt(FurnaceStartSmeltEvent event) {
tellContainerChanged(List.of(event.getBlock()), Optional.empty());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onBrewingStart(BrewingStartEvent event) {
tellContainerChanged(List.of(event.getBlock()), Optional.empty());
}
private void tellContainerChanged(List<Block> blocks, Optional<Player> player) {
for (Block block : blocks) {
Optional<ToolPlayer> toolPlayer = player.map(players::of).map(ToolPlayer.class::cast);
BlockPosition at = positionOf(block);
worlds.forWorld(block.getWorld()).ifPresent(world ->
world.tell(listener -> listener.containerChanged(toolPlayer, at)));
}
}
// What players do.
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
Optional<BukkitToolWorld> toolWorld = worlds.forWorld(player.getWorld());
if (toolWorld.isEmpty()) {
return;
}
ToolUse use = new ToolUse(
event.getHand() == org.bukkit.inventory.EquipmentSlot.OFF_HAND ? ToolUse.Hand.OFF : ToolUse.Hand.MAIN,
ToolUse.Action.valueOf(event.getAction().name()),
BukkitToolItems.read(event.getItem()),
Optional.ofNullable(event.getClickedBlock()).map(ToolWorldEvents::positionOf),
BukkitToolBlocks.faceOf(event.getBlockFace()));
ToolPlayer toolPlayer = players.of(player);
if (!toolWorld.get().ask(listener -> listener.used(toolPlayer, use), false)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onToggleSneak(PlayerToggleSneakEvent event) {
Player player = event.getPlayer();
worlds.forWorld(player.getWorld()).ifPresent(world ->
world.tell(listener -> listener.sneakToggled(players.of(player), event.isSneaking())));
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
Optional<BukkitToolWorld> toolWorld = worlds.forWorld(player.getWorld());
if (toolWorld.isEmpty()) {
return;
}
String line = lineOf(event.getMessage());
ToolPlayer toolPlayer = players.of(player);
if (!toolWorld.get().ask(listener -> listener.command(Optional.of(toolPlayer), line), true)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onServerCommand(ServerCommandEvent event) {
String line = lineOf(event.getCommand());
for (BukkitToolWorld toolWorld : worlds.all()) {
if (!toolWorld.ask(listener -> listener.command(Optional.empty(), line), true)) {
event.setCancelled(true);
return;
}
}
}
// Arriving, leaving and moving.
@EventHandler(priority = EventPriority.NORMAL)
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
worlds.forWorld(player.getWorld()).ifPresent(world -> enter(world, player, player.getLocation()));
}
@EventHandler(priority = EventPriority.NORMAL)
public void onQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
worlds.forWorld(player.getWorld()).ifPresent(world -> leave(world, player));
players.forget(player);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onChangedWorld(PlayerChangedWorldEvent event) {
Player player = event.getPlayer();
worlds.forWorld(event.getFrom()).ifPresent(world -> leave(world, player));
worlds.forWorld(player.getWorld()).ifPresent(world -> enter(world, player, player.getLocation()));
}
/**
* Every teleport of any player by anyone, portals included, is told to the tool worlds it touches at the time it
* happens, with the position it goes to: the world it leaves hears {@code left}, the one it enters {@code entered},
* and the one it arrives in {@code teleported}.
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onTeleport(PlayerTeleportEvent event) {
Player player = event.getPlayer();
Location destination = event.getTo();
Optional<BukkitToolWorld> from = worlds.forWorld(event.getFrom().getWorld());
Optional<BukkitToolWorld> to = destination == null ? Optional.empty() : worlds.forWorld(destination.getWorld());
if (from.isEmpty() && to.isPresent()) {
players.rememberOrigin(player, event.getFrom());
}
if (from.isPresent() && to.isEmpty()) {
players.restoreGameMode(player);
players.takeOrigin(player);
}
if (!from.equals(to)) {
from.ifPresent(world -> leave(world, player));
}
to.ifPresent(world -> enter(world, player, destination));
}
@EventHandler(priority = EventPriority.MONITOR)
public void onRespawn(PlayerRespawnEvent event) {
Location respawn = event.getRespawnLocation();
worlds.forWorld(respawn.getWorld()).ifPresent(world -> enter(world, event.getPlayer(), respawn));
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onMove(PlayerMoveEvent event) {
Location to = event.getTo();
if (to == null || sameBlock(event.getFrom(), to)) {
return;
}
worlds.forWorld(to.getWorld()).ifPresent(world ->
world.tell(listener -> listener.moved(players.of(event.getPlayer()), BukkitToolBlocks.positionOf(to))));
}
@EventHandler(priority = EventPriority.NORMAL)
public void onChunkLoad(ChunkLoadEvent event) {
worlds.forWorld(event.getWorld()).ifPresent(world -> world.chunkLoaded(event.getChunk()));
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onWorldUnload(WorldUnloadEvent event) {
worlds.forWorld(event.getWorld()).ifPresent(BukkitToolWorld::unloaded);
}
// The host's own rules.
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onNaturalSpawn(CreatureSpawnEvent event) {
if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NATURAL
&& worlds.forWorld(event.getLocation().getWorld()).isPresent()) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPortal(PlayerPortalEvent event) {
if (worlds.forWorld(event.getFrom().getWorld()).isPresent()) {
event.setCancelled(true);
}
}
/** The player is in the world at {@code at}: told as having entered on the first of their arrivals, and as having arrived on each. */
private void enter(BukkitToolWorld world, Player player, Location at) {
if (world.presence().enter(player.getUniqueId())) {
world.tell(listener -> listener.entered(players.of(player)));
}
BlockPosition arrival = BukkitToolBlocks.positionOf(at);
world.tell(listener -> listener.teleported(players.of(player), arrival));
}
private void leave(BukkitToolWorld world, Player player) {
if (world.presence().leave(player.getUniqueId())) {
world.tell(listener -> listener.left(players.of(player)));
}
}
private void allowOrCancel(Cancellable event, Cause cause, Block block, Optional<Player> player) {
allowOrCancel(event, cause, block.getWorld(), List.of(positionOf(block)), player, Optional.empty());
}
private void allowOrCancel(
Cancellable event,
Cause cause,
World world,
List<BlockPosition> positions,
Optional<Player> player,
Optional<BlockState> placed
) {
if (!isAllowed(cause, world, positions, player, placed)) {
event.setCancelled(true);
}
}
private void allowPistonOrCancel(Cancellable event, Block piston, List<Block> moved, BlockFace direction) {
boolean allowed = isAllowed(
Cause.PISTON,
piston.getWorld(),
pistonChecked(moved, direction),
pistonChanged(piston, moved, direction),
Optional.empty(),
Optional.empty());
if (!allowed) {
event.setCancelled(true);
}
}
private void allowContainerOrCancel(Cancellable event, Inventory inventory, Player player) {
List<Block> blocks = containerBlocks(inventory);
if (blocks.isEmpty()) {
return;
}
List<BlockPosition> positions = blocks.stream().map(ToolWorldEvents::positionOf).toList();
allowOrCancel(event, Cause.CONTAINER, blocks.getFirst().getWorld(), positions, Optional.ofNullable(player), Optional.empty());
}
/** Whether the tool lets the change happen; changes outside tool worlds are none of the host's business. */
private boolean isAllowed(
Cause cause,
World world,
List<BlockPosition> positions,
Optional<Player> player,
Optional<BlockState> placed
) {
return isAllowed(cause, world, positions, positions, player, placed);
}
private boolean isAllowed(
Cause cause,
World world,
List<BlockPosition> positions,
List<BlockPosition> changed,
Optional<Player> player,
Optional<BlockState> placed
) {
Optional<BukkitToolWorld> toolWorld = worlds.forWorld(world);
if (toolWorld.isEmpty()) {
return true;
}
BlockChange change = new BlockChange(
cause, positions, changed, player.map(players::of).map(ToolPlayer.class::cast), placed);
return toolWorld.get().ask(listener -> listener.blockChanging(change), false);
}
private void keepAllowedBlocks(World world, List<Block> exploded) {
if (worlds.forWorld(world).isEmpty()) {
return;
}
exploded.removeIf(block -> !isAllowed(Cause.EXPLOSION, world, List.of(positionOf(block)), Optional.empty(), Optional.empty()));
}
/** Each block a piston moves and the block each of them enters and leaves, which a protected area is checked against; not the piston. */
static List<BlockPosition> pistonChecked(List<Block> moved, BlockFace direction) {
List<BlockPosition> positions = new ArrayList<>();
for (Block block : moved) {
positions.add(positionOf(block));
positions.add(positionOf(block.getRelative(direction)));
positions.add(positionOf(block.getRelative(direction.getOppositeFace())));
}
return positions.stream().distinct().toList();
}
/** The piston and the block ahead of it, then each block it moves and the block each enters: what a piston changes. */
static List<BlockPosition> pistonChanged(Block piston, List<Block> moved, BlockFace direction) {
List<BlockPosition> positions = new ArrayList<>();
positions.add(positionOf(piston));
positions.add(positionOf(piston.getRelative(direction)));
for (Block block : moved) {
positions.add(positionOf(block));
positions.add(positionOf(block.getRelative(direction)));
}
return positions.stream().distinct().toList();
}
/** The blocks a container inventory is made of: none for a player's or a menu, two for a double chest. */
static List<Block> containerBlocks(Inventory inventory) {
if (inventory == null) {
return List.of();
}
List<Block> blocks = new ArrayList<>(2);
InventoryHolder holder = inventory.getHolder();
if (holder instanceof BlockInventoryHolder blockHolder) {
blocks.add(blockHolder.getBlock());
} else if (holder instanceof DoubleChest doubleChest) {
addBlockOf(blocks, doubleChest.getLeftSide());
addBlockOf(blocks, doubleChest.getRightSide());
}
return blocks;
}
private static void addBlockOf(List<Block> blocks, InventoryHolder holder) {
if (holder instanceof BlockInventoryHolder blockHolder && !blocks.contains(blockHolder.getBlock())) {
blocks.add(blockHolder.getBlock());
}
}
/** Whether two locations are in one block of one world. */
static boolean sameBlock(Location from, Location to) {
return from.getWorld() == to.getWorld()
&& from.getBlockX() == to.getBlockX()
&& from.getBlockY() == to.getBlockY()
&& from.getBlockZ() == to.getBlockZ();
}
/** What a command line is for the tool: without the slash a player types before it. */
static String lineOf(String typed) {
return typed.startsWith(COMMAND_PREFIX) ? typed.substring(COMMAND_PREFIX.length()) : typed;
}
private static BlockPosition positionOf(Block block) {
return BukkitToolBlocks.positionOf(block);
}
}
@@ -0,0 +1,46 @@
/*
* 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.toolworld;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Who stands in one tool world, so that the platform's several ways of arriving and leaving (join, teleport, world
* change, respawn, quit) tell the tool once for each stay: {@code entered} on the first of them, {@code left} on the
* first of them after.
*/
final class ToolWorldPresence {
private final Set<UUID> present = ConcurrentHashMap.newKeySet();
/** Whether the player was not here before, which is when the tool hears {@code entered}. */
boolean enter(UUID player) {
return present.add(player);
}
/** Whether the player was here, which is when the tool hears {@code left}. */
boolean leave(UUID player) {
return present.remove(player);
}
boolean isPresent(UUID player) {
return present.contains(player);
}
}
@@ -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.toolworld;
import art.arcane.iris.core.runtime.WorldRuntimeControlService;
import org.bukkit.GameRules;
import org.bukkit.World;
/**
* What every tool world is made to be, whatever the server's studio settings say: no natural mobs, no weather, no
* daylight cycle, no portals, on top of the rules the object and jigsaw studios already use.
*/
final class ToolWorldRules {
private ToolWorldRules() {
}
/** Applies the rules; runs on the thread that may change the world's rules (the main or global thread). */
static void apply(World world) {
WorldRuntimeControlService.get().applyObjectStudioWorldRules(world);
world.setGameRule(GameRules.SPAWN_MOBS, false);
world.setGameRule(GameRules.ADVANCE_WEATHER, false);
world.setGameRule(GameRules.ADVANCE_TIME, false);
world.setGameRule(GameRules.ALLOW_ENTERING_NETHER_USING_PORTALS, false);
world.setStorm(false);
world.setThundering(false);
}
}
@@ -60,7 +60,6 @@ public class IrisShutdownOrderingTest {
assertTrue("Server-stop quiescence must leave queued Paper generation admitted",
quiesce.contains("generator.quiesceForServerShutdown()"));
assertOrdered(quiesce,
"jigsawStudioService.quiesceForServerShutdown()",
"PregeneratorJob.shutdownAndWait",
"generator.quiesceForServerShutdown()");
assertOrdered(onDisable,
@@ -123,32 +122,21 @@ public class IrisShutdownOrderingTest {
}
@Test
public void jigsawStudio_quiescesOnceBeforeDeferredServiceTeardown() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.jigsawStudioSvcSource")));
String enable = section(source, "public void onEnable()", "public void onDisable()");
String disable = section(source, "public void onDisable()", "public void quiesceForServerShutdown()");
String quiesce = section(source, "public void quiesceForServerShutdown()", "public void register(");
String register = section(source, "public void register(", "public void activationCommitted(");
String activation = section(source, "public void activationCommitted(", "public void markChunkGenerated(");
String chunkGenerated = section(source, "public void markChunkGenerated(", "private void markChunkAvailable(");
public void jigsawStudio_quiescesThroughItsToolWorldBeforeTheWorldIsUnloaded() throws Exception {
String startup = Files.readString(Path.of(System.getProperty("iris.startupSource")));
String toolWorlds = Files.readString(Path.of(System.getProperty("iris.toolWorldServiceSource")));
String studio = Files.readString(Path.of(System.getProperty("iris.jigsawStudioSvcSource")));
String disable = section(toolWorlds, "public void onDisable()", "public ToolWorlds worldsOf");
String closing = section(studio, "CompletableFuture<Void> closing(", "private boolean markDirty(");
assertOrdered(enable, "disableStarted.set(false)", "enabled = true");
assertTrue("Deferred service teardown must reuse the idempotent early disable",
disable.contains("quiesceForServerShutdown();"));
assertOrdered(quiesce,
"disableStarted.compareAndSet(false, true)",
"finalizeAllJigsawTileWatches()",
"drainAutosavesBeforeDisable()",
"enabled = false",
"activeMenuController.closeAll()",
"previewRenderer.removeAll()",
"studios.clear()");
assertTrue("Registration must reject work after shutdown begins",
occurrences(register, "!enabled || disableStarted.get()") >= 2);
assertTrue("Activation must reject work after shutdown begins",
activation.contains("!enabled || disableStarted.get()"));
assertTrue("Chunk-generation callbacks must reject work after shutdown begins",
occurrences(chunkGenerated, "!enabled || disableStarted.get()") >= 2);
assertFalse("Iris no longer holds or quiesces a studio itself", startup.contains("JigsawStudio"));
assertOrdered(disable,
"awaitClosing(open)",
"open.forEach(BukkitToolWorld::unloaded)");
assertTrue("The host asks every tool world to get ready to close", toolWorlds.contains("world.prepareReplacement(Optional.empty())"));
assertOrdered(closing,
"drainAutosavesBeforeRemoval(studios.get(worldId))",
"awaitCloseForReplacement(");
}
private static String section(String source, String startMarker, String endMarker) {
@@ -1,609 +0,0 @@
package art.arcane.iris.core.commands;
import art.arcane.iris.core.pack.BrokenPackException;
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioWorkcellSpec;
import art.arcane.iris.core.service.JigsawStudioService;
import art.arcane.iris.core.structure.authoring.StructureBackend;
import art.arcane.iris.core.structure.authoring.StructureCapability;
import art.arcane.iris.core.structure.authoring.StructureHash;
import art.arcane.iris.core.structure.authoring.StructureKey;
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
import art.arcane.iris.core.structure.authoring.StructureSource;
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionInputKind;
import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat;
import art.arcane.iris.core.tools.IrisCreator;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.util.common.director.specialhandlers.IrisStructureHandler;
import art.arcane.volmlib.util.director.DirectorOrigin;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
import art.arcane.volmlib.util.director.exceptions.DirectorParsingException;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class CommandJigsawContractTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void commandIrisRegistersJigsawTree() throws Exception {
Field field = CommandIris.class.getDeclaredField("jigsaw");
assertEquals(CommandJigsaw.class, field.getType());
assertNotNull(CommandJigsaw.class.getDeclaredField("piece"));
assertNotNull(CommandJigsaw.class.getDeclaredField("pool"));
assertNotNull(CommandJigsaw.class.getDeclaredField("connector"));
assertNotNull(CommandJigsaw.class.getDeclaredField("variant"));
assertNotNull(CommandJigsaw.class.getDeclaredField("workcell"));
assertNotNull(CommandJigsaw.class.getDeclaredField("rules"));
assertNotNull(CommandJigsaw.class.getDeclaredField("preview"));
assertNotNull(CommandJigsaw.class.getDeclaredField("adopt"));
}
@Test
public void exposesStudioLifecycleAndAuthoringCommands() throws Exception {
assertCommand("create", IrisDimension.class, String.class, String.class, String.class,
int.class, int.class, int.class, long.class);
assertCommand("convert", IrisDimension.class, String.class, String.class, long.class);
assertCommand("open", IrisDimension.class, String.class, long.class);
assertCommand("close", boolean.class);
assertCommand("delete", boolean.class);
assertCommand("status");
assertCommand("menu");
assertCommand("select");
assertCommand("bounds", int.class, int.class, int.class);
assertCommand("save", String.class);
assertCommand("gotoBay", String.class);
assertCommand("particles", boolean.class);
assertCommand("export", String.class, String.class, String.class, boolean.class);
}
@Test
public void jigsawStudioUsesItsDedicatedOpenLifecycle() {
assertEquals(
StudioOpenCoordinator.StudioOpenKind.JIGSAW,
CommandJigsaw.STUDIO_OPEN_KIND);
assertFalse(CommandJigsaw.STUDIO_OPEN_KIND.openWorkspace());
assertFalse(CommandJigsaw.STUDIO_OPEN_KIND.teleportThroughStandardEntry());
assertEquals(
IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY,
CommandJigsaw.STUDIO_OPEN_KIND.datapackPreparation());
}
@Test
public void packValidationDenialsAreExpectedOpenFailures() {
BrokenPackException failure = new BrokenPackException(
"overworld", List.of("Biome 'broken' has no resolvable regions."));
assertTrue(CommandJigsaw.isExpectedOpenDenial(failure));
assertTrue(CommandJigsaw.isExpectedOpenDenial(
new CompletionException(failure)));
assertFalse(CommandJigsaw.isExpectedOpenDenial(
new IllegalStateException("Unexpected Studio failure")));
}
@Test
public void committedActivationStartsInitialEvaluationBeforePlayerBinding() throws Exception {
String source = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
int commit = source.indexOf("JigsawStudioActivation.commit(staged)");
int evaluation = source.indexOf(
"studioService.activationCommitted(world, request.requestId())",
commit);
int binding = source.indexOf("PLAYER_PACKS.put", evaluation);
assertTrue(commit >= 0);
assertTrue(evaluation > commit);
assertTrue(binding > evaluation);
}
@Test
public void convertIsAddOnlyWorkflowWithAliasesAndDefaults() throws Exception {
Method convert = CommandJigsaw.class.getDeclaredMethod(
"convert", IrisDimension.class, String.class, String.class, long.class);
Director command = convert.getAnnotation(Director.class);
Parameter[] parameters = convert.getParameters();
assertEquals(List.of("import", "import-vanilla"), List.of(command.aliases()));
assertParameter(parameters[2], "auto", null);
assertParameter(parameters[3], "1337", null);
NamespacedKey source = CommandJigsaw.parseRegisteredStructureKey("minecraft:village_plains");
assertEquals("minecraft_village_plains", CommandJigsaw.resolveConversionTarget(source, "auto"));
assertEquals("villages/plains", CommandJigsaw.resolveConversionTarget(source, "iris:villages/plains"));
NamespacedKey ancientCity = CommandJigsaw.parseRegisteredStructureKey(
"minecraft:ancient_city");
assertEquals("minecraft_ancient_city",
CommandJigsaw.resolveConversionTarget(ancientCity, "auto"));
assertThrows(IllegalArgumentException.class,
() -> CommandJigsaw.resolveConversionTarget(source, "custom:village"));
}
@Test
public void adoptionCommandsExposeTwoStepPlanContract() throws Exception {
Method inspect = CommandJigsaw.CommandJigsawAdopt.class.getDeclaredMethod(
"inspect", IrisDimension.class, String.class, String.class, String.class);
Method apply = CommandJigsaw.CommandJigsawAdopt.class.getDeclaredMethod("apply", String.class);
Parameter[] inspectParameters = inspect.getParameters();
assertNotNull(inspect.getAnnotation(Director.class));
assertNotNull(apply.getAnnotation(Director.class));
assertParameter(inspectParameters[2], "auto", null);
assertParameter(inspectParameters[3], "auto", CommandJigsaw.JigsawAdoptionStrategyHandler.class);
assertEquals(CommandJigsaw.JigsawAdoptionPlanHandler.class,
apply.getParameters()[0].getAnnotation(Param.class).customHandler());
CommandJigsaw.JigsawAdoptionStrategyHandler strategyHandler =
new CommandJigsaw.JigsawAdoptionStrategyHandler();
assertEquals(List.of("auto", "in-place", "clone"), strategyHandler.getPossibilities());
assertEquals("in-place", strategyHandler.parse("claim", false));
assertEquals("clone", strategyHandler.parse("copy", false));
assertThrows(DirectorParsingException.class, () -> strategyHandler.parse("overwrite", false));
}
@Test
public void adoptionInputKindUsesOnlyOwnershipProvenance() throws Exception {
Path root = temporaryFolder.newFolder("adoption-provenance").toPath();
assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS,
CommandJigsaw.adoptionInputKind(root, "unowned"));
writeManifest(root, "datapack-created", StructureSource.Kind.DATAPACK,
StructureOwnershipManifest.Provenance.created());
assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS,
CommandJigsaw.adoptionInputKind(root, "datapack-created"));
writeManifest(root, "managed-provenance", StructureSource.Kind.IRIS, managedProvenance());
assertEquals(IrisStructureAdoptionInputKind.MANAGED_DATAPACK,
CommandJigsaw.adoptionInputKind(root, "managed-provenance"));
}
@Test
public void legacyGraphWritersShareTheServiceMutationContract() throws Exception {
Method mutation = CommandJigsaw.class.getDeclaredMethod(
"runGraphMutation",
Player.class,
CommandJigsaw.ActiveContext.class,
JigsawStudioService.CommandGraphMutation.class);
assertEquals(boolean.class, mutation.getReturnType());
assertNotNull(JigsawStudioService.CommandGraphMutation.class.getDeclaredMethod("run"));
assertNotNull(JigsawStudioService.CommandGraphMutationResult.class.getDeclaredConstructor(
JigsawStudioLayout.class,
String.class,
String.class,
String.class));
}
@Test
public void exposesAutosaveDynamicEvaluationAndSelectedWorkcellResize() throws Exception {
Method save = CommandJigsaw.class.getDeclaredMethod("save", String.class);
Method status = CommandJigsaw.class.getDeclaredMethod("status");
Method bounds = CommandJigsaw.class.getDeclaredMethod(
"bounds", int.class, int.class, int.class);
assertEquals("Flush the automatic save for a workcell now",
save.getAnnotation(Director.class).description());
assertEquals("Show active Jigsaw Studio and dynamic evaluation state",
status.getAnnotation(Director.class).description());
assertEquals("Set the selected Studio workcell capacity",
bounds.getAnnotation(Director.class).description());
assertThrows(NoSuchMethodException.class,
() -> CommandJigsaw.class.getDeclaredMethod("validate"));
}
@Test
public void createDefaultsToPlanarIrisWithCompleteCellAndSeedDefaults() throws Exception {
Method create = CommandJigsaw.class.getDeclaredMethod(
"create",
IrisDimension.class,
String.class,
String.class,
String.class,
int.class,
int.class,
int.class,
long.class);
Parameter[] parameters = create.getParameters();
assertParameter(parameters[2], "planar", CommandJigsaw.JigsawModeHandler.class);
assertParameter(parameters[3], "iris", CommandJigsaw.JigsawCompatibilityHandler.class);
assertParameter(parameters[4], "15", null);
assertParameter(parameters[5], "15", null);
assertParameter(parameters[6], "15", null);
assertParameter(parameters[7], "1337", null);
}
@Test
public void structureKeysExplainTheirResourceAndOpenSupportsEditingAliases() throws Exception {
Method create = CommandJigsaw.class.getDeclaredMethod(
"create",
IrisDimension.class,
String.class,
String.class,
String.class,
int.class,
int.class,
int.class,
long.class);
Method open = CommandJigsaw.class.getDeclaredMethod(
"open", IrisDimension.class, String.class, long.class);
Param createKey = create.getParameters()[1].getAnnotation(Param.class);
Param openKey = open.getParameters()[1].getAnnotation(Param.class);
Director openCommand = open.getAnnotation(Director.class);
assertEquals("key", createKey.name());
assertEquals(List.of("structure", "name"), List.of(createKey.aliases()));
assertEquals("New key written as structures/<key>.json", createKey.description());
assertEquals("key", openKey.name());
assertEquals(List.of("structure", "name"), List.of(openKey.aliases()));
assertEquals("Existing key loaded from structures/<key>.json", openKey.description());
assertEquals(IrisStructureHandler.class, openKey.customHandler());
assertEquals(List.of("edit", "reopen"), List.of(openCommand.aliases()));
}
@Test
public void createChoiceHandlersExposeCanonicalCompletionsAndRetainAliases() throws Exception {
CommandJigsaw.JigsawModeHandler modeHandler = new CommandJigsaw.JigsawModeHandler();
CommandJigsaw.JigsawCompatibilityHandler compatibilityHandler =
new CommandJigsaw.JigsawCompatibilityHandler();
assertEquals(List.of("planar", "spatial"), modeHandler.getPossibilities());
assertEquals("planar", modeHandler.parse("2d", false));
assertEquals("spatial", modeHandler.parse("3d", false));
assertEquals(List.of("iris", "vanilla"), compatibilityHandler.getPossibilities());
assertEquals("iris", compatibilityHandler.parse("extended", false));
assertEquals("vanilla", compatibilityHandler.parse("portable", false));
assertThrows(DirectorParsingException.class, () -> modeHandler.parse("volume", false));
assertThrows(DirectorParsingException.class, () -> compatibilityHandler.parse("mixed", false));
}
@Test
public void exposesNestedPieceVariantAndPreviewCommands() throws Exception {
assertNotNull(CommandJigsaw.CommandJigsawPool.class
.getDeclaredMethod("create", String.class, String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawConnector.class
.getDeclaredMethod("channel", String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("create", String.class, String.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("add", String.class, String.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("remove", String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("rotatable", boolean.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("expand")
.getAnnotation(Director.class));
assertEquals("Resize the selected piece object exactly to workcell capacity",
CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("expand")
.getAnnotation(Director.class)
.description());
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("weight", String.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("resize", int.class, int.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("label", String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("labelReset")
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("duplicate")
.getAnnotation(Director.class));
Method duplicateFamily = CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("duplicateFamily", String.class);
assertNotNull(duplicateFamily.getAnnotation(Director.class));
assertParameter(duplicateFamily.getParameters()[0], "next", null);
assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class
.getDeclaredMethod("capacity", int.class, int.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class
.getDeclaredMethod("label", String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class
.getDeclaredMethod("labelReset")
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawRules.class
.getDeclaredMethod("limits", int.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawRules.class
.getDeclaredMethod("fallback", String.class, String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPreview.class
.getDeclaredMethod("assemble", long.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPreview.class
.getDeclaredMethod("gotoPreview")
.getAnnotation(Director.class));
}
@Test
public void pieceCreateUsesResolvedWorkcellCapacityInsteadOfLayoutDefault() throws Exception {
String source = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
int pieceCommands = source.indexOf("public static class CommandJigsawPiece");
int create = source.indexOf("public void create(", pieceCommands);
int add = source.indexOf("public void add(", create);
String createSource = source.substring(create, add);
assertTrue(createSource.contains("targetWorkcell = contextual;"));
assertTrue(createSource.contains("JigsawStudioCellDimensions dimensions = targetWorkcell.capacity();"));
assertFalse(createSource.contains("layout().cellDimensions()"));
}
@Test
public void pieceAddUsesCanonicalAxesForRotatedRectangularPlanarWorkcells() {
JigsawStudioLayout layout = nonuniformPlanarLayout();
IrisJigsawPiece eastEnd = new IrisJigsawPiece();
eastEnd.getConnectors().add(new IrisJigsawConnector().setDirection(IrisDirection.EAST_POSITIVE_X));
IrisObject exactObject = new IrisObject(7, 5, 13);
CommandJigsaw.PieceWorkcellResolution exact = CommandJigsaw.resolvePieceWorkcell(
layout,
eastEnd,
exactObject);
CommandJigsaw.PieceWorkcellResolution oversized = CommandJigsaw.resolvePieceWorkcell(
layout,
eastEnd,
new IrisObject(8, 5, 13));
assertEquals(JigsawPlanarArchetype.END.stableId(), exact.workcell().stableId());
assertEquals(new IrisPosition(13, 5, 7), exact.requiredDimensions());
assertEquals(new JigsawStudioCellDimensions(13, 5, 7), exact.workcell().capacity());
assertTrue(exact.fits());
assertTrue(exactObject.getD() > exact.workcell().capacity().depth());
assertFalse(oversized.fits());
}
@Test
public void pieceAddKeepsRawObjectAxesForSpatialWorkcells() {
JigsawStudioCellDimensions capacity = new JigsawStudioCellDimensions(7, 5, 13);
JigsawStudioLayout layout = JigsawStudioLayout.create(
JigsawStudioMode.SPATIAL_JIGSAW,
capacity,
JigsawStudioVariantCatalog.empty());
IrisJigsawPiece spatialPiece = new IrisJigsawPiece();
spatialPiece.getConnectors().add(
new IrisJigsawConnector().setDirection(IrisDirection.EAST_POSITIVE_X));
CommandJigsaw.PieceWorkcellResolution resolution = CommandJigsaw.resolvePieceWorkcell(
layout,
spatialPiece,
new IrisObject(7, 5, 13));
assertEquals(JigsawStudioLayout.SPATIAL_WORKCELL_ID, resolution.workcell().stableId());
assertEquals(new IrisPosition(7, 5, 13), resolution.requiredDimensions());
assertEquals(capacity, resolution.workcell().capacity());
assertTrue(resolution.fits());
}
@Test
public void everyExecutableCommandRejectsNonPlayerOrigins() {
Class<?>[] commandTypes = {
CommandJigsaw.class,
CommandJigsaw.CommandJigsawConnector.class,
CommandJigsaw.CommandJigsawPool.class,
CommandJigsaw.CommandJigsawPiece.class,
CommandJigsaw.CommandJigsawVariant.class,
CommandJigsaw.CommandJigsawWorkcell.class,
CommandJigsaw.CommandJigsawRules.class,
CommandJigsaw.CommandJigsawPreview.class,
CommandJigsaw.CommandJigsawAdopt.class
};
for (Class<?> commandType : commandTypes) {
for (Method method : commandType.getDeclaredMethods()) {
Director director = method.getAnnotation(Director.class);
if (director != null) {
assertEquals(method.toString(), DirectorOrigin.PLAYER, director.origin());
}
}
}
}
@Test
public void exportOutputIsOneSafeChildArtifact() {
Path root = Path.of("build", "jigsaw-exports").toAbsolutePath().normalize();
assertEquals(root.resolve("village.zip"), CommandJigsaw.resolveExportDestination(
root, "village", VanillaJigsawExportFormat.ZIP));
assertEquals(root.resolve("village"), CommandJigsaw.resolveExportDestination(
root, "village", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
root, "", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
root, ".", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
root, "../all-exports", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
root, "nested/export", VanillaJigsawExportFormat.DIRECTORY));
}
@Test
public void exportLeaseRejectsDuplicatePlayerAndDestination() {
UUID firstPlayer = UUID.randomUUID();
UUID secondPlayer = UUID.randomUUID();
Path firstDestination = Path.of("build", "jigsaw-exports", "first.zip");
Path secondDestination = Path.of("build", "jigsaw-exports", "second.zip");
assertEquals(true, CommandJigsaw.beginExport(firstPlayer, firstDestination));
try {
assertEquals(false, CommandJigsaw.beginExport(firstPlayer, secondDestination));
assertEquals(false, CommandJigsaw.beginExport(secondPlayer, firstDestination));
} finally {
CommandJigsaw.finishExport(firstPlayer, firstDestination);
}
assertEquals(true, CommandJigsaw.beginExport(secondPlayer, firstDestination));
CommandJigsaw.finishExport(secondPlayer, firstDestination);
}
@Test
public void exportStartFailuresHavePreciseOperatorMessages() {
assertEquals("The active Jigsaw Studio is no longer available.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.NOT_ACTIVE));
assertEquals("Only the Jigsaw Studio owner can export this project.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.NOT_OWNER));
assertEquals("Wait for the pending autosave or discard the edits before exporting the on-disk graph.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.DIRTY));
assertEquals("The active Jigsaw Studio is closing and cannot be exported.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.CLOSING));
assertEquals("Wait for the current Jigsaw Studio save to finish before exporting.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.SAVE_IN_PROGRESS));
assertEquals("Wait for the current Jigsaw Studio operation to finish before exporting.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.OPERATION_IN_PROGRESS));
assertEquals("A Jigsaw Studio export is already in progress.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.IN_PROGRESS));
assertThrows(IllegalArgumentException.class,
() -> CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.STARTED));
}
@Test
public void exportLeaseReleaseActionRunsExactlyOnce() {
AtomicInteger releases = new AtomicInteger();
CommandJigsaw.ExportLease lease = new CommandJigsaw.ExportLease(releases::incrementAndGet);
lease.release();
lease.release();
assertEquals(1, releases.get());
}
@Test
public void exportSourceAcquiresStudioLeaseBeforeStaticLeaseAndReleasesBothPaths() throws Exception {
String source = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
int serviceLease = source.indexOf("studioService.tryBeginExport(requestId, playerId)");
int staticLease = source.indexOf("beginExport(playerId, destination)", serviceLease);
int dispatch = source.indexOf("J.a(() -> runExport(operation))", staticLease);
int schedulingRelease = source.indexOf("operation.lease().release()", dispatch);
int exporter = source.indexOf("new VanillaJigsawDatapackExporter().export(operation.request())", dispatch);
int completionRelease = source.indexOf("operation.lease().release()", exporter);
assertTrue(serviceLease >= 0);
assertTrue(staticLease > serviceLease);
assertTrue(dispatch > staticLease);
assertTrue(schedulingRelease > dispatch);
assertTrue(exporter > schedulingRelease);
assertTrue(completionRelease > exporter);
}
private static void assertCommand(String name, Class<?>... parameterTypes) throws Exception {
Method method = CommandJigsaw.class.getDeclaredMethod(name, parameterTypes);
assertNotNull(method.getAnnotation(Director.class));
}
private static JigsawStudioLayout nonuniformPlanarLayout() {
List<JigsawStudioWorkcellSpec> workcells = List.of(
workcell(JigsawPlanarArchetype.BLANK, 3, 1, 3),
workcell(JigsawPlanarArchetype.END, 13, 5, 7),
workcell(JigsawPlanarArchetype.STRAIGHT, 5, 2, 11),
workcell(JigsawPlanarArchetype.CORNER, 9, 3, 6),
workcell(JigsawPlanarArchetype.TEE, 12, 4, 8),
workcell(JigsawPlanarArchetype.CROSS, 10, 6, 10));
return JigsawStudioLayout.createPlanar(
new JigsawStudioCellDimensions(3, 1, 3),
workcells,
JigsawStudioVariantCatalog.empty());
}
private static JigsawStudioWorkcellSpec workcell(
JigsawPlanarArchetype archetype,
int width,
int height,
int depth
) {
return new JigsawStudioWorkcellSpec(
archetype,
"",
new JigsawStudioCellDimensions(width, height, depth),
true);
}
private static void assertParameter(Parameter parameter, String defaultValue, Class<?> customHandler) {
Param annotation = parameter.getAnnotation(Param.class);
assertNotNull(annotation);
assertEquals(defaultValue, annotation.defaultValue());
if (customHandler != null) {
assertEquals(customHandler, annotation.customHandler());
}
}
private static void writeManifest(
Path root,
String structure,
StructureSource.Kind sourceKind,
StructureOwnershipManifest.Provenance provenance
) throws Exception {
StructureKey structureKey = new StructureKey("iris", structure);
StructureOwnershipManifest manifest = new StructureOwnershipManifest(
StructureOwnershipManifest.CURRENT_SCHEMA_VERSION,
structureKey,
StructureSource.of(sourceKind, new StructureKey("iris", "source/" + structure)),
StructureBackend.IRIS_ASSEMBLY,
List.of(StructureCapability.BLOCKS, StructureCapability.CONNECTORS),
List.of(),
Map.of("structures/" + structure + ".json", StructureHash.sha256(
structure.getBytes(StandardCharsets.UTF_8))),
provenance);
Path manifestPath = new StructureTransactionWriter(root).ownershipManifestPath(structureKey);
Files.createDirectories(manifestPath.getParent());
Files.write(manifestPath, manifest.toJson());
}
private static StructureOwnershipManifest.Provenance managedProvenance() {
String path = "structures/source.json";
String hash = StructureHash.sha256("source".getBytes(StandardCharsets.UTF_8));
return new StructureOwnershipManifest.Provenance(
StructureOwnershipManifest.Origin.MANAGED_DATAPACK,
UUID.randomUUID().toString(),
StructureHash.sha256("plan".getBytes(StandardCharsets.UTF_8)),
StructureHash.sha256("closure".getBytes(StandardCharsets.UTF_8)),
1L,
Map.of(path, hash),
Map.of(path, path),
StructureOwnershipManifest.RollbackDisposition.NONE);
}
}
@@ -228,15 +228,14 @@ public class IrisStructureLocateCommandContractTest {
@Test
public void bulkStructureImportRestrictsCaptureWithoutChangingStandaloneCapture() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
int importStart = source.indexOf("public void importAll(");
int importEnd = source.indexOf("@Director(name = \"capture\"", importStart);
int captureStart = source.indexOf("public void capture(", importEnd);
String source = Files.readString(Path.of(System.getProperty("iris.importCommandsSource")));
int importStart = source.indexOf("private static void runImportAll(");
int captureStart = source.indexOf("private static void runCapture(", importStart);
int importEnd = captureStart;
int captureEnd = source.length();
assertTrue(importStart >= 0);
assertTrue(importEnd > importStart);
assertTrue(captureStart > importEnd);
assertTrue(captureEnd > captureStart);
String importMethod = source.substring(importStart, importEnd);
String captureMethod = source.substring(captureStart, captureEnd);
@@ -42,12 +42,11 @@ public class StudioPlayerModeContractTest {
String objectCommands = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandObject.java")).replace("\r\n", "\n");
String jigsawCommands = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
System.getProperty("iris.studioLifecycleCommandsSource"))).replace("\r\n", "\n");
assertTrue(objectCommands.contains("GameMode.CREATIVE"));
assertTrue(objectCommands.contains("StudioOpenCoordinator.StudioOpenKind.OBJECT"));
assertTrue(jigsawCommands.contains("GameMode.CREATIVE"));
assertTrue(jigsawCommands.contains("player.creative(true)"));
assertFalse(objectCommands.contains("GameMode.SPECTATOR"));
assertFalse(jigsawCommands.contains("GameMode.SPECTATOR"));
}
assertFalse(jigsawCommands.contains("GameMode.SPECTATOR")); }
}
@@ -0,0 +1,33 @@
package art.arcane.iris.core.structure;
import org.junit.Test;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class BukkitCaptureAreaFailureTest {
@Test
public void captureFailurePreservesStructureChunkDetailAndCause() {
IllegalArgumentException cause = new IllegalArgumentException("placement broke");
IllegalStateException error = BukkitCaptureArea.captureFailure(
"minecraft:monument", 12, -8, "platform placement failed", cause);
assertSame(cause, error.getCause());
assertTrue(error.getMessage().contains("minecraft:monument"));
assertTrue(error.getMessage().contains("12,-8"));
assertTrue(error.getMessage().contains("platform placement failed"));
}
@Test
public void captureFailureSupportsInfrastructureFailuresWithoutACause() {
IllegalStateException error = BukkitCaptureArea.captureFailure(
"minecraft:stronghold", -3, 5, "region task was not accepted", null);
assertNull(error.getCause());
assertTrue(error.getMessage().contains("minecraft:stronghold"));
assertTrue(error.getMessage().contains("-3,5"));
assertTrue(error.getMessage().contains("region task was not accepted"));
}
}
@@ -0,0 +1,176 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
public class PoolElementReaderTest {
private static final String FINAL_STATE =
"minecraft:oak_stairs[facing=east,half=top,shape=straight,waterlogged=false]";
@Test
public void plainTemplateElementRemainsUnchanged() throws Exception {
FakeSinglePoolElement single = new FakeSinglePoolElement("minecraft:village/plains/houses/plains_small_house_1");
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(single);
assertSame(single, resolution.physicalElement());
assertEquals("minecraft:village/plains/houses/plains_small_house_1", resolution.templateLocation());
assertEquals(0, resolution.listLevels());
assertEquals(0, resolution.omittedElements());
}
@Test
public void nestedListsRetainOnlyTheRecursivePrimaryTemplate() throws Exception {
FakeSinglePoolElement primary = new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower");
FakeSinglePoolElement innerOverlay = new FakeSinglePoolElement("test:inner_overlay");
FakeSinglePoolElement outerOverlay = new FakeSinglePoolElement("test:outer_overlay");
FakeListPoolElement inner = new FakeListPoolElement(List.of(primary, innerOverlay));
FakeListPoolElement outer = new FakeListPoolElement(List.of(inner, outerOverlay));
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(outer);
assertSame(primary, resolution.physicalElement());
assertEquals("minecraft:pillager_outpost/watchtower", resolution.templateLocation());
assertEquals(2, resolution.listLevels());
assertEquals(2, resolution.omittedElements());
}
@Test
public void unsupportedPrimaryDoesNotFallThroughToLaterChildren() throws Exception {
FakeFeaturePoolElement feature = new FakeFeaturePoolElement();
FakeSinglePoolElement fallback = new FakeSinglePoolElement("test:must_not_be_selected");
FakeListPoolElement list = new FakeListPoolElement(List.of(feature, fallback));
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(list);
assertSame(feature, resolution.physicalElement());
assertNull(resolution.templateLocation());
assertEquals(1, resolution.omittedElements());
}
@Test
public void emptyListResolvesWithoutIndexingAChild() throws Exception {
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(
new FakeListPoolElement(List.of())
);
assertNull(resolution.physicalElement());
assertNull(resolution.templateLocation());
assertEquals(1, resolution.listLevels());
assertEquals(0, resolution.omittedElements());
}
@Test
public void outerChoiceProducesOneEntryWithItsOriginalWeight() throws Exception {
FakeListPoolElement towers = new FakeListPoolElement(List.of(
new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower"),
new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower_overgrown")
));
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(towers);
List<Map<String, Object>> entries = List.of(VillageImporter.piecePoolEntry(
"qa/pillager_outpost/piece/minecraft/pillager_outpost/watchtower",
7
));
assertEquals(1, entries.size());
assertEquals("minecraft:pillager_outpost/watchtower", resolution.templateLocation());
assertEquals(7, entries.getFirst().get("weight"));
assertEquals(1, resolution.omittedElements());
}
@Test
public void vanillaNbtMetadataIsReadFromTheJigsawBlockInfo() throws Exception {
FakeJigsawBlockInfo jigsaw = new FakeJigsawBlockInfo(-29, -17);
FakeStructureBlockInfo info = new FakeStructureBlockInfo(new FakeCompoundTag(FINAL_STATE));
PoolElementReader.ConnectorMetadata metadata = PoolElementReader.readConnectorMetadata(jigsaw, info);
assertEquals(Optional.of(FINAL_STATE), metadata.finalState());
assertEquals(-17, metadata.selectionPriority());
assertEquals(-29, metadata.placementPriority());
}
private record FakeJigsawBlockInfo(int placementPriority, int selectionPriority) {
}
private record FakeStructureBlockInfo(FakeCompoundTag nbt) {
}
private record FakeCompoundTag(String finalState) {
public Optional<String> getString(String key) {
return "final_state".equals(key) ? Optional.of(finalState) : Optional.empty();
}
}
private static final class FakeListPoolElement {
private final List<Object> elements;
private FakeListPoolElement(List<?> elements) {
this.elements = List.copyOf(elements);
}
public List<Object> getElements() {
return elements;
}
}
private static final class FakeSinglePoolElement {
private final FakeResourceLocation location;
private FakeSinglePoolElement(String location) {
String[] parts = location.split(":", 2);
this.location = new FakeResourceLocation(parts[0], parts[1]);
}
public FakeResourceLocation getTemplateLocation() {
return location;
}
}
private static final class FakeFeaturePoolElement {
}
private static final class FakeResourceLocation {
private final String namespace;
private final String path;
private FakeResourceLocation(String namespace, String path) {
this.namespace = namespace;
this.path = path;
}
public String getNamespace() {
return namespace;
}
public String getPath() {
return path;
}
}
}
@@ -0,0 +1,44 @@
package art.arcane.iris.core.structure;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* JigsawStructure.maxDistanceFromCenter is a plain int on some server builds and a
* JigsawStructure$MaxDistance record ({int horizontal, int vertical}) on others (e.g. Leaf
* 26.2-33). The reflective member reader must handle both — the wrapper shape previously threw
* IllegalArgumentException from Field.getInt, failing the jigsaw import of every datapack
* structure ("Failed to read jigsaw structure graph").
*/
public class ServerReflectionMaxDistanceReadTest {
private static final class IntShape {
private final int maxDistanceFromCenter = 80;
}
private record MaxDistance(int horizontal, int vertical) {
}
private static final class WrapperShape {
private final MaxDistance maxDistanceFromCenter = new MaxDistance(96, 48);
}
private static final class BoxedShape {
private final Integer maxDistanceFromCenter = 64;
}
@Test
public void readsPlainIntField() throws Exception {
assertEquals(80, ServerReflection.readIntMember(new IntShape(), "maxDistanceFromCenter"));
}
@Test
public void readsLargestIntComponentFromWrapperRecord() throws Exception {
assertEquals(96, ServerReflection.readIntMember(new WrapperShape(), "maxDistanceFromCenter"));
}
@Test
public void readsBoxedNumberField() throws Exception {
assertEquals(64, ServerReflection.readIntMember(new BoxedShape(), "maxDistanceFromCenter"));
}
}
@@ -0,0 +1,80 @@
package art.arcane.iris.core.toolworld;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.world.ToolItem;
import com.volmit.tooling.world.ToolText;
import net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.junit.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BukkitToolItemsTest {
private ItemStack stackWith(PersistentDataContainer data, ItemMeta meta) {
ItemStack stack = mock(ItemStack.class);
when(stack.getType()).thenReturn(Material.STICK);
when(stack.hasItemMeta()).thenReturn(true);
when(stack.getItemMeta()).thenReturn(meta);
when(meta.getPersistentDataContainer()).thenReturn(data);
return stack;
}
@Test
public void aStackWithThePayloadReadsBackAsTheToolItemItWasMadeFrom() {
PersistentDataContainer data = mock(PersistentDataContainer.class);
ItemMeta meta = mock(ItemMeta.class);
when(data.get(BukkitToolItems.PAYLOAD_KEY, PersistentDataType.STRING)).thenReturn("select:bay-1");
when(meta.hasDisplayName()).thenReturn(true);
when(meta.displayName()).thenReturn(Component.text("Select bay"));
when(meta.hasLore()).thenReturn(true);
when(meta.lore()).thenReturn(List.of(Component.text("Right-click to use")));
when(meta.getEnchantmentGlintOverride()).thenReturn(true);
Optional<ToolItem> item = BukkitToolItems.read(stackWith(data, meta));
assertEquals(Optional.of(new ToolItem(ResourceId.parse("minecraft:stick"), ToolText.plain("Select bay"),
List.of(ToolText.plain("Right-click to use")), true, "select:bay-1")), item);
}
@Test
public void anEmptyPayloadStillMakesAToolItemAndAMissingOneDoesNot() {
PersistentDataContainer empty = mock(PersistentDataContainer.class);
when(empty.get(BukkitToolItems.PAYLOAD_KEY, PersistentDataType.STRING)).thenReturn("");
PersistentDataContainer missing = mock(PersistentDataContainer.class);
ToolItem tagged = BukkitToolItems.read(stackWith(empty, mock(ItemMeta.class))).orElseThrow();
assertEquals("", tagged.payload());
assertEquals(ToolText.EMPTY, tagged.name());
assertEquals(List.of(), tagged.lore());
assertTrue(BukkitToolItems.read(stackWith(missing, mock(ItemMeta.class))).isEmpty());
}
@Test
public void nothingAirOrAStackWithoutMetadataIsNotAToolItem() {
ItemStack air = mock(ItemStack.class);
when(air.getType()).thenReturn(Material.AIR);
ItemStack plain = mock(ItemStack.class);
when(plain.getType()).thenReturn(Material.STICK);
when(plain.hasItemMeta()).thenReturn(false);
assertTrue(BukkitToolItems.read(null).isEmpty());
assertTrue(BukkitToolItems.read(air).isEmpty());
assertTrue(BukkitToolItems.read(plain).isEmpty());
}
@Test
public void thePayloadLivesUnderTheIrisToolPayloadKey() {
assertEquals("iris:tool_payload", BukkitToolItems.PAYLOAD_KEY.toString());
}
}
@@ -0,0 +1,61 @@
package art.arcane.iris.core.toolworld;
import com.volmit.tooling.world.TextColor;
import com.volmit.tooling.world.ToolText;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BukkitToolTextTest {
private static final String SECTION = "§";
@Test
public void legacyTextHasTheColourCodeOfEachSpanAsTheOldMenusWroteThem() {
ToolText text = ToolText.builder().aqua("Structure").gray(": village").build();
assertEquals(SECTION + "bStructure" + SECTION + "7: village", BukkitToolText.legacy(text));
}
@Test
public void anUncolouredSpanAfterAnotherResets() {
ToolText text = ToolText.builder().yellow("Walk").append(" plain").build();
assertEquals(SECTION + "eWalk" + SECTION + "r plain", BukkitToolText.legacy(text));
assertEquals("plain", BukkitToolText.legacy(ToolText.plain("plain")));
assertEquals("", BukkitToolText.legacy(ToolText.EMPTY));
}
@Test
public void stylesFollowTheColour() {
ToolText text = ToolText.builder()
.append(new ToolText.Span("x", TextColor.GRAY, true, true, true)).build();
assertEquals(SECTION + "7" + SECTION + "l" + SECTION + "o" + SECTION + "mx", BukkitToolText.legacy(text));
}
@Test
public void aComponentCarriesTheColoursAndTheTextOfEverySpan() {
ToolText text = ToolText.builder().red("a").append("b").build();
Component component = BukkitToolText.component(text);
assertEquals("ab", PlainTextComponentSerializer.plainText().serialize(component));
assertEquals(NamedTextColor.RED, component.children().getFirst().color());
assertEquals(null, component.children().getLast().color());
assertEquals(TextDecoration.State.NOT_SET, component.children().getFirst().decoration(TextDecoration.ITALIC));
}
@Test
public void aTitleTooLongForTheWindowIsCutWithoutLeavingHalfACode() {
ToolText coloured = ToolText.colored(TextColor.GREEN, "x".repeat(40));
String cut = BukkitToolMenus.shortened(coloured);
assertEquals(32, cut.length());
assertEquals(SECTION + "a", cut.substring(0, 2));
}
}
@@ -0,0 +1,125 @@
package art.arcane.iris.core.toolworld;
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity;
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedChunk;
import com.volmit.object.BlockEntityData;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.world.TextColor;
import com.volmit.tooling.world.ToolText;
import org.bukkit.World;
import org.junit.Test;
import java.util.List;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** The small pieces of state the Bukkit host keeps for its tool worlds. */
public class ToolWorldBookkeepingTest {
private static final BlockEntityData DATA = new BlockEntityData(ResourceId.parse("iris:tile"), 1, new byte[] {1});
@Test
public void aPlayerEntersAndLeavesOncePerStay() {
ToolWorldPresence presence = new ToolWorldPresence();
UUID player = UUID.randomUUID();
assertFalse(presence.leave(player));
assertTrue(presence.enter(player));
assertFalse(presence.enter(player));
assertTrue(presence.isPresent(player));
assertTrue(presence.leave(player));
assertFalse(presence.leave(player));
assertTrue("a second stay is told again", presence.enter(player));
}
@Test
public void blockEntitiesWaitForTheirChunkAndAreHandedOverOnce() {
PendingBlockEntities pending = new PendingBlockEntities();
PaintedBlockEntity chest = new PaintedBlockEntity(1, 64, 2, DATA);
pending.add(new PaintedChunk(-3, 7, List.of(chest)));
assertEquals(List.of(), pending.take(3, 7));
assertEquals(List.of(), pending.take(-3, -7));
assertEquals(List.of(chest), pending.take(-3, 7));
assertEquals(List.of(), pending.take(-3, 7));
}
@Test
public void aLaterPaintOfAChunkReplacesWhatWaitedForIt() {
PendingBlockEntities pending = new PendingBlockEntities();
PaintedBlockEntity first = new PaintedBlockEntity(1, 64, 2, DATA);
PaintedBlockEntity second = new PaintedBlockEntity(3, 64, 4, DATA);
pending.add(new PaintedChunk(0, 0, List.of(first)));
pending.add(new PaintedChunk(0, 0, List.of(second)));
assertEquals(List.of(second), pending.take(0, 0));
}
@Test
public void aToolNameIsTakenWithinAPackAndFreeAgainOnceTheWorldIsUnregistered() {
OpenToolWorlds worlds = new OpenToolWorlds();
BukkitToolWorld first = toolWorld(worlds, "pack-a", "scratch", "iris-1");
BukkitToolWorld sameNameOtherPack = toolWorld(worlds, "pack-b", "scratch", "iris-2");
BukkitToolWorld sameNameSamePack = toolWorld(worlds, "pack-a", "scratch", "iris-3");
assertTrue(worlds.register(first));
assertTrue(worlds.register(sameNameOtherPack));
assertFalse(worlds.register(sameNameSamePack));
assertEquals(first, worlds.forName("pack-a", "scratch").orElseThrow());
worlds.unregister(first);
assertTrue(worlds.forName("pack-a", "scratch").isEmpty());
assertTrue(worlds.register(sameNameSamePack));
}
@Test
public void aBoundWorldIsFoundByItsBukkitWorldAndNotByAnotherWorld() {
OpenToolWorlds worlds = new OpenToolWorlds();
BukkitToolWorld toolWorld = toolWorld(worlds, "pack", "scratch", "iris-1");
World bukkit = world(UUID.randomUUID());
World other = world(UUID.randomUUID());
assertTrue(worlds.register(toolWorld));
toolWorld.bind(bukkit);
assertEquals(toolWorld, worlds.forWorld(bukkit).orElseThrow());
assertTrue(worlds.forWorld(other).isEmpty());
assertTrue(worlds.forWorld(null).isEmpty());
worlds.unregister(toolWorld);
assertTrue(worlds.forWorld(bukkit).isEmpty());
}
@Test
public void aMenuSlotCountsFromTheMiddleColumnOfTheWindow() {
assertEquals(-4, BukkitToolMenus.positionOf(0));
assertEquals(0, BukkitToolMenus.positionOf(4));
assertEquals(4, BukkitToolMenus.positionOf(8));
assertEquals(-4, BukkitToolMenus.positionOf(9));
assertEquals(4, BukkitToolMenus.positionOf(53));
}
@Test
public void aMenuTitleIsShortenedToWhatTheWindowCanShow() {
assertEquals("short", BukkitToolMenus.shortened(ToolText.plain("short")));
assertEquals(32, BukkitToolMenus.shortened(ToolText.plain("x".repeat(50))).length());
assertEquals("§a" + "x".repeat(30), BukkitToolMenus.shortened(ToolText.colored(TextColor.GREEN, "x".repeat(50))));
}
private static BukkitToolWorld toolWorld(OpenToolWorlds worlds, String pack, String name, String storageName) {
return new BukkitToolWorld(pack, name, storageName, new com.volmit.tooling.world.ToolWorldListener() { }, null,
new PendingBlockEntities(), worlds, new ToolPlayers(worlds));
}
private static World world(UUID id) {
World world = mock(World.class);
when(world.getUID()).thenReturn(id);
return world;
}
}
@@ -0,0 +1,548 @@
package art.arcane.iris.core.toolworld;
import com.volmit.geometry.BlockPosition;
import com.volmit.tooling.world.BlockChange;
import com.volmit.tooling.world.BlockChange.Cause;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolUse;
import com.volmit.tooling.world.ToolWorldListener;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.CrafterCraftEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.event.block.Action;
import org.bukkit.inventory.EquipmentSlot;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** The events of a tool world reach its listener as the api says, and the events of other worlds reach nobody. */
public class ToolWorldEventsTest {
private static final UUID TOOL_WORLD_ID = UUID.fromString("00000000-0000-0000-0000-0000000000a1");
private static final UUID OTHER_WORLD_ID = UUID.fromString("00000000-0000-0000-0000-0000000000b2");
private static final UUID PLAYER_ID = UUID.fromString("00000000-0000-0000-0000-0000000000c3");
private final List<BlockChange> changes = new ArrayList<>();
private final List<String> heard = new ArrayList<>();
private boolean allowChanges;
private boolean allowUses = true;
private boolean allowCommands = true;
private World toolBukkitWorld;
private World otherBukkitWorld;
private Player bukkitPlayer;
private ToolWorldEvents events;
@Before
public void aToolWorldAndAnotherWorld() {
ToolWorldListener listener = new ToolWorldListener() {
@Override
public void entered(ToolPlayer player) {
heard.add("entered " + player.name());
}
@Override
public void left(ToolPlayer player) {
heard.add("left " + player.name());
}
@Override
public void teleported(ToolPlayer player, BlockPosition to) {
heard.add("teleported " + player.name() + " " + to.x() + "," + to.y() + "," + to.z());
}
@Override
public void containerChanged(Optional<ToolPlayer> player, BlockPosition at) {
heard.add("container " + player.map(ToolPlayer::name).orElse("nobody") + " " + at.x() + "," + at.y() + "," + at.z());
}
@Override
public boolean used(ToolPlayer player, ToolUse use) {
heard.add("used " + use.action() + " " + use.hand());
return allowUses;
}
@Override
public boolean blockChanging(BlockChange change) {
changes.add(change);
return allowChanges;
}
@Override
public boolean command(Optional<ToolPlayer> sender, String line) {
heard.add("command " + sender.map(ToolPlayer::name).orElse("console") + " " + line);
return allowCommands;
}
};
OpenToolWorlds worlds = new OpenToolWorlds();
ToolPlayers players = new ToolPlayers(worlds);
BukkitToolWorld toolWorld = new BukkitToolWorld("pack", "scratch", "iris-test", listener, null,
new PendingBlockEntities(), worlds, players);
toolBukkitWorld = world(TOOL_WORLD_ID);
otherBukkitWorld = world(OTHER_WORLD_ID);
assertTrue(worlds.register(toolWorld));
toolWorld.bind(toolBukkitWorld);
bukkitPlayer = mock(Player.class);
when(bukkitPlayer.getUniqueId()).thenReturn(PLAYER_ID);
when(bukkitPlayer.getName()).thenReturn("Tester");
when(bukkitPlayer.getWorld()).thenReturn(toolBukkitWorld);
events = new ToolWorldEvents(worlds, players);
}
private static World world(UUID id) {
World world = mock(World.class);
when(world.getUID()).thenReturn(id);
return world;
}
private static Block block(World world, int x, int y, int z) {
Block block = mock(Block.class);
when(block.getWorld()).thenReturn(world);
when(block.getX()).thenReturn(x);
when(block.getY()).thenReturn(y);
when(block.getZ()).thenReturn(z);
BlockData data = mock(BlockData.class);
when(data.getAsString()).thenReturn("minecraft:stone");
when(block.getBlockData()).thenReturn(data);
return block;
}
private BlockChange onlyChange() {
assertEquals(1, changes.size());
return changes.getFirst();
}
@Test
public void aPlacedBlockIsAPlaceChangeWithThePlacedStateAndThePlayer() {
Block placed = block(toolBukkitWorld, 3, 70, -4);
BlockPlaceEvent event = mock(BlockPlaceEvent.class);
when(event.getBlockPlaced()).thenReturn(placed);
when(event.getPlayer()).thenReturn(bukkitPlayer);
events.onBlockPlace(event);
BlockChange change = onlyChange();
assertEquals(Cause.PLACE, change.cause());
assertEquals(List.of(new BlockPosition(3, 70, -4)), change.positions());
assertEquals("minecraft:stone", change.placed().orElseThrow().key());
assertEquals("Tester", change.player().orElseThrow().name());
verify(event).setCancelled(true);
}
@Test
public void aListenerThatAllowsTheChangeLeavesTheEventAlone() {
allowChanges = true;
Block broken = block(toolBukkitWorld, 1, 2, 3);
BlockBreakEvent event = mock(BlockBreakEvent.class);
when(event.getBlock()).thenReturn(broken);
when(event.getPlayer()).thenReturn(bukkitPlayer);
events.onBlockBreak(event);
assertEquals(Cause.BREAK, onlyChange().cause());
verify(event, never()).setCancelled(true);
}
@Test
public void aBucketEmptiesIntoTheBlockNextToTheOneClicked() {
Block clicked = block(toolBukkitWorld, 0, 64, 0);
Block target = block(toolBukkitWorld, 0, 65, 0);
when(clicked.getRelative(BlockFace.UP)).thenReturn(target);
PlayerBucketEmptyEvent event = mock(PlayerBucketEmptyEvent.class);
when(event.getBlockClicked()).thenReturn(clicked);
when(event.getBlockFace()).thenReturn(BlockFace.UP);
when(event.getPlayer()).thenReturn(bukkitPlayer);
events.onBucketEmpty(event);
BlockChange change = onlyChange();
assertEquals(Cause.BUCKET, change.cause());
assertEquals(List.of(new BlockPosition(0, 65, 0)), change.positions());
}
@Test
public void flowingFluidNamesTheSourceAndTheTargetBlock() {
Block source = block(toolBukkitWorld, 0, 64, 0);
Block target = block(toolBukkitWorld, 1, 64, 0);
BlockFromToEvent event = mock(BlockFromToEvent.class);
when(event.getBlock()).thenReturn(source);
when(event.getToBlock()).thenReturn(target);
events.onBlockFromTo(event);
BlockChange change = onlyChange();
assertEquals(Cause.FLUID, change.cause());
assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0)), change.positions());
assertTrue(change.player().isEmpty());
verify(event).setCancelled(true);
}
@Test
public void aPistonIsCheckedAgainstEveryBlockItMovesAndTheBlocksTheyLeaveAndEnterButNotItself() {
Block piston = block(toolBukkitWorld, 0, 64, 0);
Block moved = block(toolBukkitWorld, 1, 64, 0);
Block ahead = block(toolBukkitWorld, 2, 64, 0);
when(moved.getRelative(BlockFace.EAST)).thenReturn(ahead);
when(moved.getRelative(BlockFace.WEST)).thenReturn(piston);
List<BlockPosition> positions = ToolWorldEvents.pistonChecked(List.of(moved), BlockFace.EAST);
assertEquals(List.of(new BlockPosition(1, 64, 0), new BlockPosition(2, 64, 0), new BlockPosition(0, 64, 0)), positions);
}
@Test
public void aPistonChangesItselfTheBlockAheadOfItAndEveryBlockItMovesAndWhereTheyGo() {
Block piston = block(toolBukkitWorld, 0, 64, 0);
Block moved = block(toolBukkitWorld, 1, 64, 0);
Block ahead = block(toolBukkitWorld, 2, 64, 0);
when(piston.getRelative(BlockFace.EAST)).thenReturn(moved);
when(moved.getRelative(BlockFace.EAST)).thenReturn(ahead);
List<BlockPosition> changed = ToolWorldEvents.pistonChanged(piston, List.of(moved), BlockFace.EAST);
assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0), new BlockPosition(2, 64, 0)), changed);
}
@Test
public void aPistonThatMovesNothingStillChangesItsOwnBlocks() {
Block piston = block(toolBukkitWorld, 0, 64, 0);
Block ahead = block(toolBukkitWorld, 1, 64, 0);
when(piston.getRelative(BlockFace.EAST)).thenReturn(ahead);
BlockPistonExtendEvent event = mock(BlockPistonExtendEvent.class);
when(event.getBlock()).thenReturn(piston);
when(event.getBlocks()).thenReturn(List.of());
when(event.getDirection()).thenReturn(BlockFace.EAST);
events.onPistonExtend(event);
BlockChange change = onlyChange();
assertEquals(List.of(), change.positions());
assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0)), change.changed());
}
@Test
public void aPistonExtendingInAToolWorldIsAPistonChange() {
Block piston = block(toolBukkitWorld, 0, 64, 0);
Block ahead = block(toolBukkitWorld, 1, 64, 0);
when(piston.getRelative(BlockFace.EAST)).thenReturn(ahead);
BlockPistonExtendEvent event = mock(BlockPistonExtendEvent.class);
when(event.getBlock()).thenReturn(piston);
when(event.getBlocks()).thenReturn(List.of());
when(event.getDirection()).thenReturn(BlockFace.EAST);
events.onPistonExtend(event);
assertEquals(Cause.PISTON, onlyChange().cause());
verify(event).setCancelled(true);
}
@Test
public void anExplosionAsksForEachBlockAndKeepsOnlyTheOnesTheToolAllows() {
allowChanges = false;
Block first = block(toolBukkitWorld, 0, 64, 0);
Block second = block(toolBukkitWorld, 5, 64, 5);
List<Block> blockList = new ArrayList<>(List.of(first, second));
Block source = block(toolBukkitWorld, 0, 70, 0);
BlockExplodeEvent event = mock(BlockExplodeEvent.class);
when(event.getBlock()).thenReturn(source);
when(event.blockList()).thenReturn(blockList);
events.onBlockExplode(event);
assertEquals(2, changes.size());
assertEquals(Cause.EXPLOSION, changes.getFirst().cause());
assertTrue("nothing was allowed to blow up", blockList.isEmpty());
}
@Test
public void refusedRedstoneKeepsTheOldCurrent() {
Block wire = block(toolBukkitWorld, 0, 64, 0);
BlockRedstoneEvent event = mock(BlockRedstoneEvent.class);
when(event.getBlock()).thenReturn(wire);
when(event.getOldCurrent()).thenReturn(7);
events.onBlockRedstone(event);
assertEquals(Cause.REDSTONE, onlyChange().cause());
verify(event).setNewCurrent(7);
}
@Test
public void aCrafterIsAMachine() {
Block crafter = block(toolBukkitWorld, 0, 64, 0);
CrafterCraftEvent event = mock(CrafterCraftEvent.class);
when(event.getBlock()).thenReturn(crafter);
events.onCrafterCraft(event);
assertEquals(Cause.MACHINE, onlyChange().cause());
}
@Test
public void nothingThatHappensInAnotherWorldReachesTheToolOrIsCancelled() {
Block brokenElsewhere = block(otherBukkitWorld, 1, 2, 3);
Block wireElsewhere = block(otherBukkitWorld, 1, 2, 3);
BlockBreakEvent breaking = mock(BlockBreakEvent.class);
when(breaking.getBlock()).thenReturn(brokenElsewhere);
when(breaking.getPlayer()).thenReturn(bukkitPlayer);
BlockRedstoneEvent redstone = mock(BlockRedstoneEvent.class);
when(redstone.getBlock()).thenReturn(wireElsewhere);
events.onBlockBreak(breaking);
events.onBlockRedstone(redstone);
assertTrue(changes.isEmpty());
verify(breaking, never()).setCancelled(true);
verify(redstone, never()).setNewCurrent(0);
}
@Test
public void usingTheHandIsAUseWithTheHandAndActionAndAFalseCancelsIt() {
allowUses = false;
PlayerInteractEvent event = mock(PlayerInteractEvent.class);
when(event.getPlayer()).thenReturn(bukkitPlayer);
when(event.getHand()).thenReturn(EquipmentSlot.OFF_HAND);
when(event.getAction()).thenReturn(Action.RIGHT_CLICK_AIR);
when(event.getBlockFace()).thenReturn(BlockFace.SELF);
events.onInteract(event);
assertEquals(List.of("used RIGHT_CLICK_AIR OFF"), heard);
verify(event).setCancelled(true);
}
@Test
public void aCommandReachesTheToolWithoutItsSlashAndTheConsoleHasNoPlayer() {
allowCommands = false;
PlayerCommandPreprocessEvent typed = mock(PlayerCommandPreprocessEvent.class);
when(typed.getPlayer()).thenReturn(bukkitPlayer);
when(typed.getMessage()).thenReturn("/gamemode survival");
ServerCommandEvent console = mock(ServerCommandEvent.class);
when(console.getCommand()).thenReturn("stop");
events.onPlayerCommand(typed);
events.onServerCommand(console);
assertEquals(List.of("command Tester gamemode survival", "command console stop"), heard);
verify(typed).setCancelled(true);
verify(console).setCancelled(true);
}
@Test
public void naturalSpawnsInAToolWorldAreCancelledButOtherSpawnsAreNot() {
CreatureSpawnEvent natural = mock(CreatureSpawnEvent.class);
when(natural.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.NATURAL);
when(natural.getLocation()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
CreatureSpawnEvent egg = mock(CreatureSpawnEvent.class);
when(egg.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.SPAWNER_EGG);
when(egg.getLocation()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
CreatureSpawnEvent elsewhere = mock(CreatureSpawnEvent.class);
when(elsewhere.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.NATURAL);
when(elsewhere.getLocation()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0));
events.onNaturalSpawn(natural);
events.onNaturalSpawn(egg);
events.onNaturalSpawn(elsewhere);
verify(natural).setCancelled(true);
verify(egg, never()).setCancelled(true);
verify(elsewhere, never()).setCancelled(true);
}
@Test
public void enteringIsToldOnceHoweverManyEventsAnnounceTheArrival() {
PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class);
when(teleport.getPlayer()).thenReturn(bukkitPlayer);
when(teleport.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0));
when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
events.onTeleport(teleport);
events.onTeleport(teleport);
assertEquals(List.of("entered Tester", "teleported Tester 0,64,0", "teleported Tester 0,64,0"), heard);
}
@Test
public void aTeleportInsideAToolWorldIsToldAtOnceWithItsDestination() {
PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class);
when(teleport.getPlayer()).thenReturn(bukkitPlayer);
when(teleport.getFrom()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 40, 70, -3));
events.onTeleport(teleport);
assertEquals(List.of("entered Tester", "teleported Tester 40,70,-3"), heard);
}
@Test
public void aTeleportOutOfAToolWorldIsToldAsLeaving() {
PlayerTeleportEvent in = mock(PlayerTeleportEvent.class);
when(in.getPlayer()).thenReturn(bukkitPlayer);
when(in.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0));
when(in.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
PlayerTeleportEvent out = mock(PlayerTeleportEvent.class);
when(out.getPlayer()).thenReturn(bukkitPlayer);
when(out.getFrom()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
when(out.getTo()).thenReturn(new Location(otherBukkitWorld, 5, 64, 5));
events.onTeleport(in);
events.onTeleport(out);
assertEquals(List.of("entered Tester", "teleported Tester 0,64,0", "left Tester"), heard);
}
@Test
public void respawningInAToolWorldIsAnArrivalAtTheRespawnPoint() {
PlayerRespawnEvent respawn = mock(PlayerRespawnEvent.class);
when(respawn.getPlayer()).thenReturn(bukkitPlayer);
when(respawn.getRespawnLocation()).thenReturn(new Location(toolBukkitWorld, 8, 66, 8));
events.onRespawn(respawn);
assertEquals(List.of("entered Tester", "teleported Tester 8,66,8"), heard);
}
@Test
public void closingAContainerInAToolWorldTellsTheToolWhichBlockChanged() {
Block chest = block(toolBukkitWorld, 4, 65, 4);
org.bukkit.inventory.Inventory inventory = mock(org.bukkit.inventory.Inventory.class);
org.bukkit.inventory.BlockInventoryHolder holder = mock(org.bukkit.inventory.BlockInventoryHolder.class);
when(holder.getBlock()).thenReturn(chest);
when(inventory.getHolder()).thenReturn(holder);
org.bukkit.inventory.InventoryView view = mock(org.bukkit.inventory.InventoryView.class);
when(view.getTopInventory()).thenReturn(inventory);
org.bukkit.event.inventory.InventoryCloseEvent close = mock(org.bukkit.event.inventory.InventoryCloseEvent.class);
when(close.getPlayer()).thenReturn(bukkitPlayer);
when(close.getView()).thenReturn(view);
events.onInventoryClose(close);
assertEquals(List.of("container Tester 4,65,4"), heard);
}
@Test
public void aFurnaceStartingToSmeltTellsTheToolWithoutAPlayer() {
Block furnace = block(toolBukkitWorld, 2, 64, 2);
org.bukkit.event.inventory.FurnaceStartSmeltEvent smelt = mock(org.bukkit.event.inventory.FurnaceStartSmeltEvent.class);
when(smelt.getBlock()).thenReturn(furnace);
events.onFurnaceStartSmelt(smelt);
assertEquals(List.of("container nobody 2,64,2"), heard);
}
@Test
public void leavingByQuittingIsToldOnceAfterTheStay() {
PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class);
when(teleport.getPlayer()).thenReturn(bukkitPlayer);
when(teleport.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0));
when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
PlayerQuitEvent quit = mock(PlayerQuitEvent.class);
when(quit.getPlayer()).thenReturn(bukkitPlayer);
events.onTeleport(teleport);
events.onQuit(quit);
events.onQuit(quit);
assertEquals(List.of("entered Tester", "teleported Tester 0,64,0", "left Tester"), heard);
}
@Test
public void movingInsideOneBlockIsNotAMove() {
Location from = new Location(toolBukkitWorld, 1.1, 64.0, 2.2);
assertTrue(ToolWorldEvents.sameBlock(from, new Location(toolBukkitWorld, 1.9, 64.5, 2.9)));
assertFalse(ToolWorldEvents.sameBlock(from, new Location(toolBukkitWorld, 2.1, 64.0, 2.2)));
assertFalse(ToolWorldEvents.sameBlock(from, new Location(otherBukkitWorld, 1.1, 64.0, 2.2)));
}
@Test
public void aCommandLineHasNoLeadingSlash() {
assertEquals("tp a b", ToolWorldEvents.lineOf("/tp a b"));
assertEquals("tp a b", ToolWorldEvents.lineOf("tp a b"));
}
@Test
public void everyHandlerKeepsThePriorityAndCancelFlagOfTheJigsawStudioHandlerItReplaces() {
Map<String, EventHandler> byMethod = new HashMap<>();
for (Method method : ToolWorldEvents.class.getDeclaredMethods()) {
EventHandler handler = method.getAnnotation(EventHandler.class);
if (handler != null) {
byMethod.put(method.getName(), handler);
}
}
Set<String> checked = new HashSet<>();
for (String decision : List.of("onBlockPlace", "onBlockMultiPlace", "onBlockBreak", "onBucketEmpty", "onBucketFill",
"onBlockForm", "onBlockFade", "onBlockSpread", "onBlockFromTo", "onBlockGrow", "onStructureGrow", "onBlockBurn",
"onPistonExtend", "onPistonRetract", "onBlockExplode", "onEntityExplode", "onEntityChangeBlock",
"onInventoryClick", "onInventoryDrag", "onInventoryMove", "onInventoryPickup", "onBlockCook", "onFurnaceBurn",
"onFurnaceSmelt", "onBrew", "onBrewingStandFuel", "onBlockDispense", "onCrafterCraft", "onPlayerCommand",
"onServerCommand", "onNaturalSpawn", "onPortal")) {
assertPriority(byMethod, checked, decision, EventPriority.HIGHEST, true);
}
assertPriority(byMethod, checked, "onBlockRedstone", EventPriority.HIGHEST, false);
assertPriority(byMethod, checked, "onInteract", EventPriority.LOWEST, true);
assertPriority(byMethod, checked, "onToggleSneak", EventPriority.NORMAL, false);
for (String arrival : List.of("onJoin", "onQuit", "onChangedWorld", "onChunkLoad")) {
assertPriority(byMethod, checked, arrival, EventPriority.NORMAL, false);
}
assertPriority(byMethod, checked, "onTeleport", EventPriority.MONITOR, true);
assertPriority(byMethod, checked, "onMove", EventPriority.MONITOR, true);
assertPriority(byMethod, checked, "onRespawn", EventPriority.MONITOR, false);
for (String containerNews : List.of("onInventoryClose", "onFurnaceStartSmelt", "onBrewingStart")) {
assertPriority(byMethod, checked, containerNews, EventPriority.MONITOR, false);
}
assertPriority(byMethod, checked, "onWorldUnload", EventPriority.MONITOR, true);
assertEquals("every handler of the class was checked", byMethod.keySet(), checked);
}
private static void assertPriority(
Map<String, EventHandler> byMethod,
Set<String> checked,
String method,
EventPriority priority,
boolean ignoreCancelled
) {
checked.add(method);
EventHandler handler = byMethod.get(method);
assertTrue(method + " is a handler", handler != null);
assertEquals(method + " priority", priority, handler.priority());
assertEquals(method + " ignoreCancelled", ignoreCancelled, handler.ignoreCancelled());
}
}