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);
}
}