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();
@@ -1,609 +0,0 @@
package art.arcane.iris.core.commands;
import art.arcane.iris.core.pack.BrokenPackException;
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioWorkcellSpec;
import art.arcane.iris.core.service.JigsawStudioService;
import art.arcane.iris.core.structure.authoring.StructureBackend;
import art.arcane.iris.core.structure.authoring.StructureCapability;
import art.arcane.iris.core.structure.authoring.StructureHash;
import art.arcane.iris.core.structure.authoring.StructureKey;
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
import art.arcane.iris.core.structure.authoring.StructureSource;
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionInputKind;
import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat;
import art.arcane.iris.core.tools.IrisCreator;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.util.common.director.specialhandlers.IrisStructureHandler;
import art.arcane.volmlib.util.director.DirectorOrigin;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
import art.arcane.volmlib.util.director.exceptions.DirectorParsingException;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class CommandJigsawContractTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void commandIrisRegistersJigsawTree() throws Exception {
Field field = CommandIris.class.getDeclaredField("jigsaw");
assertEquals(CommandJigsaw.class, field.getType());
assertNotNull(CommandJigsaw.class.getDeclaredField("piece"));
assertNotNull(CommandJigsaw.class.getDeclaredField("pool"));
assertNotNull(CommandJigsaw.class.getDeclaredField("connector"));
assertNotNull(CommandJigsaw.class.getDeclaredField("variant"));
assertNotNull(CommandJigsaw.class.getDeclaredField("workcell"));
assertNotNull(CommandJigsaw.class.getDeclaredField("rules"));
assertNotNull(CommandJigsaw.class.getDeclaredField("preview"));
assertNotNull(CommandJigsaw.class.getDeclaredField("adopt"));
}
@Test
public void exposesStudioLifecycleAndAuthoringCommands() throws Exception {
assertCommand("create", IrisDimension.class, String.class, String.class, String.class,
int.class, int.class, int.class, long.class);
assertCommand("convert", IrisDimension.class, String.class, String.class, long.class);
assertCommand("open", IrisDimension.class, String.class, long.class);
assertCommand("close", boolean.class);
assertCommand("delete", boolean.class);
assertCommand("status");
assertCommand("menu");
assertCommand("select");
assertCommand("bounds", int.class, int.class, int.class);
assertCommand("save", String.class);
assertCommand("gotoBay", String.class);
assertCommand("particles", boolean.class);
assertCommand("export", String.class, String.class, String.class, boolean.class);
}
@Test
public void jigsawStudioUsesItsDedicatedOpenLifecycle() {
assertEquals(
StudioOpenCoordinator.StudioOpenKind.TOOL,
CommandJigsaw.STUDIO_OPEN_KIND);
assertFalse(CommandJigsaw.STUDIO_OPEN_KIND.openWorkspace());
assertFalse(CommandJigsaw.STUDIO_OPEN_KIND.teleportThroughStandardEntry());
assertEquals(
IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY,
CommandJigsaw.STUDIO_OPEN_KIND.datapackPreparation());
}
@Test
public void packValidationDenialsAreExpectedOpenFailures() {
BrokenPackException failure = new BrokenPackException(
"overworld", List.of("Biome 'broken' has no resolvable regions."));
assertTrue(CommandJigsaw.isExpectedOpenDenial(failure));
assertTrue(CommandJigsaw.isExpectedOpenDenial(
new CompletionException(failure)));
assertFalse(CommandJigsaw.isExpectedOpenDenial(
new IllegalStateException("Unexpected Studio failure")));
}
@Test
public void committedActivationStartsInitialEvaluationBeforePlayerBinding() throws Exception {
String source = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
int commit = source.indexOf("registry().commit(staged)");
int evaluation = source.indexOf(
"studioService.activationCommitted(request.requestId())",
commit);
int binding = source.indexOf("PLAYER_PACKS.put", evaluation);
assertTrue(commit >= 0);
assertTrue(evaluation > commit);
assertTrue(binding > evaluation);
}
@Test
public void convertIsAddOnlyWorkflowWithAliasesAndDefaults() throws Exception {
Method convert = CommandJigsaw.class.getDeclaredMethod(
"convert", IrisDimension.class, String.class, String.class, long.class);
Director command = convert.getAnnotation(Director.class);
Parameter[] parameters = convert.getParameters();
assertEquals(List.of("import", "import-vanilla"), List.of(command.aliases()));
assertParameter(parameters[2], "auto", null);
assertParameter(parameters[3], "1337", null);
NamespacedKey source = CommandJigsaw.parseRegisteredStructureKey("minecraft:village_plains");
assertEquals("minecraft_village_plains", CommandJigsaw.resolveConversionTarget(source, "auto"));
assertEquals("villages/plains", CommandJigsaw.resolveConversionTarget(source, "iris:villages/plains"));
NamespacedKey ancientCity = CommandJigsaw.parseRegisteredStructureKey(
"minecraft:ancient_city");
assertEquals("minecraft_ancient_city",
CommandJigsaw.resolveConversionTarget(ancientCity, "auto"));
assertThrows(IllegalArgumentException.class,
() -> CommandJigsaw.resolveConversionTarget(source, "custom:village"));
}
@Test
public void adoptionCommandsExposeTwoStepPlanContract() throws Exception {
Method inspect = CommandJigsaw.CommandJigsawAdopt.class.getDeclaredMethod(
"inspect", IrisDimension.class, String.class, String.class, String.class);
Method apply = CommandJigsaw.CommandJigsawAdopt.class.getDeclaredMethod("apply", String.class);
Parameter[] inspectParameters = inspect.getParameters();
assertNotNull(inspect.getAnnotation(Director.class));
assertNotNull(apply.getAnnotation(Director.class));
assertParameter(inspectParameters[2], "auto", null);
assertParameter(inspectParameters[3], "auto", CommandJigsaw.JigsawAdoptionStrategyHandler.class);
assertEquals(CommandJigsaw.JigsawAdoptionPlanHandler.class,
apply.getParameters()[0].getAnnotation(Param.class).customHandler());
CommandJigsaw.JigsawAdoptionStrategyHandler strategyHandler =
new CommandJigsaw.JigsawAdoptionStrategyHandler();
assertEquals(List.of("auto", "in-place", "clone"), strategyHandler.getPossibilities());
assertEquals("in-place", strategyHandler.parse("claim", false));
assertEquals("clone", strategyHandler.parse("copy", false));
assertThrows(DirectorParsingException.class, () -> strategyHandler.parse("overwrite", false));
}
@Test
public void adoptionInputKindUsesOnlyOwnershipProvenance() throws Exception {
Path root = temporaryFolder.newFolder("adoption-provenance").toPath();
assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS,
CommandJigsaw.adoptionInputKind(root, "unowned"));
writeManifest(root, "datapack-created", StructureSource.Kind.DATAPACK,
StructureOwnershipManifest.Provenance.created());
assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS,
CommandJigsaw.adoptionInputKind(root, "datapack-created"));
writeManifest(root, "managed-provenance", StructureSource.Kind.IRIS, managedProvenance());
assertEquals(IrisStructureAdoptionInputKind.MANAGED_DATAPACK,
CommandJigsaw.adoptionInputKind(root, "managed-provenance"));
}
@Test
public void legacyGraphWritersShareTheServiceMutationContract() throws Exception {
Method mutation = CommandJigsaw.class.getDeclaredMethod(
"runGraphMutation",
Player.class,
CommandJigsaw.ActiveContext.class,
JigsawStudioService.CommandGraphMutation.class);
assertEquals(boolean.class, mutation.getReturnType());
assertNotNull(JigsawStudioService.CommandGraphMutation.class.getDeclaredMethod("run"));
assertNotNull(JigsawStudioService.CommandGraphMutationResult.class.getDeclaredConstructor(
JigsawStudioLayout.class,
String.class,
String.class,
String.class));
}
@Test
public void exposesAutosaveDynamicEvaluationAndSelectedWorkcellResize() throws Exception {
Method save = CommandJigsaw.class.getDeclaredMethod("save", String.class);
Method status = CommandJigsaw.class.getDeclaredMethod("status");
Method bounds = CommandJigsaw.class.getDeclaredMethod(
"bounds", int.class, int.class, int.class);
assertEquals("Flush the automatic save for a workcell now",
save.getAnnotation(Director.class).description());
assertEquals("Show active Jigsaw Studio and dynamic evaluation state",
status.getAnnotation(Director.class).description());
assertEquals("Set the selected Studio workcell capacity",
bounds.getAnnotation(Director.class).description());
assertThrows(NoSuchMethodException.class,
() -> CommandJigsaw.class.getDeclaredMethod("validate"));
}
@Test
public void createDefaultsToPlanarIrisWithCompleteCellAndSeedDefaults() throws Exception {
Method create = CommandJigsaw.class.getDeclaredMethod(
"create",
IrisDimension.class,
String.class,
String.class,
String.class,
int.class,
int.class,
int.class,
long.class);
Parameter[] parameters = create.getParameters();
assertParameter(parameters[2], "planar", CommandJigsaw.JigsawModeHandler.class);
assertParameter(parameters[3], "iris", CommandJigsaw.JigsawCompatibilityHandler.class);
assertParameter(parameters[4], "15", null);
assertParameter(parameters[5], "15", null);
assertParameter(parameters[6], "15", null);
assertParameter(parameters[7], "1337", null);
}
@Test
public void structureKeysExplainTheirResourceAndOpenSupportsEditingAliases() throws Exception {
Method create = CommandJigsaw.class.getDeclaredMethod(
"create",
IrisDimension.class,
String.class,
String.class,
String.class,
int.class,
int.class,
int.class,
long.class);
Method open = CommandJigsaw.class.getDeclaredMethod(
"open", IrisDimension.class, String.class, long.class);
Param createKey = create.getParameters()[1].getAnnotation(Param.class);
Param openKey = open.getParameters()[1].getAnnotation(Param.class);
Director openCommand = open.getAnnotation(Director.class);
assertEquals("key", createKey.name());
assertEquals(List.of("structure", "name"), List.of(createKey.aliases()));
assertEquals("New key written as structures/<key>.json", createKey.description());
assertEquals("key", openKey.name());
assertEquals(List.of("structure", "name"), List.of(openKey.aliases()));
assertEquals("Existing key loaded from structures/<key>.json", openKey.description());
assertEquals(IrisStructureHandler.class, openKey.customHandler());
assertEquals(List.of("edit", "reopen"), List.of(openCommand.aliases()));
}
@Test
public void createChoiceHandlersExposeCanonicalCompletionsAndRetainAliases() throws Exception {
CommandJigsaw.JigsawModeHandler modeHandler = new CommandJigsaw.JigsawModeHandler();
CommandJigsaw.JigsawCompatibilityHandler compatibilityHandler =
new CommandJigsaw.JigsawCompatibilityHandler();
assertEquals(List.of("planar", "spatial"), modeHandler.getPossibilities());
assertEquals("planar", modeHandler.parse("2d", false));
assertEquals("spatial", modeHandler.parse("3d", false));
assertEquals(List.of("iris", "vanilla"), compatibilityHandler.getPossibilities());
assertEquals("iris", compatibilityHandler.parse("extended", false));
assertEquals("vanilla", compatibilityHandler.parse("portable", false));
assertThrows(DirectorParsingException.class, () -> modeHandler.parse("volume", false));
assertThrows(DirectorParsingException.class, () -> compatibilityHandler.parse("mixed", false));
}
@Test
public void exposesNestedPieceVariantAndPreviewCommands() throws Exception {
assertNotNull(CommandJigsaw.CommandJigsawPool.class
.getDeclaredMethod("create", String.class, String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawConnector.class
.getDeclaredMethod("channel", String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("create", String.class, String.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("add", String.class, String.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("remove", String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("rotatable", boolean.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("expand")
.getAnnotation(Director.class));
assertEquals("Resize the selected piece object exactly to workcell capacity",
CommandJigsaw.CommandJigsawPiece.class
.getDeclaredMethod("expand")
.getAnnotation(Director.class)
.description());
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("weight", String.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("resize", int.class, int.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("label", String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("labelReset")
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("duplicate")
.getAnnotation(Director.class));
Method duplicateFamily = CommandJigsaw.CommandJigsawVariant.class
.getDeclaredMethod("duplicateFamily", String.class);
assertNotNull(duplicateFamily.getAnnotation(Director.class));
assertParameter(duplicateFamily.getParameters()[0], "next", null);
assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class
.getDeclaredMethod("capacity", int.class, int.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class
.getDeclaredMethod("label", String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class
.getDeclaredMethod("labelReset")
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawRules.class
.getDeclaredMethod("limits", int.class, int.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawRules.class
.getDeclaredMethod("fallback", String.class, String.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPreview.class
.getDeclaredMethod("assemble", long.class)
.getAnnotation(Director.class));
assertNotNull(CommandJigsaw.CommandJigsawPreview.class
.getDeclaredMethod("gotoPreview")
.getAnnotation(Director.class));
}
@Test
public void pieceCreateUsesResolvedWorkcellCapacityInsteadOfLayoutDefault() throws Exception {
String source = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
int pieceCommands = source.indexOf("public static class CommandJigsawPiece");
int create = source.indexOf("public void create(", pieceCommands);
int add = source.indexOf("public void add(", create);
String createSource = source.substring(create, add);
assertTrue(createSource.contains("targetWorkcell = contextual;"));
assertTrue(createSource.contains("JigsawStudioCellDimensions dimensions = targetWorkcell.capacity();"));
assertFalse(createSource.contains("layout().cellDimensions()"));
}
@Test
public void pieceAddUsesCanonicalAxesForRotatedRectangularPlanarWorkcells() {
JigsawStudioLayout layout = nonuniformPlanarLayout();
IrisJigsawPiece eastEnd = new IrisJigsawPiece();
eastEnd.getConnectors().add(new IrisJigsawConnector().setDirection(IrisDirection.EAST_POSITIVE_X));
IrisObject exactObject = new IrisObject(7, 5, 13);
CommandJigsaw.PieceWorkcellResolution exact = CommandJigsaw.resolvePieceWorkcell(
layout,
eastEnd,
exactObject);
CommandJigsaw.PieceWorkcellResolution oversized = CommandJigsaw.resolvePieceWorkcell(
layout,
eastEnd,
new IrisObject(8, 5, 13));
assertEquals(JigsawPlanarArchetype.END.stableId(), exact.workcell().stableId());
assertEquals(new IrisPosition(13, 5, 7), exact.requiredDimensions());
assertEquals(new JigsawStudioCellDimensions(13, 5, 7), exact.workcell().capacity());
assertTrue(exact.fits());
assertTrue(exactObject.getD() > exact.workcell().capacity().depth());
assertFalse(oversized.fits());
}
@Test
public void pieceAddKeepsRawObjectAxesForSpatialWorkcells() {
JigsawStudioCellDimensions capacity = new JigsawStudioCellDimensions(7, 5, 13);
JigsawStudioLayout layout = JigsawStudioLayout.create(
JigsawStudioMode.SPATIAL_JIGSAW,
capacity,
JigsawStudioVariantCatalog.empty());
IrisJigsawPiece spatialPiece = new IrisJigsawPiece();
spatialPiece.getConnectors().add(
new IrisJigsawConnector().setDirection(IrisDirection.EAST_POSITIVE_X));
CommandJigsaw.PieceWorkcellResolution resolution = CommandJigsaw.resolvePieceWorkcell(
layout,
spatialPiece,
new IrisObject(7, 5, 13));
assertEquals(JigsawStudioLayout.SPATIAL_WORKCELL_ID, resolution.workcell().stableId());
assertEquals(new IrisPosition(7, 5, 13), resolution.requiredDimensions());
assertEquals(capacity, resolution.workcell().capacity());
assertTrue(resolution.fits());
}
@Test
public void everyExecutableCommandRejectsNonPlayerOrigins() {
Class<?>[] commandTypes = {
CommandJigsaw.class,
CommandJigsaw.CommandJigsawConnector.class,
CommandJigsaw.CommandJigsawPool.class,
CommandJigsaw.CommandJigsawPiece.class,
CommandJigsaw.CommandJigsawVariant.class,
CommandJigsaw.CommandJigsawWorkcell.class,
CommandJigsaw.CommandJigsawRules.class,
CommandJigsaw.CommandJigsawPreview.class,
CommandJigsaw.CommandJigsawAdopt.class
};
for (Class<?> commandType : commandTypes) {
for (Method method : commandType.getDeclaredMethods()) {
Director director = method.getAnnotation(Director.class);
if (director != null) {
assertEquals(method.toString(), DirectorOrigin.PLAYER, director.origin());
}
}
}
}
@Test
public void exportOutputIsOneSafeChildArtifact() {
Path root = Path.of("build", "jigsaw-exports").toAbsolutePath().normalize();
assertEquals(root.resolve("village.zip"), CommandJigsaw.resolveExportDestination(
root, "village", VanillaJigsawExportFormat.ZIP));
assertEquals(root.resolve("village"), CommandJigsaw.resolveExportDestination(
root, "village", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
root, "", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
root, ".", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
root, "../all-exports", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
root, "nested/export", VanillaJigsawExportFormat.DIRECTORY));
}
@Test
public void exportLeaseRejectsDuplicatePlayerAndDestination() {
UUID firstPlayer = UUID.randomUUID();
UUID secondPlayer = UUID.randomUUID();
Path firstDestination = Path.of("build", "jigsaw-exports", "first.zip");
Path secondDestination = Path.of("build", "jigsaw-exports", "second.zip");
assertEquals(true, CommandJigsaw.beginExport(firstPlayer, firstDestination));
try {
assertEquals(false, CommandJigsaw.beginExport(firstPlayer, secondDestination));
assertEquals(false, CommandJigsaw.beginExport(secondPlayer, firstDestination));
} finally {
CommandJigsaw.finishExport(firstPlayer, firstDestination);
}
assertEquals(true, CommandJigsaw.beginExport(secondPlayer, firstDestination));
CommandJigsaw.finishExport(secondPlayer, firstDestination);
}
@Test
public void exportStartFailuresHavePreciseOperatorMessages() {
assertEquals("The active Jigsaw Studio is no longer available.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.NOT_ACTIVE));
assertEquals("Only the Jigsaw Studio owner can export this project.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.NOT_OWNER));
assertEquals("Wait for the pending autosave or discard the edits before exporting the on-disk graph.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.DIRTY));
assertEquals("The active Jigsaw Studio is closing and cannot be exported.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.CLOSING));
assertEquals("Wait for the current Jigsaw Studio save to finish before exporting.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.SAVE_IN_PROGRESS));
assertEquals("Wait for the current Jigsaw Studio operation to finish before exporting.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.OPERATION_IN_PROGRESS));
assertEquals("A Jigsaw Studio export is already in progress.",
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.IN_PROGRESS));
assertThrows(IllegalArgumentException.class,
() -> CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.STARTED));
}
@Test
public void exportLeaseReleaseActionRunsExactlyOnce() {
AtomicInteger releases = new AtomicInteger();
CommandJigsaw.ExportLease lease = new CommandJigsaw.ExportLease(releases::incrementAndGet);
lease.release();
lease.release();
assertEquals(1, releases.get());
}
@Test
public void exportSourceAcquiresStudioLeaseBeforeStaticLeaseAndReleasesBothPaths() throws Exception {
String source = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
int serviceLease = source.indexOf("studioService.tryBeginExport(requestId, playerId)");
int staticLease = source.indexOf("beginExport(playerId, destination)", serviceLease);
int dispatch = source.indexOf("J.a(() -> runExport(operation))", staticLease);
int schedulingRelease = source.indexOf("operation.lease().release()", dispatch);
int exporter = source.indexOf("new VanillaJigsawDatapackExporter().export(operation.request())", dispatch);
int completionRelease = source.indexOf("operation.lease().release()", exporter);
assertTrue(serviceLease >= 0);
assertTrue(staticLease > serviceLease);
assertTrue(dispatch > staticLease);
assertTrue(schedulingRelease > dispatch);
assertTrue(exporter > schedulingRelease);
assertTrue(completionRelease > exporter);
}
private static void assertCommand(String name, Class<?>... parameterTypes) throws Exception {
Method method = CommandJigsaw.class.getDeclaredMethod(name, parameterTypes);
assertNotNull(method.getAnnotation(Director.class));
}
private static JigsawStudioLayout nonuniformPlanarLayout() {
List<JigsawStudioWorkcellSpec> workcells = List.of(
workcell(JigsawPlanarArchetype.BLANK, 3, 1, 3),
workcell(JigsawPlanarArchetype.END, 13, 5, 7),
workcell(JigsawPlanarArchetype.STRAIGHT, 5, 2, 11),
workcell(JigsawPlanarArchetype.CORNER, 9, 3, 6),
workcell(JigsawPlanarArchetype.TEE, 12, 4, 8),
workcell(JigsawPlanarArchetype.CROSS, 10, 6, 10));
return JigsawStudioLayout.createPlanar(
new JigsawStudioCellDimensions(3, 1, 3),
workcells,
JigsawStudioVariantCatalog.empty());
}
private static JigsawStudioWorkcellSpec workcell(
JigsawPlanarArchetype archetype,
int width,
int height,
int depth
) {
return new JigsawStudioWorkcellSpec(
archetype,
"",
new JigsawStudioCellDimensions(width, height, depth),
true);
}
private static void assertParameter(Parameter parameter, String defaultValue, Class<?> customHandler) {
Param annotation = parameter.getAnnotation(Param.class);
assertNotNull(annotation);
assertEquals(defaultValue, annotation.defaultValue());
if (customHandler != null) {
assertEquals(customHandler, annotation.customHandler());
}
}
private static void writeManifest(
Path root,
String structure,
StructureSource.Kind sourceKind,
StructureOwnershipManifest.Provenance provenance
) throws Exception {
StructureKey structureKey = new StructureKey("iris", structure);
StructureOwnershipManifest manifest = new StructureOwnershipManifest(
StructureOwnershipManifest.CURRENT_SCHEMA_VERSION,
structureKey,
StructureSource.of(sourceKind, new StructureKey("iris", "source/" + structure)),
StructureBackend.IRIS_ASSEMBLY,
List.of(StructureCapability.BLOCKS, StructureCapability.CONNECTORS),
List.of(),
Map.of("structures/" + structure + ".json", StructureHash.sha256(
structure.getBytes(StandardCharsets.UTF_8))),
provenance);
Path manifestPath = new StructureTransactionWriter(root).ownershipManifestPath(structureKey);
Files.createDirectories(manifestPath.getParent());
Files.write(manifestPath, manifest.toJson());
}
private static StructureOwnershipManifest.Provenance managedProvenance() {
String path = "structures/source.json";
String hash = StructureHash.sha256("source".getBytes(StandardCharsets.UTF_8));
return new StructureOwnershipManifest.Provenance(
StructureOwnershipManifest.Origin.MANAGED_DATAPACK,
UUID.randomUUID().toString(),
StructureHash.sha256("plan".getBytes(StandardCharsets.UTF_8)),
StructureHash.sha256("closure".getBytes(StandardCharsets.UTF_8)),
1L,
Map.of(path, hash),
Map.of(path, path),
StructureOwnershipManifest.RollbackDisposition.NONE);
}
}
@@ -228,15 +228,14 @@ public class IrisStructureLocateCommandContractTest {
@Test
public void bulkStructureImportRestrictsCaptureWithoutChangingStandaloneCapture() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
int importStart = source.indexOf("public void importAll(");
int importEnd = source.indexOf("@Director(name = \"capture\"", importStart);
int captureStart = source.indexOf("public void capture(", importEnd);
String source = Files.readString(Path.of(System.getProperty("iris.importCommandsSource")));
int importStart = source.indexOf("private static void runImportAll(");
int captureStart = source.indexOf("private static void runCapture(", importStart);
int importEnd = captureStart;
int captureEnd = source.length();
assertTrue(importStart >= 0);
assertTrue(importEnd > importStart);
assertTrue(captureStart > importEnd);
assertTrue(captureEnd > captureStart);
String importMethod = source.substring(importStart, importEnd);
String captureMethod = source.substring(captureStart, captureEnd);
@@ -42,7 +42,7 @@ public class StudioPlayerModeContractTest {
String objectCommands = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandObject.java")).replace("\r\n", "\n");
String jigsawCommands = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
System.getProperty("iris.studioLifecycleCommandsSource"))).replace("\r\n", "\n");
assertTrue(objectCommands.contains("GameMode.CREATIVE"));
assertTrue(objectCommands.contains("StudioOpenCoordinator.StudioOpenKind.OBJECT"));
@@ -0,0 +1,33 @@
package art.arcane.iris.core.structure;
import org.junit.Test;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class BukkitCaptureAreaFailureTest {
@Test
public void captureFailurePreservesStructureChunkDetailAndCause() {
IllegalArgumentException cause = new IllegalArgumentException("placement broke");
IllegalStateException error = BukkitCaptureArea.captureFailure(
"minecraft:monument", 12, -8, "platform placement failed", cause);
assertSame(cause, error.getCause());
assertTrue(error.getMessage().contains("minecraft:monument"));
assertTrue(error.getMessage().contains("12,-8"));
assertTrue(error.getMessage().contains("platform placement failed"));
}
@Test
public void captureFailureSupportsInfrastructureFailuresWithoutACause() {
IllegalStateException error = BukkitCaptureArea.captureFailure(
"minecraft:stronghold", -3, 5, "region task was not accepted", null);
assertNull(error.getCause());
assertTrue(error.getMessage().contains("minecraft:stronghold"));
assertTrue(error.getMessage().contains("-3,5"));
assertTrue(error.getMessage().contains("region task was not accepted"));
}
}
@@ -0,0 +1,39 @@
package art.arcane.iris.core.structure;
import art.arcane.iris.core.pack.BrokenPackException;
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
import art.arcane.iris.core.tools.IrisCreator;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.CompletionException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BukkitJigsawStudioHostTest {
private final BukkitJigsawStudioHost host = new BukkitJigsawStudioHost();
@Test
public void jigsawStudioUsesItsDedicatedOpenLifecycle() {
assertEquals(
StudioOpenCoordinator.StudioOpenKind.TOOL,
BukkitJigsawStudioHost.STUDIO_OPEN_KIND);
assertFalse(BukkitJigsawStudioHost.STUDIO_OPEN_KIND.openWorkspace());
assertFalse(BukkitJigsawStudioHost.STUDIO_OPEN_KIND.teleportThroughStandardEntry());
assertEquals(
IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY,
BukkitJigsawStudioHost.STUDIO_OPEN_KIND.datapackPreparation());
}
@Test
public void packValidationDenialsAreExpectedOpenFailures() {
BrokenPackException failure = new BrokenPackException(
"overworld", List.of("Biome 'broken' has no resolvable regions."));
assertTrue(host.isExpectedOpenDenial(failure));
assertTrue(host.isExpectedOpenDenial(new CompletionException(failure)));
assertFalse(host.isExpectedOpenDenial(new IllegalStateException("Unexpected Studio failure")));
}
}
@@ -0,0 +1,176 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
public class PoolElementReaderTest {
private static final String FINAL_STATE =
"minecraft:oak_stairs[facing=east,half=top,shape=straight,waterlogged=false]";
@Test
public void plainTemplateElementRemainsUnchanged() throws Exception {
FakeSinglePoolElement single = new FakeSinglePoolElement("minecraft:village/plains/houses/plains_small_house_1");
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(single);
assertSame(single, resolution.physicalElement());
assertEquals("minecraft:village/plains/houses/plains_small_house_1", resolution.templateLocation());
assertEquals(0, resolution.listLevels());
assertEquals(0, resolution.omittedElements());
}
@Test
public void nestedListsRetainOnlyTheRecursivePrimaryTemplate() throws Exception {
FakeSinglePoolElement primary = new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower");
FakeSinglePoolElement innerOverlay = new FakeSinglePoolElement("test:inner_overlay");
FakeSinglePoolElement outerOverlay = new FakeSinglePoolElement("test:outer_overlay");
FakeListPoolElement inner = new FakeListPoolElement(List.of(primary, innerOverlay));
FakeListPoolElement outer = new FakeListPoolElement(List.of(inner, outerOverlay));
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(outer);
assertSame(primary, resolution.physicalElement());
assertEquals("minecraft:pillager_outpost/watchtower", resolution.templateLocation());
assertEquals(2, resolution.listLevels());
assertEquals(2, resolution.omittedElements());
}
@Test
public void unsupportedPrimaryDoesNotFallThroughToLaterChildren() throws Exception {
FakeFeaturePoolElement feature = new FakeFeaturePoolElement();
FakeSinglePoolElement fallback = new FakeSinglePoolElement("test:must_not_be_selected");
FakeListPoolElement list = new FakeListPoolElement(List.of(feature, fallback));
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(list);
assertSame(feature, resolution.physicalElement());
assertNull(resolution.templateLocation());
assertEquals(1, resolution.omittedElements());
}
@Test
public void emptyListResolvesWithoutIndexingAChild() throws Exception {
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(
new FakeListPoolElement(List.of())
);
assertNull(resolution.physicalElement());
assertNull(resolution.templateLocation());
assertEquals(1, resolution.listLevels());
assertEquals(0, resolution.omittedElements());
}
@Test
public void outerChoiceProducesOneEntryWithItsOriginalWeight() throws Exception {
FakeListPoolElement towers = new FakeListPoolElement(List.of(
new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower"),
new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower_overgrown")
));
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(towers);
List<Map<String, Object>> entries = List.of(VillageImporter.piecePoolEntry(
"qa/pillager_outpost/piece/minecraft/pillager_outpost/watchtower",
7
));
assertEquals(1, entries.size());
assertEquals("minecraft:pillager_outpost/watchtower", resolution.templateLocation());
assertEquals(7, entries.getFirst().get("weight"));
assertEquals(1, resolution.omittedElements());
}
@Test
public void vanillaNbtMetadataIsReadFromTheJigsawBlockInfo() throws Exception {
FakeJigsawBlockInfo jigsaw = new FakeJigsawBlockInfo(-29, -17);
FakeStructureBlockInfo info = new FakeStructureBlockInfo(new FakeCompoundTag(FINAL_STATE));
PoolElementReader.ConnectorMetadata metadata = PoolElementReader.readConnectorMetadata(jigsaw, info);
assertEquals(Optional.of(FINAL_STATE), metadata.finalState());
assertEquals(-17, metadata.selectionPriority());
assertEquals(-29, metadata.placementPriority());
}
private record FakeJigsawBlockInfo(int placementPriority, int selectionPriority) {
}
private record FakeStructureBlockInfo(FakeCompoundTag nbt) {
}
private record FakeCompoundTag(String finalState) {
public Optional<String> getString(String key) {
return "final_state".equals(key) ? Optional.of(finalState) : Optional.empty();
}
}
private static final class FakeListPoolElement {
private final List<Object> elements;
private FakeListPoolElement(List<?> elements) {
this.elements = List.copyOf(elements);
}
public List<Object> getElements() {
return elements;
}
}
private static final class FakeSinglePoolElement {
private final FakeResourceLocation location;
private FakeSinglePoolElement(String location) {
String[] parts = location.split(":", 2);
this.location = new FakeResourceLocation(parts[0], parts[1]);
}
public FakeResourceLocation getTemplateLocation() {
return location;
}
}
private static final class FakeFeaturePoolElement {
}
private static final class FakeResourceLocation {
private final String namespace;
private final String path;
private FakeResourceLocation(String namespace, String path) {
this.namespace = namespace;
this.path = path;
}
public String getNamespace() {
return namespace;
}
public String getPath() {
return path;
}
}
}
@@ -0,0 +1,44 @@
package art.arcane.iris.core.structure;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* JigsawStructure.maxDistanceFromCenter is a plain int on some server builds and a
* JigsawStructure$MaxDistance record ({int horizontal, int vertical}) on others (e.g. Leaf
* 26.2-33). The reflective member reader must handle both — the wrapper shape previously threw
* IllegalArgumentException from Field.getInt, failing the jigsaw import of every datapack
* structure ("Failed to read jigsaw structure graph").
*/
public class ServerReflectionMaxDistanceReadTest {
private static final class IntShape {
private final int maxDistanceFromCenter = 80;
}
private record MaxDistance(int horizontal, int vertical) {
}
private static final class WrapperShape {
private final MaxDistance maxDistanceFromCenter = new MaxDistance(96, 48);
}
private static final class BoxedShape {
private final Integer maxDistanceFromCenter = 64;
}
@Test
public void readsPlainIntField() throws Exception {
assertEquals(80, ServerReflection.readIntMember(new IntShape(), "maxDistanceFromCenter"));
}
@Test
public void readsLargestIntComponentFromWrapperRecord() throws Exception {
assertEquals(96, ServerReflection.readIntMember(new WrapperShape(), "maxDistanceFromCenter"));
}
@Test
public void readsBoxedNumberField() throws Exception {
assertEquals(64, ServerReflection.readIntMember(new BoxedShape(), "maxDistanceFromCenter"));
}
}