Move the jigsaw commands and the structure importers onto the tooling api

Add PlatformStructures, the capability the structure importers read the platform through: templates, registered
structures and structure sets, jigsaw structures, template pools with their connectors, and a closable capture area.
The Bukkit host implements it in the plugin and takes over all reflection, the structure manager and the NMS calls; the
importers keep only their model-building logic and report through the api sender. CommandContext.platformStructures()
reaches it, ToolPlayer.targetBlock() lets a command read what the player looks at.

CommandJigsaw, JigsawStudioBridge, IrisStructureHandler, the Director import and capture of CommandStructure and the
modded stubs that explained the Bukkit workflow are replaced by the neutral jigsaw command tree in
core/structure/tooling, mounted by StructureModelModule. Import and capture are now jigsaw sub-commands.

The graph editor, the vanilla exporter and StructureIndexService speak api types: IrisObject hands out its contents as
BlockState and BlockEntityData, exports go below ToolPack.outputFolder(), and the index writes through ToolPack.edit.
The move lint is at 0 for the B2 set.
This commit is contained in:
piexel committed 2026-11-10 00:27:03 +01:00
1 parent 23c93e6e74
commit ae11b38093
82 files changed
+6529 -4789

No files matched your search

@@ -47,7 +47,11 @@ 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.BukkitJigsawStudioHost;
import art.arcane.iris.core.structure.BukkitPlatformStructures;
import art.arcane.iris.core.structure.tooling.JigsawStudioHost;
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.IrisPapiInstaller;
import art.arcane.iris.core.link.IrisPapiListener;
@@ -651,6 +655,8 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
IrisServices.register(serviceType, i);
}
IrisServices.register(ToolWorldsHost.class, services.get(BukkitToolWorldService.class));
IrisServices.register(PlatformStructures.class, new BukkitPlatformStructures());
IrisServices.register(JigsawStudioHost.class, new BukkitJigsawStudioHost());
IrisServices.register(BlockEditAccess.class, services.get(EditSVC.class));
IrisServices.register(PreservationRegistry.class, services.get(PreservationSVC.class));
compat = IrisCompat.configured(getDataFile("compat.json"));
@@ -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())));
}
}
@@ -1,146 +0,0 @@
package art.arcane.iris.core.commands;
import art.arcane.iris.Iris;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.IrisModuleHost;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
import art.arcane.iris.core.service.JigsawStudioGraphEvaluation;
import art.arcane.iris.core.service.JigsawStudioRegistry;
import art.arcane.iris.core.service.JigsawStudioService;
import art.arcane.iris.core.toolworld.BukkitToolWorldService;
import art.arcane.iris.core.tooling.IrisToolPack;
import art.arcane.iris.spi.IrisServices;
import com.volmit.tooling.ToolPack;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolWorld;
import org.bukkit.entity.Player;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* What the Director commands of the Jigsaw Studio need to reach the studio, which speaks the tool world api: the studio,
* the pack as a {@link ToolPack}, and a Bukkit player as a {@link ToolPlayer}. It goes when the commands are rewritten
* as api commands, which hand the studio their own sender's player and pack.
*/
final class JigsawStudioBridge {
private final JigsawStudioService service;
private JigsawStudioBridge(JigsawStudioService service) {
this.service = service;
}
static JigsawStudioBridge get() {
return new JigsawStudioBridge(Iris.jigsawStudio());
}
static ToolPlayer toolPlayer(Player player) {
return IrisServices.get(BukkitToolWorldService.class).playerOf(player);
}
static ToolPack toolPack(IrisData data) {
return new IrisToolPack(data, IrisModuleHost.hostLog());
}
JigsawStudioRegistry registry() {
return service.registry();
}
CompletableFuture<ToolWorld> open(IrisData data, JigsawStudioRegistry.StagedActivation staged) {
return service.open(toolPack(data), staged);
}
void activationCommitted(UUID requestId) {
service.activationCommitted(requestId);
}
JigsawStudioService.CloseStart tryBeginClose(UUID requestId, UUID ownerId, boolean discard) {
return service.tryBeginClose(requestId, ownerId, discard);
}
void cancelClose(UUID requestId) {
service.cancelClose(requestId);
}
JigsawStudioService.ExportStart tryBeginExport(UUID requestId, UUID ownerId) {
return service.tryBeginExport(requestId, ownerId);
}
void finishExport(UUID requestId) {
service.finishExport(requestId);
}
boolean runCommandGraphMutation(
Player player,
UUID expectedRequestId,
JigsawStudioService.CommandGraphMutation mutation
) {
return service.runCommandGraphMutation(toolPlayer(player), expectedRequestId, mutation);
}
boolean deleteProject(Player player) {
return service.deleteProject(toolPlayer(player));
}
Optional<JigsawStudioGraphEvaluation> evaluation(Player player) {
return service.evaluation(toolPlayer(player));
}
boolean openControlMenu(Player player) {
return service.openControlMenu(toolPlayer(player));
}
boolean updateWorkcellDimensions(Player player, String workcellId, JigsawStudioCellDimensions dimensions) {
return service.updateWorkcellDimensions(toolPlayer(player), workcellId, dimensions);
}
boolean flushAutosave(Player player, String workcellId) {
return service.flushAutosave(toolPlayer(player), workcellId);
}
boolean teleportTo(Player player, String bayId) {
return service.teleportTo(toolPlayer(player), bayId);
}
boolean setParticles(Player player, boolean visible) {
return service.setParticles(toolPlayer(player), visible);
}
boolean expandVariantToCell(Player player, String workcellId) {
return service.expandVariantToCell(toolPlayer(player), workcellId);
}
boolean updateWorkcellDisplayName(Player player, String workcellId, String displayName) {
return service.updateWorkcellDisplayName(toolPlayer(player), workcellId, displayName);
}
boolean resizeVariant(
Player player,
String workcellId,
String pieceKey,
JigsawStudioCellDimensions dimensions
) {
return service.resizeVariant(toolPlayer(player), workcellId, pieceKey, dimensions);
}
boolean updateVariantDisplayName(Player player, String workcellId, String pieceKey, String displayName) {
return service.updateVariantDisplayName(toolPlayer(player), workcellId, pieceKey, displayName);
}
boolean createVariant(Player player, String workcellId, boolean duplicateActive) {
return service.createVariant(toolPlayer(player), workcellId, duplicateActive);
}
boolean duplicateActiveFamily(Player player, String themeKey) {
return service.duplicateActiveFamily(toolPlayer(player), themeKey);
}
boolean goToPreview(Player player) {
return service.goToPreview(toolPlayer(player));
}
boolean previewStudio(Player player, long seed) {
return service.previewStudio(toolPlayer(player), seed);
}
}
@@ -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,85 @@
/*
* 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.structure;
import art.arcane.iris.Iris;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.pack.BrokenPackException;
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
import art.arcane.iris.core.service.JigsawStudioService;
import art.arcane.iris.core.service.StudioSVC;
import art.arcane.iris.core.structure.tooling.JigsawStudioHost;
import art.arcane.iris.core.tooling.IrisToolPack;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.util.common.plugin.VolmitSender;
import com.volmit.tooling.Sender;
import com.volmit.tooling.ToolPack;
import org.bukkit.command.CommandSender;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
/** The Jigsaw Studio of this plugin, and the Bukkit server services the jigsaw commands need around it. */
public final class BukkitJigsawStudioHost implements JigsawStudioHost {
static final StudioOpenCoordinator.StudioOpenKind STUDIO_OPEN_KIND = StudioOpenCoordinator.StudioOpenKind.TOOL;
private static final String UNKNOWN_CLOSE_FAILURE = "unknown failure";
@Override
public JigsawStudioService studio() {
return Iris.jigsawStudio();
}
@Override
public IrisData dataOf(ToolPack pack) {
return IrisToolPack.dataOf(pack);
}
@Override
public String packKey(ToolPack pack) {
return IrisToolPack.dataOf(pack).getDataFolder().getName();
}
@Override
public Optional<Throwable> reportAdmissionFailure(Sender sender, String packKey) {
VolmitSender messages = sender.extension(CommandSender.class).map(VolmitSender::new).orElseGet(BukkitPlatform::console);
return Optional.ofNullable(StudioSVC.reportPackAdmissionFailure(messages, packKey, STUDIO_OPEN_KIND));
}
@Override
public boolean isExpectedOpenDenial(Throwable failure) {
return unwrapCompletionFailure(failure) instanceof BrokenPackException;
}
@Override
public CompletableFuture<Optional<Throwable>> closeStudio() {
return Iris.service(StudioSVC.class).close().thenApply(result -> {
Throwable failure = result == null ? new IllegalStateException(UNKNOWN_CLOSE_FAILURE) : result.failureCause();
return Optional.ofNullable(failure);
});
}
private static Throwable unwrapCompletionFailure(Throwable failure) {
Throwable current = failure;
while (current instanceof CompletionException && current.getCause() != null) {
current = current.getCause();
}
return current;
}
}
@@ -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;
}
}
@@ -99,6 +99,11 @@ final class BukkitToolPlayer implements ToolPlayer {
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();