From ae11b380935116a74e9f5152c2e49a88a0f5e467 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 10 Nov 2026 00:27:03 +0100 Subject: [PATCH] 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. --- ...terListPoolElementRuntimeContractTest.java | 21 +- adapters/bukkit/plugin/build.gradle | 3 +- .../src/main/java/art/arcane/iris/Iris.java | 6 + .../iris/core/commands/CommandIris.java | 2 - .../iris/core/commands/CommandJigsaw.java | 2233 ----------------- .../iris/core/commands/CommandStructure.java | 71 - .../core/commands/JigsawStudioBridge.java | 146 -- .../core/structure/BukkitCaptureArea.java | 165 ++ .../structure/BukkitJigsawStudioHost.java | 85 + .../structure/BukkitPlatformStructures.java | 319 +++ .../core/structure/BukkitTemplateReader.java | 111 + .../core/structure/PoolElementReader.java | 261 ++ .../iris/core/structure/ServerReflection.java | 302 +++ .../iris/core/toolworld/BukkitToolPlayer.java | 5 + .../commands/CommandJigsawContractTest.java | 609 ----- ...risStructureLocateCommandContractTest.java | 9 +- .../runtime/StudioPlayerModeContractTest.java | 2 +- .../BukkitCaptureAreaFailureTest.java | 6 +- .../structure/BukkitJigsawStudioHostTest.java | 39 + .../core/structure/PoolElementReaderTest.java | 176 ++ .../ServerReflectionMaxDistanceReadTest.java | 8 +- .../modded/command/ModdedCommandHelp.java | 7 - .../modded/command/ModdedCommandTree.java | 3 - .../command/ModdedStructureCommands.java | 66 - .../command/IrisModdedCommandParityTest.java | 15 +- .../IrisModdedStructureCommandTest.java | 5 +- api/CONTRACTS.md | 4 +- api/DESIGN.md | 6 + api/README.md | 8 + .../com/volmit/tooling/CapturedStructure.java | 18 + .../com/volmit/tooling/CommandContext.java | 3 + .../volmit/tooling/JigsawStructureInfo.java | 23 + .../volmit/tooling/PlatformStructures.java | 63 + .../tooling/StructureAccessException.java | 28 + .../com/volmit/tooling/StructureTemplate.java | 20 + .../com/volmit/tooling/TemplateBlock.java | 33 + .../java/com/volmit/tooling/TemplatePool.java | 154 ++ .../com/volmit/tooling/world/ToolPlayer.java | 6 + .../tooling/PlatformStructuresTest.java | 48 + build.gradle | 2 + core/purity-allowlist.txt | 4 - .../core/datapack/DatapackIngestService.java | 10 +- .../iris/core/modules/StructureCommands.java | 9 +- .../core/modules/StructureModelModule.java | 9 +- .../jigsaw/JigsawStudioGraphEditor.java | 131 +- .../core/structure/BulkStructureImporter.java | 374 +-- .../structure/StructureCaptureImporter.java | 197 +- .../core/structure/StructureImporter.java | 299 +-- .../core/structure/StructureIndexService.java | 67 +- .../iris/core/structure/VillageImporter.java | 773 +----- .../export/VanillaJigsawExportCompiler.java | 35 +- .../VanillaStructureTemplateEncoder.java | 12 +- .../structure/tooling/AdoptionCommands.java | 345 +++ .../structure/tooling/GraphEditCommands.java | 792 ++++++ .../structure/tooling/GraphMutations.java | 163 ++ .../structure/tooling/ImportCommands.java | 90 + .../structure/tooling/JigsawCommands.java | 63 + .../tooling/JigsawExportCommand.java | 279 ++ .../structure/tooling/JigsawStudioHost.java | 52 + .../tooling/PlatformStructuresAccess.java | 41 + .../core/structure/tooling/SenderText.java | 61 + .../core/structure/tooling/StructureKeys.java | 33 + .../tooling/StudioLifecycleCommands.java | 770 ++++++ .../structure/tooling/StudioSessions.java | 92 + .../core/structure/tooling/StudioUse.java | 163 ++ .../arcane/iris/core/tooling/CommandRun.java | 11 +- .../core/tooling/StructureIndexOnStart.java | 60 + .../iris/core/tooling/ToolingCommands.java | 15 +- .../iris/core/tooling/VolmitToolSender.java | 68 + .../art/arcane/iris/engine/IrisEngine.java | 4 +- .../iris/engine/object/prefab/IrisObject.java | 126 + .../specialhandlers/IrisStructureHandler.java | 58 - .../iris/core/service/FakeToolPlayer.java | 5 + .../structure/FakePlatformStructures.java | 82 + .../StructureImporterCaptureTest.java | 69 +- .../structure/StructureImporterModeTest.java | 6 +- .../structure/StructureIndexServiceTest.java | 56 +- ...VillageImporterConnectorRoundTripTest.java | 39 +- .../VillageImporterListPoolElementTest.java | 129 +- .../tooling/JigsawCommandsContractTest.java | 569 +++++ .../core/tooling/StructureCommandsTest.java | 5 +- .../tooling/StructureIndexOnStartTest.java | 61 + 82 files changed, 6529 insertions(+), 4789 deletions(-) delete mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java delete mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java delete mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/JigsawStudioBridge.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitCaptureArea.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitJigsawStudioHost.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitPlatformStructures.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitTemplateReader.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/PoolElementReader.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/ServerReflection.java delete mode 100644 adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/CommandJigsawContractTest.java rename core/src/test/java/art/arcane/iris/core/structure/StructureCaptureImporterFailureTest.java => adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitCaptureAreaFailureTest.java (84%) create mode 100644 adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitJigsawStudioHostTest.java create mode 100644 adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/PoolElementReaderTest.java rename core/src/test/java/art/arcane/iris/core/structure/VillageImporterMaxDistanceReadTest.java => adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/ServerReflectionMaxDistanceReadTest.java (77%) delete mode 100644 adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStructureCommands.java create mode 100644 api/api/src/main/java/com/volmit/tooling/CapturedStructure.java create mode 100644 api/api/src/main/java/com/volmit/tooling/JigsawStructureInfo.java create mode 100644 api/api/src/main/java/com/volmit/tooling/PlatformStructures.java create mode 100644 api/api/src/main/java/com/volmit/tooling/StructureAccessException.java create mode 100644 api/api/src/main/java/com/volmit/tooling/StructureTemplate.java create mode 100644 api/api/src/main/java/com/volmit/tooling/TemplateBlock.java create mode 100644 api/api/src/main/java/com/volmit/tooling/TemplatePool.java create mode 100644 api/api/src/test/java/com/volmit/tooling/PlatformStructuresTest.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/AdoptionCommands.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/GraphEditCommands.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/GraphMutations.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawCommands.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawExportCommand.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawStudioHost.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/PlatformStructuresAccess.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/SenderText.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/StructureKeys.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/StudioSessions.java create mode 100644 core/src/main/java/art/arcane/iris/core/structure/tooling/StudioUse.java create mode 100644 core/src/main/java/art/arcane/iris/core/tooling/StructureIndexOnStart.java create mode 100644 core/src/main/java/art/arcane/iris/core/tooling/VolmitToolSender.java delete mode 100644 core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/IrisStructureHandler.java create mode 100644 core/src/test/java/art/arcane/iris/core/structure/FakePlatformStructures.java create mode 100644 core/src/test/java/art/arcane/iris/core/structure/tooling/JigsawCommandsContractTest.java create mode 100644 core/src/test/java/art/arcane/iris/core/tooling/StructureIndexOnStartTest.java diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementRuntimeContractTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementRuntimeContractTest.java index 3c472a150..7edfc22a1 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementRuntimeContractTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementRuntimeContractTest.java @@ -54,13 +54,14 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructureTemplatePool.Projection.RIGID ); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(towers); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(towers); Map entry = VillageImporter.piecePoolEntry( "qa/pillager_outpost/piece/minecraft/pillager_outpost/watchtower", 1 ); StructureLoss loss = VillageImporter.listElementFallbackLoss( - resolution, + resolution.listLevels(), + resolution.omittedElements(), "minecraft:pillager_outpost/towers" ); Map basePlatePiece = VillageImporter.pieceJson( @@ -103,7 +104,7 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement waystone = StructurePoolElement .legacy("dungeons_and_taverns:waystones/waystone_scaffold") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(waystone); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(waystone); VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember( "dungeons_and_taverns:waystones", "qa/pool/dungeons_and_taverns/waystones", @@ -130,7 +131,7 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement orphan = StructurePoolElement .legacy("test:orphan_house") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(orphan); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(orphan); VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember( "test:orphan_pool", "qa/pool/test/orphan_pool", @@ -160,7 +161,7 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement start = StructurePoolElement .legacy("test:air_start") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(start); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(start); VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember( "test:start", "qa/pool/test/start", @@ -184,7 +185,7 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement inert = StructurePoolElement .legacy("test:mixed_air_inert") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(inert); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(inert); VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember( "test:mixed", "qa/pool/test/mixed", @@ -214,8 +215,8 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement nonAirElement = StructurePoolElement .legacy("test:mixed_non_air_primary") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution allAirResolution = VillageImporter.resolvePoolElement(allAirElement); - VillageImporter.PoolElementResolution nonAirResolution = VillageImporter.resolvePoolElement(nonAirElement); + PoolElementReader.PoolElementResolution allAirResolution = PoolElementReader.resolvePoolElement(allAirElement); + PoolElementReader.PoolElementResolution nonAirResolution = PoolElementReader.resolvePoolElement(nonAirElement); VillageImporter.PoolMemberNormalization allAir = VillageImporter.normalizePoolMember( "test:mixed", "qa/pool/test/mixed", @@ -257,8 +258,8 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement nonAirElement = StructurePoolElement .legacy("test:non_air_primary") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution allAirResolution = VillageImporter.resolvePoolElement(allAirElement); - VillageImporter.PoolElementResolution nonAirResolution = VillageImporter.resolvePoolElement(nonAirElement); + PoolElementReader.PoolElementResolution allAirResolution = PoolElementReader.resolvePoolElement(allAirElement); + PoolElementReader.PoolElementResolution nonAirResolution = PoolElementReader.resolvePoolElement(nonAirElement); VillageImporter.PoolMemberNormalization allAir = VillageImporter.normalizePoolMember( "test:primary", "qa/pool/test/primary", diff --git a/adapters/bukkit/plugin/build.gradle b/adapters/bukkit/plugin/build.gradle index ba8ed62a5..d5d7a15a2 100644 --- a/adapters/bukkit/plugin/build.gradle +++ b/adapters/bukkit/plugin/build.gradle @@ -66,7 +66,8 @@ tasks.named('jar', Jar).configure { tasks.named('test').configure { systemProperty('iris.commandFindSource', file('src/main/java/art/arcane/iris/core/commands/CommandFind.java').absolutePath) - systemProperty('iris.commandStructureSource', file('src/main/java/art/arcane/iris/core/commands/CommandStructure.java').absolutePath) + systemProperty('iris.importCommandsSource', rootProject.file('core/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java').absolutePath) + systemProperty('iris.studioLifecycleCommandsSource', rootProject.file('core/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java').absolutePath) systemProperty('iris.commandIrisSource', file('src/main/java/art/arcane/iris/core/commands/CommandIris.java').absolutePath) systemProperty('iris.bukkitChunkGeneratorSource', rootProject.file('core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java').absolutePath) systemProperty('iris.pregeneratorJobSource', rootProject.file('core/src/main/java/art/arcane/iris/core/gui/PregeneratorJob.java').absolutePath) diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java index a9c9f3a8f..388212f72 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java @@ -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")); diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java index 8323a81a9..8bd4eabb8 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java @@ -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; diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java deleted file mode 100644 index 073f64b76..000000000 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java +++ /dev/null @@ -1,2233 +0,0 @@ -package art.arcane.iris.core.commands; - -import art.arcane.iris.engine.framework.structure.StructureResources; -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.WorldRuntimeControlService; -import art.arcane.iris.core.runtime.StudioOpenCoordinator; -import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; -import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphMapper; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphEditor; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPoolEditor; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioProjectCreator; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioStructureEditor; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; -import art.arcane.iris.core.service.JigsawStudioGraphEvaluation; -import art.arcane.iris.core.service.JigsawStudioRegistry; -import art.arcane.iris.core.service.JigsawStudioRequest; -import art.arcane.iris.core.service.JigsawStudioService; -import art.arcane.iris.core.service.StudioSVC; -import art.arcane.iris.core.structure.StructureImporter; -import art.arcane.iris.core.structure.VillageImporter; -import art.arcane.iris.core.structure.authoring.StructureKey; -import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest; -import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; -import art.arcane.iris.core.structure.authoring.StructureWriteResult; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionDiagnostic; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionInputKind; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionPlan; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionRequest; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionResult; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionService; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionStrategy; -import art.arcane.iris.core.structure.export.VanillaJigsawDatapackExporter; -import art.arcane.iris.core.structure.export.VanillaJigsawExportDiagnostic; -import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat; -import art.arcane.iris.core.structure.export.VanillaJigsawExportRequest; -import art.arcane.iris.core.structure.export.VanillaJigsawExportResult; -import art.arcane.iris.core.structure.export.VanillaJigsawExportSource; -import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.util.common.director.DirectorExecutor; -import art.arcane.iris.util.common.director.specialhandlers.IrisStructureHandler; -import art.arcane.iris.util.common.format.C; -import art.arcane.iris.util.common.plugin.VolmitSender; -import art.arcane.iris.util.common.scheduling.J; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.director.DirectorOrigin; -import art.arcane.volmlib.util.director.DirectorParameterHandler; -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 com.volmit.tooling.world.ToolPlayer; -import com.volmit.tooling.world.ToolWorld; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.data.type.Jigsaw; -import org.bukkit.entity.Player; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.regex.Pattern; - -@Director(name = "jigsaw", aliases = {"jig", "jgs"}, description = "Iris Jigsaw Studio tools", - origin = DirectorOrigin.PLAYER) -public class CommandJigsaw implements DirectorExecutor { - private static final long DEFAULT_STUDIO_SEED = 1337L; - static final StudioOpenCoordinator.StudioOpenKind STUDIO_OPEN_KIND = - StudioOpenCoordinator.StudioOpenKind.TOOL; - private static final Pattern EXPORT_OUTPUT_NAME = Pattern.compile("[a-zA-Z0-9_-][a-zA-Z0-9._-]{0,127}"); - private static final Map PLAYER_PACKS = new ConcurrentHashMap<>(); - private static final Map ADOPTION_PLANS = new ConcurrentHashMap<>(); - private static final Map ADOPTION_SERVICES = new ConcurrentHashMap<>(); - private static final Set EXPORTING_PLAYERS = ConcurrentHashMap.newKeySet(); - private static final Set EXPORT_DESTINATIONS = ConcurrentHashMap.newKeySet(); - - static JigsawStudioRegistry registry() { - return JigsawStudioBridge.get().registry(); - } - - private CommandJigsawPiece piece; - private CommandJigsawPool pool; - private CommandJigsawConnector connector; - private CommandJigsawVariant variant; - private CommandJigsawWorkcell workcell; - private CommandJigsawRules rules; - private CommandJigsawPreview preview; - private CommandJigsawAdopt adopt; - - @Director(description = "Create and open a new atomic Jigsaw Studio project", sync = true, - origin = DirectorOrigin.PLAYER) - public void create( - @Param(description = "Pack dimension") IrisDimension dimension, - @Param(name = "key", aliases = {"structure", "name"}, - description = "New key written as structures/.json") String structure, - @Param(description = "planar or spatial", defaultValue = "planar", - customHandler = JigsawModeHandler.class) String mode, - @Param(description = "iris or vanilla", defaultValue = "iris", - customHandler = JigsawCompatibilityHandler.class) String compatibility, - @Param(description = "Cell width", defaultValue = "15") int width, - @Param(description = "Cell height", defaultValue = "15") int height, - @Param(description = "Cell depth", defaultValue = "15") int depth, - @Param(description = "Studio world seed", defaultValue = "1337") long seed - ) { - IrisData data = requireData(dimension); - if (data == null) { - return; - } - JigsawStudioMode studioMode; - JigsawStudioCompatibilityTarget target; - JigsawStudioCellDimensions dimensions; - try { - studioMode = parseMode(mode); - target = parseCompatibility(compatibility); - dimensions = new JigsawStudioCellDimensions(width, height, depth); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - - StructureWriteResult result; - try { - result = JigsawStudioProjectCreator.create( - data.getDataFolder().toPath(), - new JigsawStudioProjectCreator.Options(structure, studioMode, target, dimensions)); - } catch (IOException | RuntimeException exception) { - Iris.reportError("Failed to create Jigsaw Studio project '" + structure + "'.", exception); - sendError("Jigsaw project creation failed: " + exception.getMessage()); - return; - } - if (!result.successful()) { - sendError("Jigsaw project was not created: " + result.status()); - if (!result.conflicts().isEmpty()) { - sendError(result.conflicts().getFirst().relativePath() + ": " - + result.conflicts().getFirst().reason()); - } - return; - } - try { - JigsawStudioService.clearAutosaveHistory( - data.getDataFolder().toPath(), - structure); - } catch (IOException exception) { - Iris.reportError("Failed to clear stale Jigsaw Studio history for '" + structure + "'.", exception); - sendError("Jigsaw project was created, but stale autosave history could not be cleared: " - + exception.getMessage()); - return; - } - data.invalidateStructureResources(); - sender().sendMessage(C.GREEN + "Created Jigsaw project '" + structure + "' atomically."); - open(dimension, structure, seed); - } - - @Director(description = "Import a registered vanilla or datapack jigsaw graph into Iris Studio", - aliases = {"import", "import-vanilla"}, sync = true, origin = DirectorOrigin.PLAYER) - public void convert( - @Param(description = "Pack dimension") IrisDimension dimension, - @Param(description = "Registered structure key such as minecraft:village_plains") String source, - @Param(description = "New Iris structure key, or auto", defaultValue = "auto") String target, - @Param(description = "Studio world seed", defaultValue = "1337") long seed - ) { - if (studioIsActiveOrOpening()) { - sendError("Close the active or opening Jigsaw Studio before importing another graph."); - return; - } - IrisData data = requireData(dimension); - if (data == null) { - return; - } - NamespacedKey sourceKey; - String targetKey; - try { - sourceKey = parseRegisteredStructureKey(source); - targetKey = resolveConversionTarget(sourceKey, target); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - - VillageImporter.Result result = VillageImporter.importVillage( - data, - sourceKey, - targetKey, - StructureImporter.Mode.ADD_ONLY); - if (!result.success()) { - sendError(conversionFailureMessage(result)); - return; - } - data.invalidateStructureResources(); - VolmitSender commandSender = sender(); - commandSender.sendMessage(C.GREEN + result.message()); - openProject(player(), commandSender, dimension, targetKey, seed); - } - - @Director(description = "Open an existing Iris jigsaw graph in transient Studio", - aliases = {"edit", "reopen"}, sync = true, origin = DirectorOrigin.PLAYER) - public void open( - @Param(description = "Pack dimension") IrisDimension dimension, - @Param(name = "key", aliases = {"structure", "name"}, - description = "Existing key loaded from structures/.json", - customHandler = IrisStructureHandler.class) String structure, - @Param(description = "Studio world seed", defaultValue = "1337") long seed - ) { - openProject(player(), sender(), dimension, structure, seed); - } - - private static void openProject( - Player targetPlayer, - VolmitSender commandSender, - IrisDimension dimension, - String structure, - long seed - ) { - UUID playerId = targetPlayer.getUniqueId(); - UUID ownerId = registry().activeOwnerId(); - if (ownerId != null && !ownerId.equals(playerId)) { - sendError(commandSender, "Jigsaw Studio is already owned by another player session."); - return; - } - UUID openingOwner = registry().openingOwnerId(); - if (openingOwner != null) { - sendError(commandSender, openingOwner.equals(playerId) - ? "Your Jigsaw Studio is already opening." - : "Jigsaw Studio is already opening for another player."); - return; - } - ActiveContext previous = active(targetPlayer); - if (ownerId != null && previous == null) { - sendError(commandSender, "Your active Jigsaw Studio binding is unavailable. Close it before opening another project."); - return; - } - ActiveContext dirty = findDirtyContext(); - if (dirty != null) { - sendError(commandSender, - "The current Jigsaw Studio is waiting for autosave. Wait for it to finish or close with discard=true."); - return; - } - IrisData data = requireData(dimension, commandSender); - if (data == null) { - return; - } - IrisStructure irisStructure = StructureResources.structure(data.getPackResources(), structure); - if (irisStructure == null) { - sendError(commandSender, "No Iris jigsaw structure '" + structure + "' exists in this pack."); - return; - } - - JigsawStudioLayout layout; - try { - layout = JigsawStudioGraphMapper.map(data, irisStructure); - } catch (RuntimeException exception) { - Iris.reportError("Failed to map Jigsaw Studio graph '" + structure + "'.", exception); - sendError(commandSender, "Could not map this jigsaw graph: " + exception.getMessage()); - return; - } - String packKey = dimension.getLoadKey(); - if (!registry().tryBeginOpen(playerId)) { - sendError(commandSender, - "Jigsaw Studio began opening for another player. Try again after it finishes."); - return; - } - JigsawStudioBridge studioService = JigsawStudioBridge.get(); - UUID closingRequestId = previous == null ? null : previous.request().requestId(); - if (closingRequestId != null) { - JigsawStudioService.CloseStart closeStart = studioService.tryBeginClose( - closingRequestId, - playerId, - false); - if (closeStart != JigsawStudioService.CloseStart.STARTED) { - registry().finishOpen(playerId); - sendError(commandSender, closeStart == JigsawStudioService.CloseStart.SAVE_IN_PROGRESS - ? "The current Jigsaw Studio is saving. Wait for it to finish before opening another project." - : closeStart == JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS - ? "The current Jigsaw Studio is loading a variant. Wait for it to finish before opening another project." - : closeStart == JigsawStudioService.CloseStart.DIRTY - ? "The current Jigsaw Studio is waiting for autosave. Wait for it to finish before opening another project." - : "The current Jigsaw Studio could not be reserved for replacement."); - return; - } - } - JigsawStudioRegistry.StagedActivation staged; - try { - staged = registry().stage( - packKey, - structure, - layout.mode(), - compatibilityOf(irisStructure), - layout.cellDimensions(), - data, - layout, - playerId, - closingRequestId); - } catch (RuntimeException exception) { - registry().finishOpen(playerId); - studioService.cancelClose(closingRequestId); - Iris.reportError("Failed to stage Jigsaw Studio for '" + structure + "'.", exception); - sendError(commandSender, "Jigsaw Studio staging failed: " + exception.getMessage()); - return; - } - commandSender.sendMessage(C.GREEN + "Opening transient Jigsaw Studio for '" + structure + "' with " - + layout.bays().size() + " workcells."); - - BrokenPackException admissionFailure = StudioSVC.reportPackAdmissionFailure( - commandSender, packKey, STUDIO_OPEN_KIND); - if (admissionFailure != null) { - finishOpenAttempt(commandSender, playerId, structure, closingRequestId, studioService, staged, null, admissionFailure); - return; - } - try { - beginStagedOpen(staged); - studioService.open(data, staged) - .whenComplete((world, throwable) -> J.s(() -> { - Throwable failure = throwable; - if (failure == null) { - failure = commitOpenedStudio(targetPlayer, world, staged, studioService); - } - finishOpenAttempt( - commandSender, - playerId, - structure, - closingRequestId, - studioService, - staged, - world, - failure); - })); - } catch (Throwable exception) { - registry().finishOpen(playerId); - studioService.cancelClose(closingRequestId); - registry().rollback(staged); - Iris.reportError("Failed to open Jigsaw Studio for '" + structure + "'.", exception); - sendError(commandSender, "Jigsaw Studio open failed: " + exception.getMessage()); - } - } - - @Director(description = "Close the active Jigsaw Studio", sync = true, - origin = DirectorOrigin.PLAYER) - public void close( - @Param(description = "Discard unsaved Studio layout changes", defaultValue = "false") boolean discard - ) { - Player targetPlayer = player(); - ActiveContext context = active(targetPlayer); - if (context == null) { - sendError("You do not have an active Jigsaw Studio session."); - return; - } - if (context.session().isDirty() && !discard) { - sendError("This Jigsaw Studio is waiting for autosave. Wait for it to finish or run close with discard=true."); - return; - } - JigsawStudioBridge studioService = JigsawStudioBridge.get(); - UUID requestId = context.request().requestId(); - JigsawStudioService.CloseStart closeStart = studioService.tryBeginClose( - requestId, - targetPlayer.getUniqueId(), - discard); - if (closeStart != JigsawStudioService.CloseStart.STARTED) { - sendError(closeStart == JigsawStudioService.CloseStart.SAVE_IN_PROGRESS - ? "This Jigsaw Studio is saving. Wait for the save to finish before closing it." - : closeStart == JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS - ? "This Jigsaw Studio is loading a variant. Wait for it to finish before closing it." - : closeStart == JigsawStudioService.CloseStart.DIRTY - ? "This Jigsaw Studio is waiting for autosave. Wait for it to finish or run close with discard=true." - : closeStart == JigsawStudioService.CloseStart.NOT_OWNER - ? "This Jigsaw Studio is owned by another player session." - : "This Jigsaw Studio session is no longer active."); - return; - } - VolmitSender commandSender = sender(); - try { - Iris.service(StudioSVC.class).close().whenComplete((result, throwable) -> J.s(() -> { - if (throwable != null || result == null || result.failureCause() != null) { - studioService.cancelClose(requestId); - Throwable failure = throwable != null ? throwable : result == null ? null : result.failureCause(); - commandSender.sendMessage(C.RED + "Jigsaw Studio close failed: " - + (failure == null ? "unknown failure" : failure.getMessage())); - return; - } - registry().deactivate(context.packKey(), requestId); - PLAYER_PACKS.remove(targetPlayer.getUniqueId(), - new SessionBinding(context.packKey(), requestId)); - commandSender.sendMessage(C.GREEN + "Jigsaw Studio closed."); - })); - } catch (Throwable exception) { - studioService.cancelClose(requestId); - Iris.reportError("Failed to close Jigsaw Studio '" + context.request().structureKey() + "'.", exception); - sendError("Jigsaw Studio close failed: " + exception.getMessage()); - } - } - - @Director(name = "delete", aliases = "remove", description = "Delete the active owned jigsaw project", - sync = true, origin = DirectorOrigin.PLAYER) - public void delete( - @Param(description = "Confirm permanent project deletion", defaultValue = "false") boolean confirm - ) { - if (requireActive() == null) { - return; - } - if (!confirm) { - sendError("Project deletion removes every resource owned by this jigsaw. Run again with confirm=true."); - return; - } - JigsawStudioBridge.get().deleteProject(player()); - } - - @Director(description = "Show active Jigsaw Studio and dynamic evaluation state", sync = true, - origin = DirectorOrigin.PLAYER) - public void status() { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - JigsawStudioLayout layout = context.session().layout(); - String selection = context.session().selectedBayId().orElse("none"); - JigsawStudioVariant activeVariant = "none".equals(selection) - ? null - : context.session().activeVariant(selection).orElse(null); - JigsawStudioBay selectedBay = "none".equals(selection) ? null : layout.get(selection); - JigsawStudioCellDimensions selectedDimensions = selectedBay == null - ? null - : selectedBay.bounds().dimensions(); - Optional evaluation = JigsawStudioBridge.get().evaluation(player()); - sender().sendMessage(C.AQUA + "Jigsaw Studio: " + context.request().structureKey()); - sender().sendMessage(C.GRAY + "mode=" + layout.mode() - + ", compatibility=" + context.request().compatibilityTarget() - + ", defaultCell=" + layout.cellDimensions().width() + "x" - + layout.cellDimensions().height() + "x" + layout.cellDimensions().depth() - + ", workcells=" + layout.bays().size() - + ", variants=" + layout.variantCatalog().size()); - sender().sendMessage(C.GRAY + "selected=" + selection - + ", activeVariant=" + (activeVariant == null ? "none" : activeVariant.pieceKey()) - + ", size=" + (selectedDimensions == null ? "none" : selectedDimensions.width() + "x" - + selectedDimensions.height() + "x" + selectedDimensions.depth()) - + ", enabled=" + (selectedBay == null ? "n/a" : selectedBay.enabled()) - + ", autosavePending=" + context.session().isDirty()); - if (evaluation.isPresent()) { - JigsawStudioGraphEvaluation current = evaluation.get(); - sender().sendMessage(C.GRAY + "evaluation=" + current.state() - + ", seed=" + current.seed() - + ", theme=" + (current.selectedTheme().isBlank() ? "unthemed" : current.selectedTheme()) - + ", pieces=" + current.pieceCount() - + ", detail=" + current.detail()); - } else { - sender().sendMessage(C.GRAY + "evaluation=PENDING, seed=" + DEFAULT_STUDIO_SEED); - } - } - - @Director(description = "Open the Jigsaw Studio workcell and variant menu", sync = true, - origin = DirectorOrigin.PLAYER) - public void menu() { - if (requireActive() != null) { - JigsawStudioBridge.get().openControlMenu(player()); - } - } - - @Director(description = "Select the Jigsaw Studio workcell containing you", sync = true, - origin = DirectorOrigin.PLAYER) - public void select() { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - Location location = player().getLocation(); - JigsawStudioBay bay = context.session().layout().findAt( - location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (bay == null) { - sendError("Stand inside a Jigsaw Studio workcell before selecting it."); - return; - } - context.session().selectBay(bay.stableId()); - sender().sendMessage(C.GREEN + "Selected " + bay.stableId() + " (" + bay.kind() + ")."); - } - - @Director(name = "bounds", aliases = {"cell", "resize"}, - description = "Set the selected Studio workcell capacity", - sync = true, origin = DirectorOrigin.PLAYER) - public void bounds( - @Param(description = "Cell width") int width, - @Param(description = "Cell height") int height, - @Param(description = "Cell depth") int depth - ) { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError("Select a Jigsaw Studio workcell before changing its capacity."); - return; - } - JigsawStudioCellDimensions dimensions; - try { - dimensions = new JigsawStudioCellDimensions(width, height, depth); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - if (dimensions.equals(selected.capacity())) { - sender().sendMessage(C.YELLOW + "Workcell capacity is unchanged."); - return; - } - JigsawStudioBridge.get().updateWorkcellDimensions(player(), selected.stableId(), dimensions); - } - - @Director(description = "Flush the automatic save for a workcell now", sync = true, - origin = DirectorOrigin.PLAYER) - public void save( - @Param(description = "Workcell ID or selected", defaultValue = "selected") String bay - ) { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - if ("selected".equalsIgnoreCase(bay)) { - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError("Select a Jigsaw Studio workcell before flushing its autosave."); - return; - } - JigsawStudioBridge.get().flushAutosave(player(), selected.stableId()); - return; - } - JigsawStudioBridge.get().flushAutosave(player(), bay); - } - - @Director(name = "goto", aliases = "teleport", description = "Select and teleport to a Studio workcell", - sync = true, origin = DirectorOrigin.PLAYER) - public void gotoBay( - @Param(description = "Workcell ID") String bay - ) { - if (requireActive() != null) { - JigsawStudioBridge.get().teleportTo(player(), bay); - } - } - - @Director(description = "Enable or disable Jigsaw Studio particles", sync = true, - origin = DirectorOrigin.PLAYER) - public void particles( - @Param(description = "Whether particles are visible") boolean visible - ) { - if (requireActive() != null) { - JigsawStudioBridge.get().setParticles(player(), visible); - } - } - - @Director(description = "Export the clean active graph as a vanilla datapack", sync = true, - origin = DirectorOrigin.PLAYER) - public void export( - @Param(description = "Datapack namespace", defaultValue = "iris") String namespace, - @Param(description = "Output name under the Studio exports folder", defaultValue = "jigsaw-export") - String output, - @Param(description = "directory or zip", defaultValue = "zip") String format, - @Param(description = "Replace an existing export", defaultValue = "false") boolean replace - ) { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - if (context.session().isDirty()) { - sendError("Wait for the pending autosave or discard the edits before exporting the on-disk graph."); - return; - } - VanillaJigsawExportFormat exportFormat; - try { - exportFormat = parseFormat(format); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - Path exportRoot = new File(Iris.service(StudioSVC.class).getWorkspaceFolder(), "exports") - .toPath().toAbsolutePath().normalize(); - Path destination; - try { - destination = resolveExportDestination(exportRoot, output, exportFormat); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - VanillaJigsawExportRequest request; - try { - request = VanillaJigsawExportRequest.builder( - VanillaJigsawExportSource.forData( - context.request().source(), context.request().structureKey()), destination) - .namespace(namespace) - .resourcePath(context.request().structureKey()) - .format(exportFormat) - .replaceExisting(replace) - .build(); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - Player targetPlayer = player(); - UUID playerId = targetPlayer.getUniqueId(); - UUID requestId = context.request().requestId(); - JigsawStudioBridge studioService = JigsawStudioBridge.get(); - JigsawStudioService.ExportStart exportStart = studioService.tryBeginExport(requestId, playerId); - if (exportStart != JigsawStudioService.ExportStart.STARTED) { - sendError(exportStartError(exportStart)); - return; - } - if (!beginExport(playerId, destination)) { - studioService.finishExport(requestId); - sendError("A vanilla Jigsaw export for this player or output is already in progress."); - return; - } - ExportLease lease = new ExportLease(() -> { - finishExport(playerId, destination); - studioService.finishExport(requestId); - }); - ExportOperation operation = new ExportOperation( - targetPlayer, - sender(), - requestId, - context.request().structureKey(), - request, - lease); - sender().sendMessage(C.GRAY + "Exporting '" + operation.structureKey() - + "' in the background to " + destination + "..."); - try { - J.a(() -> runExport(operation)); - } catch (RuntimeException exception) { - operation.lease().release(); - Iris.reportError("Failed to schedule vanilla Jigsaw export for '" - + operation.structureKey() + "'.", exception); - sendError("Vanilla export could not be scheduled: " + exception.getMessage()); - } - } - - static String exportStartError(JigsawStudioService.ExportStart exportStart) { - Objects.requireNonNull(exportStart, "Jigsaw Studio export start status"); - return switch (exportStart) { - case NOT_ACTIVE -> "The active Jigsaw Studio is no longer available."; - case NOT_OWNER -> "Only the Jigsaw Studio owner can export this project."; - case DIRTY -> "Wait for the pending autosave or discard the edits before exporting the on-disk graph."; - case CLOSING -> "The active Jigsaw Studio is closing and cannot be exported."; - case SAVE_IN_PROGRESS -> "Wait for the current Jigsaw Studio save to finish before exporting."; - case OPERATION_IN_PROGRESS -> "Wait for the current Jigsaw Studio operation to finish before exporting."; - case IN_PROGRESS -> "A Jigsaw Studio export is already in progress."; - case STARTED -> throw new IllegalArgumentException("STARTED is not an export failure"); - }; - } - - static boolean beginExport(UUID playerId, Path destination) { - Objects.requireNonNull(playerId); - Path normalizedDestination = Objects.requireNonNull(destination).toAbsolutePath().normalize(); - if (!EXPORTING_PLAYERS.add(playerId)) { - return false; - } - if (EXPORT_DESTINATIONS.add(normalizedDestination)) { - return true; - } - EXPORTING_PLAYERS.remove(playerId); - return false; - } - - static void finishExport(UUID playerId, Path destination) { - EXPORTING_PLAYERS.remove(Objects.requireNonNull(playerId)); - EXPORT_DESTINATIONS.remove(Objects.requireNonNull(destination).toAbsolutePath().normalize()); - } - - private static void pruneAdoptionPlanBindings() { - for (Map.Entry entry : ADOPTION_PLANS.entrySet()) { - AdoptionPlanBinding binding = entry.getValue(); - if (binding.service().plan(entry.getKey()).isEmpty()) { - ADOPTION_PLANS.remove(entry.getKey(), binding); - } - } - } - - private static boolean studioIsActiveOrOpening() { - return registry().activeOwnerId() != null - || registry().openingOwnerId() != null; - } - - private static void runAdoptionApply( - Player targetPlayer, - VolmitSender commandSender, - UUID planId, - AdoptionPlanBinding binding - ) { - if (studioIsActiveOrOpening()) { - ADOPTION_PLANS.putIfAbsent(planId, binding); - J.runEntity(targetPlayer, () -> sendError(commandSender, - "Close the active or opening Jigsaw Studio before applying an adoption plan.")); - return; - } - IrisStructureAdoptionResult result; - Throwable failure = null; - try { - result = binding.service().apply(binding.plan()); - } catch (Throwable throwable) { - result = null; - failure = throwable; - Iris.reportError("Failed to apply Jigsaw adoption plan '" + planId + "'.", throwable); - } - IrisStructureAdoptionResult completedResult = result; - Throwable completedFailure = failure; - J.runEntity(targetPlayer, () -> finishAdoptionApply( - targetPlayer, - commandSender, - binding, - completedResult, - completedFailure)); - } - - private static void runAdoptionInspect( - Player targetPlayer, - VolmitSender commandSender, - UUID ownerId, - IrisDimension dimension, - IrisData data, - Path root, - String sourceKey, - Optional targetKey, - IrisStructureAdoptionStrategy strategy - ) { - IrisStructureAdoptionService service = null; - IrisStructureAdoptionPlan plan = null; - Throwable failure = null; - try { - IrisStructureAdoptionInputKind inputKind = adoptionInputKind(root, sourceKey); - service = ADOPTION_SERVICES.computeIfAbsent(root, IrisStructureAdoptionService::new); - plan = service.inspect(new IrisStructureAdoptionRequest( - sourceKey, - targetKey, - strategy, - inputKind)); - } catch (Throwable throwable) { - failure = throwable; - Iris.reportError("Failed to inspect Jigsaw adoption source '" + sourceKey + "'.", throwable); - } - IrisStructureAdoptionService completedService = service; - IrisStructureAdoptionPlan completedPlan = plan; - Throwable completedFailure = failure; - J.runEntity(targetPlayer, () -> finishAdoptionInspect( - commandSender, - ownerId, - dimension, - data, - completedService, - completedPlan, - completedFailure)); - } - - private static void finishAdoptionInspect( - VolmitSender commandSender, - UUID ownerId, - IrisDimension dimension, - IrisData data, - IrisStructureAdoptionService service, - IrisStructureAdoptionPlan plan, - Throwable failure - ) { - if (failure != null || service == null || plan == null) { - sendError(commandSender, "Jigsaw adoption inspection failed: " - + (failure == null ? "no result" : failure.getMessage())); - return; - } - pruneAdoptionPlanBindings(); - if (service.plan(plan.planId()).isPresent()) { - ADOPTION_PLANS.put(plan.planId(), new AdoptionPlanBinding( - ownerId, dimension, data, service, plan)); - } - reportAdoptionPlan(commandSender, plan); - } - - private static void finishAdoptionApply( - Player targetPlayer, - VolmitSender commandSender, - AdoptionPlanBinding binding, - IrisStructureAdoptionResult result, - Throwable failure - ) { - if (failure != null || result == null) { - sendError(commandSender, "Jigsaw adoption failed: " - + (failure == null ? "no result" : failure.getMessage())); - return; - } - reportAdoptionResult(commandSender, result); - if (!result.successful()) { - return; - } - StructureKey target = result.receipt().orElseThrow().targetStructure(); - binding.data().invalidateStructureResources(); - openProject(targetPlayer, commandSender, binding.dimension(), target.path(), DEFAULT_STUDIO_SEED); - } - - private static void reportAdoptionPlan(VolmitSender commandSender, IrisStructureAdoptionPlan plan) { - C statusColor = plan.canApply() ? C.GREEN : C.RED; - commandSender.sendMessage(statusColor + "Adoption plan " + plan.planId() + " -> " - + plan.disposition() + " for " + plan.targetStructure().value() + "."); - commandSender.sendMessage(C.GRAY + "Resources=" + plan.resourceCount() - + ", bytes=" + plan.totalSourceBytes() - + ", errors=" + plan.errorCount() - + ", warnings=" + plan.warningCount() + "."); - for (IrisStructureAdoptionDiagnostic diagnostic : plan.diagnostics()) { - commandSender.sendMessage(adoptionColor(diagnostic).toString() + diagnostic.summary()); - } - if (plan.canApply()) { - commandSender.sendMessage(C.AQUA + "Apply with /iris jigsaw adopt apply " + plan.planId()); - } - } - - private static void reportAdoptionResult(VolmitSender commandSender, IrisStructureAdoptionResult result) { - commandSender.sendMessage((result.successful() ? C.GREEN : C.RED) - + "Adoption plan " + result.planId() + ": " + result.status() + "."); - for (IrisStructureAdoptionDiagnostic diagnostic : result.diagnostics()) { - commandSender.sendMessage(adoptionColor(diagnostic).toString() + diagnostic.summary()); - } - } - - private static C adoptionColor(IrisStructureAdoptionDiagnostic diagnostic) { - return switch (diagnostic.severity()) { - case ERROR -> C.RED; - case WARNING -> C.YELLOW; - case INFO -> C.GRAY; - }; - } - - private static void runExport(ExportOperation operation) { - VanillaJigsawExportResult result = null; - Throwable failure = null; - try { - result = new VanillaJigsawDatapackExporter().export(operation.request()); - } catch (Throwable throwable) { - failure = throwable; - Iris.reportError("Vanilla Jigsaw export failed for '" + operation.structureKey() + "'.", throwable); - } finally { - operation.lease().release(); - } - VanillaJigsawExportResult completedResult = result; - Throwable completedFailure = failure; - Runnable response = () -> reportExport(operation, completedResult, completedFailure); - J.runEntity(operation.player(), response); - } - - private static void reportExport( - ExportOperation operation, - VanillaJigsawExportResult result, - Throwable failure - ) { - if (failure != null || result == null) { - operation.sender().sendMessage(C.RED + "Background vanilla export for '" - + operation.structureKey() + "' failed: " - + (failure == null ? "no result" : failure.getMessage())); - return; - } - for (VanillaJigsawExportDiagnostic diagnostic : result.diagnostics()) { - C color = diagnostic.isBlocking() ? C.RED : C.YELLOW; - operation.sender().sendMessage(color.toString() + diagnostic.code() + ": " + diagnostic.message()); - } - ActiveContext current = active(operation.player()); - boolean sameSession = current != null - && current.request().requestId().equals(operation.requestId()); - String contextLabel = sameSession ? "Vanilla export" : "Background vanilla export for '" - + operation.structureKey() + "'"; - operation.sender().sendMessage((result.isSuccess() ? C.GREEN : C.RED) + contextLabel + " " - + result.status() + ": " + result.output()); - } - - static ActiveContext active(Player player) { - if (player == null) { - return null; - } - SessionBinding binding = PLAYER_PACKS.get(player.getUniqueId()); - if (binding == null) { - return null; - } - ActiveContext context = context(binding); - if (context == null) { - PLAYER_PACKS.remove(player.getUniqueId(), binding); - return null; - } - return context; - } - - private static ActiveContext context(SessionBinding binding) { - JigsawStudioRequest request = registry().getRequest(binding.packKey()); - JigsawStudioSession session = registry().getSession(binding.packKey()); - if (request == null || session == null - || !binding.requestId().equals(request.requestId()) - || !request.requestId().equals(session.sessionId())) { - return null; - } - return new ActiveContext(binding.packKey(), request, session); - } - - private static ActiveContext findDirtyContext() { - for (SessionBinding binding : PLAYER_PACKS.values()) { - JigsawStudioRequest request = registry().getRequest(binding.packKey()); - JigsawStudioSession session = registry().getSession(binding.packKey()); - if (request != null && session != null - && binding.requestId().equals(request.requestId()) - && session.isDirty()) { - return new ActiveContext(binding.packKey(), request, session); - } - } - return null; - } - - private ActiveContext requireActive() { - ActiveContext context = active(player()); - if (context == null) { - sendError("Open a Jigsaw Studio project first."); - } - return context; - } - - private IrisData requireData(IrisDimension dimension) { - return requireData(dimension, sender()); - } - - private static IrisData requireData(IrisDimension dimension, VolmitSender commandSender) { - IrisData data = dimension == null ? null : dimension.getLoader(); - if (data == null) { - sendError(commandSender, "Could not resolve the requested Iris pack dimension."); - } - return data; - } - - private static void beginStagedOpen(JigsawStudioRegistry.StagedActivation staged) { - if (!registry().beginStagedGeneration(staged)) { - throw new IllegalStateException("The staged Jigsaw Studio activation is no longer current"); - } - } - - private static void finishOpenAttempt( - VolmitSender commandSender, - UUID playerId, - String structureKey, - UUID closingRequestId, - JigsawStudioBridge studioService, - JigsawStudioRegistry.StagedActivation staged, - ToolWorld result, - Throwable throwable - ) { - registry().finishOpen(playerId); - if (throwable == null && result != null) { - studioService.cancelClose(closingRequestId); - return; - } - studioService.cancelClose(closingRequestId); - registry().rollback(staged); - Throwable failure = unwrapCompletionFailure(throwable == null - ? new IllegalStateException("Studio open completed without a result") - : throwable); - if (isExpectedOpenDenial(failure)) { - Iris.warn("Jigsaw Studio open for '%s' was denied: %s", - structureKey, failure.getMessage()); - return; - } - Iris.reportError("Failed to open Jigsaw Studio for '" + structureKey + "'.", failure); - sendError(commandSender, "Jigsaw Studio open failed: " + failure.getMessage()); - } - - /** Commits the staged studio once its world is open and moves the player in; the failure, or null when all went well. */ - private static Throwable commitOpenedStudio( - Player targetPlayer, - ToolWorld world, - JigsawStudioRegistry.StagedActivation staged, - JigsawStudioBridge studioService - ) { - try { - enterCommittedStudio(targetPlayer, world, staged, studioService); - return null; - } catch (RuntimeException exception) { - return exception; - } - } - - private static void enterCommittedStudio( - Player targetPlayer, - ToolWorld world, - JigsawStudioRegistry.StagedActivation staged, - JigsawStudioBridge studioService - ) { - if (world == null) { - throw new IllegalStateException("Jigsaw Studio opened without a world"); - } - JigsawStudioRequest request = staged.request(); - JigsawStudioSession session = staged.session(); - JigsawStudioBay destination = initialBay(session.layout()); - double targetX = destination == null - ? 0.5D - : destination.bounds().originX() + destination.bounds().dimensions().width() / 2.0D; - double targetY = destination == null ? 66D : destination.bounds().maxY() + 2.0D; - double targetZ = destination == null - ? 0.5D - : destination.bounds().originZ() + destination.bounds().dimensions().depth() / 2.0D; - if (destination != null) { - session.selectBay(destination.stableId()); - } - if (!registry().commit(staged)) { - throw new IllegalStateException("The staged Jigsaw Studio activation could not be committed"); - } - studioService.activationCommitted(request.requestId()); - PLAYER_PACKS.put(targetPlayer.getUniqueId(), new SessionBinding( - request.packKey(), request.requestId())); - ToolPlayer player = JigsawStudioBridge.toolPlayer(targetPlayer); - try { - player.teleport(world, targetX, targetY, targetZ, 0.0F, 0.0F) - .thenRun(() -> player.creative(true)); - } catch (RuntimeException exception) { - Iris.reportError("Failed to move the player to the committed Jigsaw Studio workcell.", exception); - } - } - - private static JigsawStudioBay initialBay(JigsawStudioLayout layout) { - for (JigsawStudioBay bay : layout.bays()) { - if (layout.defaultVariant(bay).isPresent()) { - return bay; - } - } - return layout.bays().isEmpty() ? null : layout.bays().getFirst(); - } - - private static Throwable unwrapCompletionFailure(Throwable failure) { - Throwable current = failure; - while (current instanceof CompletionException && current.getCause() != null) { - current = current.getCause(); - } - return current; - } - - static boolean isExpectedOpenDenial(Throwable failure) { - return unwrapCompletionFailure(failure) instanceof BrokenPackException; - } - - private void sendError(String message) { - sender().sendMessage(C.RED + message); - } - - private static void sendError(VolmitSender commandSender, String message) { - commandSender.sendMessage(C.RED + message); - } - - private static JigsawStudioMode parseMode(String value) { - return switch (value.trim().toLowerCase(Locale.ROOT)) { - case "planar", "2d", "planar_jigsaw" -> JigsawStudioMode.PLANAR_JIGSAW; - case "spatial", "3d", "spatial_jigsaw" -> JigsawStudioMode.SPATIAL_JIGSAW; - default -> throw new IllegalArgumentException("Mode must be planar or spatial."); - }; - } - - private static JigsawStudioCompatibilityTarget parseCompatibility(String value) { - return switch (value.trim().toLowerCase(Locale.ROOT)) { - case "extended", "iris", "iris_extended" -> JigsawStudioCompatibilityTarget.IRIS_EXTENDED; - case "vanilla", "portable", "vanilla_portable" -> JigsawStudioCompatibilityTarget.VANILLA_PORTABLE; - default -> throw new IllegalArgumentException("Compatibility must be iris or vanilla."); - }; - } - - private static JigsawStudioCompatibilityTarget compatibilityOf(IrisStructure structure) { - return structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE - ? JigsawStudioCompatibilityTarget.VANILLA_PORTABLE - : JigsawStudioCompatibilityTarget.IRIS_EXTENDED; - } - - static NamespacedKey parseRegisteredStructureKey(String value) { - String normalized = Objects.requireNonNull(value, "Registered structure key").trim() - .toLowerCase(Locale.ROOT); - NamespacedKey key = NamespacedKey.fromString(normalized); - if (key == null) { - throw new IllegalArgumentException( - "Registered structure source must use a valid namespace:path key."); - } - return key; - } - - static String resolveConversionTarget(NamespacedKey source, String value) { - Objects.requireNonNull(source, "Registered structure key"); - String normalized = Objects.requireNonNull(value, "Conversion target").trim() - .toLowerCase(Locale.ROOT); - if (normalized.isEmpty() || "auto".equals(normalized)) { - return StructureImporter.deriveName(source); - } - StructureKey target = StructureKey.parse(normalized, "iris"); - if (!"iris".equals(target.namespace())) { - throw new IllegalArgumentException("Converted Studio targets must use the iris namespace."); - } - return target.path(); - } - - static String conversionFailureMessage(VillageImporter.Result result) { - String message = Objects.requireNonNull(result, "Village import result").message(); - String obsoleteInstruction = "; use 'import' for single-template structures"; - int instructionIndex = message.indexOf(obsoleteInstruction); - if (instructionIndex < 0) { - return message; - } - return message.substring(0, instructionIndex) - + ". This Studio converter accepts registered jigsaw structures only."; - } - - static String parseAdoptionSource(String value) { - String normalized = Objects.requireNonNull(value, "Adoption source").trim() - .toLowerCase(Locale.ROOT); - StructureKey source = StructureKey.parse(normalized, "iris"); - if (!"iris".equals(source.namespace())) { - throw new IllegalArgumentException("Adoption sources must use the iris namespace."); - } - return source.path(); - } - - static Optional parseAdoptionTarget(String value) { - String normalized = Objects.requireNonNull(value, "Adoption target").trim() - .toLowerCase(Locale.ROOT); - if (normalized.isEmpty() || "auto".equals(normalized)) { - return Optional.empty(); - } - StructureKey target = StructureKey.parse(normalized, "iris"); - if (!"iris".equals(target.namespace())) { - throw new IllegalArgumentException("Adoption targets must use the iris namespace."); - } - return Optional.of(target); - } - - private static IrisStructureAdoptionStrategy parseAdoptionStrategy(String value) { - return switch (Objects.requireNonNull(value, "Adoption strategy").trim().toLowerCase(Locale.ROOT)) { - case "auto" -> IrisStructureAdoptionStrategy.AUTO; - case "in-place", "in_place", "inplace", "claim" -> IrisStructureAdoptionStrategy.IN_PLACE; - case "clone", "copy" -> IrisStructureAdoptionStrategy.CLONE; - default -> throw new IllegalArgumentException("Adoption strategy must be auto, in-place, or clone."); - }; - } - - static IrisStructureAdoptionInputKind adoptionInputKind(Path packRoot, String source) throws IOException { - Path root = canonicalAdoptionRoot(packRoot); - StructureKey sourceKey = new StructureKey("iris", parseAdoptionSource(source)); - Path manifestPath = new StructureTransactionWriter(root).ownershipManifestPath(sourceKey); - if (!Files.exists(manifestPath, LinkOption.NOFOLLOW_LINKS)) { - return IrisStructureAdoptionInputKind.UNOWNED_IRIS; - } - if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) { - throw new IOException("Ownership manifest is not a regular file: " + manifestPath); - } - StructureOwnershipManifest manifest; - try { - manifest = StructureOwnershipManifest.fromJson(Files.readAllBytes(manifestPath)); - } catch (RuntimeException exception) { - throw new IOException("Invalid ownership manifest at " + manifestPath, exception); - } - if (!manifest.structure().equals(sourceKey)) { - throw new IOException("Ownership manifest at " + manifestPath - + " belongs to " + manifest.structure().value()); - } - return manifest.provenance().origin() == StructureOwnershipManifest.Origin.MANAGED_DATAPACK - ? IrisStructureAdoptionInputKind.MANAGED_DATAPACK - : IrisStructureAdoptionInputKind.UNOWNED_IRIS; - } - - private static Path canonicalAdoptionRoot(Path packRoot) throws IOException { - Path normalized = Objects.requireNonNull(packRoot, "Adoption pack root").toAbsolutePath().normalize(); - return Files.exists(normalized, LinkOption.NOFOLLOW_LINKS) ? normalized.toRealPath() : normalized; - } - - private static VanillaJigsawExportFormat parseFormat(String value) { - return switch (value.trim().toLowerCase(Locale.ROOT)) { - case "zip" -> VanillaJigsawExportFormat.ZIP; - case "directory", "dir", "folder" -> VanillaJigsawExportFormat.DIRECTORY; - default -> throw new IllegalArgumentException("Export format must be directory or zip."); - }; - } - - static Path resolveExportDestination( - Path exportRoot, - String output, - VanillaJigsawExportFormat format - ) { - Path root = Objects.requireNonNull(exportRoot, "Jigsaw export root").toAbsolutePath().normalize(); - String requested = Objects.requireNonNull(output, "Jigsaw export output name"); - String name = requested.trim(); - if (!name.equals(requested) || !EXPORT_OUTPUT_NAME.matcher(name).matches()) { - throw new IllegalArgumentException( - "Export output must be one file name using letters, numbers, '.', '_', or '-'."); - } - String fileName = format == VanillaJigsawExportFormat.ZIP && !name.endsWith(".zip") - ? name + ".zip" : name; - Path destination = root.resolve(fileName).normalize(); - if (destination.equals(root) || !root.equals(destination.getParent())) { - throw new IllegalArgumentException("Export output must be one artifact inside the Studio exports folder."); - } - return destination; - } - - static JigsawStudioBay selectedBay(ActiveContext context) { - String selected = context.session().selectedBayId().orElse(null); - return selected == null ? null : context.session().layout().get(selected); - } - - static JigsawStudioVariant selectedVariant(ActiveContext context) { - JigsawStudioBay selected = selectedBay(context); - return selected == null - ? null - : context.session().activeVariant(selected.stableId()).orElse(null); - } - - static boolean runGraphMutation( - Player player, - ActiveContext context, - JigsawStudioService.CommandGraphMutation mutation - ) { - return JigsawStudioBridge.get().runCommandGraphMutation( - player, - context.request().requestId(), - mutation); - } - - static JigsawStudioLayout loadPersistedLayout(ActiveContext context) throws IOException { - IrisData source = context.request().source(); - source.invalidateStructureResources(); - IrisStructure structure = StructureResources.structure(source.getPackResources(), context.request().structureKey()); - if (structure == null) { - throw new IOException("The structure could not be reloaded after the graph transaction"); - } - return JigsawStudioGraphMapper.map(source, structure); - } - - static JigsawStudioService.CommandGraphMutationResult mappedMutationResult( - ActiveContext context, - String activateWorkcellId, - String activatePieceKey, - String message - ) throws IOException { - return new JigsawStudioService.CommandGraphMutationResult( - loadPersistedLayout(context), - activateWorkcellId, - activatePieceKey, - message); - } - - static String workcellIdForVariant(JigsawStudioLayout layout, String pieceKey) throws IOException { - JigsawStudioVariant variant = layout.variantCatalog().find(pieceKey).orElse(null); - if (variant == null) { - throw new IOException("Persisted variant '" + pieceKey + "' did not map to a Studio workcell"); - } - return variant.archetype() - .map(archetype -> archetype.stableId()) - .orElse(JigsawStudioLayout.SPATIAL_WORKCELL_ID); - } - - static PieceWorkcellResolution resolvePieceWorkcell( - JigsawStudioLayout layout, - IrisJigsawPiece piece, - IrisObject object - ) { - JigsawStudioLayout activeLayout = Objects.requireNonNull(layout, "Jigsaw Studio layout"); - IrisJigsawPiece activePiece = Objects.requireNonNull(piece, "Jigsaw piece"); - IrisObject activeObject = Objects.requireNonNull(object, "Jigsaw piece object"); - String workcellId; - IrisPosition requiredDimensions; - if (activeLayout.mode() == JigsawStudioMode.PLANAR_JIGSAW) { - IrisJigsawWorkcellArchetype modelArchetype = IrisJigsawWorkcellArchetype.fromPiece(activePiece); - workcellId = JigsawPlanarArchetype.fromModel(modelArchetype).stableId(); - requiredDimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(activePiece, activeObject); - } else { - workcellId = JigsawStudioLayout.SPATIAL_WORKCELL_ID; - requiredDimensions = new IrisPosition( - activeObject.getW(), - activeObject.getH(), - activeObject.getD()); - } - JigsawStudioBay workcell = activeLayout.get(workcellId); - if (workcell == null) { - throw new IllegalArgumentException("Workcell '" + workcellId + "' is not configured"); - } - return new PieceWorkcellResolution(workcell, requiredDimensions); - } - - static String nextThemeKey(ActiveContext context) throws IOException { - IrisStructure structure = StructureResources.structure( - context.request().source().getPackResources(), - context.request().structureKey()); - if (structure == null) { - throw new IOException("The active jigsaw structure could not be loaded"); - } - Set declared = new HashSet<>(); - if (structure.getThemeSets() != null) { - for (IrisJigsawThemeSet themeSet : structure.getThemeSets()) { - if (themeSet != null && themeSet.getKey() != null) { - declared.add(themeSet.getKey()); - } - } - } - int candidate = 1; - while (candidate > 0) { - String key = "variant-" + candidate; - if (!declared.contains(key)) { - return key; - } - candidate = Math.incrementExact(candidate); - } - throw new IOException("Jigsaw Studio cannot allocate another numbered family key"); - } - - static void sendError(DirectorExecutor executor, String message) { - executor.sender().sendMessage(C.RED + message); - } - - public record ActiveContext( - String packKey, - JigsawStudioRequest request, - JigsawStudioSession session - ) { - } - - record PieceWorkcellResolution( - JigsawStudioBay workcell, - IrisPosition requiredDimensions - ) { - PieceWorkcellResolution { - workcell = Objects.requireNonNull(workcell, "Jigsaw Studio workcell"); - requiredDimensions = Objects.requireNonNull(requiredDimensions, "Jigsaw piece dimensions"); - } - - boolean fits() { - JigsawStudioCellDimensions capacity = workcell.capacity(); - return requiredDimensions.getX() <= capacity.width() - && requiredDimensions.getY() <= capacity.height() - && requiredDimensions.getZ() <= capacity.depth(); - } - } - - private record SessionBinding(String packKey, UUID requestId) { - } - - private record ExportOperation( - Player player, - VolmitSender sender, - UUID requestId, - String structureKey, - VanillaJigsawExportRequest request, - ExportLease lease - ) { - } - - static final class ExportLease { - private final Runnable release; - private final AtomicBoolean released; - - ExportLease(Runnable release) { - this.release = Objects.requireNonNull(release, "Jigsaw export lease release action"); - this.released = new AtomicBoolean(); - } - - void release() { - if (released.compareAndSet(false, true)) { - release.run(); - } - } - } - - private record AdoptionPlanBinding( - UUID ownerId, - IrisDimension dimension, - IrisData data, - IrisStructureAdoptionService service, - IrisStructureAdoptionPlan plan - ) { - } - - public static final class JigsawModeHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - return new KList<>("planar", "spatial"); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - try { - return parseMode(input) == JigsawStudioMode.PLANAR_JIGSAW ? "planar" : "spatial"; - } catch (IllegalArgumentException exception) { - throw new DirectorParsingException(exception.getMessage()); - } - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - } - - public static final class JigsawCompatibilityHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - return new KList<>("iris", "vanilla"); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - try { - return parseCompatibility(input) == JigsawStudioCompatibilityTarget.IRIS_EXTENDED - ? "iris" : "vanilla"; - } catch (IllegalArgumentException exception) { - throw new DirectorParsingException(exception.getMessage()); - } - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - } - - public static final class JigsawAdoptionStrategyHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - return new KList<>("auto", "in-place", "clone"); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - try { - return switch (parseAdoptionStrategy(input)) { - case AUTO -> "auto"; - case IN_PLACE -> "in-place"; - case CLONE -> "clone"; - }; - } catch (IllegalArgumentException exception) { - throw new DirectorParsingException(exception.getMessage()); - } - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - } - - public static final class JigsawAdoptionPlanHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - return new KList<>(); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - try { - return UUID.fromString(input).toString(); - } catch (IllegalArgumentException exception) { - throw new DirectorParsingException("Adoption plan ID must be a UUID."); - } - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - } - - @Director(name = "adopt", description = "Inspect and apply safe ownership adoption plans", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawAdopt implements DirectorExecutor { - @Director(description = "Inspect an Iris graph for safe Studio ownership adoption", sync = true, - origin = DirectorOrigin.PLAYER) - public void inspect( - @Param(description = "Pack dimension") IrisDimension dimension, - @Param(description = "Existing Iris structure key") String source, - @Param(description = "New owned Iris key, or auto", defaultValue = "auto") String target, - @Param(description = "auto, in-place, or clone", defaultValue = "auto", - customHandler = JigsawAdoptionStrategyHandler.class) String strategy - ) { - VolmitSender commandSender = sender(); - IrisData data = requireData(dimension, commandSender); - if (data == null) { - return; - } - String sourceKey; - Optional targetKey; - IrisStructureAdoptionStrategy adoptionStrategy; - Path root; - try { - sourceKey = parseAdoptionSource(source); - targetKey = parseAdoptionTarget(target); - adoptionStrategy = parseAdoptionStrategy(strategy); - root = canonicalAdoptionRoot(data.getDataFolder().toPath()); - } catch (IOException | IllegalArgumentException exception) { - sendError(commandSender, "Could not inspect adoption source: " + exception.getMessage()); - return; - } - Player targetPlayer = player(); - UUID ownerId = targetPlayer.getUniqueId(); - commandSender.sendMessage(C.GRAY + "Inspecting Jigsaw adoption source '" + sourceKey - + "' asynchronously..."); - try { - J.a(() -> runAdoptionInspect( - targetPlayer, - commandSender, - ownerId, - dimension, - data, - root, - sourceKey, - targetKey, - adoptionStrategy)); - } catch (RuntimeException exception) { - Iris.reportError("Failed to schedule Jigsaw adoption inspection for '" - + sourceKey + "'.", exception); - sendError(commandSender, "Jigsaw adoption inspection could not be scheduled: " - + exception.getMessage()); - } - } - - @Director(description = "Apply one inspected adoption plan without overwriting", sync = true, - origin = DirectorOrigin.PLAYER) - public void apply( - @Param(description = "Plan UUID returned by adopt inspect", - customHandler = JigsawAdoptionPlanHandler.class) String planId - ) { - VolmitSender commandSender = sender(); - UUID parsedPlanId; - try { - parsedPlanId = UUID.fromString(planId); - } catch (IllegalArgumentException exception) { - sendError(commandSender, "Adoption plan ID must be a UUID."); - return; - } - if (studioIsActiveOrOpening()) { - sendError(commandSender, - "Close the active or opening Jigsaw Studio before applying an adoption plan."); - return; - } - pruneAdoptionPlanBindings(); - AdoptionPlanBinding binding = ADOPTION_PLANS.get(parsedPlanId); - UUID playerId = player().getUniqueId(); - if (binding == null || !binding.ownerId().equals(playerId)) { - sendError(commandSender, "No active adoption plan '" + parsedPlanId - + "' belongs to your player session. Run adopt inspect again."); - return; - } - if (binding.service().plan(parsedPlanId).isEmpty()) { - ADOPTION_PLANS.remove(parsedPlanId, binding); - sendError(commandSender, "Adoption plan '" + parsedPlanId - + "' expired or was already consumed. Run adopt inspect again."); - return; - } - if (!ADOPTION_PLANS.remove(parsedPlanId, binding)) { - sendError(commandSender, "Adoption plan '" + parsedPlanId + "' is already being applied."); - return; - } - Player targetPlayer = player(); - commandSender.sendMessage(C.GRAY + "Applying adoption plan '" + parsedPlanId - + "' asynchronously without overwrite..."); - try { - J.a(() -> runAdoptionApply(targetPlayer, commandSender, parsedPlanId, binding)); - } catch (RuntimeException exception) { - ADOPTION_PLANS.putIfAbsent(parsedPlanId, binding); - Iris.reportError("Failed to schedule Jigsaw adoption plan '" + parsedPlanId + "'.", exception); - sendError(commandSender, "Jigsaw adoption could not be scheduled: " + exception.getMessage()); - } - } - } - - @Director(name = "connector", description = "Inspect and configure targeted jigsaw connectors", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawConnector implements DirectorExecutor { - @Director(description = "Set the Iris-only channel on the targeted jigsaw marker", sync = true, - origin = DirectorOrigin.PLAYER) - public void channel( - @Param(description = "Exact channel, or none to clear") String channel - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - Block target = player().getTargetBlockExact(8); - if (target == null || !(target.getBlockData() instanceof Jigsaw)) { - sendError(this, "Look directly at a jigsaw marker within eight blocks."); - return; - } - JigsawStudioBay bay = context.session().layout().findAt( - target.getX(), target.getY(), target.getZ()); - JigsawStudioVariant activeVariant = bay == null - ? null - : context.session().activeVariant(bay.stableId()).orElse(null); - if (activeVariant == null) { - sendError(this, "The targeted marker must be inside a workcell with an active variant."); - return; - } - if (!activeVariant.owned()) { - sendError(this, "The active variant is read-only. Adopt it into this project before editing it."); - return; - } - IrisObject object = context.request().source().getObjectLoader().load(activeVariant.objectKey()); - if (object == null) { - sendError(this, "The active variant object '" + activeVariant.objectKey() + "' is missing."); - return; - } - IrisPosition canonicalPosition = new IrisPosition( - target.getX() - bay.bounds().originX(), - target.getY() - bay.bounds().originY(), - target.getZ() - bay.bounds().originZ()); - IrisPosition position; - try { - position = activeVariant.canonicalToSourcePosition( - canonicalPosition, - new JigsawStudioCellDimensions(object.getW(), object.getH(), object.getD())); - } catch (IllegalArgumentException exception) { - sendError(this, "Connector channel update failed: " + exception.getMessage()); - return; - } - String normalized = channel == null || channel.isBlank() || "none".equalsIgnoreCase(channel) - ? "none" - : channel.trim(); - runGraphMutation(player(), context, () -> { - JigsawStudioGraphEditor.updateConnectorChannel( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - activeVariant.pieceKey(), - position, - channel); - return mappedMutationResult( - context, - "", - "", - "Persisted connector channel '" + normalized + "' on piece '" - + activeVariant.pieceKey() + "' at " + position.getX() + "," + position.getY() - + "," + position.getZ() + "."); - }); - } - } - - @Director(name = "pool", description = "Manage owned jigsaw pools", origin = DirectorOrigin.PLAYER) - public static class CommandJigsawPool implements DirectorExecutor { - @Director(description = "Create an empty owned jigsaw pool", sync = true, - origin = DirectorOrigin.PLAYER) - public void create( - @Param(description = "New owned pool resource key") String poolKey, - @Param(description = "Owned fallback pool key, or none", defaultValue = "none") - String fallbackPoolKey - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - String fallback = "none".equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey; - runGraphMutation(player(), context, () -> { - JigsawStudioGraphEditor.createPool( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - fallback); - return mappedMutationResult( - context, - "", - "", - "Created owned pool '" + poolKey + "' with fallback '" - + (fallback.isBlank() ? "none" : fallback) + "'."); - }); - } - } - - @Director(name = "piece", description = "Manage contextual Studio pieces", origin = DirectorOrigin.PLAYER) - public static class CommandJigsawPiece implements DirectorExecutor { - @Director(description = "Create an owned piece from the selected Studio topology", sync = true, - origin = DirectorOrigin.PLAYER) - public void create( - @Param(description = "Owned pool resource key") String poolKey, - @Param(description = "New owned piece and object key") String pieceKey, - @Param(description = "Positive selection weight", defaultValue = "1") int weight - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawPlanarTopology topology = null; - JigsawStudioBay targetWorkcell = context.session().layout().get(JigsawStudioLayout.SPATIAL_WORKCELL_ID); - if (context.session().layout().mode() == JigsawStudioMode.PLANAR_JIGSAW) { - Location location = player().getLocation(); - JigsawStudioBay contextual = context.session().layout().findAt( - location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (contextual == null) { - contextual = selectedBay(context); - } else { - context.session().selectBay(contextual.stableId()); - } - if (contextual == null || contextual.topology().isEmpty()) { - sendError(this, "Stand in or select a planar topology workcell before creating a variant."); - return; - } - topology = contextual.topology().get(); - targetWorkcell = contextual; - } - if (targetWorkcell == null) { - sendError(this, "The selected Jigsaw Studio workcell is no longer available."); - return; - } - JigsawPlanarTopology selectedTopology = topology; - String activationWorkcellId = targetWorkcell.stableId(); - JigsawStudioCellDimensions dimensions = targetWorkcell.capacity(); - String topologyText = selectedTopology == null ? "blank spatial" : selectedTopology.name(); - runGraphMutation(player(), context, () -> { - JigsawStudioGraphEditor.createPiece( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - pieceKey, - weight, - dimensions, - selectedTopology); - return mappedMutationResult( - context, - activationWorkcellId, - pieceKey, - "Created owned " + topologyText + " piece '" + pieceKey - + "' and added it to pool '" + poolKey + "' atomically."); - }); - } - - @Director(description = "Add an existing jigsaw piece to an owned pool transactionally", sync = true, - origin = DirectorOrigin.PLAYER) - public void add( - @Param(description = "Owned pool resource key") String poolKey, - @Param(description = "Existing jigsaw piece key") String pieceKey, - @Param(description = "Positive selection weight", defaultValue = "1") int weight - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - IrisJigsawPiece piece = StructureResources.piece(context.request().source().getPackResources(), pieceKey); - if (piece == null) { - sendError(this, "No jigsaw piece '" + pieceKey + "' exists in this pack."); - return; - } - if (piece.getObject() == null || piece.getObject().isBlank()) { - sendError(this, "Jigsaw piece '" + pieceKey + "' does not declare an object."); - return; - } - IrisObject object = context.request().source().getObjectLoader().load(piece.getObject()); - if (object == null) { - sendError(this, "Jigsaw piece '" + pieceKey + "' has no loadable object."); - return; - } - PieceWorkcellResolution resolution; - try { - resolution = resolvePieceWorkcell(context.session().layout(), piece, object); - } catch (IllegalArgumentException exception) { - sendError(this, "Jigsaw piece '" + pieceKey + "' cannot be assigned to a Studio workcell: " - + exception.getMessage()); - return; - } - if (!resolution.fits()) { - IrisPosition required = resolution.requiredDimensions(); - JigsawStudioCellDimensions capacity = resolution.workcell().capacity(); - sendError(this, "Jigsaw piece '" + pieceKey + "' requires " + required.getX() + "x" - + required.getY() + "x" + required.getZ() + " in " + resolution.workcell().displayName() - + ", but that workcell capacity is " + capacity.width() + "x" + capacity.height() - + "x" + capacity.depth() + "."); - return; - } - String objectKey = piece.getObject(); - runGraphMutation(player(), context, () -> { - if (!JigsawStudioGraphEditor.ownsPiece( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - pieceKey, - objectKey)) { - throw new IOException("Piece add accepts only piece/object resources already owned by this project; " - + "use piece create for a new owned piece"); - } - JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.addPiece( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - pieceKey, - weight); - if (!update.changed()) { - throw new IOException("The owned pool is missing or already references '" + pieceKey + "'"); - } - JigsawStudioLayout layout = loadPersistedLayout(context); - String activationWorkcellId = workcellIdForVariant(layout, pieceKey); - return new JigsawStudioService.CommandGraphMutationResult( - layout, - activationWorkcellId, - pieceKey, - "Added '" + pieceKey + "' to pool '" + poolKey + "' in one graph transaction."); - }); - } - - @Director(description = "Remove the selected piece from an owned pool transactionally", sync = true, - origin = DirectorOrigin.PLAYER) - public void remove( - @Param(description = "Owned pool resource key") String poolKey - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioVariant selected = selectedVariant(context); - if (selected == null) { - sendError(this, "Select a workcell with an active variant before removing its pool entry."); - return; - } - String pieceKey = selected.pieceKey(); - runGraphMutation(player(), context, () -> { - JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.removePiece( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - pieceKey); - if (!update.changed()) { - throw new IOException("The owned pool does not reference selected piece '" + pieceKey + "'"); - } - return mappedMutationResult( - context, - "", - "", - "Removed '" + pieceKey + "' from pool '" + poolKey + "' in one graph transaction."); - }); - } - - @Director(description = "Allow or forbid cardinal rotation of the selected piece", sync = true, - origin = DirectorOrigin.PLAYER) - public void rotatable( - @Param(description = "Whether the selected piece may rotate") boolean rotatable - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioVariant selected = selectedVariant(context); - if (selected == null) { - sendError(this, "Select a workcell with an active variant before changing rotation."); - return; - } - if (!rotatable - && context.request().compatibilityTarget() - == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE) { - sendError(this, "Vanilla-portable pieces must remain rotatable."); - return; - } - String pieceKey = selected.pieceKey(); - runGraphMutation(player(), context, () -> { - JigsawStudioGraphEditor.updateRotatable( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - pieceKey, - rotatable); - return mappedMutationResult( - context, - "", - "", - "Persisted piece '" + pieceKey + "' rotatable=" + rotatable + "."); - }); - } - - @Director(description = "Resize the selected piece object exactly to workcell capacity", sync = true, - origin = DirectorOrigin.PLAYER) - public void expand() { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay workcell = selectedBay(context); - if (workcell == null) { - sendError(this, "Select a workcell before expanding its active variant."); - return; - } - JigsawStudioBridge.get().expandVariantToCell(player(), workcell.stableId()); - } - } - - @Director(name = "workcell", aliases = "cell", description = "Manage the selected Studio workcell", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawWorkcell implements DirectorExecutor { - @Director(description = "Set capacity without resizing any variant object", sync = true, - origin = DirectorOrigin.PLAYER) - public void capacity( - @Param(description = "Capacity width") int width, - @Param(description = "Capacity height") int height, - @Param(description = "Capacity depth") int depth - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError(this, "Select a workcell before changing its capacity."); - return; - } - JigsawStudioCellDimensions dimensions; - try { - dimensions = new JigsawStudioCellDimensions(width, height, depth); - } catch (IllegalArgumentException exception) { - sendError(this, exception.getMessage()); - return; - } - JigsawStudioBridge.get().updateWorkcellDimensions( - player(), - selected.stableId(), - dimensions); - } - - @Director(description = "Set the selected workcell's author-facing label", sync = true, - origin = DirectorOrigin.PLAYER) - public void label( - @Param(description = "Display label; quote labels containing spaces") String displayName - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError(this, "Select a workcell before renaming it."); - return; - } - JigsawStudioBridge.get().updateWorkcellDisplayName( - player(), - selected.stableId(), - displayName); - } - - @Director(name = "label-reset", aliases = "reset-label", - description = "Reset the selected workcell to its canonical solver label", sync = true, - origin = DirectorOrigin.PLAYER) - public void labelReset() { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError(this, "Select a workcell before resetting its label."); - return; - } - JigsawStudioBridge.get().updateWorkcellDisplayName(player(), selected.stableId(), ""); - } - } - - @Director(name = "variant", description = "Manage selected jigsaw variants", origin = DirectorOrigin.PLAYER) - public static class CommandJigsawVariant implements DirectorExecutor { - @Director(description = "Set the selected piece weight in a pool", sync = true, - origin = DirectorOrigin.PLAYER) - public void weight( - @Param(description = "Pool resource key") String poolKey, - @Param(description = "Positive selection weight") int weight - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioVariant selected = selectedVariant(context); - if (selected == null) { - sendError(this, "Select a workcell with an active variant before changing its weight."); - return; - } - String pieceKey = selected.pieceKey(); - runGraphMutation(player(), context, () -> { - JigsawStudioPoolEditor.WeightUpdate update = JigsawStudioPoolEditor.updateWeight( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - pieceKey, - weight); - if (!update.changed()) { - throw new IOException("Pool '" + poolKey + "' does not reference selected piece '" - + pieceKey + "'"); - } - return mappedMutationResult( - context, - "", - "", - "Updated " + update.changedEntries() + " pool entry weight atomically in " - + update.poolPath() + "."); - }); - } - - @Director(description = "Resize only the active variant object within workcell capacity", sync = true, - origin = DirectorOrigin.PLAYER) - public void resize( - @Param(description = "Variant width") int width, - @Param(description = "Variant height") int height, - @Param(description = "Variant depth") int depth - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selectedWorkcell = selectedBay(context); - JigsawStudioVariant selectedVariant = selectedVariant(context); - if (selectedWorkcell == null || selectedVariant == null) { - sendError(this, "Select a workcell with an active variant before resizing it."); - return; - } - JigsawStudioCellDimensions dimensions; - try { - dimensions = new JigsawStudioCellDimensions(width, height, depth); - } catch (IllegalArgumentException exception) { - sendError(this, exception.getMessage()); - return; - } - JigsawStudioBridge.get().resizeVariant( - player(), - selectedWorkcell.stableId(), - selectedVariant.pieceKey(), - dimensions); - } - - @Director(description = "Set the active variant's author-facing label", sync = true, - origin = DirectorOrigin.PLAYER) - public void label( - @Param(description = "Display label; quote labels containing spaces") String displayName - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selectedWorkcell = selectedBay(context); - JigsawStudioVariant selectedVariant = selectedVariant(context); - if (selectedWorkcell == null || selectedVariant == null) { - sendError(this, "Select a workcell with an active variant before renaming it."); - return; - } - JigsawStudioBridge.get().updateVariantDisplayName( - player(), - selectedWorkcell.stableId(), - selectedVariant.pieceKey(), - displayName); - } - - @Director(name = "label-reset", aliases = "reset-label", - description = "Reset the active variant to its resource-key label", sync = true, - origin = DirectorOrigin.PLAYER) - public void labelReset() { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selectedWorkcell = selectedBay(context); - JigsawStudioVariant selectedVariant = selectedVariant(context); - if (selectedWorkcell == null || selectedVariant == null) { - sendError(this, "Select a workcell with an active variant before resetting its label."); - return; - } - JigsawStudioBridge.get().updateVariantDisplayName( - player(), - selectedWorkcell.stableId(), - selectedVariant.pieceKey(), - ""); - } - - @Director(description = "Duplicate the active variant in only this workcell", sync = true, - origin = DirectorOrigin.PLAYER) - public void duplicate() { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null || selectedVariant(context) == null) { - sendError(this, "Select a workcell with an active variant before duplicating it."); - return; - } - JigsawStudioBridge.get().createVariant(player(), selected.stableId(), true); - } - - @Director(name = "duplicate-family", aliases = "family", - description = "Duplicate every enabled workcell's active variant as one coherent family", - sync = true, origin = DirectorOrigin.PLAYER) - public void duplicateFamily( - @Param(description = "Family key or next", defaultValue = "next") String themeKey - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - String selectedTheme = themeKey; - if ("next".equalsIgnoreCase(themeKey)) { - try { - selectedTheme = nextThemeKey(context); - } catch (IOException | ArithmeticException exception) { - sendError(this, exception.getMessage()); - return; - } - } - JigsawStudioBridge.get().duplicateActiveFamily(player(), selectedTheme); - } - } - - @Director(name = "rules", aliases = "rule", description = "Manage structure-wide jigsaw rules", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawRules implements DirectorExecutor { - @Director(description = "Set maximum expansion depth and horizontal radius", sync = true, - origin = DirectorOrigin.PLAYER) - public void limits( - @Param(description = "Maximum expansion depth") int maxDepth, - @Param(description = "Maximum radius in chunks") int maxSizeChunks - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - if (context.request().compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE - && (maxDepth > 20 || maxSizeChunks > 8)) { - sendError(this, "Vanilla-portable rules require maxDepth <= 20 and maxSizeChunks <= 8."); - return; - } - runGraphMutation(player(), context, () -> { - JigsawStudioStructureEditor.updateLimits( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - maxDepth, - maxSizeChunks); - return mappedMutationResult( - context, - "", - "", - "Persisted jigsaw limits: maxDepth=" + maxDepth - + ", maxSizeChunks=" + maxSizeChunks + "."); - }); - } - - @Director(description = "Set or clear one owned pool's direct fallback", sync = true, - origin = DirectorOrigin.PLAYER) - public void fallback( - @Param(description = "Owned pool resource key") String poolKey, - @Param(description = "Owned fallback pool key, or none") String fallbackPoolKey - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - String fallback = "none".equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey; - runGraphMutation(player(), context, () -> { - JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.updateFallback( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - fallback); - if (!update.changed()) { - return mappedMutationResult(context, "", "", "Pool fallback is unchanged."); - } - return mappedMutationResult( - context, - "", - "", - "Persisted pool '" + poolKey + "' fallback as '" - + (fallback.isBlank() ? "none" : fallback) + "'."); - }); - } - } - - @Director(name = "preview", description = "Assemble a read-only jigsaw preview", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawPreview implements DirectorExecutor { - @Director(name = "goto", aliases = "teleport", description = "Teleport to the live seed-1337 preview", - sync = true, origin = DirectorOrigin.PLAYER) - public void gotoPreview() { - JigsawStudioBridge.get().goToPreview(player()); - } - - @Director(description = "Assemble a deterministic preview at your location", sync = true, - origin = DirectorOrigin.PLAYER) - public void assemble( - @Param(description = "Assembly seed", defaultValue = "1337") long seed - ) { - JigsawStudioBridge.get().previewStudio(player(), seed); - } - - } -} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java deleted file mode 100644 index 5fca87e87..000000000 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java +++ /dev/null @@ -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 . - */ - -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()))); - } -} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/JigsawStudioBridge.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/JigsawStudioBridge.java deleted file mode 100644 index 6393bc2cc..000000000 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/JigsawStudioBridge.java +++ /dev/null @@ -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 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 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); - } -} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitCaptureArea.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitCaptureArea.java new file mode 100644 index 000000000..c60cae150 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitCaptureArea.java @@ -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 . + */ + +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 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 capturedRef = new AtomicReference<>(); + AtomicReference 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 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 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); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitJigsawStudioHost.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitJigsawStudioHost.java new file mode 100644 index 000000000..5ed555630 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitJigsawStudioHost.java @@ -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 . + */ + +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 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> 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; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitPlatformStructures.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitPlatformStructures.java new file mode 100644 index 000000000..04c6e5496 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitPlatformStructures.java @@ -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 . + */ + +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 templates() { + try { + return enumerateTemplateKeys(); + } catch (Exception e) { + throw new StructureAccessException(ServerReflection.failureDetail(e), true, e); + } + } + + @Override + public Optional template(ResourceId id) { + return BukkitTemplateReader.read(Bukkit.getStructureManager().loadStructure(new NamespacedKey(id.namespace(), id.path()))); + } + + @Override + public List structures() { + return idsOf(INMS.get().getStructureKeys()); + } + + @Override + public List structureSets() { + return idsOf(INMS.get().getStructureSetKeys()); + } + + @Override + public Optional 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 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 fallback = Optional.empty(); + Optional 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 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 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 idsOf(Iterable keys) { + TreeSet 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 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 endsWithNbt = location -> { + String path = identifierPath(location); + return path != null && path.endsWith(TEMPLATE_FILE_SUFFIX); + }; + + Object resultMap = listResources.invoke(resourceManager, STRUCTURE_TEMPLATE_FOLDER, endsWithNbt); + TreeSet 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; + } + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitTemplateReader.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitTemplateReader.java new file mode 100644 index 000000000..933a006b7 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitTemplateReader.java @@ -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 . + */ + +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 read(Structure structure) { + if (structure == null || structure.getPalettes().isEmpty()) { + return Optional.empty(); + } + BlockVector size = structure.getSize(); + Palette palette = structure.getPalettes().get(0); + List 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 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 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(); + } + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/PoolElementReader.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/PoolElementReader.java new file mode 100644 index 000000000..ce4da0d09 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/PoolElementReader.java @@ -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 . + */ + +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 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 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 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 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 + ) { + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/ServerReflection.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/ServerReflection.java new file mode 100644 index 000000000..f878f0278 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/ServerReflection.java @@ -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 . + */ + +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; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java index d8768f284..10ec6d5bb 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java @@ -99,6 +99,11 @@ final class BukkitToolPlayer implements ToolPlayer { return player.getLocation().getPitch(); } + @Override + public Optional targetBlock(int maxDistance) { + return Optional.ofNullable(player.getTargetBlockExact(maxDistance)).map(BukkitToolBlocks::positionOf); + } + @Override public boolean sneaking() { return player.isSneaking(); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/CommandJigsawContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/CommandJigsawContractTest.java deleted file mode 100644 index 118b21633..000000000 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/CommandJigsawContractTest.java +++ /dev/null @@ -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/.json", createKey.description()); - assertEquals("key", openKey.name()); - assertEquals(List.of("structure", "name"), List.of(openKey.aliases())); - assertEquals("Existing key loaded from structures/.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 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); - } -} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java index 91dce669f..345866f9b 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java @@ -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); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/runtime/StudioPlayerModeContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/runtime/StudioPlayerModeContractTest.java index bbac37e26..6b2364be3 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/runtime/StudioPlayerModeContractTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/runtime/StudioPlayerModeContractTest.java @@ -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")); diff --git a/core/src/test/java/art/arcane/iris/core/structure/StructureCaptureImporterFailureTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitCaptureAreaFailureTest.java similarity index 84% rename from core/src/test/java/art/arcane/iris/core/structure/StructureCaptureImporterFailureTest.java rename to adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitCaptureAreaFailureTest.java index 01eb94ffe..b3960f0e9 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/StructureCaptureImporterFailureTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitCaptureAreaFailureTest.java @@ -6,12 +6,12 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -public class StructureCaptureImporterFailureTest { +public class BukkitCaptureAreaFailureTest { @Test public void captureFailurePreservesStructureChunkDetailAndCause() { IllegalArgumentException cause = new IllegalArgumentException("placement broke"); - IllegalStateException error = StructureCaptureImporter.captureFailure( + IllegalStateException error = BukkitCaptureArea.captureFailure( "minecraft:monument", 12, -8, "platform placement failed", cause); assertSame(cause, error.getCause()); @@ -22,7 +22,7 @@ public class StructureCaptureImporterFailureTest { @Test public void captureFailureSupportsInfrastructureFailuresWithoutACause() { - IllegalStateException error = StructureCaptureImporter.captureFailure( + IllegalStateException error = BukkitCaptureArea.captureFailure( "minecraft:stronghold", -3, 5, "region task was not accepted", null); assertNull(error.getCause()); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitJigsawStudioHostTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitJigsawStudioHostTest.java new file mode 100644 index 000000000..8b160260a --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitJigsawStudioHostTest.java @@ -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"))); + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/PoolElementReaderTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/PoolElementReaderTest.java new file mode 100644 index 000000000..fecce8bdb --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/PoolElementReaderTest.java @@ -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 . + */ + +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> 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 getString(String key) { + return "final_state".equals(key) ? Optional.of(finalState) : Optional.empty(); + } + } + + private static final class FakeListPoolElement { + private final List elements; + + private FakeListPoolElement(List elements) { + this.elements = List.copyOf(elements); + } + + public List 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; + } + } +} diff --git a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterMaxDistanceReadTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/ServerReflectionMaxDistanceReadTest.java similarity index 77% rename from core/src/test/java/art/arcane/iris/core/structure/VillageImporterMaxDistanceReadTest.java rename to adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/ServerReflectionMaxDistanceReadTest.java index 62b6d72ea..b54d2d95d 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterMaxDistanceReadTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/ServerReflectionMaxDistanceReadTest.java @@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals; * IllegalArgumentException from Field.getInt, failing the jigsaw import of every datapack * structure ("Failed to read jigsaw structure graph"). */ -public class VillageImporterMaxDistanceReadTest { +public class ServerReflectionMaxDistanceReadTest { private static final class IntShape { private final int maxDistanceFromCenter = 80; } @@ -29,16 +29,16 @@ public class VillageImporterMaxDistanceReadTest { @Test public void readsPlainIntField() throws Exception { - assertEquals(80, VillageImporter.readIntMember(new IntShape(), "maxDistanceFromCenter")); + assertEquals(80, ServerReflection.readIntMember(new IntShape(), "maxDistanceFromCenter")); } @Test public void readsLargestIntComponentFromWrapperRecord() throws Exception { - assertEquals(96, VillageImporter.readIntMember(new WrapperShape(), "maxDistanceFromCenter")); + assertEquals(96, ServerReflection.readIntMember(new WrapperShape(), "maxDistanceFromCenter")); } @Test public void readsBoxedNumberField() throws Exception { - assertEquals(64, VillageImporter.readIntMember(new BoxedShape(), "maxDistanceFromCenter")); + assertEquals(64, ServerReflection.readIntMember(new BoxedShape(), "maxDistanceFromCenter")); } } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java index 32bba30ca..7a08b6a00 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java @@ -85,7 +85,6 @@ final class ModdedCommandHelp { Entry.group("pack", ModdedHelpMessages.GROUP_PACK_PACK_VALIDATION_AND_MAINTENANCE, "pk"), Entry.group("world", ModdedHelpMessages.GROUP_WORLD_RUNTIME_IRIS_DIMENSION_CREATION_REMOVAL_AND_STATUS, "w"), Entry.group("datapack", ModdedHelpMessages.GROUP_DATAPACK_WORLD_DATAPACK_INSTALL_AND_STATUS_HELPERS, "datapacks", "dp"), - Entry.group("structure", ModdedHelpMessages.GROUP_STRUCTURE_IRIS_STRUCTURE_IMPORT_AND_CAPTURE_TOOLS, "struct", "str"), Entry.command(ToolingCommands.BRANCH, " ", ModdedHelpMessages.COMMAND_MODULE_RUN_A_MODULE_COMMAND_OR_LIST_THEM, ToolingCommands.BRANCH_ALIAS), Entry.command("goldenhash", "[radius] [threads] [capture|verify]", ModdedHelpMessages.COMMAND_GOLDENHASH_GENERATE_DETERMINISTIC_BLOCK_HASHES_FOR_PARITY_TESTING, "gold"), Entry.group("developer", ModdedHelpMessages.GROUP_DEVELOPER_DEVELOPER_DIAGNOSTICS_NETWORK_INTERFACES_REGION_FILE_SCAN, "dev") @@ -185,12 +184,6 @@ final class ModdedCommandHelp { )); SECTIONS.put("datapacks", SECTIONS.get("datapack")); SECTIONS.put("dp", SECTIONS.get("datapack")); - SECTIONS.put("structure", List.of( - Entry.command("import", "", ModdedHelpMessages.COMMAND_IMPORT_EXPLAIN_BUKKIT_STRUCTURE_IMPORT_WORKFLOW, "import-all", "reimport", "imp", "all"), - Entry.command("capture", "", ModdedHelpMessages.COMMAND_CAPTURE_EXPLAIN_BUKKIT_STRUCTURE_CAPTURE_WORKFLOW, "cap") - )); - SECTIONS.put("struct", SECTIONS.get("structure")); - SECTIONS.put("str", SECTIONS.get("structure")); SECTIONS.put("developer", List.of( Entry.command("network", "", ModdedHelpMessages.COMMAND_NETWORK_LIST_NETWORK_INTERFACES_AND_THEIR_ADDRESSES, "ip") )); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java index 6e1c3f5e5..ba0090057 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java @@ -147,9 +147,6 @@ final class ModdedCommandTree { root.then(ModdedDatapackCommands.tree("datapack")); root.then(ModdedDatapackCommands.tree("datapacks")); root.then(ModdedDatapackCommands.tree("dp")); - root.then(ModdedStructureCommands.tree("structure")); - root.then(ModdedStructureCommands.tree("struct")); - root.then(ModdedStructureCommands.tree("str")); root.then(ModdedDeveloperCommands.tree("developer")); root.then(ModdedDeveloperCommands.tree("dev")); root.then(ModdedModuleBranch.tree(ToolingCommands.BRANCH)); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStructureCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStructureCommands.java deleted file mode 100644 index d7f5a52d0..000000000 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStructureCommands.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.modded.command; - -import com.mojang.brigadier.arguments.StringArgumentType; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; - -/** - * The {@code /iris structure} literals that only explain the Bukkit-only import and capture. The structure module's own - * commands ({@code list}, {@code info}, {@code verify}) are under {@code /iris module structure}. - */ -public final class ModdedStructureCommands { - private static final String IMPORT_EXPLANATION = "Structure import rebuilds vanilla & datapack structures as editable Iris resources through Bukkit/NMS template managers; run /iris structure import on a Bukkit server against this pack, then copy the pack folder over."; - private static final String CAPTURE_EXPLANATION = "Structure capture generates each structure in a throwaway Bukkit scratch world to read its blocks; it requires the Bukkit plugin (v26 NMS binding)."; - - private ModdedStructureCommands() { - } - - public static LiteralArgumentBuilder tree(String name) { - LiteralArgumentBuilder root = Commands.literal(name).requires(ModdedCommandTree.GATE); - - root.executes((CommandContext context) -> ModdedCommandHelp.send(context.getSource(), name)); - - root.then(message("import", IMPORT_EXPLANATION)); - root.then(message("import-all", IMPORT_EXPLANATION)); - root.then(message("reimport", IMPORT_EXPLANATION)); - root.then(message("imp", IMPORT_EXPLANATION)); - root.then(message("all", IMPORT_EXPLANATION)); - root.then(message("capture", CAPTURE_EXPLANATION)); - root.then(message("cap", CAPTURE_EXPLANATION)); - - return root; - } - - private static LiteralArgumentBuilder message(String name, String text) { - return Commands.literal(name) - .executes((CommandContext context) -> { - IrisModdedCommands.fail(context.getSource(), text); - return 0; - }) - .then(Commands.argument("args", StringArgumentType.greedyString()) - .executes((CommandContext context) -> { - IrisModdedCommands.fail(context.getSource(), text); - return 0; - })); - } -} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java index 50a8fc86b..e4cea7a35 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java @@ -162,7 +162,7 @@ public class IrisModdedCommandParityTest { assertNotNull("iris", iris.getCommand()); for (String category : new String[]{"help", "find", "goto", "pregen", "pregenerate", "object", "o", "edit", "studio", "std", "s", "pack", "pk", "world", "w", "datapack", "datapacks", "dp", - "structure", "struct", "str", "developer", "dev", "module", "m"}) { + "developer", "dev", "module", "m"}) { assertNotNull(category, child(iris, category).getCommand()); } } @@ -174,9 +174,6 @@ public class IrisModdedCommandParityTest { for (CommandNode node : iris.getChildren()) { assertTrue(node.getName() + " must be a literal", node instanceof LiteralCommandNode); } - for (CommandNode node : child(iris, "structure").getChildren()) { - assertTrue("structure " + node.getName() + " must be a literal", node instanceof LiteralCommandNode); - } for (String branch : new String[]{"module", "m"}) { CommandNode module = child(iris, branch); assertNotNull(branch + " lists the mounted commands on its own", module.getCommand()); @@ -225,9 +222,13 @@ public class IrisModdedCommandParityTest { } @Test - public void structureHelpListsOnlyImportAndCapture() { - assertEquals(List.of("import", "import-all", "reimport", "imp", "all", "capture", "cap"), - ModdedCommandHelp.documentedWords("structure")); + public void structureImportAndCaptureAreModuleCommandsAndHaveNoLiteralsOfTheirOwn() { + CommandNode iris = irisNode(); + + for (String structure : new String[]{"structure", "struct", "str"}) { + assertNull(structure, iris.getChild(structure)); + } + assertFalse(ModdedCommandHelp.sections().contains("structure")); } private static CommandNode child( diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java index 5db627235..8595657c4 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java @@ -281,10 +281,9 @@ public class IrisModdedStructureCommandTest { @Test public void structureListInfoAndVerifyBelongToTheStructureModule() throws IOException { - String source = source("ModdedStructureCommands.java"); + Path staticTree = commonSourceRoot().resolve("art/arcane/iris/modded/command/ModdedStructureCommands.java"); - assertFalse(source.contains("Commands.literal(\"list\")")); - assertFalse(source.contains("verifyTree(")); + assertFalse(Files.exists(staticTree)); } private String source(String fileName) throws IOException { diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index c01cf4b83..834d1bf3f 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -47,8 +47,8 @@ types that carry them and lists what the Iris adapter still owes. | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | | Sparse geometry | `GeneratedObject` | | Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | -| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender` (with `player()`), `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`, `worlds`, `services`), host `CommandRegistration` in `FeatureCatalog.commands()` | -| Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `loaded`, `repaint`, `close`), `ToolPlayer` (`teleport`, `creative`, `message`, `actionBar`, `sound`, `sidebar`, `particles`, `give` answering whether the item fitted, `held`, `openMenu`), `ToolText` with `TextColor` (styled text: item names and lore, menu titles, sidebar, chat and action bar; the host shows each span in its colour and style, an empty sidebar title keeps the platform's, and an item read back has plain text), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `teleported` for every arrival other than walking, at the time of the teleport, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause` and `BlockChange.changed`, `containerChanged` for a closed container inventory or a furnace or brewing stand that started, `command`, `chunkLoaded`, `closeRefusal`, `closing`, `closed`), `com.volmit.geometry.ChunkPos`; a tool world takes the pack's studio slot, so the host asks `closeRefusal` before it closes the world for another studio, the studio close command or a server stop, and waits for `closing` when another studio replaces it; every Y is the world's own; implemented by each platform adapter (Bukkit; modded adapters answer with a failed `open`) | +| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`, `platformStructures`), plain-text `Sender` (with `player()`), `PlatformStructures` (`templates`, `template` answering `StructureTemplate`, `structures`, `structureSets`, `jigsaw` answering `JigsawStructureInfo`, `pool` answering `TemplatePool` with `Member`, `Element`, `ConnectorSource`, `Connectors` and `JigsawConnector`, `supportsCapture`, `openCaptureArea` answering a closable `CaptureArea` whose `capture` answers `CapturedStructure`; `TemplateBlock`; readers throw `StructureAccessException`), `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`, `worlds`, `services`), host `CommandRegistration` in `FeatureCatalog.commands()` | +| Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `loaded`, `repaint`, `close`), `ToolPlayer` (`targetBlock`, `teleport`, `creative`, `message`, `actionBar`, `sound`, `sidebar`, `particles`, `give` answering whether the item fitted, `held`, `openMenu`), `ToolText` with `TextColor` (styled text: item names and lore, menu titles, sidebar, chat and action bar; the host shows each span in its colour and style, an empty sidebar title keeps the platform's, and an item read back has plain text), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `teleported` for every arrival other than walking, at the time of the teleport, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause` and `BlockChange.changed`, `containerChanged` for a closed container inventory or a furnace or brewing stand that started, `command`, `chunkLoaded`, `closeRefusal`, `closing`, `closed`), `com.volmit.geometry.ChunkPos`; a tool world takes the pack's studio slot, so the host asks `closeRefusal` before it closes the world for another studio, the studio close command or a server stop, and waits for `closing` when another studio replaces it; every Y is the world's own; implemented by each platform adapter (Bukkit; modded adapters answer with a failed `open`) | | Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | | Typed generation and persistent storage | `mantle` package | diff --git a/api/DESIGN.md b/api/DESIGN.md index 045b803e8..fb1b3b79a 100644 --- a/api/DESIGN.md +++ b/api/DESIGN.md @@ -1434,6 +1434,12 @@ It exists so the tool lives in a module and runs on every platform: a tool that its own widgets (VolmLib windows and scoreboards on Bukkit). Their text is `ToolText`: spans of a named colour (`TextColor`) and a few styles, so no colour codes or components cross the api, and the host maps the spans onto whatever its platform draws text with. +- **The platform's structures are one capability.** Registries, resource managers and structure managers differ by + platform and version, and some are reached only by reflection. `PlatformStructures` is the one door for the tools that + import them, and answers in api types (`BlockState`, `BlockEntityData`, `ResourceId`), so an importer holds only + model-building logic. Capturing a structure needs a scratch area that has to be removed, so it is a `CaptureArea` the + tool closes, and not a call that leaves the area to the platform. A platform without the capability gives + `CommandContext.platformStructures()` empty and the tool says so. - **A platform may not have it.** `ToolWorlds.open` then returns a failed future and `Sender.player()` is empty, so a tool tells its user instead of failing at class loading. The package is exposed to pack modules, unlike the platform packages below `com.volmit.tooling`. diff --git a/api/README.md b/api/README.md index fde99046f..2c6fc1cf7 100644 --- a/api/README.md +++ b/api/README.md @@ -579,6 +579,14 @@ private void info(CommandContext context) { naming both modules. A host without commands, such as a build check, accepts the registration and ignores it. - `Sender.player()` is the sender as a `ToolPlayer` (see Tool worlds), empty for the console and on a platform without tool worlds. +- `CommandContext.platformStructures()` is the platform's structures for the tools that turn them into pack resources, + empty on a platform that has none. `PlatformStructures` lists the registered structures and structure sets and the + loadable templates (`templates`, `template`, `structures`, `structureSets`), reads a registered jigsaw structure and a + template pool (`jigsaw` answering `JigsawStructureInfo`, `pool` answering `TemplatePool` with its members, fallback and + the connectors of each element), and generates structures that have no template in a throwaway area + (`supportsCapture`, `openCaptureArea`). A template or a captured structure is a list of `TemplateBlock` with + `BlockState` and `BlockEntityData`. A reader throws `StructureAccessException` when the platform's registries cannot be + read, and says whether asking again may help. ## Tool worlds diff --git a/api/api/src/main/java/com/volmit/tooling/CapturedStructure.java b/api/api/src/main/java/com/volmit/tooling/CapturedStructure.java new file mode 100644 index 000000000..2cb3c0182 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/CapturedStructure.java @@ -0,0 +1,18 @@ +package com.volmit.tooling; + +import com.volmit.geometry.BlockPosition; +import java.util.List; +import java.util.Objects; + +/** + * A structure the platform generated in a scratch area and read back. + * + * @param size the width, height and depth of the box the structure filled + * @param blocks every block in that box that is not plain air, with positions from the box's corner + */ +public record CapturedStructure(BlockPosition size, List blocks) { + public CapturedStructure { + Objects.requireNonNull(size, "size"); + blocks = List.copyOf(blocks); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/CommandContext.java b/api/api/src/main/java/com/volmit/tooling/CommandContext.java index 47b8ca570..a79f64633 100644 --- a/api/api/src/main/java/com/volmit/tooling/CommandContext.java +++ b/api/api/src/main/java/com/volmit/tooling/CommandContext.java @@ -30,4 +30,7 @@ public interface CommandContext { /** The platform's registries; empty when the host runs without a platform. */ Optional platform(); + + /** The structures the platform registers and the templates it loads; empty on a platform that does not offer them. */ + Optional platformStructures(); } diff --git a/api/api/src/main/java/com/volmit/tooling/JigsawStructureInfo.java b/api/api/src/main/java/com/volmit/tooling/JigsawStructureInfo.java new file mode 100644 index 000000000..2f61f1c64 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/JigsawStructureInfo.java @@ -0,0 +1,23 @@ +package com.volmit.tooling; + +import com.volmit.resource.ResourceId; +import java.util.Objects; + +/** + * What a registered jigsaw structure says about itself. + * + * @param startPool the template pool the structure starts from + * @param maxDepth how many pieces deep the structure grows + * @param maxDistance how far from its centre the structure may reach, in blocks; the horizontal reach when the platform + * keeps a horizontal and a vertical one + * @param gameVersion the platform's own version string, which tools record as where the structure came from + * @param shuffleSeed what the platform seeds its shuffle of the connectors of this structure's pool elements with, so + * that reading the same structure twice lists them in the same order + */ +public record JigsawStructureInfo(ResourceId startPool, int maxDepth, int maxDistance, String gameVersion, + long shuffleSeed) { + public JigsawStructureInfo { + Objects.requireNonNull(startPool, "startPool"); + Objects.requireNonNull(gameVersion, "gameVersion"); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/PlatformStructures.java b/api/api/src/main/java/com/volmit/tooling/PlatformStructures.java new file mode 100644 index 000000000..4df13c77b --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/PlatformStructures.java @@ -0,0 +1,63 @@ +package com.volmit.tooling; + +import com.volmit.resource.ResourceId; +import java.util.List; +import java.util.Optional; + +/** + * The structures a platform registers and the templates it loads, for the tools that turn them into pack resources. + * A command reaches it as {@link CommandContext#platformStructures()}, which is empty on a platform without it. Every + * method may take a while and reads the running server, so a tool calls them from its worker thread and never + * from the platform's main or region thread. + * + *

Each reader that cannot answer because the platform's registries cannot be read throws a + * {@link StructureAccessException}; a reader that answers empty means the platform has no such thing. + */ +public interface PlatformStructures { + /** The ids of the structure templates the platform can load, such as {@code minecraft:village/plains/houses/plains_small_house_1}, in id order. */ + List templates(); + + /** The template {@code id}; empty when the platform has none or it holds no palette. */ + Optional template(ResourceId id); + + /** The ids of the structures the platform registers, in id order. */ + List structures(); + + /** The ids of the structure sets the platform registers, in id order. */ + List structureSets(); + + /** What {@code structure} says about itself; empty when it is no jigsaw structure or is not registered. */ + Optional jigsaw(ResourceId structure); + + /** The template pool {@code pool}; empty when it is not registered. */ + Optional pool(ResourceId pool); + + /** Whether the platform can generate a structure in a scratch area and read it back, which {@link #openCaptureArea} needs. */ + boolean supportsCapture(); + + /** + * Opens a throwaway area to generate structures in, for the structures that have no template. Close it when the + * captures are done; it is removed then. + * + * @param sender where the platform reports what it does while it opens and removes the area + * @return the area; empty when it could not be opened, which the platform has told the sender + */ + Optional openCaptureArea(Sender sender); + + /** A throwaway area structures are generated in, one after another. */ + interface CaptureArea extends AutoCloseable { + /** + * Generates {@code structure} in the next free spot of the area and reads it back. + * + * @param seed what the platform generates the structure with + * @param maxSpan the widest and tallest box, in blocks, the platform reads back + * @return the structure; empty when it placed nothing capturable here, such as one wider than {@code maxSpan} + * @throws IllegalStateException when the platform could not place it, with the reason + */ + Optional capture(ResourceId structure, long seed, int maxSpan); + + /** Removes the area. */ + @Override + void close(); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/StructureAccessException.java b/api/api/src/main/java/com/volmit/tooling/StructureAccessException.java new file mode 100644 index 000000000..ae4900049 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/StructureAccessException.java @@ -0,0 +1,28 @@ +package com.volmit.tooling; + +/** + * What a {@link PlatformStructures} reader throws when the platform cannot answer, such as a server version whose + * registries it cannot read. The message is written for the sender who ran the tool, so a tool shows it as it is. + */ +public final class StructureAccessException extends RuntimeException { + private final boolean retryable; + + /** + * @param message what went wrong, as the sender should read it + * @param retryable whether asking again later may succeed, as for a registry that was not ready yet + */ + public StructureAccessException(String message, boolean retryable) { + super(message); + this.retryable = retryable; + } + + public StructureAccessException(String message, boolean retryable, Throwable cause) { + super(message, cause); + this.retryable = retryable; + } + + /** Whether asking again later may succeed. */ + public boolean retryable() { + return retryable; + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/StructureTemplate.java b/api/api/src/main/java/com/volmit/tooling/StructureTemplate.java new file mode 100644 index 000000000..18c9251ec --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/StructureTemplate.java @@ -0,0 +1,20 @@ +package com.volmit.tooling; + +import com.volmit.geometry.BlockPosition; +import java.util.List; +import java.util.Objects; + +/** + * A structure template the platform loads, such as a vanilla {@code .nbt}: its size and the blocks of its first palette. + * + * @param size the template's width, height and depth in blocks + * @param paletteCount how many palettes the template has; only the first is in {@code blocks} + * @param entityCount how many entities the template holds, which tools do not read + * @param blocks the blocks of the first palette, with positions from the template's corner + */ +public record StructureTemplate(BlockPosition size, int paletteCount, int entityCount, List blocks) { + public StructureTemplate { + Objects.requireNonNull(size, "size"); + blocks = List.copyOf(blocks); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/TemplateBlock.java b/api/api/src/main/java/com/volmit/tooling/TemplateBlock.java new file mode 100644 index 000000000..c002c45eb --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/TemplateBlock.java @@ -0,0 +1,33 @@ +package com.volmit.tooling; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import java.util.Objects; +import java.util.Optional; + +/** + * One block of a {@link StructureTemplate} or {@link CapturedStructure}. + * + * @param position where the block is, from the template's corner + * @param state the block as the platform stores it; a jigsaw block is the jigsaw block itself + * @param blockEntity the block entity data of a block that has some; empty for a jigsaw block, which tools resolve + * through {@code jigsawFinalState} + * @param jigsawFinalState what a jigsaw block turns into when its piece is placed: the {@code final_state} the block + * names, as the platform writes it; empty for any other block and for a jigsaw block that names + * none + */ +public record TemplateBlock(BlockPosition position, BlockState state, Optional blockEntity, + Optional jigsawFinalState) { + public TemplateBlock { + Objects.requireNonNull(position, "position"); + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(blockEntity, "blockEntity"); + Objects.requireNonNull(jigsawFinalState, "jigsawFinalState"); + } + + /** A block with no jigsaw final state. */ + public static TemplateBlock of(BlockPosition position, BlockState state, Optional blockEntity) { + return new TemplateBlock(position, state, blockEntity, Optional.empty()); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/TemplatePool.java b/api/api/src/main/java/com/volmit/tooling/TemplatePool.java new file mode 100644 index 000000000..81d3b5597 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/TemplatePool.java @@ -0,0 +1,154 @@ +package com.volmit.tooling; + +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.LongSupplier; + +/** + * A jigsaw template pool the platform registers: what its entries are and where it falls back to. + * + * @param members the entries in the order the platform lists them, every one of them, so the count is the + * pool's own size + * @param fallback the pool used when none of the entries fits; empty when it has none + * @param fallbackFailure why the fallback could not be read, when it could not; the fallback is then empty + */ +public record TemplatePool(List members, Optional fallback, Optional fallbackFailure) { + public TemplatePool { + members = List.copyOf(members); + Objects.requireNonNull(fallback, "fallback"); + Objects.requireNonNull(fallbackFailure, "fallbackFailure"); + } + + /** One entry of a pool. */ + public sealed interface Member permits Absent, Unreadable, Element { + } + + /** An entry that holds no element. */ + public record Absent() implements Member { + } + + /** Which part of an entry could not be read. */ + public enum Part { + /** The element and its weight. */ + ENTRY, + /** Where the element's template is. */ + TEMPLATE_LOCATION + } + + /** + * An entry the platform could not read. + * + * @param part what could not be read + * @param detail why, as the platform reports it + */ + public record Unreadable(Part part, String detail) implements Member { + public Unreadable { + Objects.requireNonNull(part, "part"); + Objects.requireNonNull(detail, "detail"); + } + } + + /** + * One element of a pool with its weight. + * + * @param weight how likely the element is among the entries; at least 1 + * @param type the platform's name for the kind of element, such as {@code SinglePoolElement}, which tells an + * empty element from one a tool cannot convert when {@code template} is empty + * @param template the template the element places; when the platform wraps several elements in a list, the + * first one that places a template; empty for an element that places none + * @param listLevels how many list elements wrap the one {@code template} came from + * @param omittedElements how many elements those lists held besides the one {@code template} came from + * @param connectors reads the jigsaw connectors of the element + */ + public record Element(int weight, String type, Optional template, int listLevels, int omittedElements, + ConnectorSource connectors) implements Member { + public Element { + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(template, "template"); + Objects.requireNonNull(connectors, "connectors"); + } + } + + /** Reads the jigsaw connectors of one pool element. */ + @FunctionalInterface + public interface ConnectorSource { + /** + * The connectors of the element, in the order the platform shuffles them with a seed. + * + * @param shuffleSeeds gives the seed to shuffle with; the platform asks only when it shuffles, so the caller's + * random sequence advances once for each element that has connectors to shuffle + * @throws StructureAccessException when the platform cannot read the connectors at all + */ + Connectors read(LongSupplier shuffleSeeds); + } + + /** Whether the platform could list an element's connectors. */ + public enum Availability { + READ, + /** The platform's version has no way to list them. */ + UNAVAILABLE, + /** The platform answered with no list. */ + NO_COLLECTION + } + + /** + * The connectors of an element. + * + * @param availability whether {@code connectors} were listed + * @param connectors one entry for each jigsaw block, in the platform's shuffled order + */ + public record Connectors(Availability availability, List connectors) { + public Connectors { + Objects.requireNonNull(availability, "availability"); + connectors = List.copyOf(connectors); + } + } + + /** One jigsaw block of an element. */ + public sealed interface Connector permits JigsawConnector, UnreadableConnector { + } + + /** + * A jigsaw block the platform could not convert. + * + * @param detail why, as the platform reports it + */ + public record UnreadableConnector(String detail) implements Connector { + public UnreadableConnector { + Objects.requireNonNull(detail, "detail"); + } + } + + /** + * A jigsaw block. + * + * @param position where it is, from the element's corner + * @param front the side it connects through + * @param top the side its top faces, which fixes the roll of a rollable joint + * @param pool the pool it pulls its next piece from; empty when it names none + * @param name the name other blocks target + * @param target the name of the blocks it connects to + * @param aligned whether the joint keeps the pieces aligned rather than letting them roll + * @param finalState the block it turns into once it connects, as the platform writes block states; empty when + * the block names none + * @param selectionPriority which block is tried first + * @param placementPriority which connected piece is expanded first + */ + public record JigsawConnector(BlockPosition position, BlockFace front, BlockFace top, Optional pool, + String name, String target, boolean aligned, Optional finalState, + int selectionPriority, int placementPriority) implements Connector { + public JigsawConnector { + Objects.requireNonNull(position, "position"); + Objects.requireNonNull(front, "front"); + Objects.requireNonNull(top, "top"); + Objects.requireNonNull(pool, "pool"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(finalState, "finalState"); + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java b/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java index 9ffae6411..6e63f8f28 100644 --- a/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java @@ -38,6 +38,12 @@ public interface ToolPlayer { boolean sneaking(); + /** + * The block the player looks at within {@code maxDistance} blocks, fluids not counting; empty when they look at none. + * Like the other readers, valid only on the thread that owns the player. + */ + Optional targetBlock(int maxDistance); + /** Runs {@code task} on the thread that owns the player: at once when the caller is that thread, else later. */ void run(Runnable task); diff --git a/api/api/src/test/java/com/volmit/tooling/PlatformStructuresTest.java b/api/api/src/test/java/com/volmit/tooling/PlatformStructuresTest.java new file mode 100644 index 000000000..e1ee5b737 --- /dev/null +++ b/api/api/src/test/java/com/volmit/tooling/PlatformStructuresTest.java @@ -0,0 +1,48 @@ +package com.volmit.tooling; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PlatformStructuresTest { + @Test + void aTemplateKeepsItsOwnCopyOfItsBlocks() { + var blocks = new ArrayList<>(List.of(TemplateBlock.of( + new BlockPosition(0, 0, 0), BlockState.parse("minecraft:stone"), Optional.empty()))); + var template = new StructureTemplate(new BlockPosition(1, 1, 1), 1, 0, blocks); + + blocks.clear(); + + assertEquals(1, template.blocks().size()); + assertThrows(UnsupportedOperationException.class, () -> template.blocks().clear()); + } + + @Test + void aPoolListsEveryMemberWhetherTheToolCanReadItOrNot() { + var unreadable = new TemplatePool.Unreadable(TemplatePool.Part.ENTRY, "no weight"); + var element = new TemplatePool.Element(3, "SinglePoolElement", + Optional.of(ResourceId.parse("minecraft:village/house")), 0, 0, + seeds -> new TemplatePool.Connectors(TemplatePool.Availability.READ, List.of( + new TemplatePool.JigsawConnector(new BlockPosition(1, 2, 3), BlockFace.NORTH, BlockFace.UP, + Optional.empty(), "minecraft:door", "minecraft:door", false, Optional.empty(), 0, 0)))); + var pool = new TemplatePool(List.of(new TemplatePool.Absent(), unreadable, element), Optional.empty(), Optional.empty()); + + assertEquals(3, pool.members().size()); + assertEquals(1, element.connectors().read(() -> 7L).connectors().size()); + } + + @Test + void anAccessFailureSaysWhetherAskingAgainMayHelp() { + assertTrue(new StructureAccessException("registry not ready", true).retryable()); + assertEquals("no such member", new StructureAccessException("no such member", false).getMessage()); + } +} diff --git a/build.gradle b/build.gradle index 1496165ea..13e3dc9a2 100644 --- a/build.gradle +++ b/build.gradle @@ -116,6 +116,8 @@ nmsBindings.each { key, value -> compileOnly(rootProject.libs.byteBuddy.core) testImplementation('junit:junit:4.13.2') testImplementation(project(':core')) + // The runtime contract of the host's reflection over template pools runs against this binding's own classes. + testImplementation(project(':adapters:bukkit:plugin')) testCompileOnly(volmLibCoordinate) { transitive = false } diff --git a/core/purity-allowlist.txt b/core/purity-allowlist.txt index 038a8142f..9c4aca589 100644 --- a/core/purity-allowlist.txt +++ b/core/purity-allowlist.txt @@ -67,11 +67,7 @@ art/arcane/iris/core/service/ObjectStudioSaveService.java art/arcane/iris/core/service/PackDownloadProgressReporter.java art/arcane/iris/core/service/StudioSVC.java art/arcane/iris/core/service/TreeSVC.java -art/arcane/iris/core/structure/BulkStructureImporter.java art/arcane/iris/core/structure/FeatureImporter.java -art/arcane/iris/core/structure/StructureCaptureImporter.java -art/arcane/iris/core/structure/StructureImporter.java -art/arcane/iris/core/structure/VillageImporter.java art/arcane/iris/core/tools/IrisConverter.java art/arcane/iris/core/tools/IrisCreator.java art/arcane/iris/core/tools/IrisPackBenchmarking.java diff --git a/core/src/main/java/art/arcane/iris/core/datapack/DatapackIngestService.java b/core/src/main/java/art/arcane/iris/core/datapack/DatapackIngestService.java index bb5ce44f8..4a9b2f822 100644 --- a/core/src/main/java/art/arcane/iris/core/datapack/DatapackIngestService.java +++ b/core/src/main/java/art/arcane/iris/core/datapack/DatapackIngestService.java @@ -20,6 +20,7 @@ package art.arcane.iris.core.datapack; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.IrisServices; import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.core.IrisStartupValidation; import art.arcane.iris.core.IrisSettings; @@ -29,7 +30,11 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.nms.MinecraftVersion; import art.arcane.iris.core.project.IrisProject; import art.arcane.iris.core.project.IrisCodeWorkspace; +import art.arcane.iris.core.modules.IrisModuleHost; import art.arcane.iris.core.structure.BulkStructureImporter; +import art.arcane.iris.core.tooling.IrisToolPack; +import art.arcane.iris.core.tooling.VolmitToolSender; +import com.volmit.tooling.PlatformStructures; import art.arcane.iris.core.structure.StructureImporter; import art.arcane.iris.core.structure.authoring.StructureKey; import art.arcane.iris.core.structure.authoring.StructureSource; @@ -3178,9 +3183,10 @@ public final class DatapackIngestService { attemptedPacks++; try { BulkStructureImporter.Report report = BulkStructureImporter.importManagedDatapackStructures( - data, + new IrisToolPack(data, IrisModuleHost.hostLog()), + IrisServices.get(PlatformStructures.class), StructureImporter.Mode.OVERWRITE, - BukkitPlatform.console(), + new VolmitToolSender(BukkitPlatform.console()), structureKeys, templateKeys ); diff --git a/core/src/main/java/art/arcane/iris/core/modules/StructureCommands.java b/core/src/main/java/art/arcane/iris/core/modules/StructureCommands.java index 9bc980943..ac06d73fc 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/StructureCommands.java +++ b/core/src/main/java/art/arcane/iris/core/modules/StructureCommands.java @@ -19,6 +19,7 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.structure.StructureIndexService; +import art.arcane.iris.core.structure.tooling.PlatformStructuresAccess; import art.arcane.iris.core.tooling.IrisToolPack; import art.arcane.iris.engine.framework.PlacedStructurePiece; import art.arcane.iris.engine.framework.structure.StructureAssemblyResult; @@ -30,10 +31,12 @@ import com.volmit.resource.ResourceId; import com.volmit.tooling.Argument; import com.volmit.tooling.Command; import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; import java.io.File; import java.io.IOException; import java.util.List; +import java.util.Optional; /** The {@code /iris module structure} commands of {@link StructureModelModule}: the index, one structure's graph, and the verification of a world's structures. */ final class StructureCommands { @@ -64,7 +67,11 @@ final class StructureCommands { } private static void list(CommandContext context) throws IOException { - File index = context.pack().edit(packRoot -> StructureIndexService.write(IrisToolPack.dataOf(context.pack()))); + Optional platform = PlatformStructuresAccess.require(context); + if (platform.isEmpty()) { + return; + } + File index = StructureIndexService.write(context.pack(), platform.get()); context.sender().success("Wrote the structure index: " + index.getPath()); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/StructureModelModule.java b/core/src/main/java/art/arcane/iris/core/modules/StructureModelModule.java index 2ea29608b..d6b66535e 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/StructureModelModule.java +++ b/core/src/main/java/art/arcane/iris/core/modules/StructureModelModule.java @@ -18,16 +18,21 @@ package art.arcane.iris.core.modules; +import art.arcane.iris.core.structure.tooling.JigsawCommands; +import art.arcane.iris.core.structure.tooling.JigsawStudioHost; import art.arcane.iris.engine.framework.structure.StructureLocating; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.framework.structure.StructureValidator; import art.arcane.iris.engine.framework.structure.StructureVanillaStructures; +import art.arcane.iris.spi.IrisServices; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; import com.volmit.service.StructureLocator; import com.volmit.service.VanillaStructures; +import java.util.Optional; + /** * Module {@code iris:structure-model}: the parts of Iris's jigsaw structures that still need Iris itself. The structures, * jigsaw pools and jigsaw pieces are resource kinds of {@code iris:structure} ({@link StructureResources}). @@ -41,7 +46,8 @@ import com.volmit.service.VanillaStructures; * them up, and the pack's structure placements replace them, place them alongside, start them where their * {@code nativeStructures} grids say and fit them into the terrain. *

- * It mounts {@code /iris module structure list|info|verify} ({@link StructureCommands}) through the tooling api. + * It mounts {@code /iris module structure list|info|verify} ({@link StructureCommands}) and the Jigsaw Studio tree + * {@code /iris module jigsaw ...} ({@link JigsawCommands}) through the tooling api. */ public final class StructureModelModule implements IrisModule { private static final String VERSION = "built-in"; @@ -58,5 +64,6 @@ public final class StructureModelModule implements IrisModule { registry.registerService(StructureLocator.class, new StructureLocating()); registry.registerService(VanillaStructures.class, new StructureVanillaStructures()); setup.tooling().registerCommand(StructureCommands.root()); + setup.tooling().registerCommand(JigsawCommands.root(() -> Optional.ofNullable(IrisServices.getOrNull(JigsawStudioHost.class)))); } } diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java b/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java index 63344516f..8f163b661 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java +++ b/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java @@ -19,9 +19,10 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; @@ -1261,12 +1262,15 @@ public final class JigsawStudioGraphEditor { sourceObject.getH(), sourceObject.getD()); JigsawStudioCellDimensions canonicalDimensions = canonicalDimensions(sourceDimensions, quarterTurns); - Map canonicalBlocks = canonicalBlocks( + IrisObject.ApiContents sourceContents = sourceObject.apiContents(); + Map canonicalBlocks = canonicalBlocks( sourceObject, + sourceContents, quarterTurns, targetPieceKey); - Map canonicalTiles = canonicalTiles( + Map canonicalTiles = canonicalTiles( sourceObject, + sourceContents, quarterTurns, targetPieceKey); List connectors = targetPiece.getConnectors(); @@ -1285,6 +1289,7 @@ public final class JigsawStudioGraphEditor { JigsawStudioCellDimensions resizedSourceDimensions = sourceDimensions(targetDimensions, quarterTurns); IrisObject resizedObject = rebuildSourceObject( + sourceContents, canonicalBlocks, canonicalTiles, resizedSourceDimensions, @@ -1304,20 +1309,18 @@ public final class JigsawStudioGraphEditor { return new PlanarPieceObjectResize(resizedObject, relocatedConnectors); } - private static Map canonicalBlocks( + private static Map canonicalBlocks( IrisObject source, + IrisObject.ApiContents contents, int quarterTurns, String pieceKey ) throws IOException { - Map blocks = new LinkedHashMap<>(); - for (Map.Entry entry : source.getBlocks()) { - LocalPosition sourcePosition = unsignedPosition(entry.getKey(), source); + Map blocks = new LinkedHashMap<>(); + for (Map.Entry entry : contents.blocks().entrySet()) { + LocalPosition sourcePosition = LocalPosition.from(entry.getKey()); requireInside(sourcePosition, source.getW(), source.getH(), source.getD(), "stored block", pieceKey); - PlatformBlockState state = entry.getValue(); - if (state == null) { - throw new IOException("Planar piece '" + pieceKey + "' contains a null stored block state"); - } + BlockState state = entry.getValue(); LocalPosition canonicalPosition = toCanonical( sourcePosition, source.getW(), @@ -1331,26 +1334,24 @@ public final class JigsawStudioGraphEditor { return blocks; } - private static Map canonicalTiles( + private static Map canonicalTiles( IrisObject source, + IrisObject.ApiContents contents, int quarterTurns, String pieceKey ) throws IOException { - Map tiles = new LinkedHashMap<>(); - for (Map.Entry entry : source.getStates()) { - LocalPosition sourcePosition = unsignedPosition(entry.getKey(), source); + Map tiles = new LinkedHashMap<>(); + for (Map.Entry entry : contents.blockEntities().entrySet()) { + LocalPosition sourcePosition = LocalPosition.from(entry.getKey()); requireInside(sourcePosition, source.getW(), source.getH(), source.getD(), "tile data", pieceKey); - TileData tile = entry.getValue(); - if (tile == null) { - throw new IOException("Planar piece '" + pieceKey + "' contains null tile data"); - } + BlockEntityData tile = entry.getValue(); LocalPosition canonicalPosition = toCanonical( sourcePosition, source.getW(), source.getD(), quarterTurns); - if (tiles.putIfAbsent(canonicalPosition, tile.clone()) != null) { + if (tiles.putIfAbsent(canonicalPosition, tile) != null) { throw new IOException("Planar piece '" + pieceKey + "' maps more than one tile payload to " + canonicalPosition.describe()); } @@ -1425,8 +1426,8 @@ public final class JigsawStudioGraphEditor { } private static void relocateConnectorPayloads( - Map blocks, - Map tiles, + Map blocks, + Map tiles, List connectorResizes, String pieceKey ) throws IOException { @@ -1460,7 +1461,7 @@ public final class JigsawStudioGraphEditor { continue; } boolean present = blocks.containsKey(connectorResize.sourceCanonical()); - PlatformBlockState state = blocks.remove(connectorResize.sourceCanonical()); + BlockState state = blocks.remove(connectorResize.sourceCanonical()); payloads.add(new BlockRelocation(connectorResize.targetCanonical(), state, present)); } for (BlockRelocation payload : payloads) { @@ -1475,8 +1476,8 @@ public final class JigsawStudioGraphEditor { } private static void requireContentInsideTarget( - Map blocks, - Map tiles, + Map blocks, + Map tiles, JigsawStudioCellDimensions dimensions, String pieceKey ) throws IOException { @@ -1495,50 +1496,34 @@ public final class JigsawStudioGraphEditor { } private static IrisObject rebuildSourceObject( - Map canonicalBlocks, - Map canonicalTiles, + IrisObject.ApiContents sourceContents, + Map canonicalBlocks, + Map canonicalTiles, JigsawStudioCellDimensions sourceDimensions, int quarterTurns, String pieceKey ) throws IOException { - IrisObject resized = new IrisObject( - sourceDimensions.width(), - sourceDimensions.height(), - sourceDimensions.depth()); - Set sourcePositions = new LinkedHashSet<>(); - for (Map.Entry entry : canonicalBlocks.entrySet()) { + Map blocks = new LinkedHashMap<>(); + for (Map.Entry entry : canonicalBlocks.entrySet()) { LocalPosition sourcePosition = toSource(entry.getKey(), sourceDimensions, quarterTurns); - if (!sourcePositions.add(sourcePosition)) { + if (blocks.put(sourcePosition.toBlockPosition(), entry.getValue()) != null) { throw new IOException("Planar piece '" + pieceKey + "' maps multiple stored blocks to " + sourcePosition.describe()); } - resized.setUnsigned( - sourcePosition.x(), - sourcePosition.y(), - sourcePosition.z(), - entry.getValue()); } - sourcePositions.clear(); - for (Map.Entry entry : canonicalTiles.entrySet()) { + Map blockEntities = new LinkedHashMap<>(); + for (Map.Entry entry : canonicalTiles.entrySet()) { LocalPosition sourcePosition = toSource(entry.getKey(), sourceDimensions, quarterTurns); - if (!sourcePositions.add(sourcePosition)) { + if (blockEntities.put(sourcePosition.toBlockPosition(), entry.getValue()) != null) { throw new IOException("Planar piece '" + pieceKey + "' maps multiple tile payloads to " + sourcePosition.describe()); } - resized.setUnsignedTile( - sourcePosition.x(), - sourcePosition.y(), - sourcePosition.z(), - entry.getValue().clone()); } - return resized; - } - - private static LocalPosition unsignedPosition(IrisBlockVector signed, IrisObject object) { - return new LocalPosition( - signed.getBlockX() + object.getCenter().getBlockX(), - signed.getBlockY() + object.getCenter().getBlockY(), - signed.getBlockZ() + object.getCenter().getBlockZ()); + return IrisObject.fromApiContents( + sourceDimensions.width(), + sourceDimensions.height(), + sourceDimensions.depth(), + sourceContents.with(blocks, blockEntities)); } private static JigsawStudioCellDimensions canonicalDimensions( @@ -1650,35 +1635,23 @@ public final class JigsawStudioGraphEditor { dimensions, "Jigsaw Studio target object dimensions"); String normalizedPiece = pieceKey == null || pieceKey.isBlank() ? "unknown" : pieceKey; - IrisObject resized = new IrisObject(target.width(), target.height(), target.depth()); - for (Map.Entry entry : object.getBlocks()) { - IrisBlockVector position = entry.getKey(); - LocalPosition unsigned = unsignedPosition(position, object); + IrisObject.ApiContents contents = object.apiContents(); + for (BlockPosition position : contents.blocks().keySet()) { + LocalPosition unsigned = LocalPosition.from(position); if (!inside(unsigned, target)) { throw new IOException("Spatial piece '" + normalizedPiece + "' has a stored block, including explicit air, at " + unsigned.describe() + " that would be cropped by the requested variant size"); } - resized.setUnsigned( - unsigned.x(), - unsigned.y(), - unsigned.z(), - entry.getValue()); } - for (Map.Entry entry : object.getStates()) { - IrisBlockVector position = entry.getKey(); - LocalPosition unsigned = unsignedPosition(position, object); + for (BlockPosition position : contents.blockEntities().keySet()) { + LocalPosition unsigned = LocalPosition.from(position); if (!inside(unsigned, target)) { throw new IOException("Spatial piece '" + normalizedPiece + "' has tile data at " + unsigned.describe() + " that would be cropped by the requested variant size"); } - resized.setUnsignedTile( - unsigned.x(), - unsigned.y(), - unsigned.z(), - entry.getValue().clone()); } - return resized; + return IrisObject.fromApiContents(target.width(), target.height(), target.depth(), contents); } private static void requireConnectorsInside( @@ -1848,7 +1821,7 @@ public final class JigsawStudioGraphEditor { } } - private record BlockRelocation(LocalPosition target, PlatformBlockState state, boolean present) { + private record BlockRelocation(LocalPosition target, BlockState state, boolean present) { private BlockRelocation { Objects.requireNonNull(target, "Planar Jigsaw Studio connector block target"); if (present) { @@ -1862,6 +1835,14 @@ public final class JigsawStudioGraphEditor { return new LocalPosition(position.getX(), position.getY(), position.getZ()); } + private static LocalPosition from(BlockPosition position) { + return new LocalPosition(position.x(), position.y(), position.z()); + } + + private BlockPosition toBlockPosition() { + return new BlockPosition(x, y, z); + } + private IrisPosition toIrisPosition() { return new IrisPosition(x, y, z); } diff --git a/core/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java b/core/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java index 53a1854d2..f40d3f904 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java +++ b/core/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java @@ -18,15 +18,15 @@ package art.arcane.iris.core.structure; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.nms.INMS; -import art.arcane.iris.util.common.format.C; -import art.arcane.iris.util.common.plugin.VolmitSender; -import art.arcane.volmlib.util.collection.KList; -import org.bukkit.Bukkit; -import org.bukkit.NamespacedKey; +import art.arcane.iris.core.structure.tooling.SenderText; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; -import java.lang.reflect.Method; +import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -35,12 +35,10 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; -import java.util.function.Predicate; -import art.arcane.iris.core.localization.BukkitRuntimeMessages; -import art.arcane.iris.core.localization.IrisLanguage; -import art.arcane.volmlib.util.localization.MessageArgument; public final class BulkStructureImporter { + private static final int TEMPLATE_PROGRESS_INTERVAL = 50; + public record Report( int total, int imported, @@ -72,14 +70,9 @@ public final class BulkStructureImporter { private BulkStructureImporter() { } - public static Report importAllVanilla(IrisData data, StructureImporter.Mode mode, boolean includeNonJigsaw, VolmitSender sender) { - KList keys = INMS.get().getStructureKeys(); - List vanilla = new ArrayList<>(); - for (String k : keys) { - if (k != null && !k.isBlank()) { - vanilla.add(k); - } - } + public static Report importAllVanilla(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + boolean includeNonJigsaw, Sender sender) { + List vanilla = new ArrayList<>(platform.structures()); Collections.sort(vanilla); int total = vanilla.size(); @@ -88,22 +81,20 @@ public final class BulkStructureImporter { int failed = 0; TreeSet captureCandidates = new TreeSet<>(); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTING_VANILLA_DATAPACK_STRUCTURES_MODE_INCLUDENONJIGSAW, MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("mode", String.valueOf(mode)), MessageArgument.untrusted("includeNonJigsaw", String.valueOf(includeNonJigsaw)))); + SenderText.send(sender, ToolText.builder() + .green("Importing ").white(String.valueOf(total)) + .green(" vanilla & datapack structures (mode=" + mode + ", includeNonJigsaw=" + includeNonJigsaw + ")...") + .build()); - for (String keyString : vanilla) { - NamespacedKey nk = NamespacedKey.fromString(keyString.toLowerCase()); - if (nk == null) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); - continue; - } + for (ResourceId nk : vanilla) { + String keyString = nk.toString(); String name = StructureImporter.deriveName(nk); try { - VillageImporter.Result jigsaw = VillageImporter.importVillage(data, nk, name, mode); + VillageImporter.Result jigsaw = VillageImporter.importVillage(pack, platform, nk, name, mode); if (jigsaw.success()) { imported++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_JIGSAW, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("name", String.valueOf(name)))); + SenderText.send(sender, TextColor.GRAY, "[jigsaw] " + keyString + " -> " + name); continue; } @@ -113,19 +104,20 @@ public final class BulkStructureImporter { skipped++; continue; } - StructureImporter.Result single = StructureImporter.importStructure(data, nk, name, mode); + StructureImporter.Result single = StructureImporter.importStructure(pack, platform, nk, name, mode); if (single.success()) { imported++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SINGLE, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("name", String.valueOf(name)))); + SenderText.send(sender, TextColor.GRAY, "[single] " + keyString + " -> " + name); } else if (single.message() != null && single.message().startsWith("Skipped")) { skipped++; } else if (isCaptureCandidate(message, single.message())) { skipped++; - captureCandidates.add(nk.toString()); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SKIP_NO_SINGLE_TEMPLATE_NBT_VANILLA_BUILDS_THIS_CODE_FROM_SEPARATE_PIECE, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); + captureCandidates.add(keyString); + SenderText.send(sender, TextColor.YELLOW, "[skip] " + keyString + + ": no single-template NBT - vanilla builds this in code or from separate piece templates (imported via the templates pass); nothing to import as one structure."); } else { failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(single.message())))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + single.message()); } continue; } @@ -136,20 +128,21 @@ public final class BulkStructureImporter { } failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(message)))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + message); } catch (Throwable e) { failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_3, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage()); } } - StructureIndexService.write(data); + refreshIndex(pack, platform); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_BULK_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED_TOTAL, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)), MessageArgument.untrusted("total", String.valueOf(total)))); + SenderText.send(sender, completion("Bulk import complete: ", imported, skipped, failed, total)); return new Report(total, imported, skipped, failed, Map.of(), false, captureCandidates); } - public static Report importTemplateGroups(IrisData data, StructureImporter.Mode mode, VolmitSender sender) { + public static Report importTemplateGroups(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender) { String[][] groups = { {"shipwreck", "minecraft:shipwreck", "shipwreck"}, {"ruined_portal", "minecraft:ruined_portal", "ruined_portal"}, @@ -161,45 +154,45 @@ public final class BulkStructureImporter { int skipped = 0; int failed = 0; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_BUILDING_SINGLE_TEMPLATE_STRUCTURES_FROM_IMPORTED_PIECES_ONE_VARIANT_PLACED_PER_GENERATION)); + SenderText.send(sender, TextColor.GREEN, + "Building single-template structures from imported pieces (one variant placed per generation)..."); for (String[] g : groups) { try { - StructureImporter.Result result = StructureImporter.importTemplateGroup(data, g[0], g[1], g[2], mode); + StructureImporter.Result result = StructureImporter.importTemplateGroup(pack, g[0], g[1], g[2], mode); if (result.success()) { imported++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_GROUP_VARIANTS, MessageArgument.untrusted("value", String.valueOf(g[1])), MessageArgument.untrusted("value2", String.valueOf(g[0])), MessageArgument.untrusted("blocks", String.valueOf(result.blocks())))); + SenderText.send(sender, TextColor.GRAY, "[group] " + g[1] + " -> " + g[0] + " (" + result.blocks() + " variants)"); } else if (result.message() != null && result.message().startsWith("Skipped")) { skipped++; } else { skipped++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SKIP, MessageArgument.untrusted("value", String.valueOf(g[0])), MessageArgument.untrusted("message", String.valueOf(result.message())))); + SenderText.send(sender, TextColor.YELLOW, "[skip] " + g[0] + ": " + result.message()); } } catch (Throwable e) { failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_4, MessageArgument.untrusted("value", String.valueOf(g[0])), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); + SenderText.send(sender, TextColor.RED, "[fail] " + g[0] + ": " + e.getMessage()); } } - StructureIndexService.write(data); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SINGLE_TEMPLATE_STRUCTURES_BUILT_SKIPPED_FAILED, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)))); + refreshIndex(pack, platform); + SenderText.send(sender, ToolText.builder() + .green("Single-template structures: ").white(String.valueOf(imported)) + .green(" built, ").white(String.valueOf(skipped)) + .green(" skipped, ").white(String.valueOf(failed)) + .green(" failed.").build()); return new Report(groups.length, imported, skipped, failed); } - public static Report importAllTemplates(IrisData data, StructureImporter.Mode mode, VolmitSender sender) { - List templateKeys; + public static Report importAllTemplates(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender) { + List all; try { - templateKeys = enumerateTemplateKeys(); + all = new ArrayList<>(platform.templates()); } catch (Throwable e) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAILED_ENUMERATE_STRUCTURE_TEMPLATES_VIA_SERVER_RESOURCEMANAGER, MessageArgument.untrusted("e", String.valueOf(e)))); + SenderText.send(sender, TextColor.RED, + "Failed to enumerate structure templates via the server ResourceManager: " + e.getMessage()); return enumerationFailureReport(); } - - List all = new ArrayList<>(); - for (String key : templateKeys) { - if (key != null && !key.isBlank()) { - all.add(key); - } - } Collections.sort(all); int total = all.size(); @@ -208,51 +201,51 @@ public final class BulkStructureImporter { int failed = 0; if (total == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_NO_STRUCTURE_TEMPLATES_WERE_FOUND_UNDER_STRUCTURE_RESOURCE_PATH)); + SenderText.send(sender, TextColor.YELLOW, "No structure templates were found under the 'structure' resource path."); return new Report(0, 0, 0, 0); } - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTING_STRUCTURE_TEMPLATES_MODE, MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("mode", String.valueOf(mode)))); + SenderText.send(sender, ToolText.builder() + .green("Importing ").white(String.valueOf(total)) + .green(" structure templates (mode=" + mode + ")...").build()); - for (String keyString : all) { - NamespacedKey nk = NamespacedKey.fromString(keyString.toLowerCase()); - if (nk == null) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); - continue; - } + for (ResourceId nk : all) { + String keyString = nk.toString(); String name = templateNameFor(keyString); try { - StructureImporter.Result result = StructureImporter.importStructure(data, nk, name, mode, true); + StructureImporter.Result result = StructureImporter.importStructure(pack, platform, nk, name, mode, true); if (result.success()) { imported++; } else if (result.message() != null && result.message().startsWith("Skipped")) { skipped++; } else { failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_5, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(result.message())))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + result.message()); } } catch (Throwable e) { failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_6, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage()); } int processed = imported + skipped + failed; - if (processed % 50 == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTED_SKIPPED_FAILED, MessageArgument.untrusted("processed", String.valueOf(processed)), MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)))); + if (processed % TEMPLATE_PROGRESS_INTERVAL == 0) { + SenderText.send(sender, TextColor.GRAY, "..." + processed + "/" + total + " (" + imported + + " imported, " + skipped + " skipped, " + failed + " failed)"); } } - StructureIndexService.write(data); + refreshIndex(pack, platform); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_TEMPLATE_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED_TOTAL, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)), MessageArgument.untrusted("total", String.valueOf(total)))); + SenderText.send(sender, completion("Template import complete: ", imported, skipped, failed, total)); return new Report(total, imported, skipped, failed); } - public static Report importDatapackStructures(IrisData data, StructureImporter.Mode mode, VolmitSender sender) { + public static Report importDatapackStructures(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender) { return importDatapackStructures( - data, + pack, + platform, mode, sender, null, @@ -262,14 +255,16 @@ public final class BulkStructureImporter { } public static Report importManagedDatapackStructures( - IrisData data, + ToolPack pack, + PlatformStructures platform, StructureImporter.Mode mode, - VolmitSender sender, + Sender sender, Set allowedStructureKeys, Set allowedTemplateKeys ) { return importDatapackStructures( - data, + pack, + platform, mode, sender, allowedStructureKeys, @@ -279,15 +274,15 @@ public final class BulkStructureImporter { } private static Report importDatapackStructures( - IrisData data, + ToolPack pack, + PlatformStructures platform, StructureImporter.Mode mode, - VolmitSender sender, + Sender sender, Set allowedStructureKeys, Set allowedTemplateKeys, StructureImporter.Ownership ownership ) { - KList keys = INMS.get().getStructureKeys(); - KeySelection structureSelection = selectDatapackKeys(keys, allowedStructureKeys); + KeySelection structureSelection = selectDatapackKeys(keysOf(platform.structures()), allowedStructureKeys); List datapack = structureSelection.present(); int structureAttempts = structureSelection.total(); @@ -299,24 +294,24 @@ public final class BulkStructureImporter { Map successfulBundles = new TreeMap<>(); if (structureAttempts == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_NO_DATAPACK_NON_MINECRAFT_STRUCTURES_ARE_REGISTERED_INGEST_DATAPACK_RESTART_FIRST_THEN)); + SenderText.send(sender, TextColor.YELLOW, + "No datapack (non-minecraft) structures are registered. Ingest a datapack and restart first, then run this again."); } else { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTING_DATAPACK_STRUCTURES_MODE, MessageArgument.untrusted("total", String.valueOf(structureAttempts)), MessageArgument.untrusted("mode", String.valueOf(mode)))); + SenderText.send(sender, ToolText.builder() + .green("Importing ").white(String.valueOf(structureAttempts)) + .green(" datapack structures (mode=" + mode + ")...").build()); for (String missingKey : structureSelection.missing()) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_8, MessageArgument.untrusted("keyString", missingKey), MessageArgument.untrusted("message", "allowed structure key is absent from the live registry"))); + SenderText.send(sender, TextColor.RED, "[fail] " + missingKey + + ": allowed structure key is absent from the live registry"); } for (String keyString : datapack) { - NamespacedKey nk = NamespacedKey.fromString(keyString.toLowerCase()); - if (nk == null) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_3, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); - continue; - } + ResourceId nk = ResourceId.parse(keyString); String name = StructureImporter.deriveName(nk); try { VillageImporter.Result jigsaw = VillageImporter.importVillage( - data, + pack, + platform, nk, name, mode, @@ -325,7 +320,7 @@ public final class BulkStructureImporter { if (jigsaw.success()) { imported++; successfulBundles.put(bundleKey(name), keyString); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_JIGSAW_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("name", String.valueOf(name)))); + SenderText.send(sender, TextColor.GRAY, "[jigsaw] " + keyString + " -> " + name); continue; } retryRequired |= jigsaw.retryableFailure(); @@ -333,7 +328,8 @@ public final class BulkStructureImporter { String message = jigsaw.message() == null ? "" : jigsaw.message(); if (message.contains("is not a jigsaw structure")) { StructureImporter.Result single = StructureImporter.importStructure( - data, + pack, + platform, nk, name, mode, @@ -343,7 +339,7 @@ public final class BulkStructureImporter { if (single.success()) { imported++; successfulBundles.put(bundleKey(name), keyString); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SINGLE_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("name", String.valueOf(name)))); + SenderText.send(sender, TextColor.GRAY, "[single] " + keyString + " -> " + name); } else if (single.message() != null && single.message().startsWith("Skipped")) { skipped++; } else if (single.message() != null && single.message().contains("No loadable structure NBT")) { @@ -351,7 +347,7 @@ public final class BulkStructureImporter { } else { failed++; retryRequired |= single.retryableFailure(); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_7, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(single.message())))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + single.message()); } continue; } @@ -362,11 +358,11 @@ public final class BulkStructureImporter { } failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_8, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(message)))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + message); } catch (Throwable e) { failed++; retryRequired = true; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_9, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage()); } } } @@ -375,13 +371,14 @@ public final class BulkStructureImporter { List templateKeys = List.of(); boolean enumerationSucceeded = false; try { - templateKeys = enumerateTemplateKeys(); + templateKeys = keysOf(platform.templates()); enumerationSucceeded = true; } catch (Throwable e) { templateAttempts++; failed++; retryRequired = true; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_COULD_NOT_ENUMERATE_DATAPACK_TEMPLATES_VIA_SERVER_RESOURCEMANAGER, MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); + SenderText.send(sender, TextColor.YELLOW, + "Could not enumerate datapack templates via the server ResourceManager: " + e.getMessage()); } if (enumerationSucceeded) { KeySelection templateSelection = selectDatapackKeys(templateKeys, allowedTemplateKeys); @@ -389,21 +386,20 @@ public final class BulkStructureImporter { templateAttempts += templateSelection.total(); failed += templateSelection.missing().size(); for (String missingKey : templateSelection.missing()) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_10, MessageArgument.untrusted("keyString", missingKey), MessageArgument.untrusted("message", "allowed template key is absent from the live server resources"))); + SenderText.send(sender, TextColor.RED, "[fail] " + missingKey + + ": allowed template key is absent from the live server resources"); } if (!datapackTemplates.isEmpty()) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTING_DATAPACK_STRUCTURE_TEMPLATES, MessageArgument.untrusted("size", String.valueOf(datapackTemplates.size())))); + SenderText.send(sender, ToolText.builder() + .green("Importing ").white(String.valueOf(datapackTemplates.size())) + .green(" datapack structure templates...").build()); for (String keyString : datapackTemplates) { - NamespacedKey nk = NamespacedKey.fromString(keyString.toLowerCase()); - if (nk == null) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); - continue; - } + ResourceId nk = ResourceId.parse(keyString); String name = templateNameFor(keyString); try { StructureImporter.Result result = StructureImporter.importStructure( - data, + pack, + platform, nk, name, mode, @@ -418,20 +414,24 @@ public final class BulkStructureImporter { } else { failed++; retryRequired |= result.retryableFailure(); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_10, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(result.message())))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + result.message()); } } catch (Throwable e) { failed++; retryRequired = true; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_11, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage()); } } } } } - StructureIndexService.write(data); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_DATAPACK_STRUCTURE_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)))); + refreshIndex(pack, platform); + SenderText.send(sender, ToolText.builder() + .green("Datapack structure import complete: ").white(String.valueOf(imported)) + .green(" imported, ").white(String.valueOf(skipped)) + .green(" skipped, ").white(String.valueOf(failed)) + .green(" failed.").build()); return datapackReport( structureAttempts, templateAttempts, @@ -442,6 +442,27 @@ public final class BulkStructureImporter { retryRequired); } + private static ToolText completion(String label, int imported, int skipped, int failed, int total) { + return ToolText.builder() + .green(label).white(String.valueOf(imported)) + .green(" imported, ").white(String.valueOf(skipped)) + .green(" skipped, ").white(String.valueOf(failed)) + .green(" failed (").white(String.valueOf(total)) + .green(" total).").build(); + } + + private static List keysOf(List ids) { + return ids.stream().map(ResourceId::toString).toList(); + } + + private static void refreshIndex(ToolPack pack, PlatformStructures platform) { + try { + StructureIndexService.write(pack, platform); + } catch (IOException | RuntimeException e) { + pack.log().error("Could not refresh the structure index", e); + } + } + static boolean isAllowedDatapackKey(String key, Set allowedKeys) { return allowedKeys == null ? !key.startsWith("minecraft:") : allowedKeys.contains(key); } @@ -523,89 +544,6 @@ public final class BulkStructureImporter { return "minecraft".equals(namespace) ? safePath : namespace + "/" + safePath; } - private static List enumerateTemplateKeys() throws Exception { - Object craftServer = Bukkit.getServer(); - Object dedicated = invoke(craftServer, "getHandle"); - Object server = invoke(dedicated, "getServer"); - 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 endsWithNbt = location -> { - String path = identifierPath(location); - return path != null && path.endsWith(".nbt"); - }; - - Object resultMap = listResources.invoke(resourceManager, "structure", endsWithNbt); - TreeSet 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/")) { - stripped = stripped.substring("structure/".length()); - } - if (stripped.endsWith(".nbt")) { - stripped = stripped.substring(0, stripped.length() - ".nbt".length()); - } - if (stripped.isEmpty()) { - continue; - } - keys.add(namespace + ":" + stripped); - } - } - return new ArrayList<>(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 TreeSet normalizeKeys(Iterable keys) { TreeSet normalized = new TreeSet<>(); for (String key : keys) { @@ -621,48 +559,6 @@ public final class BulkStructureImporter { return "iris:" + name; } - 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; - } - } - - private static Object invoke(Object target, String method) throws Exception { - Class c = target.getClass(); - while (c != null) { - for (Method m : c.getDeclaredMethods()) { - if (m.getName().equals(method) && m.getParameterCount() == 0) { - m.setAccessible(true); - return m.invoke(target); - } - } - c = c.getSuperclass(); - } - for (Method m : target.getClass().getMethods()) { - if (m.getName().equals(method) && m.getParameterCount() == 0) { - m.setAccessible(true); - return m.invoke(target); - } - } - throw new NoSuchMethodException(method + " on " + target.getClass().getName()); - } - record KeySelection(List present, List missing) { KeySelection { present = List.copyOf(present); diff --git a/core/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java b/core/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java index 3b12a0dd1..29d5b0b35 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java +++ b/core/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java @@ -18,65 +18,61 @@ package art.arcane.iris.core.structure; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.nms.INMS; +import art.arcane.iris.core.structure.tooling.SenderText; +import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.util.common.format.C; -import art.arcane.iris.util.common.plugin.VolmitSender; -import art.arcane.iris.util.common.scheduling.J; -import art.arcane.volmlib.util.collection.KList; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.CapturedStructure; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.TemplateBlock; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; -import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Optional; import java.util.Set; import java.util.TreeSet; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import art.arcane.iris.core.localization.BukkitRuntimeMessages; -import art.arcane.iris.core.localization.IrisLanguage; -import art.arcane.volmlib.util.localization.MessageArgument; public final class StructureCaptureImporter { public record Report(int total, int imported, int skipped, int failed) { } private static final int MAX_SPAN = 48; - private static final int CELL_STRIDE = 128; - private static final int CELL_COLUMNS = 8; - private static final long REGION_TIMEOUT_SECONDS = 30L; + private static final int PROGRESS_INTERVAL = 10; private StructureCaptureImporter() { } - public static Report importAllStructures(IrisData data, StructureImporter.Mode mode, VolmitSender sender) { - return importStructures(data, mode, sender, null); + public static Report importAllStructures(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender) { + return importStructures(pack, platform, mode, sender, null); } - public static Report importStructures(IrisData data, StructureImporter.Mode mode, VolmitSender sender, - Set allowedStructureKeys) { + public static Report importStructures(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender, Set allowedStructureKeys) { StructureImporter.Mode activeMode = mode == null ? StructureImporter.Mode.ADD_ONLY : mode; - if (!INMS.get().supportsStructureCapture()) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_STRUCTURE_CAPTURE_IS_NOT_SUPPORTED_BY_ACTIVE_NMS_BINDING_SKIPPING_CAPTURE_PASS)); + if (!platform.supportsCapture()) { + SenderText.send(sender, TextColor.YELLOW, + "Structure capture is not supported by the active NMS binding; skipping the capture pass."); return new Report(0, 0, 0, 0); } - KList keys = INMS.get().getStructureKeys(); - if (keys == null || keys.isEmpty()) { + List keys = platform.structures().stream().map(ResourceId::toString).toList(); + if (keys.isEmpty()) { return new Report(0, 0, 0, 0); } + PackResources resources = pack.resources(); ArrayList targets = new ArrayList<>(); for (String key : selectCaptureKeys(keys, allowedStructureKeys)) { String name = StructureImporter.deriveName(key); - File structureFile = new File(data.getDataFolder(), "structures/" + name + ".json"); - if (structureFile.exists() && activeMode != StructureImporter.Mode.OVERWRITE) { + boolean alreadyImported = resources.ids(StructureResources.STRUCTURES).contains(resources.idOf(name)); + if (alreadyImported && activeMode != StructureImporter.Mode.OVERWRITE) { continue; } targets.add(key); @@ -84,14 +80,18 @@ public final class StructureCaptureImporter { int total = targets.size(); if (total == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_NO_CODE_GENERATED_STRUCTURES_LEFT_CAPTURE_EVERYTHING_IS_ALREADY_IMPORTED_AS_STRUCTURE)); + SenderText.send(sender, TextColor.GRAY, + "No code-generated structures left to capture (everything is already imported as a structure)."); return new Report(0, 0, 0, 0); } - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_CAPTURING_CODE_GENERATED_STRUCTURES_NO_NBT_TEMPLATE_INTO_SCRATCH_WORLD_SKIPPING_ANY, MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("MAXSPAN", String.valueOf(MAX_SPAN)))); + SenderText.send(sender, ToolText.builder() + .green("Capturing ").white(String.valueOf(total)) + .green(" code-generated structures (no NBT template) into a scratch world (skipping any wider/taller than " + + MAX_SPAN + " blocks)...").build()); - World scratch = FeatureImporter.createScratchWorld(sender); - if (scratch == null) { + Optional opened = platform.openCaptureArea(sender); + if (opened.isEmpty()) { return new Report(total, 0, 0, total); } @@ -100,42 +100,48 @@ public final class StructureCaptureImporter { int failed = 0; int cellIndex = 0; - try { + try (PlatformStructures.CaptureArea area = opened.get()) { for (String key : targets) { String name = StructureImporter.deriveName(key); try { - IrisObject object = captureOne(scratch, key, cellIndex++); + IrisObject object = captureOne(area, key, cellIndex++); if (object == null || object.getBlocks().isEmpty()) { skipped++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_SKIP_DID_NOT_PLACE_CAPTURABLE_STRUCTURE_HERE_TOO_LARGE_WRONG_DIMENSION_NO, MessageArgument.untrusted("key", String.valueOf(key)))); + SenderText.send(sender, TextColor.YELLOW, "[skip] " + key + + ": did not place a capturable structure here (too large, wrong dimension, or no valid placement in a flat world). Stays vanilla-generated."); continue; } object.shrinkwrap(); StructureImporter.Result result = StructureImporter.writeSinglePieceStructure( - data, name, key, object, "CENTER_HEIGHT", activeMode); + pack, name, key, object, "CENTER_HEIGHT", activeMode); if (!result.success()) { failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_FAIL, MessageArgument.untrusted("key", String.valueOf(key)), MessageArgument.untrusted("message", String.valueOf(result.message())))); + SenderText.send(sender, TextColor.RED, "[fail] " + key + ": " + result.message()); continue; } imported++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_CAPTURE_OBJECTS_IOB_X_X, MessageArgument.untrusted("key", String.valueOf(key)), MessageArgument.untrusted("name", String.valueOf(name)), MessageArgument.untrusted("w", String.valueOf(object.getW())), MessageArgument.untrusted("h", String.valueOf(object.getH())), MessageArgument.untrusted("d", String.valueOf(object.getD())))); + SenderText.send(sender, TextColor.GRAY, "[capture] " + key + " -> objects/" + name + ".iob (" + + object.getW() + "x" + object.getH() + "x" + object.getD() + ")"); } catch (Throwable e) { failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_FAIL_2, MessageArgument.untrusted("key", String.valueOf(key)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); - IrisLogging.reportError(e); + SenderText.send(sender, TextColor.RED, "[fail] " + key + ": " + e.getMessage()); + pack.log().error("Could not capture structure " + key, e); } int processed = imported + skipped + failed; - if (processed % 10 == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_CAPTURED_SKIPPED_FAILED, MessageArgument.untrusted("processed", String.valueOf(processed)), MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)))); + if (processed % PROGRESS_INTERVAL == 0) { + SenderText.send(sender, TextColor.GRAY, "..." + processed + "/" + total + " (" + imported + + " captured, " + skipped + " skipped, " + failed + " failed)"); } } - } finally { - FeatureImporter.destroyScratchWorld(scratch, sender); } - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_STRUCTURE_CAPTURE_COMPLETE_CAPTURED_SKIPPED_FAILED_TOTAL, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)), MessageArgument.untrusted("total", String.valueOf(total)))); + SenderText.send(sender, ToolText.builder() + .green("Structure capture complete: ").white(String.valueOf(imported)) + .green(" captured, ").white(String.valueOf(skipped)) + .green(" skipped, ").white(String.valueOf(failed)) + .green(" failed (").white(String.valueOf(total)) + .green(" total).").build()); return new Report(total, imported, skipped, failed); } @@ -168,94 +174,19 @@ public final class StructureCaptureImporter { return normalized; } - private static IrisObject captureOne(World world, String key, int cellIndex) { - 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; + private static IrisObject captureOne(PlatformStructures.CaptureArea area, String key, int cellIndex) { long seed = key.hashCode() * 0x9E3779B97F4A7C15L + cellIndex * 0x100000001B3L + 0x5DEECE66DL; - - AtomicReference objectRef = new AtomicReference<>(); - AtomicReference errorRef = new AtomicReference<>(); - CountDownLatch latch = new CountDownLatch(1); - - boolean scheduled = J.runRegion(world, anchorChunkX, anchorChunkZ, () -> { - try { - int[] box = INMS.get().placeStructure(world, anchorChunkX, anchorChunkZ, key, seed, MAX_SPAN); - if (box == null) { - return; - } - 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; - } - IrisObject object = new IrisObject(width, height, depth); - boolean any = false; - 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; - } - object.setUnsigned(dx, dy, dz, block, false); - any = true; - } - } - } - if (any) { - objectRef.set(object); - } - - 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) { - } - } - } - } 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 objectRef.get(); + Optional captured = area.capture(ResourceId.parse(key), seed, MAX_SPAN); + return captured.map(StructureCaptureImporter::objectOf).orElse(null); } - 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); + private static IrisObject objectOf(CapturedStructure captured) { + IrisObject object = new IrisObject(captured.size().x(), captured.size().y(), captured.size().z()); + for (TemplateBlock block : captured.blocks()) { + object.setUnsignedState(block.position().x(), block.position().y(), block.position().z(), block.state()); + block.blockEntity().ifPresent(entity -> + object.setUnsignedBlockEntity(block.position().x(), block.position().y(), block.position().z(), entity)); + } + return object; } } diff --git a/core/src/main/java/art/arcane/iris/core/structure/StructureImporter.java b/core/src/main/java/art/arcane/iris/core/structure/StructureImporter.java index ae81914fa..becbca801 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/StructureImporter.java +++ b/core/src/main/java/art/arcane/iris/core/structure/StructureImporter.java @@ -18,7 +18,6 @@ package art.arcane.iris.core.structure; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.structure.authoring.IrisStructureBundleFactory; import art.arcane.iris.core.structure.authoring.StructureBackend; import art.arcane.iris.core.structure.authoring.StructureCapability; @@ -32,25 +31,22 @@ import art.arcane.iris.core.structure.authoring.StructureWriteResult; import art.arcane.iris.engine.framework.structure.StructureGraphValidationException; import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.LegacyTileData; -import art.arcane.iris.spi.IrisLogging; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; -import org.bukkit.structure.Palette; -import org.bukkit.structure.Structure; -import org.bukkit.util.BlockVector; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplateBlock; +import com.volmit.tooling.ToolPack; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; @@ -58,9 +54,15 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; public final class StructureImporter { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + private static final String STRUCTURE_VOID = "minecraft:structure_void"; + private static final String JIGSAW = "minecraft:jigsaw"; + private static final String STRUCTURE_BLOCK = "minecraft:structure_block"; + private static final Set AIR_BLOCKS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air"); + private static final String PLATFORM_NAMESPACE = "minecraft"; public enum Mode { OVERWRITE, @@ -72,14 +74,16 @@ public final class StructureImporter { MANAGED_DATAPACK; StructureWriteResult write( - IrisData data, + ToolPack pack, StructureResourceBundle bundle, StructureWriteMode mode - ) { - StructureTransactionWriter writer = new StructureTransactionWriter(data.getDataFolder().toPath()); - return this == MANAGED_DATAPACK - ? writer.writeManagedDatapack(bundle, mode) - : writer.write(bundle, mode); + ) throws IOException { + return pack.edit(root -> { + StructureTransactionWriter writer = new StructureTransactionWriter(root); + return this == MANAGED_DATAPACK + ? writer.writeManagedDatapack(bundle, mode) + : writer.write(bundle, mode); + }); } } @@ -132,47 +136,49 @@ public final class StructureImporter { }; } - public static String deriveName(NamespacedKey key) { - return (key.getNamespace() + "_" + key.getKey()).replace('/', '_').replace(':', '_'); + public static String deriveName(ResourceId key) { + return (key.namespace() + "_" + key.path()).replace('/', '_').replace(':', '_'); } public static String deriveName(String key) { return key.toLowerCase().replace('/', '_').replace(':', '_'); } - public static Result importStructure(IrisData data, NamespacedKey key, String name, Mode mode) { - return importStructure(data, key, name, mode, false, Ownership.EDITABLE); + public static Result importStructure(ToolPack pack, PlatformStructures platform, ResourceId key, String name, Mode mode) { + return importStructure(pack, platform, key, name, mode, false, Ownership.EDITABLE); } - public static Result importStructure(IrisData data, NamespacedKey key, String name, Mode mode, boolean objectOnly) { - return importStructure(data, key, name, mode, objectOnly, Ownership.EDITABLE); + public static Result importStructure(ToolPack pack, PlatformStructures platform, ResourceId key, String name, Mode mode, + boolean objectOnly) { + return importStructure(pack, platform, key, name, mode, objectOnly, Ownership.EDITABLE); } static Result importStructure( - IrisData data, - NamespacedKey key, + ToolPack pack, + PlatformStructures platform, + ResourceId key, String name, Mode mode, boolean objectOnly, Ownership ownership ) { Mode activeMode = mode == null ? Mode.ADD_ONLY : mode; - Structure structure; + Optional loaded; try { - structure = Bukkit.getStructureManager().loadStructure(key); + loaded = platform.template(key); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not load structure template " + key, e); return new Result(false, "Failed to load structure " + key + ": " + e.getMessage(), 0, List.of(), true); } - if (structure == null || structure.getPalettes().isEmpty()) { + if (loaded.isEmpty()) { return new Result(false, "No loadable structure NBT for key " + key + " (jigsaw structures must be imported by their piece keys)", 0, List.of()); } CapturedStructure captured; try { - captured = captureStructure(structure); + captured = captureStructure(loaded.get()); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not capture structure template " + key, e); return new Result(false, "Failed to capture structure " + key + ": " + e.getMessage(), 0, List.of(), true); } @@ -193,7 +199,7 @@ public final class StructureImporter { try { StructureKey sourceKey = StructureKey.parse(key.toString()); StructureKey bundleKey = new StructureKey("iris", name); - StructureSource.Kind sourceKind = key.getNamespace().equals("minecraft") + StructureSource.Kind sourceKind = key.namespace().equals(PLATFORM_NAMESPACE) ? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK; StructureSource source = StructureSource.of(sourceKind, sourceKey); IrisStructureBundleFactory.SinglePieceOptions options = new IrisStructureBundleFactory.SinglePieceOptions( @@ -205,20 +211,17 @@ public final class StructureImporter { } StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY ? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE; - StructureWriteResult writeResult = ownership.write(data, bundle, writeMode); - reportWriteFailure(writeResult); + StructureWriteResult writeResult = ownership.write(pack, bundle, writeMode); + reportWriteFailure(pack, writeResult); if (!writeResult.successful()) { return new Result(false, writeFailureMessage(name, activeMode, writeResult), count, losses, writeResult.failure().isPresent()); } - if (writeResult.committed()) { - data.invalidateStructureResources(); - } writeNote = writeResultNote(writeResult); } catch (StructureGraphValidationException e) { return new Result(false, "Failed writing import for '" + name + "': " + e.getMessage(), count, losses); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not write the import of " + key, e); return new Result(false, "Failed writing import for '" + name + "': " + e.getMessage(), count, losses, true); } @@ -228,64 +231,58 @@ public final class StructureImporter { + " tiles, " + w + "x" + h + "x" + d + lossSummary + ")" + writeNote, count, losses); } - static CapturedStructure captureStructure(Structure structure) { - Structure activeStructure = Objects.requireNonNull(structure); - if (activeStructure.getPalettes().isEmpty()) { + static CapturedStructure captureStructure(StructureTemplate template) { + StructureTemplate activeTemplate = Objects.requireNonNull(template); + if (activeTemplate.paletteCount() < 1) { throw new IllegalArgumentException("Structure has no palettes"); } - BlockVector size = activeStructure.getSize(); - int w = Math.max(1, size.getBlockX()); - int h = Math.max(1, size.getBlockY()); - int d = Math.max(1, size.getBlockZ()); + BlockPosition size = activeTemplate.size(); + int w = Math.max(1, size.x()); + int h = Math.max(1, size.y()); + int d = Math.max(1, size.z()); IrisObject object = new IrisObject(w, h, d); int count = 0; int nonAirBlocks = 0; int tiles = 0; int structureMarkers = 0; int invalidFinalStates = 0; - Palette palette = activeStructure.getPalettes().get(0); - for (BlockState block : palette.getBlocks()) { - Location loc = block.getLocation(); - int x = loc.getBlockX(); - int y = loc.getBlockY(); - int z = loc.getBlockZ(); + for (TemplateBlock block : activeTemplate.blocks()) { + int x = block.position().x(); + int y = block.position().y(); + int z = block.position().z(); if (x < 0 || y < 0 || z < 0 || x >= w || y >= h || z >= d) { continue; } - BlockData blockData = block.getBlockData(); - Material mat = blockData.getMaterial(); - if (mat == Material.STRUCTURE_VOID) { + String material = block.state().material().toString(); + if (material.equals(STRUCTURE_VOID)) { continue; } - boolean structural = mat == Material.JIGSAW || mat == Material.STRUCTURE_BLOCK; + boolean structural = material.equals(JIGSAW) || material.equals(STRUCTURE_BLOCK); if (structural) { structureMarkers++; } - if (mat == Material.JIGSAW) { + BlockState placed = block.state(); + if (material.equals(JIGSAW)) { FinalStateResult finalState = readJigsawFinalState(block); - BlockData resolved = finalState.blockData(); if (finalState.invalidSourceState()) { invalidFinalStates++; } - if (resolved == null || isAir(resolved)) { + if (finalState.state() == null || isAir(finalState.state())) { continue; } - blockData = resolved; - } else if (mat == Material.STRUCTURE_BLOCK) { + placed = finalState.state(); + } else if (material.equals(STRUCTURE_BLOCK)) { continue; } - object.setUnsigned(x, y, z, art.arcane.iris.platform.bukkit.BukkitBlockState.of(blockData)); + object.setUnsignedState(x, y, z, placed); count++; - if (!isAir(blockData)) { + if (!isAir(placed)) { nonAirBlocks++; } - if (!structural) { - LegacyTileData tile = captureTile(block); - if (tile != null) { - object.setUnsignedTile(x, y, z, tile); - tiles++; - } + if (!structural && block.blockEntity().isPresent()) { + object.setUnsignedBlockEntity(x, y, z, block.blockEntity().get()); + tiles++; } } @@ -304,32 +301,31 @@ public final class StructureImporter { d, structureMarkers, capabilities, - importLosses(activeStructure, structureMarkers, invalidFinalStates) + importLosses(activeTemplate, structureMarkers, invalidFinalStates) ); } - private static boolean isAir(BlockData data) { - Material m = data.getMaterial(); - return m == Material.AIR || m == Material.CAVE_AIR || m == Material.VOID_AIR; + private static boolean isAir(BlockState state) { + return AIR_BLOCKS.contains(state.material().toString()); } private static List importLosses( - Structure structure, + StructureTemplate structure, int structureMarkers, int invalidFinalStates ) { List losses = new ArrayList<>(); - if (structure.getPaletteCount() > 1) { + if (structure.paletteCount() > 1) { losses.add(StructureLoss.warning( StructureCapability.BLOCKS, "palette_variants_not_imported", - "Only palette 0 was converted; " + (structure.getPaletteCount() - 1) + " additional palette(s) remain native-only.")); + "Only palette 0 was converted; " + (structure.paletteCount() - 1) + " additional palette(s) remain native-only.")); } - if (structure.getEntityCount() > 0) { + if (structure.entityCount() > 0) { losses.add(StructureLoss.warning( StructureCapability.ENTITIES, "entities_not_imported", - structure.getEntityCount() + " structure entit" + (structure.getEntityCount() == 1 ? "y was" : "ies were") + structure.entityCount() + " structure entit" + (structure.entityCount() == 1 ? "y was" : "ies were") + " not converted into the Iris snapshot.")); } if (structureMarkers > 0) { @@ -347,10 +343,8 @@ public final class StructureImporter { return losses; } - private static void reportWriteFailure(StructureWriteResult result) { - result.failure().ifPresent((Throwable failure) -> { - IrisLogging.reportError(failure); - }); + private static void reportWriteFailure(ToolPack pack, StructureWriteResult result) { + result.failure().ifPresent((Throwable failure) -> pack.log().error("Structure write failed", failure)); } private static String writeResultNote(StructureWriteResult result) { @@ -371,36 +365,23 @@ public final class StructureImporter { return "Failed writing import for '" + name + "' in " + mode.name().toLowerCase() + " mode: " + failure; } - private static FinalStateResult readJigsawFinalState(BlockState block) { - String finalState; - try { - Object nbt = block.getClass().getMethod("getSnapshotNBT").invoke(block); - if (nbt == null) { - return new FinalStateResult(null, false); - } - Object res = nbt.getClass().getMethod("getString", String.class).invoke(nbt, "final_state"); - finalState = null; - if (res instanceof String s) { - finalState = s; - } else if (res instanceof Optional o && o.isPresent()) { - finalState = String.valueOf(o.get()); - } - if (finalState == null || finalState.isBlank()) { - return new FinalStateResult(null, false); - } - } catch (Throwable e) { - IrisLogging.reportError(e); - if (VillageImporter.shouldPrintFullTrace(e)) { - } + private static FinalStateResult readJigsawFinalState(TemplateBlock block) { + if (block.jigsawFinalState().isEmpty() || block.jigsawFinalState().get().isBlank()) { return new FinalStateResult(null, false); } try { - return new FinalStateResult(Bukkit.createBlockData(normalizeJigsawFinalState(finalState)), false); + return new FinalStateResult(BlockState.parse(withNamespace(normalizeJigsawFinalState(block.jigsawFinalState().get()))), false); } catch (IllegalArgumentException e) { return new FinalStateResult(null, true); } } + private static String withNamespace(String blockState) { + int propertiesStart = blockState.indexOf('['); + String blockId = propertiesStart < 0 ? blockState : blockState.substring(0, propertiesStart); + return blockId.indexOf(':') < 0 ? PLATFORM_NAMESPACE + ":" + blockState : blockState; + } + static String normalizeJigsawFinalState(String finalState) { if (finalState == null) { return null; @@ -419,30 +400,33 @@ public final class StructureImporter { return finalState.replaceAll("([\\[,])half=(top|bottom)(?=[,\\]])", "$1type=$2"); } - private record FinalStateResult(BlockData blockData, boolean invalidSourceState) { + private record FinalStateResult(BlockState state, boolean invalidSourceState) { } - private static LegacyTileData captureTile(BlockState block) { + public static Result importTemplateGroup(ToolPack pack, String groupName, String vanillaSource, String prefix, Mode mode) { try { - return LegacyTileData.fromBukkit(block); + return pack.edit(root -> importTemplateGroup(pack, root, groupName, vanillaSource, prefix, mode)); } catch (Throwable e) { - IrisLogging.reportError(e); - return null; + pack.log().error("Could not build group structure " + groupName, e); + return new Result(false, "Failed writing group structure '" + groupName + "': " + e.getMessage(), 0, + List.of(), true); } } - public static Result importTemplateGroup(IrisData data, String groupName, String vanillaSource, String prefix, Mode mode) { + private static Result importTemplateGroup(ToolPack pack, Path root, String groupName, String vanillaSource, + String prefix, Mode mode) { Mode activeMode = mode == null ? Mode.ADD_ONLY : mode; - File objectsRoot = new File(data.getDataFolder(), "objects"); + String objectExtension = pack.objects().extension(); + File objectsRoot = new File(root.toFile(), "objects"); File prefixDir = new File(objectsRoot, prefix); if (!prefixDir.isDirectory()) { return new Result(false, "No imported templates under objects/" + prefix + " for " + groupName, 0, List.of()); } List iobs = new ArrayList<>(); - collectIob(prefixDir, iobs); + collectObjects(prefixDir, objectExtension, iobs); if (iobs.isEmpty()) { - return new Result(false, "No .iob templates under objects/" + prefix + " for " + groupName, 0, List.of()); + return new Result(false, "No " + objectExtension + " templates under objects/" + prefix + " for " + groupName, 0, List.of()); } iobs.sort(Comparator.comparing(File::getAbsolutePath)); @@ -451,71 +435,60 @@ public final class StructureImporter { int maxSpan = 1; for (File iob : iobs) { String rel = iob.getAbsolutePath().substring(rootPath.length()).replace(File.separatorChar, '/'); - if (rel.endsWith(".iob")) { - rel = rel.substring(0, rel.length() - ".iob".length()); + if (rel.endsWith(objectExtension)) { + rel = rel.substring(0, rel.length() - objectExtension.length()); } pieceNames.add(rel); try { maxSpan = Math.max(maxSpan, readObjectSpan(iob)); } catch (IOException e) { - IrisLogging.reportError(e); + pack.log().error("Could not read the imported object " + rel, e); return new Result(false, "Cannot read imported object '" + rel + "': " + e.getMessage(), 0, List.of(), true); } } - try { - for (String piece : pieceNames) { - File pieceFile = new File(data.getDataFolder(), "jigsaw-pieces/" + piece + ".json"); - if (!pieceFile.isFile()) { - return new Result(false, "Missing imported jigsaw piece '" + piece - + "'; import the source templates before building group '" + groupName + "'", 0, List.of()); - } + for (String piece : pieceNames) { + File pieceFile = new File(root.toFile(), "jigsaw-pieces/" + piece + ".json"); + if (!pieceFile.isFile()) { + return new Result(false, "Missing imported jigsaw piece '" + piece + + "'; import the source templates before building group '" + groupName + "'", 0, List.of()); } - - StructureKey sourceKey = StructureKey.parse(vanillaSource, "minecraft"); - StructureSource.Kind sourceKind = sourceKey.namespace().equals("minecraft") - ? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK; - StructureResourceBundle bundle = StructureResourceBundle.builder(new StructureKey("iris", groupName)) - .source(StructureSource.of(sourceKind, sourceKey)) - .backend(StructureBackend.IRIS_ASSEMBLY) - .capability(StructureCapability.BLOCKS) - .capability(StructureCapability.IRIS_PLACEMENT) - .textResource("jigsaw-pools/" + groupName + ".json", GSON.toJson(poolJsonMulti(pieceNames))) - .textResource("structures/" + groupName + ".json", - GSON.toJson(structureJson(groupName, vanillaSource, maxSpan))) - .build(); - StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY - ? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE; - StructureWriteResult writeResult = new StructureTransactionWriter(data.getDataFolder().toPath()) - .write(bundle, writeMode); - reportWriteFailure(writeResult); - if (!writeResult.successful()) { - return new Result(false, writeFailureMessage(groupName, activeMode, writeResult), 0, List.of(), - writeResult.failure().isPresent()); - } - if (writeResult.committed()) { - data.invalidateStructureResources(); - } - return new Result(true, "Built structure '" + groupName + "' from " + pieceNames.size() - + " template variants" + writeResultNote(writeResult), pieceNames.size(), List.of()); - } catch (Throwable e) { - IrisLogging.reportError(e); - return new Result(false, "Failed writing group structure '" + groupName + "': " + e.getMessage(), 0, - List.of(), true); } + StructureKey sourceKey = StructureKey.parse(vanillaSource, "minecraft"); + StructureSource.Kind sourceKind = sourceKey.namespace().equals("minecraft") + ? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK; + StructureResourceBundle bundle = StructureResourceBundle.builder(new StructureKey("iris", groupName)) + .source(StructureSource.of(sourceKind, sourceKey)) + .backend(StructureBackend.IRIS_ASSEMBLY) + .capability(StructureCapability.BLOCKS) + .capability(StructureCapability.IRIS_PLACEMENT) + .textResource("jigsaw-pools/" + groupName + ".json", GSON.toJson(poolJsonMulti(pieceNames))) + .textResource("structures/" + groupName + ".json", + GSON.toJson(structureJson(groupName, vanillaSource, maxSpan))) + .build(); + StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY + ? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE; + StructureWriteResult writeResult = new StructureTransactionWriter(root).write(bundle, writeMode); + reportWriteFailure(pack, writeResult); + if (!writeResult.successful()) { + return new Result(false, writeFailureMessage(groupName, activeMode, writeResult), 0, List.of(), + writeResult.failure().isPresent()); + } + return new Result(true, "Built structure '" + groupName + "' from " + pieceNames.size() + + " template variants" + writeResultNote(writeResult), pieceNames.size(), List.of()); } - private static void collectIob(File dir, List out) { + private static void collectObjects(File dir, String extension, List out) { File[] files = dir.listFiles(); if (files == null) { return; } for (File f : files) { if (f.isDirectory()) { - collectIob(f, out); - } else if (f.getName().endsWith(".iob")) { + collectObjects(f, extension, out); + } else if (f.getName().endsWith(extension)) { out.add(f); } } @@ -547,7 +520,7 @@ public final class StructureImporter { } public static Result writeSinglePieceStructure( - IrisData data, + ToolPack pack, String name, String vanillaSource, IrisObject object, @@ -574,22 +547,18 @@ public final class StructureImporter { StructureResourceBundleGraphCompiler.requireViable(bundle); StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY ? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE; - StructureWriteResult writeResult = new StructureTransactionWriter(data.getDataFolder().toPath()) - .write(bundle, writeMode); - reportWriteFailure(writeResult); + StructureWriteResult writeResult = Ownership.EDITABLE.write(pack, bundle, writeMode); + reportWriteFailure(pack, writeResult); if (!writeResult.successful()) { return new Result(false, writeFailureMessage(name, activeMode, writeResult), 0, List.of(), writeResult.failure().isPresent()); } - if (writeResult.committed()) { - data.invalidateStructureResources(); - } return new Result(true, "Captured '" + vanillaSource + "' as '" + name + "'" + writeResultNote(writeResult), object.getBlocks().size(), List.of()); } catch (StructureGraphValidationException e) { return new Result(false, "Failed writing capture for '" + name + "': " + e.getMessage(), 0, List.of()); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not write the capture of " + vanillaSource, e); return new Result(false, "Failed writing capture for '" + name + "': " + e.getMessage(), 0, List.of(), true); } diff --git a/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java b/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java index 22031d9e1..ff6a23f31 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java +++ b/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java @@ -18,13 +18,16 @@ package art.arcane.iris.core.structure; -import art.arcane.iris.core.modules.ModuleServices; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.structure.tooling.StructureKeys; import com.google.gson.GsonBuilder; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.service.StructureLocator; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.ToolPack; import java.io.File; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; @@ -33,43 +36,43 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; +import java.util.TreeSet; public final class StructureIndexService { private static final String INDEX_PATH = ".iris/structure-index.json"; - private static final Set GENERATED = ConcurrentHashMap.newKeySet(); + private static final String PLATFORM_NAMESPACE_PREFIX = "minecraft:"; private StructureIndexService() { } - public static File writeOnce(IrisData data) { - if (data == null || !IrisPlatforms.isBound() || IrisPlatforms.get().structureHooks() == null) { - return null; - } - - File dataFolder = data.getDataFolder(); - String key = dataFolder == null ? null : dataFolder.getAbsolutePath(); - if (key == null || !GENERATED.add(key)) { - return null; - } - - try { - return write(data); - } catch (Throwable e) { - GENERATED.remove(key); - IrisLogging.reportError(e); - return null; - } + /** Writes the index of every structure the platform registers and the pack's modules know into the pack, and returns its file. */ + public static File write(ToolPack pack, PlatformStructures platform) throws IOException { + List structures = keysOf(platform.structures()); + List sets = keysOf(platform.structureSets()); + List iris = irisStructureKeys(pack); + return pack.edit(root -> writeIndex(pack, indexFile(root.toFile()), structures, sets, iris)); } - public static File write(IrisData data) { - List structures = IrisPlatforms.get().structureHooks().structureKeys(); - List sets = IrisPlatforms.get().structureHooks().structureSetKeys(); + private static List keysOf(List ids) { + return ids.stream().map(ResourceId::toString).toList(); + } + private static List irisStructureKeys(ToolPack pack) { + PackResources resources = pack.resources(); + Set keys = new TreeSet<>(); + for (StructureLocator provider : pack.services(StructureLocator.class)) { + for (ResourceId structure : provider.structures(resources)) { + keys.add(StructureKeys.keyOf(resources, structure)); + } + } + return new ArrayList<>(keys); + } + + private static File writeIndex(ToolPack pack, File file, List structures, List sets, List iris) { List vanilla = new ArrayList<>(); List datapack = new ArrayList<>(); for (String k : structures) { - if (k.startsWith("minecraft:")) { + if (k.startsWith(PLATFORM_NAMESPACE_PREFIX)) { vanilla.add(k); } else { datapack.add(k); @@ -79,20 +82,17 @@ public final class StructureIndexService { List vanillaSets = new ArrayList<>(); List datapackSets = new ArrayList<>(); for (String k : sets) { - if (k.startsWith("minecraft:")) { + if (k.startsWith(PLATFORM_NAMESPACE_PREFIX)) { vanillaSets.add(k); } else { datapackSets.add(k); } } - List iris = new ArrayList<>(ModuleServices.structureKeys(data)); - Collections.sort(vanilla); Collections.sort(datapack); Collections.sort(vanillaSets); Collections.sort(datapackSets); - Collections.sort(iris); Map structuresNode = new LinkedHashMap<>(); structuresNode.put("vanilla", vanilla); @@ -115,13 +115,12 @@ public final class StructureIndexService { root.put("structureSets", setsNode); root.put("iris", iris); - File file = indexFile(data.getDataFolder()); try { file.getParentFile().mkdirs(); String json = new GsonBuilder().setPrettyPrinting().create().toJson(root); Files.writeString(file.toPath(), json, StandardCharsets.UTF_8); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not write the structure index " + file, e); } return file; } diff --git a/core/src/main/java/art/arcane/iris/core/structure/VillageImporter.java b/core/src/main/java/art/arcane/iris/core/structure/VillageImporter.java index 78c4a2d9e..9a06543c9 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/VillageImporter.java +++ b/core/src/main/java/art/arcane/iris/core/structure/VillageImporter.java @@ -18,7 +18,6 @@ package art.arcane.iris.core.structure; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.structure.authoring.StructureBackend; import art.arcane.iris.core.structure.authoring.StructureCapability; import art.arcane.iris.core.structure.authoring.StructureKey; @@ -31,18 +30,19 @@ import art.arcane.iris.engine.framework.structure.StructureGraphValidationExcept import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.spi.IrisLogging; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import org.bukkit.Bukkit; -import org.bukkit.NamespacedKey; -import org.bukkit.structure.Structure; +import com.volmit.geometry.BlockFace; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.JigsawStructureInfo; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.StructureAccessException; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplatePool; +import com.volmit.tooling.ToolPack; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; @@ -52,12 +52,17 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public final class VillageImporter { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private static final Set PRINTED_FAILURE_SIGNATURES = ConcurrentHashMap.newKeySet(); + private static final String EMPTY_POOL_ELEMENT_TYPE = "EmptyPoolElement"; + private static final String LIST_POOL_ELEMENT_TYPE = "ListPoolElement"; + private static final String FEATURE_POOL_ELEMENT_TYPE = "FeaturePoolElement"; + private static final String AIR_FINAL_STATE = "minecraft:air"; public record Result( boolean success, @@ -79,13 +84,15 @@ public final class VillageImporter { private VillageImporter() { } - public static Result importVillage(IrisData data, NamespacedKey structureKey, String name, StructureImporter.Mode mode) { - return importVillage(data, structureKey, name, mode, StructureImporter.Ownership.EDITABLE); + public static Result importVillage(ToolPack pack, PlatformStructures platform, ResourceId structureKey, String name, + StructureImporter.Mode mode) { + return importVillage(pack, platform, structureKey, name, mode, StructureImporter.Ownership.EDITABLE); } static Result importVillage( - IrisData data, - NamespacedKey structureKey, + ToolPack pack, + PlatformStructures platform, + ResourceId structureKey, String name, StructureImporter.Mode mode, StructureImporter.Ownership ownership @@ -93,66 +100,28 @@ public final class VillageImporter { StructureImporter.Mode activeMode = mode == null ? StructureImporter.Mode.ADD_ONLY : mode; List losses = new ArrayList<>(); boolean retryableFailure = false; - Object server; - Object registryAccess; - Object structureManager; String writeNote = ""; - try { - Object craftServer = Bukkit.getServer(); - Object dedicated = invoke(craftServer, "getHandle"); - server = invoke(dedicated, "getServer"); - registryAccess = resolveRegistryAccess(server); - structureManager = invoke(server, "getStructureManager"); - } catch (Throwable e) { - reportFailure(e); - return failed("Failed to access server registries via reflection: " + e, losses, true); - } - if (registryAccess == null) { - return failed("Could not resolve RegistryAccess from the server", losses, true); - } - Object startPool; - int maxDepth; - int maxDistanceFromCenter; + JigsawStructureInfo structure; try { - Object structureRegistry = lookupRegistry(registryAccess, "STRUCTURE"); - Object structure = registryGet(structureRegistry, structureKey); - if (structure == null) { - return failed("No structure registered for key " + structureKey, losses); + Optional info = platform.jigsaw(structureKey); + if (info.isEmpty()) { + return failed(platform.structures().contains(structureKey) + ? "Structure " + structureKey + " is not a jigsaw structure; use 'import' for single-template structures" + : "No structure registered for key " + structureKey, losses); } - if (!structure.getClass().getName().endsWith("JigsawStructure")) { - return failed("Structure " + structureKey + " is not a jigsaw structure (" - + structure.getClass().getSimpleName() + "); use 'import' for single-template structures", losses); - } - Object startPoolHolder = invoke(structure, "getStartPool"); - startPool = unwrapHolder(startPoolHolder); - maxDepth = readIntMember(structure, "maxDepth"); - maxDistanceFromCenter = readIntMember(structure, "maxDistanceFromCenter"); + structure = info.get(); + } catch (StructureAccessException e) { + reportFailure(pack, e); + return failed(e.getMessage(), losses, e.retryable()); } catch (Throwable e) { - reportFailure(e); + reportFailure(pack, e); return failed("Failed to read jigsaw structure graph: " + e, losses, true); } - - Object templatePoolRegistry; - java.util.Random random; - try { - templatePoolRegistry = lookupRegistry(registryAccess, "TEMPLATE_POOL"); - random = new java.util.Random(structureKey.hashCode()); - } catch (Throwable e) { - reportFailure(e); - return failed("Failed to access TEMPLATE_POOL registry: " + e, losses, true); - } - - String startPoolKey; - try { - startPoolKey = registryKeyOf(templatePoolRegistry, startPool); - } catch (Throwable e) { - reportFailure(e); - return failed("Could not resolve the start pool key for " + structureKey + ": " + e, losses, true); - } - if (startPoolKey == null) { - return failed("Could not resolve the start pool key for " + structureKey, losses); - } + int maxDepth = structure.maxDepth(); + int maxDistanceFromCenter = structure.maxDistance(); + Random random = new Random(structure.shuffleSeed()); + String startPoolKey = structure.startPool().toString(); Set visitedPools = new HashSet<>(); Deque poolQueue = new ArrayDeque<>(); @@ -179,144 +148,106 @@ public final class VillageImporter { if (!visitedPools.add(poolKey)) { continue; } - Object pool; + Optional registered; try { - pool = registryGetByKey(templatePoolRegistry, poolKey); + registered = platform.pool(ResourceId.parse(poolKey)); + } catch (StructureAccessException e) { + reportFailure(pack, e); + retryableFailure = true; + fatalErrors.add(e.getMessage()); + continue; } catch (Throwable e) { - reportFailure(e); + reportFailure(pack, e); retryableFailure = true; fatalErrors.add("pool " + poolKey + ": " + e.getMessage()); continue; } - if (pool == null) { + if (registered.isEmpty()) { fatalErrors.add("pool " + poolKey + " is not registered"); continue; } + TemplatePool pool = registered.get(); String irisPoolName = poolName(name, poolKey); List pieceEntries = new ArrayList<>(); - String fallbackKey = null; - try { - Object fallbackHolder = invoke(pool, "getFallback"); - Object fallbackPool = unwrapHolder(fallbackHolder); - fallbackKey = registryKeyOf(templatePoolRegistry, fallbackPool); - } catch (Throwable e) { - reportFailure(e); + if (pool.fallbackFailure().isPresent()) { retryableFailure = true; losses.add(StructureLoss.warning( StructureCapability.CONNECTORS, "fallback_pool_not_imported", - "The fallback for source pool " + poolKey + " could not be resolved: " + failureDetail(e)) + "The fallback for source pool " + poolKey + " could not be resolved: " + pool.fallbackFailure().get()) .affecting("jigsaw-pools/" + irisPoolName + ".json")); } + String fallbackKey = pool.fallback().map(ResourceId::toString).orElse(null); if (fallbackKey != null && !fallbackKey.equals(poolKey)) { poolQueue.add(fallbackKey); } - List templates; - try { - templates = (List) invoke(pool, "getTemplates"); - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - fatalErrors.add("templates " + poolKey + ": " + e.getMessage()); - templates = List.of(); - } - - for (Object pair : templates) { - Object element; - int weight; - try { - element = invoke(pair, "getFirst"); - Object second = invoke(pair, "getSecond"); - weight = second instanceof Number ? Math.max(1, ((Number) second).intValue()) : 1; - } catch (Throwable e) { - reportFailure(e); + List templates = pool.members(); + for (TemplatePool.Member member : templates) { + if (member instanceof TemplatePool.Absent) { + continue; + } + if (member instanceof TemplatePool.Unreadable unreadable) { retryableFailure = true; - losses.add(StructureLoss.warning( - StructureCapability.LIST_ELEMENTS, - "pool_entry_not_imported", - "A source entry in pool " + poolKey + " could not be read: " + failureDetail(e)) - .affecting("jigsaw-pools/" + irisPoolName + ".json")); + losses.add(unreadableMemberLoss(unreadable, poolKey).affecting("jigsaw-pools/" + irisPoolName + ".json")); continue; } - if (element == null) { - continue; - } - PoolElementResolution elementResolution; - try { - elementResolution = resolvePoolElement(element); - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - losses.add(StructureLoss.warning( - StructureCapability.BLOCKS, - "template_location_not_imported", - "A source template location in pool " + poolKey + " could not be read: " + failureDetail(e)) - .affecting("jigsaw-pools/" + irisPoolName + ".json")); - continue; - } - if (elementResolution.omittedElements() > 0) { - losses.add(listElementFallbackLoss(elementResolution, poolKey) + TemplatePool.Element element = (TemplatePool.Element) member; + int weight = element.weight(); + if (element.omittedElements() > 0) { + losses.add(listElementFallbackLoss(element.listLevels(), element.omittedElements(), poolKey) .affecting("jigsaw-pools/" + irisPoolName + ".json")); } - Object physicalElement = elementResolution.physicalElement(); - String templateLocation = elementResolution.templateLocation(); - if (templateLocation == null) { - String elementType = physicalElement == null - ? element.getClass().getSimpleName() - : physicalElement.getClass().getSimpleName(); - if (elementType.endsWith("EmptyPoolElement")) { + if (element.template().isEmpty()) { + if (element.type().endsWith(EMPTY_POOL_ELEMENT_TYPE)) { pieceEntries.add(emptyPoolEntry(weight)); emittedPoolMembers++; } else { - StructureCapability unsupportedCapability = unsupportedCapability(elementType); + StructureCapability unsupportedCapability = unsupportedCapability(element.type()); losses.add(StructureLoss.warning( unsupportedCapability, "unsupported_pool_element", - "Skipped unsupported " + elementType + " in source pool " + poolKey + ".") + "Skipped unsupported " + element.type() + " in source pool " + poolKey + ".") .affecting("jigsaw-pools/" + irisPoolName + ".json")); } continue; } - NamespacedKey pieceNbtKey = NamespacedKey.fromString(templateLocation.toLowerCase()); - if (pieceNbtKey == null) { - fatalErrors.add("invalid piece key " + templateLocation + " in pool " + poolKey); - continue; - } + ResourceId pieceNbtKey = element.template().get(); + String templateLocation = pieceNbtKey.toString(); String irisPieceName = pieceName(name, templateLocation); ImportedTemplate importedTemplate = importedTemplates.get(irisPieceName); if (importedTemplate == null) { - Structure sourceTemplate; + Optional sourceTemplate; try { - sourceTemplate = Bukkit.getStructureManager().loadStructure(pieceNbtKey); + sourceTemplate = platform.template(pieceNbtKey); } catch (Throwable e) { - reportFailure(e); + reportFailure(pack, e); retryableFailure = true; fatalErrors.add(templateLocation + ": failed to load structure template: " + failureDetail(e)); continue; } - if (sourceTemplate == null || sourceTemplate.getPalettes().isEmpty()) { + if (sourceTemplate.isEmpty()) { fatalErrors.add(templateLocation + ": no loadable structure template was registered"); continue; } StructureImporter.CapturedStructure captured; try { - captured = StructureImporter.captureStructure(sourceTemplate); + captured = StructureImporter.captureStructure(sourceTemplate.get()); } catch (Throwable e) { - reportFailure(e); + reportFailure(pack, e); retryableFailure = true; fatalErrors.add(templateLocation + ": failed to capture structure template: " + failureDetail(e)); continue; } for (StructureLoss loss : captured.losses()) { - losses.add(loss.affecting("objects/" + irisPieceName + ".iob")); + losses.add(loss.affecting("objects/" + irisPieceName + pack.objects().extension())); } - Connectors result = readConnectors(element, structureManager, random, name, irisPieceName); + Connectors result = readConnectors(pack, element, random, name, irisPieceName); retryableFailure |= result.retryableFailure(); importedTemplate = new ImportedTemplate( captured.object(), @@ -383,9 +314,9 @@ public final class VillageImporter { try { StructureKey sourceKey = StructureKey.parse(structureKey.toString()); - StructureSource.Kind sourceKind = structureKey.getNamespace().equals("minecraft") + StructureSource.Kind sourceKind = structureKey.namespace().equals("minecraft") ? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK; - StructureSource source = new StructureSource(sourceKind, sourceKey, Bukkit.getBukkitVersion(), ""); + StructureSource source = new StructureSource(sourceKind, sourceKey, structure.gameVersion(), ""); Map objectResources = new LinkedHashMap<>(); for (Map.Entry entry : emittedObjects.entrySet()) { objectResources.put(entry.getKey(), serialize(entry.getValue())); @@ -407,21 +338,18 @@ public final class VillageImporter { StructureResourceBundleGraphCompiler.requireViable(bundle); StructureWriteMode writeMode = activeMode == StructureImporter.Mode.OVERWRITE ? StructureWriteMode.OVERWRITE : StructureWriteMode.ADD_ONLY; - StructureWriteResult writeResult = ownership.write(data, bundle, writeMode); - reportWriteFailure(writeResult); + StructureWriteResult writeResult = ownership.write(pack, bundle, writeMode); + reportWriteFailure(pack, writeResult); if (!writeResult.successful()) { return new Result(false, writeFailureMessage(name, writeResult), emittedPools.size(), emittedPieces.size(), losses, writeResult.failure().isPresent()); } - if (writeResult.committed()) { - data.invalidateStructureResources(); - } writeNote = writeResultNote(writeResult); } catch (StructureGraphValidationException e) { return new Result(false, "Failed writing jigsaw resources for '" + name + "': " + e.getMessage(), emittedPools.size(), emittedPieces.size(), losses, retryableFailure); } catch (Throwable e) { - reportFailure(e); + reportFailure(pack, e); return new Result(false, "Failed writing jigsaw resources for '" + name + "': " + e, emittedPools.size(), emittedPieces.size(), losses, true); } @@ -507,10 +435,23 @@ public final class VillageImporter { } } + private static StructureLoss unreadableMemberLoss(TemplatePool.Unreadable unreadable, String poolKey) { + if (unreadable.part() == TemplatePool.Part.ENTRY) { + return StructureLoss.warning( + StructureCapability.LIST_ELEMENTS, + "pool_entry_not_imported", + "A source entry in pool " + poolKey + " could not be read: " + unreadable.detail()); + } + return StructureLoss.warning( + StructureCapability.BLOCKS, + "template_location_not_imported", + "A source template location in pool " + poolKey + " could not be read: " + unreadable.detail()); + } + private static Connectors readConnectors( - Object element, - Object structureManager, - java.util.Random random, + ToolPack pack, + TemplatePool.Element element, + Random random, String baseName, String pieceName ) { @@ -520,10 +461,8 @@ public final class VillageImporter { boolean retryableFailure = false; String affectedResource = "jigsaw-pieces/" + pieceName + ".json"; try { - Object zero = staticField("net.minecraft.core.BlockPos", "ZERO"); - Object rotationNone = staticField("net.minecraft.world.level.block.Rotation", "NONE"); - Method m = findMethod4(element.getClass(), "getShuffledJigsawBlocks"); - if (m == null) { + TemplatePool.Connectors read = element.connectors().read(random::nextLong); + if (read.availability() == TemplatePool.Availability.UNAVAILABLE) { losses.add(StructureLoss.warning( StructureCapability.CONNECTORS, "connector_extraction_unavailable", @@ -531,10 +470,7 @@ public final class VillageImporter { .affecting(affectedResource)); return new Connectors(connectors, targets, losses, false); } - m.setAccessible(true); - Object random0 = freshRandomSource(random); - List blocks = (List) m.invoke(element, structureManager, zero, rotationNone, random0); - if (blocks == null) { + if (read.availability() == TemplatePool.Availability.NO_COLLECTION) { losses.add(StructureLoss.warning( StructureCapability.CONNECTORS, "connector_extraction_returned_null", @@ -542,26 +478,22 @@ public final class VillageImporter { .affecting(affectedResource)); return new Connectors(connectors, targets, losses, false); } - for (Object jigsaw : blocks) { - String[] rawPoolKey = new String[1]; - try { - Map connector = connectorFrom(jigsaw, baseName, rawPoolKey); - connectors.add(connector); - if (rawPoolKey[0] != null && !rawPoolKey[0].isEmpty()) { - targets.add(rawPoolKey[0]); - } - } catch (Throwable e) { - reportFailure(e); + for (TemplatePool.Connector connector : read.connectors()) { + if (connector instanceof TemplatePool.UnreadableConnector unreadable) { retryableFailure = true; losses.add(StructureLoss.warning( StructureCapability.CONNECTORS, "connector_not_imported", - "A source jigsaw connector could not be converted: " + failureDetail(e)) + "A source jigsaw connector could not be converted: " + unreadable.detail()) .affecting(affectedResource)); + continue; } + TemplatePool.JigsawConnector jigsaw = (TemplatePool.JigsawConnector) connector; + connectors.add(connectorJson(jigsaw, baseName)); + jigsaw.pool().ifPresent(pool -> targets.add(pool.toString())); } } catch (Throwable e) { - reportFailure(e); + reportFailure(pack, e); retryableFailure = true; losses.add(StructureLoss.warning( StructureCapability.CONNECTORS, @@ -572,474 +504,50 @@ public final class VillageImporter { return new Connectors(connectors, targets, losses, retryableFailure); } - private static Map connectorFrom(Object jigsaw, String baseName, String[] rawPoolKeyOut) throws Exception { - Object info = invoke(jigsaw, "info"); - Object pos = invoke(info, "pos"); - Object blockState = invoke(info, "state"); - int x = readInt(pos, "getX"); - int y = readInt(pos, "getY"); - int z = readInt(pos, "getZ"); - - Object poolKey = invoke(jigsaw, "pool"); - String poolId = identifierString(invoke(poolKey, "identifier")); - Object nameId = invoke(jigsaw, "name"); - Object targetId = invoke(jigsaw, "target"); - Object jointType = invoke(jigsaw, "jointType"); - - String front = frontFacing(blockState); - String top = topFacing(blockState); - rawPoolKeyOut[0] = poolId; - - ConnectorMetadata metadata = readConnectorMetadata(jigsaw, info); - return connectorJson( - x, - y, - z, - front, - top, - poolId, - baseName, - identifierString(nameId), - identifierString(targetId), - jointType, - metadata - ); - } - - static Map connectorJson( - int x, - int y, - int z, - String front, - String top, - String poolId, - String baseName, - String nameId, - String targetId, - Object jointType, - ConnectorMetadata metadata - ) { + static Map connectorJson(TemplatePool.JigsawConnector jigsaw, String baseName) { Map connector = new LinkedHashMap<>(); Map position = new LinkedHashMap<>(); - position.put("x", x); - position.put("y", y); - position.put("z", z); + position.put("x", jigsaw.position().x()); + position.put("y", jigsaw.position().y()); + position.put("z", jigsaw.position().z()); connector.put("position", position); - connector.put("direction", irisDirection(front)); - connector.put("top", irisDirection(top)); - connector.put("pool", poolId == null ? "" : poolName(baseName, poolId)); - connector.put("name", nameId); - connector.put("targetName", targetId); - connector.put("joint", jointType != null && jointType.toString().toUpperCase().contains("ALIGN") ? "ALIGNED" : "ROLLABLE"); - connector.put("finalState", metadata.finalState()); - connector.put("selectionPriority", metadata.selectionPriority()); - connector.put("placementPriority", metadata.placementPriority()); + connector.put("direction", irisDirection(jigsaw.front())); + connector.put("top", irisDirection(jigsaw.top())); + connector.put("pool", jigsaw.pool().map(pool -> poolName(baseName, pool.toString())).orElse("")); + connector.put("name", jigsaw.name()); + connector.put("targetName", jigsaw.target()); + connector.put("joint", jigsaw.aligned() ? "ALIGNED" : "ROLLABLE"); + connector.put("finalState", jigsaw.finalState() + .map(StructureImporter::normalizeJigsawFinalState) + .orElse(AIR_FINAL_STATE)); + connector.put("selectionPriority", jigsaw.selectionPriority()); + connector.put("placementPriority", jigsaw.placementPriority()); return connector; } - static ConnectorMetadata readConnectorMetadata(Object jigsaw, Object info) throws Exception { - Object nbt = invoke(info, "nbt"); - String finalState = readNbtString(nbt, "final_state"); - String normalizedFinalState = finalState == null || finalState.isBlank() - ? "minecraft:air" - : StructureImporter.normalizeJigsawFinalState(finalState); - return new ConnectorMetadata( - normalizedFinalState, - readIntAccessor(jigsaw, "selectionPriority"), - readIntAccessor(jigsaw, "placementPriority") - ); - } - - private static String readNbtString(Object nbt, String key) throws Exception { - if (nbt == null) { - return null; - } - Method method = 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 = 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 { - Class jigsawBlock = Class.forName("net.minecraft.world.level.block.JigsawBlock"); - Method getFront = jigsawBlock.getMethod("getFrontFacing", Class.forName("net.minecraft.world.level.block.state.BlockState")); - Object direction = getFront.invoke(null, blockState); - if (direction == null) { - return "north"; - } - Method getName = direction.getClass().getMethod("getName"); - getName.setAccessible(true); - return String.valueOf(getName.invoke(direction)).toLowerCase(); - } - - private static String topFacing(Object blockState) throws Exception { - Class jigsawBlock = Class.forName("net.minecraft.world.level.block.JigsawBlock"); - Method getTop = jigsawBlock.getMethod("getTopFacing", Class.forName("net.minecraft.world.level.block.state.BlockState")); - Object direction = getTop.invoke(null, blockState); - if (direction == null) { - return "up"; - } - Method getName = direction.getClass().getMethod("getName"); - getName.setAccessible(true); - return String.valueOf(getName.invoke(direction)).toLowerCase(); - } - - private static String irisDirection(String front) { + private static String irisDirection(BlockFace front) { return switch (front) { - case "up" -> "UP_POSITIVE_Y"; - case "down" -> "DOWN_NEGATIVE_Y"; - case "south" -> "SOUTH_POSITIVE_Z"; - case "east" -> "EAST_POSITIVE_X"; - case "west" -> "WEST_NEGATIVE_X"; + case UP -> "UP_POSITIVE_Y"; + case DOWN -> "DOWN_NEGATIVE_Y"; + case SOUTH -> "SOUTH_POSITIVE_Z"; + case EAST -> "EAST_POSITIVE_X"; + case WEST -> "WEST_NEGATIVE_X"; default -> "NORTH_NEGATIVE_Z"; }; } - private static String templateLocationOf(Object element) throws Exception { - Method m = findMethod(element.getClass(), "getTemplateLocation"); - if (m == null) { - return null; - } - m.setAccessible(true); - Object id = m.invoke(element); - return identifierString(id); - } - - static PoolElementResolution resolvePoolElement(Object element) throws Exception { - if (element == null) { - return new PoolElementResolution(null, null, 0, 0); - } - if (!element.getClass().getSimpleName().endsWith("ListPoolElement")) { - return new PoolElementResolution(element, templateLocationOf(element), 0, 0); - } - Object rawElements = 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 - ); - } - - static StructureLoss listElementFallbackLoss(PoolElementResolution resolution, String poolKey) { - int omitted = resolution.omittedElements(); + static StructureLoss listElementFallbackLoss(int listLevels, int omitted, String poolKey) { String elementLabel = omitted == 1 ? "element" : "elements"; - String levelLabel = resolution.listLevels() == 1 ? "list level" : "nested list levels"; + String levelLabel = listLevels == 1 ? "list level" : "nested list levels"; return StructureLoss.warning( StructureCapability.LIST_ELEMENTS, "list_pool_overlays_not_imported", "Converted the first physical template from a ListPoolElement in source pool " + poolKey + " and omitted " + omitted + " colocated " + elementLabel - + ", including their processors, across " + resolution.listLevels() + " " + levelLabel + "." + + ", including their processors, across " + listLevels + " " + levelLabel + "." ); } - private 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) { - reportFailure(e); - } - return null; - } - - private 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); - } - - private static Object registryGet(Object registry, NamespacedKey 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; - } - - private static Object registryGetByKey(Object registry, String key) throws Exception { - NamespacedKey nk = NamespacedKey.fromString(key.toLowerCase()); - if (nk == null) { - return null; - } - return registryGet(registry, nk); - } - - private 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; - } - - private static Object identifierOf(NamespacedKey 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.getNamespace(), key.getKey()); - } catch (NoSuchMethodException e) { - Method withDefaultNamespace = identifier.getMethod("parse", String.class); - return withDefaultNamespace.invoke(null, key.toString()); - } - } - - private 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(); - } - } - - private 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; - } - - private static Object unwrapOptional(Object opt) { - if (opt == null) { - return null; - } - if (opt instanceof java.util.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; - } - - private static int readInt(Object o, String method) throws Exception { - Method m = o.getClass().getMethod(method); - m.setAccessible(true); - return ((Number) m.invoke(o)).intValue(); - } - - private static Object staticField(String className, String fieldName) throws Exception { - Class c = Class.forName(className); - Field f = c.getField(fieldName); - return f.get(null); - } - - private 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); - } - - private static Method findMethod(Class type, String name) { - Class c = type; - while (c != null) { - for (Method m : c.getDeclaredMethods()) { - if (m.getName().equals(name) && m.getParameterCount() == 0) { - return m; - } - } - c = c.getSuperclass(); - } - for (Method m : type.getMethods()) { - if (m.getName().equals(name) && m.getParameterCount() == 0) { - return m; - } - } - return null; - } - - private static Method findMethod4(Class type, String name) { - return findMethod(type, name, 4); - } - - private 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; - } - - private static Object freshRandomSource(java.util.Random random) throws Exception { - Class randomSource = Class.forName("net.minecraft.util.RandomSource"); - Method create = randomSource.getMethod("create", long.class); - return create.invoke(null, random.nextLong()); - } - static String poolName(String base, String poolKey) { StructureKey key = StructureKey.parse(poolKey); return base + "/pool/" + key.namespace() + "/" + key.path(); @@ -1178,10 +686,10 @@ public final class VillageImporter { } private static StructureCapability unsupportedCapability(String elementType) { - if (elementType.endsWith("ListPoolElement")) { + if (elementType.endsWith(LIST_POOL_ELEMENT_TYPE)) { return StructureCapability.LIST_ELEMENTS; } - if (elementType.endsWith("FeaturePoolElement")) { + if (elementType.endsWith(FEATURE_POOL_ELEMENT_TYPE)) { return StructureCapability.FEATURE_ELEMENTS; } return StructureCapability.BLOCKS; @@ -1201,10 +709,8 @@ public final class VillageImporter { return new Result(false, message, 0, 0, losses, retryableFailure); } - private static void reportFailure(Throwable failure) { - IrisLogging.reportError(failure); - if (shouldPrintFullTrace(failure)) { - } + private static void reportFailure(ToolPack pack, Throwable failure) { + pack.log().error("Jigsaw structure import failed", failure); } /** @@ -1226,8 +732,8 @@ public final class VillageImporter { PRINTED_FAILURE_SIGNATURES.clear(); } - private static void reportWriteFailure(StructureWriteResult result) { - result.failure().ifPresent(VillageImporter::reportFailure); + private static void reportWriteFailure(ToolPack pack, StructureWriteResult result) { + result.failure().ifPresent(failure -> reportFailure(pack, failure)); } private static String writeResultNote(StructureWriteResult result) { @@ -1252,15 +758,4 @@ public final class VillageImporter { String message = failure.getMessage(); return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message; } - - record ConnectorMetadata(String finalState, int selectionPriority, int placementPriority) { - } - - record PoolElementResolution( - Object physicalElement, - String templateLocation, - int listLevels, - int omittedElements - ) { - } } diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java b/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java index c88879fb6..999cdb6ea 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java +++ b/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java @@ -16,8 +16,9 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetyp import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; @@ -379,19 +380,23 @@ final class VanillaJigsawExportCompiler { IrisObject object, List diagnostics ) { - if (!object.getStates().isEmpty()) { + IrisObject.ApiContents contents = object.apiContents(); + if (!contents.blockEntities().isEmpty()) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_TILE_DATA, pieceKey, "The .iob contains tile payloads; exact registry-aware block-entity NBT export is not available in core."); } - for (Map.Entry entry : object.getBlocks()) { - PlatformBlockState state = entry.getValue(); - String resource = pieceKey + "@" + entry.getKey(); - IrisBlockVector position = entry.getKey(); - int x = position.getBlockX() + object.getCenter().getX(); - int y = position.getBlockY() + object.getCenter().getY(); - int z = position.getBlockZ() + object.getCenter().getZ(); + for (Map.Entry entry : contents.blocks().entrySet()) { + BlockState state = entry.getValue(); + BlockPosition position = entry.getKey(); + String resource = pieceKey + "@" + new IrisBlockVector( + position.x() - object.getCenter().getX(), + position.y() - object.getCenter().getY(), + position.z() - object.getCenter().getZ()); + int x = position.x(); + int y = position.y(); + int z = position.z(); if (x < 0 || x >= object.getW() || y < 0 || y >= object.getH() || z < 0 || z >= object.getD()) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.INVALID_BLOCK_STATE, @@ -399,14 +404,14 @@ final class VanillaJigsawExportCompiler { "The .iob contains a block outside its declared dimensions."); continue; } - if (state.isCustom()) { + if (contents.customBlocks().contains(position)) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_CUSTOM_BLOCK, resource, "Custom-content block '" + state.key() + "' is not available in unmodded vanilla."); continue; } - if (state.hasTileEntity()) { + if (contents.blocksNeedingEntity().contains(position)) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_BLOCK_ENTITY, resource, @@ -442,6 +447,7 @@ final class VanillaJigsawExportCompiler { return; } Set positions = new LinkedHashSet<>(); + Map storedBlocks = object.apiContents().blocks(); for (int index = 0; index < piece.getConnectors().size(); index++) { IrisJigsawConnector connector = piece.getConnectors().get(index); if (connector == null) { @@ -482,7 +488,7 @@ final class VanillaJigsawExportCompiler { resource, "Multiple vanilla jigsaw block entities cannot occupy " + positionKey + "."); } - validateFinalState(object, connector, resource, diagnostics); + validateFinalState(storedBlocks, connector, resource, diagnostics); } } @@ -502,7 +508,7 @@ final class VanillaJigsawExportCompiler { } private void validateFinalState( - IrisObject object, + Map storedBlocks, IrisJigsawConnector connector, String resource, List diagnostics @@ -518,8 +524,7 @@ final class VanillaJigsawExportCompiler { return; } IrisPosition position = connector.getPosition(); - PlatformBlockState objectState = object.getBlocks().get( - object.getSigned(position.getX(), position.getY(), position.getZ())); + BlockState objectState = storedBlocks.get(new BlockPosition(position.getX(), position.getY(), position.getZ())); String expectedSource = objectState == null ? "minecraft:structure_void" : objectState.key(); try { VanillaBlockState expected = VanillaBlockState.parse(expectedSource); diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java b/core/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java index 130c15aaa..98ca1877f 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java +++ b/core/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java @@ -5,9 +5,6 @@ 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.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.nbt.io.NBTUtil; import art.arcane.volmlib.util.nbt.io.NamedTag; import art.arcane.volmlib.util.nbt.tag.CompoundTag; @@ -65,13 +62,8 @@ final class VanillaStructureTemplateEncoder { private Map objectBlocks(IrisObject object) { Map blocks = new LinkedHashMap<>(); - Vector3i center = object.getCenter(); - for (Map.Entry entry : object.getBlocks()) { - IrisBlockVector signed = entry.getKey(); - BlockPosition position = new BlockPosition( - signed.getBlockX() + center.getX(), - signed.getBlockY() + center.getY(), - signed.getBlockZ() + center.getZ()); + for (var entry : object.apiContents().blocks().entrySet()) { + BlockPosition position = new BlockPosition(entry.getKey().x(), entry.getKey().y(), entry.getKey().z()); VanillaBlockState state = VanillaBlockState.parse(entry.getValue().key()); blocks.put(position, new BlockEntry(position, state, null)); } diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/AdoptionCommands.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/AdoptionCommands.java new file mode 100644 index 000000000..b5df3d8c1 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/AdoptionCommands.java @@ -0,0 +1,345 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.structure.authoring.StructureKey; +import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest; +import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionDiagnostic; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionInputKind; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionPlan; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionRequest; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionResult; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionService; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionStrategy; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** {@code adopt}: inspects an Iris graph for safe Studio ownership adoption, then applies the inspected plan. */ +final class AdoptionCommands { + private static final Map ADOPTION_PLANS = new ConcurrentHashMap<>(); + private static final Map ADOPTION_SERVICES = new ConcurrentHashMap<>(); + private static final String AUTO = "auto"; + + private static final Argument SOURCE = Argument.word("source").describe("Existing Iris structure key"); + private static final Argument TARGET = Argument.word("target").orElse(AUTO) + .describe("New owned Iris key, or auto"); + private static final Argument STRATEGY = Argument.word("strategy").orElse(AUTO) + .describe("auto, in-place, or clone").suggesting(context -> List.of(AUTO, "in-place", "clone")); + private static final Argument PLAN = Argument.word("plan").describe("Plan UUID returned by adopt inspect"); + + private final Supplier> hosts; + + AdoptionCommands(Supplier> hosts) { + this.hosts = hosts; + } + + Command command() { + return Command.named("adopt").describe("Inspect and apply safe ownership adoption plans") + .child(Command.named("inspect").describe("Inspect an Iris graph for safe Studio ownership adoption") + .argument(SOURCE).argument(TARGET).argument(STRATEGY) + .runs(this::inspect)) + .child(Command.named("apply").describe("Apply one inspected adoption plan without overwriting") + .argument(PLAN).runs(this::apply)); + } + + private void inspect(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + IrisData data = use.host().dataOf(context.pack()); + String sourceKey; + Optional targetKey; + IrisStructureAdoptionStrategy adoptionStrategy; + Path root; + try { + sourceKey = parseAdoptionSource(context.get(SOURCE)); + targetKey = parseAdoptionTarget(context.get(TARGET)); + adoptionStrategy = parseAdoptionStrategy(context.get(STRATEGY)); + root = canonicalAdoptionRoot(data.getDataFolder().toPath()); + } catch (IOException | IllegalArgumentException exception) { + use.error("Could not inspect adoption source: " + exception.getMessage()); + return; + } + UUID ownerId = use.player().id(); + use.say(TextColor.GRAY, "Inspecting Jigsaw adoption source '" + sourceKey + "' asynchronously..."); + runAdoptionInspect(use, ownerId, data, root, sourceKey, targetKey, adoptionStrategy); + } + + private void apply(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + UUID parsedPlanId; + try { + parsedPlanId = UUID.fromString(context.get(PLAN)); + } catch (IllegalArgumentException exception) { + use.error("Adoption plan ID must be a UUID."); + return; + } + if (studioIsActiveOrOpening(use)) { + use.error("Close the active or opening Jigsaw Studio before applying an adoption plan."); + return; + } + pruneAdoptionPlanBindings(); + AdoptionPlanBinding binding = ADOPTION_PLANS.get(parsedPlanId); + UUID playerId = use.player().id(); + if (binding == null || !binding.ownerId().equals(playerId)) { + use.error("No active adoption plan '" + parsedPlanId + + "' belongs to your player session. Run adopt inspect again."); + return; + } + if (binding.service().plan(parsedPlanId).isEmpty()) { + ADOPTION_PLANS.remove(parsedPlanId, binding); + use.error("Adoption plan '" + parsedPlanId + + "' expired or was already consumed. Run adopt inspect again."); + return; + } + if (!ADOPTION_PLANS.remove(parsedPlanId, binding)) { + use.error("Adoption plan '" + parsedPlanId + "' is already being applied."); + return; + } + use.say(TextColor.GRAY, "Applying adoption plan '" + parsedPlanId + + "' asynchronously without overwrite..."); + runAdoptionApply(use, parsedPlanId, binding); + } + + private static void pruneAdoptionPlanBindings() { + for (Map.Entry entry : ADOPTION_PLANS.entrySet()) { + AdoptionPlanBinding binding = entry.getValue(); + if (binding.service().plan(entry.getKey()).isEmpty()) { + ADOPTION_PLANS.remove(entry.getKey(), binding); + } + } + } + + private static boolean studioIsActiveOrOpening(StudioUse use) { + return use.registry().activeOwnerId() != null + || use.registry().openingOwnerId() != null; + } + + private static void runAdoptionApply(StudioUse use, UUID planId, AdoptionPlanBinding binding) { + if (studioIsActiveOrOpening(use)) { + ADOPTION_PLANS.putIfAbsent(planId, binding); + use.error("Close the active or opening Jigsaw Studio before applying an adoption plan."); + return; + } + IrisStructureAdoptionResult result; + Throwable failure = null; + try { + result = binding.service().apply(binding.plan()); + } catch (Throwable throwable) { + result = null; + failure = throwable; + binding.pack().log().error("Failed to apply Jigsaw adoption plan '" + planId + "'.", throwable); + } + finishAdoptionApply(use, binding, result, failure); + } + + private static void runAdoptionInspect( + StudioUse use, + UUID ownerId, + IrisData data, + Path root, + String sourceKey, + Optional targetKey, + IrisStructureAdoptionStrategy strategy + ) { + IrisStructureAdoptionService service = null; + IrisStructureAdoptionPlan plan = null; + Throwable failure = null; + try { + IrisStructureAdoptionInputKind inputKind = adoptionInputKind(root, sourceKey); + service = ADOPTION_SERVICES.computeIfAbsent(root, IrisStructureAdoptionService::new); + plan = service.inspect(new IrisStructureAdoptionRequest( + sourceKey, + targetKey, + strategy, + inputKind)); + } catch (Throwable throwable) { + failure = throwable; + use.pack().log().error("Failed to inspect Jigsaw adoption source '" + sourceKey + "'.", throwable); + } + finishAdoptionInspect(use, ownerId, data, service, plan, failure); + } + + private static void finishAdoptionInspect( + StudioUse use, + UUID ownerId, + IrisData data, + IrisStructureAdoptionService service, + IrisStructureAdoptionPlan plan, + Throwable failure + ) { + if (failure != null || service == null || plan == null) { + use.error("Jigsaw adoption inspection failed: " + + (failure == null ? "no result" : failure.getMessage())); + return; + } + pruneAdoptionPlanBindings(); + if (service.plan(plan.planId()).isPresent()) { + ADOPTION_PLANS.put(plan.planId(), new AdoptionPlanBinding( + ownerId, use.pack(), data, service, plan)); + } + reportAdoptionPlan(use, plan); + } + + private static void finishAdoptionApply( + StudioUse use, + AdoptionPlanBinding binding, + IrisStructureAdoptionResult result, + Throwable failure + ) { + if (failure != null || result == null) { + use.error("Jigsaw adoption failed: " + (failure == null ? "no result" : failure.getMessage())); + return; + } + reportAdoptionResult(use, result); + if (!result.successful()) { + return; + } + StructureKey target = result.receipt().orElseThrow().targetStructure(); + binding.data().invalidateStructureResources(); + StudioLifecycleCommands.openProject(use.onPack(binding.pack()), target.path()); + } + + private static void reportAdoptionPlan(StudioUse use, IrisStructureAdoptionPlan plan) { + use.say(plan.canApply() ? TextColor.GREEN : TextColor.RED, + "Adoption plan " + plan.planId() + " -> " + + plan.disposition() + " for " + plan.targetStructure().value() + "."); + use.say(TextColor.GRAY, "Resources=" + plan.resourceCount() + + ", bytes=" + plan.totalSourceBytes() + + ", errors=" + plan.errorCount() + + ", warnings=" + plan.warningCount() + "."); + for (IrisStructureAdoptionDiagnostic diagnostic : plan.diagnostics()) { + use.say(adoptionColor(diagnostic), diagnostic.summary()); + } + if (plan.canApply()) { + use.say(TextColor.AQUA, "Apply with /iris jigsaw adopt apply " + plan.planId()); + } + } + + private static void reportAdoptionResult(StudioUse use, IrisStructureAdoptionResult result) { + use.say(result.successful() ? TextColor.GREEN : TextColor.RED, + "Adoption plan " + result.planId() + ": " + result.status() + "."); + for (IrisStructureAdoptionDiagnostic diagnostic : result.diagnostics()) { + use.say(adoptionColor(diagnostic), diagnostic.summary()); + } + } + + private static TextColor adoptionColor(IrisStructureAdoptionDiagnostic diagnostic) { + return switch (diagnostic.severity()) { + case ERROR -> TextColor.RED; + case WARNING -> TextColor.YELLOW; + case INFO -> TextColor.GRAY; + }; + } + + static String parseAdoptionSource(String value) { + String normalized = Objects.requireNonNull(value, "Adoption source").trim() + .toLowerCase(Locale.ROOT); + StructureKey source = StructureKey.parse(normalized, "iris"); + if (!"iris".equals(source.namespace())) { + throw new IllegalArgumentException("Adoption sources must use the iris namespace."); + } + return source.path(); + } + + static Optional parseAdoptionTarget(String value) { + String normalized = Objects.requireNonNull(value, "Adoption target").trim() + .toLowerCase(Locale.ROOT); + if (normalized.isEmpty() || AUTO.equals(normalized)) { + return Optional.empty(); + } + StructureKey target = StructureKey.parse(normalized, "iris"); + if (!"iris".equals(target.namespace())) { + throw new IllegalArgumentException("Adoption targets must use the iris namespace."); + } + return Optional.of(target); + } + + static IrisStructureAdoptionStrategy parseAdoptionStrategy(String value) { + return switch (Objects.requireNonNull(value, "Adoption strategy").trim().toLowerCase(Locale.ROOT)) { + case AUTO -> IrisStructureAdoptionStrategy.AUTO; + case "in-place", "in_place", "inplace", "claim" -> IrisStructureAdoptionStrategy.IN_PLACE; + case "clone", "copy" -> IrisStructureAdoptionStrategy.CLONE; + default -> throw new IllegalArgumentException("Adoption strategy must be auto, in-place, or clone."); + }; + } + + static IrisStructureAdoptionInputKind adoptionInputKind(Path packRoot, String source) throws IOException { + Path root = canonicalAdoptionRoot(packRoot); + StructureKey sourceKey = new StructureKey("iris", parseAdoptionSource(source)); + Path manifestPath = new StructureTransactionWriter(root).ownershipManifestPath(sourceKey); + if (!Files.exists(manifestPath, LinkOption.NOFOLLOW_LINKS)) { + return IrisStructureAdoptionInputKind.UNOWNED_IRIS; + } + if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Ownership manifest is not a regular file: " + manifestPath); + } + StructureOwnershipManifest manifest; + try { + manifest = StructureOwnershipManifest.fromJson(Files.readAllBytes(manifestPath)); + } catch (RuntimeException exception) { + throw new IOException("Invalid ownership manifest at " + manifestPath, exception); + } + if (!manifest.structure().equals(sourceKey)) { + throw new IOException("Ownership manifest at " + manifestPath + + " belongs to " + manifest.structure().value()); + } + return manifest.provenance().origin() == StructureOwnershipManifest.Origin.MANAGED_DATAPACK + ? IrisStructureAdoptionInputKind.MANAGED_DATAPACK + : IrisStructureAdoptionInputKind.UNOWNED_IRIS; + } + + private static Path canonicalAdoptionRoot(Path packRoot) throws IOException { + Path normalized = Objects.requireNonNull(packRoot, "Adoption pack root").toAbsolutePath().normalize(); + return Files.exists(normalized, LinkOption.NOFOLLOW_LINKS) ? normalized.toRealPath() : normalized; + } + + private record AdoptionPlanBinding( + UUID ownerId, + ToolPack pack, + IrisData data, + IrisStructureAdoptionService service, + IrisStructureAdoptionPlan plan + ) { + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/GraphEditCommands.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/GraphEditCommands.java new file mode 100644 index 000000000..f1ae64d37 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/GraphEditCommands.java @@ -0,0 +1,792 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphEditor; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPoolEditor; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioStructureEditor; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.tooling.GraphMutations.PieceWorkcellResolution; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import art.arcane.iris.engine.object.value.IrisPosition; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.world.ToolWorld; + +import java.io.IOException; +import java.util.Optional; +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; + +import static art.arcane.iris.core.structure.tooling.GraphMutations.loadPersistedLayout; +import static art.arcane.iris.core.structure.tooling.GraphMutations.mappedMutationResult; +import static art.arcane.iris.core.structure.tooling.GraphMutations.runGraphMutation; +import static art.arcane.iris.core.structure.tooling.StudioUse.selectedBay; +import static art.arcane.iris.core.structure.tooling.StudioUse.selectedVariant; + +/** The commands that edit the open graph: connectors, pools, pieces, workcells, variants, the rules and the preview. */ +final class GraphEditCommands { + private static final String NONE = "none"; + private static final String JIGSAW_BLOCK = "minecraft:jigsaw"; + private static final int CONNECTOR_REACH_BLOCKS = 8; + private static final int VANILLA_PORTABLE_MAX_DEPTH = 20; + private static final int VANILLA_PORTABLE_MAX_SIZE_CHUNKS = 8; + private static final String NEXT = "next"; + + private static final Argument CHANNEL = Argument.word("channel").describe("Exact channel, or none to clear"); + private static final Argument NEW_POOL = Argument.word("poolKey").describe("New owned pool resource key"); + private static final Argument NEW_POOL_FALLBACK = Argument.word("fallbackPoolKey").orElse(NONE) + .describe("Owned fallback pool key, or none"); + private static final Argument OWNED_POOL = Argument.word("poolKey").describe("Owned pool resource key"); + private static final Argument NEW_PIECE = Argument.word("pieceKey").describe("New owned piece and object key"); + private static final Argument EXISTING_PIECE = Argument.word("pieceKey").describe("Existing jigsaw piece key"); + private static final Argument OPTIONAL_WEIGHT = weight().orElse(1L); + private static final Argument ROTATABLE = Argument.flag("rotatable") + .describe("Whether the selected piece may rotate"); + private static final Argument CAPACITY_WIDTH = size("width", "Capacity width"); + private static final Argument CAPACITY_HEIGHT = size("height", "Capacity height"); + private static final Argument CAPACITY_DEPTH = size("depth", "Capacity depth"); + private static final Argument LABEL = Argument.word("displayName") + .describe("Display label; quote labels containing spaces"); + private static final Argument VARIANT_POOL = Argument.word("poolKey").describe("Pool resource key"); + private static final Argument REQUIRED_WEIGHT = weight(); + private static final Argument VARIANT_WIDTH = size("width", "Variant width"); + private static final Argument VARIANT_HEIGHT = size("height", "Variant height"); + private static final Argument VARIANT_DEPTH = size("depth", "Variant depth"); + private static final Argument THEME_KEY = Argument.word("themeKey").orElse(NEXT) + .describe("Family key or next"); + private static final Argument MAX_DEPTH = Argument.integer("maxDepth", Integer.MIN_VALUE, Integer.MAX_VALUE) + .describe("Maximum expansion depth"); + private static final Argument MAX_SIZE_CHUNKS = Argument.integer("maxSizeChunks", Integer.MIN_VALUE, Integer.MAX_VALUE) + .describe("Maximum radius in chunks"); + private static final Argument FALLBACK_POOL = Argument.word("fallbackPoolKey") + .describe("Owned fallback pool key, or none"); + private static final Argument ASSEMBLY_SEED = Argument.integer("seed", Long.MIN_VALUE, Long.MAX_VALUE) + .orElse(StudioLifecycleCommands.DEFAULT_STUDIO_SEED).describe("Assembly seed"); + + private final Supplier> hosts; + + GraphEditCommands(Supplier> hosts) { + this.hosts = hosts; + } + + Command connector() { + return Command.named("connector").describe("Inspect and configure targeted jigsaw connectors") + .child(Command.named("channel").describe("Set the Iris-only channel on the targeted jigsaw marker") + .argument(CHANNEL).runs(this::connectorChannel)); + } + + Command pool() { + return Command.named("pool").describe("Manage owned jigsaw pools") + .child(Command.named("create").describe("Create an empty owned jigsaw pool") + .argument(NEW_POOL).argument(NEW_POOL_FALLBACK).runs(this::poolCreate)); + } + + Command piece() { + return Command.named("piece").describe("Manage contextual Studio pieces") + .child(Command.named("create").describe("Create an owned piece from the selected Studio topology") + .argument(OWNED_POOL).argument(NEW_PIECE).argument(OPTIONAL_WEIGHT).runs(this::pieceCreate)) + .child(Command.named("add").describe("Add an existing jigsaw piece to an owned pool transactionally") + .argument(OWNED_POOL).argument(EXISTING_PIECE).argument(OPTIONAL_WEIGHT).runs(this::pieceAdd)) + .child(Command.named("remove").describe("Remove the selected piece from an owned pool transactionally") + .argument(OWNED_POOL).runs(this::pieceRemove)) + .child(Command.named("rotatable").describe("Allow or forbid cardinal rotation of the selected piece") + .argument(ROTATABLE).runs(this::pieceRotatable)) + .child(Command.named("expand").describe("Resize the selected piece object exactly to workcell capacity") + .runs(this::pieceExpand)); + } + + Command workcell() { + return Command.named("workcell").describe("Manage the selected Studio workcell") + .child(Command.named("capacity").describe("Set capacity without resizing any variant object") + .argument(CAPACITY_WIDTH).argument(CAPACITY_HEIGHT).argument(CAPACITY_DEPTH) + .runs(this::workcellCapacity)) + .child(Command.named("label").describe("Set the selected workcell's author-facing label") + .argument(LABEL).runs(this::workcellLabel)) + .child(Command.named("label-reset").alias("reset-label") + .describe("Reset the selected workcell to its canonical solver label") + .runs(this::workcellLabelReset)); + } + + Command variant() { + return Command.named("variant").describe("Manage selected jigsaw variants") + .child(Command.named("weight").describe("Set the selected piece weight in a pool") + .argument(VARIANT_POOL).argument(REQUIRED_WEIGHT).runs(this::variantWeight)) + .child(Command.named("resize").describe("Resize only the active variant object within workcell capacity") + .argument(VARIANT_WIDTH).argument(VARIANT_HEIGHT).argument(VARIANT_DEPTH).runs(this::variantResize)) + .child(Command.named("label").describe("Set the active variant's author-facing label") + .argument(LABEL).runs(this::variantLabel)) + .child(Command.named("label-reset").alias("reset-label") + .describe("Reset the active variant to its resource-key label").runs(this::variantLabelReset)) + .child(Command.named("duplicate").describe("Duplicate the active variant in only this workcell") + .runs(this::variantDuplicate)) + .child(Command.named("duplicate-family").alias("family") + .describe("Duplicate every enabled workcell's active variant as one coherent family") + .argument(THEME_KEY).runs(this::variantDuplicateFamily)); + } + + Command rules() { + return Command.named("rules").alias("rule").describe("Manage structure-wide jigsaw rules") + .child(Command.named("limits").describe("Set maximum expansion depth and horizontal radius") + .argument(MAX_DEPTH).argument(MAX_SIZE_CHUNKS).runs(this::rulesLimits)) + .child(Command.named("fallback").describe("Set or clear one owned pool's direct fallback") + .argument(OWNED_POOL).argument(FALLBACK_POOL).runs(this::rulesFallback)); + } + + Command preview() { + return Command.named("preview").describe("Assemble a read-only jigsaw preview") + .child(Command.named("goto").alias("teleport").describe("Teleport to the live seed-1337 preview") + .runs(this::previewGoto)) + .child(Command.named("assemble").describe("Assemble a deterministic preview at your location") + .argument(ASSEMBLY_SEED).runs(this::previewAssemble)); + } + + private static Argument weight() { + return Argument.integer("weight", Integer.MIN_VALUE, Integer.MAX_VALUE).describe("Positive selection weight"); + } + + private static Argument size(String name, String description) { + return Argument.integer(name, Integer.MIN_VALUE, Integer.MAX_VALUE).describe(description); + } + + private static JigsawStudioCellDimensions dimensions(long width, long height, long depth) { + return new JigsawStudioCellDimensions((int) width, (int) height, (int) depth); + } + + private void connectorChannel(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + BlockPosition target = targetedJigsawMarker(use); + if (target == null) { + use.error("Look directly at a jigsaw marker within eight blocks."); + return; + } + var bay = active.session().layout().findAt(target.x(), target.y(), target.z()); + JigsawStudioVariant activeVariant = bay == null + ? null + : active.session().activeVariant(bay.stableId()).orElse(null); + if (activeVariant == null) { + use.error("The targeted marker must be inside a workcell with an active variant."); + return; + } + if (!activeVariant.owned()) { + use.error("The active variant is read-only. Adopt it into this project before editing it."); + return; + } + IrisObject object = active.request().source().getObjectLoader().load(activeVariant.objectKey()); + if (object == null) { + use.error("The active variant object '" + activeVariant.objectKey() + "' is missing."); + return; + } + IrisPosition canonicalPosition = new IrisPosition( + target.x() - bay.bounds().originX(), + target.y() - bay.bounds().originY(), + target.z() - bay.bounds().originZ()); + IrisPosition position; + try { + position = activeVariant.canonicalToSourcePosition( + canonicalPosition, + new JigsawStudioCellDimensions(object.getW(), object.getH(), object.getD())); + } catch (IllegalArgumentException exception) { + use.error("Connector channel update failed: " + exception.getMessage()); + return; + } + String channel = context.get(CHANNEL); + String normalized = channel == null || channel.isBlank() || NONE.equalsIgnoreCase(channel) + ? NONE + : channel.trim(); + runGraphMutation(use, active, () -> { + JigsawStudioGraphEditor.updateConnectorChannel( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + activeVariant.pieceKey(), + position, + channel); + return mappedMutationResult( + active, + "", + "", + "Persisted connector channel '" + normalized + "' on piece '" + + activeVariant.pieceKey() + "' at " + position.getX() + "," + position.getY() + + "," + position.getZ() + "."); + }); + } + + /** Where the player looks when it is a jigsaw marker within reach; null otherwise. */ + private static BlockPosition targetedJigsawMarker(StudioUse use) { + Optional target = use.readFromPlayer(() -> use.player().targetBlock(CONNECTOR_REACH_BLOCKS)); + Optional world = use.readFromPlayer(() -> use.player().world()); + if (target.isEmpty() || world.isEmpty()) { + return null; + } + try { + boolean marker = world.get().call(target.get(), () -> world.get().block(target.get())) + .get().material().toString().equals(JIGSAW_BLOCK); + return marker ? target.get() : null; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return null; + } catch (ExecutionException failure) { + return null; + } + } + + private void poolCreate(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(NEW_POOL); + String fallbackPoolKey = context.get(NEW_POOL_FALLBACK); + String fallback = NONE.equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey; + runGraphMutation(use, active, () -> { + JigsawStudioGraphEditor.createPool( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + poolKey, + fallback); + return mappedMutationResult( + active, + "", + "", + "Created owned pool '" + poolKey + "' with fallback '" + + (fallback.isBlank() ? NONE : fallback) + "'."); + }); + } + + private void pieceCreate(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(OWNED_POOL); + String pieceKey = context.get(NEW_PIECE); + int weight = context.get(OPTIONAL_WEIGHT).intValue(); + JigsawPlanarTopology topology = null; + JigsawStudioBay targetWorkcell = active.session().layout().get(JigsawStudioLayout.SPATIAL_WORKCELL_ID); + if (active.session().layout().mode() == JigsawStudioMode.PLANAR_JIGSAW) { + BlockPosition location = use.readFromPlayer(use.player()::position); + JigsawStudioBay contextual = active.session().layout().findAt(location.x(), location.y(), location.z()); + if (contextual == null) { + contextual = selectedBay(active); + } else { + active.session().selectBay(contextual.stableId()); + } + if (contextual == null || contextual.topology().isEmpty()) { + use.error("Stand in or select a planar topology workcell before creating a variant."); + return; + } + topology = contextual.topology().get(); + targetWorkcell = contextual; + } + if (targetWorkcell == null) { + use.error("The selected Jigsaw Studio workcell is no longer available."); + return; + } + JigsawPlanarTopology selectedTopology = topology; + String activationWorkcellId = targetWorkcell.stableId(); + JigsawStudioCellDimensions dimensions = targetWorkcell.capacity(); + String topologyText = selectedTopology == null ? "blank spatial" : selectedTopology.name(); + runGraphMutation(use, active, () -> { + JigsawStudioGraphEditor.createPiece( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + poolKey, + pieceKey, + weight, + dimensions, + selectedTopology); + return mappedMutationResult( + active, + activationWorkcellId, + pieceKey, + "Created owned " + topologyText + " piece '" + pieceKey + + "' and added it to pool '" + poolKey + "' atomically."); + }); + } + + private void pieceAdd(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(OWNED_POOL); + String pieceKey = context.get(EXISTING_PIECE); + int weight = context.get(OPTIONAL_WEIGHT).intValue(); + IrisJigsawPiece piece = StructureResources.piece(active.request().source().getPackResources(), pieceKey); + if (piece == null) { + use.error("No jigsaw piece '" + pieceKey + "' exists in this pack."); + return; + } + if (piece.getObject() == null || piece.getObject().isBlank()) { + use.error("Jigsaw piece '" + pieceKey + "' does not declare an object."); + return; + } + IrisObject object = active.request().source().getObjectLoader().load(piece.getObject()); + if (object == null) { + use.error("Jigsaw piece '" + pieceKey + "' has no loadable object."); + return; + } + PieceWorkcellResolution resolution; + try { + resolution = GraphMutations.resolvePieceWorkcell(active.session().layout(), piece, object); + } catch (IllegalArgumentException exception) { + use.error("Jigsaw piece '" + pieceKey + "' cannot be assigned to a Studio workcell: " + + exception.getMessage()); + return; + } + if (!resolution.fits()) { + IrisPosition required = resolution.requiredDimensions(); + JigsawStudioCellDimensions capacity = resolution.workcell().capacity(); + use.error("Jigsaw piece '" + pieceKey + "' requires " + required.getX() + "x" + + required.getY() + "x" + required.getZ() + " in " + resolution.workcell().displayName() + + ", but that workcell capacity is " + capacity.width() + "x" + capacity.height() + + "x" + capacity.depth() + "."); + return; + } + String objectKey = piece.getObject(); + runGraphMutation(use, active, () -> { + if (!JigsawStudioGraphEditor.ownsPiece( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + pieceKey, + objectKey)) { + throw new IOException("Piece add accepts only piece/object resources already owned by this project; " + + "use piece create for a new owned piece"); + } + JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.addPiece( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + poolKey, + pieceKey, + weight); + if (!update.changed()) { + throw new IOException("The owned pool is missing or already references '" + pieceKey + "'"); + } + JigsawStudioLayout layout = loadPersistedLayout(active); + String activationWorkcellId = GraphMutations.workcellIdForVariant(layout, pieceKey); + return new JigsawStudioService.CommandGraphMutationResult( + layout, + activationWorkcellId, + pieceKey, + "Added '" + pieceKey + "' to pool '" + poolKey + "' in one graph transaction."); + }); + } + + private void pieceRemove(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(OWNED_POOL); + JigsawStudioVariant selected = selectedVariant(active); + if (selected == null) { + use.error("Select a workcell with an active variant before removing its pool entry."); + return; + } + String pieceKey = selected.pieceKey(); + runGraphMutation(use, active, () -> { + JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.removePiece( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + poolKey, + pieceKey); + if (!update.changed()) { + throw new IOException("The owned pool does not reference selected piece '" + pieceKey + "'"); + } + return mappedMutationResult( + active, + "", + "", + "Removed '" + pieceKey + "' from pool '" + poolKey + "' in one graph transaction."); + }); + } + + private void pieceRotatable(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + boolean rotatable = context.get(ROTATABLE); + JigsawStudioVariant selected = selectedVariant(active); + if (selected == null) { + use.error("Select a workcell with an active variant before changing rotation."); + return; + } + if (!rotatable + && active.request().compatibilityTarget() + == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE) { + use.error("Vanilla-portable pieces must remain rotatable."); + return; + } + String pieceKey = selected.pieceKey(); + runGraphMutation(use, active, () -> { + JigsawStudioGraphEditor.updateRotatable( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + pieceKey, + rotatable); + return mappedMutationResult( + active, + "", + "", + "Persisted piece '" + pieceKey + "' rotatable=" + rotatable + "."); + }); + } + + private void pieceExpand(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay workcell = selectedBay(active); + if (workcell == null) { + use.error("Select a workcell before expanding its active variant."); + return; + } + use.onPlayer(() -> use.studio().expandVariantToCell(use.player(), workcell.stableId())); + } + + private void workcellCapacity(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selected = selectedBay(active); + if (selected == null) { + use.error("Select a workcell before changing its capacity."); + return; + } + JigsawStudioCellDimensions dimensions; + try { + dimensions = dimensions(context.get(CAPACITY_WIDTH), context.get(CAPACITY_HEIGHT), context.get(CAPACITY_DEPTH)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + use.onPlayer(() -> use.studio().updateWorkcellDimensions(use.player(), selected.stableId(), dimensions)); + } + + private void workcellLabel(CommandContext context) { + renameWorkcell(context, "Select a workcell before renaming it.", LABEL); + } + + private void workcellLabelReset(CommandContext context) { + renameWorkcell(context, "Select a workcell before resetting its label.", null); + } + + /** Names the selected workcell by {@code label}, or resets its label when there is none. */ + private void renameWorkcell(CommandContext context, String noSelectionMessage, Argument label) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selected = selectedBay(active); + if (selected == null) { + use.error(noSelectionMessage); + return; + } + String displayName = label == null ? "" : context.get(label); + use.onPlayer(() -> use.studio().updateWorkcellDisplayName(use.player(), selected.stableId(), displayName)); + } + + private void variantWeight(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(VARIANT_POOL); + int weight = context.get(REQUIRED_WEIGHT).intValue(); + JigsawStudioVariant selected = selectedVariant(active); + if (selected == null) { + use.error("Select a workcell with an active variant before changing its weight."); + return; + } + String pieceKey = selected.pieceKey(); + runGraphMutation(use, active, () -> { + JigsawStudioPoolEditor.WeightUpdate update = JigsawStudioPoolEditor.updateWeight( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + poolKey, + pieceKey, + weight); + if (!update.changed()) { + throw new IOException("Pool '" + poolKey + "' does not reference selected piece '" + + pieceKey + "'"); + } + return mappedMutationResult( + active, + "", + "", + "Updated " + update.changedEntries() + " pool entry weight atomically in " + + update.poolPath() + "."); + }); + } + + private void variantResize(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selectedWorkcell = selectedBay(active); + JigsawStudioVariant selectedVariant = selectedVariant(active); + if (selectedWorkcell == null || selectedVariant == null) { + use.error("Select a workcell with an active variant before resizing it."); + return; + } + JigsawStudioCellDimensions dimensions; + try { + dimensions = dimensions(context.get(VARIANT_WIDTH), context.get(VARIANT_HEIGHT), context.get(VARIANT_DEPTH)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + use.onPlayer(() -> use.studio().resizeVariant( + use.player(), + selectedWorkcell.stableId(), + selectedVariant.pieceKey(), + dimensions)); + } + + private void variantLabel(CommandContext context) { + renameVariant(context, "Select a workcell with an active variant before renaming it.", LABEL); + } + + private void variantLabelReset(CommandContext context) { + renameVariant(context, "Select a workcell with an active variant before resetting its label.", null); + } + + /** Names the active variant by {@code label}, or resets its label when there is none. */ + private void renameVariant(CommandContext context, String noSelectionMessage, Argument label) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selectedWorkcell = selectedBay(active); + JigsawStudioVariant selectedVariant = selectedVariant(active); + if (selectedWorkcell == null || selectedVariant == null) { + use.error(noSelectionMessage); + return; + } + String displayName = label == null ? "" : context.get(label); + use.onPlayer(() -> use.studio().updateVariantDisplayName( + use.player(), + selectedWorkcell.stableId(), + selectedVariant.pieceKey(), + displayName)); + } + + private void variantDuplicate(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selected = selectedBay(active); + if (selected == null || selectedVariant(active) == null) { + use.error("Select a workcell with an active variant before duplicating it."); + return; + } + use.onPlayer(() -> use.studio().createVariant(use.player(), selected.stableId(), true)); + } + + private void variantDuplicateFamily(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String themeKey = context.get(THEME_KEY); + String selectedTheme = themeKey; + if (NEXT.equalsIgnoreCase(themeKey)) { + try { + selectedTheme = GraphMutations.nextThemeKey(active); + } catch (IOException | ArithmeticException exception) { + use.error(exception.getMessage()); + return; + } + } + String familyKey = selectedTheme; + use.onPlayer(() -> use.studio().duplicateActiveFamily(use.player(), familyKey)); + } + + private void rulesLimits(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + int maxDepth = context.get(MAX_DEPTH).intValue(); + int maxSizeChunks = context.get(MAX_SIZE_CHUNKS).intValue(); + if (active.request().compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE + && (maxDepth > VANILLA_PORTABLE_MAX_DEPTH || maxSizeChunks > VANILLA_PORTABLE_MAX_SIZE_CHUNKS)) { + use.error("Vanilla-portable rules require maxDepth <= 20 and maxSizeChunks <= 8."); + return; + } + runGraphMutation(use, active, () -> { + JigsawStudioStructureEditor.updateLimits( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + maxDepth, + maxSizeChunks); + return mappedMutationResult( + active, + "", + "", + "Persisted jigsaw limits: maxDepth=" + maxDepth + + ", maxSizeChunks=" + maxSizeChunks + "."); + }); + } + + private void rulesFallback(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(OWNED_POOL); + String fallbackPoolKey = context.get(FALLBACK_POOL); + String fallback = NONE.equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey; + runGraphMutation(use, active, () -> { + JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.updateFallback( + active.request().source().getDataFolder().toPath(), + active.request().structureKey(), + poolKey, + fallback); + if (!update.changed()) { + return mappedMutationResult(active, "", "", "Pool fallback is unchanged."); + } + return mappedMutationResult( + active, + "", + "", + "Persisted pool '" + poolKey + "' fallback as '" + + (fallback.isBlank() ? NONE : fallback) + "'."); + }); + } + + private void previewGoto(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + use.onPlayer(() -> use.studio().goToPreview(use.player())); + } + + private void previewAssemble(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + long seed = context.get(ASSEMBLY_SEED); + use.onPlayer(() -> use.studio().previewStudio(use.player(), seed)); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/GraphMutations.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/GraphMutations.java new file mode 100644 index 000000000..af481c785 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/GraphMutations.java @@ -0,0 +1,163 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphMapper; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; +import art.arcane.iris.engine.object.value.IrisPosition; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +/** What the commands that edit the open graph share: running a change as one graph transaction, and reading the graph back. */ +final class GraphMutations { + private static final String NUMBERED_FAMILY_PREFIX = "variant-"; + + private GraphMutations() { + } + + static void runGraphMutation( + StudioUse use, + ActiveContext context, + JigsawStudioService.CommandGraphMutation mutation + ) { + use.onPlayer(() -> use.studio().runCommandGraphMutation(use.player(), context.request().requestId(), mutation)); + } + + static JigsawStudioLayout loadPersistedLayout(ActiveContext context) throws IOException { + IrisData source = context.request().source(); + source.invalidateStructureResources(); + IrisStructure structure = StructureResources.structure(source.getPackResources(), context.request().structureKey()); + if (structure == null) { + throw new IOException("The structure could not be reloaded after the graph transaction"); + } + return JigsawStudioGraphMapper.map(source, structure); + } + + static JigsawStudioService.CommandGraphMutationResult mappedMutationResult( + ActiveContext context, + String activateWorkcellId, + String activatePieceKey, + String message + ) throws IOException { + return new JigsawStudioService.CommandGraphMutationResult( + loadPersistedLayout(context), + activateWorkcellId, + activatePieceKey, + message); + } + + static String workcellIdForVariant(JigsawStudioLayout layout, String pieceKey) throws IOException { + JigsawStudioVariant variant = layout.variantCatalog().find(pieceKey).orElse(null); + if (variant == null) { + throw new IOException("Persisted variant '" + pieceKey + "' did not map to a Studio workcell"); + } + return variant.archetype() + .map(archetype -> archetype.stableId()) + .orElse(JigsawStudioLayout.SPATIAL_WORKCELL_ID); + } + + static PieceWorkcellResolution resolvePieceWorkcell( + JigsawStudioLayout layout, + IrisJigsawPiece piece, + IrisObject object + ) { + JigsawStudioLayout activeLayout = Objects.requireNonNull(layout, "Jigsaw Studio layout"); + IrisJigsawPiece activePiece = Objects.requireNonNull(piece, "Jigsaw piece"); + IrisObject activeObject = Objects.requireNonNull(object, "Jigsaw piece object"); + String workcellId; + IrisPosition requiredDimensions; + if (activeLayout.mode() == JigsawStudioMode.PLANAR_JIGSAW) { + IrisJigsawWorkcellArchetype modelArchetype = IrisJigsawWorkcellArchetype.fromPiece(activePiece); + workcellId = JigsawPlanarArchetype.fromModel(modelArchetype).stableId(); + requiredDimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(activePiece, activeObject); + } else { + workcellId = JigsawStudioLayout.SPATIAL_WORKCELL_ID; + requiredDimensions = new IrisPosition( + activeObject.getW(), + activeObject.getH(), + activeObject.getD()); + } + JigsawStudioBay workcell = activeLayout.get(workcellId); + if (workcell == null) { + throw new IllegalArgumentException("Workcell '" + workcellId + "' is not configured"); + } + return new PieceWorkcellResolution(workcell, requiredDimensions); + } + + static String nextThemeKey(ActiveContext context) throws IOException { + IrisStructure structure = StructureResources.structure( + context.request().source().getPackResources(), + context.request().structureKey()); + if (structure == null) { + throw new IOException("The active jigsaw structure could not be loaded"); + } + Set declared = new HashSet<>(); + if (structure.getThemeSets() != null) { + for (IrisJigsawThemeSet themeSet : structure.getThemeSets()) { + if (themeSet != null && themeSet.getKey() != null) { + declared.add(themeSet.getKey()); + } + } + } + int candidate = 1; + while (candidate > 0) { + String key = NUMBERED_FAMILY_PREFIX + candidate; + if (!declared.contains(key)) { + return key; + } + candidate = Math.incrementExact(candidate); + } + throw new IOException("Jigsaw Studio cannot allocate another numbered family key"); + } + + record PieceWorkcellResolution( + JigsawStudioBay workcell, + IrisPosition requiredDimensions + ) { + PieceWorkcellResolution { + workcell = Objects.requireNonNull(workcell, "Jigsaw Studio workcell"); + requiredDimensions = Objects.requireNonNull(requiredDimensions, "Jigsaw piece dimensions"); + } + + boolean fits() { + JigsawStudioCellDimensions capacity = workcell.capacity(); + return requiredDimensions.getX() <= capacity.width() + && requiredDimensions.getY() <= capacity.height() + && requiredDimensions.getZ() <= capacity.depth(); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java new file mode 100644 index 000000000..852c72dc3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java @@ -0,0 +1,90 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.structure.BulkStructureImporter; +import art.arcane.iris.core.structure.StructureCaptureImporter; +import art.arcane.iris.core.structure.StructureImporter; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; + +import java.util.Optional; + +/** {@code import} and {@code capture}: turn the platform's structures into editable jigsaw structures of the pack. */ +final class ImportCommands { + private ImportCommands() { + } + + static Command importAll() { + return Command.named("import").alias("import-all", "reimport", "imp", "all") + .describe("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.") + .runs(ImportCommands::runImportAll); + } + + static Command capture() { + return Command.named("capture").alias("cap") + .describe("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 jigsaw import runs a restricted final capture pass only for non-jigsaw structures that have no loadable NBT template.") + .runs(ImportCommands::runCapture); + } + + private static void runImportAll(CommandContext context) { + Optional platform = PlatformStructuresAccess.require(context); + if (platform.isEmpty()) { + return; + } + ToolPack pack = context.pack(); + Sender sender = context.sender(); + SenderText.send(sender, ToolText.builder() + .green("Importing all vanilla & datapack structures into ") + .white(pack.resources().packId().namespace()) + .green(" (overwrite)...").build()); + BulkStructureImporter.Report jigsaws = BulkStructureImporter.importAllVanilla( + pack, platform.get(), StructureImporter.Mode.OVERWRITE, true, sender); + BulkStructureImporter.Report templates = BulkStructureImporter.importAllTemplates( + pack, platform.get(), StructureImporter.Mode.OVERWRITE, sender); + BulkStructureImporter.Report groups = BulkStructureImporter.importTemplateGroups( + pack, platform.get(), StructureImporter.Mode.OVERWRITE, sender); + StructureCaptureImporter.Report captured = StructureCaptureImporter.importStructures( + pack, platform.get(), 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(); + SenderText.send(sender, ToolText.builder() + .green("Import complete: ").white(String.valueOf(imported)) + .green(" structures/objects written, ").white(String.valueOf(failed)) + .green(" failed.").build()); + SenderText.send(sender, TextColor.GRAY, + "Reference them from a biome/region/dimension 'structures' list, or run /iris module structure list to refresh the index. Regenerate chunks for changes to take effect."); + } + + private static void runCapture(CommandContext context) { + Optional platform = PlatformStructuresAccess.require(context); + if (platform.isEmpty()) { + return; + } + StructureCaptureImporter.Report report = StructureCaptureImporter.importAllStructures( + context.pack(), platform.get(), StructureImporter.Mode.OVERWRITE, context.sender()); + SenderText.send(context.sender(), TextColor.GRAY, "Captured " + report.imported() + + " structures. Place them from a 'structures' list and regenerate chunks. Delete a structures/*.json to re-capture it."); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawCommands.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawCommands.java new file mode 100644 index 000000000..5e19a3aa3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawCommands.java @@ -0,0 +1,63 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import com.volmit.tooling.Command; + +import java.util.Optional; +import java.util.function.Supplier; + +/** + * The {@code jigsaw} command tree: the Jigsaw Studio (create, open, close, edit and export a jigsaw structure in a tool + * world), and the {@code import} and {@code capture} that turn the platform's structures into jigsaw structures. Platforms + * mount it below their module branch, so the studio commands run as {@code /iris module jigsaw ...}. + */ +public final class JigsawCommands { + private static final String ROOT_NAME = "jigsaw"; + + private JigsawCommands() { + } + + /** + * The tree. + * + * @param hosts the studio host of the server, which is empty on a platform that runs no studio; read when a command + * runs, so a host that binds late is found + */ + public static Command root(Supplier> hosts) { + StudioLifecycleCommands lifecycle = new StudioLifecycleCommands(hosts); + GraphEditCommands graph = new GraphEditCommands(hosts); + Command root = Command.named(ROOT_NAME).alias("jig", "jgs").describe("Iris Jigsaw Studio tools"); + for (Command command : lifecycle.commands()) { + root = root.child(command); + } + return root + .child(new JigsawExportCommand(hosts).command()) + .child(new AdoptionCommands(hosts).command()) + .child(graph.connector()) + .child(graph.pool()) + .child(graph.piece()) + .child(graph.workcell()) + .child(graph.variant()) + .child(graph.rules()) + .child(graph.preview()) + .child(ImportCommands.importAll()) + .child(ImportCommands.capture()); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawExportCommand.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawExportCommand.java new file mode 100644 index 000000000..bafadaa21 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawExportCommand.java @@ -0,0 +1,279 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.export.VanillaJigsawDatapackExporter; +import art.arcane.iris.core.structure.export.VanillaJigsawExportDiagnostic; +import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat; +import art.arcane.iris.core.structure.export.VanillaJigsawExportRequest; +import art.arcane.iris.core.structure.export.VanillaJigsawExportResult; +import art.arcane.iris.core.structure.export.VanillaJigsawExportSource; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; + +import java.nio.file.Path; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import java.util.regex.Pattern; + +/** {@code export}: writes the clean graph of the open studio as a vanilla datapack below the pack's output folder. */ +final class JigsawExportCommand { + private static final Pattern EXPORT_OUTPUT_NAME = Pattern.compile("[a-zA-Z0-9_-][a-zA-Z0-9._-]{0,127}"); + private static final Set EXPORTING_PLAYERS = ConcurrentHashMap.newKeySet(); + private static final Set EXPORT_DESTINATIONS = ConcurrentHashMap.newKeySet(); + + private static final Argument NAMESPACE = Argument.word("namespace").orElse("iris") + .describe("Datapack namespace"); + private static final Argument OUTPUT = Argument.word("output").orElse("jigsaw-export") + .describe("Output name under the Studio exports folder"); + private static final Argument FORMAT = Argument.word("format").orElse("zip") + .describe("directory or zip").suggesting(context -> java.util.List.of("directory", "zip")); + private static final Argument REPLACE = Argument.word("replace").orElse("false") + .describe("Replace an existing export"); + + private final Supplier> hosts; + + JigsawExportCommand(Supplier> hosts) { + this.hosts = hosts; + } + + Command command() { + return Command.named("export").describe("Export the clean active graph as a vanilla datapack") + .argument(NAMESPACE).argument(OUTPUT).argument(FORMAT).argument(REPLACE) + .runs(this::export); + } + + private void export(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + if (active.session().isDirty()) { + use.error("Wait for the pending autosave or discard the edits before exporting the on-disk graph."); + return; + } + VanillaJigsawExportFormat exportFormat; + try { + exportFormat = parseFormat(context.get(FORMAT)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + Path exportRoot = use.pack().outputFolder().toAbsolutePath().normalize(); + Path destination; + try { + destination = resolveExportDestination(exportRoot, context.get(OUTPUT), exportFormat); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + VanillaJigsawExportRequest request; + try { + request = VanillaJigsawExportRequest.builder( + VanillaJigsawExportSource.forData( + active.request().source(), active.request().structureKey()), destination) + .namespace(context.get(NAMESPACE)) + .resourcePath(active.request().structureKey()) + .format(exportFormat) + .replaceExisting(StudioLifecycleCommands.flagValue(REPLACE.name(), context.get(REPLACE))) + .build(); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + ToolPlayer targetPlayer = use.player(); + UUID playerId = targetPlayer.id(); + UUID requestId = active.request().requestId(); + JigsawStudioService studioService = use.studio(); + JigsawStudioService.ExportStart exportStart = studioService.tryBeginExport(requestId, playerId); + if (exportStart != JigsawStudioService.ExportStart.STARTED) { + use.error(exportStartError(exportStart)); + return; + } + if (!beginExport(playerId, destination)) { + studioService.finishExport(requestId); + use.error("A vanilla Jigsaw export for this player or output is already in progress."); + return; + } + ExportLease lease = new ExportLease(() -> { + finishExport(playerId, destination); + studioService.finishExport(requestId); + }); + ExportOperation operation = new ExportOperation( + use, + context.sender(), + requestId, + active.request().structureKey(), + request, + lease); + use.say(TextColor.GRAY, "Exporting '" + operation.structureKey() + + "' in the background to " + destination + "..."); + try { + runExport(operation); + } catch (RuntimeException exception) { + operation.lease().release(); + use.pack().log().error("Failed to schedule vanilla Jigsaw export for '" + + operation.structureKey() + "'.", exception); + use.error("Vanilla export could not be scheduled: " + exception.getMessage()); + } + } + + static String exportStartError(JigsawStudioService.ExportStart exportStart) { + Objects.requireNonNull(exportStart, "Jigsaw Studio export start status"); + return switch (exportStart) { + case NOT_ACTIVE -> "The active Jigsaw Studio is no longer available."; + case NOT_OWNER -> "Only the Jigsaw Studio owner can export this project."; + case DIRTY -> "Wait for the pending autosave or discard the edits before exporting the on-disk graph."; + case CLOSING -> "The active Jigsaw Studio is closing and cannot be exported."; + case SAVE_IN_PROGRESS -> "Wait for the current Jigsaw Studio save to finish before exporting."; + case OPERATION_IN_PROGRESS -> "Wait for the current Jigsaw Studio operation to finish before exporting."; + case IN_PROGRESS -> "A Jigsaw Studio export is already in progress."; + case STARTED -> throw new IllegalArgumentException("STARTED is not an export failure"); + }; + } + + static boolean beginExport(UUID playerId, Path destination) { + Objects.requireNonNull(playerId); + Path normalizedDestination = Objects.requireNonNull(destination).toAbsolutePath().normalize(); + if (!EXPORTING_PLAYERS.add(playerId)) { + return false; + } + if (EXPORT_DESTINATIONS.add(normalizedDestination)) { + return true; + } + EXPORTING_PLAYERS.remove(playerId); + return false; + } + + static void finishExport(UUID playerId, Path destination) { + EXPORTING_PLAYERS.remove(Objects.requireNonNull(playerId)); + EXPORT_DESTINATIONS.remove(Objects.requireNonNull(destination).toAbsolutePath().normalize()); + } + + private static void runExport(ExportOperation operation) { + VanillaJigsawExportResult result = null; + Throwable failure = null; + try { + result = new VanillaJigsawDatapackExporter().export(operation.request()); + } catch (Throwable throwable) { + failure = throwable; + operation.use().pack().log().error("Vanilla Jigsaw export failed for '" + operation.structureKey() + "'.", throwable); + } finally { + operation.lease().release(); + } + reportExport(operation, result, failure); + } + + private static void reportExport( + ExportOperation operation, + VanillaJigsawExportResult result, + Throwable failure + ) { + Sender sender = operation.sender(); + if (failure != null || result == null) { + SenderText.send(sender, TextColor.RED, "Background vanilla export for '" + + operation.structureKey() + "' failed: " + + (failure == null ? "no result" : failure.getMessage())); + return; + } + for (VanillaJigsawExportDiagnostic diagnostic : result.diagnostics()) { + TextColor color = diagnostic.isBlocking() ? TextColor.RED : TextColor.YELLOW; + SenderText.send(sender, color, diagnostic.code() + ": " + diagnostic.message()); + } + ActiveContext current = StudioSessions.active(operation.use().registry(), operation.use().player().id()); + boolean sameSession = current != null + && current.request().requestId().equals(operation.requestId()); + String contextLabel = sameSession ? "Vanilla export" : "Background vanilla export for '" + + operation.structureKey() + "'"; + SenderText.send(sender, result.isSuccess() ? TextColor.GREEN : TextColor.RED, + contextLabel + " " + result.status() + ": " + result.output()); + } + + private static VanillaJigsawExportFormat parseFormat(String value) { + return switch (value.trim().toLowerCase(Locale.ROOT)) { + case "zip" -> VanillaJigsawExportFormat.ZIP; + case "directory", "dir", "folder" -> VanillaJigsawExportFormat.DIRECTORY; + default -> throw new IllegalArgumentException("Export format must be directory or zip."); + }; + } + + static Path resolveExportDestination( + Path exportRoot, + String output, + VanillaJigsawExportFormat format + ) { + Path root = Objects.requireNonNull(exportRoot, "Jigsaw export root").toAbsolutePath().normalize(); + String requested = Objects.requireNonNull(output, "Jigsaw export output name"); + String name = requested.trim(); + if (!name.equals(requested) || !EXPORT_OUTPUT_NAME.matcher(name).matches()) { + throw new IllegalArgumentException( + "Export output must be one file name using letters, numbers, '.', '_', or '-'."); + } + String fileName = format == VanillaJigsawExportFormat.ZIP && !name.endsWith(".zip") + ? name + ".zip" : name; + Path destination = root.resolve(fileName).normalize(); + if (destination.equals(root) || !root.equals(destination.getParent())) { + throw new IllegalArgumentException("Export output must be one artifact inside the Studio exports folder."); + } + return destination; + } + + private record ExportOperation( + StudioUse use, + Sender sender, + UUID requestId, + String structureKey, + VanillaJigsawExportRequest request, + ExportLease lease + ) { + } + + static final class ExportLease { + private final Runnable release; + private final AtomicBoolean released; + + ExportLease(Runnable release) { + this.release = Objects.requireNonNull(release, "Jigsaw export lease release action"); + this.released = new AtomicBoolean(); + } + + void release() { + if (released.compareAndSet(false, true)) { + release.run(); + } + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawStudioHost.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawStudioHost.java new file mode 100644 index 000000000..9a9a5bf19 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/JigsawStudioHost.java @@ -0,0 +1,52 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.service.JigsawStudioService; +import com.volmit.tooling.Sender; +import com.volmit.tooling.ToolPack; + +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** + * What the jigsaw commands need from the server that runs the Jigsaw Studio and that no api type offers: the studio + * itself, the pack's data, whether a pack may open a studio, and the server's one open studio. The adapter that runs a + * studio implements it; a platform without one has none, and the commands then say so. + */ +public interface JigsawStudioHost { + /** The studio, which keeps the sessions of its players. */ + JigsawStudioService studio(); + + /** The pack's data, for the resources the studio still reads through it. */ + IrisData dataOf(ToolPack pack); + + /** The key the studio files {@code pack} under. */ + String packKey(ToolPack pack); + + /** Tells {@code sender} why {@code packKey} may not open a studio; empty, and silent, when it may. */ + Optional reportAdmissionFailure(Sender sender, String packKey); + + /** Whether {@code failure} is the pack's validation denying the studio, which is the pack author's to fix and not an error of Iris. */ + boolean isExpectedOpenDenial(Throwable failure); + + /** Closes the studio the server has open; completes with why it failed, or empty when it closed. */ + CompletableFuture> closeStudio(); +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/PlatformStructuresAccess.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/PlatformStructuresAccess.java new file mode 100644 index 000000000..6887350e4 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/PlatformStructuresAccess.java @@ -0,0 +1,41 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; + +import java.util.Optional; + +/** Asks a command's platform for its structures, and tells the sender when it has none. */ +public final class PlatformStructuresAccess { + public static final String UNAVAILABLE = "PlatformStructures is unavailable on this platform"; + + private PlatformStructuresAccess() { + } + + /** The platform's structures; empty after telling the sender that this platform has none. */ + public static Optional require(CommandContext context) { + Optional platform = context.platformStructures(); + if (platform.isEmpty()) { + context.sender().error(UNAVAILABLE); + } + return platform; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/SenderText.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/SenderText.java new file mode 100644 index 000000000..a500c30b0 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/SenderText.java @@ -0,0 +1,61 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; + +import java.util.Optional; + +/** + * Sends a sender a line in colour: a player sees the colours as they are, and a sender that is not a player gets the + * line as an error, a success or plain information, by the colour the line starts with. + */ +public final class SenderText { + private SenderText() { + } + + public static void send(Sender sender, ToolText text) { + Optional player = sender.player(); + if (player.isPresent()) { + player.get().message(text); + return; + } + String plain = text.plainText(); + switch (leadingColor(text)) { + case RED -> sender.error(plain); + case GREEN -> sender.success(plain); + default -> sender.info(plain); + } + } + + /** A whole line in {@code color}. */ + public static void send(Sender sender, TextColor color, String line) { + send(sender, ToolText.colored(color, line)); + } + + private static TextColor leadingColor(ToolText text) { + if (text.isEmpty() || text.spans().getFirst().color() == null) { + return TextColor.WHITE; + } + return text.spans().getFirst().color(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/StructureKeys.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/StructureKeys.java new file mode 100644 index 000000000..ea75bfe3c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/StructureKeys.java @@ -0,0 +1,33 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; + +/** The keys the jigsaw commands show and the studio files its sessions under. */ +public final class StructureKeys { + private StructureKeys() { + } + + /** The key of a resource of the pack: its path when it is of the pack's namespace, else the id as written. */ + public static String keyOf(PackResources resources, ResourceId id) { + return resources.idOf(id.path()).equals(id) ? id.path() : id.toString(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java new file mode 100644 index 000000000..12929f8d5 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java @@ -0,0 +1,770 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphMapper; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioProjectCreator; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.service.JigsawStudioGraphEvaluation; +import art.arcane.iris.core.service.JigsawStudioRegistry; +import art.arcane.iris.core.service.JigsawStudioRequest; +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.StructureImporter; +import art.arcane.iris.core.structure.VillageImporter; +import art.arcane.iris.core.structure.authoring.StructureKey; +import art.arcane.iris.core.structure.authoring.StructureWriteResult; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import art.arcane.iris.core.structure.tooling.StudioSessions.SessionBinding; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorld; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletionException; +import java.util.function.Supplier; + +/** The Jigsaw Studio commands that create, open, close and inspect a player's studio, and that select and resize its workcells. */ +final class StudioLifecycleCommands { + static final long DEFAULT_STUDIO_SEED = 1337L; + private static final String PLANAR = "planar"; + private static final String SPATIAL = "spatial"; + private static final String IRIS = "iris"; + private static final String VANILLA = "vanilla"; + private static final String NONE = "none"; + private static final String SELECTED = "selected"; + private static final long DEFAULT_CELL_SIZE = 15L; + + private static final Argument NEW_KEY = Argument.word("key") + .describe("New key written as structures/.json"); + private static final Argument EXISTING_KEY = Argument.resource("key", StructureResources.STRUCTURES) + .describe("Existing key loaded from structures/.json"); + private static final Argument MODE = Argument.word("mode").orElse(PLANAR) + .describe("planar or spatial").suggesting(context -> List.of(PLANAR, SPATIAL)); + private static final Argument COMPATIBILITY = Argument.word("compatibility").orElse(IRIS) + .describe("iris or vanilla").suggesting(context -> List.of(IRIS, VANILLA)); + private static final Argument WIDTH = size("width", "Cell width").orElse(DEFAULT_CELL_SIZE); + private static final Argument HEIGHT = size("height", "Cell height").orElse(DEFAULT_CELL_SIZE); + private static final Argument DEPTH = size("depth", "Cell depth").orElse(DEFAULT_CELL_SIZE); + private static final Argument SEED = seed(); + private static final Argument SOURCE = Argument.word("source") + .describe("Registered structure key such as minecraft:village_plains"); + private static final Argument TARGET = Argument.word("target").orElse("auto") + .describe("New Iris structure key, or auto"); + private static final Argument DISCARD = Argument.word("discard").orElse("false") + .describe("Discard unsaved Studio layout changes"); + private static final Argument CONFIRM = Argument.word("confirm").orElse("false") + .describe("Confirm permanent project deletion"); + private static final Argument REQUIRED_WIDTH = size("width", "Cell width"); + private static final Argument REQUIRED_HEIGHT = size("height", "Cell height"); + private static final Argument REQUIRED_DEPTH = size("depth", "Cell depth"); + private static final Argument BAY = Argument.word("bay").orElse(SELECTED) + .describe("Workcell ID or selected"); + private static final Argument GOTO_BAY = Argument.word("bay").describe("Workcell ID"); + private static final Argument VISIBLE = Argument.flag("visible") + .describe("Whether particles are visible"); + + private final Supplier> hosts; + + StudioLifecycleCommands(Supplier> hosts) { + this.hosts = hosts; + } + + List commands() { + return List.of( + Command.named("create").describe("Create and open a new atomic Jigsaw Studio project") + .argument(NEW_KEY).argument(MODE).argument(COMPATIBILITY) + .argument(WIDTH).argument(HEIGHT).argument(DEPTH).argument(SEED) + .runs(this::create), + Command.named("convert").alias("import-vanilla") + .describe("Import a registered vanilla or datapack jigsaw graph into Iris Studio") + .argument(SOURCE).argument(TARGET).argument(SEED) + .runs(this::convert), + Command.named("open").alias("edit", "reopen") + .describe("Open an existing Iris jigsaw graph in transient Studio") + .argument(EXISTING_KEY).argument(SEED) + .runs(this::open), + Command.named("close").describe("Close the active Jigsaw Studio") + .argument(DISCARD).runs(this::close), + Command.named("delete").alias("remove").describe("Delete the active owned jigsaw project") + .argument(CONFIRM).runs(this::delete), + Command.named("status").describe("Show active Jigsaw Studio and dynamic evaluation state") + .runs(this::status), + Command.named("menu").describe("Open the Jigsaw Studio workcell and variant menu") + .runs(this::menu), + Command.named("select").describe("Select the Jigsaw Studio workcell containing you") + .runs(this::select), + Command.named("bounds").alias("cell", "resize") + .describe("Set the selected Studio workcell capacity") + .argument(REQUIRED_WIDTH).argument(REQUIRED_HEIGHT).argument(REQUIRED_DEPTH) + .runs(this::bounds), + Command.named("save").describe("Flush the automatic save for a workcell now") + .argument(BAY).runs(this::save), + Command.named("goto").alias("teleport").describe("Select and teleport to a Studio workcell") + .argument(GOTO_BAY).runs(this::gotoBay), + Command.named("particles").describe("Enable or disable Jigsaw Studio particles") + .argument(VISIBLE).runs(this::particles)); + } + + private static Argument size(String name, String description) { + return Argument.integer(name, Integer.MIN_VALUE, Integer.MAX_VALUE).describe(description); + } + + private static Argument seed() { + return Argument.integer("seed", Long.MIN_VALUE, Long.MAX_VALUE).orElse(DEFAULT_STUDIO_SEED) + .describe("Studio world seed"); + } + + private void create(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ToolPack pack = context.pack(); + String structure = context.get(NEW_KEY); + JigsawStudioMode studioMode; + JigsawStudioCompatibilityTarget target; + JigsawStudioCellDimensions dimensions; + try { + studioMode = parseMode(context.get(MODE)); + target = parseCompatibility(context.get(COMPATIBILITY)); + dimensions = cellDimensions(context.get(WIDTH), context.get(HEIGHT), context.get(DEPTH)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + + CreateOutcome outcome; + try { + JigsawStudioProjectCreator.Options options = + new JigsawStudioProjectCreator.Options(structure, studioMode, target, dimensions); + outcome = pack.edit(root -> createProject(root, options, structure)); + } catch (IOException | RuntimeException exception) { + pack.log().error("Failed to create Jigsaw Studio project '" + structure + "'.", exception); + use.error("Jigsaw project creation failed: " + exception.getMessage()); + return; + } + StructureWriteResult result = outcome.result(); + if (!result.successful()) { + use.error("Jigsaw project was not created: " + result.status()); + if (!result.conflicts().isEmpty()) { + use.error(result.conflicts().getFirst().relativePath() + ": " + + result.conflicts().getFirst().reason()); + } + return; + } + if (outcome.historyFailure() != null) { + pack.log().error("Failed to clear stale Jigsaw Studio history for '" + structure + "'.", outcome.historyFailure()); + use.error("Jigsaw project was created, but stale autosave history could not be cleared: " + + outcome.historyFailure().getMessage()); + return; + } + use.say(TextColor.GREEN, "Created Jigsaw project '" + structure + "' atomically."); + openProject(use, structure); + } + + private static CreateOutcome createProject(Path root, JigsawStudioProjectCreator.Options options, String structure) + throws IOException { + StructureWriteResult result = JigsawStudioProjectCreator.create(root, options); + if (!result.successful()) { + return new CreateOutcome(result, null); + } + try { + JigsawStudioService.clearAutosaveHistory(root, structure); + } catch (IOException exception) { + return new CreateOutcome(result, exception); + } + return new CreateOutcome(result, null); + } + + private record CreateOutcome(StructureWriteResult result, IOException historyFailure) { + } + + private void convert(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + if (studioIsActiveOrOpening(use.registry())) { + use.error("Close the active or opening Jigsaw Studio before importing another graph."); + return; + } + Optional platform = PlatformStructuresAccess.require(context); + if (platform.isEmpty()) { + return; + } + ResourceId sourceKey; + String targetKey; + try { + sourceKey = parseRegisteredStructureKey(context.get(SOURCE)); + targetKey = resolveConversionTarget(sourceKey, context.get(TARGET)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + + VillageImporter.Result result = VillageImporter.importVillage( + context.pack(), + platform.get(), + sourceKey, + targetKey, + StructureImporter.Mode.ADD_ONLY); + if (!result.success()) { + use.error(conversionFailureMessage(result)); + return; + } + use.say(TextColor.GREEN, result.message()); + openProject(use, targetKey); + } + + private void open(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + openProject(begun.get(), StructureKeys.keyOf(context.pack().resources(), context.get(EXISTING_KEY))); + } + + /** Stages the studio of {@code structure}, opens its tool world and moves the player in once the studio is committed. */ + static void openProject(StudioUse use, String structure) { + ToolPack pack = use.pack(); + ToolPlayer player = use.player(); + JigsawStudioHost host = use.host(); + JigsawStudioService studioService = use.studio(); + JigsawStudioRegistry registry = use.registry(); + UUID playerId = player.id(); + UUID ownerId = registry.activeOwnerId(); + if (ownerId != null && !ownerId.equals(playerId)) { + use.error("Jigsaw Studio is already owned by another player session."); + return; + } + UUID openingOwner = registry.openingOwnerId(); + if (openingOwner != null) { + use.error(openingOwner.equals(playerId) + ? "Your Jigsaw Studio is already opening." + : "Jigsaw Studio is already opening for another player."); + return; + } + ActiveContext previous = StudioSessions.active(registry, playerId); + if (ownerId != null && previous == null) { + use.error("Your active Jigsaw Studio binding is unavailable. Close it before opening another project."); + return; + } + ActiveContext dirty = StudioSessions.findDirtyContext(registry); + if (dirty != null) { + use.error("The current Jigsaw Studio is waiting for autosave. Wait for it to finish or close with discard=true."); + return; + } + IrisData data = host.dataOf(pack); + IrisStructure irisStructure = StructureResources.structure(pack.resources(), structure); + if (irisStructure == null) { + use.error("No Iris jigsaw structure '" + structure + "' exists in this pack."); + return; + } + + JigsawStudioLayout layout; + try { + layout = JigsawStudioGraphMapper.map(data, irisStructure); + } catch (RuntimeException exception) { + pack.log().error("Failed to map Jigsaw Studio graph '" + structure + "'.", exception); + use.error("Could not map this jigsaw graph: " + exception.getMessage()); + return; + } + String packKey = host.packKey(pack); + if (!registry.tryBeginOpen(playerId)) { + use.error("Jigsaw Studio began opening for another player. Try again after it finishes."); + return; + } + UUID closingRequestId = previous == null ? null : previous.request().requestId(); + if (closingRequestId != null) { + JigsawStudioService.CloseStart closeStart = studioService.tryBeginClose( + closingRequestId, + playerId, + false); + if (closeStart != JigsawStudioService.CloseStart.STARTED) { + registry.finishOpen(playerId); + use.error(closeStart == JigsawStudioService.CloseStart.SAVE_IN_PROGRESS + ? "The current Jigsaw Studio is saving. Wait for it to finish before opening another project." + : closeStart == JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS + ? "The current Jigsaw Studio is loading a variant. Wait for it to finish before opening another project." + : closeStart == JigsawStudioService.CloseStart.DIRTY + ? "The current Jigsaw Studio is waiting for autosave. Wait for it to finish before opening another project." + : "The current Jigsaw Studio could not be reserved for replacement."); + return; + } + } + JigsawStudioRegistry.StagedActivation staged; + try { + staged = registry.stage( + packKey, + structure, + layout.mode(), + compatibilityOf(irisStructure), + layout.cellDimensions(), + data, + layout, + playerId, + closingRequestId); + } catch (RuntimeException exception) { + registry.finishOpen(playerId); + studioService.cancelClose(closingRequestId); + pack.log().error("Failed to stage Jigsaw Studio for '" + structure + "'.", exception); + use.error("Jigsaw Studio staging failed: " + exception.getMessage()); + return; + } + use.say(TextColor.GREEN, "Opening transient Jigsaw Studio for '" + structure + "' with " + + layout.bays().size() + " workcells."); + + Optional admissionFailure = host.reportAdmissionFailure(use.sender(), packKey); + if (admissionFailure.isPresent()) { + finishOpenAttempt(use, structure, closingRequestId, staged, null, admissionFailure.get()); + return; + } + try { + beginStagedOpen(registry, staged); + studioService.open(pack, staged) + .whenComplete((world, throwable) -> player.run(() -> { + Throwable failure = throwable; + if (failure == null) { + failure = commitOpenedStudio(use, world, staged); + } + finishOpenAttempt(use, structure, closingRequestId, staged, world, failure); + })); + } catch (Throwable exception) { + registry.finishOpen(playerId); + studioService.cancelClose(closingRequestId); + registry.rollback(staged); + pack.log().error("Failed to open Jigsaw Studio for '" + structure + "'.", exception); + use.error("Jigsaw Studio open failed: " + exception.getMessage()); + } + } + + private void close(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + boolean discard = flagValue(DISCARD.name(), context.get(DISCARD)); + ToolPlayer player = use.player(); + ActiveContext active = StudioSessions.active(use.registry(), player.id()); + if (active == null) { + use.error("You do not have an active Jigsaw Studio session."); + return; + } + if (active.session().isDirty() && !discard) { + use.error("This Jigsaw Studio is waiting for autosave. Wait for it to finish or run close with discard=true."); + return; + } + JigsawStudioService studioService = use.studio(); + UUID requestId = active.request().requestId(); + JigsawStudioService.CloseStart closeStart = studioService.tryBeginClose( + requestId, + player.id(), + discard); + if (closeStart != JigsawStudioService.CloseStart.STARTED) { + use.error(closeStart == JigsawStudioService.CloseStart.SAVE_IN_PROGRESS + ? "This Jigsaw Studio is saving. Wait for the save to finish before closing it." + : closeStart == JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS + ? "This Jigsaw Studio is loading a variant. Wait for it to finish before closing it." + : closeStart == JigsawStudioService.CloseStart.DIRTY + ? "This Jigsaw Studio is waiting for autosave. Wait for it to finish or run close with discard=true." + : closeStart == JigsawStudioService.CloseStart.NOT_OWNER + ? "This Jigsaw Studio is owned by another player session." + : "This Jigsaw Studio session is no longer active."); + return; + } + try { + use.host().closeStudio().whenComplete((failure, throwable) -> player.run(() -> { + if (throwable != null || failure.isPresent()) { + studioService.cancelClose(requestId); + Throwable cause = throwable != null ? throwable : failure.get(); + use.error("Jigsaw Studio close failed: " + cause.getMessage()); + return; + } + use.registry().deactivate(active.packKey(), requestId); + StudioSessions.unbind(player.id(), new SessionBinding(active.packKey(), requestId)); + use.say(TextColor.GREEN, "Jigsaw Studio closed."); + })); + } catch (Throwable exception) { + studioService.cancelClose(requestId); + context.pack().log().error("Failed to close Jigsaw Studio '" + active.request().structureKey() + "'.", exception); + use.error("Jigsaw Studio close failed: " + exception.getMessage()); + } + } + + private void delete(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty() || begun.get().requireActive() == null) { + return; + } + StudioUse use = begun.get(); + if (!flagValue(CONFIRM.name(), context.get(CONFIRM))) { + use.error("Project deletion removes every resource owned by this jigsaw. Run again with confirm=true."); + return; + } + use.onPlayer(() -> use.studio().deleteProject(use.player())); + } + + private void status(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioLayout layout = active.session().layout(); + String selection = active.session().selectedBayId().orElse(NONE); + JigsawStudioVariant activeVariant = NONE.equals(selection) + ? null + : active.session().activeVariant(selection).orElse(null); + JigsawStudioBay selectedBay = NONE.equals(selection) ? null : layout.get(selection); + JigsawStudioCellDimensions selectedDimensions = selectedBay == null + ? null + : selectedBay.bounds().dimensions(); + Optional evaluation = use.readFromPlayer(() -> use.studio().evaluation(use.player())); + use.say(TextColor.AQUA, "Jigsaw Studio: " + active.request().structureKey()); + use.say(TextColor.GRAY, "mode=" + layout.mode() + + ", compatibility=" + active.request().compatibilityTarget() + + ", defaultCell=" + layout.cellDimensions().width() + "x" + + layout.cellDimensions().height() + "x" + layout.cellDimensions().depth() + + ", workcells=" + layout.bays().size() + + ", variants=" + layout.variantCatalog().size()); + use.say(TextColor.GRAY, "selected=" + selection + + ", activeVariant=" + (activeVariant == null ? NONE : activeVariant.pieceKey()) + + ", size=" + (selectedDimensions == null ? NONE : selectedDimensions.width() + "x" + + selectedDimensions.height() + "x" + selectedDimensions.depth()) + + ", enabled=" + (selectedBay == null ? "n/a" : selectedBay.enabled()) + + ", autosavePending=" + active.session().isDirty()); + if (evaluation.isPresent()) { + JigsawStudioGraphEvaluation current = evaluation.get(); + use.say(TextColor.GRAY, "evaluation=" + current.state() + + ", seed=" + current.seed() + + ", theme=" + (current.selectedTheme().isBlank() ? "unthemed" : current.selectedTheme()) + + ", pieces=" + current.pieceCount() + + ", detail=" + current.detail()); + } else { + use.say(TextColor.GRAY, "evaluation=PENDING, seed=" + DEFAULT_STUDIO_SEED); + } + } + + private void menu(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty() || begun.get().requireActive() == null) { + return; + } + StudioUse use = begun.get(); + use.onPlayer(() -> use.studio().openControlMenu(use.player())); + } + + private void select(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + BlockPosition location = use.readFromPlayer(use.player()::position); + JigsawStudioBay bay = active.session().layout().findAt(location.x(), location.y(), location.z()); + if (bay == null) { + use.error("Stand inside a Jigsaw Studio workcell before selecting it."); + return; + } + active.session().selectBay(bay.stableId()); + use.say(TextColor.GREEN, "Selected " + bay.stableId() + " (" + bay.kind() + ")."); + } + + private void bounds(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selected = StudioUse.selectedBay(active); + if (selected == null) { + use.error("Select a Jigsaw Studio workcell before changing its capacity."); + return; + } + JigsawStudioCellDimensions dimensions; + try { + dimensions = cellDimensions(context.get(REQUIRED_WIDTH), context.get(REQUIRED_HEIGHT), context.get(REQUIRED_DEPTH)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + if (dimensions.equals(selected.capacity())) { + use.say(TextColor.YELLOW, "Workcell capacity is unchanged."); + return; + } + use.onPlayer(() -> use.studio().updateWorkcellDimensions(use.player(), selected.stableId(), dimensions)); + } + + private void save(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String bay = context.get(BAY); + if (SELECTED.equalsIgnoreCase(bay)) { + JigsawStudioBay selected = StudioUse.selectedBay(active); + if (selected == null) { + use.error("Select a Jigsaw Studio workcell before flushing its autosave."); + return; + } + use.onPlayer(() -> use.studio().flushAutosave(use.player(), selected.stableId())); + return; + } + use.onPlayer(() -> use.studio().flushAutosave(use.player(), bay)); + } + + private void gotoBay(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty() || begun.get().requireActive() == null) { + return; + } + StudioUse use = begun.get(); + String bay = context.get(GOTO_BAY); + use.onPlayer(() -> use.studio().teleportTo(use.player(), bay)); + } + + private void particles(CommandContext context) { + Optional begun = StudioUse.begin(hosts, context); + if (begun.isEmpty() || begun.get().requireActive() == null) { + return; + } + StudioUse use = begun.get(); + boolean visible = context.get(VISIBLE); + use.onPlayer(() -> use.studio().setParticles(use.player(), visible)); + } + + private static boolean studioIsActiveOrOpening(JigsawStudioRegistry registry) { + return registry.activeOwnerId() != null + || registry.openingOwnerId() != null; + } + + private static void beginStagedOpen(JigsawStudioRegistry registry, JigsawStudioRegistry.StagedActivation staged) { + if (!registry.beginStagedGeneration(staged)) { + throw new IllegalStateException("The staged Jigsaw Studio activation is no longer current"); + } + } + + private static void finishOpenAttempt( + StudioUse use, + String structureKey, + UUID closingRequestId, + JigsawStudioRegistry.StagedActivation staged, + ToolWorld result, + Throwable throwable + ) { + JigsawStudioRegistry registry = use.registry(); + registry.finishOpen(use.player().id()); + if (throwable == null && result != null) { + use.studio().cancelClose(closingRequestId); + return; + } + use.studio().cancelClose(closingRequestId); + registry.rollback(staged); + Throwable failure = unwrapCompletionFailure(throwable == null + ? new IllegalStateException("Studio open completed without a result") + : throwable); + ToolPack pack = use.pack(); + if (use.host().isExpectedOpenDenial(failure)) { + pack.log().warn("Jigsaw Studio open for '" + structureKey + "' was denied: " + failure.getMessage()); + return; + } + pack.log().error("Failed to open Jigsaw Studio for '" + structureKey + "'.", failure); + use.error("Jigsaw Studio open failed: " + failure.getMessage()); + } + + /** Commits the staged studio once its world is open and moves the player in; the failure, or null when all went well. */ + private static Throwable commitOpenedStudio( + StudioUse use, + ToolWorld world, + JigsawStudioRegistry.StagedActivation staged + ) { + try { + enterCommittedStudio(use, world, staged); + return null; + } catch (RuntimeException exception) { + return exception; + } + } + + private static void enterCommittedStudio( + StudioUse use, + ToolWorld world, + JigsawStudioRegistry.StagedActivation staged + ) { + if (world == null) { + throw new IllegalStateException("Jigsaw Studio opened without a world"); + } + JigsawStudioRegistry registry = use.registry(); + JigsawStudioRequest request = staged.request(); + JigsawStudioSession session = staged.session(); + JigsawStudioBay destination = initialBay(session.layout()); + double targetX = destination == null + ? 0.5D + : destination.bounds().originX() + destination.bounds().dimensions().width() / 2.0D; + double targetY = destination == null ? 66D : destination.bounds().maxY() + 2.0D; + double targetZ = destination == null + ? 0.5D + : destination.bounds().originZ() + destination.bounds().dimensions().depth() / 2.0D; + if (destination != null) { + session.selectBay(destination.stableId()); + } + if (!registry.commit(staged)) { + throw new IllegalStateException("The staged Jigsaw Studio activation could not be committed"); + } + use.studio().activationCommitted(request.requestId()); + StudioSessions.bind(use.player().id(), new SessionBinding( + request.packKey(), request.requestId())); + ToolPlayer player = use.player(); + try { + player.teleport(world, targetX, targetY, targetZ, 0.0F, 0.0F) + .thenRun(() -> player.creative(true)); + } catch (RuntimeException exception) { + use.pack().log().error("Failed to move the player to the committed Jigsaw Studio workcell.", exception); + } + } + + private static JigsawStudioBay initialBay(JigsawStudioLayout layout) { + for (JigsawStudioBay bay : layout.bays()) { + if (layout.defaultVariant(bay).isPresent()) { + return bay; + } + } + return layout.bays().isEmpty() ? null : layout.bays().getFirst(); + } + + private static Throwable unwrapCompletionFailure(Throwable failure) { + Throwable current = failure; + while (current instanceof CompletionException && current.getCause() != null) { + current = current.getCause(); + } + return current; + } + + private static JigsawStudioCellDimensions cellDimensions(long width, long height, long depth) { + return new JigsawStudioCellDimensions((int) width, (int) height, (int) depth); + } + + /** Whether the text says true, written either as a value or as {@code name=value}, which is how the commands tell it. */ + static boolean flagValue(String name, String text) { + String value = text.trim().toLowerCase(Locale.ROOT); + String prefix = name + "="; + return Boolean.parseBoolean(value.startsWith(prefix) ? value.substring(prefix.length()) : value); + } + + static JigsawStudioMode parseMode(String value) { + return switch (value.trim().toLowerCase(Locale.ROOT)) { + case "planar", "2d", "planar_jigsaw" -> JigsawStudioMode.PLANAR_JIGSAW; + case "spatial", "3d", "spatial_jigsaw" -> JigsawStudioMode.SPATIAL_JIGSAW; + default -> throw new IllegalArgumentException("Mode must be planar or spatial."); + }; + } + + static JigsawStudioCompatibilityTarget parseCompatibility(String value) { + return switch (value.trim().toLowerCase(Locale.ROOT)) { + case "extended", "iris", "iris_extended" -> JigsawStudioCompatibilityTarget.IRIS_EXTENDED; + case "vanilla", "portable", "vanilla_portable" -> JigsawStudioCompatibilityTarget.VANILLA_PORTABLE; + default -> throw new IllegalArgumentException("Compatibility must be iris or vanilla."); + }; + } + + private static JigsawStudioCompatibilityTarget compatibilityOf(IrisStructure structure) { + return structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE + ? JigsawStudioCompatibilityTarget.VANILLA_PORTABLE + : JigsawStudioCompatibilityTarget.IRIS_EXTENDED; + } + + static ResourceId parseRegisteredStructureKey(String value) { + String normalized = Objects.requireNonNull(value, "Registered structure key").trim() + .toLowerCase(Locale.ROOT); + try { + return ResourceId.ofPlatformKey(normalized); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Registered structure source must use a valid namespace:path key."); + } + } + + static String resolveConversionTarget(ResourceId source, String value) { + Objects.requireNonNull(source, "Registered structure key"); + String normalized = Objects.requireNonNull(value, "Conversion target").trim() + .toLowerCase(Locale.ROOT); + if (normalized.isEmpty() || "auto".equals(normalized)) { + return StructureImporter.deriveName(source); + } + StructureKey target = StructureKey.parse(normalized, "iris"); + if (!"iris".equals(target.namespace())) { + throw new IllegalArgumentException("Converted Studio targets must use the iris namespace."); + } + return target.path(); + } + + static String conversionFailureMessage(VillageImporter.Result result) { + String message = Objects.requireNonNull(result, "Village import result").message(); + String obsoleteInstruction = "; use 'import' for single-template structures"; + int instructionIndex = message.indexOf(obsoleteInstruction); + if (instructionIndex < 0) { + return message; + } + return message.substring(0, instructionIndex) + + ". This Studio converter accepts registered jigsaw structures only."; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/StudioSessions.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/StudioSessions.java new file mode 100644 index 000000000..eb23e8133 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/StudioSessions.java @@ -0,0 +1,92 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; +import art.arcane.iris.core.service.JigsawStudioRegistry; +import art.arcane.iris.core.service.JigsawStudioRequest; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** The studio each player of the commands has open: which pack's studio, and which request opened it. */ +final class StudioSessions { + private static final Map PLAYER_PACKS = new ConcurrentHashMap<>(); + + private StudioSessions() { + } + + /** The studio of the pack {@code packKey}, opened by one request, with its session. */ + public record ActiveContext(String packKey, JigsawStudioRequest request, JigsawStudioSession session) { + } + + record SessionBinding(String packKey, UUID requestId) { + } + + static void bind(UUID playerId, SessionBinding binding) { + PLAYER_PACKS.put(playerId, binding); + } + + static void unbind(UUID playerId, SessionBinding binding) { + PLAYER_PACKS.remove(playerId, binding); + } + + /** The studio the player has open, or null when they have none or it has since been replaced. */ + static ActiveContext active(JigsawStudioRegistry registry, UUID playerId) { + if (playerId == null) { + return null; + } + SessionBinding binding = PLAYER_PACKS.get(playerId); + if (binding == null) { + return null; + } + ActiveContext context = context(registry, binding); + if (context == null) { + PLAYER_PACKS.remove(playerId, binding); + return null; + } + return context; + } + + private static ActiveContext context(JigsawStudioRegistry registry, SessionBinding binding) { + JigsawStudioRequest request = registry.getRequest(binding.packKey()); + JigsawStudioSession session = registry.getSession(binding.packKey()); + if (request == null || session == null + || !binding.requestId().equals(request.requestId()) + || !request.requestId().equals(session.sessionId())) { + return null; + } + return new ActiveContext(binding.packKey(), request, session); + } + + /** A studio of any player that still has unsaved edits, or null. */ + static ActiveContext findDirtyContext(JigsawStudioRegistry registry) { + for (SessionBinding binding : PLAYER_PACKS.values()) { + JigsawStudioRequest request = registry.getRequest(binding.packKey()); + JigsawStudioSession session = registry.getSession(binding.packKey()); + if (request != null && session != null + && binding.requestId().equals(request.requestId()) + && session.isDirty()) { + return new ActiveContext(binding.packKey(), request, session); + } + } + return null; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/tooling/StudioUse.java b/core/src/main/java/art/arcane/iris/core/structure/tooling/StudioUse.java new file mode 100644 index 000000000..427ba7baa --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/structure/tooling/StudioUse.java @@ -0,0 +1,163 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.service.JigsawStudioRegistry; +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.Sender; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; + +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; + +/** + * One run of a command that acts on a player's studio: the host that runs the studio, the player who ran the command and + * what they say back. A command that needs a player or a studio host and has none has told the sender when {@link #begin} + * answers empty. + */ +final class StudioUse { + static final String PLAYERS_ONLY = "This command can only be used by players."; + static final String NO_STUDIO_HOST = "Jigsaw Studio is unavailable on this platform."; + static final String NO_ACTIVE_STUDIO = "Open a Jigsaw Studio project first."; + private static final long PLAYER_THREAD_TIMEOUT_SECONDS = 10L; + + private final JigsawStudioHost host; + private final CommandContext context; + private final ToolPlayer player; + private final ToolPack pack; + + private StudioUse(JigsawStudioHost host, CommandContext context, ToolPlayer player, ToolPack pack) { + this.host = host; + this.context = context; + this.player = player; + this.pack = pack; + } + + /** This use on another pack, such as the one an earlier command prepared a change for. */ + StudioUse onPack(ToolPack other) { + return new StudioUse(host, context, player, other); + } + + ToolPack pack() { + return pack; + } + + /** The use for a command that needs the studio host and the player who ran it. */ + static Optional begin(Supplier> hosts, CommandContext context) { + Optional player = context.sender().player(); + if (player.isEmpty()) { + context.sender().error(PLAYERS_ONLY); + return Optional.empty(); + } + Optional host = hosts.get(); + if (host.isEmpty()) { + context.sender().error(NO_STUDIO_HOST); + return Optional.empty(); + } + return Optional.of(new StudioUse(host.get(), context, player.get(), context.pack())); + } + + JigsawStudioHost host() { + return host; + } + + CommandContext context() { + return context; + } + + ToolPlayer player() { + return player; + } + + Sender sender() { + return context.sender(); + } + + JigsawStudioService studio() { + return host.studio(); + } + + JigsawStudioRegistry registry() { + return host.studio().registry(); + } + + void say(TextColor color, String message) { + SenderText.send(context.sender(), color, message); + } + + void error(String message) { + say(TextColor.RED, message); + } + + /** The studio this player has open, after telling them to open one when they have none. */ + ActiveContext requireActive() { + ActiveContext active = StudioSessions.active(registry(), player.id()); + if (active == null) { + error(NO_ACTIVE_STUDIO); + } + return active; + } + + /** Runs {@code task} on the thread that owns the player, as the studio's calls about a player expect. */ + void onPlayer(Runnable task) { + player.run(task); + } + + /** What {@code reader} reads from the player, on the thread that owns them; waits for it. */ + T readFromPlayer(Supplier reader) { + CompletableFuture result = new CompletableFuture<>(); + player.run(() -> { + try { + result.complete(reader.get()); + } catch (Throwable failure) { + result.completeExceptionally(failure); + } + }); + try { + return result.get(PLAYER_THREAD_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while reading from the player", interrupted); + } catch (ExecutionException | TimeoutException failure) { + throw new IllegalStateException("Could not read from the player: " + failure.getMessage(), failure); + } + } + + static JigsawStudioBay selectedBay(ActiveContext context) { + String selected = context.session().selectedBayId().orElse(null); + return selected == null ? null : context.session().layout().get(selected); + } + + static JigsawStudioVariant selectedVariant(ActiveContext context) { + JigsawStudioBay selected = selectedBay(context); + return selected == null + ? null + : context.session().activeVariant(selected.stableId()).orElse(null); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java b/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java index 4139c3252..919b2bfc0 100644 --- a/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java +++ b/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java @@ -20,6 +20,7 @@ package art.arcane.iris.core.tooling; import com.volmit.resource.PlatformRegistries; import com.volmit.tooling.Argument; import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; import com.volmit.tooling.Sender; import com.volmit.tooling.ToolPack; import com.volmit.world.PackWorld; @@ -34,13 +35,16 @@ final class CommandRun implements CommandContext { private final ToolPack pack; private final Optional world; private final Optional platform; + private final Optional platformStructures; private final Map, Object> values = new IdentityHashMap<>(); - CommandRun(Sender sender, ToolPack pack, Optional world, Optional platform) { + CommandRun(Sender sender, ToolPack pack, Optional world, Optional platform, + Optional platformStructures) { this.sender = sender; this.pack = pack; this.world = world; this.platform = platform; + this.platformStructures = platformStructures; } void put(Argument argument, T value) { @@ -78,4 +82,9 @@ final class CommandRun implements CommandContext { public Optional platform() { return platform; } + + @Override + public Optional platformStructures() { + return platformStructures; + } } diff --git a/core/src/main/java/art/arcane/iris/core/tooling/StructureIndexOnStart.java b/core/src/main/java/art/arcane/iris/core/tooling/StructureIndexOnStart.java new file mode 100644 index 000000000..72608b682 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/StructureIndexOnStart.java @@ -0,0 +1,60 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisModuleHost; +import art.arcane.iris.core.structure.StructureIndexService; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisServices; +import com.volmit.tooling.PlatformStructures; + +import java.io.File; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** Writes a pack's structure index once, when the first engine of the pack starts and the platform can list its structures. */ +public final class StructureIndexOnStart { + private static final Set GENERATED = ConcurrentHashMap.newKeySet(); + + private StructureIndexOnStart() { + } + + /** The index file; null when it was written before, or the platform does not list its structures yet, or writing failed. */ + public static File writeOnce(IrisData data) { + PlatformStructures platform = IrisServices.getOrNull(PlatformStructures.class); + if (data == null || platform == null) { + return null; + } + + File dataFolder = data.getDataFolder(); + String key = dataFolder == null ? null : dataFolder.getAbsolutePath(); + if (key == null || !GENERATED.add(key)) { + return null; + } + + try { + return StructureIndexService.write(new IrisToolPack(data, IrisModuleHost.hostLog()), platform); + } catch (Throwable e) { + GENERATED.remove(key); + IrisLogging.reportError(e); + return null; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java b/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java index a200cb784..4a040df63 100644 --- a/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java +++ b/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java @@ -20,10 +20,12 @@ package art.arcane.iris.core.tooling; import art.arcane.iris.core.modules.IrisValidationContext; import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisServices; import com.volmit.host.CommandRegistration; import com.volmit.resource.PlatformRegistries; import com.volmit.tooling.Argument; import com.volmit.tooling.Command; +import com.volmit.tooling.PlatformStructures; import com.volmit.world.PackWorld; import java.util.ArrayList; @@ -55,11 +57,18 @@ public final class ToolingCommands { private final PackDirectory packs; private final Executor workers; private final Supplier> platform; + private final Supplier> platformStructures; public ToolingCommands(PackDirectory packs, Executor workers, Supplier> platform) { + this(packs, workers, platform, Optional::empty); + } + + public ToolingCommands(PackDirectory packs, Executor workers, Supplier> platform, + Supplier> platformStructures) { this.packs = packs; this.workers = workers; this.platform = platform; + this.platformStructures = platformStructures; } /** The dispatcher of the bound platform, with daemon worker threads created as commands need them. */ @@ -70,7 +79,8 @@ public final class ToolingCommands { worker.setDaemon(true); return worker; }); - return new ToolingCommands(PackDirectory.ofBoundPlatform(), workers, IrisValidationContext::boundPlatformRegistries); + return new ToolingCommands(PackDirectory.ofBoundPlatform(), workers, IrisValidationContext::boundPlatformRegistries, + () -> Optional.ofNullable(IrisServices.getOrNull(PlatformStructures.class))); } /** Whether {@code word} opens the module branch of the {@code /iris} root, {@code module} or its alias {@code m}. */ @@ -223,7 +233,8 @@ public final class ToolingCommands { } private CommandRun contextOf(ToolingSender sender, ResolvedPack pack, LocatedCommand located) { - return new CommandRun(sender, pack.served().toolPack(located.root().module().log()), pack.world(), platform.get()); + return new CommandRun(sender, pack.served().toolPack(located.root().module().log()), pack.world(), platform.get(), + platformStructures.get()); } private static void parseArguments(LocatedCommand located, CommandRun context) throws CommandFailure { diff --git a/core/src/main/java/art/arcane/iris/core/tooling/VolmitToolSender.java b/core/src/main/java/art/arcane/iris/core/tooling/VolmitToolSender.java new file mode 100644 index 000000000..0e294efa8 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/VolmitToolSender.java @@ -0,0 +1,68 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.tooling; + +import art.arcane.iris.util.common.format.C; +import art.arcane.iris.util.common.plugin.VolmitSender; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.ToolPlayer; + +import java.util.Optional; + +/** + * An Iris {@link VolmitSender}, such as the console, as a tool {@link Sender}, for core code that runs tools without a + * command. It is never a player, because only a command's sender knows its tool player. + */ +public final class VolmitToolSender implements Sender { + private final VolmitSender messages; + + public VolmitToolSender(VolmitSender messages) { + this.messages = messages; + } + + @Override + public String name() { + return messages.getS().getName(); + } + + @Override + public void info(String message) { + messages.sendMessage(C.WHITE + message); + } + + @Override + public void success(String message) { + messages.sendMessage(C.GREEN + message); + } + + @Override + public void error(String message) { + messages.sendMessage(C.RED + message); + } + + @Override + public Optional extension(Class type) { + return type.isInstance(messages.getS()) ? Optional.of(type.cast(messages.getS())) : Optional.empty(); + } + + @Override + public Optional player() { + return Optional.empty(); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java index ff6e34ce7..074b7a6d9 100644 --- a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java +++ b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java @@ -46,7 +46,7 @@ import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.IrisServices; import art.arcane.iris.core.nms.container.BlockPos; import art.arcane.iris.core.nms.container.Pair; -import art.arcane.iris.core.structure.StructureIndexService; +import art.arcane.iris.core.tooling.StructureIndexOnStart; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.common.plugin.VolmitSender; @@ -223,7 +223,7 @@ public class IrisEngine implements Engine { IrisLogging.debug("[IrisEngine timing] loadPrefetch=" + (M.ms() - _t0) + "ms"); logStudioInitializationPhase("load_prefetch", phaseStartedAt, false); try { - StructureIndexService.writeOnce(getData()); + StructureIndexOnStart.writeOnce(getData()); } catch (Throwable e) { IrisLogging.reportError(e); } diff --git a/core/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java b/core/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java index f1d108963..d3df55116 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java +++ b/core/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java @@ -22,7 +22,9 @@ import com.volmit.object.PlaceableObject; import com.volmit.object.ScaleMethod; import art.arcane.iris.engine.object.placement.IObjectPlacer; import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.iris.core.modules.BlockEntities; import art.arcane.iris.core.modules.ObjectGeometry; +import art.arcane.iris.core.modules.PlatformBlockStates; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.platform.bukkit.BukkitBlockState; @@ -36,6 +38,9 @@ import art.arcane.volmlib.util.math.IrisVector; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.iris.util.common.plugin.VolmitSender; import art.arcane.volmlib.util.collection.KList; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; import com.volmit.object.GeneratedObject; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -49,8 +54,11 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -283,6 +291,124 @@ public class IrisObject extends IrisRegistrant implements PlaceableObject { return written; } + /** + * Stores {@code state} at the unsigned position, as the platform builds it from its key. + */ + public void setUnsignedState(int x, int y, int z, BlockState state) { + setUnsigned(x, y, z, B.getState(state.key())); + } + + /** Stores {@code data} as the block entity at the unsigned position. */ + public void setUnsignedBlockEntity(int x, int y, int z, BlockEntityData data) { + setUnsignedTile(x, y, z, BlockEntities.tileOf(data)); + } + + /** + * The stored blocks and block entities as IrisApi values at their unsigned positions, in storage order, for tools that + * edit an object's contents without the platform's block types. A block Iris cannot read is cave air, as Iris places + * it. Hand the edited values back through {@link #fromApiContents}. + */ + public ApiContents apiContents() { + readLock.lock(); + try { + PlatformBlockStates conversion = new PlatformBlockStates(B::getState); + Map apiBlocks = new LinkedHashMap<>(); + Set customBlocks = new LinkedHashSet<>(); + Set blocksNeedingEntity = new LinkedHashSet<>(); + for (Map.Entry entry : blocks) { + BlockPosition position = unsignedPositionOf(entry.getKey()); + PlatformBlockState stored = entry.getValue(); + apiBlocks.put(position, stored == null ? ApiContents.UNREADABLE_BLOCK : conversion.toApi(stored)); + if (stored != null && stored.isCustom()) { + customBlocks.add(position); + } + if (stored != null && stored.hasTileEntity()) { + blocksNeedingEntity.add(position); + } + } + Map apiEntities = new LinkedHashMap<>(); + for (Map.Entry entry : states) { + apiEntities.put(unsignedPositionOf(entry.getKey()), BlockEntities.of(entry.getValue())); + } + return new ApiContents(conversion, apiBlocks, apiEntities, customBlocks, blocksNeedingEntity); + } finally { + readLock.unlock(); + } + } + + /** + * An object of the given size holding {@code contents}, which came from {@link #apiContents} of some object and may + * have been edited since. A block that was read from the platform is written back as that same platform state. + */ + public static IrisObject fromApiContents(int w, int h, int d, ApiContents contents) { + IrisObject object = new IrisObject(w, h, d); + contents.blocks().forEach((position, state) -> + object.setUnsigned(position.x(), position.y(), position.z(), contents.platformStateOf(state))); + contents.blockEntities().forEach((position, entity) -> + object.setUnsignedBlockEntity(position.x(), position.y(), position.z(), entity)); + return object; + } + + private BlockPosition unsignedPositionOf(IrisBlockVector signed) { + return new BlockPosition( + signed.getBlockX() + center.getBlockX(), + signed.getBlockY() + center.getBlockY(), + signed.getBlockZ() + center.getBlockZ()); + } + + /** + * The contents of an object as IrisApi values, at unsigned positions. + * + * @param blocks the stored blocks, which a tool may change; an edited map goes back through {@link #with} + * @param blockEntities the stored block entities + * @param customBlocks where the stored block is a custom-content block that only the platform can place + * @param blocksNeedingEntity where the stored block is of a kind that carries a block entity + */ + public static final class ApiContents { + private static final BlockState UNREADABLE_BLOCK = BlockState.parse("minecraft:cave_air"); + + private final PlatformBlockStates conversion; + private final Map blocks; + private final Map blockEntities; + private final Set customBlocks; + private final Set blocksNeedingEntity; + + private ApiContents(PlatformBlockStates conversion, Map blocks, + Map blockEntities, Set customBlocks, + Set blocksNeedingEntity) { + this.conversion = conversion; + this.blocks = blocks; + this.blockEntities = blockEntities; + this.customBlocks = customBlocks; + this.blocksNeedingEntity = blocksNeedingEntity; + } + + public Map blocks() { + return blocks; + } + + public Map blockEntities() { + return blockEntities; + } + + public Set customBlocks() { + return customBlocks; + } + + public Set blocksNeedingEntity() { + return blocksNeedingEntity; + } + + /** These contents with other blocks and block entities, such as a resized copy; the platform states stay the same ones. */ + public ApiContents with(Map blocks, Map blockEntities) { + return new ApiContents(conversion, blocks, blockEntities, customBlocks, blocksNeedingEntity); + } + + private PlatformBlockState platformStateOf(BlockState state) { + return conversion.toPlatform(state); + } + } + /** This object as IrisApi geometry, read once until its blocks change. */ public GeneratedObject getGeometry() { return geometry.aquireOrThrow(() -> ObjectGeometry.of(this)); diff --git a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/IrisStructureHandler.java b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/IrisStructureHandler.java deleted file mode 100644 index faac8e8e7..000000000 --- a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/IrisStructureHandler.java +++ /dev/null @@ -1,58 +0,0 @@ -package art.arcane.iris.util.common.director.specialhandlers; - -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.PackModulesException; -import art.arcane.iris.core.pack.PackDirectoryResolver; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.util.common.director.DirectorParameterHandler; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.director.exceptions.DirectorParsingException; - -import java.io.File; -import java.util.LinkedHashSet; -import java.util.Set; - -public final class IrisStructureHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - Set keys = new LinkedHashSet<>(); - IrisData activeData = data(); - if (activeData != null) { - addStructureKeys(keys, activeData); - } - for (File pack : PackDirectoryResolver.listVisiblePackDirectories( - IrisPlatforms.get().packsFolder())) { - addStructureKeys(keys, IrisData.get(pack)); - } - return new KList<>(keys); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - for (String option : getPossibilities(input)) { - if (option.equalsIgnoreCase(input)) { - return option; - } - } - throw new DirectorParsingException("Unable to find Iris structure \"" + input + "\""); - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - - /** A pack whose modules fail to load has no structures to offer; its failure was reported when it loaded. */ - private static void addStructureKeys(Set keys, IrisData data) { - try { - keys.addAll(StructureResources.structureKeys(data.getPackResources())); - } catch (PackModulesException ignored) { - } - } -} diff --git a/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java b/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java index 30c94f32e..b6887c376 100644 --- a/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java +++ b/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java @@ -112,6 +112,11 @@ final class FakeToolPlayer implements ToolPlayer { return sneaking; } + @Override + public java.util.Optional targetBlock(int maxDistance) { + return java.util.Optional.empty(); + } + @Override public void run(Runnable task) { if (ownedElsewhere) { diff --git a/core/src/test/java/art/arcane/iris/core/structure/FakePlatformStructures.java b/core/src/test/java/art/arcane/iris/core/structure/FakePlatformStructures.java new file mode 100644 index 000000000..556be69ca --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/structure/FakePlatformStructures.java @@ -0,0 +1,82 @@ +package art.arcane.iris.core.structure; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.JigsawStructureInfo; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplatePool; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** A platform with exactly the structures, templates and pools a test gives it, and no way to capture. */ +public final class FakePlatformStructures implements PlatformStructures { + private final List structures = new ArrayList<>(); + private final List structureSets = new ArrayList<>(); + private final Map templates = new LinkedHashMap<>(); + private final Map jigsaws = new LinkedHashMap<>(); + private final Map pools = new LinkedHashMap<>(); + + public FakePlatformStructures withStructures(String... keys) { + for (String key : keys) { + structures.add(ResourceId.parse(key)); + } + return this; + } + + public FakePlatformStructures withStructureSets(String... keys) { + for (String key : keys) { + structureSets.add(ResourceId.parse(key)); + } + return this; + } + + public FakePlatformStructures withTemplate(String key, StructureTemplate template) { + templates.put(ResourceId.parse(key), template); + return this; + } + + @Override + public List templates() { + return new ArrayList<>(templates.keySet()); + } + + @Override + public Optional template(ResourceId id) { + return Optional.ofNullable(templates.get(id)); + } + + @Override + public List structures() { + return List.copyOf(structures); + } + + @Override + public List structureSets() { + return List.copyOf(structureSets); + } + + @Override + public Optional jigsaw(ResourceId structure) { + return Optional.ofNullable(jigsaws.get(structure)); + } + + @Override + public Optional pool(ResourceId pool) { + return Optional.ofNullable(pools.get(pool)); + } + + @Override + public boolean supportsCapture() { + return false; + } + + @Override + public Optional openCaptureArea(Sender sender) { + return Optional.empty(); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/structure/StructureImporterCaptureTest.java b/core/src/test/java/art/arcane/iris/core/structure/StructureImporterCaptureTest.java index 4299e4a02..6433727e6 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/StructureImporterCaptureTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/StructureImporterCaptureTest.java @@ -19,39 +19,40 @@ package art.arcane.iris.core.structure; import art.arcane.iris.core.structure.authoring.StructureCapability; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; -import org.bukkit.structure.Palette; -import org.bukkit.structure.Structure; -import org.bukkit.util.BlockVector; +import art.arcane.iris.engine.UsableBlockPlatform; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplateBlock; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import java.util.List; +import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class StructureImporterCaptureTest { + @Before + public void bindBlocks() { + UsableBlockPlatform.bind(); + } + + @After + public void unbindBlocks() { + UsableBlockPlatform.unbind(); + } + @Test public void captureReturnsAnInMemorySnapshotWithDistinctBlockMarkerLoss() { - Structure structure = mock(Structure.class); - Palette palette = mock(Palette.class); - BlockState marker = mock(BlockState.class); - BlockData markerData = mock(BlockData.class); - Location location = mock(Location.class); - when(structure.getSize()).thenReturn(new BlockVector(2, 3, 4)); - when(structure.getPalettes()).thenReturn(List.of(palette)); - when(structure.getPaletteCount()).thenReturn(2); - when(structure.getEntityCount()).thenReturn(1); - when(palette.getBlocks()).thenReturn(List.of(marker)); - when(marker.getLocation()).thenReturn(location); - when(marker.getBlockData()).thenReturn(markerData); - when(markerData.getMaterial()).thenReturn(Material.STRUCTURE_BLOCK); + StructureTemplate structure = new StructureTemplate( + new BlockPosition(2, 3, 4), + 2, + 1, + List.of(block("minecraft:structure_block", 0))); StructureImporter.CapturedStructure captured = StructureImporter.captureStructure(structure); @@ -71,13 +72,11 @@ public class StructureImporterCaptureTest { @Test public void captureCountsStoredAirSeparatelyFromPhysicalBlocks() { - Structure structure = mock(Structure.class); - Palette palette = mock(Palette.class); - BlockState air = blockState(Material.AIR, "minecraft:air", 0); - BlockState stone = blockState(Material.STONE, "minecraft:stone", 1); - when(structure.getSize()).thenReturn(new BlockVector(2, 1, 1)); - when(structure.getPalettes()).thenReturn(List.of(palette)); - when(palette.getBlocks()).thenReturn(List.of(air, stone)); + StructureTemplate structure = new StructureTemplate( + new BlockPosition(2, 1, 1), + 1, + 0, + List.of(block("minecraft:air", 0), block("minecraft:stone", 1))); StructureImporter.CapturedStructure captured = StructureImporter.captureStructure(structure); @@ -85,15 +84,7 @@ public class StructureImporterCaptureTest { assertEquals(1, captured.nonAirBlocks()); } - private static BlockState blockState(Material material, String state, int x) { - BlockState block = mock(BlockState.class); - BlockData data = mock(BlockData.class); - Location location = mock(Location.class); - when(block.getLocation()).thenReturn(location); - when(block.getBlockData()).thenReturn(data); - when(location.getBlockX()).thenReturn(x); - when(data.getMaterial()).thenReturn(material); - when(data.getAsString()).thenReturn(state); - return block; + private static TemplateBlock block(String state, int x) { + return TemplateBlock.of(new BlockPosition(x, 0, 0), BlockState.parse(state), Optional.empty()); } } diff --git a/core/src/test/java/art/arcane/iris/core/structure/StructureImporterModeTest.java b/core/src/test/java/art/arcane/iris/core/structure/StructureImporterModeTest.java index 198b8ce25..9719bec8e 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/StructureImporterModeTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/StructureImporterModeTest.java @@ -18,7 +18,7 @@ package art.arcane.iris.core.structure; -import org.bukkit.NamespacedKey; +import com.volmit.resource.ResourceId; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -62,12 +62,12 @@ public class StructureImporterModeTest { @Test public void deriveNameFromNamespacedKeyJoinsNamespaceAndPath() { - assertEquals("minecraft_village", StructureImporter.deriveName(NamespacedKey.minecraft("village"))); + assertEquals("minecraft_village", StructureImporter.deriveName(ResourceId.parse("minecraft:village"))); } @Test public void deriveNameFromNamespacedKeyNormalizesSlashesInPath() { - NamespacedKey key = NamespacedKey.fromString("nova_structures:temple/large"); + ResourceId key = ResourceId.parse("nova_structures:temple/large"); assertEquals("nova_structures_temple_large", StructureImporter.deriveName(key)); } diff --git a/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java b/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java index 65fc15e93..ae721aaa5 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java @@ -1,16 +1,13 @@ package art.arcane.iris.core.structure; -import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisModuleHost; import art.arcane.iris.core.modules.ModuleResourceFixture; import art.arcane.iris.core.modules.StructureModelModule; +import art.arcane.iris.core.tooling.IrisToolPack; +import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformStructureHooks; -import org.junit.After; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -18,38 +15,19 @@ import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.List; +import java.nio.file.Files; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class StructureIndexServiceTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private IrisPlatform previousPlatform; - - @Before - public void detachPlatform() { - previousPlatform = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; - IrisPlatforms.unbind(); - } - - @After - public void restorePlatform() { - IrisPlatforms.unbind(); - if (previousPlatform != null) { - IrisPlatforms.bind(previousPlatform); - } - } - @Test public void generatedIndexLivesOutsideStructureRegistrantDirectory() throws Exception { File pack = temporaryFolder.newFolder("pack"); @@ -60,30 +38,24 @@ public class StructureIndexServiceTest { } @Test - public void writeOnceWaitsForBoundHooksThenWritesOnce() throws Exception { + public void writeListsPlatformStructuresAndTheStructuresOfThePack() throws Exception { File pack = temporaryFolder.newFolder("pack"); IrisData data = mock(IrisData.class); - IrisPlatform platform = mock(IrisPlatform.class); - PlatformStructureHooks structureHooks = mock(PlatformStructureHooks.class); ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); when(data.getDataFolder()).thenReturn(pack); ModuleResourceFixture.serve(data).resource(StructureResources.STRUCTURES, "castle", new IrisStructure()); - when(structureHooks.structureKeys()).thenReturn(List.of("minecraft:village", "example:castle")); - when(structureHooks.structureSetKeys()).thenReturn(List.of("minecraft:villages")); + FakePlatformStructures platform = new FakePlatformStructures() + .withStructures("minecraft:village", "example:castle") + .withStructureSets("minecraft:villages"); - assertNull(StructureIndexService.writeOnce(data)); - - IrisPlatforms.bind(platform); - assertNull(StructureIndexService.writeOnce(data)); - - when(platform.structureHooks()).thenReturn(structureHooks); - File index = StructureIndexService.writeOnce(data); + File index = StructureIndexService.write(new IrisToolPack(data, IrisModuleHost.hostLog()), platform); assertEquals(StructureIndexService.indexFile(pack), index); - assertTrue(index.isFile()); - assertNull(StructureIndexService.writeOnce(data)); - verify(structureHooks, times(1)).structureKeys(); - verify(structureHooks, times(1)).structureSetKeys(); + String written = Files.readString(index.toPath()); + assertTrue(written.contains("minecraft:village")); + assertTrue(written.contains("example:castle")); + assertTrue(written.contains("minecraft:villages")); + assertTrue(written.contains("\"castle\"")); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterConnectorRoundTripTest.java b/core/src/test/java/art/arcane/iris/core/structure/VillageImporterConnectorRoundTripTest.java index 925db0852..b0a33e340 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterConnectorRoundTripTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/VillageImporterConnectorRoundTripTest.java @@ -19,6 +19,10 @@ import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.nbt.io.NBTUtil; import art.arcane.volmlib.util.nbt.tag.CompoundTag; import com.google.gson.Gson; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.TemplatePool; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -43,22 +47,19 @@ public class VillageImporterConnectorRoundTripTest { @Test public void vanillaNbtMetadataSurvivesIrisPieceAndVanillaExport() throws Exception { - FakeJigsawBlockInfo jigsaw = new FakeJigsawBlockInfo(-29, -17); - FakeStructureBlockInfo info = new FakeStructureBlockInfo(new FakeCompoundTag(FINAL_STATE)); - VillageImporter.ConnectorMetadata metadata = VillageImporter.readConnectorMetadata(jigsaw, info); - Map importedConnector = VillageImporter.connectorJson( - 1, - 1, - 0, - "north", - "up", - "minecraft:terminal", - "roundtrip", + TemplatePool.JigsawConnector jigsaw = new TemplatePool.JigsawConnector( + new BlockPosition(1, 1, 0), + BlockFace.NORTH, + BlockFace.UP, + Optional.of(ResourceId.parse("minecraft:terminal")), "minecraft:source", "minecraft:door", - "ALIGNED", - metadata + true, + Optional.of(FINAL_STATE), + -17, + -29 ); + Map importedConnector = VillageImporter.connectorJson(jigsaw, "roundtrip"); Map importedPiece = new LinkedHashMap<>(); importedPiece.put("object", "objects/start"); @@ -120,18 +121,6 @@ public class VillageImporterConnectorRoundTripTest { return graph; } - private record FakeJigsawBlockInfo(int placementPriority, int selectionPriority) { - } - - private record FakeStructureBlockInfo(FakeCompoundTag nbt) { - } - - private record FakeCompoundTag(String finalState) { - public Optional getString(String key) { - return "final_state".equals(key) ? Optional.of(finalState) : Optional.empty(); - } - } - private static final class TestGraph implements StructureGraphResolver { private final Map pools = new LinkedHashMap<>(); private final Map pieces = new LinkedHashMap<>(); diff --git a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementTest.java b/core/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementTest.java index 61879d7a2..0792f959d 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementTest.java @@ -28,93 +28,17 @@ import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; public class VillageImporterListPoolElementTest { - @Test - public void plainTemplateElementRemainsUnchanged() throws Exception { - FakeSinglePoolElement single = new FakeSinglePoolElement("minecraft:village/plains/houses/plains_small_house_1"); - - VillageImporter.PoolElementResolution resolution = VillageImporter.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)); - - VillageImporter.PoolElementResolution resolution = VillageImporter.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)); - - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(list); - - assertSame(feature, resolution.physicalElement()); - assertNull(resolution.templateLocation()); - assertEquals(1, resolution.omittedElements()); - } - - @Test - public void emptyListResolvesWithoutIndexingAChild() throws Exception { - VillageImporter.PoolElementResolution resolution = VillageImporter.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") - )); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(towers); - - List> 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 omittedCompositeChildrenProduceExplicitFidelityLoss() throws Exception { - FakeListPoolElement towers = new FakeListPoolElement(List.of( - new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower"), - new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower_overgrown") - )); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(towers); + int listLevels = 1; + int omittedElements = 1; StructureLoss loss = VillageImporter.listElementFallbackLoss( - resolution, + listLevels, + omittedElements, "minecraft:pillager_outpost/towers" ); @@ -373,49 +297,4 @@ public class VillageImporterListPoolElementTest { assertTrue(imported.emittedCapabilities(omitted).isEmpty()); } - private static final class FakeListPoolElement { - private final List elements; - - private FakeListPoolElement(List elements) { - this.elements = List.copyOf(elements); - } - - public List 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; - } - } } diff --git a/core/src/test/java/art/arcane/iris/core/structure/tooling/JigsawCommandsContractTest.java b/core/src/test/java/art/arcane/iris/core/structure/tooling/JigsawCommandsContractTest.java new file mode 100644 index 000000000..5f7da951f --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/structure/tooling/JigsawCommandsContractTest.java @@ -0,0 +1,569 @@ +package art.arcane.iris.core.structure.tooling; + +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.conversion.IrisStructureAdoptionStrategy; +import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.value.IrisPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.ToolPlayer; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +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 JigsawCommandsContractTest { + private static final long DEFAULT_SEED = 1337L; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private final Command root = JigsawCommands.root(Optional::empty); + + @Test + public void theJigsawRootAnswersToItsShortNamesAndHoldsTheWholeTree() { + assertEquals("jigsaw", root.name()); + assertEquals(List.of("jig", "jgs"), root.aliases()); + for (String name : List.of("adopt", "connector", "pool", "piece", "variant", "workcell", "rules", "preview")) { + assertTrue(name, child(root, name).action().isEmpty()); + } + } + + @Test + public void exposesStudioLifecycleAndAuthoringCommands() { + assertArguments("create", "key", "mode", "compatibility", "width", "height", "depth", "seed"); + assertArguments("convert", "source", "target", "seed"); + assertArguments("open", "key", "seed"); + assertArguments("close", "discard"); + assertArguments("delete", "confirm"); + assertArguments("status"); + assertArguments("menu"); + assertArguments("select"); + assertArguments("bounds", "width", "height", "depth"); + assertArguments("save", "bay"); + assertArguments("goto", "bay"); + assertArguments("particles", "visible"); + assertArguments("export", "namespace", "output", "format", "replace"); + } + + @Test + public void importAndCaptureAreJigsawCommandsAndNeedNoPlayer() { + Command importAll = child(root, "import"); + Command capture = child(root, "capture"); + + assertEquals(List.of("import-all", "reimport", "imp", "all"), importAll.aliases()); + assertEquals(List.of("cap"), capture.aliases()); + assertTrue(importAll.arguments().isEmpty()); + assertTrue(capture.arguments().isEmpty()); + assertTrue(importAll.action().isPresent()); + assertTrue(capture.action().isPresent()); + } + + @Test + public void committedActivationStartsInitialEvaluationBeforePlayerBinding() throws Exception { + String source = source("StudioLifecycleCommands.java"); + int commit = source.indexOf("registry.commit(staged)"); + int evaluation = source.indexOf( + "use.studio().activationCommitted(request.requestId())", + commit); + int binding = source.indexOf("StudioSessions.bind(", evaluation); + + assertTrue(commit >= 0); + assertTrue(evaluation > commit); + assertTrue(binding > evaluation); + } + + @Test + public void convertIsAddOnlyWorkflowWithAliasesAndDefaults() { + Command convert = child(root, "convert"); + + assertEquals(List.of("import-vanilla"), convert.aliases()); + assertEquals("auto", convert.arguments().get(1).fallback()); + assertEquals(DEFAULT_SEED, convert.arguments().get(2).fallback()); + ResourceId source = StudioLifecycleCommands.parseRegisteredStructureKey("minecraft:village_plains"); + assertEquals("minecraft_village_plains", StudioLifecycleCommands.resolveConversionTarget(source, "auto")); + assertEquals("villages/plains", StudioLifecycleCommands.resolveConversionTarget(source, "iris:villages/plains")); + ResourceId ancientCity = StudioLifecycleCommands.parseRegisteredStructureKey("minecraft:ancient_city"); + assertEquals("minecraft_ancient_city", StudioLifecycleCommands.resolveConversionTarget(ancientCity, "auto")); + assertThrows(IllegalArgumentException.class, + () -> StudioLifecycleCommands.resolveConversionTarget(source, "custom:village")); + } + + @Test + public void adoptionCommandsExposeTwoStepPlanContract() { + Command adopt = child(root, "adopt"); + Command inspect = child(adopt, "inspect"); + Command apply = child(adopt, "apply"); + + assertEquals(List.of("source", "target", "strategy"), argumentNames(inspect)); + assertEquals("auto", inspect.arguments().get(1).fallback()); + assertEquals("auto", inspect.arguments().get(2).fallback()); + assertEquals(List.of("plan"), argumentNames(apply)); + assertEquals(List.of("auto", "clone", "in-place"), inspect.arguments().get(2).complete("", null)); + assertEquals(IrisStructureAdoptionStrategy.IN_PLACE, AdoptionCommands.parseAdoptionStrategy("claim")); + assertEquals(IrisStructureAdoptionStrategy.CLONE, AdoptionCommands.parseAdoptionStrategy("copy")); + assertThrows(IllegalArgumentException.class, () -> AdoptionCommands.parseAdoptionStrategy("overwrite")); + } + + @Test + public void adoptionInputKindUsesOnlyOwnershipProvenance() throws Exception { + Path packRoot = temporaryFolder.newFolder("adoption-provenance").toPath(); + + assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS, + AdoptionCommands.adoptionInputKind(packRoot, "unowned")); + writeManifest(packRoot, "datapack-created", StructureSource.Kind.DATAPACK, + StructureOwnershipManifest.Provenance.created()); + assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS, + AdoptionCommands.adoptionInputKind(packRoot, "datapack-created")); + writeManifest(packRoot, "managed-provenance", StructureSource.Kind.IRIS, managedProvenance()); + assertEquals(IrisStructureAdoptionInputKind.MANAGED_DATAPACK, + AdoptionCommands.adoptionInputKind(packRoot, "managed-provenance")); + } + + @Test + public void legacyGraphWritersShareTheServiceMutationContract() throws Exception { + Method mutation = GraphMutations.class.getDeclaredMethod( + "runGraphMutation", + StudioUse.class, + StudioSessions.ActiveContext.class, + JigsawStudioService.CommandGraphMutation.class); + + assertEquals(void.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() { + assertEquals("Flush the automatic save for a workcell now", child(root, "save").description()); + assertEquals("Show active Jigsaw Studio and dynamic evaluation state", child(root, "status").description()); + assertEquals("Set the selected Studio workcell capacity", child(root, "bounds").description()); + assertThrows(IllegalStateException.class, () -> child(root, "validate")); + } + + @Test + public void createDefaultsToPlanarIrisWithCompleteCellAndSeedDefaults() { + List> arguments = child(root, "create").arguments(); + + assertEquals("planar", arguments.get(1).fallback()); + assertEquals("iris", arguments.get(2).fallback()); + assertEquals(15L, arguments.get(3).fallback()); + assertEquals(15L, arguments.get(4).fallback()); + assertEquals(15L, arguments.get(5).fallback()); + assertEquals(DEFAULT_SEED, arguments.get(6).fallback()); + } + + @Test + public void structureKeysExplainTheirResourceAndOpenSupportsEditingAliases() { + Command create = child(root, "create"); + Command open = child(root, "open"); + + assertEquals("key", create.arguments().getFirst().name()); + assertEquals("New key written as structures/.json", create.arguments().getFirst().description()); + assertEquals("key", open.arguments().getFirst().name()); + assertEquals("Existing key loaded from structures/.json", open.arguments().getFirst().description()); + assertEquals(List.of("edit", "reopen"), open.aliases()); + } + + @Test + public void createChoicesExposeCanonicalCompletionsAndRetainAliases() { + Command create = child(root, "create"); + + assertEquals(List.of("planar", "spatial"), create.arguments().get(1).complete("", null)); + assertEquals(JigsawStudioMode.PLANAR_JIGSAW, StudioLifecycleCommands.parseMode("2d")); + assertEquals(JigsawStudioMode.SPATIAL_JIGSAW, StudioLifecycleCommands.parseMode("3d")); + assertEquals(List.of("iris", "vanilla"), create.arguments().get(2).complete("", null)); + assertEquals(art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget.IRIS_EXTENDED, + StudioLifecycleCommands.parseCompatibility("extended")); + assertEquals(art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget.VANILLA_PORTABLE, + StudioLifecycleCommands.parseCompatibility("portable")); + assertThrows(IllegalArgumentException.class, () -> StudioLifecycleCommands.parseMode("volume")); + assertThrows(IllegalArgumentException.class, () -> StudioLifecycleCommands.parseCompatibility("mixed")); + } + + @Test + public void exposesNestedPieceVariantAndPreviewCommands() { + assertArguments(child(root, "pool"), "create", "poolKey", "fallbackPoolKey"); + assertArguments(child(root, "connector"), "channel", "channel"); + Command piece = child(root, "piece"); + assertArguments(piece, "create", "poolKey", "pieceKey", "weight"); + assertArguments(piece, "add", "poolKey", "pieceKey", "weight"); + assertArguments(piece, "remove", "poolKey"); + assertArguments(piece, "rotatable", "rotatable"); + assertArguments(piece, "expand"); + assertEquals("Resize the selected piece object exactly to workcell capacity", + child(piece, "expand").description()); + Command variant = child(root, "variant"); + assertArguments(variant, "weight", "poolKey", "weight"); + assertArguments(variant, "resize", "width", "height", "depth"); + assertArguments(variant, "label", "displayName"); + assertArguments(variant, "label-reset"); + assertArguments(variant, "duplicate"); + assertArguments(variant, "duplicate-family", "themeKey"); + assertEquals("next", child(variant, "duplicate-family").arguments().getFirst().fallback()); + Command workcell = child(root, "workcell"); + assertArguments(workcell, "capacity", "width", "height", "depth"); + assertArguments(workcell, "label", "displayName"); + assertArguments(workcell, "label-reset"); + Command rules = child(root, "rules"); + assertArguments(rules, "limits", "maxDepth", "maxSizeChunks"); + assertArguments(rules, "fallback", "poolKey", "fallbackPoolKey"); + Command preview = child(root, "preview"); + assertArguments(preview, "assemble", "seed"); + assertArguments(preview, "goto"); + } + + @Test + public void pieceCreateUsesResolvedWorkcellCapacityInsteadOfLayoutDefault() throws Exception { + String source = source("GraphEditCommands.java"); + int create = source.indexOf("private void pieceCreate("); + int add = source.indexOf("private void pieceAdd(", 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); + + GraphMutations.PieceWorkcellResolution exact = GraphMutations.resolvePieceWorkcell( + layout, + eastEnd, + exactObject); + GraphMutations.PieceWorkcellResolution oversized = GraphMutations.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)); + + GraphMutations.PieceWorkcellResolution resolution = GraphMutations.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 everyStudioCommandRejectsSendersThatAreNotPlayers() throws Exception { + List answered = new ArrayList<>(); + RecordingSender sender = new RecordingSender(); + + for (Command command : playerCommands(root)) { + sender.errors.clear(); + command.action().orElseThrow().run(contextOf(sender)); + assertEquals(command.name(), List.of(StudioUse.PLAYERS_ONLY), sender.errors); + answered.add(command.name()); + } + + assertTrue(answered.size() > 30); + } + + @Test + public void exportOutputIsOneSafeChildArtifact() { + Path exportRoot = Path.of("build", "jigsaw-exports").toAbsolutePath().normalize(); + + assertEquals(exportRoot.resolve("village.zip"), JigsawExportCommand.resolveExportDestination( + exportRoot, "village", VanillaJigsawExportFormat.ZIP)); + assertEquals(exportRoot.resolve("village"), JigsawExportCommand.resolveExportDestination( + exportRoot, "village", VanillaJigsawExportFormat.DIRECTORY)); + assertThrows(IllegalArgumentException.class, () -> JigsawExportCommand.resolveExportDestination( + exportRoot, "", VanillaJigsawExportFormat.DIRECTORY)); + assertThrows(IllegalArgumentException.class, () -> JigsawExportCommand.resolveExportDestination( + exportRoot, ".", VanillaJigsawExportFormat.DIRECTORY)); + assertThrows(IllegalArgumentException.class, () -> JigsawExportCommand.resolveExportDestination( + exportRoot, "../all-exports", VanillaJigsawExportFormat.DIRECTORY)); + assertThrows(IllegalArgumentException.class, () -> JigsawExportCommand.resolveExportDestination( + exportRoot, "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"); + + assertTrue(JigsawExportCommand.beginExport(firstPlayer, firstDestination)); + try { + assertFalse(JigsawExportCommand.beginExport(firstPlayer, secondDestination)); + assertFalse(JigsawExportCommand.beginExport(secondPlayer, firstDestination)); + } finally { + JigsawExportCommand.finishExport(firstPlayer, firstDestination); + } + + assertTrue(JigsawExportCommand.beginExport(secondPlayer, firstDestination)); + JigsawExportCommand.finishExport(secondPlayer, firstDestination); + } + + @Test + public void exportStartFailuresHavePreciseOperatorMessages() { + assertEquals("The active Jigsaw Studio is no longer available.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.NOT_ACTIVE)); + assertEquals("Only the Jigsaw Studio owner can export this project.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.NOT_OWNER)); + assertEquals("Wait for the pending autosave or discard the edits before exporting the on-disk graph.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.DIRTY)); + assertEquals("The active Jigsaw Studio is closing and cannot be exported.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.CLOSING)); + assertEquals("Wait for the current Jigsaw Studio save to finish before exporting.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.SAVE_IN_PROGRESS)); + assertEquals("Wait for the current Jigsaw Studio operation to finish before exporting.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.OPERATION_IN_PROGRESS)); + assertEquals("A Jigsaw Studio export is already in progress.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.IN_PROGRESS)); + assertThrows(IllegalArgumentException.class, + () -> JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.STARTED)); + } + + @Test + public void exportLeaseReleaseActionRunsExactlyOnce() { + AtomicInteger releases = new AtomicInteger(); + JigsawExportCommand.ExportLease lease = new JigsawExportCommand.ExportLease(releases::incrementAndGet); + + lease.release(); + lease.release(); + + assertEquals(1, releases.get()); + } + + @Test + public void exportSourceAcquiresStudioLeaseBeforeStaticLeaseAndReleasesBothPaths() throws Exception { + String source = source("JigsawExportCommand.java"); + int serviceLease = source.indexOf("studioService.tryBeginExport(requestId, playerId)"); + int staticLease = source.indexOf("beginExport(playerId, destination)", serviceLease); + int dispatch = source.indexOf("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); + } + + @Test + public void exportGoesBelowTheOutputFolderOfThePack() throws Exception { + String source = source("JigsawExportCommand.java"); + + assertTrue(source.contains("use.pack().outputFolder()")); + } + + private static Command child(Command parent, String name) { + return parent.children().stream() + .filter(command -> command.answersTo(name)) + .findFirst() + .orElseThrow(() -> new IllegalStateException(parent.name() + " has no sub-command " + name)); + } + + private void assertArguments(String name, String... argumentNames) { + assertArguments(root, name, argumentNames); + } + + private static void assertArguments(Command parent, String name, String... argumentNames) { + Command command = child(parent, name); + assertTrue(name, command.action().isPresent()); + assertEquals(name, List.of(argumentNames), argumentNames(command)); + } + + private static List argumentNames(Command command) { + return command.arguments().stream().map(Argument::name).toList(); + } + + private static List playerCommands(Command parent) { + List commands = new ArrayList<>(); + for (Command child : parent.children()) { + if (parent.name().equals("jigsaw") && (child.name().equals("import") || child.name().equals("capture"))) { + continue; + } + if (child.action().isPresent()) { + commands.add(child); + } + commands.addAll(playerCommands(child)); + } + return commands; + } + + private static String source(String fileName) throws Exception { + return Files.readString(Path.of("src/main/java/art/arcane/iris/core/structure/tooling", fileName)) + .replace("\r\n", "\n"); + } + + private static CommandContext contextOf(Sender sender) { + return (CommandContext) java.lang.reflect.Proxy.newProxyInstance( + JigsawCommandsContractTest.class.getClassLoader(), + new Class[]{CommandContext.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("sender")) { + return sender; + } + throw new IllegalStateException("A command that needs a player asks for " + method.getName() + " too early"); + }); + } + + private static final class RecordingSender implements Sender { + private final List errors = new ArrayList<>(); + + @Override + public String name() { + return "console"; + } + + @Override + public void info(String message) { + } + + @Override + public void success(String message) { + } + + @Override + public void error(String message) { + errors.add(message); + } + + @Override + public Optional extension(Class type) { + return Optional.empty(); + } + + @Override + public Optional player() { + return Optional.empty(); + } + } + + private static JigsawStudioLayout nonuniformPlanarLayout() { + List 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 writeManifest( + Path packRoot, + 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(packRoot).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); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/tooling/StructureCommandsTest.java b/core/src/test/java/art/arcane/iris/core/tooling/StructureCommandsTest.java index 83fb1658d..f3c7c051f 100644 --- a/core/src/test/java/art/arcane/iris/core/tooling/StructureCommandsTest.java +++ b/core/src/test/java/art/arcane/iris/core/tooling/StructureCommandsTest.java @@ -3,6 +3,7 @@ package art.arcane.iris.core.tooling; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.ModuleResourceFixture; import art.arcane.iris.core.modules.StructureModelModule; +import art.arcane.iris.core.structure.FakePlatformStructures; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.object.structure.IrisStructure; @@ -70,7 +71,9 @@ public class StructureCommandsTest { public List names() { return List.of("overworld"); } - }, Runnable::run, Optional::empty); + }, Runnable::run, Optional::empty, () -> Optional.of(new FakePlatformStructures() + .withStructures("minecraft:village", "example:castle") + .withStructureSets("minecraft:villages"))); } @After diff --git a/core/src/test/java/art/arcane/iris/core/tooling/StructureIndexOnStartTest.java b/core/src/test/java/art/arcane/iris/core/tooling/StructureIndexOnStartTest.java new file mode 100644 index 000000000..989b7e877 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/StructureIndexOnStartTest.java @@ -0,0 +1,61 @@ +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.core.modules.StructureModelModule; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.mantle.components.StructureModule; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.spi.IrisServices; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.PlatformStructures; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class StructureIndexOnStartTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + @After + public void withoutPlatformStructures() { + IrisServices.remove(PlatformStructures.class); + } + + @Test + public void writeOnceWaitsForPlatformStructuresThenWritesOnce() throws Exception { + File pack = temporaryFolder.newFolder("pack"); + IrisData data = mock(IrisData.class); + PlatformStructures platform = mock(PlatformStructures.class); + ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); + when(data.getDataFolder()).thenReturn(pack); + ModuleResourceFixture.serve(data).resource(StructureResources.STRUCTURES, "castle", new IrisStructure()); + when(platform.structures()).thenReturn(List.of(ResourceId.parse("minecraft:village"), ResourceId.parse("example:castle"))); + when(platform.structureSets()).thenReturn(List.of(ResourceId.parse("minecraft:villages"))); + + assertNull(StructureIndexOnStart.writeOnce(data)); + + IrisServices.register(PlatformStructures.class, platform); + File index = StructureIndexOnStart.writeOnce(data); + + assertEquals(new File(pack, ".iris/structure-index.json"), index); + assertTrue(index.isFile()); + assertNull(StructureIndexOnStart.writeOnce(data)); + verify(platform, times(1)).structures(); + verify(platform, times(1)).structureSets(); + } +}