mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-30 09:44:24 +00:00
Merge feat/structure-jigsaw-modules into port/v3-features
Structure placement and jigsaw now live in the built-in modules jar, on top of the port's weighted picking, studio tooling
and procedural object work.
api/CONTRACTS.md keeps both sides' rows: the weighted entries and the studio bake and scene creation types from the port,
and VanillaStructureContext.world, Argument.reading, PlatformStructures, tool worlds and the services lookup from the
structure move.
PackModuleResourceKindTest installs the built-in modules jar into its castle pack, as the structure move requires, and
writes the dimension and region lists as weighted entries, as the port requires.
StructurePlacing takes the structure move's version. Its int sentinel for a sampled height is replaced by an explicit
sampledHeight flag that calls ObjectRun.automatic, and explicit pieces pass their world Y minus the world's minimum, so an
explicit world Y below zero stays a height (e3dd61c17).
StructureOutputPinTest.everyScenarioPlacesThePinnedStructures is re-baselined for the underground scenario's writes hash
only (9176f55f60410c117cdd9d5e to 1025f82c04539d4881a0e92b): pieces at world Y -1 are now placed there instead of on the
surface. The start count, the piece hash and every other scenario are unchanged.
This commit is contained in:
commit
2889274291
514 files changed
+29979
-15110
No files matched your search
@@ -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,8 +30,15 @@ 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.structure.BulkStructureImporter;
|
||||
import art.arcane.iris.core.structure.StructureImporter;
|
||||
import art.arcane.iris.core.modules.IrisModuleHost;
|
||||
import art.arcane.iris.core.modules.PackServices;
|
||||
import art.arcane.iris.core.tooling.IrisToolPack;
|
||||
import art.arcane.iris.core.tooling.VolmitToolSender;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.DatapackImportReport;
|
||||
import com.volmit.tooling.DatapackStructureImport;
|
||||
import com.volmit.tooling.PlatformStructures;
|
||||
import art.arcane.iris.core.structure.authoring.StructureBundleNames;
|
||||
import art.arcane.iris.core.structure.authoring.StructureKey;
|
||||
import art.arcane.iris.core.structure.authoring.StructureSource;
|
||||
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
|
||||
@@ -76,6 +84,7 @@ import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
@@ -96,6 +105,7 @@ import java.util.stream.Stream;
|
||||
|
||||
public final class DatapackIngestService {
|
||||
private static final String USER_AGENT = "VolmitSoftware/Iris (datapack-ingest)";
|
||||
private static final String NO_STRUCTURE_IMPORT_KEY = "datapack-structure-import-missing:";
|
||||
private static final String FINDER_METADATA = ".DS_Store";
|
||||
private static final String OVERRIDES_STRIPPED_MARKER = ".iris-overrides-stripped";
|
||||
private static final String OWNERSHIP_MARKER = ".iris-managed.json";
|
||||
@@ -3299,19 +3309,30 @@ public final class DatapackIngestService {
|
||||
}
|
||||
attemptedPacks++;
|
||||
try {
|
||||
BulkStructureImporter.Report report = BulkStructureImporter.importManagedDatapackStructures(
|
||||
data,
|
||||
StructureImporter.Mode.OVERWRITE,
|
||||
BukkitPlatform.console(),
|
||||
structureKeys,
|
||||
templateKeys
|
||||
Optional<DatapackStructureImport> structureImport = PackServices.of(data)
|
||||
.providers(DatapackStructureImport.class).stream().findFirst();
|
||||
if (structureImport.isEmpty()) {
|
||||
IrisLogging.warnOnce(NO_STRUCTURE_IMPORT_KEY + data.getDataFolder().getAbsolutePath(),
|
||||
"Pack '%s' has no module that imports datapack structures; they stay pending until it has one.",
|
||||
data.getDataFolder().getPath());
|
||||
failedUrls.addAll(pendingUrls);
|
||||
reconcileFailedImportInventories(root, manifest, data, targetId, pendingUrls, entriesByUrl);
|
||||
continue;
|
||||
}
|
||||
DatapackImportReport report = structureImport.get().importAll(
|
||||
new IrisToolPack(data, IrisModuleHost.hostLog()),
|
||||
IrisServices.get(PlatformStructures.class),
|
||||
new VolmitToolSender(BukkitPlatform.console()),
|
||||
resourceIds(structureKeys),
|
||||
resourceIds(templateKeys)
|
||||
);
|
||||
Map<String, String> importedBundles = bundleKeys(report);
|
||||
Set<String> successfulPendingUrls = new HashSet<>(pendingUrls);
|
||||
Set<String> incompleteUrls = new HashSet<>();
|
||||
for (String pendingUrl : pendingUrls) {
|
||||
Entry entry = entriesByUrl.get(pendingUrl);
|
||||
Map<String, String> desired = importBundleInventory(entry);
|
||||
if (!report.successfulBundles().entrySet().containsAll(desired.entrySet())) {
|
||||
if (!importedBundles.entrySet().containsAll(desired.entrySet())) {
|
||||
successfulPendingUrls.remove(pendingUrl);
|
||||
incompleteUrls.add(pendingUrl);
|
||||
failedUrls.add(pendingUrl);
|
||||
@@ -3613,13 +3634,23 @@ public final class DatapackIngestService {
|
||||
return bundles;
|
||||
}
|
||||
|
||||
private static List<ResourceId> resourceIds(Collection<String> keys) {
|
||||
return keys.stream().map(ResourceId::ofPlatformKey).toList();
|
||||
}
|
||||
|
||||
private static Map<String, String> bundleKeys(DatapackImportReport report) {
|
||||
Map<String, String> bundles = new TreeMap<>();
|
||||
report.importedBundles().forEach((bundle, source) -> bundles.put(bundle, source.toString()));
|
||||
return bundles;
|
||||
}
|
||||
|
||||
static Map<String, String> importBundleInventory(Entry entry) {
|
||||
Map<String, String> bundles = new TreeMap<>();
|
||||
for (String structureKey : copyList(entry.structureKeys)) {
|
||||
bundles.put("iris:" + StructureImporter.deriveName(structureKey), structureKey);
|
||||
bundles.put(StructureBundleNames.ofStructure(structureKey), structureKey);
|
||||
}
|
||||
for (String templateKey : copyList(entry.templateKeys)) {
|
||||
bundles.put("iris:" + BulkStructureImporter.templateNameFor(templateKey), templateKey);
|
||||
bundles.put(StructureBundleNames.ofTemplate(templateKey), templateKey);
|
||||
}
|
||||
return bundles;
|
||||
}
|
||||
|
||||
@@ -46,50 +46,6 @@ public final class BukkitRuntimeMessages {
|
||||
public static final TextKey COMMAND_PACK_MESSAGE_2 = text("iris.bukkit.runtime.commandpack.message_2");
|
||||
public static final PluralKey COMMAND_PACK_MORE_WARNING_S = plural("iris.bukkit.runtime.commandpack.more_warning_s");
|
||||
public static final LinesKey COMMAND_DEVELOPER_UPDATE_WORLD_WARNING = lines("iris.bukkit.runtime.commanddeveloper.update_world_warning");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTING_VANILLA_DATAPACK_STRUCTURES_MODE_INCLUDENONJIGSAW = text("iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY = text("iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_JIGSAW = text("iris.bukkit.runtime.bulkstructureimporter.jigsaw");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_SINGLE = text("iris.bukkit.runtime.bulkstructureimporter.single");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_SKIP_NO_SINGLE_TEMPLATE_NBT_VANILLA_BUILDS_THIS_CODE_FROM_SEPARATE_PIECE = text("iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL = text("iris.bukkit.runtime.bulkstructureimporter.fail");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_2 = text("iris.bukkit.runtime.bulkstructureimporter.fail_2");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_3 = text("iris.bukkit.runtime.bulkstructureimporter.fail_3");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_BULK_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED_TOTAL = text("iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_BUILDING_SINGLE_TEMPLATE_STRUCTURES_FROM_IMPORTED_PIECES_ONE_VARIANT_PLACED_PER_GENERATION = text("iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_GROUP_VARIANTS = text("iris.bukkit.runtime.bulkstructureimporter.group_variants");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_SKIP = text("iris.bukkit.runtime.bulkstructureimporter.skip");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_4 = text("iris.bukkit.runtime.bulkstructureimporter.fail_4");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_SINGLE_TEMPLATE_STRUCTURES_BUILT_SKIPPED_FAILED = text("iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAILED_ENUMERATE_STRUCTURE_TEMPLATES_VIA_SERVER_RESOURCEMANAGER = text("iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_NO_STRUCTURE_TEMPLATES_WERE_FOUND_UNDER_STRUCTURE_RESOURCE_PATH = text("iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTING_STRUCTURE_TEMPLATES_MODE = text("iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_2 = text("iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_5 = text("iris.bukkit.runtime.bulkstructureimporter.fail_5");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_6 = text("iris.bukkit.runtime.bulkstructureimporter.fail_6");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTED_SKIPPED_FAILED = text("iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_TEMPLATE_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED_TOTAL = text("iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_NO_DATAPACK_NON_MINECRAFT_STRUCTURES_ARE_REGISTERED_INGEST_DATAPACK_RESTART_FIRST_THEN = text("iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTING_DATAPACK_STRUCTURES_MODE = text("iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_3 = text("iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_JIGSAW_2 = text("iris.bukkit.runtime.bulkstructureimporter.jigsaw_2");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_SINGLE_2 = text("iris.bukkit.runtime.bulkstructureimporter.single_2");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_7 = text("iris.bukkit.runtime.bulkstructureimporter.fail_7");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_8 = text("iris.bukkit.runtime.bulkstructureimporter.fail_8");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_9 = text("iris.bukkit.runtime.bulkstructureimporter.fail_9");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTING_DATAPACK_STRUCTURE_TEMPLATES = text("iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_10 = text("iris.bukkit.runtime.bulkstructureimporter.fail_10");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_11 = text("iris.bukkit.runtime.bulkstructureimporter.fail_11");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_COULD_NOT_ENUMERATE_DATAPACK_TEMPLATES_VIA_SERVER_RESOURCEMANAGER = text("iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager");
|
||||
public static final TextKey BULK_STRUCTURE_IMPORTER_DATAPACK_STRUCTURE_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED = text("iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed");
|
||||
public static final TextKey STRUCTURE_CAPTURE_IMPORTER_STRUCTURE_CAPTURE_IS_NOT_SUPPORTED_BY_ACTIVE_NMS_BINDING_SKIPPING_CAPTURE_PASS = text("iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass");
|
||||
public static final TextKey STRUCTURE_CAPTURE_IMPORTER_NO_CODE_GENERATED_STRUCTURES_LEFT_CAPTURE_EVERYTHING_IS_ALREADY_IMPORTED_AS_STRUCTURE = text("iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure");
|
||||
public static final TextKey STRUCTURE_CAPTURE_IMPORTER_CAPTURING_CODE_GENERATED_STRUCTURES_NO_NBT_TEMPLATE_INTO_SCRATCH_WORLD_SKIPPING_ANY = text("iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any");
|
||||
public static final TextKey STRUCTURE_CAPTURE_IMPORTER_SKIP_DID_NOT_PLACE_CAPTURABLE_STRUCTURE_HERE_TOO_LARGE_WRONG_DIMENSION_NO = text("iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no");
|
||||
public static final TextKey STRUCTURE_CAPTURE_IMPORTER_FAIL = text("iris.bukkit.runtime.structurecaptureimporter.fail");
|
||||
public static final TextKey STRUCTURE_CAPTURE_IMPORTER_CAPTURE_OBJECTS_IOB_X_X = text("iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x");
|
||||
public static final TextKey STRUCTURE_CAPTURE_IMPORTER_FAIL_2 = text("iris.bukkit.runtime.structurecaptureimporter.fail_2");
|
||||
public static final TextKey STRUCTURE_CAPTURE_IMPORTER_CAPTURED_SKIPPED_FAILED = text("iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed");
|
||||
public static final TextKey STRUCTURE_CAPTURE_IMPORTER_STRUCTURE_CAPTURE_COMPLETE_CAPTURED_SKIPPED_FAILED_TOTAL = text("iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total");
|
||||
public static final TextKey FEATURE_IMPORTER_NO_VANILLA_TREE_OBJECT_FEATURES_ARE_EXPOSED_BY_ACTIVE_NMS_BINDING_IMPORTING = text("iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing");
|
||||
public static final TextKey FEATURE_IMPORTER_IMPORTING_VANILLA_TREE_OBJECT_FEATURES_VARIANTS_EACH_INTO_SCRATCH_WORLD = text("iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world");
|
||||
public static final TextKey FEATURE_IMPORTER_OBJ_OBJECTS_VANILLA = text("iris.bukkit.runtime.featureimporter.obj_objects_vanilla");
|
||||
|
||||
@@ -175,6 +175,10 @@ final class CarvedVoids implements MantleLayer<CarvedVoid> {
|
||||
}
|
||||
|
||||
private CarvedVoid toApi(MatterCavern cavern) {
|
||||
return toApi(cavern, ids);
|
||||
}
|
||||
|
||||
static CarvedVoid toApi(MatterCavern cavern, PackResourceIds ids) {
|
||||
CarvedVoid plain = switch (cavern.getLiquid()) {
|
||||
case LIQUID_FLUID -> CarvedVoid.FLUID;
|
||||
case LIQUID_LAVA -> CarvedVoid.LAVA;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.block.BlockRegistry;
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.host.ModuleLogs;
|
||||
import com.volmit.item.ItemRegistry;
|
||||
import com.volmit.noise.NoiseFactory;
|
||||
import com.volmit.object.PackObjects;
|
||||
import com.volmit.placement.Placements;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import com.volmit.world.PackWorld;
|
||||
import com.volmit.world.RunningWorld;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* The world a fit has outside any world: a start fitted with its memo needs nothing of a world but the noise its
|
||||
* terrain carving draws on, which comes from plain styles. Everything else a fit could ask of a world fails, saying why.
|
||||
*/
|
||||
final class FitlessWorld implements PackWorld, PackResources {
|
||||
private static final String OUTSIDE_A_WORLD = "The built-in modules fit outside a world here: a start needs its memo"
|
||||
+ " and a fit without palettes";
|
||||
private static final ResourceId PACK = ResourceId.parse("iris:fitless");
|
||||
|
||||
private final UUID snapshot = UUID.randomUUID();
|
||||
private final NoiseFactory noise = IrisNoiseFactory.standalone();
|
||||
|
||||
@Override
|
||||
public long seed() {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackResources resources() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackSettings settings() {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int minWorldY() {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RunningWorld> running() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Placements placements() {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModuleLog log() {
|
||||
return ModuleLogs.discarding();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S> List<S> services(Class<S> service) {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceId packId() {
|
||||
return PACK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID snapshotId() {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockRegistry blocks() {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemRegistry items() {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public NoiseFactory noise() {
|
||||
return noise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackObjects objects() {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Optional<T> find(ResourceKind<T> kind, ResourceId id) {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourceId> ids(ResourceKind<?> kind) {
|
||||
throw outsideAWorld();
|
||||
}
|
||||
|
||||
private static IllegalStateException outsideAWorld() {
|
||||
return new IllegalStateException(OUTSIDE_A_WORLD);
|
||||
}
|
||||
}
|
||||
@@ -148,8 +148,14 @@ final class IrisBlockRegistry implements BlockRegistry {
|
||||
/** A block that cannot face the way it is turned is dropped, as Iris drops it: it becomes air. */
|
||||
@Override
|
||||
public BlockState rotate(BlockState state, BlockTurn turn) {
|
||||
return tryRotate(state, turn).orElse(PlatformBlockStates.AIR);
|
||||
}
|
||||
|
||||
/** Empty exactly when the platform has no state for the turned block, which is when Iris drops it. */
|
||||
@Override
|
||||
public Optional<BlockState> tryRotate(BlockState state, BlockTurn turn) {
|
||||
PlatformBlockState rotated = BlockStateRotation.rotate(turn, platformState(state));
|
||||
return rotated == null ? PlatformBlockStates.AIR : apiState(rotated);
|
||||
return rotated == null ? Optional.empty() : Optional.of(apiState(rotated));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.mantle.components.StructureModule;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleLog;
|
||||
@@ -52,8 +51,14 @@ public final class IrisModuleHost {
|
||||
* and Gson, which every platform Iris runs on provides.
|
||||
*/
|
||||
public static final List<String> SHARED_LIBRARY_PACKAGES = List.of("art.arcane.volmlib", "com.google.gson");
|
||||
/**
|
||||
* The structure file transactions Iris's datapack ingest and the jigsaw module's tools both run, which each would
|
||||
* otherwise see as a copy of its own; exposed with its subpackages.
|
||||
*/
|
||||
public static final String STRUCTURE_FILES_PACKAGE = "art.arcane.iris.core.structure.authoring";
|
||||
/** Every package pack modules may use besides the IrisApi. {@code exposedHostPackages} in IrisModule's build lists the same. */
|
||||
public static final List<String> EXPOSED_PACKAGES = Stream.concat(Stream.of(BUILT_IN_API_PACKAGE), SHARED_LIBRARY_PACKAGES.stream()).toList();
|
||||
public static final List<String> EXPOSED_PACKAGES = Stream.concat(Stream.of(BUILT_IN_API_PACKAGE, STRUCTURE_FILES_PACKAGE),
|
||||
SHARED_LIBRARY_PACKAGES.stream()).toList();
|
||||
/**
|
||||
* The ids of the built-in modules that ship in the built-ins jar ({@code iris-builtins.jar}, listed in
|
||||
* {@code IrisModule/builtin-modules.txt}) instead of being compiled into Iris. Every pack loads them from the jar Iris
|
||||
@@ -62,9 +67,15 @@ public final class IrisModuleHost {
|
||||
public static final List<String> JAR_MODULE_IDS = List.of("iris:post", "iris:perfection", "iris:matter", "iris:loot",
|
||||
"iris:spawn", "iris:prepare", "iris:anchor", "iris:validate", "iris:bore", "iris:blocks", "iris:stilt", "iris:vacuum",
|
||||
"iris:snow", "iris:vanilla-features", "iris:carve", "iris:deposit", "iris:decorant", "iris:terrain", "iris:objects",
|
||||
"iris:floating");
|
||||
/** Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. */
|
||||
public static final String HOST_TYPE_PACKAGE = "art.arcane.iris.engine.object";
|
||||
"iris:floating", "iris:structure", "iris:jigsaw");
|
||||
/**
|
||||
* Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. The
|
||||
* structure model (engine.object.structure) is not among them: it speaks the api's vocabulary and its module describes it.
|
||||
*/
|
||||
public static final String[] HOST_TYPE_PACKAGES = Stream.of("annotations", "compatibility", "image", "material", "noise",
|
||||
"placement", "prefab", "runtime", "terrain", "value", "world")
|
||||
.map(subpackage -> "art.arcane.iris.engine.object." + subpackage)
|
||||
.toArray(String[]::new);
|
||||
private static final String[] JAR_COPY_FOLDER = {"cache", "module-jars"};
|
||||
private static final String BUNDLED_JAR_RESOURCE = "/" + MissingBuiltInModules.JAR_NAME;
|
||||
private static final String BUNDLED_JAR_TEMPORARY_PREFIX = "iris-built-in-modules-";
|
||||
@@ -84,11 +95,10 @@ public final class IrisModuleHost {
|
||||
|
||||
/**
|
||||
* Modules Iris registers itself, not from the built-ins jar: those that are Iris (they write the layout's platform
|
||||
* biomes, record the platform's custom blocks and answer for Iris's structure model) and {@code iris:structure}, whose
|
||||
* resources Iris's jigsaw studio reads as the same classes. A pack never replaces them.
|
||||
* biomes and record the platform's custom blocks). A pack never replaces them.
|
||||
*/
|
||||
private static List<IrisModule> hostModules() {
|
||||
return List.of(new BiomeModule(), new CustomModule(), new StructureModule(), new StructureModelModule());
|
||||
return List.of(new BiomeModule(), new CustomModule());
|
||||
}
|
||||
|
||||
/** Iris's own log, labelled {@code [iris]}, for host code that calls module classes outside any module's stage, service or hook. */
|
||||
@@ -98,14 +108,14 @@ public final class IrisModuleHost {
|
||||
|
||||
/** Whether {@code type} is one of Iris's own classes that built-in settings may hold. */
|
||||
public static boolean isHostType(Class<?> type) {
|
||||
return type.getName().startsWith(HOST_TYPE_PACKAGE + ".");
|
||||
return Stream.of(HOST_TYPE_PACKAGES).anyMatch(hostPackage -> type.getName().startsWith(hostPackage + "."));
|
||||
}
|
||||
|
||||
private static ModuleHost build() {
|
||||
return ModuleHost.of(builtInModules())
|
||||
.exposing(EXPOSED_PACKAGES.toArray(String[]::new))
|
||||
.reservingFields(ModuleTargets.reservedFields())
|
||||
.describingHostTypesIn(HOST_TYPE_PACKAGE)
|
||||
.describingHostTypesIn(HOST_TYPE_PACKAGES)
|
||||
.reservingFolders(IrisData.ownFolderNames().toArray(String[]::new))
|
||||
.bundlingJars(bundledJars())
|
||||
.copyingJarsTo(jarCopyRoot())
|
||||
|
||||
@@ -49,6 +49,11 @@ final class IrisNoiseFactory implements NoiseFactory {
|
||||
this.resources = resources;
|
||||
}
|
||||
|
||||
/** Noise with no pack behind it: the plain styles, but no expressions and no image maps. */
|
||||
static IrisNoiseFactory standalone() {
|
||||
return new IrisNoiseFactory(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NoiseSampler sampler(NoiseStyle style, long seed) {
|
||||
IrisGeneratorStyle iris = styles.computeIfAbsent(style, unbuilt -> IrisValues.generatorStyle(unbuilt, resources));
|
||||
|
||||
@@ -167,6 +167,11 @@ public final class IrisPackResources implements PackResources {
|
||||
return kindOf(kind).ids();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S> List<S> services(Class<S> service) {
|
||||
return PackServices.of(data).providers(service);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids of the resources of the kind {@code kindId} names, for Iris's own tools that list a module's resources
|
||||
* without the module's class for them, which the plugin's classes cannot reach when the kind ships in a module jar.
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.builtin.structure.StructureHost;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
@@ -40,8 +39,8 @@ import java.util.Optional;
|
||||
/**
|
||||
* The settings an engine's pack declares, for working out mantle stage reaches when the pack loads and for vanilla
|
||||
* structure hooks: the engine's dimension, then every region it can reach, then every biome. Iris's built-in modules
|
||||
* decide from Iris's own pack data instead of module settings; they reach it through the object, floating and structure
|
||||
* hosts the settings offer as {@linkplain #extension extensions}.
|
||||
* decide from Iris's own pack data instead of module settings; they reach it through the engine the settings offer as an
|
||||
* {@linkplain #extension extension}.
|
||||
*/
|
||||
public final class IrisPackSettings implements PackSettings {
|
||||
static final String DIMENSION = "dimension";
|
||||
@@ -71,15 +70,9 @@ public final class IrisPackSettings implements PackSettings {
|
||||
return HostExtensions.as(type, offered(type));
|
||||
}
|
||||
|
||||
/** The engine is offered only for the structure built-ins, which drive Iris's structure locator themselves. */
|
||||
/** The engine is offered only for the built-ins that read Iris's own pack data. */
|
||||
private Object offered(Class<?> type) {
|
||||
if (type == Engine.class) {
|
||||
return engine;
|
||||
}
|
||||
if (type == StructureHost.class) {
|
||||
return new IrisStructureHost(engine, IrisApiLogger.hostLog());
|
||||
}
|
||||
return null;
|
||||
return type == Engine.class ? engine : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -18,14 +18,17 @@
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.builtin.structure.StructureHost;
|
||||
import art.arcane.iris.builtin.structure.StructureVerifier;
|
||||
import art.arcane.iris.builtin.structure.StructureSeeds;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.host.WorldStates;
|
||||
import com.volmit.placement.Placements;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.world.PackWorld;
|
||||
import com.volmit.world.RunningWorld;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
@@ -33,7 +36,7 @@ import java.util.function.Function;
|
||||
* One Iris world as modules see it: an engine runtime generating with one snapshot of its pack's resources, and the
|
||||
* state modules keep for it. {@link ModuleWorlds} makes one when the runtime is built and a new one whenever the
|
||||
* pack's resources reload under it. Iris's built-in modules reach what they need of Iris through its
|
||||
* {@linkplain #extension extensions}: the structure host.
|
||||
* {@linkplain #extension extensions}: the engine and the structure verifier.
|
||||
*/
|
||||
public final class IrisPackWorld implements PackWorld {
|
||||
private final Engine engine;
|
||||
@@ -42,7 +45,7 @@ public final class IrisPackWorld implements PackWorld {
|
||||
private final ModuleLog log;
|
||||
private final IrisRunningWorld running;
|
||||
private final Placements placements;
|
||||
private final IrisStructureHost structureHost;
|
||||
private final StructureVerifier structureVerifier;
|
||||
|
||||
IrisPackWorld(Engine engine) {
|
||||
this.engine = engine;
|
||||
@@ -51,7 +54,7 @@ public final class IrisPackWorld implements PackWorld {
|
||||
this.log = IrisApiLogger.hostLog();
|
||||
this.placements = new IrisPlacements(engine.getData(), engine, () -> this);
|
||||
this.running = new IrisRunningWorld(engine, log);
|
||||
this.structureHost = new IrisStructureHost(engine, log);
|
||||
this.structureVerifier = (context, radiusChunks) -> StructureVerification.run(engine, context, radiusChunks);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -69,6 +72,14 @@ public final class IrisPackWorld implements PackWorld {
|
||||
return engine.getSeedManager().getSeed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long seed(ResourceId purpose) {
|
||||
if (StructureSeeds.PLACEMENT.equals(purpose)) {
|
||||
return engine.getSeedManager().getMantle();
|
||||
}
|
||||
return PackWorld.super.seed(purpose);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public IrisPackResources resources() {
|
||||
@@ -77,7 +88,7 @@ public final class IrisPackWorld implements PackWorld {
|
||||
|
||||
@Override
|
||||
public int minWorldY() {
|
||||
return engine.getWorld().minHeight();
|
||||
return engine.getMinHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -100,6 +111,11 @@ public final class IrisPackWorld implements PackWorld {
|
||||
return states.state(type, () -> create.apply(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S> List<S> services(Class<S> service) {
|
||||
return PackServices.of(engine.getData()).providers(service);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModuleLog log() {
|
||||
return log;
|
||||
@@ -115,8 +131,8 @@ public final class IrisPackWorld implements PackWorld {
|
||||
if (type == Engine.class) {
|
||||
return engine;
|
||||
}
|
||||
if (type == StructureHost.class) {
|
||||
return structureHost;
|
||||
if (type == StructureVerifier.class) {
|
||||
return structureVerifier;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -24,11 +24,13 @@ import art.arcane.iris.spi.PlatformWorld;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
|
||||
import art.arcane.volmlib.util.matter.Matter;
|
||||
import art.arcane.volmlib.util.matter.MatterCavern;
|
||||
import art.arcane.volmlib.util.matter.slices.MarkerMatter;
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.config.FeatureSettings;
|
||||
import com.volmit.data.SavedKey;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.mantle.CarvedVoid;
|
||||
import com.volmit.placement.PlacementRecord;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.world.RunningWorld;
|
||||
@@ -139,6 +141,12 @@ final class IrisRunningWorld implements RunningWorld {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<CarvedVoid> carvedAt(int worldX, int y, int worldZ) {
|
||||
MatterCavern cavern = engine.getMantle().getMantle().get(worldX, y, worldZ, MatterCavern.class);
|
||||
return Optional.ofNullable(cavern).map(carved -> CarvedVoids.toApi(carved, packIds()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean debug() {
|
||||
return engine.isStudio();
|
||||
|
||||
@@ -1,70 +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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.builtin.structure.StructureHost;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.engine.mantle.components.StructurePlacing;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.generation.InvocationContext;
|
||||
import com.volmit.resource.ResourceId;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Iris's {@link StructureHost}: the engine's {@link StructurePlacing}, one per engine runtime, places and sizes its structures. */
|
||||
final class IrisStructureHost implements StructureHost {
|
||||
private final Engine engine;
|
||||
private final ModuleLog log;
|
||||
|
||||
IrisStructureHost(Engine engine, ModuleLog log) {
|
||||
this.engine = engine;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void placeChunk(InvocationContext context) {
|
||||
IrisMantleChunk chunk = context.extension(IrisMantleChunk.class).orElseThrow();
|
||||
placing().place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int reach() {
|
||||
return placing().reach();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<List<String>> lootTables(ResourceId structureId) {
|
||||
IrisPackResources resources = engine.getData().getPackResources();
|
||||
IrisStructure structure = StructureResources.structure(resources, resources.keyOf(structureId));
|
||||
if (structure == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (structure.getLoot() == null) {
|
||||
return Optional.of(List.of());
|
||||
}
|
||||
return Optional.of(structure.getLoot().stream().filter(table -> table != null && !table.isBlank()).toList());
|
||||
}
|
||||
|
||||
private StructurePlacing placing() {
|
||||
return engine.getGeneration().state(StructurePlacing.class, generating -> new StructurePlacing(generating, log));
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,11 @@ public final class IrisValidationContext implements ValidationContext {
|
||||
return platform;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S> List<S> services(Class<S> service) {
|
||||
return PackServices.of(data).providers(service);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void report(Problem problem) {
|
||||
problems.add(Objects.requireNonNull(problem, "problem"));
|
||||
|
||||
@@ -99,7 +99,7 @@ public final class ModuleObjectPlacement {
|
||||
}
|
||||
long worldSeed = rng.nextLong();
|
||||
try (ToolWorld toolWorld = new ToolWorld(worldSeed, data.getPackResources(), new PackDeclaredSettings(data),
|
||||
world -> new IrisPlacements(data, null, () -> world))) {
|
||||
PackServices.of(data), world -> new IrisPlacements(data, null, () -> world))) {
|
||||
return run.placeIn(toolWorld, terrain);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import art.arcane.iris.engine.framework.nativefit.NativeFitStart;
|
||||
import art.arcane.iris.engine.framework.nativefit.NativeFitTrait;
|
||||
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
|
||||
import art.arcane.iris.engine.framework.nativefit.NativeTemplateCells;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.block.BlockTrait;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
@@ -62,6 +63,7 @@ import java.util.Optional;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The pack's {@link VanillaStructures} providers fitting the platform's starts into a chunk: the platform code's view
|
||||
@@ -92,14 +94,16 @@ public final class ModuleStructureFitting implements NativeStructureFitting {
|
||||
() -> engine.getGeneration().world());
|
||||
}
|
||||
|
||||
/** The built-in modules' registrations only: their stage graph needs the modules of the built-ins jar too. */
|
||||
public static NativeStructureFitting builtInModules() {
|
||||
/**
|
||||
* Iris's own modules' and {@code modules}' registrations only, whose classes the caller names because they ship in the
|
||||
* built-ins jar: their stage graph needs the rest of the jar too.
|
||||
*/
|
||||
public static NativeStructureFitting ofModules(IrisModule... modules) {
|
||||
ModuleRegistry registry = new ModuleRegistry();
|
||||
IrisModuleHost.builtInModules().forEach(module -> ModuleSetups.run(DiscoveredModule.builtIn(module), new StageGraphBuilder(), registry));
|
||||
return new ModuleStructureFitting(registry.freeze().registrations(VanillaStructures.class), () -> {
|
||||
throw new IllegalStateException("The built-in modules fit outside a world here: a start needs its memo"
|
||||
+ " and a fit without palettes");
|
||||
});
|
||||
Stream.concat(IrisModuleHost.builtInModules().stream(), Stream.of(modules))
|
||||
.forEach(module -> ModuleSetups.run(DiscoveredModule.builtIn(module), new StageGraphBuilder(), registry));
|
||||
FitlessWorld fitless = new FitlessWorld();
|
||||
return new ModuleStructureFitting(registry.freeze().registrations(VanillaStructures.class), () -> fitless);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -54,6 +54,7 @@ import java.util.OptionalInt;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* What the pack's modules want for the platform's own structures, asked through their {@link VanillaStructures}
|
||||
@@ -77,7 +78,8 @@ public final class ModuleVanillaStructures {
|
||||
private ModuleVanillaStructures(Engine engine, PackResources snapshot) {
|
||||
this.snapshot = snapshot;
|
||||
this.providers = providersOf(engine.getData());
|
||||
this.world = new World(snapshot, new IrisPackSettings(engine));
|
||||
this.world = new World(snapshot, new IrisPackSettings(engine),
|
||||
() -> Optional.of(engine.getGeneration().world()));
|
||||
}
|
||||
|
||||
/** The combined rule of the pack's modules for the platform structure {@code structureKey} in {@code engine}'s world. */
|
||||
@@ -139,7 +141,7 @@ public final class ModuleVanillaStructures {
|
||||
|
||||
/** The combined setup of the pack's modules for {@code dimension} of the pack {@code data} serves, before any world exists. */
|
||||
public static VanillaStructureSetup setupFor(IrisData data, IrisDimension dimension) {
|
||||
VanillaStructureContext context = new World(data.getPackResources(), new DimensionSettings(data, dimension));
|
||||
VanillaStructureContext context = new World(data.getPackResources(), new DimensionSettings(data, dimension), Optional::empty);
|
||||
VanillaStructureSetup combined = VanillaStructureSetup.UNCHANGED;
|
||||
for (ServiceRegistration registration : providersOf(data)) {
|
||||
combined = combined.and(ask(registration, "setting up the vanilla structures of dimension " + dimension.getLoadKey(),
|
||||
@@ -241,7 +243,12 @@ public final class ModuleVanillaStructures {
|
||||
}
|
||||
|
||||
/** The world the providers decide for: the engine's pack snapshot and the settings its dimension reaches. */
|
||||
private record World(PackResources resources, PackSettings settings) implements VanillaStructureContext {
|
||||
private record World(PackResources resources, PackSettings settings, Supplier<Optional<PackWorld>> worldSource)
|
||||
implements VanillaStructureContext {
|
||||
@Override
|
||||
public Optional<PackWorld> world() {
|
||||
return worldSource.get();
|
||||
}
|
||||
}
|
||||
|
||||
private record StartContext(PackWorld world, TerrainSampler terrain) implements VanillaStructureStartContext {
|
||||
|
||||
@@ -56,6 +56,24 @@ public final class ObjectGeometry {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link #of}, but the bounds are the size the object file declares around its center, not the box of its blocks,
|
||||
* so the file can be written again at the size it had.
|
||||
*/
|
||||
public static GeneratedObject ofDeclared(IrisObject object) {
|
||||
object.readLock.lock();
|
||||
try {
|
||||
int centerX = object.w / 2;
|
||||
int centerY = object.h / 2;
|
||||
int centerZ = object.d / 2;
|
||||
BlockBox declared = new BlockBox(-centerX, -centerY, -centerZ,
|
||||
object.w - centerX, object.h - centerY, object.d - centerZ);
|
||||
return new GeneratedObject(declared, CENTER, blocksOf(object), List.of());
|
||||
} finally {
|
||||
object.readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<ObjectBlock> blocksOf(IrisObject object) {
|
||||
Map<BlockPosition, ObjectBlock> blocks = new LinkedHashMap<>();
|
||||
for (Map.Entry<IrisBlockVector, PlatformBlockState> entry : object.blocks) {
|
||||
|
||||
@@ -28,9 +28,11 @@ import com.volmit.config.PackSettings;
|
||||
import com.volmit.config.SettingsStack;
|
||||
import com.volmit.resource.PackResources;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The settings a whole pack declares, for validators: every dimension of the pack, then every region, then every
|
||||
@@ -51,6 +53,12 @@ final class PackDeclaredSettings implements PackSettings {
|
||||
return data.getPackResources();
|
||||
}
|
||||
|
||||
/** The pack's folder is offered as a {@link File}, for checks that read the files of the pack as written. */
|
||||
@Override
|
||||
public <T> Optional<T> extension(Class<T> type) {
|
||||
return HostExtensions.as(type, type == File.class ? data.getDataFolder() : null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <F extends IrisFeature> SettingsStack<F> declared(Class<F> featureType) {
|
||||
List<Entry<F>> entries = new ArrayList<>();
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The service providers of one pack's modules, as {@code PackWorld.services}, {@code ValidationContext.services} and
|
||||
* {@code ToolPack.services} answer them. Asking a pack whose modules fail to load throws its {@link PackModulesException}.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface PackServices {
|
||||
/**
|
||||
* Every provider of {@code service}, in module id order; empty when no module provides it.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code service} is not an interface marked as a service
|
||||
*/
|
||||
<S> List<S> providers(Class<S> service);
|
||||
|
||||
/** The providers of the modules of the pack {@code data} holds, looked up whenever they are asked for. */
|
||||
static PackServices of(IrisData data) {
|
||||
Objects.requireNonNull(data, "data");
|
||||
return new PackServices() {
|
||||
@Override
|
||||
public <S> List<S> providers(Class<S> service) {
|
||||
return data.getModules().pack().catalog().services(service);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,19 @@ final class PlacerTerrain implements PlacementTerrain {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearBlock(int x, int y, int z) {
|
||||
placer.clearBlock(x, y, z);
|
||||
if (written != null) {
|
||||
written.remove(new BlockPosition(x, y, z));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearAttached(int x, int y, int z) {
|
||||
placer.clearAttached(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCarved(int x, int y, int z) {
|
||||
return placer.isCarved(x, y, z);
|
||||
|
||||
@@ -1,38 +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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.StructureAssembler;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
|
||||
/**
|
||||
* Structure assembly for Iris's own tools, the commands and studio, which run outside any module's stage, service or hook and so
|
||||
* log as Iris itself.
|
||||
*/
|
||||
public final class StructureAssemblies {
|
||||
private StructureAssemblies() {
|
||||
}
|
||||
|
||||
/** The assembler of {@code structure}, compiled from the pack {@code data} serves, for a start at {@code origin}. */
|
||||
public static StructureAssembler forData(IrisData data, IrisStructure structure, IrisPosition origin) {
|
||||
return StructureAssembler.forData(data, structure, origin, IrisModuleHost.hostLog());
|
||||
}
|
||||
}
|
||||
@@ -1,95 +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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.structure.StructureIndexService;
|
||||
import art.arcane.iris.core.tooling.IrisToolPack;
|
||||
import art.arcane.iris.engine.framework.PlacedStructurePiece;
|
||||
import art.arcane.iris.engine.framework.structure.StructureAssemblyResult;
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.Argument;
|
||||
import com.volmit.tooling.Command;
|
||||
import com.volmit.tooling.CommandContext;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/** 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 {
|
||||
private static final String ROOT_NAME = "structure";
|
||||
private static final long INFO_SAMPLE_SEED = 1234L;
|
||||
private static final int INFO_ORIGIN_Y = 64;
|
||||
|
||||
private static final Argument<ResourceId> STRUCTURE = Argument.resource("structure", StructureResources.STRUCTURES)
|
||||
.describe("The Iris structure to inspect");
|
||||
|
||||
private StructureCommands() {
|
||||
}
|
||||
|
||||
static Command root() {
|
||||
return Command.named(ROOT_NAME).alias("struct", "str")
|
||||
.describe("Iris structure tools")
|
||||
.child(Command.named("list").alias("ls")
|
||||
.describe("Write the index of every vanilla, datapack and Iris structure of the pack")
|
||||
.runs(StructureCommands::list))
|
||||
.child(Command.named("info")
|
||||
.describe("Resolve an Iris structure's jigsaw graph and report its piece count and footprint")
|
||||
.argument(STRUCTURE)
|
||||
.runs(StructureCommands::info))
|
||||
.child(Command.named("verify").alias("locateall")
|
||||
.describe("Verify native structure eligibility and locate Iris-placed structures in the world you stand in")
|
||||
.argument(StructureVerification.RADIUS)
|
||||
.runs(StructureVerification::run));
|
||||
}
|
||||
|
||||
private static void list(CommandContext context) throws IOException {
|
||||
File index = context.pack().edit(packRoot -> StructureIndexService.write(IrisToolPack.dataOf(context.pack())));
|
||||
context.sender().success("Wrote the structure index: " + index.getPath());
|
||||
}
|
||||
|
||||
private static void info(CommandContext context) {
|
||||
ResourceId id = context.get(STRUCTURE);
|
||||
IrisStructure structure = context.pack().resources().require(StructureResources.STRUCTURES, id);
|
||||
StructureAssemblyResult assembly = StructureAssemblies
|
||||
.forData(IrisToolPack.dataOf(context.pack()), structure, new IrisPosition(0, INFO_ORIGIN_Y, 0))
|
||||
.assemble(new RNG(INFO_SAMPLE_SEED));
|
||||
if (!assembly.hasOutput()) {
|
||||
context.sender().error("Structure " + id + " assembled 0 pieces (check startPool '" + structure.getStartPool() + "')");
|
||||
return;
|
||||
}
|
||||
List<PlacedStructurePiece> pieces = assembly.pieces();
|
||||
int minX = Integer.MAX_VALUE;
|
||||
int minZ = Integer.MAX_VALUE;
|
||||
int maxX = Integer.MIN_VALUE;
|
||||
int maxZ = Integer.MIN_VALUE;
|
||||
for (PlacedStructurePiece piece : pieces) {
|
||||
minX = Math.min(minX, piece.getMinX());
|
||||
minZ = Math.min(minZ, piece.getMinZ());
|
||||
maxX = Math.max(maxX, piece.getMaxX());
|
||||
maxZ = Math.max(maxZ, piece.getMaxZ());
|
||||
}
|
||||
context.sender().success("Structure " + id + ": " + pieces.size() + " pieces, footprint " + (maxX - minX + 1) + "x"
|
||||
+ (maxZ - minZ + 1) + " blocks (sample seed " + INFO_SAMPLE_SEED + ")");
|
||||
}
|
||||
}
|
||||
@@ -1,62 +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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
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 com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.service.StructureLocator;
|
||||
import com.volmit.service.VanillaStructures;
|
||||
|
||||
/**
|
||||
* 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}).
|
||||
* <p>
|
||||
* It checks them with {@link StructureValidator} wherever Iris validates a pack. It lets Iris find its structures
|
||||
* through {@link StructureLocating}; a world's structure index lives in the
|
||||
* world's state, so a reload of the pack's structure files, which starts a new world, builds it again.
|
||||
* <p>
|
||||
* It decides over the platform's own structures through its {@link VanillaStructures} provider
|
||||
* ({@link StructureVanillaStructures}): the dimension's {@code importedStructures} settings disable, move, fit and set
|
||||
* 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.
|
||||
* <p>
|
||||
* It mounts {@code /iris module structure list|info|verify} ({@link StructureCommands}) through the tooling api.
|
||||
*/
|
||||
public final class StructureModelModule implements IrisModule {
|
||||
private static final String VERSION = "built-in";
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:structure-model", "Structure model", VERSION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
var registry = setup.registry();
|
||||
registry.registerValidator(new StructureValidator());
|
||||
registry.registerService(StructureLocator.class, new StructureLocating());
|
||||
registry.registerService(VanillaStructures.class, new StructureVanillaStructures());
|
||||
setup.tooling().registerCommand(StructureCommands.root());
|
||||
}
|
||||
}
|
||||
@@ -18,14 +18,13 @@
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.builtin.structure.StructureVerifier;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
|
||||
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
|
||||
import art.arcane.iris.engine.framework.StructureReachability;
|
||||
import com.volmit.config.Reference;
|
||||
import com.volmit.tooling.Argument;
|
||||
import com.volmit.tooling.CommandContext;
|
||||
import com.volmit.tooling.Sender;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -36,17 +35,12 @@ import java.util.TreeSet;
|
||||
/**
|
||||
* {@code /iris module structure verify}: for every structure the platform registers and every structure the pack's modules place,
|
||||
* whether it can generate in the world the sender stands in, searching around the world origin for those the pack places.
|
||||
* Native eligibility is decided without the platform's blocking locate.
|
||||
* Native eligibility is decided without the platform's blocking locate. The command is {@code iris:structure}'s; the world
|
||||
* offers this to it as its {@link StructureVerifier}.
|
||||
*/
|
||||
final class StructureVerification {
|
||||
private static final long DEFAULT_RADIUS_CHUNKS = 48L;
|
||||
private static final long MAX_RADIUS_CHUNKS = 1000L;
|
||||
private static final int ORIGIN_BLOCK = 0;
|
||||
|
||||
static final Argument<Long> RADIUS = Argument.integer("radius", 1, MAX_RADIUS_CHUNKS)
|
||||
.orElse(DEFAULT_RADIUS_CHUNKS)
|
||||
.describe("Search radius in chunks around the world origin (larger is much slower)");
|
||||
|
||||
private final Engine engine;
|
||||
private final CommandContext context;
|
||||
private final int radiusChunks;
|
||||
@@ -64,15 +58,8 @@ final class StructureVerification {
|
||||
this.radiusChunks = radiusChunks;
|
||||
}
|
||||
|
||||
static void run(CommandContext context) {
|
||||
Sender sender = context.sender();
|
||||
Engine engine = context.world().flatMap(world -> world.extension(Engine.class)).orElse(null);
|
||||
if (engine == null) {
|
||||
sender.error("Stand in a world generated with this pack: verify reads the running world");
|
||||
return;
|
||||
}
|
||||
int radiusChunks = Math.toIntExact(context.get(RADIUS));
|
||||
sender.info("Verifying structures within " + radiusChunks + " chunks of the world origin...");
|
||||
static void run(Engine engine, CommandContext context, int radiusChunks) {
|
||||
context.sender().info("Verifying structures within " + radiusChunks + " chunks of the world origin...");
|
||||
new StructureVerification(engine, context, radiusChunks).report();
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import com.volmit.resource.PackResources;
|
||||
import com.volmit.world.PackWorld;
|
||||
import com.volmit.world.RunningWorld;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
@@ -42,12 +43,15 @@ final class ToolWorld implements PackWorld, AutoCloseable {
|
||||
private final WorldStates states;
|
||||
private final ModuleLog log;
|
||||
private final Placements placements;
|
||||
private final PackServices services;
|
||||
|
||||
/** {@code placements} makes the placements of the new world. */
|
||||
ToolWorld(long seed, PackResources resources, PackSettings settings, Function<PackWorld, Placements> placements) {
|
||||
/** {@code placements} makes the placements of the new world; {@code services} are those of the pack's modules. */
|
||||
ToolWorld(long seed, PackResources resources, PackSettings settings, PackServices services,
|
||||
Function<PackWorld, Placements> placements) {
|
||||
this.seeds = new SeedManager(seed);
|
||||
this.resources = resources;
|
||||
this.settings = settings;
|
||||
this.services = services;
|
||||
this.states = new WorldStates();
|
||||
this.log = IrisApiLogger.hostLog();
|
||||
this.placements = placements.apply(this);
|
||||
@@ -91,6 +95,11 @@ final class ToolWorld implements PackWorld, AutoCloseable {
|
||||
return states.state(type, () -> create.apply(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S> List<S> services(Class<S> service) {
|
||||
return services.providers(service);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModuleLog log() {
|
||||
return log;
|
||||
|
||||
@@ -23,13 +23,13 @@ import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.core.modules.IrisPackResources;
|
||||
import art.arcane.iris.engine.object.annotations.RegistryListResource;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.volmlib.util.io.IO;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import com.google.gson.Gson;
|
||||
import com.volmit.config.ResourceRef;
|
||||
import com.volmit.host.ResourceKindRegistration;
|
||||
import com.volmit.object.GeneratedObject;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
|
||||
import java.io.File;
|
||||
@@ -62,15 +62,21 @@ public final class ModuleResourceClosure {
|
||||
|
||||
private final IrisData data;
|
||||
private final Map<Class<?>, ResourceKind<?>> kindsByType = new HashMap<>();
|
||||
private final Class<?> structureType;
|
||||
private final Map<ResourceKind<?>, Map<String, Object>> found = new LinkedHashMap<>();
|
||||
private final Set<Object> visited = java.util.Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
private final Set<String> objectKeys = new TreeSet<>();
|
||||
|
||||
public ModuleResourceClosure(IrisData data) {
|
||||
this.data = data;
|
||||
Class<?> structures = null;
|
||||
for (ResourceKindRegistration registration : data.getModules().pack().catalog().resourceKinds()) {
|
||||
kindsByType.put(registration.kind().type(), registration.kind());
|
||||
if (registration.kind().id().equals(IrisStructureRef.KIND)) {
|
||||
structures = registration.kind().type();
|
||||
}
|
||||
}
|
||||
this.structureType = structures;
|
||||
}
|
||||
|
||||
/** Adds the resources that the module settings of {@code owner} reference, and those they reference. */
|
||||
@@ -118,6 +124,15 @@ public final class ModuleResourceClosure {
|
||||
return kind == null || !found.containsKey(kind) ? List.of() : new ArrayList<>(new TreeMap<>(found.get(kind)).keySet());
|
||||
}
|
||||
|
||||
/** The keys of the resources found of the kind {@code kindId}, in key order, for a kind whose class Iris cannot name. */
|
||||
public List<String> keysOf(ResourceId kindId) {
|
||||
return kindsByType.values().stream()
|
||||
.filter(kind -> kind.id().equals(kindId))
|
||||
.findFirst()
|
||||
.map(kind -> found.containsKey(kind) ? new ArrayList<>(new TreeMap<>(found.get(kind)).keySet()) : new ArrayList<String>())
|
||||
.orElseGet(ArrayList::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys of the pack objects that what was found references, in key order. Objects are Iris's own files, not a
|
||||
* module kind, so the export copies them itself.
|
||||
@@ -165,13 +180,13 @@ public final class ModuleResourceClosure {
|
||||
}
|
||||
|
||||
/** The class of the resources the field names by key, or null when it names none. */
|
||||
private static Class<?> referencedType(Field field) {
|
||||
private Class<?> referencedType(Field field) {
|
||||
ResourceRef reference = field.getAnnotation(ResourceRef.class);
|
||||
if (reference != null) {
|
||||
return reference.value();
|
||||
}
|
||||
if (field.isAnnotationPresent(IrisStructureRef.class)) {
|
||||
return IrisStructure.class;
|
||||
return structureType;
|
||||
}
|
||||
RegistryListResource registry = field.getAnnotation(RegistryListResource.class);
|
||||
return registry == null ? null : registry.value();
|
||||
|
||||
@@ -1,605 +0,0 @@
|
||||
package art.arcane.iris.core.pack;
|
||||
|
||||
import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
|
||||
import art.arcane.volmlib.util.io.IO;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public final class StructurePackageClosure {
|
||||
private static final String STRUCTURES = "structures";
|
||||
private static final String POOLS = "jigsaw-pools";
|
||||
private static final String PIECES = "jigsaw-pieces";
|
||||
private static final String OBJECTS = "objects";
|
||||
private static final String LOOT = "loot";
|
||||
|
||||
private final Path sourceRoot;
|
||||
private final Set<String> structures;
|
||||
private final Set<String> pools;
|
||||
private final Set<String> pieces;
|
||||
private final Set<String> objects;
|
||||
private final Set<String> loot;
|
||||
private final List<String> errors;
|
||||
|
||||
private StructurePackageClosure(Path sourceRoot, MutableClosure closure) {
|
||||
this.sourceRoot = sourceRoot;
|
||||
this.structures = Collections.unmodifiableSet(new LinkedHashSet<>(closure.structures));
|
||||
this.pools = Collections.unmodifiableSet(new LinkedHashSet<>(closure.pools));
|
||||
this.pieces = Collections.unmodifiableSet(new LinkedHashSet<>(closure.pieces));
|
||||
this.objects = Collections.unmodifiableSet(new LinkedHashSet<>(closure.objects));
|
||||
this.loot = Collections.unmodifiableSet(new LinkedHashSet<>(closure.loot));
|
||||
this.errors = Collections.unmodifiableList(new ArrayList<>(closure.errors));
|
||||
}
|
||||
|
||||
public static StructurePackageClosure collect(File sourceRoot, Collection<String> rootStructures) {
|
||||
return collect(sourceRoot, rootStructures, null);
|
||||
}
|
||||
|
||||
public static StructurePackageClosure collect(
|
||||
File sourceRoot,
|
||||
Collection<String> rootStructures,
|
||||
Limits limits
|
||||
) {
|
||||
Path normalizedRoot = sourceRoot.toPath().toAbsolutePath().normalize();
|
||||
MutableClosure closure = new MutableClosure(limits);
|
||||
if (!Files.isDirectory(normalizedRoot)) {
|
||||
closure.errors.add("Structure package source is not a directory: " + normalizedRoot);
|
||||
return new StructurePackageClosure(normalizedRoot, closure);
|
||||
}
|
||||
|
||||
if (rootStructures != null) {
|
||||
for (String structureKey : rootStructures) {
|
||||
enqueueKey(closure.structureQueue, structureKey, "structure", closure.errors);
|
||||
}
|
||||
}
|
||||
|
||||
collectStructures(normalizedRoot, closure);
|
||||
collectPools(normalizedRoot, closure);
|
||||
collectPieces(normalizedRoot, closure);
|
||||
validateBinaryResources(normalizedRoot, closure);
|
||||
validatePortableCollisions(closure.structures, STRUCTURES, closure.errors);
|
||||
validatePortableCollisions(closure.pools, POOLS, closure.errors);
|
||||
validatePortableCollisions(closure.pieces, PIECES, closure.errors);
|
||||
validatePortableCollisions(closure.objects, OBJECTS, closure.errors);
|
||||
validatePortableCollisions(closure.loot, LOOT, closure.errors);
|
||||
return new StructurePackageClosure(normalizedRoot, closure);
|
||||
}
|
||||
|
||||
public boolean isValid() {
|
||||
return errors.isEmpty();
|
||||
}
|
||||
|
||||
public Set<String> structures() {
|
||||
return structures;
|
||||
}
|
||||
|
||||
public Set<String> pools() {
|
||||
return pools;
|
||||
}
|
||||
|
||||
public Set<String> pieces() {
|
||||
return pieces;
|
||||
}
|
||||
|
||||
public Set<String> objects() {
|
||||
return objects;
|
||||
}
|
||||
|
||||
public Set<String> loot() {
|
||||
return loot;
|
||||
}
|
||||
|
||||
public List<String> errors() {
|
||||
return errors;
|
||||
}
|
||||
|
||||
public String writeTo(File targetRoot, boolean minify) throws IOException {
|
||||
if (!isValid()) {
|
||||
throw new IOException("Cannot package an invalid structure graph: " + String.join("; ", errors));
|
||||
}
|
||||
|
||||
Path normalizedTarget = targetRoot.toPath().toAbsolutePath().normalize();
|
||||
prepareTargetRoot(normalizedTarget);
|
||||
StringBuilder hashes = new StringBuilder();
|
||||
copyJsonResources(normalizedTarget, STRUCTURES, structures, minify, hashes);
|
||||
copyJsonResources(normalizedTarget, POOLS, pools, minify, hashes);
|
||||
copyJsonResources(normalizedTarget, PIECES, pieces, minify, hashes);
|
||||
copyJsonResources(normalizedTarget, LOOT, loot, minify, hashes);
|
||||
copyBinaryResources(normalizedTarget, OBJECTS, objects, hashes);
|
||||
return IO.hash(hashes.toString());
|
||||
}
|
||||
|
||||
private static void collectStructures(Path sourceRoot, MutableClosure closure) {
|
||||
while (!closure.structureQueue.isEmpty()) {
|
||||
String structureKey = closure.structureQueue.removeFirst();
|
||||
if (!closure.structures.add(structureKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
JSONObject structure = readJson(sourceRoot, STRUCTURES, structureKey, closure.errors, closure.limits);
|
||||
if (structure == null) {
|
||||
continue;
|
||||
}
|
||||
String startPool = requiredString(structure, "startPool", "Structure '" + structureKey + "'", closure.errors);
|
||||
if (startPool != null) {
|
||||
enqueueKey(closure.poolQueue, startPool,
|
||||
"start pool for structure '" + structureKey + "'", closure.errors);
|
||||
}
|
||||
JSONArray loot = optionalArray(structure, "loot", "Structure '" + structureKey + "'", closure.errors);
|
||||
addArrayKeys(loot, closure.loot, "loot table", closure.errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void collectPools(Path sourceRoot, MutableClosure closure) {
|
||||
while (!closure.poolQueue.isEmpty()) {
|
||||
String poolKey = closure.poolQueue.removeFirst();
|
||||
if (!closure.pools.add(poolKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
JSONObject pool = readJson(sourceRoot, POOLS, poolKey, closure.errors, closure.limits);
|
||||
if (pool == null) {
|
||||
continue;
|
||||
}
|
||||
JSONArray entries = requiredArray(pool, "pieces", "Jigsaw pool '" + poolKey + "'", closure.errors);
|
||||
if (entries != null) {
|
||||
for (int index = 0; index < entries.length(); index++) {
|
||||
JSONObject entry = entries.optJSONObject(index);
|
||||
if (entry == null) {
|
||||
closure.errors.add("Jigsaw pool '" + poolKey + "' has a non-object piece entry at index " + index + ".");
|
||||
continue;
|
||||
}
|
||||
if (isEmptyEntry(entry, poolKey, index, closure.errors)) {
|
||||
continue;
|
||||
}
|
||||
String pieceKey = requiredString(entry, "piece",
|
||||
"Piece entry " + index + " in jigsaw pool '" + poolKey + "'", closure.errors);
|
||||
if (pieceKey != null) {
|
||||
enqueueKey(closure.pieceQueue, pieceKey,
|
||||
"piece in pool '" + poolKey + "'", closure.errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
String fallback = optionalString(pool, "fallback", "Jigsaw pool '" + poolKey + "'", closure.errors);
|
||||
enqueueOptionalKey(closure.poolQueue, fallback,
|
||||
"fallback pool for '" + poolKey + "'", closure.errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void collectPieces(Path sourceRoot, MutableClosure closure) {
|
||||
while (!closure.pieceQueue.isEmpty()) {
|
||||
String pieceKey = closure.pieceQueue.removeFirst();
|
||||
if (!closure.pieces.add(pieceKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
JSONObject piece = readJson(sourceRoot, PIECES, pieceKey, closure.errors, closure.limits);
|
||||
if (piece == null) {
|
||||
continue;
|
||||
}
|
||||
String objectKey = requiredString(piece, "object", "Jigsaw piece '" + pieceKey + "'", closure.errors);
|
||||
if (objectKey != null) {
|
||||
addRequiredKey(closure.objects, objectKey,
|
||||
"object for piece '" + pieceKey + "'", closure.errors);
|
||||
}
|
||||
JSONArray connectors = optionalArray(piece, "connectors", "Jigsaw piece '" + pieceKey + "'", closure.errors);
|
||||
if (connectors == null) {
|
||||
continue;
|
||||
}
|
||||
for (int index = 0; index < connectors.length(); index++) {
|
||||
JSONObject connector = connectors.optJSONObject(index);
|
||||
if (connector == null) {
|
||||
closure.errors.add("Jigsaw piece '" + pieceKey + "' has a non-object connector at index " + index + ".");
|
||||
continue;
|
||||
}
|
||||
String poolKey = requiredString(connector, "pool",
|
||||
"Connector " + index + " in jigsaw piece '" + pieceKey + "'", closure.errors);
|
||||
if (poolKey != null) {
|
||||
enqueueKey(closure.poolQueue, poolKey,
|
||||
"connector pool for piece '" + pieceKey + "'", closure.errors);
|
||||
}
|
||||
}
|
||||
collectPools(sourceRoot, closure);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateBinaryResources(Path sourceRoot, MutableClosure closure) {
|
||||
for (String objectKey : closure.objects) {
|
||||
resolveExisting(sourceRoot, OBJECTS, objectKey, ".iob", closure.errors);
|
||||
}
|
||||
for (String lootKey : closure.loot) {
|
||||
resolveExisting(sourceRoot, LOOT, lootKey, ".json", closure.errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static JSONObject readJson(
|
||||
Path sourceRoot,
|
||||
String folder,
|
||||
String key,
|
||||
List<String> errors,
|
||||
Limits limits
|
||||
) {
|
||||
Path file = resolveExisting(sourceRoot, folder, key, ".json", errors);
|
||||
if (file == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String content = limits == null
|
||||
? Files.readString(file, StandardCharsets.UTF_8)
|
||||
: new String(readBounded(file, limits.maxJsonBytes()), StandardCharsets.UTF_8);
|
||||
return new JSONObject(content);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
errors.add("Invalid " + folder + " resource '" + key + "': " + describe(e));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] readBounded(Path file, int maximumBytes) throws IOException {
|
||||
try (InputStream input = Files.newInputStream(file)) {
|
||||
byte[] content = input.readNBytes(maximumBytes + 1);
|
||||
if (content.length > maximumBytes) {
|
||||
throw new IOException("JSON resource exceeds " + maximumBytes + " bytes");
|
||||
}
|
||||
return content;
|
||||
}
|
||||
}
|
||||
|
||||
private static Path resolveExisting(Path sourceRoot, String folder, String key, String extension,
|
||||
List<String> errors) {
|
||||
Path file = resolveResource(sourceRoot, folder, key, extension, errors);
|
||||
if (file != null && !Files.isRegularFile(file)) {
|
||||
errors.add("Missing " + folder + " resource '" + key + "'.");
|
||||
return null;
|
||||
}
|
||||
if (file != null && !isContainedSourceResource(sourceRoot, folder, key, extension, file, errors)) {
|
||||
return null;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private static Path resolveResource(Path root, String folder, String key, String extension, List<String> errors) {
|
||||
if (!validKey(key)) {
|
||||
errors.add("Invalid " + folder + " resource key '" + key + "'.");
|
||||
return null;
|
||||
}
|
||||
Path folderRoot = root.resolve(folder).normalize();
|
||||
Path file = folderRoot.resolve(key + extension).normalize();
|
||||
if (!file.startsWith(folderRoot)) {
|
||||
errors.add("Resource key escapes " + folder + ": '" + key + "'.");
|
||||
return null;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private void copyJsonResources(Path targetRoot, String folder, Set<String> keys, boolean minify,
|
||||
StringBuilder hashes) throws IOException {
|
||||
for (String key : keys) {
|
||||
Path source = resolveExistingOrThrow(sourceRoot, folder, key, ".json");
|
||||
Path target = prepareTargetResource(targetRoot, folder, key, ".json");
|
||||
String json = new JSONObject(Files.readString(source, StandardCharsets.UTF_8)).toString(minify ? 0 : 4);
|
||||
Files.writeString(target, json, StandardCharsets.UTF_8);
|
||||
hashes.append(IO.hash(json));
|
||||
}
|
||||
}
|
||||
|
||||
private void copyBinaryResources(Path targetRoot, String folder, Set<String> keys,
|
||||
StringBuilder hashes) throws IOException {
|
||||
for (String key : keys) {
|
||||
Path source = resolveExistingOrThrow(sourceRoot, folder, key, ".iob");
|
||||
Path target = prepareTargetResource(targetRoot, folder, key, ".iob");
|
||||
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
hashes.append(IO.hash(source.toFile()));
|
||||
}
|
||||
}
|
||||
|
||||
private static Path resolveExistingOrThrow(Path root, String folder, String key, String extension) throws IOException {
|
||||
List<String> errors = new ArrayList<>();
|
||||
Path file = resolveExisting(root, folder, key, extension, errors);
|
||||
if (file == null) {
|
||||
throw new IOException(String.join("; ", errors));
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private static Path resolveResourceOrThrow(Path root, String folder, String key, String extension) throws IOException {
|
||||
List<String> errors = new ArrayList<>();
|
||||
Path file = resolveResource(root, folder, key, extension, errors);
|
||||
if (file == null) {
|
||||
throw new IOException(String.join("; ", errors));
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private static void prepareTargetRoot(Path targetRoot) throws IOException {
|
||||
if (Files.exists(targetRoot, LinkOption.NOFOLLOW_LINKS)) {
|
||||
if (!Files.isDirectory(targetRoot)) {
|
||||
throw new IOException("Structure package target is not a directory: " + targetRoot);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Files.createDirectories(targetRoot);
|
||||
}
|
||||
|
||||
private static Path prepareTargetResource(Path targetRoot, String folder, String key, String extension) throws IOException {
|
||||
Path target = resolveResourceOrThrow(targetRoot, folder, key, extension);
|
||||
Path parent = target.getParent();
|
||||
Path current = targetRoot;
|
||||
Path relativeParent = targetRoot.relativize(parent);
|
||||
for (Path segment : relativeParent) {
|
||||
Path next = current.resolve(segment);
|
||||
if (Files.exists(next, LinkOption.NOFOLLOW_LINKS)) {
|
||||
if (Files.isSymbolicLink(next) || !Files.isDirectory(next, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Structure package target contains a non-directory or symbolic link: " + next);
|
||||
}
|
||||
} else {
|
||||
Files.createDirectory(next);
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
if (Files.isSymbolicLink(target)) {
|
||||
throw new IOException("Structure package target is a symbolic link: " + target);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
private static boolean isContainedSourceResource(Path sourceRoot, String folder, String key, String extension,
|
||||
Path file, List<String> errors) {
|
||||
try {
|
||||
Path realSourceRoot = sourceRoot.toRealPath();
|
||||
Path realFile = file.toRealPath();
|
||||
if (!realFile.startsWith(realSourceRoot)) {
|
||||
errors.add("Resource escapes the structure package through a symbolic link: "
|
||||
+ folder + "/" + key + extension + ".");
|
||||
return false;
|
||||
}
|
||||
if (!hasExactSourceCase(sourceRoot, file)) {
|
||||
errors.add("Resource path casing does not match its reference: "
|
||||
+ folder + "/" + key + extension + ".");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (IOException exception) {
|
||||
errors.add("Cannot verify " + folder + " resource '" + key + "': " + describe(exception));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasExactSourceCase(Path sourceRoot, Path file) throws IOException {
|
||||
Path current = sourceRoot;
|
||||
for (Path segment : sourceRoot.relativize(file)) {
|
||||
Path exactChild = findExactChild(current, segment.toString());
|
||||
if (exactChild == null) {
|
||||
return false;
|
||||
}
|
||||
current = exactChild;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Path findExactChild(Path folder, String name) throws IOException {
|
||||
try (DirectoryStream<Path> children = Files.newDirectoryStream(folder)) {
|
||||
for (Path child : children) {
|
||||
if (child.getFileName().toString().equals(name)) {
|
||||
return child;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void addArrayKeys(JSONArray values, Set<String> target, String kind, List<String> errors) {
|
||||
if (values == null) {
|
||||
return;
|
||||
}
|
||||
for (int index = 0; index < values.length(); index++) {
|
||||
Object raw = values.opt(index);
|
||||
if (!(raw instanceof String value)) {
|
||||
errors.add("Invalid " + kind + " reference at index " + index + ".");
|
||||
continue;
|
||||
}
|
||||
addRequiredKey(target, value, kind, errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void addRequiredKey(Set<String> target, String key, String kind, List<String> errors) {
|
||||
String canonical = canonicalKey(key);
|
||||
if (canonical == null) {
|
||||
errors.add("Missing or invalid " + kind + ".");
|
||||
return;
|
||||
}
|
||||
target.add(canonical);
|
||||
}
|
||||
|
||||
private static void enqueueKey(Deque<String> queue, String key, String kind, List<String> errors) {
|
||||
String canonical = canonicalKey(key);
|
||||
if (canonical == null) {
|
||||
errors.add("Missing or invalid " + kind + ".");
|
||||
return;
|
||||
}
|
||||
queue.addLast(canonical);
|
||||
}
|
||||
|
||||
private static void enqueueOptionalKey(Deque<String> queue, String key, String kind, List<String> errors) {
|
||||
if (key == null || key.isBlank()) {
|
||||
return;
|
||||
}
|
||||
enqueueKey(queue, key, kind, errors);
|
||||
}
|
||||
|
||||
private static String canonicalKey(String key) {
|
||||
if (key == null || !key.equals(key.trim())) {
|
||||
return null;
|
||||
}
|
||||
return validKey(key) ? key : null;
|
||||
}
|
||||
|
||||
private static boolean validKey(String key) {
|
||||
if (key == null || key.isBlank() || !key.equals(key.trim())) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
StructureResourceBundle.validateRelativePath(key);
|
||||
return true;
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String requiredString(JSONObject object, String field, String resource, List<String> errors) {
|
||||
Object value = object.opt(field);
|
||||
if (value instanceof String stringValue) {
|
||||
return stringValue;
|
||||
}
|
||||
errors.add(resource + " requires string field '" + field + "'.");
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String optionalString(JSONObject object, String field, String resource, List<String> errors) {
|
||||
if (!object.has(field)) {
|
||||
return null;
|
||||
}
|
||||
return requiredString(object, field, resource, errors);
|
||||
}
|
||||
|
||||
private static JSONArray requiredArray(JSONObject object, String field, String resource, List<String> errors) {
|
||||
Object value = object.opt(field);
|
||||
if (value instanceof JSONArray arrayValue) {
|
||||
return arrayValue;
|
||||
}
|
||||
errors.add(resource + " requires array field '" + field + "'.");
|
||||
return null;
|
||||
}
|
||||
|
||||
private static JSONArray optionalArray(JSONObject object, String field, String resource, List<String> errors) {
|
||||
if (!object.has(field)) {
|
||||
return null;
|
||||
}
|
||||
return requiredArray(object, field, resource, errors);
|
||||
}
|
||||
|
||||
private static boolean isEmptyEntry(JSONObject entry, String poolKey, int index, List<String> errors) {
|
||||
if (!entry.has("empty")) {
|
||||
return false;
|
||||
}
|
||||
Object emptyValue = entry.opt("empty");
|
||||
if (!(emptyValue instanceof Boolean isEmpty)) {
|
||||
errors.add("Piece entry " + index + " in jigsaw pool '" + poolKey + "' requires boolean field 'empty'.");
|
||||
return false;
|
||||
}
|
||||
if (!isEmpty) {
|
||||
return false;
|
||||
}
|
||||
if (!entry.has("piece")) {
|
||||
return true;
|
||||
}
|
||||
Object pieceValue = entry.opt("piece");
|
||||
if (!(pieceValue instanceof String piece)) {
|
||||
errors.add("Empty piece entry " + index + " in jigsaw pool '" + poolKey
|
||||
+ "' requires string field 'piece' when defined.");
|
||||
} else if (!piece.isBlank()) {
|
||||
errors.add("Empty piece entry " + index + " in jigsaw pool '" + poolKey
|
||||
+ "' cannot define non-empty field 'piece'.");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void validatePortableCollisions(Set<String> keys, String folder, List<String> errors) {
|
||||
Map<String, String> portableKeys = new HashMap<>();
|
||||
for (String key : keys) {
|
||||
String portableKey = key.toLowerCase(Locale.ROOT);
|
||||
String previous = portableKeys.putIfAbsent(portableKey, key);
|
||||
if (previous != null && !previous.equals(key)) {
|
||||
errors.add("Case-insensitive " + folder + " resource collision between '"
|
||||
+ previous + "' and '" + key + "'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String describe(Exception exception) {
|
||||
String message = exception.getMessage();
|
||||
return message == null || message.isBlank() ? exception.getClass().getSimpleName() : message;
|
||||
}
|
||||
|
||||
public record Limits(int maxResources, int maxJsonBytes) {
|
||||
public Limits {
|
||||
if (maxResources < 1 || maxResources > 100_000) {
|
||||
throw new IllegalArgumentException("Structure closure resource limit must be between 1 and 100000");
|
||||
}
|
||||
if (maxJsonBytes < 1 || maxJsonBytes > 64 * 1024 * 1024) {
|
||||
throw new IllegalArgumentException("Structure closure JSON limit must be between 1 and 67108864 bytes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class MutableClosure {
|
||||
private final Limits limits;
|
||||
private final Set<String> structures;
|
||||
private final Set<String> pools;
|
||||
private final Set<String> pieces;
|
||||
private final Set<String> objects;
|
||||
private final Set<String> loot;
|
||||
private final List<String> errors = new ArrayList<>();
|
||||
private final Deque<String> structureQueue = new ArrayDeque<>();
|
||||
private final Deque<String> poolQueue = new ArrayDeque<>();
|
||||
private final Deque<String> pieceQueue = new ArrayDeque<>();
|
||||
private int resources;
|
||||
private boolean resourceLimitReported;
|
||||
|
||||
private MutableClosure(Limits limits) {
|
||||
this.limits = limits;
|
||||
structures = new BudgetedSet(this);
|
||||
pools = new BudgetedSet(this);
|
||||
pieces = new BudgetedSet(this);
|
||||
objects = new BudgetedSet(this);
|
||||
loot = new BudgetedSet(this);
|
||||
}
|
||||
|
||||
private boolean reserveResource() {
|
||||
if (limits == null || resources < limits.maxResources()) {
|
||||
resources++;
|
||||
return true;
|
||||
}
|
||||
if (!resourceLimitReported) {
|
||||
errors.add("Structure closure exceeds " + limits.maxResources() + " resources.");
|
||||
resourceLimitReported = true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class BudgetedSet extends LinkedHashSet<String> {
|
||||
private final MutableClosure closure;
|
||||
|
||||
private BudgetedSet(MutableClosure closure) {
|
||||
this.closure = closure;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(String value) {
|
||||
if (contains(value) || !closure.reserveResource()) {
|
||||
return false;
|
||||
}
|
||||
return super.add(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,6 @@ import art.arcane.iris.engine.object.image.IrisImageMap;
|
||||
import art.arcane.iris.engine.object.noise.NoiseStyle;
|
||||
import art.arcane.iris.engine.object.noise.expression.IrisExpression;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.engine.framework.ListFunction;
|
||||
@@ -491,7 +490,7 @@ public class SchemaBuilder {
|
||||
if (field.isEmpty() || !field.get().isAnnotationPresent(IrisStructureRef.class)) {
|
||||
return;
|
||||
}
|
||||
putPackResourceRef(property, IrisStructure.class);
|
||||
completeResourceReference(property, IrisStructureRef.KIND);
|
||||
}
|
||||
|
||||
private static Optional<Field> declaredField(String typeName, String fieldName) {
|
||||
|
||||
@@ -97,6 +97,16 @@ public final class StudioOpenCoordinator {
|
||||
return closeWorldCoordinated(provider, worldName, world, true, project);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unloads a tool world and deletes its files, reserving the world mutation lock like a studio close. Players must be
|
||||
* gone from it already; any that remain are sent to the spawn of another world.
|
||||
*/
|
||||
public CompletableFuture<StudioCloseResult> closeToolWorld(World world, IrisProject project) {
|
||||
Objects.requireNonNull(world, "world");
|
||||
PlatformChunkGenerator provider = IrisToolbelt.access(world);
|
||||
return closeWorldCoordinated(provider, IrisWorldStorage.logicalName(world), world, true, project);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> teleportPlayerToProject(
|
||||
IrisProject project,
|
||||
Player player
|
||||
@@ -782,7 +792,7 @@ public final class StudioOpenCoordinator {
|
||||
}
|
||||
String transientName = TransientWorldCleanupSupport.transientStudioBaseWorldName(
|
||||
child.getFileName().toString());
|
||||
if (transientName != null) {
|
||||
if (transientName != null && !StudioPainterSlots.isInstalled(transientName)) {
|
||||
worldNames.add(transientName);
|
||||
}
|
||||
}
|
||||
@@ -932,7 +942,7 @@ public final class StudioOpenCoordinator {
|
||||
false,
|
||||
true,
|
||||
IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY),
|
||||
JIGSAW(
|
||||
TOOL(
|
||||
false,
|
||||
false,
|
||||
IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY);
|
||||
@@ -962,7 +972,7 @@ public final class StudioOpenCoordinator {
|
||||
}
|
||||
|
||||
public boolean prepareGeneratorState() {
|
||||
return this != JIGSAW;
|
||||
return this != TOOL;
|
||||
}
|
||||
|
||||
public IrisCreator.DatapackPreparation datapackPreparation() {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.runtime;
|
||||
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import com.volmit.tooling.world.ChunkPainter;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Which studio worlds are painted by a tool instead of generated from their pack, keyed by the logical name of the
|
||||
* world. A tool world installs its slot before the world is created, so the first chunk the world generates is already
|
||||
* the tool's, and removes it when the world closes. The world's generator reads the slot on every chunk, so a slot that
|
||||
* is installed or removed takes effect at the next chunk.
|
||||
*/
|
||||
public final class StudioPainterSlots {
|
||||
private static final Map<String, Slot> SLOTS = new ConcurrentHashMap<>();
|
||||
|
||||
private StudioPainterSlots() {
|
||||
}
|
||||
|
||||
/**
|
||||
* A tool's claim on one world: the painter, and where the block entities it painted go. They go to
|
||||
* {@code blockEntities} because they can only be applied once the chunk is live, which is later than the paint.
|
||||
*/
|
||||
public record Slot(ChunkPainter painter, Consumer<PaintedChunk> blockEntities) {
|
||||
public Slot {
|
||||
Objects.requireNonNull(painter, "painter");
|
||||
Objects.requireNonNull(blockEntities, "blockEntities");
|
||||
}
|
||||
}
|
||||
|
||||
/** The block entities one paint of chunk {@code chunkX}, {@code chunkZ} asked for; never empty. */
|
||||
public record PaintedChunk(int chunkX, int chunkZ, List<PaintedBlockEntity> blockEntities) {
|
||||
public PaintedChunk {
|
||||
blockEntities = List.copyOf(blockEntities);
|
||||
}
|
||||
}
|
||||
|
||||
/** A block entity at chunk-local {@code x} and {@code z} and world {@code y}. */
|
||||
public record PaintedBlockEntity(int x, int y, int z, BlockEntityData data) {
|
||||
public PaintedBlockEntity {
|
||||
Objects.requireNonNull(data, "data");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the world called {@code worldName} a painted one.
|
||||
*
|
||||
* @throws IllegalStateException when a tool painted that world already
|
||||
*/
|
||||
public static void install(String worldName, Slot slot) {
|
||||
Objects.requireNonNull(worldName, "worldName");
|
||||
Objects.requireNonNull(slot, "slot");
|
||||
if (SLOTS.putIfAbsent(worldName, slot) != null) {
|
||||
throw new IllegalStateException("The world " + worldName + " is painted by a tool already");
|
||||
}
|
||||
}
|
||||
|
||||
/** The slot of the world called {@code worldName}; empty for a world generated from its pack. */
|
||||
public static Optional<Slot> slotOf(String worldName) {
|
||||
return worldName == null ? Optional.empty() : Optional.ofNullable(SLOTS.get(worldName));
|
||||
}
|
||||
|
||||
public static boolean isInstalled(String worldName) {
|
||||
return slotOf(worldName).isPresent();
|
||||
}
|
||||
|
||||
/** Gives the world back to its pack. Does nothing for a world nobody painted. */
|
||||
public static void remove(String worldName) {
|
||||
if (worldName != null) {
|
||||
SLOTS.remove(worldName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.runtime;
|
||||
|
||||
import art.arcane.iris.core.project.IrisProject;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* A tool world that holds the studio slot, the way an open studio project does: opening another studio, the studio
|
||||
* close command and a server stop go through it. The studio service asks it, and the platform's tool world answers for
|
||||
* the tool that owns the world.
|
||||
*/
|
||||
public interface StudioSlotOccupant {
|
||||
/**
|
||||
* The studio project the world is, which the studio service shows to every command that asks for the open studio: it
|
||||
* is open while the world is and carries the world's generator, as the project of any other studio does.
|
||||
*/
|
||||
IrisProject project();
|
||||
|
||||
/** A message that vetoes closing the world now; empty lets it close. */
|
||||
Optional<String> closeRefusal();
|
||||
|
||||
/**
|
||||
* Gets the world ready to be replaced by another studio, such as finishing a save. Completes when the world may be
|
||||
* closed, or fails with the message to show the user.
|
||||
*
|
||||
* @param requestedBy the player who asked for the replacement; empty when the console did
|
||||
*/
|
||||
CompletableFuture<Void> prepareReplacement(Optional<UUID> requestedBy);
|
||||
|
||||
/** Closes the world and sends its players back; completes when it is unloaded and deleted. */
|
||||
CompletableFuture<Void> close();
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public enum JigsawPlanarArchetype {
|
||||
BLANK("workcell/blank", JigsawPlanarTopology.BLANK),
|
||||
END("workcell/end", JigsawPlanarTopology.NORTH_END),
|
||||
STRAIGHT("workcell/straight", JigsawPlanarTopology.NORTH_SOUTH_STRAIGHT),
|
||||
CORNER("workcell/corner", JigsawPlanarTopology.NORTH_EAST_CORNER),
|
||||
TEE("workcell/tee", JigsawPlanarTopology.NORTH_EAST_WEST_TEE),
|
||||
CROSS("workcell/cross", JigsawPlanarTopology.CROSS);
|
||||
|
||||
private final String stableId;
|
||||
private final JigsawPlanarTopology canonicalTopology;
|
||||
|
||||
JigsawPlanarArchetype(String stableId, JigsawPlanarTopology canonicalTopology) {
|
||||
this.stableId = stableId;
|
||||
this.canonicalTopology = canonicalTopology;
|
||||
}
|
||||
|
||||
public static JigsawPlanarArchetype fromTopology(JigsawPlanarTopology topology) {
|
||||
JigsawPlanarTopology source = Objects.requireNonNull(topology, "Planar topology");
|
||||
return switch (source.kind()) {
|
||||
case BLANK -> BLANK;
|
||||
case END -> END;
|
||||
case STRAIGHT -> STRAIGHT;
|
||||
case CORNER -> CORNER;
|
||||
case TEE -> TEE;
|
||||
case CROSS -> CROSS;
|
||||
};
|
||||
}
|
||||
|
||||
public static JigsawPlanarArchetype fromModel(IrisJigsawWorkcellArchetype archetype) {
|
||||
return valueOf(Objects.requireNonNull(archetype, "Planar workcell archetype").name());
|
||||
}
|
||||
|
||||
public String stableId() {
|
||||
return stableId;
|
||||
}
|
||||
|
||||
public JigsawPlanarTopology canonicalTopology() {
|
||||
return canonicalTopology;
|
||||
}
|
||||
|
||||
public IrisJigsawWorkcellArchetype modelArchetype() {
|
||||
return IrisJigsawWorkcellArchetype.valueOf(name());
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return switch (this) {
|
||||
case BLANK -> "Blank";
|
||||
case END -> "End Cap";
|
||||
case STRAIGHT -> "Hallway";
|
||||
case CORNER -> "L Junction";
|
||||
case TEE -> "T Junction";
|
||||
case CROSS -> "Cross Junction";
|
||||
};
|
||||
}
|
||||
|
||||
public int sourceToCanonicalQuarterTurns(JigsawPlanarTopology sourceTopology) {
|
||||
JigsawPlanarTopology source = Objects.requireNonNull(sourceTopology, "Source planar topology");
|
||||
if (fromTopology(source) != this) {
|
||||
throw new IllegalArgumentException("Topology " + source + " does not belong to archetype " + this);
|
||||
}
|
||||
for (int quarterTurns = 0; quarterTurns < 4; quarterTurns++) {
|
||||
if (source.rotateClockwise(quarterTurns) == canonicalTopology) {
|
||||
return quarterTurns;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("No canonical rotation exists for topology " + source);
|
||||
}
|
||||
|
||||
public int canonicalToSourceQuarterTurns(JigsawPlanarTopology sourceTopology) {
|
||||
return Math.floorMod(-sourceToCanonicalQuarterTurns(sourceTopology), 4);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.engine.object.value.IrisDirection;
|
||||
|
||||
public enum JigsawPlanarDirection {
|
||||
NORTH(1),
|
||||
EAST(2),
|
||||
SOUTH(4),
|
||||
WEST(8);
|
||||
|
||||
private final int bit;
|
||||
|
||||
JigsawPlanarDirection(int bit) {
|
||||
this.bit = bit;
|
||||
}
|
||||
|
||||
public int bit() {
|
||||
return bit;
|
||||
}
|
||||
|
||||
public IrisDirection irisDirection() {
|
||||
return switch (this) {
|
||||
case NORTH -> IrisDirection.NORTH_NEGATIVE_Z;
|
||||
case EAST -> IrisDirection.EAST_POSITIVE_X;
|
||||
case SOUTH -> IrisDirection.SOUTH_POSITIVE_Z;
|
||||
case WEST -> IrisDirection.WEST_NEGATIVE_X;
|
||||
};
|
||||
}
|
||||
|
||||
public JigsawPlanarDirection rotateClockwise(int quarterTurns) {
|
||||
int normalizedTurns = Math.floorMod(quarterTurns, values().length);
|
||||
return values()[(ordinal() + normalizedTurns) % values().length];
|
||||
}
|
||||
|
||||
public JigsawPlanarDirection opposite() {
|
||||
return rotateClockwise(2);
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Set;
|
||||
|
||||
public enum JigsawPlanarTopology {
|
||||
BLANK(0),
|
||||
NORTH_END(1),
|
||||
EAST_END(2),
|
||||
NORTH_EAST_CORNER(3),
|
||||
SOUTH_END(4),
|
||||
NORTH_SOUTH_STRAIGHT(5),
|
||||
EAST_SOUTH_CORNER(6),
|
||||
NORTH_EAST_SOUTH_TEE(7),
|
||||
WEST_END(8),
|
||||
NORTH_WEST_CORNER(9),
|
||||
EAST_WEST_STRAIGHT(10),
|
||||
NORTH_EAST_WEST_TEE(11),
|
||||
SOUTH_WEST_CORNER(12),
|
||||
NORTH_SOUTH_WEST_TEE(13),
|
||||
EAST_SOUTH_WEST_TEE(14),
|
||||
CROSS(15);
|
||||
|
||||
private static final JigsawPlanarTopology[] BY_MASK = buildMaskIndex();
|
||||
|
||||
private final int mask;
|
||||
private final JigsawPlanarTopologyKind kind;
|
||||
private final Set<JigsawPlanarDirection> directions;
|
||||
|
||||
JigsawPlanarTopology(int mask) {
|
||||
this.mask = mask;
|
||||
this.kind = resolveKind(mask);
|
||||
this.directions = Collections.unmodifiableSet(resolveDirections(mask));
|
||||
}
|
||||
|
||||
public static JigsawPlanarTopology fromMask(int mask) {
|
||||
if (mask < 0 || mask >= BY_MASK.length) {
|
||||
throw new IllegalArgumentException("Planar topology mask must be between 0 and 15");
|
||||
}
|
||||
return BY_MASK[mask];
|
||||
}
|
||||
|
||||
public int mask() {
|
||||
return mask;
|
||||
}
|
||||
|
||||
public JigsawPlanarTopologyKind kind() {
|
||||
return kind;
|
||||
}
|
||||
|
||||
public Set<JigsawPlanarDirection> directions() {
|
||||
return directions;
|
||||
}
|
||||
|
||||
public boolean connects(JigsawPlanarDirection direction) {
|
||||
return directions.contains(direction);
|
||||
}
|
||||
|
||||
public JigsawPlanarTopology rotateClockwise(int quarterTurns) {
|
||||
int normalizedTurns = Math.floorMod(quarterTurns, 4);
|
||||
if (normalizedTurns == 0 || mask == 0 || mask == 15) {
|
||||
return this;
|
||||
}
|
||||
int rotatedMask = ((mask << normalizedTurns) | (mask >>> (4 - normalizedTurns))) & 15;
|
||||
return fromMask(rotatedMask);
|
||||
}
|
||||
|
||||
private static JigsawPlanarTopology[] buildMaskIndex() {
|
||||
JigsawPlanarTopology[] index = new JigsawPlanarTopology[16];
|
||||
for (JigsawPlanarTopology topology : values()) {
|
||||
index[topology.mask] = topology;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
private static EnumSet<JigsawPlanarDirection> resolveDirections(int mask) {
|
||||
EnumSet<JigsawPlanarDirection> result = EnumSet.noneOf(JigsawPlanarDirection.class);
|
||||
for (JigsawPlanarDirection direction : JigsawPlanarDirection.values()) {
|
||||
if ((mask & direction.bit()) != 0) {
|
||||
result.add(direction);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static JigsawPlanarTopologyKind resolveKind(int mask) {
|
||||
int connectionCount = Integer.bitCount(mask);
|
||||
return switch (connectionCount) {
|
||||
case 0 -> JigsawPlanarTopologyKind.BLANK;
|
||||
case 1 -> JigsawPlanarTopologyKind.END;
|
||||
case 2 -> mask == 5 || mask == 10
|
||||
? JigsawPlanarTopologyKind.STRAIGHT
|
||||
: JigsawPlanarTopologyKind.CORNER;
|
||||
case 3 -> JigsawPlanarTopologyKind.TEE;
|
||||
case 4 -> JigsawPlanarTopologyKind.CROSS;
|
||||
default -> throw new IllegalArgumentException("Invalid planar topology mask " + mask);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
public enum JigsawPlanarTopologyKind {
|
||||
BLANK,
|
||||
END,
|
||||
STRAIGHT,
|
||||
CORNER,
|
||||
TEE,
|
||||
CROSS
|
||||
}
|
||||
@@ -1,409 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public final class JigsawStudioActivation {
|
||||
private static final Map<String, ActiveRequest> ACTIVE = new ConcurrentHashMap<>();
|
||||
private static final AtomicReference<UUID> OPENING_OWNER = new AtomicReference<>();
|
||||
private static final AtomicReference<StagedState> STAGED = new AtomicReference<>();
|
||||
|
||||
private JigsawStudioActivation() {
|
||||
}
|
||||
|
||||
public static Request activate(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source
|
||||
) {
|
||||
JigsawStudioLayout layout = JigsawStudioLayout.create(
|
||||
mode,
|
||||
cellDimensions,
|
||||
JigsawStudioVariantCatalog.empty());
|
||||
return activate(
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
layout,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
public static Request activate(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
JigsawStudioLayout initialLayout
|
||||
) {
|
||||
return activate(
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
initialLayout,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
public static synchronized Request activate(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
JigsawStudioLayout initialLayout,
|
||||
UUID ownerId
|
||||
) {
|
||||
if (STAGED.get() != null) {
|
||||
throw new IllegalStateException("A Jigsaw Studio replacement is already staged");
|
||||
}
|
||||
if (ownerId != null && !ownerId.equals(OPENING_OWNER.get())) {
|
||||
throw new IllegalStateException("Jigsaw Studio activation does not own the active opening lease");
|
||||
}
|
||||
UUID activeOwnerId = activeOwnerId();
|
||||
if (ownerId != null && activeOwnerId != null && !ownerId.equals(activeOwnerId)) {
|
||||
throw new IllegalStateException("Jigsaw Studio is owned by another player session");
|
||||
}
|
||||
ActiveRequest activeRequest = createActiveRequest(
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
initialLayout,
|
||||
ownerId);
|
||||
ACTIVE.put(normalize(packKey), activeRequest);
|
||||
return activeRequest.request();
|
||||
}
|
||||
|
||||
public static synchronized StagedActivation stage(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
JigsawStudioLayout initialLayout,
|
||||
UUID ownerId,
|
||||
UUID preservedRequestId
|
||||
) {
|
||||
UUID openingOwner = OPENING_OWNER.get();
|
||||
UUID activeOwner = activeOwnerId();
|
||||
UUID requestedOwner = Objects.requireNonNull(ownerId, "Jigsaw Studio staged owner ID");
|
||||
if (!requestedOwner.equals(openingOwner)) {
|
||||
throw new IllegalStateException("Jigsaw Studio staging does not own the active opening lease");
|
||||
}
|
||||
if (activeOwner != null && !requestedOwner.equals(activeOwner)) {
|
||||
throw new IllegalStateException("Jigsaw Studio is owned by another player session");
|
||||
}
|
||||
if (STAGED.get() != null) {
|
||||
throw new IllegalStateException("A Jigsaw Studio replacement is already staged");
|
||||
}
|
||||
ActiveRequest preserved = preservedRequestId == null ? null : active(preservedRequestId);
|
||||
if (preservedRequestId != null && preserved == null) {
|
||||
throw new IllegalStateException("The Jigsaw Studio being replaced is no longer active");
|
||||
}
|
||||
if (activeOwner != null && preserved == null) {
|
||||
throw new IllegalStateException("The active Jigsaw Studio must be preserved during replacement");
|
||||
}
|
||||
if (preserved != null && preserved.request().ownerId() != null
|
||||
&& !requestedOwner.equals(preserved.request().ownerId())) {
|
||||
throw new IllegalStateException("The Jigsaw Studio being replaced belongs to another player session");
|
||||
}
|
||||
ActiveRequest candidate = createActiveRequest(
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
initialLayout,
|
||||
requestedOwner);
|
||||
StagedActivation staged = new StagedActivation(
|
||||
UUID.randomUUID(), candidate.request(), candidate.session());
|
||||
STAGED.set(new StagedState(staged, candidate, preserved, false));
|
||||
return staged;
|
||||
}
|
||||
|
||||
public static synchronized boolean beginStagedGeneration(StagedActivation expected) {
|
||||
StagedState state = stagedState(expected);
|
||||
if (state == null || state.generationVisible()) {
|
||||
return false;
|
||||
}
|
||||
STAGED.set(new StagedState(state.staged(), state.candidate(), state.preserved(), true));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static synchronized boolean commit(StagedActivation expected) {
|
||||
StagedState state = stagedState(expected);
|
||||
if (state == null || !state.generationVisible()) {
|
||||
return false;
|
||||
}
|
||||
if (state.preserved() != null) {
|
||||
ACTIVE.remove(normalize(state.preserved().request().packKey()), state.preserved());
|
||||
}
|
||||
ACTIVE.put(normalize(state.candidate().request().packKey()), state.candidate());
|
||||
STAGED.set(null);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static synchronized boolean rollback(StagedActivation expected) {
|
||||
StagedState state = stagedState(expected);
|
||||
if (state == null) {
|
||||
return false;
|
||||
}
|
||||
STAGED.set(null);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Request getGeneratorRequest(String packKey) {
|
||||
StagedState state = STAGED.get();
|
||||
if (state != null && state.generationVisible()
|
||||
&& normalize(state.candidate().request().packKey()).equals(normalize(packKey))) {
|
||||
return state.candidate().request();
|
||||
}
|
||||
return getRequest(packKey);
|
||||
}
|
||||
|
||||
public static JigsawStudioSession getGeneratorSession(String packKey) {
|
||||
StagedState state = STAGED.get();
|
||||
if (state != null && state.generationVisible()
|
||||
&& normalize(state.candidate().request().packKey()).equals(normalize(packKey))) {
|
||||
return state.candidate().session();
|
||||
}
|
||||
return getSession(packKey);
|
||||
}
|
||||
|
||||
public static boolean tryBeginOpen(UUID ownerId) {
|
||||
UUID requestedOwner = Objects.requireNonNull(ownerId, "Jigsaw Studio opening owner ID");
|
||||
UUID activeOwnerId = activeOwnerId();
|
||||
if (activeOwnerId != null && !requestedOwner.equals(activeOwnerId)) {
|
||||
return false;
|
||||
}
|
||||
return OPENING_OWNER.compareAndSet(null, requestedOwner);
|
||||
}
|
||||
|
||||
public static void finishOpen(UUID ownerId) {
|
||||
if (ownerId != null) {
|
||||
OPENING_OWNER.compareAndSet(ownerId, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static UUID openingOwnerId() {
|
||||
return OPENING_OWNER.get();
|
||||
}
|
||||
|
||||
public static UUID activeOwnerId() {
|
||||
for (ActiveRequest activeRequest : ACTIVE.values()) {
|
||||
UUID ownerId = activeRequest.request().ownerId();
|
||||
if (ownerId != null) {
|
||||
return ownerId;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void deactivate(String packKey) {
|
||||
if (packKey != null) {
|
||||
ACTIVE.remove(normalize(packKey));
|
||||
StagedState state = STAGED.get();
|
||||
if (state != null && (normalize(state.candidate().request().packKey()).equals(normalize(packKey))
|
||||
|| state.preserved() != null && normalize(state.preserved().request().packKey())
|
||||
.equals(normalize(packKey)))) {
|
||||
STAGED.compareAndSet(state, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean deactivate(String packKey, UUID requestId) {
|
||||
if (packKey == null || requestId == null) {
|
||||
return false;
|
||||
}
|
||||
StagedState staged = STAGED.get();
|
||||
if (staged != null && staged.preserved() != null
|
||||
&& requestId.equals(staged.preserved().request().requestId())
|
||||
&& normalize(packKey).equals(normalize(staged.preserved().request().packKey()))) {
|
||||
return false;
|
||||
}
|
||||
AtomicBoolean removed = new AtomicBoolean(false);
|
||||
ACTIVE.computeIfPresent(normalize(packKey), (key, activeRequest) -> {
|
||||
if (!requestId.equals(activeRequest.request().requestId())) {
|
||||
return activeRequest;
|
||||
}
|
||||
removed.set(true);
|
||||
return null;
|
||||
});
|
||||
return removed.get();
|
||||
}
|
||||
|
||||
public static boolean isActive(String packKey) {
|
||||
return getRequest(packKey) != null;
|
||||
}
|
||||
|
||||
public static Request getRequest(String packKey) {
|
||||
ActiveRequest activeRequest = active(packKey);
|
||||
return activeRequest == null ? null : activeRequest.request();
|
||||
}
|
||||
|
||||
public static JigsawStudioSession getSession(String packKey) {
|
||||
ActiveRequest activeRequest = active(packKey);
|
||||
return activeRequest == null ? null : activeRequest.session();
|
||||
}
|
||||
|
||||
public static JigsawStudioLayout getLayout(String packKey) {
|
||||
JigsawStudioSession session = getSession(packKey);
|
||||
return session == null ? null : session.layout();
|
||||
}
|
||||
|
||||
public static Request getRequest(UUID requestId) {
|
||||
ActiveRequest activeRequest = active(requestId);
|
||||
return activeRequest == null ? null : activeRequest.request();
|
||||
}
|
||||
|
||||
public static JigsawStudioSession getSession(UUID requestId) {
|
||||
ActiveRequest activeRequest = active(requestId);
|
||||
return activeRequest == null ? null : activeRequest.session();
|
||||
}
|
||||
|
||||
private static ActiveRequest active(String packKey) {
|
||||
if (packKey == null) {
|
||||
return null;
|
||||
}
|
||||
return ACTIVE.get(normalize(packKey));
|
||||
}
|
||||
|
||||
private static ActiveRequest active(UUID requestId) {
|
||||
if (requestId == null) {
|
||||
return null;
|
||||
}
|
||||
for (ActiveRequest activeRequest : ACTIVE.values()) {
|
||||
if (requestId.equals(activeRequest.request().requestId())) {
|
||||
return activeRequest;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static ActiveRequest createActiveRequest(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
JigsawStudioLayout initialLayout,
|
||||
UUID ownerId
|
||||
) {
|
||||
Request request = new Request(
|
||||
UUID.randomUUID(),
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
ownerId);
|
||||
JigsawStudioLayout layout = Objects.requireNonNull(initialLayout, "Initial Jigsaw Studio layout");
|
||||
if (layout.mode() != mode) {
|
||||
throw new IllegalArgumentException("Initial Jigsaw Studio layout mode does not match the request");
|
||||
}
|
||||
if (!layout.cellDimensions().equals(cellDimensions)) {
|
||||
throw new IllegalArgumentException("Initial Jigsaw Studio layout cell dimensions do not match the request");
|
||||
}
|
||||
JigsawStudioSession session = new JigsawStudioSession(
|
||||
request.requestId(),
|
||||
request.packKey(),
|
||||
request.structureKey(),
|
||||
layout);
|
||||
return new ActiveRequest(request, session);
|
||||
}
|
||||
|
||||
private static StagedState stagedState(StagedActivation expected) {
|
||||
StagedActivation staged = Objects.requireNonNull(expected, "Staged Jigsaw Studio activation");
|
||||
StagedState state = STAGED.get();
|
||||
return state != null && state.staged().stageId().equals(staged.stageId()) ? state : null;
|
||||
}
|
||||
|
||||
private static String normalize(String key) {
|
||||
return key.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private record ActiveRequest(Request request, JigsawStudioSession session) {
|
||||
}
|
||||
|
||||
private record StagedState(
|
||||
StagedActivation staged,
|
||||
ActiveRequest candidate,
|
||||
ActiveRequest preserved,
|
||||
boolean generationVisible
|
||||
) {
|
||||
}
|
||||
|
||||
public record StagedActivation(
|
||||
UUID stageId,
|
||||
Request request,
|
||||
JigsawStudioSession session
|
||||
) {
|
||||
public StagedActivation {
|
||||
Objects.requireNonNull(stageId, "Jigsaw Studio stage ID");
|
||||
Objects.requireNonNull(request, "Jigsaw Studio staged request");
|
||||
Objects.requireNonNull(session, "Jigsaw Studio staged session");
|
||||
if (!request.requestId().equals(session.sessionId())) {
|
||||
throw new IllegalArgumentException("Staged Jigsaw Studio request and session IDs do not match");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Request(
|
||||
UUID requestId,
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
UUID ownerId
|
||||
) {
|
||||
public Request {
|
||||
requestId = Objects.requireNonNull(requestId, "Jigsaw Studio request ID");
|
||||
packKey = requireKey(packKey, "pack");
|
||||
structureKey = requireKey(structureKey, "structure");
|
||||
mode = Objects.requireNonNull(mode, "Jigsaw Studio mode");
|
||||
compatibilityTarget = Objects.requireNonNull(
|
||||
compatibilityTarget,
|
||||
"Jigsaw Studio compatibility target"
|
||||
);
|
||||
cellDimensions = Objects.requireNonNull(cellDimensions, "Jigsaw Studio cell dimensions");
|
||||
source = Objects.requireNonNull(source, "Jigsaw Studio source data");
|
||||
}
|
||||
|
||||
private static String requireKey(String value, String name) {
|
||||
Objects.requireNonNull(value, "Jigsaw Studio " + name + " key");
|
||||
String normalized = value.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio " + name + " key cannot be blank");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class JigsawStudioAuthoringAccess {
|
||||
private JigsawStudioAuthoringAccess() {
|
||||
}
|
||||
|
||||
public static boolean isEditable(StructureOwnershipManifest manifest) {
|
||||
StructureOwnershipManifest ownership = Objects.requireNonNull(
|
||||
manifest,
|
||||
"Jigsaw Studio ownership manifest");
|
||||
return ownership.provenance().origin() != StructureOwnershipManifest.Origin.MANAGED_DATAPACK;
|
||||
}
|
||||
|
||||
public static StructureOwnershipManifest requireEditable(
|
||||
StructureOwnershipManifest manifest
|
||||
) throws IOException {
|
||||
StructureOwnershipManifest ownership = Objects.requireNonNull(
|
||||
manifest,
|
||||
"Jigsaw Studio ownership manifest");
|
||||
if (!isEditable(ownership)) {
|
||||
throw new IOException("This graph is read-only because it is managed by datapack ingest; "
|
||||
+ "adopt or clone it before making authoring changes.");
|
||||
}
|
||||
return ownership;
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public record JigsawStudioBay(
|
||||
String stableId,
|
||||
JigsawStudioBayKind kind,
|
||||
Optional<JigsawStudioWorkcellSpec> workcellSpec,
|
||||
String authorDisplayName,
|
||||
JigsawStudioBounds bounds
|
||||
) {
|
||||
public JigsawStudioBay {
|
||||
stableId = requireStableId(stableId);
|
||||
kind = Objects.requireNonNull(kind, "Jigsaw Studio bay kind");
|
||||
workcellSpec = Objects.requireNonNull(workcellSpec, "Jigsaw Studio workcell specification");
|
||||
authorDisplayName = authorDisplayName == null ? "" : authorDisplayName.trim();
|
||||
bounds = Objects.requireNonNull(bounds, "Jigsaw Studio bay bounds");
|
||||
if (kind == JigsawStudioBayKind.PLANAR_WORKCELL && workcellSpec.isEmpty()) {
|
||||
throw new IllegalArgumentException("Planar Jigsaw Studio workcells require an archetype");
|
||||
}
|
||||
if (kind == JigsawStudioBayKind.SPATIAL_WORKCELL && workcellSpec.isPresent()) {
|
||||
throw new IllegalArgumentException("Spatial Jigsaw Studio workcells cannot declare an archetype");
|
||||
}
|
||||
if (workcellSpec.isPresent() && !workcellSpec.get().dimensions().equals(bounds.dimensions())) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio workcell specification dimensions do not match bounds");
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<JigsawPlanarArchetype> archetype() {
|
||||
return workcellSpec.map(JigsawStudioWorkcellSpec::archetype);
|
||||
}
|
||||
|
||||
public boolean enabled() {
|
||||
return workcellSpec.map(JigsawStudioWorkcellSpec::enabled).orElse(true);
|
||||
}
|
||||
|
||||
public String canonicalDisplayName() {
|
||||
return archetype().map(JigsawPlanarArchetype::displayName).orElse("Spatial");
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return authorDisplayName.isEmpty() ? canonicalDisplayName() : authorDisplayName;
|
||||
}
|
||||
|
||||
public JigsawStudioCellDimensions capacity() {
|
||||
return bounds.dimensions();
|
||||
}
|
||||
|
||||
public Optional<JigsawPlanarTopology> topology() {
|
||||
return archetype().map(JigsawPlanarArchetype::canonicalTopology);
|
||||
}
|
||||
|
||||
private static String requireStableId(String value) {
|
||||
Objects.requireNonNull(value, "Jigsaw Studio bay stable ID");
|
||||
String normalized = value.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio bay stable ID cannot be blank");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
public enum JigsawStudioBayKind {
|
||||
PLANAR_WORKCELL,
|
||||
SPATIAL_WORKCELL
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public record JigsawStudioBounds(
|
||||
int originX,
|
||||
int originY,
|
||||
int originZ,
|
||||
JigsawStudioCellDimensions dimensions
|
||||
) {
|
||||
public JigsawStudioBounds {
|
||||
dimensions = Objects.requireNonNull(dimensions, "Jigsaw Studio bounds dimensions");
|
||||
}
|
||||
|
||||
public int maxX() {
|
||||
return originX + dimensions.width() - 1;
|
||||
}
|
||||
|
||||
public int maxY() {
|
||||
return originY + dimensions.height() - 1;
|
||||
}
|
||||
|
||||
public int maxZ() {
|
||||
return originZ + dimensions.depth() - 1;
|
||||
}
|
||||
|
||||
public boolean contains(int worldX, int worldY, int worldZ) {
|
||||
return worldX >= originX && worldX <= maxX()
|
||||
&& worldY >= originY && worldY <= maxY()
|
||||
&& worldZ >= originZ && worldZ <= maxZ();
|
||||
}
|
||||
|
||||
public boolean intersectsHorizontal(int minX, int minZ, int maxX, int maxZ) {
|
||||
return this.maxX() >= minX && originX <= maxX
|
||||
&& this.maxZ() >= minZ && originZ <= maxZ;
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
public record JigsawStudioCellDimensions(int width, int height, int depth) {
|
||||
public static final int MAX_HORIZONTAL_AXIS = 128;
|
||||
public static final int MAX_HEIGHT = 192;
|
||||
public static final long MAX_VOLUME = 2_097_152L;
|
||||
|
||||
public JigsawStudioCellDimensions {
|
||||
if (width < 1 || height < 1 || depth < 1) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio cell dimensions must be positive");
|
||||
}
|
||||
if (width > MAX_HORIZONTAL_AXIS || depth > MAX_HORIZONTAL_AXIS) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio cell width and depth cannot exceed "
|
||||
+ MAX_HORIZONTAL_AXIS + " blocks");
|
||||
}
|
||||
if (height > MAX_HEIGHT) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio cell height cannot exceed "
|
||||
+ MAX_HEIGHT + " blocks");
|
||||
}
|
||||
long volume = (long) width * height * depth;
|
||||
if (volume > MAX_VOLUME) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio cell volume cannot exceed "
|
||||
+ MAX_VOLUME + " blocks");
|
||||
}
|
||||
}
|
||||
|
||||
public long volume() {
|
||||
return (long) width * height * depth;
|
||||
}
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
public enum JigsawStudioCompatibilityTarget {
|
||||
IRIS_EXTENDED,
|
||||
VANILLA_PORTABLE
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
public record JigsawStudioControlPosition(int worldX, int worldY, int worldZ) {
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,382 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
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.engine.framework.structure.PlanarJigsawWorkcellResolver;
|
||||
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.IrisJigsawMode;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
|
||||
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 java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
public final class JigsawStudioGraphMapper {
|
||||
private JigsawStudioGraphMapper() {
|
||||
}
|
||||
|
||||
public static JigsawStudioLayout map(IrisData data, IrisStructure structure) {
|
||||
Objects.requireNonNull(data, "Jigsaw Studio graph mapping requires pack data");
|
||||
Objects.requireNonNull(structure, "Jigsaw Studio graph mapping requires a structure");
|
||||
JigsawStudioMode mode = structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW
|
||||
? JigsawStudioMode.PLANAR_JIGSAW
|
||||
: JigsawStudioMode.SPATIAL_JIGSAW;
|
||||
JigsawStudioVariantCatalog catalog = catalog(data, structure, mode);
|
||||
IrisPosition configuredCell = structure.getCellSize();
|
||||
JigsawStudioCellDimensions dimensions = configuredCell == null
|
||||
? new JigsawStudioCellDimensions(15, 15, 15)
|
||||
: new JigsawStudioCellDimensions(
|
||||
Math.max(1, configuredCell.getX()),
|
||||
Math.max(1, configuredCell.getY()),
|
||||
Math.max(1, configuredCell.getZ()));
|
||||
if (mode == JigsawStudioMode.SPATIAL_JIGSAW) {
|
||||
dimensions = expandSpatialDimensions(data, catalog, dimensions);
|
||||
return JigsawStudioLayout.createSpatial(
|
||||
dimensions,
|
||||
catalog,
|
||||
structure.getSpatialWorkcellDisplayName());
|
||||
}
|
||||
Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell> resolved =
|
||||
PlanarJigsawWorkcellResolver.resolve(structure);
|
||||
List<JigsawStudioWorkcellSpec> workcells = new ArrayList<>(resolved.size());
|
||||
for (JigsawPlanarArchetype archetype : JigsawPlanarArchetype.values()) {
|
||||
PlanarJigsawWorkcellResolver.ResolvedWorkcell workcell = resolved.get(archetype.modelArchetype());
|
||||
workcells.add(new JigsawStudioWorkcellSpec(
|
||||
archetype,
|
||||
workcell.displayName(),
|
||||
new JigsawStudioCellDimensions(
|
||||
workcell.width(),
|
||||
workcell.height(),
|
||||
workcell.depth()),
|
||||
workcell.enabled()));
|
||||
}
|
||||
return JigsawStudioLayout.createPlanar(dimensions, workcells, catalog);
|
||||
}
|
||||
|
||||
public static JigsawStudioVariantCatalog catalog(
|
||||
IrisData data,
|
||||
IrisStructure structure,
|
||||
JigsawStudioMode mode
|
||||
) {
|
||||
IrisData source = Objects.requireNonNull(data, "Jigsaw Studio catalog pack data");
|
||||
IrisStructure root = Objects.requireNonNull(structure, "Jigsaw Studio catalog structure");
|
||||
JigsawStudioMode activeMode = Objects.requireNonNull(mode, "Jigsaw Studio catalog mode");
|
||||
OwnedResources owned = ownedResources(source, root);
|
||||
Map<String, MutableVariant> variants = new LinkedHashMap<>();
|
||||
Set<String> visitedPools = new LinkedHashSet<>();
|
||||
Set<String> queuedPools = new HashSet<>();
|
||||
ArrayDeque<String> pools = new ArrayDeque<>();
|
||||
enqueuePool(root.getStartPool(), pools, queuedPools);
|
||||
traversePools(source, activeMode, owned, pools, queuedPools, visitedPools, variants);
|
||||
|
||||
for (String poolKey : owned.poolKeys()) {
|
||||
enqueuePool(poolKey, pools, queuedPools);
|
||||
}
|
||||
traversePools(source, activeMode, owned, pools, queuedPools, visitedPools, variants);
|
||||
|
||||
for (String pieceKey : owned.pieceKeys()) {
|
||||
addOwnedVariant(source, activeMode, owned, pieceKey, variants);
|
||||
}
|
||||
|
||||
List<JigsawStudioVariant> built = new ArrayList<>(variants.size());
|
||||
for (MutableVariant variant : variants.values()) {
|
||||
built.add(variant.build(source));
|
||||
}
|
||||
return new JigsawStudioVariantCatalog(built, owned.editable());
|
||||
}
|
||||
|
||||
public static JigsawPlanarTopology topologyOf(IrisJigsawPiece piece) {
|
||||
Objects.requireNonNull(piece, "Planar topology requires a jigsaw piece");
|
||||
int mask = 0;
|
||||
if (piece.getConnectors() != null) {
|
||||
for (IrisJigsawConnector connector : piece.getConnectors()) {
|
||||
if (connector == null || connector.getDirection() == null) {
|
||||
continue;
|
||||
}
|
||||
mask |= directionBit(connector.getDirection());
|
||||
}
|
||||
}
|
||||
return JigsawPlanarTopology.fromMask(mask);
|
||||
}
|
||||
|
||||
static JigsawStudioCellDimensions expandSpatialDimensions(
|
||||
IrisData data,
|
||||
JigsawStudioVariantCatalog catalog,
|
||||
JigsawStudioCellDimensions configured
|
||||
) {
|
||||
if (data.getObjectLoader() == null) {
|
||||
return configured;
|
||||
}
|
||||
int width = configured.width();
|
||||
int height = configured.height();
|
||||
int depth = configured.depth();
|
||||
for (JigsawStudioVariant variant : catalog.spatialVariants()) {
|
||||
IrisObject object = data.getObjectLoader().load(variant.objectKey());
|
||||
if (object == null) {
|
||||
continue;
|
||||
}
|
||||
int objectWidth = object.getW();
|
||||
int objectDepth = object.getD();
|
||||
if (variant.rotatable()) {
|
||||
int horizontalSpan = Math.max(objectWidth, objectDepth);
|
||||
objectWidth = horizontalSpan;
|
||||
objectDepth = horizontalSpan;
|
||||
}
|
||||
width = Math.max(width, objectWidth);
|
||||
height = Math.max(height, object.getH());
|
||||
depth = Math.max(depth, objectDepth);
|
||||
}
|
||||
return new JigsawStudioCellDimensions(width, height, depth);
|
||||
}
|
||||
|
||||
private static void traversePools(
|
||||
IrisData data,
|
||||
JigsawStudioMode mode,
|
||||
OwnedResources owned,
|
||||
ArrayDeque<String> pools,
|
||||
Set<String> queuedPools,
|
||||
Set<String> visitedPools,
|
||||
Map<String, MutableVariant> variants
|
||||
) {
|
||||
while (!pools.isEmpty()) {
|
||||
String poolKey = pools.removeFirst();
|
||||
if (!visitedPools.add(poolKey)) {
|
||||
continue;
|
||||
}
|
||||
IrisJigsawPool pool = StructureResources.pool(data.getPackResources(), poolKey);
|
||||
if (pool == null) {
|
||||
continue;
|
||||
}
|
||||
enqueuePool(pool.getFallback(), pools, queuedPools);
|
||||
if (pool.getPieces() == null) {
|
||||
continue;
|
||||
}
|
||||
for (int entryIndex = 0; entryIndex < pool.getPieces().size(); entryIndex++) {
|
||||
IrisJigsawPieceEntry entry = pool.getPieces().get(entryIndex);
|
||||
if (entry == null || entry.isEmpty() || entry.getPiece() == null || entry.getPiece().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String pieceKey = entry.getPiece();
|
||||
IrisJigsawPiece piece = StructureResources.piece(data.getPackResources(), pieceKey);
|
||||
if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
MutableVariant variant = variants.computeIfAbsent(
|
||||
pieceKey,
|
||||
key -> new MutableVariant(
|
||||
key,
|
||||
piece,
|
||||
mode,
|
||||
owned.owns(key, piece.getObject())));
|
||||
variant.addMembership(new JigsawStudioPoolMembership(
|
||||
poolKey,
|
||||
entryIndex,
|
||||
entry.getWeight(),
|
||||
entry.getChance()));
|
||||
enqueueConnectorPools(piece, pools, queuedPools);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void addOwnedVariant(
|
||||
IrisData data,
|
||||
JigsawStudioMode mode,
|
||||
OwnedResources owned,
|
||||
String pieceKey,
|
||||
Map<String, MutableVariant> variants
|
||||
) {
|
||||
if (variants.containsKey(pieceKey)) {
|
||||
return;
|
||||
}
|
||||
IrisJigsawPiece piece = StructureResources.piece(data.getPackResources(), pieceKey);
|
||||
if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) {
|
||||
return;
|
||||
}
|
||||
variants.put(pieceKey, new MutableVariant(pieceKey, piece, mode, owned.owns(pieceKey, piece.getObject())));
|
||||
}
|
||||
|
||||
private static OwnedResources ownedResources(IrisData data, IrisStructure structure) {
|
||||
String structureKey = structure.getLoadKey();
|
||||
File dataFolder = data.getDataFolder();
|
||||
if (structureKey == null || structureKey.isBlank() || dataFolder == null) {
|
||||
return OwnedResources.empty();
|
||||
}
|
||||
try {
|
||||
Path root = dataFolder.toPath().toAbsolutePath().normalize();
|
||||
StructureTransactionWriter writer = new StructureTransactionWriter(root);
|
||||
Path manifestPath = writer.ownershipManifestPath(StructureKey.parse(structureKey, "iris"));
|
||||
if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return OwnedResources.empty();
|
||||
}
|
||||
StructureOwnershipManifest manifest = StructureOwnershipManifest.fromJson(Files.readAllBytes(manifestPath));
|
||||
Set<String> pieceKeys = new TreeSet<>();
|
||||
Set<String> poolKeys = new TreeSet<>();
|
||||
Set<String> objectKeys = new TreeSet<>();
|
||||
for (String path : manifest.resourceHashes().keySet()) {
|
||||
addOwnedKey(path, "jigsaw-pieces/", ".json", pieceKeys);
|
||||
addOwnedKey(path, "jigsaw-pools/", ".json", poolKeys);
|
||||
addOwnedKey(path, "objects/", ".iob", objectKeys);
|
||||
}
|
||||
boolean editable = JigsawStudioAuthoringAccess.isEditable(manifest);
|
||||
return new OwnedResources(pieceKeys, poolKeys, objectKeys, editable);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException(
|
||||
"Failed to read Jigsaw Studio ownership for structure '" + structureKey + "'",
|
||||
exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static void addOwnedKey(String path, String prefix, String suffix, Set<String> keys) {
|
||||
if (path.startsWith(prefix) && path.endsWith(suffix) && path.length() > prefix.length() + suffix.length()) {
|
||||
keys.add(path.substring(prefix.length(), path.length() - suffix.length()));
|
||||
}
|
||||
}
|
||||
|
||||
private static int directionBit(IrisDirection direction) {
|
||||
return switch (direction) {
|
||||
case NORTH_NEGATIVE_Z -> JigsawPlanarDirection.NORTH.bit();
|
||||
case EAST_POSITIVE_X -> JigsawPlanarDirection.EAST.bit();
|
||||
case SOUTH_POSITIVE_Z -> JigsawPlanarDirection.SOUTH.bit();
|
||||
case WEST_NEGATIVE_X -> JigsawPlanarDirection.WEST.bit();
|
||||
case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> 0;
|
||||
};
|
||||
}
|
||||
|
||||
private static void enqueueConnectorPools(
|
||||
IrisJigsawPiece piece,
|
||||
ArrayDeque<String> pools,
|
||||
Set<String> queuedPools
|
||||
) {
|
||||
if (piece.getConnectors() == null) {
|
||||
return;
|
||||
}
|
||||
for (IrisJigsawConnector connector : piece.getConnectors()) {
|
||||
if (connector != null) {
|
||||
enqueuePool(connector.getPool(), pools, queuedPools);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void enqueuePool(String poolKey, ArrayDeque<String> pools, Set<String> queuedPools) {
|
||||
if (poolKey == null || poolKey.isBlank() || !queuedPools.add(poolKey)) {
|
||||
return;
|
||||
}
|
||||
pools.addLast(poolKey);
|
||||
}
|
||||
|
||||
private static final class MutableVariant {
|
||||
private final String pieceKey;
|
||||
private final IrisJigsawPiece piece;
|
||||
private final JigsawStudioMode mode;
|
||||
private final boolean owned;
|
||||
private final List<JigsawStudioPoolMembership> memberships = new ArrayList<>();
|
||||
|
||||
private MutableVariant(
|
||||
String pieceKey,
|
||||
IrisJigsawPiece piece,
|
||||
JigsawStudioMode mode,
|
||||
boolean owned
|
||||
) {
|
||||
this.pieceKey = pieceKey;
|
||||
this.piece = piece;
|
||||
this.mode = mode;
|
||||
this.owned = owned;
|
||||
}
|
||||
|
||||
private void addMembership(JigsawStudioPoolMembership membership) {
|
||||
memberships.add(membership);
|
||||
}
|
||||
|
||||
private JigsawStudioVariant build(IrisData data) {
|
||||
Optional<JigsawStudioCellDimensions> dimensions = objectDimensions(data, piece, mode);
|
||||
return new JigsawStudioVariant(
|
||||
pieceKey,
|
||||
piece.getObject(),
|
||||
piece.getDisplayName(),
|
||||
dimensions,
|
||||
mode,
|
||||
mode == JigsawStudioMode.PLANAR_JIGSAW
|
||||
? Optional.of(topologyOf(piece))
|
||||
: Optional.empty(),
|
||||
piece.isRotatable(),
|
||||
owned,
|
||||
piece.getThemes() == null ? List.of() : piece.getThemes(),
|
||||
JigsawStudioPieceRules.from(piece.resolvedRules()),
|
||||
memberships);
|
||||
}
|
||||
|
||||
private static Optional<JigsawStudioCellDimensions> objectDimensions(
|
||||
IrisData data,
|
||||
IrisJigsawPiece piece,
|
||||
JigsawStudioMode mode
|
||||
) {
|
||||
if (data.getObjectLoader() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
IrisObject object = data.getObjectLoader().load(piece.getObject());
|
||||
if (object == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
JigsawStudioCellDimensions sourceDimensions = new JigsawStudioCellDimensions(
|
||||
object.getW(),
|
||||
object.getH(),
|
||||
object.getD());
|
||||
if (mode == JigsawStudioMode.SPATIAL_JIGSAW) {
|
||||
return Optional.of(sourceDimensions);
|
||||
}
|
||||
JigsawPlanarTopology topology = topologyOf(piece);
|
||||
int quarterTurns = JigsawPlanarArchetype.fromTopology(topology)
|
||||
.sourceToCanonicalQuarterTurns(topology);
|
||||
return Math.floorMod(quarterTurns, 2) == 0
|
||||
? Optional.of(sourceDimensions)
|
||||
: Optional.of(new JigsawStudioCellDimensions(
|
||||
sourceDimensions.depth(),
|
||||
sourceDimensions.height(),
|
||||
sourceDimensions.width()));
|
||||
}
|
||||
}
|
||||
|
||||
private record OwnedResources(
|
||||
Set<String> pieceKeys,
|
||||
Set<String> poolKeys,
|
||||
Set<String> objectKeys,
|
||||
boolean editable
|
||||
) {
|
||||
private OwnedResources {
|
||||
pieceKeys = Collections.unmodifiableSet(new LinkedHashSet<>(pieceKeys));
|
||||
poolKeys = Collections.unmodifiableSet(new LinkedHashSet<>(poolKeys));
|
||||
objectKeys = Collections.unmodifiableSet(new LinkedHashSet<>(objectKeys));
|
||||
}
|
||||
|
||||
private boolean owns(String pieceKey, String objectKey) {
|
||||
return editable && pieceKeys.contains(pieceKey) && objectKeys.contains(objectKey);
|
||||
}
|
||||
|
||||
private static OwnedResources empty() {
|
||||
return new OwnedResources(Set.of(), Set.of(), Set.of(), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,344 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class JigsawStudioLayout {
|
||||
public static final int FLOOR_Y = 64;
|
||||
public static final int PLANAR_COLUMNS = 3;
|
||||
public static final int PLANAR_GAP = 1;
|
||||
public static final int MAX_VARIANTS = 512;
|
||||
public static final String SPATIAL_WORKCELL_ID = "workcell/spatial";
|
||||
|
||||
private static final int FIRST_ORIGIN = 16;
|
||||
private static final JigsawStudioControlPosition CONTROL_POSITION =
|
||||
new JigsawStudioControlPosition(8, FLOOR_Y + 1, 8);
|
||||
|
||||
private final JigsawStudioMode mode;
|
||||
private final JigsawStudioCellDimensions cellDimensions;
|
||||
private final int columns;
|
||||
private final int gap;
|
||||
private final JigsawStudioVariantCatalog variantCatalog;
|
||||
private final List<JigsawStudioBay> bays;
|
||||
private final Map<String, JigsawStudioBay> byStableId;
|
||||
private final Map<String, String> spatialVariantByBay;
|
||||
|
||||
private JigsawStudioLayout(
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
int columns,
|
||||
int gap,
|
||||
JigsawStudioVariantCatalog variantCatalog,
|
||||
List<JigsawStudioBay> bays,
|
||||
Map<String, String> spatialVariantByBay
|
||||
) {
|
||||
this.mode = mode;
|
||||
this.cellDimensions = cellDimensions;
|
||||
this.columns = columns;
|
||||
this.gap = gap;
|
||||
this.variantCatalog = variantCatalog;
|
||||
this.bays = Collections.unmodifiableList(new ArrayList<>(bays));
|
||||
Map<String, JigsawStudioBay> index = new LinkedHashMap<>();
|
||||
for (JigsawStudioBay bay : bays) {
|
||||
JigsawStudioBay previous = index.putIfAbsent(bay.stableId(), bay);
|
||||
if (previous != null) {
|
||||
throw new IllegalArgumentException("Duplicate Jigsaw Studio workcell stable ID " + bay.stableId());
|
||||
}
|
||||
}
|
||||
this.byStableId = Collections.unmodifiableMap(index);
|
||||
this.spatialVariantByBay = Collections.unmodifiableMap(new LinkedHashMap<>(spatialVariantByBay));
|
||||
}
|
||||
|
||||
public static JigsawStudioLayout create(
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
JigsawStudioVariantCatalog variantCatalog
|
||||
) {
|
||||
JigsawStudioMode activeMode = Objects.requireNonNull(mode, "Jigsaw Studio layout mode");
|
||||
JigsawStudioCellDimensions dimensions = Objects.requireNonNull(
|
||||
cellDimensions,
|
||||
"Jigsaw Studio layout cell dimensions");
|
||||
JigsawStudioVariantCatalog catalog = Objects.requireNonNull(
|
||||
variantCatalog,
|
||||
"Jigsaw Studio variant catalog");
|
||||
validateCatalogMode(activeMode, catalog);
|
||||
|
||||
if (activeMode == JigsawStudioMode.PLANAR_JIGSAW) {
|
||||
return createPlanar(dimensions, uniformSpecs(dimensions), catalog);
|
||||
}
|
||||
|
||||
return createSpatial(dimensions, catalog, "");
|
||||
}
|
||||
|
||||
public static JigsawStudioLayout createSpatial(
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
JigsawStudioVariantCatalog variantCatalog,
|
||||
String displayName
|
||||
) {
|
||||
JigsawStudioCellDimensions dimensions = Objects.requireNonNull(
|
||||
cellDimensions,
|
||||
"Spatial Jigsaw Studio cell dimensions");
|
||||
JigsawStudioVariantCatalog catalog = Objects.requireNonNull(
|
||||
variantCatalog,
|
||||
"Spatial Jigsaw Studio variant catalog");
|
||||
validateCatalogMode(JigsawStudioMode.SPATIAL_JIGSAW, catalog);
|
||||
String resolvedDisplayName = displayName == null ? "" : displayName.trim();
|
||||
|
||||
List<JigsawStudioVariant> variants = catalog.spatialVariants();
|
||||
List<JigsawStudioBay> workcells = new ArrayList<>(Math.max(1, variants.size()));
|
||||
Map<String, String> variantsByWorkcell = new LinkedHashMap<>();
|
||||
if (variants.isEmpty()) {
|
||||
workcells.add(new JigsawStudioBay(
|
||||
SPATIAL_WORKCELL_ID,
|
||||
JigsawStudioBayKind.SPATIAL_WORKCELL,
|
||||
Optional.empty(),
|
||||
resolvedDisplayName,
|
||||
new JigsawStudioBounds(FIRST_ORIGIN, FLOOR_Y + 1, FIRST_ORIGIN, dimensions)));
|
||||
} else {
|
||||
int originX = FIRST_ORIGIN;
|
||||
for (int index = 0; index < variants.size(); index++) {
|
||||
JigsawStudioVariant variant = variants.get(index);
|
||||
String stableId = index == 0
|
||||
? SPATIAL_WORKCELL_ID
|
||||
: SPATIAL_WORKCELL_ID + "/" + variant.pieceKey();
|
||||
workcells.add(new JigsawStudioBay(
|
||||
stableId,
|
||||
JigsawStudioBayKind.SPATIAL_WORKCELL,
|
||||
Optional.empty(),
|
||||
variant.resolvedDisplayName(),
|
||||
new JigsawStudioBounds(originX, FLOOR_Y + 1, FIRST_ORIGIN, dimensions)));
|
||||
variantsByWorkcell.put(stableId, variant.pieceKey());
|
||||
originX = Math.addExact(originX, Math.addExact(dimensions.width(), PLANAR_GAP));
|
||||
}
|
||||
}
|
||||
return new JigsawStudioLayout(
|
||||
JigsawStudioMode.SPATIAL_JIGSAW,
|
||||
dimensions,
|
||||
workcells.size(),
|
||||
PLANAR_GAP,
|
||||
catalog,
|
||||
workcells,
|
||||
variantsByWorkcell);
|
||||
}
|
||||
|
||||
public static JigsawStudioLayout createPlanar(
|
||||
JigsawStudioCellDimensions defaultDimensions,
|
||||
List<JigsawStudioWorkcellSpec> workcellSpecs,
|
||||
JigsawStudioVariantCatalog variantCatalog
|
||||
) {
|
||||
JigsawStudioCellDimensions defaults = Objects.requireNonNull(
|
||||
defaultDimensions,
|
||||
"Jigsaw Studio default cell dimensions");
|
||||
JigsawStudioVariantCatalog catalog = Objects.requireNonNull(
|
||||
variantCatalog,
|
||||
"Jigsaw Studio variant catalog");
|
||||
validateCatalogMode(JigsawStudioMode.PLANAR_JIGSAW, catalog);
|
||||
Map<JigsawPlanarArchetype, JigsawStudioWorkcellSpec> specs = indexSpecs(workcellSpecs);
|
||||
int[] columnWidths = new int[PLANAR_COLUMNS];
|
||||
int[] rowDepths = new int[2];
|
||||
JigsawPlanarArchetype[] archetypes = JigsawPlanarArchetype.values();
|
||||
for (int index = 0; index < archetypes.length; index++) {
|
||||
JigsawStudioCellDimensions dimensions = specs.get(archetypes[index]).dimensions();
|
||||
int column = index % PLANAR_COLUMNS;
|
||||
int row = index / PLANAR_COLUMNS;
|
||||
columnWidths[column] = Math.max(columnWidths[column], dimensions.width());
|
||||
rowDepths[row] = Math.max(rowDepths[row], dimensions.depth());
|
||||
}
|
||||
List<JigsawStudioBay> workcells = new ArrayList<>(archetypes.length);
|
||||
for (int index = 0; index < archetypes.length; index++) {
|
||||
JigsawPlanarArchetype archetype = archetypes[index];
|
||||
JigsawStudioWorkcellSpec spec = specs.get(archetype);
|
||||
workcells.add(new JigsawStudioBay(
|
||||
archetype.stableId(),
|
||||
JigsawStudioBayKind.PLANAR_WORKCELL,
|
||||
Optional.of(spec),
|
||||
spec.displayName(),
|
||||
planarBounds(index, spec.dimensions(), columnWidths, rowDepths)));
|
||||
}
|
||||
return new JigsawStudioLayout(
|
||||
JigsawStudioMode.PLANAR_JIGSAW,
|
||||
defaults,
|
||||
PLANAR_COLUMNS,
|
||||
PLANAR_GAP,
|
||||
catalog,
|
||||
workcells,
|
||||
Map.of());
|
||||
}
|
||||
|
||||
public JigsawStudioMode mode() {
|
||||
return mode;
|
||||
}
|
||||
|
||||
public JigsawStudioCellDimensions cellDimensions() {
|
||||
return cellDimensions;
|
||||
}
|
||||
|
||||
public int columns() {
|
||||
return columns;
|
||||
}
|
||||
|
||||
public int gap() {
|
||||
return gap;
|
||||
}
|
||||
|
||||
public JigsawStudioVariantCatalog variantCatalog() {
|
||||
return variantCatalog;
|
||||
}
|
||||
|
||||
public List<JigsawStudioBay> bays() {
|
||||
return bays;
|
||||
}
|
||||
|
||||
public JigsawStudioBay get(String stableId) {
|
||||
return stableId == null ? null : byStableId.get(stableId);
|
||||
}
|
||||
|
||||
public JigsawStudioBay findAt(int worldX, int worldY, int worldZ) {
|
||||
for (JigsawStudioBay bay : bays) {
|
||||
if (bay.bounds().contains(worldX, worldY, worldZ)) {
|
||||
return bay;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<JigsawStudioVariant> variants(JigsawStudioBay workcell) {
|
||||
JigsawStudioBay activeWorkcell = requireWorkcell(workcell);
|
||||
if (activeWorkcell.kind() == JigsawStudioBayKind.SPATIAL_WORKCELL) {
|
||||
String pieceKey = spatialVariantByBay.get(activeWorkcell.stableId());
|
||||
if (pieceKey == null) {
|
||||
return variantCatalog.spatialVariants();
|
||||
}
|
||||
return variantCatalog.find(pieceKey).map(List::of).orElseGet(List::of);
|
||||
}
|
||||
return variantCatalog.variants(activeWorkcell.archetype().orElseThrow());
|
||||
}
|
||||
|
||||
public Optional<JigsawStudioVariant> defaultVariant(JigsawStudioBay workcell) {
|
||||
List<JigsawStudioVariant> variants = variants(workcell);
|
||||
return variants.isEmpty() ? Optional.empty() : Optional.of(variants.getFirst());
|
||||
}
|
||||
|
||||
public boolean accepts(JigsawStudioBay workcell, JigsawStudioVariant variant) {
|
||||
JigsawStudioBay activeWorkcell = requireWorkcell(workcell);
|
||||
JigsawStudioVariant activeVariant = Objects.requireNonNull(variant, "Jigsaw Studio variant");
|
||||
if (variantCatalog.find(activeVariant.pieceKey()).filter(activeVariant::equals).isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (activeWorkcell.kind() == JigsawStudioBayKind.SPATIAL_WORKCELL) {
|
||||
return activeVariant.mode() == JigsawStudioMode.SPATIAL_JIGSAW
|
||||
&& variants(activeWorkcell).contains(activeVariant);
|
||||
}
|
||||
return activeVariant.archetype().filter(activeWorkcell.archetype().orElseThrow()::equals).isPresent();
|
||||
}
|
||||
|
||||
public Optional<JigsawStudioBay> workcellForVariant(String pieceKey) {
|
||||
Optional<JigsawStudioVariant> variant = variantCatalog.find(pieceKey);
|
||||
if (variant.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (mode == JigsawStudioMode.PLANAR_JIGSAW) {
|
||||
return variant.get().archetype().map(archetype -> get(archetype.stableId()));
|
||||
}
|
||||
for (Map.Entry<String, String> entry : spatialVariantByBay.entrySet()) {
|
||||
if (entry.getValue().equals(variant.get().pieceKey())) {
|
||||
return Optional.ofNullable(get(entry.getKey()));
|
||||
}
|
||||
}
|
||||
return Optional.ofNullable(get(SPATIAL_WORKCELL_ID));
|
||||
}
|
||||
|
||||
public JigsawStudioControlPosition controlPosition() {
|
||||
return CONTROL_POSITION;
|
||||
}
|
||||
|
||||
public int extentX() {
|
||||
int maximum = CONTROL_POSITION.worldX();
|
||||
for (JigsawStudioBay bay : bays) {
|
||||
maximum = Math.max(maximum, bay.bounds().maxX() + PLANAR_GAP);
|
||||
}
|
||||
return maximum;
|
||||
}
|
||||
|
||||
public int extentZ() {
|
||||
int maximum = CONTROL_POSITION.worldZ();
|
||||
for (JigsawStudioBay bay : bays) {
|
||||
maximum = Math.max(maximum, bay.bounds().maxZ() + PLANAR_GAP);
|
||||
}
|
||||
return maximum;
|
||||
}
|
||||
|
||||
private JigsawStudioBay requireWorkcell(JigsawStudioBay workcell) {
|
||||
JigsawStudioBay activeWorkcell = Objects.requireNonNull(workcell, "Jigsaw Studio workcell");
|
||||
if (byStableId.get(activeWorkcell.stableId()) != activeWorkcell) {
|
||||
throw new IllegalArgumentException("Workcell does not belong to this Jigsaw Studio layout");
|
||||
}
|
||||
return activeWorkcell;
|
||||
}
|
||||
|
||||
private static void validateCatalogMode(JigsawStudioMode mode, JigsawStudioVariantCatalog catalog) {
|
||||
for (JigsawStudioVariant variant : catalog.variants()) {
|
||||
if (variant.mode() != mode) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio variant mode does not match the layout mode");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<JigsawStudioWorkcellSpec> uniformSpecs(JigsawStudioCellDimensions dimensions) {
|
||||
List<JigsawStudioWorkcellSpec> specs = new ArrayList<>(JigsawPlanarArchetype.values().length);
|
||||
for (JigsawPlanarArchetype archetype : JigsawPlanarArchetype.values()) {
|
||||
specs.add(new JigsawStudioWorkcellSpec(archetype, "", dimensions, true));
|
||||
}
|
||||
return specs;
|
||||
}
|
||||
|
||||
private static Map<JigsawPlanarArchetype, JigsawStudioWorkcellSpec> indexSpecs(
|
||||
List<JigsawStudioWorkcellSpec> workcellSpecs
|
||||
) {
|
||||
List<JigsawStudioWorkcellSpec> source = List.copyOf(Objects.requireNonNull(
|
||||
workcellSpecs,
|
||||
"Jigsaw Studio workcell specifications"));
|
||||
Map<JigsawPlanarArchetype, JigsawStudioWorkcellSpec> specs =
|
||||
new EnumMap<>(JigsawPlanarArchetype.class);
|
||||
for (JigsawStudioWorkcellSpec spec : source) {
|
||||
JigsawStudioWorkcellSpec active = Objects.requireNonNull(
|
||||
spec,
|
||||
"Jigsaw Studio workcell specification");
|
||||
if (specs.putIfAbsent(active.archetype(), active) != null) {
|
||||
throw new IllegalArgumentException(
|
||||
"Duplicate Jigsaw Studio workcell specification " + active.archetype());
|
||||
}
|
||||
}
|
||||
for (JigsawPlanarArchetype archetype : JigsawPlanarArchetype.values()) {
|
||||
if (!specs.containsKey(archetype)) {
|
||||
throw new IllegalArgumentException("Missing Jigsaw Studio workcell specification " + archetype);
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableMap(specs);
|
||||
}
|
||||
|
||||
private static JigsawStudioBounds planarBounds(
|
||||
int index,
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
int[] columnWidths,
|
||||
int[] rowDepths
|
||||
) {
|
||||
int column = index % PLANAR_COLUMNS;
|
||||
int row = index / PLANAR_COLUMNS;
|
||||
int originX = FIRST_ORIGIN;
|
||||
for (int current = 0; current < column; current++) {
|
||||
originX = Math.addExact(originX, Math.addExact(columnWidths[current], PLANAR_GAP));
|
||||
}
|
||||
int originZ = FIRST_ORIGIN;
|
||||
for (int current = 0; current < row; current++) {
|
||||
originZ = Math.addExact(originZ, Math.addExact(rowDepths[current], PLANAR_GAP));
|
||||
}
|
||||
return new JigsawStudioBounds(originX, FLOOR_Y + 1, originZ, dimensions);
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class JigsawStudioMarkerKeyCodec {
|
||||
private static final String STUDIO_NAMESPACE = "iris:";
|
||||
private static final Pattern INTERNAL_PATH = Pattern.compile("[a-z0-9._-]+(?:/[a-z0-9._-]+)*");
|
||||
|
||||
private JigsawStudioMarkerKeyCodec() {
|
||||
}
|
||||
|
||||
public static String encodePool(String internalPoolKey) {
|
||||
return STUDIO_NAMESPACE + requireInternalPath(internalPoolKey, "pool");
|
||||
}
|
||||
|
||||
public static String decodePool(String markerPoolKey) {
|
||||
String markerKey = Objects.requireNonNull(markerPoolKey, "Jigsaw Studio marker pool key").trim();
|
||||
if (!markerKey.toLowerCase(Locale.ROOT).startsWith(STUDIO_NAMESPACE)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Jigsaw Studio marker pools must use iris:<owned-pool-key>, not '" + markerKey + "'");
|
||||
}
|
||||
return requireInternalPath(markerKey.substring(STUDIO_NAMESPACE.length()), "pool");
|
||||
}
|
||||
|
||||
public static String requireInternalPath(String value, String kind) {
|
||||
String path = Objects.requireNonNull(value, "Jigsaw Studio " + kind + " key").trim();
|
||||
if (!INTERNAL_PATH.matcher(path).matches()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio " + kind
|
||||
+ " keys must use lowercase [a-z0-9._-/] resource-path characters");
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
public enum JigsawStudioMode {
|
||||
PLANAR_JIGSAW,
|
||||
SPATIAL_JIGSAW
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public record JigsawStudioPieceRules(
|
||||
int minimumDepth,
|
||||
int maximumDepth,
|
||||
int minimumPlacements,
|
||||
int maximumPlacements,
|
||||
boolean terminal
|
||||
) {
|
||||
public JigsawStudioPieceRules {
|
||||
if (minimumDepth < 0 || maximumDepth < minimumDepth || maximumDepth > 30) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio piece depth rules are invalid");
|
||||
}
|
||||
if (minimumPlacements < 0 || maximumPlacements < 0
|
||||
|| minimumPlacements > 512 || maximumPlacements > 512
|
||||
|| maximumPlacements != 0 && minimumPlacements > maximumPlacements) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio piece placement-count rules are invalid");
|
||||
}
|
||||
}
|
||||
|
||||
public static JigsawStudioPieceRules from(IrisJigsawPieceRules rules) {
|
||||
IrisJigsawPieceRules source = Objects.requireNonNull(rules, "Jigsaw Studio piece rules");
|
||||
return new JigsawStudioPieceRules(
|
||||
source.getMinimumDepth(),
|
||||
source.getMaximumDepth(),
|
||||
source.getMinimumPlacements(),
|
||||
source.getMaximumPlacements(),
|
||||
source.isTerminal());
|
||||
}
|
||||
}
|
||||
@@ -1,442 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.core.structure.authoring.StructureKey;
|
||||
import art.arcane.iris.core.structure.authoring.StructureHash;
|
||||
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
|
||||
import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
|
||||
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
|
||||
import art.arcane.iris.core.structure.authoring.StructureWriteOptions;
|
||||
import art.arcane.iris.core.structure.authoring.StructureWriteResult;
|
||||
import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class JigsawStudioPoolEditor {
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
private JigsawStudioPoolEditor() {
|
||||
}
|
||||
|
||||
public static WeightUpdate updateWeight(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String poolKey,
|
||||
String pieceKey,
|
||||
int weight
|
||||
) throws IOException {
|
||||
if (weight < 1) {
|
||||
throw new IllegalArgumentException("Jigsaw variant weight must be positive");
|
||||
}
|
||||
PoolUpdate update = updateOwnedPool(
|
||||
packRoot,
|
||||
structureKey,
|
||||
poolKey,
|
||||
(content, poolPath) -> mutateWeight(content, pieceKey, weight, poolPath));
|
||||
return new WeightUpdate(
|
||||
update.changed(),
|
||||
update.changedEntries(),
|
||||
update.poolPath(),
|
||||
update.writeResult());
|
||||
}
|
||||
|
||||
public static WeightUpdate updateWeightAtIndex(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String poolKey,
|
||||
int entryIndex,
|
||||
String expectedPieceKey,
|
||||
int weight
|
||||
) throws IOException {
|
||||
if (weight < 1) {
|
||||
throw new IllegalArgumentException("Jigsaw variant weight must be positive");
|
||||
}
|
||||
if (entryIndex < 0) {
|
||||
throw new IllegalArgumentException("Jigsaw pool entry index cannot be negative");
|
||||
}
|
||||
PoolUpdate update = updateOwnedPool(
|
||||
packRoot,
|
||||
structureKey,
|
||||
poolKey,
|
||||
(content, poolPath) -> mutateWeightAtIndex(
|
||||
content,
|
||||
entryIndex,
|
||||
expectedPieceKey,
|
||||
weight,
|
||||
poolPath));
|
||||
return new WeightUpdate(
|
||||
update.changed(),
|
||||
update.changedEntries(),
|
||||
update.poolPath(),
|
||||
update.writeResult());
|
||||
}
|
||||
|
||||
public static ChanceUpdate updateChanceAtIndex(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String poolKey,
|
||||
int entryIndex,
|
||||
String expectedPieceKey,
|
||||
double chance
|
||||
) throws IOException {
|
||||
if (!Double.isFinite(chance) || chance < 0D || chance > 1D) {
|
||||
throw new IllegalArgumentException("Jigsaw variant chance must be finite and within 0 and 1");
|
||||
}
|
||||
if (entryIndex < 0) {
|
||||
throw new IllegalArgumentException("Jigsaw pool entry index cannot be negative");
|
||||
}
|
||||
PoolUpdate update = updateOwnedPool(
|
||||
packRoot,
|
||||
structureKey,
|
||||
poolKey,
|
||||
(content, poolPath) -> mutateChanceAtIndex(
|
||||
content,
|
||||
entryIndex,
|
||||
expectedPieceKey,
|
||||
chance,
|
||||
poolPath));
|
||||
return new ChanceUpdate(
|
||||
update.changed(),
|
||||
update.changedEntries(),
|
||||
update.poolPath(),
|
||||
update.writeResult());
|
||||
}
|
||||
|
||||
public static PoolUpdate addPiece(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String poolKey,
|
||||
String pieceKey,
|
||||
int weight
|
||||
) throws IOException {
|
||||
if (weight < 1) {
|
||||
throw new IllegalArgumentException("Jigsaw piece weight must be positive");
|
||||
}
|
||||
return updateOwnedPool(
|
||||
packRoot,
|
||||
structureKey,
|
||||
poolKey,
|
||||
(content, poolPath) -> mutateAdd(content, pieceKey, weight, poolPath));
|
||||
}
|
||||
|
||||
public static PoolUpdate removePiece(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String poolKey,
|
||||
String pieceKey
|
||||
) throws IOException {
|
||||
return updateOwnedPool(
|
||||
packRoot,
|
||||
structureKey,
|
||||
poolKey,
|
||||
(content, poolPath) -> mutateRemove(content, pieceKey, poolPath));
|
||||
}
|
||||
|
||||
public static PoolUpdate removeEntry(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String poolKey,
|
||||
int entryIndex,
|
||||
String expectedPieceKey
|
||||
) throws IOException {
|
||||
if (entryIndex < 0) {
|
||||
throw new IllegalArgumentException("Jigsaw pool entry index cannot be negative");
|
||||
}
|
||||
return updateOwnedPool(
|
||||
packRoot,
|
||||
structureKey,
|
||||
poolKey,
|
||||
(content, poolPath) -> mutateRemoveAtIndex(
|
||||
content,
|
||||
entryIndex,
|
||||
expectedPieceKey,
|
||||
poolPath));
|
||||
}
|
||||
|
||||
public static PoolUpdate updateFallback(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String poolKey,
|
||||
String fallbackPoolKey
|
||||
) throws IOException {
|
||||
String fallback = fallbackPoolKey == null ? "" : fallbackPoolKey.trim();
|
||||
return updateOwnedPool(
|
||||
packRoot,
|
||||
structureKey,
|
||||
poolKey,
|
||||
(content, poolPath) -> mutateFallback(content, fallback, poolPath));
|
||||
}
|
||||
|
||||
private static PoolUpdate updateOwnedPool(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String poolKey,
|
||||
PoolContentEditor editor
|
||||
) throws IOException {
|
||||
Path root = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
StructureKey ownershipKey = StructureKey.parse(structureKey, "iris");
|
||||
StructureTransactionWriter writer = new StructureTransactionWriter(root);
|
||||
Path manifestPath = writer.ownershipManifestPath(ownershipKey);
|
||||
if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("This graph is read-only because it is not Studio-owned; create a new Jigsaw Studio project before editing pools");
|
||||
}
|
||||
byte[] manifestContent = Files.readAllBytes(manifestPath);
|
||||
String expectedManifestHash = StructureHash.sha256(manifestContent);
|
||||
StructureOwnershipManifest manifest = JigsawStudioAuthoringAccess.requireEditable(
|
||||
StructureOwnershipManifest.fromJson(manifestContent));
|
||||
String normalizedPool = JigsawStudioProjectCreator.Options.requireResourceKey(poolKey);
|
||||
String targetResource = "jigsaw-pools/" + normalizedPool + ".json";
|
||||
Path targetPath = root.resolve(targetResource).normalize();
|
||||
if (!manifest.resourceHashes().containsKey(targetResource)) {
|
||||
return new PoolUpdate(false, 0, targetPath, null);
|
||||
}
|
||||
|
||||
StructureResourceBundle.Builder bundle = StructureResourceBundle.builder(manifest.structure())
|
||||
.source(manifest.source())
|
||||
.backend(manifest.backend())
|
||||
.capabilities(manifest.capabilities())
|
||||
.losses(manifest.losses());
|
||||
int changedEntries = 0;
|
||||
for (Map.Entry<String, String> resource : manifest.resourceHashes().entrySet()) {
|
||||
Path resourcePath = resolveOwnedResource(root, resource.getKey());
|
||||
byte[] content = Files.readAllBytes(resourcePath);
|
||||
if (resource.getKey().equals(targetResource)) {
|
||||
PoolMutation mutation = editor.edit(content, resourcePath);
|
||||
changedEntries = mutation.changedEntries();
|
||||
content = mutation.content();
|
||||
}
|
||||
bundle.resource(resource.getKey(), content);
|
||||
}
|
||||
if (changedEntries == 0) {
|
||||
return new PoolUpdate(false, 0, targetPath, null);
|
||||
}
|
||||
StructureResourceBundle updatedBundle = bundle.build();
|
||||
StructureResourceBundleGraphCompiler.requireViable(updatedBundle);
|
||||
StructureWriteResult writeResult = writer.write(
|
||||
updatedBundle,
|
||||
StructureWriteOptions.overwriteExpected(expectedManifestHash));
|
||||
if (!writeResult.successful()) {
|
||||
String conflict = writeResult.conflicts().isEmpty()
|
||||
? writeResult.status().name()
|
||||
: writeResult.conflicts().getFirst().relativePath() + ": "
|
||||
+ writeResult.conflicts().getFirst().reason();
|
||||
throw new IOException("Atomic graph update was rejected: " + conflict);
|
||||
}
|
||||
return new PoolUpdate(true, changedEntries, targetPath, writeResult);
|
||||
}
|
||||
|
||||
private static Path resolveOwnedResource(Path root, String relativePath) throws IOException {
|
||||
StructureResourceBundle.validateRelativePath(relativePath);
|
||||
Path resource = root.resolve(relativePath).normalize();
|
||||
if (!resource.startsWith(root) || !Files.isRegularFile(resource, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Owned graph resource is missing or unsafe: " + relativePath);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
private static PoolMutation mutateWeight(
|
||||
byte[] content,
|
||||
String pieceKey,
|
||||
int weight,
|
||||
Path poolPath
|
||||
) throws IOException {
|
||||
JsonObject root = parsePool(content, poolPath);
|
||||
JsonArray pieces = root.getAsJsonArray("pieces");
|
||||
int changedEntries = 0;
|
||||
for (JsonElement element : pieces) {
|
||||
if (!isPiece(element, pieceKey)) {
|
||||
continue;
|
||||
}
|
||||
element.getAsJsonObject().addProperty("weight", weight);
|
||||
changedEntries++;
|
||||
}
|
||||
return mutation(root, changedEntries);
|
||||
}
|
||||
|
||||
private static PoolMutation mutateWeightAtIndex(
|
||||
byte[] content,
|
||||
int entryIndex,
|
||||
String expectedPieceKey,
|
||||
int weight,
|
||||
Path poolPath
|
||||
) throws IOException {
|
||||
JsonObject root = parsePool(content, poolPath);
|
||||
JsonArray pieces = root.getAsJsonArray("pieces");
|
||||
JsonObject entry = requirePieceEntry(pieces, entryIndex, expectedPieceKey, poolPath);
|
||||
int currentWeight = entry.has("weight") ? entry.get("weight").getAsInt() : 1;
|
||||
if (currentWeight == weight) {
|
||||
return mutation(root, 0);
|
||||
}
|
||||
entry.addProperty("weight", weight);
|
||||
return mutation(root, 1);
|
||||
}
|
||||
|
||||
private static PoolMutation mutateChanceAtIndex(
|
||||
byte[] content,
|
||||
int entryIndex,
|
||||
String expectedPieceKey,
|
||||
double chance,
|
||||
Path poolPath
|
||||
) throws IOException {
|
||||
JsonObject root = parsePool(content, poolPath);
|
||||
JsonArray pieces = root.getAsJsonArray("pieces");
|
||||
JsonObject entry = requirePieceEntry(pieces, entryIndex, expectedPieceKey, poolPath);
|
||||
double currentChance = entry.has("chance") ? entry.get("chance").getAsDouble() : 1D;
|
||||
if (Double.compare(currentChance, chance) == 0) {
|
||||
return mutation(root, 0);
|
||||
}
|
||||
entry.addProperty("chance", chance);
|
||||
return mutation(root, 1);
|
||||
}
|
||||
|
||||
private static PoolMutation mutateAdd(
|
||||
byte[] content,
|
||||
String pieceKey,
|
||||
int weight,
|
||||
Path poolPath
|
||||
) throws IOException {
|
||||
JsonObject root = parsePool(content, poolPath);
|
||||
JsonArray pieces = root.getAsJsonArray("pieces");
|
||||
for (JsonElement element : pieces) {
|
||||
if (isPiece(element, pieceKey)) {
|
||||
return mutation(root, 0);
|
||||
}
|
||||
}
|
||||
JsonObject entry = new JsonObject();
|
||||
entry.addProperty("piece", pieceKey);
|
||||
entry.addProperty("weight", weight);
|
||||
pieces.add(entry);
|
||||
return mutation(root, 1);
|
||||
}
|
||||
|
||||
private static PoolMutation mutateRemove(
|
||||
byte[] content,
|
||||
String pieceKey,
|
||||
Path poolPath
|
||||
) throws IOException {
|
||||
JsonObject root = parsePool(content, poolPath);
|
||||
JsonArray pieces = root.getAsJsonArray("pieces");
|
||||
int changedEntries = 0;
|
||||
for (int index = pieces.size() - 1; index >= 0; index--) {
|
||||
if (isPiece(pieces.get(index), pieceKey)) {
|
||||
pieces.remove(index);
|
||||
changedEntries++;
|
||||
}
|
||||
}
|
||||
return mutation(root, changedEntries);
|
||||
}
|
||||
|
||||
private static PoolMutation mutateRemoveAtIndex(
|
||||
byte[] content,
|
||||
int entryIndex,
|
||||
String expectedPieceKey,
|
||||
Path poolPath
|
||||
) throws IOException {
|
||||
JsonObject root = parsePool(content, poolPath);
|
||||
JsonArray pieces = root.getAsJsonArray("pieces");
|
||||
requirePieceEntry(pieces, entryIndex, expectedPieceKey, poolPath);
|
||||
pieces.remove(entryIndex);
|
||||
return mutation(root, 1);
|
||||
}
|
||||
|
||||
private static PoolMutation mutateFallback(
|
||||
byte[] content,
|
||||
String fallbackPoolKey,
|
||||
Path poolPath
|
||||
) throws IOException {
|
||||
JsonObject root = parsePool(content, poolPath);
|
||||
String existing = root.has("fallback") && !root.get("fallback").isJsonNull()
|
||||
? root.get("fallback").getAsString().trim()
|
||||
: "";
|
||||
if (existing.equals(fallbackPoolKey)) {
|
||||
return mutation(root, 0);
|
||||
}
|
||||
root.addProperty("fallback", fallbackPoolKey);
|
||||
return mutation(root, 1);
|
||||
}
|
||||
|
||||
private static JsonObject parsePool(byte[] content, Path poolPath) throws IOException {
|
||||
JsonElement parsed = JsonParser.parseString(new String(content, StandardCharsets.UTF_8));
|
||||
if (!parsed.isJsonObject()) {
|
||||
throw new IOException("Jigsaw pool is not a JSON object: " + poolPath);
|
||||
}
|
||||
JsonObject root = parsed.getAsJsonObject();
|
||||
if (!root.has("pieces") || !root.get("pieces").isJsonArray()) {
|
||||
throw new IOException("Jigsaw pool does not declare a pieces array: " + poolPath);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
private static boolean isPiece(JsonElement element, String pieceKey) {
|
||||
return element.isJsonObject()
|
||||
&& element.getAsJsonObject().has("piece")
|
||||
&& pieceKey.equals(element.getAsJsonObject().get("piece").getAsString());
|
||||
}
|
||||
|
||||
private static JsonObject requirePieceEntry(
|
||||
JsonArray pieces,
|
||||
int entryIndex,
|
||||
String expectedPieceKey,
|
||||
Path poolPath
|
||||
) throws IOException {
|
||||
if (entryIndex >= pieces.size()) {
|
||||
throw new IOException("Jigsaw pool entry " + entryIndex + " no longer exists in " + poolPath);
|
||||
}
|
||||
JsonElement element = pieces.get(entryIndex);
|
||||
if (!isPiece(element, expectedPieceKey)) {
|
||||
throw new IOException("Jigsaw pool entry " + entryIndex + " changed before the update in "
|
||||
+ poolPath);
|
||||
}
|
||||
return element.getAsJsonObject();
|
||||
}
|
||||
|
||||
private static PoolMutation mutation(JsonObject root, int changedEntries) {
|
||||
return new PoolMutation(
|
||||
(GSON.toJson(root) + "\n").getBytes(StandardCharsets.UTF_8),
|
||||
changedEntries);
|
||||
}
|
||||
|
||||
public record WeightUpdate(
|
||||
boolean changed,
|
||||
int changedEntries,
|
||||
Path poolPath,
|
||||
StructureWriteResult writeResult
|
||||
) {
|
||||
}
|
||||
|
||||
public record ChanceUpdate(
|
||||
boolean changed,
|
||||
int changedEntries,
|
||||
Path poolPath,
|
||||
StructureWriteResult writeResult
|
||||
) {
|
||||
}
|
||||
|
||||
public record PoolUpdate(
|
||||
boolean changed,
|
||||
int changedEntries,
|
||||
Path poolPath,
|
||||
StructureWriteResult writeResult
|
||||
) {
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface PoolContentEditor {
|
||||
PoolMutation edit(byte[] content, Path poolPath) throws IOException;
|
||||
}
|
||||
|
||||
private record PoolMutation(byte[] content, int changedEntries) {
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public record JigsawStudioPoolMembership(String poolKey, int entryIndex, int weight, double chance) {
|
||||
public JigsawStudioPoolMembership {
|
||||
Objects.requireNonNull(poolKey, "Jigsaw Studio pool key");
|
||||
poolKey = poolKey.trim();
|
||||
if (poolKey.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio pool key cannot be blank");
|
||||
}
|
||||
if (entryIndex < 0) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio pool entry index cannot be negative");
|
||||
}
|
||||
if (weight < 1) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio pool membership weight must be positive");
|
||||
}
|
||||
if (!Double.isFinite(chance) || chance < 0D || chance > 1D) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio pool membership chance must be within 0 and 1");
|
||||
}
|
||||
}
|
||||
}
|
||||
-294
@@ -1,294 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.core.structure.authoring.StructureBackend;
|
||||
import art.arcane.iris.core.structure.authoring.StructureCapability;
|
||||
import art.arcane.iris.core.structure.authoring.StructureKey;
|
||||
import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
|
||||
import art.arcane.iris.core.structure.authoring.StructureSource;
|
||||
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
|
||||
import art.arcane.iris.core.structure.authoring.StructureWriteMode;
|
||||
import art.arcane.iris.core.structure.authoring.StructureWriteResult;
|
||||
import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility;
|
||||
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.IrisJigsawMode;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell;
|
||||
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 com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class JigsawStudioProjectCreator {
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
private static final List<IrisDirection> SPATIAL_CONNECTOR_ORDER = List.of(
|
||||
IrisDirection.NORTH_NEGATIVE_Z,
|
||||
IrisDirection.SOUTH_POSITIVE_Z,
|
||||
IrisDirection.EAST_POSITIVE_X,
|
||||
IrisDirection.WEST_NEGATIVE_X,
|
||||
IrisDirection.UP_POSITIVE_Y,
|
||||
IrisDirection.DOWN_NEGATIVE_Y);
|
||||
|
||||
private JigsawStudioProjectCreator() {
|
||||
}
|
||||
|
||||
public static StructureWriteResult create(Path packRoot, Options options) throws IOException {
|
||||
Options activeOptions = Objects.requireNonNull(options, "Jigsaw Studio project options");
|
||||
StructureResourceBundle bundle = bundle(activeOptions);
|
||||
StructureResourceBundleGraphCompiler.requireViable(bundle);
|
||||
return new StructureTransactionWriter(packRoot).write(bundle, StructureWriteMode.ADD_ONLY);
|
||||
}
|
||||
|
||||
static StructureResourceBundle bundle(Options options) throws IOException {
|
||||
String resourceKey = options.structureKey();
|
||||
StructureKey ownershipKey = new StructureKey("iris", resourceKey);
|
||||
IrisStructure structure = new IrisStructure()
|
||||
.setStartPool(resourceKey + "/start")
|
||||
.setMaxDepth(7)
|
||||
.setMaxSizeChunks(8)
|
||||
.setMode(toModelMode(options.mode()))
|
||||
.setCompatibility(toModelCompatibility(options.compatibilityTarget()))
|
||||
.setBranchFailurePolicy(toBranchFailurePolicy(options.compatibilityTarget()))
|
||||
.setCellSize(new IrisPosition(
|
||||
options.cellDimensions().width(),
|
||||
options.cellDimensions().height(),
|
||||
options.cellDimensions().depth()));
|
||||
if (options.compatibilityTarget() == JigsawStudioCompatibilityTarget.IRIS_EXTENDED) {
|
||||
structure.getThemeSets().add(new IrisJigsawThemeSet("variant-1", 1));
|
||||
}
|
||||
StructureResourceBundle.Builder bundle = StructureResourceBundle.builder(ownershipKey)
|
||||
.source(StructureSource.of(StructureSource.Kind.IRIS, ownershipKey))
|
||||
.backend(StructureBackend.IRIS_ASSEMBLY)
|
||||
.capability(StructureCapability.BLOCKS)
|
||||
.capability(StructureCapability.CONNECTORS)
|
||||
.capability(StructureCapability.IRIS_PLACEMENT);
|
||||
IrisJigsawPool pool = new IrisJigsawPool();
|
||||
if (options.mode() == JigsawStudioMode.PLANAR_JIGSAW) {
|
||||
addPlanarDefaults(bundle, structure, pool, options);
|
||||
} else {
|
||||
addSpatialDefaults(bundle, pool, options);
|
||||
}
|
||||
bundle.textResource("jigsaw-pools/" + resourceKey + "/start.json", GSON.toJson(pool) + "\n");
|
||||
bundle.textResource("structures/" + resourceKey + ".json", GSON.toJson(structure) + "\n");
|
||||
return bundle.build();
|
||||
}
|
||||
|
||||
static byte[] serialize(IrisObject object) throws IOException {
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
object.write(output);
|
||||
return output.toByteArray();
|
||||
}
|
||||
|
||||
private static IrisJigsawMode toModelMode(JigsawStudioMode mode) {
|
||||
return mode == JigsawStudioMode.PLANAR_JIGSAW
|
||||
? IrisJigsawMode.PLANAR_JIGSAW
|
||||
: IrisJigsawMode.SPATIAL_JIGSAW;
|
||||
}
|
||||
|
||||
private static IrisJigsawCompatibility toModelCompatibility(
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget
|
||||
) {
|
||||
return compatibilityTarget == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE
|
||||
? IrisJigsawCompatibility.VANILLA_PORTABLE
|
||||
: IrisJigsawCompatibility.IRIS_EXTENDED;
|
||||
}
|
||||
|
||||
private static IrisJigsawBranchFailurePolicy toBranchFailurePolicy(
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget
|
||||
) {
|
||||
return compatibilityTarget == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE
|
||||
? IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH
|
||||
: IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY;
|
||||
}
|
||||
|
||||
private static void addPlanarDefaults(
|
||||
StructureResourceBundle.Builder bundle,
|
||||
IrisStructure structure,
|
||||
IrisJigsawPool pool,
|
||||
Options options
|
||||
) throws IOException {
|
||||
JigsawStudioCellDimensions dimensions = options.cellDimensions();
|
||||
IrisPosition size = new IrisPosition(dimensions.width(), dimensions.height(), dimensions.depth());
|
||||
String piecePoolKey = options.structureKey() + "/pieces";
|
||||
String capPoolKey = options.structureKey() + "/caps";
|
||||
IrisJigsawPool piecePool = new IrisJigsawPool().setFallback(capPoolKey);
|
||||
IrisJigsawPool capPool = new IrisJigsawPool();
|
||||
for (JigsawPlanarArchetype archetype : JigsawPlanarArchetype.values()) {
|
||||
String key = options.structureKey() + "/" + archetype.name().toLowerCase(Locale.ROOT);
|
||||
IrisJigsawPiece piece = planarPiece(key, piecePoolKey, size, archetype);
|
||||
if (options.compatibilityTarget() == JigsawStudioCompatibilityTarget.IRIS_EXTENDED) {
|
||||
piece.getThemes().add("variant-1");
|
||||
}
|
||||
if (archetype == JigsawPlanarArchetype.CROSS) {
|
||||
pool.getPieces().add(new IrisJigsawPieceEntry(key, 1));
|
||||
}
|
||||
if (archetype != JigsawPlanarArchetype.BLANK) {
|
||||
piecePool.getPieces().add(new IrisJigsawPieceEntry(key, 1));
|
||||
}
|
||||
if (archetype == JigsawPlanarArchetype.END) {
|
||||
if (options.compatibilityTarget() == JigsawStudioCompatibilityTarget.IRIS_EXTENDED) {
|
||||
piece.setRules(new IrisJigsawPieceRules().setTerminal(true));
|
||||
}
|
||||
capPool.getPieces().add(new IrisJigsawPieceEntry(key, 1));
|
||||
}
|
||||
structure.getPlanarWorkcells().add(new IrisJigsawWorkcell(
|
||||
"",
|
||||
archetype.modelArchetype(),
|
||||
dimensions.width(),
|
||||
dimensions.height(),
|
||||
dimensions.depth(),
|
||||
true));
|
||||
bundle.resource("objects/" + key + ".iob", serialize(new IrisObject(
|
||||
dimensions.width(),
|
||||
dimensions.height(),
|
||||
dimensions.depth())));
|
||||
bundle.textResource("jigsaw-pieces/" + key + ".json", GSON.toJson(piece) + "\n");
|
||||
}
|
||||
capPool.getPieces().add(new IrisJigsawPieceEntry().setEmpty(true));
|
||||
bundle.textResource("jigsaw-pools/" + piecePoolKey + ".json", GSON.toJson(piecePool) + "\n");
|
||||
bundle.textResource("jigsaw-pools/" + capPoolKey + ".json", GSON.toJson(capPool) + "\n");
|
||||
}
|
||||
|
||||
private static void addSpatialDefaults(
|
||||
StructureResourceBundle.Builder bundle,
|
||||
IrisJigsawPool pool,
|
||||
Options options
|
||||
) throws IOException {
|
||||
JigsawStudioCellDimensions dimensions = options.cellDimensions();
|
||||
String piecePoolKey = options.structureKey() + "/pieces";
|
||||
IrisJigsawPool piecePool = new IrisJigsawPool();
|
||||
for (int connectorCount = 0; connectorCount <= SPATIAL_CONNECTOR_ORDER.size(); connectorCount++) {
|
||||
String key = options.structureKey() + "/"
|
||||
+ (connectorCount == 0 ? "start" : "connectors-" + connectorCount);
|
||||
IrisJigsawPiece piece = spatialPiece(
|
||||
key,
|
||||
piecePoolKey,
|
||||
dimensions,
|
||||
connectorCount);
|
||||
if (options.compatibilityTarget() == JigsawStudioCompatibilityTarget.IRIS_EXTENDED) {
|
||||
piece.getThemes().add("variant-1");
|
||||
}
|
||||
pool.getPieces().add(new IrisJigsawPieceEntry(key, 1));
|
||||
if (connectorCount > 0) {
|
||||
piecePool.getPieces().add(new IrisJigsawPieceEntry(key, 1));
|
||||
}
|
||||
bundle.resource("objects/" + key + ".iob", serialize(new IrisObject(
|
||||
dimensions.width(),
|
||||
dimensions.height(),
|
||||
dimensions.depth())));
|
||||
bundle.textResource("jigsaw-pieces/" + key + ".json", GSON.toJson(piece) + "\n");
|
||||
}
|
||||
piecePool.getPieces().add(new IrisJigsawPieceEntry().setEmpty(true));
|
||||
bundle.textResource("jigsaw-pools/" + piecePoolKey + ".json", GSON.toJson(piecePool) + "\n");
|
||||
}
|
||||
|
||||
private static IrisJigsawPiece spatialPiece(
|
||||
String objectKey,
|
||||
String poolKey,
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
int connectorCount
|
||||
) {
|
||||
IrisJigsawPiece piece = new IrisJigsawPiece()
|
||||
.setDisplayName(connectorCount + (connectorCount == 1 ? " Connector" : " Connectors"))
|
||||
.setObject(objectKey)
|
||||
.setRotatable(true)
|
||||
.setRules(new IrisJigsawPieceRules().setMaximumPlacements(16));
|
||||
for (int index = 0; index < connectorCount; index++) {
|
||||
IrisDirection direction = SPATIAL_CONNECTOR_ORDER.get(index);
|
||||
piece.getConnectors().add(new IrisJigsawConnector()
|
||||
.setPosition(spatialConnectorPosition(dimensions, direction))
|
||||
.setDirection(direction)
|
||||
.setTop(direction.isVertical()
|
||||
? IrisDirection.NORTH_NEGATIVE_Z
|
||||
: IrisDirection.UP_POSITIVE_Y)
|
||||
.setPool(poolKey)
|
||||
.setName("iris:spatial")
|
||||
.setTargetName("iris:spatial")
|
||||
.setJoint(JigsawJoint.ROLLABLE)
|
||||
.setFinalState("minecraft:structure_void"));
|
||||
}
|
||||
return piece;
|
||||
}
|
||||
|
||||
private static IrisPosition spatialConnectorPosition(
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
IrisDirection direction
|
||||
) {
|
||||
int centerX = dimensions.width() / 2;
|
||||
int centerY = dimensions.height() / 2;
|
||||
int centerZ = dimensions.depth() / 2;
|
||||
return switch (direction) {
|
||||
case NORTH_NEGATIVE_Z -> new IrisPosition(centerX, centerY, 0);
|
||||
case SOUTH_POSITIVE_Z -> new IrisPosition(centerX, centerY, dimensions.depth() - 1);
|
||||
case EAST_POSITIVE_X -> new IrisPosition(dimensions.width() - 1, centerY, centerZ);
|
||||
case WEST_NEGATIVE_X -> new IrisPosition(0, centerY, centerZ);
|
||||
case UP_POSITIVE_Y -> new IrisPosition(centerX, dimensions.height() - 1, centerZ);
|
||||
case DOWN_NEGATIVE_Y -> new IrisPosition(centerX, 0, centerZ);
|
||||
};
|
||||
}
|
||||
|
||||
private static IrisJigsawPiece planarPiece(
|
||||
String objectKey,
|
||||
String poolKey,
|
||||
IrisPosition dimensions,
|
||||
JigsawPlanarArchetype archetype
|
||||
) {
|
||||
IrisJigsawPiece piece = new IrisJigsawPiece().setObject(objectKey).setRotatable(true);
|
||||
for (JigsawPlanarDirection planarDirection : archetype.canonicalTopology().directions()) {
|
||||
IrisDirection direction = planarDirection.irisDirection();
|
||||
piece.getConnectors().add(new IrisJigsawConnector()
|
||||
.setPosition(IrisJigsawConnector.canonicalPlanarPosition(dimensions, direction))
|
||||
.setDirection(direction)
|
||||
.setTop(IrisDirection.UP_POSITIVE_Y)
|
||||
.setPool(poolKey)
|
||||
.setName("iris:planar")
|
||||
.setTargetName("iris:planar")
|
||||
.setJoint(JigsawJoint.ALIGNED)
|
||||
.setFinalState("minecraft:structure_void"));
|
||||
}
|
||||
return piece;
|
||||
}
|
||||
|
||||
public record Options(
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions
|
||||
) {
|
||||
public Options {
|
||||
structureKey = requireResourceKey(structureKey);
|
||||
mode = Objects.requireNonNull(mode, "Jigsaw Studio mode");
|
||||
compatibilityTarget = Objects.requireNonNull(
|
||||
compatibilityTarget,
|
||||
"Jigsaw Studio compatibility target");
|
||||
cellDimensions = Objects.requireNonNull(cellDimensions, "Jigsaw Studio cell dimensions");
|
||||
if (mode == JigsawStudioMode.PLANAR_JIGSAW
|
||||
&& (cellDimensions.width() < 3 || cellDimensions.depth() < 3)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Planar Jigsaw Studio cells require width and depth of at least 3 blocks");
|
||||
}
|
||||
}
|
||||
|
||||
static String requireResourceKey(String value) {
|
||||
String key = JigsawStudioMarkerKeyCodec.requireInternalPath(value, "resource");
|
||||
StructureResourceBundle.validateRelativePath("structures/" + key + ".json");
|
||||
new StructureKey("iris", key);
|
||||
return key;
|
||||
}
|
||||
}
|
||||
}
|
||||
-435
@@ -1,435 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
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.StructureResourceBundle;
|
||||
import art.arcane.iris.core.structure.authoring.StructureSource;
|
||||
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public final class JigsawStudioProjectDeletionService {
|
||||
private static final long MAX_JSON_BYTES = 16L * 1024L * 1024L;
|
||||
private static final int MAX_SCANNED_FILES = 100_000;
|
||||
|
||||
private JigsawStudioProjectDeletionService() {
|
||||
}
|
||||
|
||||
public static DeletionPlan inspect(Path packRoot, String structureKey) throws IOException {
|
||||
Path root = canonicalRoot(packRoot);
|
||||
StructureKey key = StructureKey.parse(structureKey, "iris");
|
||||
ManifestSnapshot snapshot = loadSnapshot(root, key);
|
||||
List<ReverseReference> blockers = scanReverseReferences(root, snapshot);
|
||||
return new DeletionPlan(
|
||||
UUID.randomUUID(),
|
||||
root,
|
||||
key,
|
||||
snapshot.manifest().source(),
|
||||
snapshot.manifestHash(),
|
||||
snapshot.sourceHash(),
|
||||
snapshot.manifest().resourceHashes(),
|
||||
blockers);
|
||||
}
|
||||
|
||||
public static ProjectDeletionResult delete(DeletionPlan plan) throws IOException {
|
||||
DeletionPlan expected = Objects.requireNonNull(plan, "Jigsaw Studio project deletion plan");
|
||||
if (!expected.deletable()) {
|
||||
throw new IOException("Jigsaw Studio project deletion is blocked by "
|
||||
+ expected.blockers().size() + " reverse references");
|
||||
}
|
||||
Path root = canonicalRoot(expected.packRoot());
|
||||
StructureTransactionWriter writer = new StructureTransactionWriter(root);
|
||||
StructureTransactionWriter.OwnedRemoval request = new StructureTransactionWriter.OwnedRemoval(
|
||||
expected.structureKey(),
|
||||
expected.expectedSource().kind(),
|
||||
expected.expectedSource().key(),
|
||||
Optional.empty(),
|
||||
Optional.of(expected.expectedManifestHash()));
|
||||
try (StructureTransactionWriter.PreparedRemoval removal = writer.prepareOwnedRemovals(
|
||||
List.of(request),
|
||||
() -> validateDeletion(root, expected))) {
|
||||
if (!removal.changed()) {
|
||||
throw new IOException("Jigsaw Studio project no longer exists");
|
||||
}
|
||||
removal.markCommitted();
|
||||
removal.finishCommit();
|
||||
}
|
||||
return new ProjectDeletionResult(
|
||||
expected.planId(),
|
||||
expected.structureKey(),
|
||||
expected.expectedResourceHashes().size(),
|
||||
true);
|
||||
}
|
||||
|
||||
private static void validateDeletion(Path root, DeletionPlan expected) throws IOException {
|
||||
ManifestSnapshot current = loadSnapshot(root, expected.structureKey());
|
||||
if (!expected.expectedManifestHash().equals(current.manifestHash())) {
|
||||
throw new IOException("Jigsaw Studio project changed after deletion was inspected");
|
||||
}
|
||||
if (!expected.expectedSource().equals(current.manifest().source())
|
||||
|| !expected.expectedSourceHash().equals(current.sourceHash())) {
|
||||
throw new IOException("Jigsaw Studio project source changed after deletion was inspected");
|
||||
}
|
||||
if (!expected.expectedResourceHashes().equals(current.manifest().resourceHashes())) {
|
||||
throw new IOException("Jigsaw Studio project resources changed after deletion was inspected");
|
||||
}
|
||||
List<ReverseReference> currentBlockers = scanReverseReferences(root, current);
|
||||
if (!currentBlockers.isEmpty()) {
|
||||
throw new IOException("Jigsaw Studio project gained " + currentBlockers.size()
|
||||
+ " reverse references after deletion was inspected");
|
||||
}
|
||||
}
|
||||
|
||||
private static Path canonicalRoot(Path packRoot) throws IOException {
|
||||
Path normalized = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
Path resolved;
|
||||
try {
|
||||
resolved = normalized.toRealPath();
|
||||
} catch (IOException exception) {
|
||||
throw new IOException("Cannot resolve Jigsaw Studio pack root " + normalized, exception);
|
||||
}
|
||||
if (!Files.isDirectory(resolved, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Jigsaw Studio pack root is not a directory: " + resolved);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private static ManifestSnapshot loadSnapshot(Path root, StructureKey key) throws IOException {
|
||||
StructureTransactionWriter writer = new StructureTransactionWriter(root);
|
||||
Path manifestPath = writer.ownershipManifestPath(key);
|
||||
if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("This graph is read-only because it is not Studio-owned; only Studio-owned projects can be deleted");
|
||||
}
|
||||
byte[] manifestContent = readBoundedJson(manifestPath, "Jigsaw Studio ownership manifest");
|
||||
StructureOwnershipManifest manifest;
|
||||
try {
|
||||
manifest = JigsawStudioAuthoringAccess.requireEditable(
|
||||
StructureOwnershipManifest.fromJson(manifestContent));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IOException("Invalid Jigsaw Studio ownership manifest at " + manifestPath, exception);
|
||||
}
|
||||
if (!manifest.structure().equals(key)) {
|
||||
throw new IOException("Jigsaw Studio ownership manifest belongs to " + manifest.structure());
|
||||
}
|
||||
String structureResource = "structures/" + manifest.structure().path() + ".json";
|
||||
String structureHash = manifest.resourceHashes().get(structureResource);
|
||||
if (structureHash == null) {
|
||||
throw new IOException("Jigsaw Studio ownership manifest does not include " + structureResource);
|
||||
}
|
||||
for (Map.Entry<String, String> resource : manifest.resourceHashes().entrySet()) {
|
||||
Path resourcePath = resolveOwnedResource(root, resource.getKey());
|
||||
String actualHash;
|
||||
try (InputStream input = Files.newInputStream(resourcePath)) {
|
||||
actualHash = StructureHash.sha256(input);
|
||||
}
|
||||
if (!resource.getValue().equals(actualHash)) {
|
||||
throw new IOException("Owned graph resource changed outside Studio: " + resource.getKey());
|
||||
}
|
||||
}
|
||||
String sourceHash = manifest.source().contentHash().isEmpty()
|
||||
? structureHash
|
||||
: manifest.source().contentHash();
|
||||
return new ManifestSnapshot(
|
||||
manifest,
|
||||
StructureHash.sha256(manifestContent),
|
||||
sourceHash,
|
||||
manifestPath);
|
||||
}
|
||||
|
||||
private static Path resolveOwnedResource(Path root, String relativePath) throws IOException {
|
||||
StructureResourceBundle.validateRelativePath(relativePath);
|
||||
Path resource = root.resolve(relativePath).normalize();
|
||||
if (!resource.startsWith(root)
|
||||
|| !Files.isRegularFile(resource, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Owned graph resource is missing or unsafe: " + relativePath);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
private static List<ReverseReference> scanReverseReferences(
|
||||
Path root,
|
||||
ManifestSnapshot snapshot
|
||||
) throws IOException {
|
||||
Map<String, Set<String>> targetsByKey = referenceTargets(snapshot.manifest());
|
||||
Set<String> ownedPaths = snapshot.manifest().resourceHashes().keySet();
|
||||
Set<ReverseReference> references = new LinkedHashSet<>();
|
||||
int scannedFiles = 0;
|
||||
try (Stream<Path> paths = Files.walk(root)) {
|
||||
Iterator<Path> iterator = paths.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Path path = iterator.next();
|
||||
Path relative = root.relativize(path);
|
||||
String relativePath = relative.toString().replace(path.getFileSystem().getSeparator(), "/");
|
||||
if (relativePath.isEmpty() || relativePath.startsWith(".iris/")) {
|
||||
continue;
|
||||
}
|
||||
if (Files.isSymbolicLink(path)) {
|
||||
if (relativePath.endsWith(".json") || Files.isDirectory(path)) {
|
||||
throw new IOException("Cannot prove deletion safety through symbolic pack path "
|
||||
+ relativePath);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!relativePath.endsWith(".json") || ownedPaths.contains(relativePath)) {
|
||||
continue;
|
||||
}
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
|
||||
continue;
|
||||
}
|
||||
scannedFiles++;
|
||||
if (scannedFiles > MAX_SCANNED_FILES) {
|
||||
throw new IOException("Jigsaw Studio project deletion scan exceeds "
|
||||
+ MAX_SCANNED_FILES + " JSON resources");
|
||||
}
|
||||
JsonElement json = parseBoundedJson(path, relativePath);
|
||||
collectReferences(json, "$", relativePath, targetsByKey, references);
|
||||
}
|
||||
}
|
||||
scanOwnershipManifests(root, snapshot, references);
|
||||
List<ReverseReference> ordered = new ArrayList<>(references);
|
||||
ordered.sort(Comparator.comparing(ReverseReference::ownerPath)
|
||||
.thenComparing(ReverseReference::location)
|
||||
.thenComparing(ReverseReference::targetResourcePath));
|
||||
return List.copyOf(ordered);
|
||||
}
|
||||
|
||||
private static Map<String, Set<String>> referenceTargets(StructureOwnershipManifest manifest) {
|
||||
Map<String, Set<String>> targets = new LinkedHashMap<>();
|
||||
addReferenceTarget(targets, manifest.structure().path(),
|
||||
"structures/" + manifest.structure().path() + ".json");
|
||||
addReferenceTarget(targets, manifest.structure().value(),
|
||||
"structures/" + manifest.structure().path() + ".json");
|
||||
for (String relativePath : manifest.resourceHashes().keySet()) {
|
||||
addResourceReferenceTarget(targets, relativePath, "jigsaw-pools/", ".json");
|
||||
addResourceReferenceTarget(targets, relativePath, "jigsaw-pieces/", ".json");
|
||||
addResourceReferenceTarget(targets, relativePath, "objects/", ".iob");
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
private static void addResourceReferenceTarget(
|
||||
Map<String, Set<String>> targets,
|
||||
String relativePath,
|
||||
String prefix,
|
||||
String suffix
|
||||
) {
|
||||
if (!relativePath.startsWith(prefix) || !relativePath.endsWith(suffix)) {
|
||||
return;
|
||||
}
|
||||
String key = relativePath.substring(prefix.length(), relativePath.length() - suffix.length());
|
||||
addReferenceTarget(targets, key, relativePath);
|
||||
addReferenceTarget(targets, "iris:" + key, relativePath);
|
||||
}
|
||||
|
||||
private static void addReferenceTarget(
|
||||
Map<String, Set<String>> targets,
|
||||
String key,
|
||||
String relativePath
|
||||
) {
|
||||
targets.computeIfAbsent(key, ignored -> new LinkedHashSet<>()).add(relativePath);
|
||||
}
|
||||
|
||||
private static void collectReferences(
|
||||
JsonElement element,
|
||||
String location,
|
||||
String ownerPath,
|
||||
Map<String, Set<String>> targetsByKey,
|
||||
Set<ReverseReference> references
|
||||
) {
|
||||
if (element == null || element.isJsonNull()) {
|
||||
return;
|
||||
}
|
||||
if (element.isJsonPrimitive() && element.getAsJsonPrimitive().isString()) {
|
||||
Set<String> targets = targetsByKey.get(element.getAsString());
|
||||
if (targets != null) {
|
||||
for (String target : targets) {
|
||||
references.add(new ReverseReference(ownerPath, location, target));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (element.isJsonArray()) {
|
||||
JsonArray array = element.getAsJsonArray();
|
||||
for (int index = 0; index < array.size(); index++) {
|
||||
collectReferences(
|
||||
array.get(index),
|
||||
location + "[" + index + "]",
|
||||
ownerPath,
|
||||
targetsByKey,
|
||||
references);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (element.isJsonObject()) {
|
||||
JsonObject object = element.getAsJsonObject();
|
||||
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
|
||||
collectReferences(
|
||||
entry.getValue(),
|
||||
location + "." + entry.getKey(),
|
||||
ownerPath,
|
||||
targetsByKey,
|
||||
references);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void scanOwnershipManifests(
|
||||
Path root,
|
||||
ManifestSnapshot target,
|
||||
Set<ReverseReference> references
|
||||
) throws IOException {
|
||||
Path manifestRoot = root.resolve(".iris/structure-manifests");
|
||||
if (!Files.isDirectory(manifestRoot, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return;
|
||||
}
|
||||
try (Stream<Path> paths = Files.list(manifestRoot)) {
|
||||
Iterator<Path> iterator = paths.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Path path = iterator.next();
|
||||
if (Files.isSameFile(path, target.manifestPath())
|
||||
|| !path.getFileName().toString().endsWith(".json")) {
|
||||
continue;
|
||||
}
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Cannot prove deletion safety through ownership manifest " + path);
|
||||
}
|
||||
StructureOwnershipManifest manifest;
|
||||
try {
|
||||
manifest = StructureOwnershipManifest.fromJson(
|
||||
readBoundedJson(path, "Structure ownership manifest"));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IOException("Invalid structure ownership manifest at " + path, exception);
|
||||
}
|
||||
for (String relativePath : target.manifest().resourceHashes().keySet()) {
|
||||
if (manifest.resourceHashes().containsKey(relativePath)) {
|
||||
references.add(new ReverseReference(
|
||||
root.relativize(path).toString().replace(path.getFileSystem().getSeparator(), "/"),
|
||||
"$.resourceHashes",
|
||||
relativePath));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonElement parseBoundedJson(Path path, String relativePath) throws IOException {
|
||||
byte[] content = readBoundedJson(path, "JSON resource");
|
||||
try {
|
||||
return JsonParser.parseString(new String(content, StandardCharsets.UTF_8));
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IOException("Cannot prove deletion safety through invalid JSON resource "
|
||||
+ relativePath, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] readBoundedJson(Path path, String kind) throws IOException {
|
||||
long size = Files.size(path);
|
||||
if (size > MAX_JSON_BYTES) {
|
||||
throw new IOException(kind + " exceeds " + MAX_JSON_BYTES + " bytes: " + path);
|
||||
}
|
||||
return Files.readAllBytes(path);
|
||||
}
|
||||
|
||||
public record DeletionPlan(
|
||||
UUID planId,
|
||||
Path packRoot,
|
||||
StructureKey structureKey,
|
||||
StructureSource expectedSource,
|
||||
String expectedManifestHash,
|
||||
String expectedSourceHash,
|
||||
Map<String, String> expectedResourceHashes,
|
||||
List<ReverseReference> blockers
|
||||
) {
|
||||
public DeletionPlan {
|
||||
Objects.requireNonNull(planId, "Jigsaw Studio project deletion plan ID");
|
||||
packRoot = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
Objects.requireNonNull(structureKey, "Jigsaw Studio project deletion structure key");
|
||||
Objects.requireNonNull(expectedSource, "Jigsaw Studio project deletion source");
|
||||
if (!StructureHash.isSha256(expectedManifestHash)) {
|
||||
throw new IllegalArgumentException("Expected Jigsaw Studio ownership manifest hash must be SHA-256");
|
||||
}
|
||||
if (!StructureHash.isSha256(expectedSourceHash)) {
|
||||
throw new IllegalArgumentException("Expected Jigsaw Studio source hash must be SHA-256");
|
||||
}
|
||||
Objects.requireNonNull(expectedResourceHashes, "Jigsaw Studio project deletion resources");
|
||||
expectedResourceHashes = Collections.unmodifiableMap(new TreeMap<>(expectedResourceHashes));
|
||||
blockers = List.copyOf(Objects.requireNonNull(
|
||||
blockers,
|
||||
"Jigsaw Studio project deletion blockers"));
|
||||
}
|
||||
|
||||
public boolean deletable() {
|
||||
return blockers.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
public record ReverseReference(
|
||||
String ownerPath,
|
||||
String location,
|
||||
String targetResourcePath
|
||||
) {
|
||||
public ReverseReference {
|
||||
ownerPath = requireNonBlank(ownerPath, "reverse-reference owner path");
|
||||
location = requireNonBlank(location, "reverse-reference location");
|
||||
targetResourcePath = StructureResourceBundle.validateRelativePath(targetResourcePath);
|
||||
}
|
||||
}
|
||||
|
||||
public record ProjectDeletionResult(
|
||||
UUID planId,
|
||||
StructureKey structureKey,
|
||||
int removedResourceCount,
|
||||
boolean manifestRemoved
|
||||
) {
|
||||
public ProjectDeletionResult {
|
||||
Objects.requireNonNull(planId, "Jigsaw Studio project deletion plan ID");
|
||||
Objects.requireNonNull(structureKey, "Deleted Jigsaw Studio structure key");
|
||||
if (removedResourceCount < 0) {
|
||||
throw new IllegalArgumentException("Removed Jigsaw Studio resource count cannot be negative");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String requireNonBlank(String value, String name) {
|
||||
Objects.requireNonNull(value, name);
|
||||
String normalized = value.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException(name + " cannot be blank");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private record ManifestSnapshot(
|
||||
StructureOwnershipManifest manifest,
|
||||
String manifestHash,
|
||||
String sourceHash,
|
||||
Path manifestPath
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -1,689 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class JigsawStudioSession {
|
||||
private final UUID sessionId;
|
||||
private final String packKey;
|
||||
private final String structureKey;
|
||||
private final Map<String, MutableWorkcellState> workcells = new LinkedHashMap<>();
|
||||
private JigsawStudioLayout layout;
|
||||
private String selectedBayId;
|
||||
private long nextLoadGeneration;
|
||||
private long nextMutationGeneration;
|
||||
private long nextOperationGeneration;
|
||||
private long revision;
|
||||
|
||||
public JigsawStudioSession(String packKey, String structureKey, JigsawStudioLayout layout) {
|
||||
this(UUID.randomUUID(), packKey, structureKey, layout);
|
||||
}
|
||||
|
||||
public JigsawStudioSession(
|
||||
UUID sessionId,
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioLayout layout
|
||||
) {
|
||||
this.sessionId = Objects.requireNonNull(sessionId, "Jigsaw Studio session ID");
|
||||
this.packKey = requireKey(packKey, "pack");
|
||||
this.structureKey = requireKey(structureKey, "structure");
|
||||
this.layout = Objects.requireNonNull(layout, "Jigsaw Studio session layout");
|
||||
initializeWorkcells(layout);
|
||||
}
|
||||
|
||||
public synchronized UUID sessionId() {
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
public synchronized String packKey() {
|
||||
return packKey;
|
||||
}
|
||||
|
||||
public synchronized String structureKey() {
|
||||
return structureKey;
|
||||
}
|
||||
|
||||
public synchronized JigsawStudioLayout layout() {
|
||||
return layout;
|
||||
}
|
||||
|
||||
public synchronized Optional<String> selectedBayId() {
|
||||
return Optional.ofNullable(selectedBayId);
|
||||
}
|
||||
|
||||
public synchronized boolean selectBay(String stableId) {
|
||||
Objects.requireNonNull(stableId, "Jigsaw Studio selected workcell ID");
|
||||
if (layout.get(stableId) == null) {
|
||||
return false;
|
||||
}
|
||||
selectedBayId = stableId;
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized void clearSelection() {
|
||||
selectedBayId = null;
|
||||
}
|
||||
|
||||
public synchronized Optional<JigsawStudioVariant> activeVariant(String workcellId) {
|
||||
MutableWorkcellState state = workcells.get(workcellId);
|
||||
if (state == null || state.activeVariantKey.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return layout.variantCatalog().find(state.activeVariantKey);
|
||||
}
|
||||
|
||||
public synchronized WorkcellSnapshot workcellSnapshot(String workcellId) {
|
||||
MutableWorkcellState state = requireWorkcellState(workcellId);
|
||||
return state.snapshot(workcellId);
|
||||
}
|
||||
|
||||
public synchronized boolean setConnectorsVisible(String workcellId, boolean visible) {
|
||||
MutableWorkcellState state = requireWorkcellState(workcellId);
|
||||
if (state.connectorsVisible == visible) {
|
||||
return false;
|
||||
}
|
||||
state.connectorsVisible = visible;
|
||||
revision++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized boolean replaceLayout(JigsawStudioLayout replacement) {
|
||||
JigsawStudioLayout nextLayout = Objects.requireNonNull(replacement, "Replacement Jigsaw Studio layout");
|
||||
if (layout.mode() != nextLayout.mode()) {
|
||||
throw new IllegalArgumentException("Replacement Jigsaw Studio layout mode does not match the session");
|
||||
}
|
||||
if (operationInProgress()) {
|
||||
throw new IllegalStateException("Jigsaw Studio layout cannot change during a save or variant switch");
|
||||
}
|
||||
if (layout == nextLayout) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Map<String, MutableWorkcellState> updated = new LinkedHashMap<>();
|
||||
for (JigsawStudioBay workcell : nextLayout.bays()) {
|
||||
MutableWorkcellState previous = workcells.get(workcell.stableId());
|
||||
String activeVariantKey = retainedVariantKey(nextLayout, workcell, previous);
|
||||
if (previous != null && previous.activeVariantKey.equals(activeVariantKey)) {
|
||||
updated.put(workcell.stableId(), previous.copy());
|
||||
continue;
|
||||
}
|
||||
updated.put(workcell.stableId(), new MutableWorkcellState(
|
||||
activeVariantKey,
|
||||
nextLoadGeneration(),
|
||||
nextMutationGeneration(),
|
||||
false,
|
||||
previous != null && previous.connectorsVisible));
|
||||
}
|
||||
layout = nextLayout;
|
||||
workcells.clear();
|
||||
workcells.putAll(updated);
|
||||
if (selectedBayId != null && layout.get(selectedBayId) == null) {
|
||||
selectedBayId = null;
|
||||
}
|
||||
revision++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized boolean replaceLayoutAndRebind(
|
||||
JigsawStudioLayout replacement,
|
||||
Map<String, String> activeVariantsByWorkcell
|
||||
) {
|
||||
JigsawStudioLayout nextLayout = Objects.requireNonNull(replacement, "Replacement Jigsaw Studio layout");
|
||||
Map<String, String> bindings = Map.copyOf(Objects.requireNonNull(
|
||||
activeVariantsByWorkcell,
|
||||
"Replacement Jigsaw Studio active variants"));
|
||||
if (layout.mode() != nextLayout.mode()) {
|
||||
throw new IllegalArgumentException("Replacement Jigsaw Studio layout mode does not match the session");
|
||||
}
|
||||
if (operationInProgress()) {
|
||||
throw new IllegalStateException("Jigsaw Studio layout cannot change during a save or variant switch");
|
||||
}
|
||||
for (Map.Entry<String, String> binding : bindings.entrySet()) {
|
||||
JigsawStudioBay workcell = nextLayout.get(binding.getKey());
|
||||
JigsawStudioVariant variant = nextLayout.variantCatalog().find(binding.getValue())
|
||||
.orElseThrow(() -> new IllegalArgumentException(
|
||||
"Unknown replacement Jigsaw Studio variant " + binding.getValue()));
|
||||
if (workcell == null || !nextLayout.accepts(workcell, variant)) {
|
||||
throw new IllegalArgumentException("Replacement Jigsaw Studio variant " + binding.getValue()
|
||||
+ " does not belong to workcell " + binding.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, MutableWorkcellState> updated = new LinkedHashMap<>();
|
||||
boolean changed = layout != nextLayout;
|
||||
for (JigsawStudioBay workcell : nextLayout.bays()) {
|
||||
MutableWorkcellState previous = workcells.get(workcell.stableId());
|
||||
String targetVariantKey = bindings.get(workcell.stableId());
|
||||
if (targetVariantKey == null) {
|
||||
targetVariantKey = retainedVariantKey(nextLayout, workcell, previous);
|
||||
}
|
||||
if (previous != null && previous.activeVariantKey.equals(targetVariantKey)) {
|
||||
updated.put(workcell.stableId(), previous.copy());
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
updated.put(workcell.stableId(), new MutableWorkcellState(
|
||||
targetVariantKey,
|
||||
nextLoadGeneration(),
|
||||
nextMutationGeneration(),
|
||||
false,
|
||||
previous != null && previous.connectorsVisible));
|
||||
}
|
||||
layout = nextLayout;
|
||||
workcells.clear();
|
||||
workcells.putAll(updated);
|
||||
if (selectedBayId != null && layout.get(selectedBayId) == null) {
|
||||
selectedBayId = null;
|
||||
}
|
||||
if (changed) {
|
||||
revision++;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
public synchronized SwitchStart beginVariantSwitch(
|
||||
String workcellId,
|
||||
String targetPieceKey,
|
||||
boolean discardDirty
|
||||
) {
|
||||
return beginVariantTransition(workcellId, targetPieceKey, discardDirty, false);
|
||||
}
|
||||
|
||||
public synchronized SwitchStart beginVariantReload(String workcellId) {
|
||||
MutableWorkcellState state = workcells.get(workcellId);
|
||||
if (state == null) {
|
||||
return SwitchStart.failure(SwitchStatus.UNKNOWN_WORKCELL);
|
||||
}
|
||||
if (state.activeVariantKey.isEmpty()) {
|
||||
return SwitchStart.failure(SwitchStatus.UNKNOWN_VARIANT);
|
||||
}
|
||||
return beginVariantTransition(workcellId, state.activeVariantKey, false, true);
|
||||
}
|
||||
|
||||
private SwitchStart beginVariantTransition(
|
||||
String workcellId,
|
||||
String targetPieceKey,
|
||||
boolean discardDirty,
|
||||
boolean allowActive
|
||||
) {
|
||||
MutableWorkcellState state = workcells.get(workcellId);
|
||||
if (state == null) {
|
||||
return SwitchStart.failure(SwitchStatus.UNKNOWN_WORKCELL);
|
||||
}
|
||||
Optional<JigsawStudioVariant> target = layout.variantCatalog().find(targetPieceKey);
|
||||
if (target.isEmpty()) {
|
||||
return SwitchStart.failure(SwitchStatus.UNKNOWN_VARIANT);
|
||||
}
|
||||
JigsawStudioBay workcell = layout.get(workcellId);
|
||||
if (!layout.accepts(workcell, target.get())) {
|
||||
return SwitchStart.failure(SwitchStatus.WRONG_WORKCELL);
|
||||
}
|
||||
if (state.switchInProgress) {
|
||||
return SwitchStart.failure(SwitchStatus.SWITCH_IN_PROGRESS);
|
||||
}
|
||||
if (state.saveInProgress) {
|
||||
return SwitchStart.failure(SwitchStatus.SAVE_IN_PROGRESS);
|
||||
}
|
||||
if (state.activeVariantKey.equals(targetPieceKey) && !allowActive) {
|
||||
return SwitchStart.failure(SwitchStatus.ALREADY_ACTIVE);
|
||||
}
|
||||
if (state.dirty && !discardDirty) {
|
||||
return SwitchStart.failure(SwitchStatus.DIRTY);
|
||||
}
|
||||
|
||||
JigsawStudioVariant previous = state.activeVariantKey.isEmpty()
|
||||
? null
|
||||
: layout.variantCatalog().find(state.activeVariantKey).orElse(null);
|
||||
long switchGeneration = nextOperationGeneration();
|
||||
state.switchInProgress = true;
|
||||
state.switchGeneration = switchGeneration;
|
||||
VariantSwitchToken token = new VariantSwitchToken(
|
||||
sessionId,
|
||||
workcellId,
|
||||
Optional.ofNullable(previous),
|
||||
target.get(),
|
||||
state.loadGeneration,
|
||||
state.mutationGeneration,
|
||||
switchGeneration,
|
||||
discardDirty);
|
||||
revision++;
|
||||
return SwitchStart.started(token);
|
||||
}
|
||||
|
||||
public synchronized boolean completeVariantSwitch(VariantSwitchToken expected) {
|
||||
VariantSwitchToken token = Objects.requireNonNull(expected, "Jigsaw Studio variant switch token");
|
||||
MutableWorkcellState state = workcells.get(token.workcellId());
|
||||
if (!validSwitchToken(state, token)) {
|
||||
return false;
|
||||
}
|
||||
state.activeVariantKey = token.targetVariant().pieceKey();
|
||||
state.loadGeneration = nextLoadGeneration();
|
||||
state.mutationGeneration = nextMutationGeneration();
|
||||
state.dirty = false;
|
||||
state.switchInProgress = false;
|
||||
state.switchGeneration = 0L;
|
||||
revision++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized boolean isVariantSwitchCurrent(VariantSwitchToken expected) {
|
||||
VariantSwitchToken token = Objects.requireNonNull(expected, "Jigsaw Studio variant switch token");
|
||||
return validSwitchToken(workcells.get(token.workcellId()), token);
|
||||
}
|
||||
|
||||
public synchronized boolean abortVariantSwitch(VariantSwitchToken expected) {
|
||||
VariantSwitchToken token = Objects.requireNonNull(expected, "Jigsaw Studio variant switch token");
|
||||
MutableWorkcellState state = workcells.get(token.workcellId());
|
||||
if (!validSwitchToken(state, token)) {
|
||||
return false;
|
||||
}
|
||||
state.switchInProgress = false;
|
||||
state.switchGeneration = 0L;
|
||||
revision++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized DirtyMark markWorkcellDirty(String workcellId) {
|
||||
MutableWorkcellState state = workcells.get(workcellId);
|
||||
if (state == null) {
|
||||
return DirtyMark.failure(DirtyStatus.UNKNOWN_WORKCELL);
|
||||
}
|
||||
if (state.activeVariantKey.isEmpty()) {
|
||||
return DirtyMark.failure(DirtyStatus.NO_ACTIVE_VARIANT);
|
||||
}
|
||||
if (state.switchInProgress) {
|
||||
return DirtyMark.failure(DirtyStatus.SWITCH_IN_PROGRESS);
|
||||
}
|
||||
state.mutationGeneration = nextMutationGeneration();
|
||||
boolean newlyDirty = !state.dirty;
|
||||
state.dirty = true;
|
||||
revision++;
|
||||
return DirtyMark.marked(new DirtyIdentity(
|
||||
sessionId,
|
||||
workcellId,
|
||||
state.activeVariantKey,
|
||||
state.loadGeneration,
|
||||
state.mutationGeneration), newlyDirty);
|
||||
}
|
||||
|
||||
public synchronized boolean isDirtyCurrent(DirtyIdentity expected) {
|
||||
DirtyIdentity identity = Objects.requireNonNull(expected, "Jigsaw Studio dirty identity");
|
||||
MutableWorkcellState state = workcells.get(identity.workcellId());
|
||||
return sessionId.equals(identity.sessionId())
|
||||
&& state != null
|
||||
&& state.dirty
|
||||
&& state.activeVariantKey.equals(identity.variantKey())
|
||||
&& state.loadGeneration == identity.loadGeneration()
|
||||
&& state.mutationGeneration == identity.mutationGeneration();
|
||||
}
|
||||
|
||||
public synchronized SaveStart beginSave(String workcellId) {
|
||||
MutableWorkcellState state = workcells.get(workcellId);
|
||||
if (state == null) {
|
||||
return SaveStart.failure(SaveStatus.UNKNOWN_WORKCELL);
|
||||
}
|
||||
if (state.activeVariantKey.isEmpty()) {
|
||||
return SaveStart.failure(SaveStatus.NO_ACTIVE_VARIANT);
|
||||
}
|
||||
if (state.switchInProgress) {
|
||||
return SaveStart.failure(SaveStatus.SWITCH_IN_PROGRESS);
|
||||
}
|
||||
if (state.saveInProgress) {
|
||||
return SaveStart.failure(SaveStatus.SAVE_IN_PROGRESS);
|
||||
}
|
||||
long saveGeneration = nextOperationGeneration();
|
||||
state.saveInProgress = true;
|
||||
state.saveGeneration = saveGeneration;
|
||||
SaveIdentity identity = new SaveIdentity(
|
||||
sessionId,
|
||||
workcellId,
|
||||
state.activeVariantKey,
|
||||
state.loadGeneration,
|
||||
state.mutationGeneration,
|
||||
saveGeneration);
|
||||
revision++;
|
||||
return SaveStart.started(identity);
|
||||
}
|
||||
|
||||
public synchronized boolean markWorkcellSaved(SaveIdentity expected) {
|
||||
SaveIdentity identity = Objects.requireNonNull(expected, "Jigsaw Studio save identity");
|
||||
MutableWorkcellState state = workcells.get(identity.workcellId());
|
||||
if (!validSaveReservation(state, identity)) {
|
||||
return false;
|
||||
}
|
||||
boolean unchanged = state.activeVariantKey.equals(identity.variantKey())
|
||||
&& state.loadGeneration == identity.loadGeneration()
|
||||
&& state.mutationGeneration == identity.mutationGeneration();
|
||||
state.saveInProgress = false;
|
||||
state.saveGeneration = 0L;
|
||||
if (unchanged) {
|
||||
state.dirty = false;
|
||||
}
|
||||
revision++;
|
||||
return unchanged;
|
||||
}
|
||||
|
||||
public synchronized boolean isSaveCurrent(SaveIdentity expected) {
|
||||
SaveIdentity identity = Objects.requireNonNull(expected, "Jigsaw Studio save identity");
|
||||
MutableWorkcellState state = workcells.get(identity.workcellId());
|
||||
return validSaveReservation(state, identity)
|
||||
&& state.activeVariantKey.equals(identity.variantKey())
|
||||
&& state.loadGeneration == identity.loadGeneration()
|
||||
&& state.mutationGeneration == identity.mutationGeneration();
|
||||
}
|
||||
|
||||
public synchronized boolean abortSave(SaveIdentity expected) {
|
||||
SaveIdentity identity = Objects.requireNonNull(expected, "Jigsaw Studio save identity");
|
||||
MutableWorkcellState state = workcells.get(identity.workcellId());
|
||||
if (!validSaveReservation(state, identity)) {
|
||||
return false;
|
||||
}
|
||||
state.saveInProgress = false;
|
||||
state.saveGeneration = 0L;
|
||||
revision++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized boolean isDirty() {
|
||||
for (MutableWorkcellState state : workcells.values()) {
|
||||
if (state.dirty) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public synchronized List<String> dirtyWorkcellIds() {
|
||||
List<String> dirty = new ArrayList<>();
|
||||
for (Map.Entry<String, MutableWorkcellState> entry : workcells.entrySet()) {
|
||||
if (entry.getValue().dirty) {
|
||||
dirty.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
return List.copyOf(dirty);
|
||||
}
|
||||
|
||||
public synchronized boolean operationInProgress() {
|
||||
for (MutableWorkcellState state : workcells.values()) {
|
||||
if (state.saveInProgress || state.switchInProgress) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public synchronized long revision() {
|
||||
return revision;
|
||||
}
|
||||
|
||||
private void initializeWorkcells(JigsawStudioLayout initialLayout) {
|
||||
for (JigsawStudioBay workcell : initialLayout.bays()) {
|
||||
String variantKey = initialLayout.defaultVariant(workcell)
|
||||
.map(JigsawStudioVariant::pieceKey)
|
||||
.orElse("");
|
||||
workcells.put(workcell.stableId(), new MutableWorkcellState(
|
||||
variantKey,
|
||||
nextLoadGeneration(),
|
||||
nextMutationGeneration(),
|
||||
false,
|
||||
false));
|
||||
}
|
||||
}
|
||||
|
||||
private String retainedVariantKey(
|
||||
JigsawStudioLayout nextLayout,
|
||||
JigsawStudioBay workcell,
|
||||
MutableWorkcellState previous
|
||||
) {
|
||||
if (previous != null && previous.activeVariantKey.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
if (previous != null) {
|
||||
Optional<JigsawStudioVariant> retained = nextLayout.variantCatalog().find(previous.activeVariantKey);
|
||||
if (retained.isPresent() && nextLayout.accepts(workcell, retained.get())) {
|
||||
return previous.activeVariantKey;
|
||||
}
|
||||
}
|
||||
return nextLayout.defaultVariant(workcell).map(JigsawStudioVariant::pieceKey).orElse("");
|
||||
}
|
||||
|
||||
private boolean validSwitchToken(MutableWorkcellState state, VariantSwitchToken token) {
|
||||
if (!sessionId.equals(token.sessionId()) || state == null || !state.switchInProgress) {
|
||||
return false;
|
||||
}
|
||||
String previousKey = token.previousVariant().map(JigsawStudioVariant::pieceKey).orElse("");
|
||||
return state.switchGeneration == token.switchGeneration()
|
||||
&& state.activeVariantKey.equals(previousKey)
|
||||
&& state.loadGeneration == token.loadGeneration()
|
||||
&& state.mutationGeneration == token.mutationGeneration();
|
||||
}
|
||||
|
||||
private boolean validSaveReservation(MutableWorkcellState state, SaveIdentity identity) {
|
||||
return sessionId.equals(identity.sessionId())
|
||||
&& state != null
|
||||
&& state.saveInProgress
|
||||
&& state.saveGeneration == identity.saveGeneration();
|
||||
}
|
||||
|
||||
private MutableWorkcellState requireWorkcellState(String workcellId) {
|
||||
MutableWorkcellState state = workcells.get(Objects.requireNonNull(workcellId, "Jigsaw Studio workcell ID"));
|
||||
if (state == null) {
|
||||
throw new IllegalArgumentException("Unknown Jigsaw Studio workcell " + workcellId);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
private long nextLoadGeneration() {
|
||||
return nextLoadGeneration = Math.incrementExact(nextLoadGeneration);
|
||||
}
|
||||
|
||||
private long nextMutationGeneration() {
|
||||
return nextMutationGeneration = Math.incrementExact(nextMutationGeneration);
|
||||
}
|
||||
|
||||
private long nextOperationGeneration() {
|
||||
return nextOperationGeneration = Math.incrementExact(nextOperationGeneration);
|
||||
}
|
||||
|
||||
private static String requireKey(String value, String name) {
|
||||
Objects.requireNonNull(value, "Jigsaw Studio " + name + " key");
|
||||
String normalized = value.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio " + name + " key cannot be blank");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
public enum SwitchStatus {
|
||||
STARTED,
|
||||
UNKNOWN_WORKCELL,
|
||||
UNKNOWN_VARIANT,
|
||||
WRONG_WORKCELL,
|
||||
ALREADY_ACTIVE,
|
||||
DIRTY,
|
||||
SAVE_IN_PROGRESS,
|
||||
SWITCH_IN_PROGRESS
|
||||
}
|
||||
|
||||
public enum SaveStatus {
|
||||
STARTED,
|
||||
UNKNOWN_WORKCELL,
|
||||
NO_ACTIVE_VARIANT,
|
||||
SWITCH_IN_PROGRESS,
|
||||
SAVE_IN_PROGRESS
|
||||
}
|
||||
|
||||
public enum DirtyStatus {
|
||||
MARKED,
|
||||
UNKNOWN_WORKCELL,
|
||||
NO_ACTIVE_VARIANT,
|
||||
SWITCH_IN_PROGRESS
|
||||
}
|
||||
|
||||
public record WorkcellSnapshot(
|
||||
String workcellId,
|
||||
String activeVariantKey,
|
||||
long loadGeneration,
|
||||
long mutationGeneration,
|
||||
boolean dirty,
|
||||
boolean saveInProgress,
|
||||
boolean switchInProgress,
|
||||
boolean connectorsVisible
|
||||
) {
|
||||
}
|
||||
|
||||
public record DirtyIdentity(
|
||||
UUID sessionId,
|
||||
String workcellId,
|
||||
String variantKey,
|
||||
long loadGeneration,
|
||||
long mutationGeneration
|
||||
) {
|
||||
public DirtyIdentity {
|
||||
Objects.requireNonNull(sessionId, "Jigsaw Studio dirty session ID");
|
||||
Objects.requireNonNull(workcellId, "Jigsaw Studio dirty workcell ID");
|
||||
Objects.requireNonNull(variantKey, "Jigsaw Studio dirty variant key");
|
||||
}
|
||||
}
|
||||
|
||||
public record DirtyMark(
|
||||
DirtyStatus status,
|
||||
Optional<DirtyIdentity> identity,
|
||||
boolean newlyDirty
|
||||
) {
|
||||
public DirtyMark {
|
||||
status = Objects.requireNonNull(status, "Jigsaw Studio dirty status");
|
||||
identity = Objects.requireNonNull(identity, "Jigsaw Studio dirty identity");
|
||||
if (status == DirtyStatus.MARKED && identity.isEmpty()) {
|
||||
throw new IllegalArgumentException("A marked Jigsaw Studio workcell requires a dirty identity");
|
||||
}
|
||||
if (status != DirtyStatus.MARKED && (identity.isPresent() || newlyDirty)) {
|
||||
throw new IllegalArgumentException("A rejected Jigsaw Studio dirty mark cannot carry an identity");
|
||||
}
|
||||
}
|
||||
|
||||
private static DirtyMark marked(DirtyIdentity identity, boolean newlyDirty) {
|
||||
return new DirtyMark(DirtyStatus.MARKED, Optional.of(identity), newlyDirty);
|
||||
}
|
||||
|
||||
private static DirtyMark failure(DirtyStatus status) {
|
||||
return new DirtyMark(status, Optional.empty(), false);
|
||||
}
|
||||
}
|
||||
|
||||
public record VariantSwitchToken(
|
||||
UUID sessionId,
|
||||
String workcellId,
|
||||
Optional<JigsawStudioVariant> previousVariant,
|
||||
JigsawStudioVariant targetVariant,
|
||||
long loadGeneration,
|
||||
long mutationGeneration,
|
||||
long switchGeneration,
|
||||
boolean discardDirty
|
||||
) {
|
||||
public VariantSwitchToken {
|
||||
Objects.requireNonNull(sessionId, "Jigsaw Studio switch session ID");
|
||||
Objects.requireNonNull(workcellId, "Jigsaw Studio switch workcell ID");
|
||||
previousVariant = Objects.requireNonNull(previousVariant, "Jigsaw Studio previous variant");
|
||||
targetVariant = Objects.requireNonNull(targetVariant, "Jigsaw Studio target variant");
|
||||
}
|
||||
}
|
||||
|
||||
public record SwitchStart(SwitchStatus status, Optional<VariantSwitchToken> token) {
|
||||
public SwitchStart {
|
||||
status = Objects.requireNonNull(status, "Jigsaw Studio switch status");
|
||||
token = Objects.requireNonNull(token, "Jigsaw Studio switch token");
|
||||
}
|
||||
|
||||
private static SwitchStart started(VariantSwitchToken token) {
|
||||
return new SwitchStart(SwitchStatus.STARTED, Optional.of(token));
|
||||
}
|
||||
|
||||
private static SwitchStart failure(SwitchStatus status) {
|
||||
return new SwitchStart(status, Optional.empty());
|
||||
}
|
||||
}
|
||||
|
||||
public record SaveIdentity(
|
||||
UUID sessionId,
|
||||
String workcellId,
|
||||
String variantKey,
|
||||
long loadGeneration,
|
||||
long mutationGeneration,
|
||||
long saveGeneration
|
||||
) {
|
||||
public SaveIdentity {
|
||||
Objects.requireNonNull(sessionId, "Jigsaw Studio save session ID");
|
||||
Objects.requireNonNull(workcellId, "Jigsaw Studio save workcell ID");
|
||||
Objects.requireNonNull(variantKey, "Jigsaw Studio save variant key");
|
||||
}
|
||||
}
|
||||
|
||||
public record SaveStart(SaveStatus status, Optional<SaveIdentity> identity) {
|
||||
public SaveStart {
|
||||
status = Objects.requireNonNull(status, "Jigsaw Studio save status");
|
||||
identity = Objects.requireNonNull(identity, "Jigsaw Studio save identity");
|
||||
}
|
||||
|
||||
private static SaveStart started(SaveIdentity identity) {
|
||||
return new SaveStart(SaveStatus.STARTED, Optional.of(identity));
|
||||
}
|
||||
|
||||
private static SaveStart failure(SaveStatus status) {
|
||||
return new SaveStart(status, Optional.empty());
|
||||
}
|
||||
}
|
||||
|
||||
private static final class MutableWorkcellState {
|
||||
private String activeVariantKey;
|
||||
private long loadGeneration;
|
||||
private long mutationGeneration;
|
||||
private boolean dirty;
|
||||
private boolean saveInProgress;
|
||||
private long saveGeneration;
|
||||
private boolean switchInProgress;
|
||||
private long switchGeneration;
|
||||
private boolean connectorsVisible;
|
||||
|
||||
private MutableWorkcellState(
|
||||
String activeVariantKey,
|
||||
long loadGeneration,
|
||||
long mutationGeneration,
|
||||
boolean dirty,
|
||||
boolean connectorsVisible
|
||||
) {
|
||||
this.activeVariantKey = activeVariantKey;
|
||||
this.loadGeneration = loadGeneration;
|
||||
this.mutationGeneration = mutationGeneration;
|
||||
this.dirty = dirty;
|
||||
this.connectorsVisible = connectorsVisible;
|
||||
}
|
||||
|
||||
private MutableWorkcellState copy() {
|
||||
return new MutableWorkcellState(
|
||||
activeVariantKey,
|
||||
loadGeneration,
|
||||
mutationGeneration,
|
||||
dirty,
|
||||
connectorsVisible);
|
||||
}
|
||||
|
||||
private WorkcellSnapshot snapshot(String workcellId) {
|
||||
return new WorkcellSnapshot(
|
||||
workcellId,
|
||||
activeVariantKey,
|
||||
loadGeneration,
|
||||
mutationGeneration,
|
||||
dirty,
|
||||
saveInProgress,
|
||||
switchInProgress,
|
||||
connectorsVisible);
|
||||
}
|
||||
}
|
||||
}
|
||||
-465
@@ -1,465 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.core.structure.authoring.StructureKey;
|
||||
import art.arcane.iris.core.structure.authoring.StructureHash;
|
||||
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
|
||||
import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
|
||||
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
|
||||
import art.arcane.iris.core.structure.authoring.StructureWriteOptions;
|
||||
import art.arcane.iris.core.structure.authoring.StructureWriteResult;
|
||||
import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver;
|
||||
import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode;
|
||||
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.structure.IrisStructure;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public final class JigsawStudioStructureEditor {
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
private JigsawStudioStructureEditor() {
|
||||
}
|
||||
|
||||
public static StructureWriteResult updateCellSize(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
JigsawStudioCellDimensions dimensions
|
||||
) throws IOException {
|
||||
Path root = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
ManifestSnapshot snapshot = loadManifest(root, structureKey);
|
||||
requireOwnedObjectsFit(root, snapshot.manifest(), dimensions);
|
||||
return updateOwnedStructure(
|
||||
root,
|
||||
structureKey,
|
||||
snapshot,
|
||||
(content, structurePath) -> updateCellSize(content, dimensions, structurePath));
|
||||
}
|
||||
|
||||
public static StructureWriteResult updateLimits(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
int maxDepth,
|
||||
int maxSizeChunks
|
||||
) throws IOException {
|
||||
if (maxDepth < 1 || maxDepth > 30) {
|
||||
throw new IllegalArgumentException("Jigsaw max depth must be between 1 and 30");
|
||||
}
|
||||
if (maxSizeChunks < 1 || maxSizeChunks > 32) {
|
||||
throw new IllegalArgumentException("Jigsaw maximum size must be between 1 and 32 chunks");
|
||||
}
|
||||
Path root = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
ManifestSnapshot snapshot = loadManifest(root, structureKey);
|
||||
return updateOwnedStructure(
|
||||
root,
|
||||
structureKey,
|
||||
snapshot,
|
||||
(content, structurePath) -> updateLimits(
|
||||
content, maxDepth, maxSizeChunks, structurePath));
|
||||
}
|
||||
|
||||
public static StructureWriteResult updateThemeSets(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
List<IrisJigsawThemeSet> themeSets
|
||||
) throws IOException {
|
||||
List<IrisJigsawThemeSet> normalizedThemeSets = normalizeThemeSets(themeSets);
|
||||
Path root = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
ManifestSnapshot snapshot = loadManifest(root, structureKey);
|
||||
return updateOwnedStructure(
|
||||
root,
|
||||
structureKey,
|
||||
snapshot,
|
||||
(content, structurePath) -> updateThemeSets(
|
||||
content,
|
||||
normalizedThemeSets,
|
||||
structurePath));
|
||||
}
|
||||
|
||||
public static StructureWriteResult updateRequireCaps(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
boolean requireCaps
|
||||
) throws IOException {
|
||||
Path root = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
ManifestSnapshot snapshot = loadManifest(root, structureKey);
|
||||
return updateOwnedStructure(
|
||||
root,
|
||||
structureKey,
|
||||
snapshot,
|
||||
(content, structurePath) -> updateRequireCaps(
|
||||
content,
|
||||
requireCaps,
|
||||
structurePath));
|
||||
}
|
||||
|
||||
public static StructureWriteResult updateWorkcellEnabled(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
JigsawPlanarArchetype archetype,
|
||||
boolean enabled
|
||||
) throws IOException {
|
||||
Path root = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
JigsawPlanarArchetype target = Objects.requireNonNull(archetype, "Planar Jigsaw Studio archetype");
|
||||
ManifestSnapshot snapshot = loadManifest(root, structureKey);
|
||||
return updateOwnedStructure(
|
||||
root,
|
||||
structureKey,
|
||||
snapshot,
|
||||
(content, structurePath) -> updateWorkcell(
|
||||
content,
|
||||
target,
|
||||
null,
|
||||
enabled,
|
||||
null,
|
||||
structurePath));
|
||||
}
|
||||
|
||||
public static StructureWriteResult updateWorkcellDimensions(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
JigsawPlanarArchetype archetype,
|
||||
JigsawStudioCellDimensions dimensions
|
||||
) throws IOException {
|
||||
return JigsawStudioGraphEditor.updatePlanarWorkcellCapacity(
|
||||
packRoot,
|
||||
structureKey,
|
||||
archetype,
|
||||
dimensions).writeResult();
|
||||
}
|
||||
|
||||
public static StructureWriteResult updateWorkcellDisplayName(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
JigsawPlanarArchetype archetype,
|
||||
String displayName
|
||||
) throws IOException {
|
||||
Path root = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
JigsawPlanarArchetype target = Objects.requireNonNull(archetype, "Planar Jigsaw Studio archetype");
|
||||
String normalizedName = JigsawStudioGraphEditor.normalizeDisplayName(displayName);
|
||||
ManifestSnapshot snapshot = loadManifest(root, structureKey);
|
||||
return updateOwnedStructure(
|
||||
root,
|
||||
structureKey,
|
||||
snapshot,
|
||||
(content, structurePath) -> updateWorkcell(
|
||||
content,
|
||||
target,
|
||||
null,
|
||||
null,
|
||||
normalizedName,
|
||||
structurePath));
|
||||
}
|
||||
|
||||
public static StructureWriteResult updateSpatialWorkcellDisplayName(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String displayName
|
||||
) throws IOException {
|
||||
Path root = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
String normalizedName = JigsawStudioGraphEditor.normalizeDisplayName(displayName);
|
||||
ManifestSnapshot snapshot = loadManifest(root, structureKey);
|
||||
return updateOwnedStructure(
|
||||
root,
|
||||
structureKey,
|
||||
snapshot,
|
||||
(content, structurePath) -> updateSpatialWorkcellDisplayName(
|
||||
content,
|
||||
normalizedName,
|
||||
structurePath));
|
||||
}
|
||||
|
||||
private static ManifestSnapshot loadManifest(Path root, String structureKey) throws IOException {
|
||||
StructureKey ownershipKey = StructureKey.parse(structureKey, "iris");
|
||||
StructureTransactionWriter writer = new StructureTransactionWriter(root);
|
||||
Path manifestPath = writer.ownershipManifestPath(ownershipKey);
|
||||
if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("This graph is read-only because it is not Studio-owned; create a new Jigsaw Studio project before editing rules");
|
||||
}
|
||||
byte[] manifestContent = Files.readAllBytes(manifestPath);
|
||||
return new ManifestSnapshot(
|
||||
JigsawStudioAuthoringAccess.requireEditable(
|
||||
StructureOwnershipManifest.fromJson(manifestContent)),
|
||||
StructureHash.sha256(manifestContent));
|
||||
}
|
||||
|
||||
private static StructureWriteResult updateOwnedStructure(
|
||||
Path root,
|
||||
String structureKey,
|
||||
ManifestSnapshot snapshot,
|
||||
StructureContentEditor editor
|
||||
) throws IOException {
|
||||
StructureTransactionWriter writer = new StructureTransactionWriter(root);
|
||||
StructureOwnershipManifest manifest = snapshot.manifest();
|
||||
String normalizedStructure = JigsawStudioProjectCreator.Options.requireResourceKey(structureKey);
|
||||
String targetResource = "structures/" + normalizedStructure + ".json";
|
||||
if (!manifest.resourceHashes().containsKey(targetResource)) {
|
||||
throw new IOException("The owned graph manifest does not include " + targetResource);
|
||||
}
|
||||
|
||||
StructureResourceBundle.Builder bundle = StructureResourceBundle.builder(manifest.structure())
|
||||
.source(manifest.source())
|
||||
.backend(manifest.backend())
|
||||
.capabilities(manifest.capabilities())
|
||||
.losses(manifest.losses());
|
||||
for (Map.Entry<String, String> resource : manifest.resourceHashes().entrySet()) {
|
||||
Path resourcePath = resolveOwnedResource(root, resource.getKey());
|
||||
byte[] content = Files.readAllBytes(resourcePath);
|
||||
if (resource.getKey().equals(targetResource)) {
|
||||
content = editor.edit(content, resourcePath);
|
||||
}
|
||||
bundle.resource(resource.getKey(), content);
|
||||
}
|
||||
StructureResourceBundle updatedBundle = bundle.build();
|
||||
StructureResourceBundleGraphCompiler.requireViable(updatedBundle);
|
||||
StructureWriteResult result = writer.write(
|
||||
updatedBundle,
|
||||
StructureWriteOptions.overwriteExpected(snapshot.expectedManifestHash()));
|
||||
if (!result.successful()) {
|
||||
String conflict = result.conflicts().isEmpty()
|
||||
? result.status().name()
|
||||
: result.conflicts().getFirst().relativePath() + ": "
|
||||
+ result.conflicts().getFirst().reason();
|
||||
throw new IOException("Atomic graph structure update was rejected: " + conflict);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Path resolveOwnedResource(Path root, String relativePath) throws IOException {
|
||||
StructureResourceBundle.validateRelativePath(relativePath);
|
||||
Path resource = root.resolve(relativePath).normalize();
|
||||
if (!resource.startsWith(root) || !Files.isRegularFile(resource, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Owned graph resource is missing or unsafe: " + relativePath);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
private static void requireOwnedObjectsFit(
|
||||
Path root,
|
||||
StructureOwnershipManifest manifest,
|
||||
JigsawStudioCellDimensions dimensions
|
||||
) throws IOException {
|
||||
for (String relativePath : manifest.resourceHashes().keySet()) {
|
||||
if (!relativePath.startsWith("objects/") || !relativePath.endsWith(".iob")) {
|
||||
continue;
|
||||
}
|
||||
Path objectPath = resolveOwnedResource(root, relativePath);
|
||||
IrisBlockVector size = IrisObject.sampleSize(objectPath.toFile());
|
||||
if (size.getBlockX() > dimensions.width()
|
||||
|| size.getBlockY() > dimensions.height()
|
||||
|| size.getBlockZ() > dimensions.depth()) {
|
||||
throw new IOException("Owned object '" + relativePath + "' is "
|
||||
+ size.getBlockX() + "x" + size.getBlockY() + "x" + size.getBlockZ()
|
||||
+ " and does not fit the requested cell bounds");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] updateCellSize(
|
||||
byte[] content,
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
Path structurePath
|
||||
) throws IOException {
|
||||
JsonElement parsed = JsonParser.parseString(new String(content, StandardCharsets.UTF_8));
|
||||
if (!parsed.isJsonObject()) {
|
||||
throw new IOException("Jigsaw structure is not a JSON object: " + structurePath);
|
||||
}
|
||||
JsonObject cellSize = new JsonObject();
|
||||
JsonObject structure = parsed.getAsJsonObject();
|
||||
if (structure.has("mode")
|
||||
&& "PLANAR_JIGSAW".equals(structure.get("mode").getAsString())
|
||||
&& dimensions.width() != dimensions.depth()) {
|
||||
throw new IOException("Planar Jigsaw Studio cells require equal width and depth");
|
||||
}
|
||||
cellSize.addProperty("x", dimensions.width());
|
||||
cellSize.addProperty("y", dimensions.height());
|
||||
cellSize.addProperty("z", dimensions.depth());
|
||||
structure.add("cellSize", cellSize);
|
||||
return (GSON.toJson(structure) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static byte[] updateLimits(
|
||||
byte[] content,
|
||||
int maxDepth,
|
||||
int maxSizeChunks,
|
||||
Path structurePath
|
||||
) throws IOException {
|
||||
JsonElement parsed = JsonParser.parseString(new String(content, StandardCharsets.UTF_8));
|
||||
if (!parsed.isJsonObject()) {
|
||||
throw new IOException("Jigsaw structure is not a JSON object: " + structurePath);
|
||||
}
|
||||
JsonObject structure = parsed.getAsJsonObject();
|
||||
structure.addProperty("maxDepth", maxDepth);
|
||||
structure.addProperty("maxSizeChunks", maxSizeChunks);
|
||||
return (GSON.toJson(structure) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static List<IrisJigsawThemeSet> normalizeThemeSets(List<IrisJigsawThemeSet> themeSets) {
|
||||
Objects.requireNonNull(themeSets, "Jigsaw Studio theme sets");
|
||||
List<IrisJigsawThemeSet> normalized = new ArrayList<>(themeSets.size());
|
||||
Set<String> keys = new LinkedHashSet<>();
|
||||
for (IrisJigsawThemeSet themeSet : themeSets) {
|
||||
IrisJigsawThemeSet source = Objects.requireNonNull(themeSet, "Jigsaw Studio theme set");
|
||||
String key = source.getKey() == null ? "" : source.getKey().trim();
|
||||
if (key.isEmpty() || !key.equals(source.getKey())) {
|
||||
throw new IllegalArgumentException(
|
||||
"Jigsaw Studio theme keys must be non-blank and whitespace-normalized");
|
||||
}
|
||||
if (!keys.add(key)) {
|
||||
throw new IllegalArgumentException("Duplicate Jigsaw Studio theme key '" + key + "'");
|
||||
}
|
||||
if (source.getWeight() < 1) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio theme weights must be positive");
|
||||
}
|
||||
normalized.add(new IrisJigsawThemeSet(key, source.getWeight()));
|
||||
}
|
||||
return List.copyOf(normalized);
|
||||
}
|
||||
|
||||
private static byte[] updateThemeSets(
|
||||
byte[] content,
|
||||
List<IrisJigsawThemeSet> themeSets,
|
||||
Path structurePath
|
||||
) throws IOException {
|
||||
JsonObject structure = parseStructure(content, structurePath);
|
||||
JsonArray values = new JsonArray();
|
||||
for (IrisJigsawThemeSet themeSet : themeSets) {
|
||||
JsonObject value = new JsonObject();
|
||||
value.addProperty("key", themeSet.getKey());
|
||||
value.addProperty("weight", themeSet.getWeight());
|
||||
values.add(value);
|
||||
}
|
||||
structure.add("themeSets", values);
|
||||
return (GSON.toJson(structure) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static byte[] updateRequireCaps(
|
||||
byte[] content,
|
||||
boolean requireCaps,
|
||||
Path structurePath
|
||||
) throws IOException {
|
||||
JsonObject structure = parseStructure(content, structurePath);
|
||||
structure.addProperty("requireCaps", requireCaps);
|
||||
return (GSON.toJson(structure) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static byte[] updateSpatialWorkcellDisplayName(
|
||||
byte[] content,
|
||||
String displayName,
|
||||
Path structurePath
|
||||
) throws IOException {
|
||||
JsonObject structure = parseStructure(content, structurePath);
|
||||
IrisStructure model;
|
||||
try {
|
||||
model = GSON.fromJson(structure, IrisStructure.class);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IOException("Jigsaw structure is not valid JSON: " + structurePath, exception);
|
||||
}
|
||||
if (model == null || model.resolvedMode() != IrisJigsawMode.SPATIAL_JIGSAW) {
|
||||
throw new IOException("Spatial workcell labels require a spatial Jigsaw Studio structure");
|
||||
}
|
||||
if (displayName.isEmpty()) {
|
||||
structure.remove("spatialWorkcellDisplayName");
|
||||
} else {
|
||||
structure.addProperty("spatialWorkcellDisplayName", displayName);
|
||||
}
|
||||
return (GSON.toJson(structure) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static JsonObject parseStructure(byte[] content, Path structurePath) throws IOException {
|
||||
JsonElement parsed = JsonParser.parseString(new String(content, StandardCharsets.UTF_8));
|
||||
if (!parsed.isJsonObject()) {
|
||||
throw new IOException("Jigsaw structure is not a JSON object: " + structurePath);
|
||||
}
|
||||
return parsed.getAsJsonObject();
|
||||
}
|
||||
|
||||
static byte[] updateWorkcell(
|
||||
byte[] content,
|
||||
JigsawPlanarArchetype archetype,
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
Boolean enabled,
|
||||
String displayName,
|
||||
Path structurePath
|
||||
) throws IOException {
|
||||
JsonElement parsed = JsonParser.parseString(new String(content, StandardCharsets.UTF_8));
|
||||
if (!parsed.isJsonObject()) {
|
||||
throw new IOException("Jigsaw structure is not a JSON object: " + structurePath);
|
||||
}
|
||||
JsonObject structureJson = parsed.getAsJsonObject();
|
||||
IrisStructure structure;
|
||||
try {
|
||||
structure = GSON.fromJson(structureJson, IrisStructure.class);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IOException("Jigsaw structure is not valid JSON: " + structurePath, exception);
|
||||
}
|
||||
if (structure == null || structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW) {
|
||||
throw new IOException("Workcell settings require a planar Jigsaw Studio structure");
|
||||
}
|
||||
Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell> resolved;
|
||||
try {
|
||||
resolved = PlanarJigsawWorkcellResolver.resolve(structure);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IOException("Planar workcell configuration is invalid: " + exception.getMessage(), exception);
|
||||
}
|
||||
JsonArray workcells = new JsonArray();
|
||||
for (JigsawPlanarArchetype current : JigsawPlanarArchetype.values()) {
|
||||
PlanarJigsawWorkcellResolver.ResolvedWorkcell source = resolved.get(current.modelArchetype());
|
||||
JsonObject workcell = new JsonObject();
|
||||
workcell.addProperty("archetype", current.name());
|
||||
String resolvedDisplayName = current == archetype && displayName != null
|
||||
? displayName : source.displayName();
|
||||
if (!resolvedDisplayName.isEmpty()) {
|
||||
workcell.addProperty("displayName", resolvedDisplayName);
|
||||
}
|
||||
workcell.addProperty("width", current == archetype && dimensions != null
|
||||
? dimensions.width() : source.width());
|
||||
workcell.addProperty("height", current == archetype && dimensions != null
|
||||
? dimensions.height() : source.height());
|
||||
workcell.addProperty("depth", current == archetype && dimensions != null
|
||||
? dimensions.depth() : source.depth());
|
||||
workcell.addProperty("enabled", current == archetype && enabled != null
|
||||
? enabled : source.enabled());
|
||||
workcells.add(workcell);
|
||||
}
|
||||
structureJson.add("planarWorkcells", workcells);
|
||||
return (GSON.toJson(structureJson) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface StructureContentEditor {
|
||||
byte[] edit(byte[] content, Path structurePath) throws IOException;
|
||||
}
|
||||
|
||||
private record ManifestSnapshot(
|
||||
StructureOwnershipManifest manifest,
|
||||
String expectedManifestHash
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public enum JigsawStudioToolAction {
|
||||
OPEN_MENU("Open Control Menu", false),
|
||||
SELECT_WORKCELL("Select Workcell", false),
|
||||
TOGGLE_WORKCELL("Toggle Workcell", false),
|
||||
LOAD_VARIANT("Load Variant", false),
|
||||
CREATE_VARIANT("New Blank Variant", false),
|
||||
DUPLICATE_VARIANT("Duplicate This Cell's Variant", false),
|
||||
DUPLICATE_FAMILY("Duplicate All Enabled Cells as Family", false),
|
||||
PREVIEW_GRAPH("Go to Preview", false),
|
||||
FLUSH_AUTOSAVE("Flush Autosave", false),
|
||||
TOGGLE_ROTATION("Toggle Rotation", false),
|
||||
EXPAND_TO_CELL("Resize Variant to Capacity", false),
|
||||
RESIZE_VARIANT("Resize This Variant", false),
|
||||
RESIZE_WORKCELL("Resize Workcell Capacity", false),
|
||||
RENAME_VARIANT("Rename This Variant", false),
|
||||
RENAME_WORKCELL("Rename This Workcell", false),
|
||||
ADJUST_VARIANT_WEIGHT("Adjust Variant Weight", false),
|
||||
ADJUST_VARIANT_CHANCE("Adjust Variant Chance", false),
|
||||
SET_THEME("Set Theme", false),
|
||||
SET_PIECE_RULES("Set Piece Rules", false),
|
||||
TOGGLE_REQUIRE_CAPS("Toggle Required Caps", false),
|
||||
UNLINK_MEMBERSHIP("Unlink Pool Entry", true),
|
||||
DELETE_VARIANT("Delete Variant", true),
|
||||
DELETE_PROJECT("Delete Project", true);
|
||||
|
||||
private final String displayName;
|
||||
private final boolean destructive;
|
||||
|
||||
JigsawStudioToolAction(String displayName, boolean destructive) {
|
||||
this.displayName = Objects.requireNonNull(displayName, "Jigsaw Studio tool display name");
|
||||
this.destructive = destructive;
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public boolean destructive() {
|
||||
return destructive;
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public record JigsawStudioToolPayload(
|
||||
int schemaVersion,
|
||||
JigsawStudioToolAction action,
|
||||
UUID requestId,
|
||||
String workcellId,
|
||||
String pieceKey,
|
||||
String poolKey,
|
||||
int entryIndex,
|
||||
int amount
|
||||
) {
|
||||
public static final int CURRENT_SCHEMA_VERSION = 2;
|
||||
public static final int NO_ENTRY_INDEX = -1;
|
||||
|
||||
private static final int MAX_FIELD_LENGTH = 512;
|
||||
|
||||
public JigsawStudioToolPayload {
|
||||
if (schemaVersion < 1) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio tool schema version must be positive");
|
||||
}
|
||||
action = Objects.requireNonNull(action, "Jigsaw Studio tool action");
|
||||
requestId = Objects.requireNonNull(requestId, "Jigsaw Studio tool request ID");
|
||||
workcellId = normalize(workcellId, "workcell ID");
|
||||
pieceKey = normalize(pieceKey, "piece key");
|
||||
poolKey = normalize(poolKey, "pool key");
|
||||
if (entryIndex < NO_ENTRY_INDEX) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio tool entry index cannot be lower than -1");
|
||||
}
|
||||
}
|
||||
|
||||
public static JigsawStudioToolPayload request(
|
||||
JigsawStudioToolAction action,
|
||||
UUID requestId
|
||||
) {
|
||||
return new JigsawStudioToolPayload(
|
||||
CURRENT_SCHEMA_VERSION,
|
||||
action,
|
||||
requestId,
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
NO_ENTRY_INDEX,
|
||||
0);
|
||||
}
|
||||
|
||||
public static JigsawStudioToolPayload workcell(
|
||||
JigsawStudioToolAction action,
|
||||
UUID requestId,
|
||||
String workcellId
|
||||
) {
|
||||
return new JigsawStudioToolPayload(
|
||||
CURRENT_SCHEMA_VERSION,
|
||||
action,
|
||||
requestId,
|
||||
workcellId,
|
||||
"",
|
||||
"",
|
||||
NO_ENTRY_INDEX,
|
||||
0);
|
||||
}
|
||||
|
||||
public static JigsawStudioToolPayload variant(
|
||||
JigsawStudioToolAction action,
|
||||
UUID requestId,
|
||||
String workcellId,
|
||||
String pieceKey
|
||||
) {
|
||||
return new JigsawStudioToolPayload(
|
||||
CURRENT_SCHEMA_VERSION,
|
||||
action,
|
||||
requestId,
|
||||
workcellId,
|
||||
pieceKey,
|
||||
"",
|
||||
NO_ENTRY_INDEX,
|
||||
0);
|
||||
}
|
||||
|
||||
public static JigsawStudioToolPayload membership(
|
||||
JigsawStudioToolAction action,
|
||||
UUID requestId,
|
||||
String workcellId,
|
||||
String pieceKey,
|
||||
String poolKey,
|
||||
int entryIndex,
|
||||
int amount
|
||||
) {
|
||||
return new JigsawStudioToolPayload(
|
||||
CURRENT_SCHEMA_VERSION,
|
||||
action,
|
||||
requestId,
|
||||
workcellId,
|
||||
pieceKey,
|
||||
poolKey,
|
||||
entryIndex,
|
||||
amount);
|
||||
}
|
||||
|
||||
private static String normalize(String value, String fieldName) {
|
||||
String normalized = value == null ? "" : value.trim();
|
||||
if (normalized.length() > MAX_FIELD_LENGTH) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio tool " + fieldName
|
||||
+ " cannot exceed " + MAX_FIELD_LENGTH + " characters");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class JigsawStudioTripleSneakTracker {
|
||||
public static final long DEFAULT_WINDOW_NANOS = 1_500_000_000L;
|
||||
|
||||
private static final int REQUIRED_SNEAKS = 3;
|
||||
|
||||
private final long windowNanos;
|
||||
private final Map<UUID, GestureState> gestures = new HashMap<>();
|
||||
|
||||
public JigsawStudioTripleSneakTracker() {
|
||||
this(DEFAULT_WINDOW_NANOS);
|
||||
}
|
||||
|
||||
public JigsawStudioTripleSneakTracker(long windowNanos) {
|
||||
if (windowNanos <= 0L) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio triple-sneak window must be positive");
|
||||
}
|
||||
this.windowNanos = windowNanos;
|
||||
}
|
||||
|
||||
public synchronized Progress recordSneak(
|
||||
UUID playerId,
|
||||
UUID worldId,
|
||||
UUID requestId,
|
||||
long nowNanos
|
||||
) {
|
||||
UUID player = Objects.requireNonNull(playerId, "Jigsaw Studio gesture player ID");
|
||||
UUID world = Objects.requireNonNull(worldId, "Jigsaw Studio gesture world ID");
|
||||
UUID request = Objects.requireNonNull(requestId, "Jigsaw Studio gesture request ID");
|
||||
GestureState previous = gestures.get(player);
|
||||
if (previous == null
|
||||
|| !previous.worldId().equals(world)
|
||||
|| !previous.requestId().equals(request)
|
||||
|| expired(previous, nowNanos)) {
|
||||
gestures.put(player, new GestureState(world, request, nowNanos, nowNanos, 1));
|
||||
return Progress.FIRST;
|
||||
}
|
||||
|
||||
int count = previous.count() + 1;
|
||||
if (count >= REQUIRED_SNEAKS) {
|
||||
gestures.remove(player);
|
||||
return Progress.TRIGGERED;
|
||||
}
|
||||
gestures.put(player, new GestureState(
|
||||
world,
|
||||
request,
|
||||
previous.startedAtNanos(),
|
||||
nowNanos,
|
||||
count));
|
||||
return Progress.SECOND;
|
||||
}
|
||||
|
||||
public synchronized void clearPlayer(UUID playerId) {
|
||||
if (playerId != null) {
|
||||
gestures.remove(playerId);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized int clearRequest(UUID requestId) {
|
||||
if (requestId == null) {
|
||||
return 0;
|
||||
}
|
||||
int removed = 0;
|
||||
Iterator<GestureState> states = gestures.values().iterator();
|
||||
while (states.hasNext()) {
|
||||
GestureState state = states.next();
|
||||
if (state.requestId().equals(requestId)) {
|
||||
states.remove();
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
public synchronized void clearAll() {
|
||||
gestures.clear();
|
||||
}
|
||||
|
||||
public synchronized int trackedPlayers() {
|
||||
return gestures.size();
|
||||
}
|
||||
|
||||
private boolean expired(GestureState state, long nowNanos) {
|
||||
long elapsedSinceStart = nowNanos - state.startedAtNanos();
|
||||
long elapsedSinceLast = nowNanos - state.lastSneakAtNanos();
|
||||
return elapsedSinceStart < 0L
|
||||
|| elapsedSinceLast < 0L
|
||||
|| elapsedSinceStart > windowNanos;
|
||||
}
|
||||
|
||||
public enum Progress {
|
||||
FIRST,
|
||||
SECOND,
|
||||
TRIGGERED
|
||||
}
|
||||
|
||||
private record GestureState(
|
||||
UUID worldId,
|
||||
UUID requestId,
|
||||
long startedAtNanos,
|
||||
long lastSneakAtNanos,
|
||||
int count
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public record JigsawStudioVariant(
|
||||
String pieceKey,
|
||||
String objectKey,
|
||||
String displayName,
|
||||
Optional<JigsawStudioCellDimensions> dimensions,
|
||||
JigsawStudioMode mode,
|
||||
Optional<JigsawPlanarTopology> sourceTopology,
|
||||
boolean rotatable,
|
||||
boolean owned,
|
||||
List<String> themes,
|
||||
JigsawStudioPieceRules rules,
|
||||
List<JigsawStudioPoolMembership> memberships
|
||||
) {
|
||||
public JigsawStudioVariant {
|
||||
pieceKey = requireKey(pieceKey, "piece");
|
||||
objectKey = requireKey(objectKey, "object");
|
||||
displayName = displayName == null ? "" : displayName.trim();
|
||||
dimensions = Objects.requireNonNull(dimensions, "Jigsaw Studio variant dimensions");
|
||||
mode = Objects.requireNonNull(mode, "Jigsaw Studio variant mode");
|
||||
sourceTopology = Objects.requireNonNull(sourceTopology, "Jigsaw Studio variant topology");
|
||||
themes = List.copyOf(Objects.requireNonNull(themes, "Jigsaw Studio variant themes"));
|
||||
rules = Objects.requireNonNull(rules, "Jigsaw Studio variant rules");
|
||||
memberships = List.copyOf(Objects.requireNonNull(memberships, "Jigsaw Studio pool memberships"));
|
||||
if (mode == JigsawStudioMode.PLANAR_JIGSAW && sourceTopology.isEmpty()) {
|
||||
throw new IllegalArgumentException("Planar Jigsaw Studio variants require a topology");
|
||||
}
|
||||
if (mode == JigsawStudioMode.SPATIAL_JIGSAW && sourceTopology.isPresent()) {
|
||||
throw new IllegalArgumentException("Spatial Jigsaw Studio variants cannot declare a planar topology");
|
||||
}
|
||||
}
|
||||
|
||||
public String resolvedDisplayName() {
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
int separator = Math.max(pieceKey.lastIndexOf('/'), pieceKey.lastIndexOf(':'));
|
||||
return separator < 0 ? pieceKey : pieceKey.substring(separator + 1);
|
||||
}
|
||||
|
||||
public Optional<JigsawPlanarArchetype> archetype() {
|
||||
return sourceTopology.map(JigsawPlanarArchetype::fromTopology);
|
||||
}
|
||||
|
||||
public int sourceToCanonicalQuarterTurns() {
|
||||
JigsawPlanarTopology topology = sourceTopology.orElse(null);
|
||||
return topology == null ? 0 : JigsawPlanarArchetype.fromTopology(topology)
|
||||
.sourceToCanonicalQuarterTurns(topology);
|
||||
}
|
||||
|
||||
public int canonicalToSourceQuarterTurns() {
|
||||
JigsawPlanarTopology topology = sourceTopology.orElse(null);
|
||||
return topology == null ? 0 : JigsawPlanarArchetype.fromTopology(topology)
|
||||
.canonicalToSourceQuarterTurns(topology);
|
||||
}
|
||||
|
||||
public IrisPosition sourceToCanonicalPosition(
|
||||
IrisPosition sourcePosition,
|
||||
JigsawStudioCellDimensions sourceDimensions
|
||||
) {
|
||||
return rotatePosition(
|
||||
sourcePosition,
|
||||
sourceDimensions,
|
||||
sourceToCanonicalQuarterTurns());
|
||||
}
|
||||
|
||||
public IrisPosition canonicalToSourcePosition(
|
||||
IrisPosition canonicalPosition,
|
||||
JigsawStudioCellDimensions sourceDimensions
|
||||
) {
|
||||
JigsawStudioCellDimensions canonicalDimensions = canonicalDimensions(sourceDimensions);
|
||||
return rotatePosition(
|
||||
canonicalPosition,
|
||||
canonicalDimensions,
|
||||
canonicalToSourceQuarterTurns());
|
||||
}
|
||||
|
||||
public JigsawStudioCellDimensions canonicalDimensions(JigsawStudioCellDimensions sourceDimensions) {
|
||||
JigsawStudioCellDimensions dimensions = Objects.requireNonNull(
|
||||
sourceDimensions,
|
||||
"Jigsaw Studio source dimensions");
|
||||
return Math.floorMod(sourceToCanonicalQuarterTurns(), 2) == 0
|
||||
? dimensions
|
||||
: new JigsawStudioCellDimensions(
|
||||
dimensions.depth(),
|
||||
dimensions.height(),
|
||||
dimensions.width());
|
||||
}
|
||||
|
||||
public boolean assigned() {
|
||||
return !memberships.isEmpty();
|
||||
}
|
||||
|
||||
private static IrisPosition rotatePosition(
|
||||
IrisPosition position,
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
int quarterTurns
|
||||
) {
|
||||
IrisPosition source = Objects.requireNonNull(position, "Jigsaw Studio variant position");
|
||||
JigsawStudioCellDimensions bounds = Objects.requireNonNull(
|
||||
dimensions,
|
||||
"Jigsaw Studio variant position bounds");
|
||||
if (source.getX() < 0 || source.getX() >= bounds.width()
|
||||
|| source.getY() < 0 || source.getY() >= bounds.height()
|
||||
|| source.getZ() < 0 || source.getZ() >= bounds.depth()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio variant position is outside its object bounds");
|
||||
}
|
||||
return switch (Math.floorMod(quarterTurns, 4)) {
|
||||
case 0 -> new IrisPosition(source.getX(), source.getY(), source.getZ());
|
||||
case 1 -> new IrisPosition(
|
||||
bounds.depth() - 1 - source.getZ(),
|
||||
source.getY(),
|
||||
source.getX());
|
||||
case 2 -> new IrisPosition(
|
||||
bounds.width() - 1 - source.getX(),
|
||||
source.getY(),
|
||||
bounds.depth() - 1 - source.getZ());
|
||||
case 3 -> new IrisPosition(
|
||||
source.getZ(),
|
||||
source.getY(),
|
||||
bounds.width() - 1 - source.getX());
|
||||
default -> throw new IllegalStateException("Unreachable Jigsaw Studio rotation");
|
||||
};
|
||||
}
|
||||
|
||||
private static String requireKey(String value, String name) {
|
||||
Objects.requireNonNull(value, "Jigsaw Studio " + name + " key");
|
||||
String normalized = value.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio " + name + " key cannot be blank");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class JigsawStudioVariantCatalog {
|
||||
private final List<JigsawStudioVariant> variants;
|
||||
private final Map<String, JigsawStudioVariant> byPieceKey;
|
||||
private final Map<JigsawPlanarArchetype, List<JigsawStudioVariant>> byArchetype;
|
||||
private final List<JigsawStudioVariant> spatialVariants;
|
||||
private final boolean editableGraph;
|
||||
|
||||
public JigsawStudioVariantCatalog(List<JigsawStudioVariant> variants) {
|
||||
this(variants, true);
|
||||
}
|
||||
|
||||
public JigsawStudioVariantCatalog(
|
||||
List<JigsawStudioVariant> variants,
|
||||
boolean editableGraph
|
||||
) {
|
||||
Objects.requireNonNull(variants, "Jigsaw Studio variants");
|
||||
if (variants.size() > JigsawStudioLayout.MAX_VARIANTS) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio catalogs cannot exceed "
|
||||
+ JigsawStudioLayout.MAX_VARIANTS + " variants");
|
||||
}
|
||||
List<JigsawStudioVariant> copied = List.copyOf(variants);
|
||||
Map<String, JigsawStudioVariant> pieceIndex = new LinkedHashMap<>();
|
||||
Map<JigsawPlanarArchetype, List<JigsawStudioVariant>> archetypeIndex =
|
||||
new EnumMap<>(JigsawPlanarArchetype.class);
|
||||
List<JigsawStudioVariant> spatial = new ArrayList<>();
|
||||
for (JigsawStudioVariant variant : copied) {
|
||||
JigsawStudioVariant activeVariant = Objects.requireNonNull(variant, "Jigsaw Studio variant");
|
||||
JigsawStudioVariant previous = pieceIndex.putIfAbsent(activeVariant.pieceKey(), activeVariant);
|
||||
if (previous != null) {
|
||||
throw new IllegalArgumentException("Duplicate Jigsaw Studio variant piece key "
|
||||
+ activeVariant.pieceKey());
|
||||
}
|
||||
Optional<JigsawPlanarArchetype> archetype = activeVariant.archetype();
|
||||
if (archetype.isPresent()) {
|
||||
archetypeIndex.computeIfAbsent(archetype.get(), key -> new ArrayList<>()).add(activeVariant);
|
||||
} else {
|
||||
spatial.add(activeVariant);
|
||||
}
|
||||
}
|
||||
Map<JigsawPlanarArchetype, List<JigsawStudioVariant>> immutableArchetypes =
|
||||
new EnumMap<>(JigsawPlanarArchetype.class);
|
||||
for (JigsawPlanarArchetype archetype : JigsawPlanarArchetype.values()) {
|
||||
immutableArchetypes.put(
|
||||
archetype,
|
||||
List.copyOf(archetypeIndex.getOrDefault(archetype, List.of())));
|
||||
}
|
||||
this.variants = copied;
|
||||
this.byPieceKey = Collections.unmodifiableMap(pieceIndex);
|
||||
this.byArchetype = Collections.unmodifiableMap(immutableArchetypes);
|
||||
this.spatialVariants = List.copyOf(spatial);
|
||||
this.editableGraph = editableGraph;
|
||||
}
|
||||
|
||||
public static JigsawStudioVariantCatalog empty() {
|
||||
return new JigsawStudioVariantCatalog(List.of());
|
||||
}
|
||||
|
||||
public List<JigsawStudioVariant> variants() {
|
||||
return variants;
|
||||
}
|
||||
|
||||
public Optional<JigsawStudioVariant> find(String pieceKey) {
|
||||
if (pieceKey == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(byPieceKey.get(pieceKey));
|
||||
}
|
||||
|
||||
public List<JigsawStudioVariant> variants(JigsawPlanarArchetype archetype) {
|
||||
return byArchetype.get(Objects.requireNonNull(archetype, "Planar archetype"));
|
||||
}
|
||||
|
||||
public List<JigsawStudioVariant> spatialVariants() {
|
||||
return spatialVariants;
|
||||
}
|
||||
|
||||
public boolean editableGraph() {
|
||||
return editableGraph;
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return variants.size();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public record JigsawStudioWorkcellSpec(
|
||||
JigsawPlanarArchetype archetype,
|
||||
String displayName,
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
boolean enabled
|
||||
) {
|
||||
public JigsawStudioWorkcellSpec {
|
||||
archetype = Objects.requireNonNull(archetype, "Jigsaw Studio workcell archetype");
|
||||
displayName = displayName == null ? "" : displayName.trim();
|
||||
dimensions = Objects.requireNonNull(dimensions, "Jigsaw Studio workcell dimensions");
|
||||
}
|
||||
|
||||
public String resolvedDisplayName() {
|
||||
return displayName.isEmpty() ? archetype.displayName() : displayName;
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import art.arcane.volmlib.util.board.Board;
|
||||
import art.arcane.volmlib.util.board.BoardProvider;
|
||||
import art.arcane.volmlib.util.board.BoardSettings;
|
||||
import art.arcane.volmlib.util.board.ScoreDirection;
|
||||
import com.volmit.tooling.world.ToolText;
|
||||
import art.arcane.volmlib.util.format.Form;
|
||||
import art.arcane.iris.util.common.plugin.IrisService;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
@@ -60,11 +61,10 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class BoardSVC implements IrisService, BoardProvider {
|
||||
private static final String SEPARATOR = "&7&m-------------------";
|
||||
private static final Pattern LEGACY_COLOR = Pattern.compile("(?i)\\u00a7[0-9A-FK-ORX]");
|
||||
|
||||
private final Map<Player, PlayerBoard> boards = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, JigsawStudioBoardContext> jigsawContexts = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, ToolSidebar> toolSidebars = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, UUID> yieldedWorlds = new ConcurrentHashMap<>();
|
||||
private final Set<UUID> hiddenPlayers = ConcurrentHashMap.newKeySet();
|
||||
private volatile BoardSettings settings;
|
||||
@@ -117,7 +117,7 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
board.cancel();
|
||||
}
|
||||
boards.clear();
|
||||
jigsawContexts.clear();
|
||||
toolSidebars.clear();
|
||||
yieldedWorlds.clear();
|
||||
hiddenPlayers.clear();
|
||||
settings = null;
|
||||
@@ -136,7 +136,7 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void on(PlayerQuitEvent e) {
|
||||
remove(e.getPlayer());
|
||||
jigsawContexts.remove(e.getPlayer().getUniqueId());
|
||||
toolSidebars.remove(e.getPlayer().getUniqueId());
|
||||
yieldedWorlds.remove(e.getPlayer().getUniqueId());
|
||||
clearPlayerPreference(e.getPlayer().getUniqueId());
|
||||
}
|
||||
@@ -163,43 +163,55 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
}
|
||||
|
||||
if (!isEligibleWorld(p)) {
|
||||
jigsawContexts.remove(playerId);
|
||||
toolSidebars.remove(playerId);
|
||||
remove(p);
|
||||
return;
|
||||
}
|
||||
|
||||
PlayerBoard playerBoard = boards.computeIfAbsent(p, PlayerBoard::new);
|
||||
JigsawStudioBoardContext jigsawContext = currentJigsawContext(p);
|
||||
if (jigsawContext != null) {
|
||||
playerBoard.showJigsaw(jigsawContext);
|
||||
ToolSidebar toolSidebar = currentToolSidebar(p);
|
||||
if (toolSidebar != null) {
|
||||
playerBoard.showTool(toolSidebar);
|
||||
} else {
|
||||
playerBoard.showOrdinary();
|
||||
}
|
||||
}
|
||||
|
||||
public void applyJigsawContext(Player player, JigsawStudioBoardContext context) {
|
||||
Objects.requireNonNull(player, "Jigsaw Studio board player");
|
||||
Objects.requireNonNull(context, "Jigsaw Studio board context");
|
||||
/**
|
||||
* What a tool shows a player in a tool world: a title and styled lines, top to bottom, for as long as the player
|
||||
* stays in {@code worldId}. An empty title keeps the Iris board title.
|
||||
*/
|
||||
public record ToolSidebar(UUID worldId, ToolText title, List<ToolText> lines) {
|
||||
public ToolSidebar {
|
||||
Objects.requireNonNull(worldId, "worldId");
|
||||
Objects.requireNonNull(title, "title");
|
||||
lines = List.copyOf(lines);
|
||||
}
|
||||
}
|
||||
|
||||
public void applyToolSidebar(Player player, ToolSidebar sidebar) {
|
||||
Objects.requireNonNull(player, "Tool sidebar player");
|
||||
Objects.requireNonNull(sidebar, "Tool sidebar");
|
||||
if (!J.isOwnedByCurrentRegion(player)) {
|
||||
J.runEntity(player, () -> applyJigsawContext(player, context));
|
||||
J.runEntity(player, () -> applyToolSidebar(player, sidebar));
|
||||
return;
|
||||
}
|
||||
if (!player.isOnline()) {
|
||||
return;
|
||||
}
|
||||
jigsawContexts.put(player.getUniqueId(), context);
|
||||
if (context.worldId().equals(player.getWorld().getUID())) {
|
||||
toolSidebars.put(player.getUniqueId(), sidebar);
|
||||
if (sidebar.worldId().equals(player.getWorld().getUID())) {
|
||||
updatePlayer(player);
|
||||
}
|
||||
}
|
||||
|
||||
public void clearJigsawContext(Player player) {
|
||||
Objects.requireNonNull(player, "Jigsaw Studio board player");
|
||||
public void clearToolSidebar(Player player) {
|
||||
Objects.requireNonNull(player, "Tool sidebar player");
|
||||
if (!J.isOwnedByCurrentRegion(player)) {
|
||||
J.runEntity(player, () -> clearJigsawContext(player));
|
||||
J.runEntity(player, () -> clearToolSidebar(player));
|
||||
return;
|
||||
}
|
||||
jigsawContexts.remove(player.getUniqueId());
|
||||
toolSidebars.remove(player.getUniqueId());
|
||||
updatePlayer(player);
|
||||
}
|
||||
|
||||
@@ -211,7 +223,7 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
}
|
||||
PlayerBoard previousBoard = boards.get(player);
|
||||
boolean alreadyOrdinary = previousBoard != null && previousBoard.isOrdinary();
|
||||
jigsawContexts.remove(player.getUniqueId());
|
||||
toolSidebars.remove(player.getUniqueId());
|
||||
updatePlayer(player);
|
||||
PlayerBoard playerBoard = boards.get(player);
|
||||
if (alreadyOrdinary && playerBoard == previousBoard) {
|
||||
@@ -247,6 +259,10 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
|
||||
@Override
|
||||
public String getTitle(Player player) {
|
||||
PlayerBoard board = boards.get(player);
|
||||
if (board != null && board.view == BoardView.TOOL && !board.title.isEmpty()) {
|
||||
return board.title;
|
||||
}
|
||||
return IrisLanguage.text(BukkitUiMessages.SCOREBOARD_TITLE);
|
||||
}
|
||||
|
||||
@@ -275,45 +291,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
&& generator.getEngine() != null;
|
||||
}
|
||||
|
||||
static List<String> jigsawLines(JigsawStudioBoardContext context) {
|
||||
Objects.requireNonNull(context, "Jigsaw Studio board context");
|
||||
List<String> lines = new ArrayList<>(11);
|
||||
lines.add(SEPARATOR);
|
||||
lines.add("&dJigsaw Studio");
|
||||
lines.add("&bStructure&7: " + untrustedBoardValue(context.structureKey()));
|
||||
if (!context.insideWorkcell()) {
|
||||
lines.add("&bMode&7: " + context.modeDisplayName());
|
||||
lines.add(SEPARATOR);
|
||||
lines.add("&eWalk into a workcell");
|
||||
if (!context.controlHint().isEmpty()) {
|
||||
lines.add("&7" + untrustedBoardValue(context.controlHint()));
|
||||
}
|
||||
lines.add(SEPARATOR);
|
||||
return List.copyOf(lines);
|
||||
}
|
||||
|
||||
lines.add("&bWorkcell&7: " + untrustedBoardValue(context.workcellName()));
|
||||
if (!context.workcellRole().isEmpty() && !context.workcellRole().equals(context.workcellName())) {
|
||||
lines.add("&bRole&7: " + untrustedBoardValue(context.workcellRole()));
|
||||
}
|
||||
lines.add("&bVariant&7: " + untrustedBoardValue(
|
||||
context.variantName().isEmpty() ? "None" : context.variantName()));
|
||||
lines.add("&bState&7: " + context.state().displayName());
|
||||
lines.add(SEPARATOR);
|
||||
if (!context.controlHint().isEmpty()) {
|
||||
lines.add("&e" + untrustedBoardValue(context.controlHint()));
|
||||
}
|
||||
lines.add(SEPARATOR);
|
||||
return List.copyOf(lines);
|
||||
}
|
||||
|
||||
static boolean shouldRenderJigsaw(
|
||||
JigsawStudioBoardContext previous,
|
||||
JigsawStudioBoardContext next
|
||||
) {
|
||||
return !Objects.equals(previous, next);
|
||||
}
|
||||
|
||||
static String untrustedBoardValue(String value) {
|
||||
String normalized = value == null ? "" : value.replace('\n', ' ').replace('\r', ' ');
|
||||
return LEGACY_COLOR.matcher(normalized).replaceAll("")
|
||||
@@ -342,19 +319,50 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private JigsawStudioBoardContext currentJigsawContext(Player player) {
|
||||
JigsawStudioBoardContext context = jigsawContexts.get(player.getUniqueId());
|
||||
if (context == null || !context.worldId().equals(player.getWorld().getUID())) {
|
||||
private ToolSidebar currentToolSidebar(Player player) {
|
||||
ToolSidebar sidebar = toolSidebars.get(player.getUniqueId());
|
||||
if (sidebar == null || !sidebar.worldId().equals(player.getWorld().getUID())) {
|
||||
return null;
|
||||
}
|
||||
return context;
|
||||
return sidebar;
|
||||
}
|
||||
|
||||
static List<String> toolLines(ToolSidebar sidebar) {
|
||||
return sidebar.lines().stream().map(BoardSVC::boardLine).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code text} in the board's {@code &} codes: each span starts with its colour and styles, a span without a colour
|
||||
* resets after another, and the text of a span cannot carry codes of its own.
|
||||
*/
|
||||
static String boardLine(ToolText text) {
|
||||
StringBuilder line = new StringBuilder();
|
||||
for (ToolText.Span span : text.spans()) {
|
||||
if (span.color() != null) {
|
||||
line.append('&').append(span.color().code());
|
||||
} else if (!line.isEmpty()) {
|
||||
line.append("&r");
|
||||
}
|
||||
if (span.bold()) {
|
||||
line.append("&l");
|
||||
}
|
||||
if (span.italic()) {
|
||||
line.append("&o");
|
||||
}
|
||||
if (span.strikethrough()) {
|
||||
line.append("&m");
|
||||
}
|
||||
line.append(untrustedBoardValue(span.text()));
|
||||
}
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
public class PlayerBoard {
|
||||
private final Player player;
|
||||
private final Board board;
|
||||
private volatile List<String> lines;
|
||||
private volatile JigsawStudioBoardContext jigsawContext;
|
||||
private volatile ToolSidebar toolSidebar;
|
||||
private volatile String title;
|
||||
private volatile BoardView view;
|
||||
private volatile boolean cancelled;
|
||||
private volatile boolean ordinaryTickScheduled;
|
||||
@@ -363,7 +371,8 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
this.player = player;
|
||||
this.board = new Board(player, settings);
|
||||
this.lines = List.of();
|
||||
this.jigsawContext = null;
|
||||
this.toolSidebar = null;
|
||||
this.title = "";
|
||||
this.view = BoardView.NONE;
|
||||
this.cancelled = false;
|
||||
this.ordinaryTickScheduled = false;
|
||||
@@ -379,7 +388,7 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
}
|
||||
boolean switched = view != BoardView.ORDINARY;
|
||||
view = BoardView.ORDINARY;
|
||||
jigsawContext = null;
|
||||
toolSidebar = null;
|
||||
if (switched) {
|
||||
updateOrdinary();
|
||||
board.update();
|
||||
@@ -399,7 +408,7 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
return !cancelled && view == BoardView.ORDINARY;
|
||||
}
|
||||
|
||||
private void showJigsaw(JigsawStudioBoardContext context) {
|
||||
private void showTool(ToolSidebar sidebar) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
@@ -407,12 +416,13 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
yieldBoard(player, this);
|
||||
return;
|
||||
}
|
||||
if (view == BoardView.JIGSAW && !shouldRenderJigsaw(jigsawContext, context)) {
|
||||
if (view == BoardView.TOOL && sidebar.equals(toolSidebar)) {
|
||||
return;
|
||||
}
|
||||
view = BoardView.JIGSAW;
|
||||
jigsawContext = context;
|
||||
lines = jigsawLines(context);
|
||||
view = BoardView.TOOL;
|
||||
toolSidebar = sidebar;
|
||||
title = boardLine(sidebar.title());
|
||||
lines = toolLines(sidebar);
|
||||
board.update();
|
||||
}
|
||||
|
||||
@@ -444,9 +454,9 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
JigsawStudioBoardContext context = currentJigsawContext(player);
|
||||
if (context != null) {
|
||||
showJigsaw(context);
|
||||
ToolSidebar sidebar = currentToolSidebar(player);
|
||||
if (sidebar != null) {
|
||||
showTool(sidebar);
|
||||
return;
|
||||
}
|
||||
if (!board.ownsScoreboardAssignment()) {
|
||||
@@ -534,6 +544,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
private enum BoardView {
|
||||
NONE,
|
||||
ORDINARY,
|
||||
JIGSAW
|
||||
TOOL
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public record JigsawStudioBoardContext(
|
||||
UUID worldId,
|
||||
UUID requestId,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
String workcellRole,
|
||||
String workcellName,
|
||||
String variantName,
|
||||
JigsawStudioBoardState state,
|
||||
String controlHint
|
||||
) {
|
||||
public JigsawStudioBoardContext {
|
||||
worldId = Objects.requireNonNull(worldId, "Jigsaw Studio board world ID");
|
||||
requestId = Objects.requireNonNull(requestId, "Jigsaw Studio board request ID");
|
||||
structureKey = requireText(structureKey, "structure key");
|
||||
mode = Objects.requireNonNull(mode, "Jigsaw Studio board mode");
|
||||
workcellRole = optionalText(workcellRole);
|
||||
workcellName = optionalText(workcellName);
|
||||
variantName = optionalText(variantName);
|
||||
state = Objects.requireNonNull(state, "Jigsaw Studio board state");
|
||||
controlHint = optionalText(controlHint);
|
||||
if (workcellName.isEmpty() && (!workcellRole.isEmpty() || !variantName.isEmpty())) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio board variants require a workcell");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean insideWorkcell() {
|
||||
return !workcellName.isEmpty();
|
||||
}
|
||||
|
||||
public String modeDisplayName() {
|
||||
return switch (mode) {
|
||||
case PLANAR_JIGSAW -> "Planar";
|
||||
case SPATIAL_JIGSAW -> "Spatial";
|
||||
};
|
||||
}
|
||||
|
||||
private static String requireText(String value, String name) {
|
||||
String normalized = optionalText(value);
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio board " + name + " cannot be blank");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static String optionalText(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
public enum JigsawStudioBoardState {
|
||||
LOADING("Loading"),
|
||||
SAVED("Saved"),
|
||||
UNSAVED("Unsaved"),
|
||||
SAVING("Saving"),
|
||||
DISABLED("Disabled"),
|
||||
INVALID("Invalid"),
|
||||
READ_ONLY("Read-only");
|
||||
|
||||
private final String displayName;
|
||||
|
||||
JigsawStudioBoardState(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return displayName;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
public enum JigsawStudioEvaluationState {
|
||||
PENDING,
|
||||
VALID,
|
||||
WARNING,
|
||||
INVALID,
|
||||
STALE
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public record JigsawStudioGraphEvaluation(
|
||||
UUID requestId,
|
||||
long generation,
|
||||
long seed,
|
||||
JigsawStudioEvaluationState state,
|
||||
String selectedTheme,
|
||||
int pieceCount,
|
||||
String detail,
|
||||
JigsawStudioPreviewRenderer.PreviewBounds previewBounds
|
||||
) {
|
||||
public JigsawStudioGraphEvaluation {
|
||||
requestId = Objects.requireNonNull(requestId, "Jigsaw Studio evaluation request ID");
|
||||
if (generation < 1L) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio evaluation generation must be positive");
|
||||
}
|
||||
state = Objects.requireNonNull(state, "Jigsaw Studio evaluation state");
|
||||
selectedTheme = normalize(selectedTheme);
|
||||
if (pieceCount < 0) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio evaluation piece count cannot be negative");
|
||||
}
|
||||
detail = normalize(detail);
|
||||
previewBounds = Objects.requireNonNull(previewBounds, "Jigsaw Studio evaluation preview bounds");
|
||||
}
|
||||
|
||||
public JigsawStudioGraphEvaluation stale(String reason) {
|
||||
return new JigsawStudioGraphEvaluation(
|
||||
requestId,
|
||||
generation,
|
||||
seed,
|
||||
JigsawStudioEvaluationState.STALE,
|
||||
selectedTheme,
|
||||
pieceCount,
|
||||
reason,
|
||||
previewBounds);
|
||||
}
|
||||
|
||||
public boolean successful() {
|
||||
return state == JigsawStudioEvaluationState.VALID
|
||||
|| state == JigsawStudioEvaluationState.WARNING;
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -1,519 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
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.StructureLoss;
|
||||
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
|
||||
import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
|
||||
import art.arcane.iris.core.structure.authoring.StructureSource;
|
||||
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
|
||||
import art.arcane.iris.core.structure.authoring.StructureWriteOptions;
|
||||
import art.arcane.iris.core.structure.authoring.StructureWriteResult;
|
||||
import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
final class JigsawStudioHistoryStore {
|
||||
static final int MAX_ITERATIONS = 5;
|
||||
private static final int SCHEMA_VERSION = 1;
|
||||
private static final long MAX_HISTORY_BYTES = 512L * 1024L * 1024L;
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
private static final ConcurrentMap<Path, ReentrantLock> LOCKS = new ConcurrentHashMap<>();
|
||||
|
||||
private final Path packRoot;
|
||||
private final StructureKey structureKey;
|
||||
private final StructureTransactionWriter writer;
|
||||
private final Path historyPath;
|
||||
private final ReentrantLock lock;
|
||||
|
||||
JigsawStudioHistoryStore(Path packRoot, String structureKey) {
|
||||
this.packRoot = canonicalPackRoot(packRoot);
|
||||
this.structureKey = new StructureKey(
|
||||
"iris",
|
||||
Objects.requireNonNull(structureKey, "Jigsaw Studio history structure key"));
|
||||
writer = new StructureTransactionWriter(this.packRoot);
|
||||
String identityHash = StructureHash.sha256(this.structureKey.value().getBytes(StandardCharsets.UTF_8));
|
||||
historyPath = this.packRoot.resolve(".iris/jigsaw-history/key-" + identityHash + ".json").normalize();
|
||||
if (!historyPath.startsWith(this.packRoot)) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio history path escapes its pack root");
|
||||
}
|
||||
lock = LOCKS.computeIfAbsent(historyPath, ignored -> new ReentrantLock());
|
||||
}
|
||||
|
||||
Snapshot snapshotCurrent(String pieceKey) throws IOException {
|
||||
lock.lock();
|
||||
try {
|
||||
return readCurrentSnapshot(pieceKey);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
int append(Snapshot snapshot) throws IOException {
|
||||
Objects.requireNonNull(snapshot, "Jigsaw Studio history snapshot");
|
||||
lock.lock();
|
||||
try {
|
||||
HistoryDocument document = readDocument();
|
||||
if (!document.structure().equals(structureKey.value())) {
|
||||
throw new IOException("Jigsaw Studio history belongs to " + document.structure());
|
||||
}
|
||||
ArrayList<HistoryIteration> iterations = new ArrayList<>(document.iterations());
|
||||
HistoryIteration iteration = snapshot.iteration();
|
||||
if (!iterations.isEmpty() && iterations.getLast().sameState(iteration)) {
|
||||
return iterations.size();
|
||||
}
|
||||
iterations.add(iteration);
|
||||
while (iterations.size() > MAX_ITERATIONS) {
|
||||
iterations.removeFirst();
|
||||
}
|
||||
TreeMap<String, String> blobs = new TreeMap<>(document.blobs());
|
||||
for (Map.Entry<String, byte[]> resource : snapshot.resources().entrySet()) {
|
||||
String hash = StructureHash.sha256(resource.getValue());
|
||||
blobs.putIfAbsent(hash, Base64.getEncoder().encodeToString(resource.getValue()));
|
||||
}
|
||||
retainReferencedBlobs(blobs, iterations);
|
||||
writeDocument(new HistoryDocument(
|
||||
SCHEMA_VERSION,
|
||||
structureKey.value(),
|
||||
List.copyOf(iterations),
|
||||
Map.copyOf(blobs)));
|
||||
return iterations.size();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
UndoResult undoLatest() throws IOException {
|
||||
lock.lock();
|
||||
try {
|
||||
HistoryDocument document = readDocument();
|
||||
if (document.iterations().isEmpty()) {
|
||||
return UndoResult.unavailable();
|
||||
}
|
||||
HistoryIteration iteration = document.iterations().getLast();
|
||||
StructureResourceBundle bundle = restoreBundle(iteration, document.blobs());
|
||||
StructureResourceBundleGraphCompiler.requireViable(bundle);
|
||||
Path manifestPath = writer.ownershipManifestPath(structureKey);
|
||||
byte[] currentManifest = readRegularFile(manifestPath, "ownership manifest");
|
||||
StructureWriteResult result = writer.write(
|
||||
bundle,
|
||||
StructureWriteOptions.overwriteExpected(StructureHash.sha256(currentManifest)));
|
||||
if (!result.successful()) {
|
||||
return new UndoResult(
|
||||
false,
|
||||
true,
|
||||
document.iterations().size(),
|
||||
iteration.pieceKey(),
|
||||
result,
|
||||
"");
|
||||
}
|
||||
ArrayList<HistoryIteration> remaining = new ArrayList<>(document.iterations());
|
||||
remaining.removeLast();
|
||||
TreeMap<String, String> blobs = new TreeMap<>(document.blobs());
|
||||
retainReferencedBlobs(blobs, remaining);
|
||||
String warning = "";
|
||||
try {
|
||||
if (remaining.isEmpty()) {
|
||||
Files.deleteIfExists(historyPath);
|
||||
forceDirectory(historyPath.getParent());
|
||||
} else {
|
||||
writeDocument(new HistoryDocument(
|
||||
SCHEMA_VERSION,
|
||||
structureKey.value(),
|
||||
List.copyOf(remaining),
|
||||
Map.copyOf(blobs)));
|
||||
}
|
||||
} catch (IOException historyFailure) {
|
||||
warning = historyFailure.getMessage() == null
|
||||
? historyFailure.getClass().getSimpleName()
|
||||
: historyFailure.getMessage();
|
||||
}
|
||||
return new UndoResult(
|
||||
true,
|
||||
true,
|
||||
remaining.size(),
|
||||
iteration.pieceKey(),
|
||||
result,
|
||||
warning);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
int availableIterations() throws IOException {
|
||||
lock.lock();
|
||||
try {
|
||||
return readDocument().iterations().size();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
void delete() throws IOException {
|
||||
lock.lock();
|
||||
try {
|
||||
if (Files.deleteIfExists(historyPath)) {
|
||||
forceDirectory(historyPath.getParent());
|
||||
}
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
Path historyPath() {
|
||||
return historyPath;
|
||||
}
|
||||
|
||||
private Snapshot readCurrentSnapshot(String pieceKey) throws IOException {
|
||||
Path manifestPath = writer.ownershipManifestPath(structureKey);
|
||||
byte[] manifestContent = readRegularFile(manifestPath, "ownership manifest");
|
||||
StructureOwnershipManifest manifest;
|
||||
try {
|
||||
manifest = StructureOwnershipManifest.fromJson(manifestContent);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IOException("Jigsaw Studio history cannot parse the ownership manifest", exception);
|
||||
}
|
||||
if (!manifest.structure().equals(structureKey)) {
|
||||
throw new IOException("Jigsaw Studio ownership manifest belongs to " + manifest.structure());
|
||||
}
|
||||
TreeMap<String, byte[]> resources = new TreeMap<>();
|
||||
for (Map.Entry<String, String> resource : manifest.resourceHashes().entrySet()) {
|
||||
Path resourcePath = resolveOwnedResource(resource.getKey());
|
||||
byte[] content = readRegularFile(resourcePath, "owned resource " + resource.getKey());
|
||||
String actualHash = StructureHash.sha256(content);
|
||||
if (!resource.getValue().equals(actualHash)) {
|
||||
throw new IOException("Jigsaw Studio owned resource changed before history capture: "
|
||||
+ resource.getKey());
|
||||
}
|
||||
resources.put(resource.getKey(), content);
|
||||
}
|
||||
return new Snapshot(
|
||||
new HistoryIteration(
|
||||
System.currentTimeMillis(),
|
||||
Objects.requireNonNull(pieceKey, "Jigsaw Studio history piece key"),
|
||||
manifest.source(),
|
||||
manifest.backend(),
|
||||
manifest.capabilities(),
|
||||
manifest.losses(),
|
||||
manifest.resourceHashes()),
|
||||
resources);
|
||||
}
|
||||
|
||||
private StructureResourceBundle restoreBundle(
|
||||
HistoryIteration iteration,
|
||||
Map<String, String> blobs
|
||||
) throws IOException {
|
||||
StructureResourceBundle.Builder builder = StructureResourceBundle.builder(structureKey)
|
||||
.source(iteration.source())
|
||||
.backend(iteration.backend())
|
||||
.capabilities(iteration.capabilities())
|
||||
.losses(iteration.losses());
|
||||
for (Map.Entry<String, String> resource : iteration.resourceHashes().entrySet()) {
|
||||
String encoded = blobs.get(resource.getValue());
|
||||
if (encoded == null) {
|
||||
throw new IOException("Jigsaw Studio history is missing resource blob " + resource.getValue());
|
||||
}
|
||||
byte[] content;
|
||||
try {
|
||||
content = Base64.getDecoder().decode(encoded);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IOException("Jigsaw Studio history contains invalid resource data", exception);
|
||||
}
|
||||
if (!resource.getValue().equals(StructureHash.sha256(content))) {
|
||||
throw new IOException("Jigsaw Studio history resource hash does not match "
|
||||
+ resource.getKey());
|
||||
}
|
||||
builder.resource(resource.getKey(), content);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private HistoryDocument readDocument() throws IOException {
|
||||
if (!Files.exists(historyPath, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return HistoryDocument.empty(structureKey.value());
|
||||
}
|
||||
byte[] content = readRegularFile(historyPath, "history file");
|
||||
if (content.length > MAX_HISTORY_BYTES) {
|
||||
throw new IOException("Jigsaw Studio history exceeds " + MAX_HISTORY_BYTES + " bytes");
|
||||
}
|
||||
HistoryDocument document;
|
||||
try {
|
||||
document = GSON.fromJson(new String(content, StandardCharsets.UTF_8), HistoryDocument.class);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IOException("Jigsaw Studio history is invalid", exception);
|
||||
}
|
||||
if (document == null || document.schemaVersion() != SCHEMA_VERSION) {
|
||||
throw new IOException("Unsupported Jigsaw Studio history schema");
|
||||
}
|
||||
HistoryDocument validated;
|
||||
try {
|
||||
validated = document.validated();
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IOException("Jigsaw Studio history is invalid", exception);
|
||||
}
|
||||
if (!validated.structure().equals(structureKey.value())) {
|
||||
throw new IOException("Jigsaw Studio history belongs to " + validated.structure());
|
||||
}
|
||||
return validated;
|
||||
}
|
||||
|
||||
private void writeDocument(HistoryDocument document) throws IOException {
|
||||
HistoryDocument validated = document.validated();
|
||||
byte[] content = (GSON.toJson(validated) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
if (content.length > MAX_HISTORY_BYTES) {
|
||||
throw new IOException("Jigsaw Studio history exceeds " + MAX_HISTORY_BYTES + " bytes");
|
||||
}
|
||||
Path historyRoot = historyPath.getParent();
|
||||
Files.createDirectories(historyRoot);
|
||||
rejectSymbolicPath(historyRoot);
|
||||
Path temporary = historyRoot.resolve(historyPath.getFileName() + "."
|
||||
+ UUID.randomUUID() + ".tmp").normalize();
|
||||
try {
|
||||
try (FileChannel channel = FileChannel.open(
|
||||
temporary,
|
||||
StandardOpenOption.CREATE_NEW,
|
||||
StandardOpenOption.WRITE)) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(content);
|
||||
while (buffer.hasRemaining()) {
|
||||
channel.write(buffer);
|
||||
}
|
||||
channel.force(true);
|
||||
}
|
||||
try {
|
||||
Files.move(
|
||||
temporary,
|
||||
historyPath,
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException exception) {
|
||||
Files.move(temporary, historyPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
forceDirectory(historyRoot);
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
private Path resolveOwnedResource(String relativePath) throws IOException {
|
||||
StructureResourceBundle.validateRelativePath(relativePath);
|
||||
Path resource = packRoot.resolve(relativePath).normalize();
|
||||
if (!resource.startsWith(packRoot)) {
|
||||
throw new IOException("Jigsaw Studio history resource escapes its pack root: " + relativePath);
|
||||
}
|
||||
rejectSymbolicPath(resource.getParent());
|
||||
return resource;
|
||||
}
|
||||
|
||||
private static byte[] readRegularFile(Path path, String kind) throws IOException {
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Jigsaw Studio " + kind + " is missing or not a regular file: " + path);
|
||||
}
|
||||
return Files.readAllBytes(path);
|
||||
}
|
||||
|
||||
private static void retainReferencedBlobs(
|
||||
Map<String, String> blobs,
|
||||
List<HistoryIteration> iterations
|
||||
) {
|
||||
Set<String> retained = new TreeSet<>();
|
||||
for (HistoryIteration iteration : iterations) {
|
||||
retained.addAll(iteration.resourceHashes().values());
|
||||
}
|
||||
blobs.keySet().retainAll(retained);
|
||||
}
|
||||
|
||||
private void rejectSymbolicPath(Path path) throws IOException {
|
||||
Path current = path;
|
||||
while (current != null && current.startsWith(packRoot)) {
|
||||
if (Files.isSymbolicLink(current)) {
|
||||
throw new IOException("Jigsaw Studio history path contains a symbolic link: " + current);
|
||||
}
|
||||
if (current.equals(packRoot)) {
|
||||
return;
|
||||
}
|
||||
current = current.getParent();
|
||||
}
|
||||
throw new IOException("Jigsaw Studio history path escapes its pack root: " + path);
|
||||
}
|
||||
|
||||
private static Path canonicalPackRoot(Path root) {
|
||||
Path normalized = Objects.requireNonNull(root, "Jigsaw Studio history pack root")
|
||||
.toAbsolutePath().normalize();
|
||||
try {
|
||||
return normalized.toRealPath();
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio history pack root is unavailable: "
|
||||
+ normalized, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static void forceDirectory(Path directory) throws IOException {
|
||||
// A directory can only be opened and fsynced on a POSIX filesystem; Windows rejects the
|
||||
// open outright. Matches DirectoryDurability and DatapackIngestService, which already
|
||||
// skip the barrier there.
|
||||
if (!Files.getFileStore(directory).supportsFileAttributeView("posix")) {
|
||||
return;
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) {
|
||||
channel.force(true);
|
||||
}
|
||||
}
|
||||
|
||||
record Snapshot(HistoryIteration iteration, Map<String, byte[]> resources) {
|
||||
Snapshot {
|
||||
Objects.requireNonNull(iteration, "Jigsaw Studio history iteration");
|
||||
Objects.requireNonNull(resources, "Jigsaw Studio history resources");
|
||||
LinkedHashMap<String, byte[]> copies = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, byte[]> resource : resources.entrySet()) {
|
||||
copies.put(resource.getKey(), resource.getValue().clone());
|
||||
}
|
||||
resources = Map.copyOf(copies);
|
||||
}
|
||||
|
||||
boolean matches(StructureResourceBundle bundle) {
|
||||
if (!iteration.source().equals(bundle.source())
|
||||
|| iteration.backend() != bundle.backend()
|
||||
|| !Set.copyOf(iteration.capabilities()).equals(bundle.capabilities())
|
||||
|| !iteration.losses().equals(bundle.losses())
|
||||
|| iteration.resourceHashes().size() != bundle.resources().size()) {
|
||||
return false;
|
||||
}
|
||||
for (Map.Entry<String, StructureResourceBundle.Resource> resource
|
||||
: bundle.resources().entrySet()) {
|
||||
if (!resource.getValue().contentHash().equals(
|
||||
iteration.resourceHashes().get(resource.getKey()))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
record UndoResult(
|
||||
boolean successful,
|
||||
boolean available,
|
||||
int remainingIterations,
|
||||
String pieceKey,
|
||||
StructureWriteResult writeResult,
|
||||
String warning
|
||||
) {
|
||||
UndoResult {
|
||||
pieceKey = pieceKey == null ? "" : pieceKey;
|
||||
warning = warning == null ? "" : warning;
|
||||
}
|
||||
|
||||
static UndoResult unavailable() {
|
||||
return new UndoResult(false, false, 0, "", null, "");
|
||||
}
|
||||
}
|
||||
|
||||
private record HistoryDocument(
|
||||
int schemaVersion,
|
||||
String structure,
|
||||
List<HistoryIteration> iterations,
|
||||
Map<String, String> blobs
|
||||
) {
|
||||
private HistoryDocument {
|
||||
structure = structure == null ? "" : structure;
|
||||
iterations = iterations == null ? List.of() : List.copyOf(iterations);
|
||||
blobs = blobs == null ? Map.of() : Map.copyOf(blobs);
|
||||
}
|
||||
|
||||
private static HistoryDocument empty(String structure) {
|
||||
return new HistoryDocument(SCHEMA_VERSION, structure, List.of(), Map.of());
|
||||
}
|
||||
|
||||
private HistoryDocument validated() throws IOException {
|
||||
if (schemaVersion != SCHEMA_VERSION || structure.isBlank()) {
|
||||
throw new IOException("Jigsaw Studio history header is invalid");
|
||||
}
|
||||
if (iterations.size() > MAX_ITERATIONS) {
|
||||
throw new IOException("Jigsaw Studio history contains too many iterations");
|
||||
}
|
||||
TreeMap<String, String> validatedBlobs = new TreeMap<>();
|
||||
for (Map.Entry<String, String> blob : blobs.entrySet()) {
|
||||
if (!StructureHash.isSha256(blob.getKey()) || blob.getValue() == null) {
|
||||
throw new IOException("Jigsaw Studio history contains an invalid resource blob");
|
||||
}
|
||||
validatedBlobs.put(blob.getKey(), blob.getValue());
|
||||
}
|
||||
return new HistoryDocument(
|
||||
SCHEMA_VERSION,
|
||||
structure,
|
||||
List.copyOf(iterations),
|
||||
Map.copyOf(validatedBlobs));
|
||||
}
|
||||
}
|
||||
|
||||
private record HistoryIteration(
|
||||
long recordedAtEpochMilli,
|
||||
String pieceKey,
|
||||
StructureSource source,
|
||||
StructureBackend backend,
|
||||
List<StructureCapability> capabilities,
|
||||
List<StructureLoss> losses,
|
||||
Map<String, String> resourceHashes
|
||||
) {
|
||||
private HistoryIteration {
|
||||
pieceKey = Objects.requireNonNull(pieceKey, "Jigsaw Studio history piece key").trim();
|
||||
if (pieceKey.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio history piece key cannot be empty");
|
||||
}
|
||||
Objects.requireNonNull(source, "Jigsaw Studio history source");
|
||||
Objects.requireNonNull(backend, "Jigsaw Studio history backend");
|
||||
capabilities = List.copyOf(Objects.requireNonNull(
|
||||
capabilities,
|
||||
"Jigsaw Studio history capabilities"));
|
||||
losses = List.copyOf(Objects.requireNonNull(losses, "Jigsaw Studio history losses"));
|
||||
TreeMap<String, String> hashes = new TreeMap<>();
|
||||
for (Map.Entry<String, String> resource : Objects.requireNonNull(
|
||||
resourceHashes,
|
||||
"Jigsaw Studio history resource hashes").entrySet()) {
|
||||
String relativePath = StructureResourceBundle.validateRelativePath(resource.getKey());
|
||||
if (!StructureHash.isSha256(resource.getValue())) {
|
||||
throw new IllegalArgumentException("Invalid Jigsaw Studio history resource hash");
|
||||
}
|
||||
hashes.put(relativePath, resource.getValue());
|
||||
}
|
||||
if (hashes.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio history iteration cannot be empty");
|
||||
}
|
||||
resourceHashes = Map.copyOf(hashes);
|
||||
}
|
||||
|
||||
private boolean sameState(HistoryIteration other) {
|
||||
return source.equals(other.source)
|
||||
&& backend == other.backend
|
||||
&& pieceKey.equals(other.pieceKey)
|
||||
&& capabilities.equals(other.capabilities)
|
||||
&& losses.equals(other.losses)
|
||||
&& resourceHashes.equals(other.resourceHashes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMarkerKeyCodec;
|
||||
import art.arcane.iris.engine.object.value.IrisDirection;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
|
||||
import org.bukkit.block.Orientation;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
final class JigsawStudioMarkerParser {
|
||||
private JigsawStudioMarkerParser() {
|
||||
}
|
||||
|
||||
static IrisJigsawConnector parse(
|
||||
Map<String, Object> nbt,
|
||||
Orientation orientation,
|
||||
int x,
|
||||
int y,
|
||||
int z
|
||||
) {
|
||||
Map<String, Object> properties = Objects.requireNonNull(nbt, "Jigsaw marker NBT");
|
||||
Directions directions = directions(orientation);
|
||||
String jointName = requiredString(properties, "joint").toUpperCase(Locale.ROOT);
|
||||
JigsawJoint joint;
|
||||
try {
|
||||
joint = JigsawJoint.valueOf(jointName);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IllegalArgumentException("Unsupported jigsaw joint '" + jointName + "'", exception);
|
||||
}
|
||||
return new IrisJigsawConnector()
|
||||
.setPosition(new IrisPosition(x, y, z))
|
||||
.setDirection(directions.front())
|
||||
.setTop(directions.top())
|
||||
.setPool(JigsawStudioMarkerKeyCodec.decodePool(requiredString(properties, "pool")))
|
||||
.setName(requiredString(properties, "name"))
|
||||
.setTargetName(requiredString(properties, "target"))
|
||||
.setChannel(optionalString(properties, "channel"))
|
||||
.setJoint(joint)
|
||||
.setFinalState(requiredString(properties, "final_state"))
|
||||
.setSelectionPriority(optionalInt(properties, "selection_priority"))
|
||||
.setPlacementPriority(optionalInt(properties, "placement_priority"));
|
||||
}
|
||||
|
||||
static Directions directions(Orientation orientation) {
|
||||
return switch (Objects.requireNonNull(orientation, "Jigsaw orientation")) {
|
||||
case DOWN_EAST -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.EAST_POSITIVE_X);
|
||||
case DOWN_NORTH -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.NORTH_NEGATIVE_Z);
|
||||
case DOWN_SOUTH -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.SOUTH_POSITIVE_Z);
|
||||
case DOWN_WEST -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.WEST_NEGATIVE_X);
|
||||
case UP_EAST -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.EAST_POSITIVE_X);
|
||||
case UP_NORTH -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.NORTH_NEGATIVE_Z);
|
||||
case UP_SOUTH -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.SOUTH_POSITIVE_Z);
|
||||
case UP_WEST -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.WEST_NEGATIVE_X);
|
||||
case WEST_UP -> new Directions(IrisDirection.WEST_NEGATIVE_X, IrisDirection.UP_POSITIVE_Y);
|
||||
case EAST_UP -> new Directions(IrisDirection.EAST_POSITIVE_X, IrisDirection.UP_POSITIVE_Y);
|
||||
case NORTH_UP -> new Directions(IrisDirection.NORTH_NEGATIVE_Z, IrisDirection.UP_POSITIVE_Y);
|
||||
case SOUTH_UP -> new Directions(IrisDirection.SOUTH_POSITIVE_Z, IrisDirection.UP_POSITIVE_Y);
|
||||
};
|
||||
}
|
||||
|
||||
private static String requiredString(Map<String, Object> properties, String key) {
|
||||
Object value = properties.get(key);
|
||||
if (!(value instanceof String stringValue) || stringValue.isBlank()) {
|
||||
throw new IllegalArgumentException("Jigsaw marker requires non-empty string NBT '" + key + "'");
|
||||
}
|
||||
return stringValue.trim();
|
||||
}
|
||||
|
||||
private static String optionalString(Map<String, Object> properties, String key) {
|
||||
Object value = properties.get(key);
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
if (!(value instanceof String stringValue)) {
|
||||
throw new IllegalArgumentException("Jigsaw marker NBT '" + key + "' must be a string");
|
||||
}
|
||||
return stringValue.trim();
|
||||
}
|
||||
|
||||
private static int optionalInt(Map<String, Object> properties, String key) {
|
||||
Object value = properties.get(key);
|
||||
if (value == null) {
|
||||
return 0;
|
||||
}
|
||||
if (!(value instanceof Number number)) {
|
||||
throw new IllegalArgumentException("Jigsaw marker NBT '" + key + "' must be an integer");
|
||||
}
|
||||
long longValue = number.longValue();
|
||||
if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) {
|
||||
throw new IllegalArgumentException("Jigsaw marker NBT '" + key + "' is outside the integer range");
|
||||
}
|
||||
return (int) longValue;
|
||||
}
|
||||
|
||||
record Directions(IrisDirection front, IrisDirection top) {
|
||||
Directions {
|
||||
Objects.requireNonNull(front, "Jigsaw front direction");
|
||||
Objects.requireNonNull(top, "Jigsaw top direction");
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,290 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPieceRules;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public record JigsawStudioMenuState(
|
||||
UUID worldId,
|
||||
UUID requestId,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
boolean requireCaps,
|
||||
List<ThemeSet> themeSets,
|
||||
String selectedWorkcellId,
|
||||
Evaluation evaluation,
|
||||
List<Workcell> workcells
|
||||
) {
|
||||
public JigsawStudioMenuState {
|
||||
worldId = Objects.requireNonNull(worldId, "Jigsaw Studio menu world ID");
|
||||
requestId = Objects.requireNonNull(requestId, "Jigsaw Studio menu request ID");
|
||||
structureKey = requireText(structureKey, "structure key");
|
||||
mode = Objects.requireNonNull(mode, "Jigsaw Studio menu mode");
|
||||
compatibilityTarget = Objects.requireNonNull(
|
||||
compatibilityTarget,
|
||||
"Jigsaw Studio menu compatibility target");
|
||||
themeSets = List.copyOf(Objects.requireNonNull(themeSets, "Jigsaw Studio menu theme sets"));
|
||||
selectedWorkcellId = optionalText(selectedWorkcellId);
|
||||
evaluation = Objects.requireNonNull(evaluation, "Jigsaw Studio menu evaluation");
|
||||
workcells = List.copyOf(Objects.requireNonNull(workcells, "Jigsaw Studio menu workcells"));
|
||||
|
||||
Set<String> workcellIds = new HashSet<>();
|
||||
for (Workcell workcell : workcells) {
|
||||
Workcell resolved = Objects.requireNonNull(workcell, "Jigsaw Studio menu workcell");
|
||||
if (!workcellIds.add(resolved.stableId())) {
|
||||
throw new IllegalArgumentException("Duplicate Jigsaw Studio menu workcell " + resolved.stableId());
|
||||
}
|
||||
}
|
||||
if (!selectedWorkcellId.isEmpty() && !workcellIds.contains(selectedWorkcellId)) {
|
||||
throw new IllegalArgumentException("Selected Jigsaw Studio menu workcell is not present");
|
||||
}
|
||||
|
||||
Set<String> themeKeys = new HashSet<>();
|
||||
for (ThemeSet themeSet : themeSets) {
|
||||
ThemeSet resolved = Objects.requireNonNull(themeSet, "Jigsaw Studio menu theme set");
|
||||
if (!themeKeys.add(resolved.key())) {
|
||||
throw new IllegalArgumentException("Duplicate Jigsaw Studio menu theme " + resolved.key());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Workcell selectedWorkcell() {
|
||||
if (selectedWorkcellId.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return workcell(selectedWorkcellId);
|
||||
}
|
||||
|
||||
public boolean irisExtended() {
|
||||
return compatibilityTarget == JigsawStudioCompatibilityTarget.IRIS_EXTENDED;
|
||||
}
|
||||
|
||||
public Workcell workcell(String stableId) {
|
||||
if (stableId == null) {
|
||||
return null;
|
||||
}
|
||||
for (Workcell workcell : workcells) {
|
||||
if (workcell.stableId().equals(stableId)) {
|
||||
return workcell;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public ThemeSet themeSet(String key) {
|
||||
if (key == null) {
|
||||
return null;
|
||||
}
|
||||
for (ThemeSet themeSet : themeSets) {
|
||||
if (themeSet.key().equals(key)) {
|
||||
return themeSet;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public record ThemeSet(String key, int weight) {
|
||||
public ThemeSet {
|
||||
key = requireText(key, "theme key");
|
||||
if (weight < 1) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio menu theme weight must be positive");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Evaluation(
|
||||
JigsawStudioEvaluationState state,
|
||||
long generation,
|
||||
long seed,
|
||||
String selectedTheme,
|
||||
int pieceCount,
|
||||
String detail
|
||||
) {
|
||||
public Evaluation {
|
||||
state = Objects.requireNonNull(state, "Jigsaw Studio evaluation state");
|
||||
if (generation < 0L) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio evaluation generation cannot be negative");
|
||||
}
|
||||
selectedTheme = optionalText(selectedTheme);
|
||||
if (pieceCount < 0) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio evaluation piece count cannot be negative");
|
||||
}
|
||||
detail = optionalText(detail);
|
||||
}
|
||||
|
||||
public static Evaluation pending() {
|
||||
return new Evaluation(
|
||||
JigsawStudioEvaluationState.PENDING,
|
||||
0L,
|
||||
1337L,
|
||||
"",
|
||||
0,
|
||||
"Iris evaluates the graph automatically as authoring state changes.");
|
||||
}
|
||||
|
||||
public static Evaluation from(JigsawStudioGraphEvaluation evaluation) {
|
||||
JigsawStudioGraphEvaluation source = Objects.requireNonNull(
|
||||
evaluation,
|
||||
"Jigsaw Studio graph evaluation");
|
||||
return new Evaluation(
|
||||
source.state(),
|
||||
source.generation(),
|
||||
source.seed(),
|
||||
source.selectedTheme(),
|
||||
source.pieceCount(),
|
||||
source.detail());
|
||||
}
|
||||
}
|
||||
|
||||
public record Workcell(
|
||||
String stableId,
|
||||
String canonicalName,
|
||||
String displayName,
|
||||
JigsawStudioCellDimensions capacity,
|
||||
boolean enabled,
|
||||
String activeVariantKey,
|
||||
boolean dirty,
|
||||
boolean saving,
|
||||
boolean loading,
|
||||
boolean connectorsVisible,
|
||||
List<Variant> variants
|
||||
) {
|
||||
public Workcell {
|
||||
stableId = requireText(stableId, "workcell ID");
|
||||
canonicalName = requireText(canonicalName, "workcell canonical name");
|
||||
displayName = requireText(displayName, "workcell display name");
|
||||
capacity = Objects.requireNonNull(capacity, "Jigsaw Studio menu workcell capacity");
|
||||
activeVariantKey = optionalText(activeVariantKey);
|
||||
variants = List.copyOf(Objects.requireNonNull(variants, "Jigsaw Studio menu variants"));
|
||||
|
||||
Set<String> variantKeys = new HashSet<>();
|
||||
int activeVariants = 0;
|
||||
for (Variant variant : variants) {
|
||||
Variant resolved = Objects.requireNonNull(variant, "Jigsaw Studio menu variant");
|
||||
if (!variantKeys.add(resolved.pieceKey())) {
|
||||
throw new IllegalArgumentException("Duplicate Jigsaw Studio menu variant " + resolved.pieceKey());
|
||||
}
|
||||
if (resolved.active()) {
|
||||
activeVariants++;
|
||||
if (!resolved.pieceKey().equals(activeVariantKey)) {
|
||||
throw new IllegalArgumentException("Active Jigsaw Studio menu variant key does not match");
|
||||
}
|
||||
}
|
||||
}
|
||||
if ((activeVariantKey.isEmpty() && activeVariants != 0)
|
||||
|| (!activeVariantKey.isEmpty() && activeVariants != 1)) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio menu workcell active variant is inconsistent");
|
||||
}
|
||||
}
|
||||
|
||||
public Variant activeVariant() {
|
||||
if (activeVariantKey.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
for (Variant variant : variants) {
|
||||
if (variant.pieceKey().equals(activeVariantKey)) {
|
||||
return variant;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean busy() {
|
||||
return saving || loading;
|
||||
}
|
||||
}
|
||||
|
||||
public record Variant(
|
||||
String pieceKey,
|
||||
String displayName,
|
||||
Optional<JigsawStudioCellDimensions> dimensions,
|
||||
boolean active,
|
||||
boolean owned,
|
||||
boolean rotatable,
|
||||
boolean rotationEditable,
|
||||
boolean resizableToCapacity,
|
||||
List<String> themes,
|
||||
JigsawStudioPieceRules rules,
|
||||
List<Membership> memberships
|
||||
) {
|
||||
public Variant {
|
||||
pieceKey = requireText(pieceKey, "variant piece key");
|
||||
displayName = requireText(displayName, "variant display name");
|
||||
dimensions = Objects.requireNonNull(dimensions, "Jigsaw Studio menu variant dimensions");
|
||||
List<String> resolvedThemes = new ArrayList<>();
|
||||
Set<String> uniqueThemes = new HashSet<>();
|
||||
for (String theme : Objects.requireNonNull(themes, "Jigsaw Studio menu variant themes")) {
|
||||
String resolvedTheme = requireText(theme, "variant theme");
|
||||
if (!uniqueThemes.add(resolvedTheme)) {
|
||||
throw new IllegalArgumentException("Duplicate Jigsaw Studio menu variant theme "
|
||||
+ resolvedTheme);
|
||||
}
|
||||
resolvedThemes.add(resolvedTheme);
|
||||
}
|
||||
themes = List.copyOf(resolvedThemes);
|
||||
rules = Objects.requireNonNull(rules, "Jigsaw Studio menu variant rules");
|
||||
memberships = List.copyOf(Objects.requireNonNull(
|
||||
memberships,
|
||||
"Jigsaw Studio menu variant memberships"));
|
||||
if (rotationEditable && !owned) {
|
||||
throw new IllegalArgumentException("Read-only Jigsaw Studio variants cannot edit rotation");
|
||||
}
|
||||
if (resizableToCapacity && (!owned || !active)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Only the active owned Jigsaw Studio variant can resize to its workcell capacity");
|
||||
}
|
||||
|
||||
Set<MembershipIdentity> identities = new HashSet<>();
|
||||
for (Membership membership : memberships) {
|
||||
Membership resolved = Objects.requireNonNull(
|
||||
membership,
|
||||
"Jigsaw Studio menu variant membership");
|
||||
MembershipIdentity identity = new MembershipIdentity(resolved.poolKey(), resolved.entryIndex());
|
||||
if (!identities.add(identity)) {
|
||||
throw new IllegalArgumentException("Duplicate Jigsaw Studio menu membership "
|
||||
+ resolved.poolKey() + "[" + resolved.entryIndex() + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Membership(String poolKey, int entryIndex, int weight, double chance) {
|
||||
public Membership {
|
||||
poolKey = requireText(poolKey, "membership pool key");
|
||||
if (entryIndex < 0) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio menu membership index cannot be negative");
|
||||
}
|
||||
if (weight < 1) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio menu membership weight must be positive");
|
||||
}
|
||||
if (!Double.isFinite(chance) || chance < 0D || chance > 1D) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio menu membership chance must be within 0 and 1");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record MembershipIdentity(String poolKey, int entryIndex) {
|
||||
}
|
||||
|
||||
private static String requireText(String value, String name) {
|
||||
String normalized = optionalText(value);
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio menu " + name + " cannot be blank");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static String optionalText(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -1,456 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.engine.framework.PlacedStructurePiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.ObjectTurn;
|
||||
import art.arcane.iris.engine.object.prefab.BlockStateRotation;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class JigsawStudioPreviewRenderer {
|
||||
private static final int MAX_BLOCKS = 250_000;
|
||||
private static final String AIR = "minecraft:air";
|
||||
private static final String STRUCTURE_VOID = "minecraft:structure_void";
|
||||
|
||||
private final Map<UUID, RenderState> requests = new HashMap<>();
|
||||
|
||||
public static PreviewPlan plan(List<PlacedStructurePiece> pieces) throws IOException {
|
||||
List<PlacedStructurePiece> source = List.copyOf(Objects.requireNonNull(
|
||||
pieces,
|
||||
"Jigsaw Studio preview pieces"));
|
||||
if (source.isEmpty()) {
|
||||
return PreviewPlan.empty();
|
||||
}
|
||||
Map<BlockPosition, String> blocks = new LinkedHashMap<>();
|
||||
int minimumX = Integer.MAX_VALUE;
|
||||
int minimumY = Integer.MAX_VALUE;
|
||||
int minimumZ = Integer.MAX_VALUE;
|
||||
int maximumX = Integer.MIN_VALUE;
|
||||
int maximumY = Integer.MIN_VALUE;
|
||||
int maximumZ = Integer.MIN_VALUE;
|
||||
for (PlacedStructurePiece piece : source) {
|
||||
if (piece == null || piece.getObject() == null || piece.getPiece() == null
|
||||
|| piece.getRotation() == null) {
|
||||
throw new IOException("Jigsaw Studio preview contains an incomplete placed piece");
|
||||
}
|
||||
minimumX = Math.min(minimumX, piece.getMinX());
|
||||
minimumY = Math.min(minimumY, piece.getMinY());
|
||||
minimumZ = Math.min(minimumZ, piece.getMinZ());
|
||||
maximumX = Math.max(maximumX, piece.getMaxX());
|
||||
maximumY = Math.max(maximumY, piece.getMaxY());
|
||||
maximumZ = Math.max(maximumZ, piece.getMaxZ());
|
||||
appendObject(blocks, piece);
|
||||
appendFinalStates(blocks, piece);
|
||||
if (blocks.size() > MAX_BLOCKS) {
|
||||
throw new IOException("The seed-1337 preview exceeds the Studio render limit of "
|
||||
+ MAX_BLOCKS + " explicit blocks");
|
||||
}
|
||||
}
|
||||
return new PreviewPlan(
|
||||
Map.copyOf(blocks),
|
||||
new PreviewBounds(minimumX, minimumY, minimumZ, maximumX, maximumY, maximumZ));
|
||||
}
|
||||
|
||||
public void render(
|
||||
World world,
|
||||
UUID requestId,
|
||||
long generation,
|
||||
PreviewPlan plan,
|
||||
Consumer<RenderResult> completion
|
||||
) {
|
||||
World activeWorld = Objects.requireNonNull(world, "Jigsaw Studio preview world");
|
||||
UUID activeRequestId = Objects.requireNonNull(requestId, "Jigsaw Studio preview request ID");
|
||||
PreviewPlan activePlan = Objects.requireNonNull(plan, "Jigsaw Studio preview plan");
|
||||
Consumer<RenderResult> callback = Objects.requireNonNull(completion, "Jigsaw Studio preview callback");
|
||||
Map<BlockPosition, String> previous;
|
||||
Set<BlockPosition> uncertain;
|
||||
Map<Long, List<BlockUpdate>> updates;
|
||||
synchronized (this) {
|
||||
RenderState old = requests.get(activeRequestId);
|
||||
previous = old == null || !old.worldId().equals(activeWorld.getUID())
|
||||
? Map.of()
|
||||
: old.blocks();
|
||||
uncertain = old == null || !old.worldId().equals(activeWorld.getUID())
|
||||
? Set.of()
|
||||
: Set.copyOf(old.pending());
|
||||
updates = updates(previous, activePlan.blocks(), uncertain);
|
||||
Set<BlockPosition> pending = new HashSet<>();
|
||||
for (List<BlockUpdate> chunkUpdates : updates.values()) {
|
||||
for (BlockUpdate update : chunkUpdates) {
|
||||
pending.add(update.position());
|
||||
}
|
||||
}
|
||||
requests.put(activeRequestId, new RenderState(
|
||||
activeWorld.getUID(), generation, activePlan.blocks(), activePlan.bounds(), pending));
|
||||
}
|
||||
if (updates.isEmpty()) {
|
||||
callback.accept(new RenderResult(true, 0, ""));
|
||||
return;
|
||||
}
|
||||
AtomicInteger remaining = new AtomicInteger(updates.size());
|
||||
AtomicBoolean failed = new AtomicBoolean();
|
||||
for (Map.Entry<Long, List<BlockUpdate>> chunk : updates.entrySet()) {
|
||||
int chunkX = chunkX(chunk.getKey());
|
||||
int chunkZ = chunkZ(chunk.getKey());
|
||||
boolean scheduled = J.runRegion(
|
||||
activeWorld,
|
||||
chunkX,
|
||||
chunkZ,
|
||||
() -> applyChunk(
|
||||
activeWorld,
|
||||
activeRequestId,
|
||||
generation,
|
||||
chunk.getValue(),
|
||||
remaining,
|
||||
failed,
|
||||
callback));
|
||||
if (!scheduled) {
|
||||
failed.set(true);
|
||||
if (remaining.decrementAndGet() == 0) {
|
||||
callback.accept(new RenderResult(
|
||||
false,
|
||||
activePlan.blocks().size(),
|
||||
"One or more preview chunks could not be scheduled"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized PreviewBounds bounds(UUID requestId) {
|
||||
RenderState state = requests.get(requestId);
|
||||
return state == null ? null : state.bounds();
|
||||
}
|
||||
|
||||
public synchronized boolean contains(UUID requestId, int x, int y, int z) {
|
||||
RenderState state = requests.get(requestId);
|
||||
return state != null && state.bounds().contains(x, y, z);
|
||||
}
|
||||
|
||||
public void removeRequest(UUID requestId) {
|
||||
if (requestId == null) {
|
||||
return;
|
||||
}
|
||||
RenderState removed;
|
||||
synchronized (this) {
|
||||
removed = requests.remove(requestId);
|
||||
}
|
||||
if (removed != null) {
|
||||
World world = Bukkit.getWorld(removed.worldId());
|
||||
if (world != null) {
|
||||
clear(world, removalPositions(removed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void forgetRequest(UUID requestId) {
|
||||
if (requestId == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (this) {
|
||||
requests.remove(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAll() {
|
||||
Map<UUID, RenderState> removed;
|
||||
synchronized (this) {
|
||||
removed = Map.copyOf(requests);
|
||||
requests.clear();
|
||||
}
|
||||
for (RenderState state : removed.values()) {
|
||||
World world = Bukkit.getWorld(state.worldId());
|
||||
if (world != null) {
|
||||
clear(world, removalPositions(state));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendObject(
|
||||
Map<BlockPosition, String> blocks,
|
||||
PlacedStructurePiece piece
|
||||
) throws IOException {
|
||||
IrisObject object = piece.getObject();
|
||||
ObjectTurn rotation = piece.getRotation();
|
||||
for (Map.Entry<IrisBlockVector, PlatformBlockState> entry : object.getBlocks()) {
|
||||
IrisBlockVector rotated = rotation.rotate(entry.getKey());
|
||||
PlatformBlockState state = BlockStateRotation.rotate(rotation, entry.getValue());
|
||||
putState(
|
||||
blocks,
|
||||
new BlockPosition(
|
||||
piece.getX() + rotated.getBlockX(),
|
||||
piece.getY() + rotated.getBlockY(),
|
||||
piece.getZ() + rotated.getBlockZ()),
|
||||
state,
|
||||
"object block");
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendFinalStates(
|
||||
Map<BlockPosition, String> blocks,
|
||||
PlacedStructurePiece piece
|
||||
) throws IOException {
|
||||
IrisObject object = piece.getObject();
|
||||
ObjectTurn rotation = piece.getRotation();
|
||||
if (piece.getPiece().getConnectors() == null) {
|
||||
return;
|
||||
}
|
||||
for (IrisJigsawConnector connector : piece.getPiece().getConnectors()) {
|
||||
if (connector == null || connector.getPosition() == null) {
|
||||
throw new IOException("Jigsaw Studio preview contains an incomplete connector");
|
||||
}
|
||||
IrisBlockVector signed = new IrisBlockVector(
|
||||
connector.getPosition().getX() - object.getCenter().getBlockX(),
|
||||
connector.getPosition().getY() - object.getCenter().getBlockY(),
|
||||
connector.getPosition().getZ() - object.getCenter().getBlockZ());
|
||||
IrisBlockVector rotated = rotation.rotate(signed);
|
||||
PlatformBlockState source = B.getStateOrNull(connector.getFinalState(), false);
|
||||
PlatformBlockState state = source == null ? null : BlockStateRotation.rotate(rotation, source);
|
||||
putState(
|
||||
blocks,
|
||||
new BlockPosition(
|
||||
piece.getX() + rotated.getBlockX(),
|
||||
piece.getY() + rotated.getBlockY(),
|
||||
piece.getZ() + rotated.getBlockZ()),
|
||||
state,
|
||||
"connector final state");
|
||||
}
|
||||
}
|
||||
|
||||
private static void putState(
|
||||
Map<BlockPosition, String> blocks,
|
||||
BlockPosition position,
|
||||
PlatformBlockState state,
|
||||
String source
|
||||
) throws IOException {
|
||||
if (state == null || state.key() == null || state.key().isBlank()) {
|
||||
throw new IOException("Jigsaw Studio preview could not resolve a " + source);
|
||||
}
|
||||
String key = state.key();
|
||||
if (AIR.equals(key) || STRUCTURE_VOID.equals(key)) {
|
||||
blocks.remove(position);
|
||||
return;
|
||||
}
|
||||
blocks.put(position, key);
|
||||
}
|
||||
|
||||
private void applyChunk(
|
||||
World world,
|
||||
UUID requestId,
|
||||
long generation,
|
||||
List<BlockUpdate> updates,
|
||||
AtomicInteger remaining,
|
||||
AtomicBoolean failed,
|
||||
Consumer<RenderResult> completion
|
||||
) {
|
||||
int changed = 0;
|
||||
List<BlockPosition> applied = new ArrayList<>(updates.size());
|
||||
try {
|
||||
if (!isCurrent(world.getUID(), requestId, generation)) {
|
||||
return;
|
||||
}
|
||||
for (BlockUpdate update : updates) {
|
||||
Block block = world.getBlockAt(update.position().x(), update.position().y(), update.position().z());
|
||||
BlockData data = Bukkit.createBlockData(update.stateKey());
|
||||
block.setBlockData(data, false);
|
||||
applied.add(update.position());
|
||||
changed++;
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
failed.set(true);
|
||||
IrisLogging.reportError(exception);
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
RenderState active = requests.get(requestId);
|
||||
if (active != null
|
||||
&& active.worldId().equals(world.getUID())
|
||||
&& active.generation() == generation) {
|
||||
active.pending().removeAll(applied);
|
||||
}
|
||||
}
|
||||
if (remaining.decrementAndGet() == 0) {
|
||||
RenderState state;
|
||||
boolean pendingEmpty;
|
||||
synchronized (this) {
|
||||
state = requests.get(requestId);
|
||||
pendingEmpty = state != null && state.pending().isEmpty();
|
||||
}
|
||||
boolean current = state != null
|
||||
&& state.worldId().equals(world.getUID())
|
||||
&& state.generation() == generation;
|
||||
completion.accept(new RenderResult(
|
||||
current && pendingEmpty && !failed.get(),
|
||||
current ? state.blocks().size() : changed,
|
||||
failed.get() || current && !pendingEmpty
|
||||
? "One or more preview blocks could not be rendered"
|
||||
: ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized boolean isCurrent(UUID worldId, UUID requestId, long generation) {
|
||||
RenderState state = requests.get(requestId);
|
||||
return state != null && state.worldId().equals(worldId) && state.generation() == generation;
|
||||
}
|
||||
|
||||
private static Map<Long, List<BlockUpdate>> updates(
|
||||
Map<BlockPosition, String> previous,
|
||||
Map<BlockPosition, String> next,
|
||||
Set<BlockPosition> uncertain
|
||||
) {
|
||||
Set<BlockPosition> positions = new HashSet<>(previous.keySet());
|
||||
positions.addAll(next.keySet());
|
||||
positions.addAll(uncertain);
|
||||
Map<Long, List<BlockUpdate>> updates = new HashMap<>();
|
||||
for (BlockPosition position : positions) {
|
||||
String nextState = next.getOrDefault(position, AIR);
|
||||
if (!requiresUpdate(position, previous, next, uncertain)) {
|
||||
continue;
|
||||
}
|
||||
updates.computeIfAbsent(
|
||||
chunkKey(position.x() >> 4, position.z() >> 4),
|
||||
ignored -> new ArrayList<>()).add(new BlockUpdate(position, nextState));
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
|
||||
static boolean requiresUpdate(
|
||||
BlockPosition position,
|
||||
Map<BlockPosition, String> previous,
|
||||
Map<BlockPosition, String> next,
|
||||
Set<BlockPosition> uncertain
|
||||
) {
|
||||
return uncertain.contains(position)
|
||||
|| !next.getOrDefault(position, AIR).equals(previous.get(position));
|
||||
}
|
||||
|
||||
private static void clear(World world, Set<BlockPosition> positions) {
|
||||
Map<Long, List<BlockUpdate>> updates = new HashMap<>();
|
||||
for (BlockPosition position : positions) {
|
||||
updates.computeIfAbsent(
|
||||
chunkKey(position.x() >> 4, position.z() >> 4),
|
||||
ignored -> new ArrayList<>()).add(new BlockUpdate(position, AIR));
|
||||
}
|
||||
for (Map.Entry<Long, List<BlockUpdate>> chunk : updates.entrySet()) {
|
||||
J.runRegion(world, chunkX(chunk.getKey()), chunkZ(chunk.getKey()), () -> {
|
||||
for (BlockUpdate update : chunk.getValue()) {
|
||||
world.getBlockAt(
|
||||
update.position().x(),
|
||||
update.position().y(),
|
||||
update.position().z())
|
||||
.setType(Material.AIR, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<BlockPosition> removalPositions(RenderState state) {
|
||||
Set<BlockPosition> positions = new HashSet<>(state.blocks().keySet());
|
||||
positions.addAll(state.pending());
|
||||
return Set.copyOf(positions);
|
||||
}
|
||||
|
||||
private static long chunkKey(int chunkX, int chunkZ) {
|
||||
return ((long) chunkX << 32) ^ (chunkZ & 0xffffffffL);
|
||||
}
|
||||
|
||||
private static int chunkX(long chunkKey) {
|
||||
return (int) (chunkKey >> 32);
|
||||
}
|
||||
|
||||
private static int chunkZ(long chunkKey) {
|
||||
return (int) chunkKey;
|
||||
}
|
||||
|
||||
public record PreviewPlan(Map<BlockPosition, String> blocks, PreviewBounds bounds) {
|
||||
public PreviewPlan {
|
||||
blocks = Map.copyOf(Objects.requireNonNull(blocks, "Jigsaw Studio preview blocks"));
|
||||
bounds = Objects.requireNonNull(bounds, "Jigsaw Studio preview bounds");
|
||||
}
|
||||
|
||||
static PreviewPlan empty() {
|
||||
return new PreviewPlan(Map.of(), PreviewBounds.empty());
|
||||
}
|
||||
}
|
||||
|
||||
public record PreviewBounds(
|
||||
int minimumX,
|
||||
int minimumY,
|
||||
int minimumZ,
|
||||
int maximumX,
|
||||
int maximumY,
|
||||
int maximumZ
|
||||
) {
|
||||
static PreviewBounds empty() {
|
||||
return new PreviewBounds(0, 0, 0, -1, -1, -1);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return maximumX < minimumX || maximumY < minimumY || maximumZ < minimumZ;
|
||||
}
|
||||
|
||||
public int centerX() {
|
||||
return isEmpty() ? 0 : minimumX + (maximumX - minimumX) / 2;
|
||||
}
|
||||
|
||||
public int centerZ() {
|
||||
return isEmpty() ? 0 : minimumZ + (maximumZ - minimumZ) / 2;
|
||||
}
|
||||
|
||||
public boolean contains(int x, int y, int z) {
|
||||
return !isEmpty()
|
||||
&& x >= minimumX && x <= maximumX
|
||||
&& y >= minimumY && y <= maximumY
|
||||
&& z >= minimumZ && z <= maximumZ;
|
||||
}
|
||||
}
|
||||
|
||||
public record BlockPosition(int x, int y, int z) {
|
||||
}
|
||||
|
||||
public record RenderResult(boolean successful, int blockCount, String failure) {
|
||||
public RenderResult {
|
||||
failure = failure == null ? "" : failure;
|
||||
}
|
||||
}
|
||||
|
||||
private record RenderState(
|
||||
UUID worldId,
|
||||
long generation,
|
||||
Map<BlockPosition, String> blocks,
|
||||
PreviewBounds bounds,
|
||||
Set<BlockPosition> pending
|
||||
) {
|
||||
private RenderState {
|
||||
Objects.requireNonNull(worldId, "Jigsaw Studio preview world ID");
|
||||
blocks = Map.copyOf(Objects.requireNonNull(blocks, "Jigsaw Studio preview state blocks"));
|
||||
bounds = Objects.requireNonNull(bounds, "Jigsaw Studio preview state bounds");
|
||||
pending = Objects.requireNonNull(pending, "Jigsaw Studio preview pending blocks");
|
||||
}
|
||||
}
|
||||
|
||||
private record BlockUpdate(BlockPosition position, String stateKey) {
|
||||
}
|
||||
}
|
||||
-185
@@ -1,185 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.pack.StructurePackageClosure;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioAuthoringAccess;
|
||||
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.StructureResourceBundle;
|
||||
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
final class JigsawStudioResourceBundleAssembler {
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
private JigsawStudioResourceBundleAssembler() {
|
||||
}
|
||||
|
||||
static Assembly assemble(
|
||||
Path packRoot,
|
||||
String structureKey,
|
||||
String pieceKey,
|
||||
byte[] objectContent,
|
||||
List<IrisJigsawConnector> connectors,
|
||||
boolean hasBlockEntities
|
||||
) throws IOException {
|
||||
Path root = Objects.requireNonNull(packRoot, "Jigsaw Studio pack root").toAbsolutePath().normalize();
|
||||
String rootStructure = requireResourceKey(structureKey, "structure");
|
||||
String editedPiece = requireResourceKey(pieceKey, "piece");
|
||||
StructureKey ownershipKey = new StructureKey("iris", rootStructure);
|
||||
StructureTransactionWriter writer = new StructureTransactionWriter(root);
|
||||
Path manifestPath = writer.ownershipManifestPath(ownershipKey);
|
||||
if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Jigsaw Studio cannot save '" + rootStructure
|
||||
+ "' because it is not Studio-owned. Existing unowned graphs are read-only; create a new Jigsaw Studio project to author in-game.");
|
||||
}
|
||||
byte[] manifestContent = Files.readAllBytes(manifestPath);
|
||||
StructureOwnershipManifest manifest;
|
||||
try {
|
||||
manifest = StructureOwnershipManifest.fromJson(manifestContent);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IOException("Jigsaw Studio cannot read the ownership manifest for '" + rootStructure + "'", exception);
|
||||
}
|
||||
JigsawStudioAuthoringAccess.requireEditable(manifest);
|
||||
if (!manifest.structure().equals(ownershipKey)) {
|
||||
throw new IOException("Jigsaw Studio ownership manifest belongs to " + manifest.structure()
|
||||
+ ", not " + ownershipKey);
|
||||
}
|
||||
|
||||
StructurePackageClosure closure = StructurePackageClosure.collect(root.toFile(), List.of(rootStructure));
|
||||
if (!closure.isValid()) {
|
||||
throw new IOException("Jigsaw Studio cannot save an invalid structure graph: "
|
||||
+ String.join("; ", closure.errors()));
|
||||
}
|
||||
Set<String> reachablePaths = resourcePaths(closure);
|
||||
for (String relativePath : reachablePaths) {
|
||||
if (!manifest.resourceHashes().containsKey(relativePath)) {
|
||||
throw new IOException("Jigsaw Studio ownership conflict: reachable resource '" + relativePath
|
||||
+ "' is not owned by structure '" + rootStructure + "'.");
|
||||
}
|
||||
}
|
||||
|
||||
String piecePath = "jigsaw-pieces/" + editedPiece + ".json";
|
||||
if (!manifest.resourceHashes().containsKey(piecePath)) {
|
||||
throw new IOException("Jigsaw Studio ownership conflict: piece '" + editedPiece
|
||||
+ "' is not owned by structure '" + rootStructure + "'.");
|
||||
}
|
||||
Path absolutePiecePath = resolveOwnedResource(root, piecePath);
|
||||
IrisJigsawPiece piece;
|
||||
JsonObject pieceJson;
|
||||
try {
|
||||
JsonElement parsed = GSON.fromJson(
|
||||
Files.readString(absolutePiecePath, StandardCharsets.UTF_8),
|
||||
JsonElement.class);
|
||||
if (parsed == null || !parsed.isJsonObject()) {
|
||||
throw new IllegalArgumentException("Jigsaw piece is not a JSON object");
|
||||
}
|
||||
pieceJson = parsed.getAsJsonObject();
|
||||
piece = GSON.fromJson(pieceJson, IrisJigsawPiece.class);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IOException("Jigsaw Studio cannot parse piece '" + editedPiece + "'", exception);
|
||||
}
|
||||
if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) {
|
||||
throw new IOException("Jigsaw Studio piece '" + editedPiece + "' does not declare an object");
|
||||
}
|
||||
String objectKey = requireResourceKey(piece.getObject(), "object");
|
||||
String objectPath = "objects/" + objectKey + ".iob";
|
||||
if (!manifest.resourceHashes().containsKey(objectPath)) {
|
||||
throw new IOException("Jigsaw Studio ownership conflict: object '" + objectKey
|
||||
+ "' is not owned by structure '" + rootStructure + "'.");
|
||||
}
|
||||
piece.setConnectors(new KList<>(List.copyOf(connectors)));
|
||||
pieceJson.add("connectors", GSON.toJsonTree(piece.getConnectors()));
|
||||
|
||||
StructureResourceBundle.Builder bundle = StructureResourceBundle.builder(ownershipKey)
|
||||
.source(manifest.source())
|
||||
.backend(manifest.backend())
|
||||
.capabilities(manifest.capabilities())
|
||||
.losses(manifest.losses())
|
||||
.capability(StructureCapability.CONNECTORS);
|
||||
if (hasBlockEntities) {
|
||||
bundle.capability(StructureCapability.BLOCK_ENTITIES);
|
||||
}
|
||||
for (String relativePath : manifest.resourceHashes().keySet()) {
|
||||
if (relativePath.equals(piecePath)) {
|
||||
bundle.textResource(relativePath, GSON.toJson(pieceJson) + "\n");
|
||||
} else if (relativePath.equals(objectPath)) {
|
||||
bundle.resource(relativePath, objectContent);
|
||||
} else {
|
||||
Path resource = resolveOwnedResource(root, relativePath);
|
||||
bundle.resource(relativePath, Files.readAllBytes(resource));
|
||||
}
|
||||
}
|
||||
return new Assembly(bundle.build(), objectKey, piece, StructureHash.sha256(manifestContent));
|
||||
}
|
||||
|
||||
private static Set<String> resourcePaths(StructurePackageClosure closure) {
|
||||
Set<String> resources = new LinkedHashSet<>();
|
||||
addPaths(resources, "structures", closure.structures(), ".json");
|
||||
addPaths(resources, "jigsaw-pools", closure.pools(), ".json");
|
||||
addPaths(resources, "jigsaw-pieces", closure.pieces(), ".json");
|
||||
addPaths(resources, "objects", closure.objects(), ".iob");
|
||||
addPaths(resources, "loot", closure.loot(), ".json");
|
||||
return resources;
|
||||
}
|
||||
|
||||
private static void addPaths(Set<String> resources, String folder, Set<String> keys, String extension) {
|
||||
for (String key : keys) {
|
||||
resources.add(folder + "/" + key + extension);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path resolveOwnedResource(Path root, String relativePath) throws IOException {
|
||||
StructureResourceBundle.validateRelativePath(relativePath);
|
||||
Path resource = root.resolve(relativePath).normalize();
|
||||
if (!resource.startsWith(root)) {
|
||||
throw new IOException("Jigsaw Studio resource escapes its pack root: " + relativePath);
|
||||
}
|
||||
if (!Files.isRegularFile(resource, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Jigsaw Studio owned resource is missing or not a regular file: " + relativePath);
|
||||
}
|
||||
Path realRoot = root.toRealPath();
|
||||
Path realResource = resource.toRealPath();
|
||||
if (!realResource.startsWith(realRoot)) {
|
||||
throw new IOException("Jigsaw Studio owned resource escapes through a symbolic link: " + relativePath);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
private static String requireResourceKey(String key, String kind) {
|
||||
String normalized = Objects.requireNonNull(key, "Jigsaw Studio " + kind + " key").trim();
|
||||
StructureResourceBundle.validateRelativePath(normalized);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
record Assembly(
|
||||
StructureResourceBundle bundle,
|
||||
String objectKey,
|
||||
IrisJigsawPiece piece,
|
||||
String expectedManifestHash
|
||||
) {
|
||||
Assembly {
|
||||
Objects.requireNonNull(bundle, "Jigsaw Studio resource bundle");
|
||||
Objects.requireNonNull(objectKey, "Jigsaw Studio object key");
|
||||
Objects.requireNonNull(piece, "Jigsaw Studio piece");
|
||||
Objects.requireNonNull(expectedManifestHash, "Jigsaw Studio expected manifest hash");
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,150 +0,0 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class JigsawStudioToolCodec {
|
||||
static final NamespacedKey SCHEMA_KEY = new NamespacedKey("iris", "jigsaw_tool_schema");
|
||||
static final NamespacedKey ACTION_KEY = new NamespacedKey("iris", "jigsaw_tool_action");
|
||||
static final NamespacedKey REQUEST_KEY = new NamespacedKey("iris", "jigsaw_tool_request");
|
||||
static final NamespacedKey WORKCELL_KEY = new NamespacedKey("iris", "jigsaw_tool_workcell");
|
||||
static final NamespacedKey PIECE_KEY = new NamespacedKey("iris", "jigsaw_tool_piece");
|
||||
static final NamespacedKey POOL_KEY = new NamespacedKey("iris", "jigsaw_tool_pool");
|
||||
static final NamespacedKey ENTRY_INDEX_KEY = new NamespacedKey("iris", "jigsaw_tool_entry_index");
|
||||
static final NamespacedKey AMOUNT_KEY = new NamespacedKey("iris", "jigsaw_tool_amount");
|
||||
|
||||
public ItemStack create(JigsawStudioToolPayload payload) {
|
||||
ItemStack tool = new ItemStack(Material.STICK);
|
||||
bind(tool, payload);
|
||||
return tool;
|
||||
}
|
||||
|
||||
public void bind(ItemStack tool, JigsawStudioToolPayload payload) {
|
||||
ItemStack item = Objects.requireNonNull(tool, "Jigsaw Studio tool item");
|
||||
JigsawStudioToolPayload binding = requireCurrentSchema(payload);
|
||||
if (item.getType() != Material.STICK) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio tools must use a stick");
|
||||
}
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) {
|
||||
throw new IllegalStateException("Jigsaw Studio tool stick has no item metadata");
|
||||
}
|
||||
write(meta.getPersistentDataContainer(), binding);
|
||||
meta.setDisplayName(ChatColor.AQUA + "Jigsaw Studio: " + binding.action().displayName());
|
||||
meta.setLore(lore(binding));
|
||||
if (!item.setItemMeta(meta)) {
|
||||
throw new IllegalStateException("Jigsaw Studio tool metadata was rejected");
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<JigsawStudioToolPayload> decode(ItemStack tool) {
|
||||
if (tool == null || tool.getType() != Material.STICK || !tool.hasItemMeta()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
ItemMeta meta = tool.getItemMeta();
|
||||
return meta == null ? Optional.empty() : decode(meta.getPersistentDataContainer());
|
||||
}
|
||||
|
||||
public boolean isTool(ItemStack tool) {
|
||||
return decode(tool).isPresent();
|
||||
}
|
||||
|
||||
void write(PersistentDataContainer container, JigsawStudioToolPayload payload) {
|
||||
PersistentDataContainer data = Objects.requireNonNull(
|
||||
container,
|
||||
"Jigsaw Studio tool persistent data");
|
||||
JigsawStudioToolPayload binding = requireCurrentSchema(payload);
|
||||
data.set(SCHEMA_KEY, PersistentDataType.INTEGER, binding.schemaVersion());
|
||||
data.set(ACTION_KEY, PersistentDataType.STRING, binding.action().name());
|
||||
data.set(REQUEST_KEY, PersistentDataType.STRING, binding.requestId().toString());
|
||||
data.set(WORKCELL_KEY, PersistentDataType.STRING, binding.workcellId());
|
||||
data.set(PIECE_KEY, PersistentDataType.STRING, binding.pieceKey());
|
||||
data.set(POOL_KEY, PersistentDataType.STRING, binding.poolKey());
|
||||
data.set(ENTRY_INDEX_KEY, PersistentDataType.INTEGER, binding.entryIndex());
|
||||
data.set(AMOUNT_KEY, PersistentDataType.INTEGER, binding.amount());
|
||||
}
|
||||
|
||||
Optional<JigsawStudioToolPayload> decode(PersistentDataContainer container) {
|
||||
if (container == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Integer schemaVersion = container.get(SCHEMA_KEY, PersistentDataType.INTEGER);
|
||||
String actionName = container.get(ACTION_KEY, PersistentDataType.STRING);
|
||||
String requestValue = container.get(REQUEST_KEY, PersistentDataType.STRING);
|
||||
if (schemaVersion == null
|
||||
|| schemaVersion != JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION
|
||||
|| actionName == null
|
||||
|| requestValue == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
JigsawStudioToolAction action = JigsawStudioToolAction.valueOf(actionName);
|
||||
UUID requestId = UUID.fromString(requestValue);
|
||||
String workcellId = optionalString(container, WORKCELL_KEY);
|
||||
String pieceKey = optionalString(container, PIECE_KEY);
|
||||
String poolKey = optionalString(container, POOL_KEY);
|
||||
Integer entryIndex = container.get(ENTRY_INDEX_KEY, PersistentDataType.INTEGER);
|
||||
Integer amount = container.get(AMOUNT_KEY, PersistentDataType.INTEGER);
|
||||
return Optional.of(new JigsawStudioToolPayload(
|
||||
schemaVersion,
|
||||
action,
|
||||
requestId,
|
||||
workcellId,
|
||||
pieceKey,
|
||||
poolKey,
|
||||
entryIndex == null ? JigsawStudioToolPayload.NO_ENTRY_INDEX : entryIndex,
|
||||
amount == null ? 0 : amount));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static JigsawStudioToolPayload requireCurrentSchema(JigsawStudioToolPayload payload) {
|
||||
JigsawStudioToolPayload binding = Objects.requireNonNull(payload, "Jigsaw Studio tool payload");
|
||||
if (binding.schemaVersion() != JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION) {
|
||||
throw new IllegalArgumentException("Unsupported Jigsaw Studio tool schema "
|
||||
+ binding.schemaVersion());
|
||||
}
|
||||
return binding;
|
||||
}
|
||||
|
||||
private static String optionalString(PersistentDataContainer container, NamespacedKey key) {
|
||||
String value = container.get(key, PersistentDataType.STRING);
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
private static List<String> lore(JigsawStudioToolPayload payload) {
|
||||
List<String> lore = new ArrayList<>();
|
||||
if (!payload.workcellId().isEmpty()) {
|
||||
lore.add(ChatColor.GRAY + "Workcell: " + payload.workcellId());
|
||||
}
|
||||
if (!payload.pieceKey().isEmpty()) {
|
||||
lore.add(ChatColor.GRAY + "Variant: " + payload.pieceKey());
|
||||
}
|
||||
if (!payload.poolKey().isEmpty()) {
|
||||
lore.add(ChatColor.GRAY + "Pool: " + payload.poolKey()
|
||||
+ (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]"));
|
||||
}
|
||||
if (payload.amount() != 0) {
|
||||
lore.add(ChatColor.GRAY + "Amount: " + payload.amount());
|
||||
}
|
||||
lore.add(payload.action().destructive()
|
||||
? ChatColor.RED + "Right-click twice to confirm"
|
||||
: ChatColor.YELLOW + "Right-click to use");
|
||||
return List.copyOf(lore);
|
||||
}
|
||||
}
|
||||
@@ -42,9 +42,9 @@ import art.arcane.iris.core.project.IrisPackageCompiler;
|
||||
import art.arcane.iris.core.project.IrisCodeWorkspace;
|
||||
import art.arcane.iris.core.project.IrisProjectCopier;
|
||||
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
|
||||
import art.arcane.iris.core.runtime.StudioSlotOccupant;
|
||||
import art.arcane.iris.core.runtime.TransientWorldCleanupSupport;
|
||||
import art.arcane.iris.core.runtime.WorldDeletionQueue;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
@@ -100,6 +100,7 @@ public class StudioSVC implements IrisService {
|
||||
private final StudioTransitionQueue studioTransitions = new StudioTransitionQueue();
|
||||
private final Object downloadAdmissionMonitor = new Object();
|
||||
private volatile IrisProject activeProject;
|
||||
private volatile StudioSlotOccupant activeToolWorld;
|
||||
private volatile CompletableFuture<StudioOpenCoordinator.StudioOpenResult> activeOpen;
|
||||
private PackDownloadExecution activeDownload;
|
||||
private boolean downloadAdmissionOpen;
|
||||
@@ -125,8 +126,9 @@ public class StudioSVC implements IrisService {
|
||||
boolean stopping = IrisToolbelt.isServerStopping();
|
||||
LinkedHashSet<String> worldNamesToDelete = new LinkedHashSet<>(TransientWorldCleanupSupport.collectTransientStudioWorldNames(IrisWorldStorage.levelRoot()));
|
||||
|
||||
if (activeProject != null) {
|
||||
PlatformChunkGenerator activeProvider = activeProject.getActiveProvider();
|
||||
IrisProject openProject = currentProject();
|
||||
if (openProject != null) {
|
||||
PlatformChunkGenerator activeProvider = openProject.getActiveProvider();
|
||||
if (activeProvider != null) {
|
||||
String activeWorldName = IrisWorldStorage.logicalName(
|
||||
WorldIdentity.parse(activeProvider.getTarget().getWorld().identity()));
|
||||
@@ -475,13 +477,20 @@ public class StudioSVC implements IrisService {
|
||||
}
|
||||
|
||||
public boolean isProjectOpen() {
|
||||
return activeProject != null && activeProject.isOpen();
|
||||
IrisProject project = currentProject();
|
||||
return project != null && project.isOpen();
|
||||
}
|
||||
|
||||
/** The studio project in the slot: the project of the open tool world, or the one opened as a project. */
|
||||
private IrisProject currentProject() {
|
||||
StudioSlotOccupant toolWorld = activeToolWorld;
|
||||
return toolWorld == null ? activeProject : toolWorld.project();
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> teleportToActiveProject(Player player) {
|
||||
Player target = Objects.requireNonNull(player, "Studio teleport player");
|
||||
return studioTransitions.submit(() -> {
|
||||
IrisProject project = activeProject;
|
||||
IrisProject project = currentProject();
|
||||
if (project == null || !project.isOpen()) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException(
|
||||
"No active Studio project is available for teleport."));
|
||||
@@ -511,11 +520,28 @@ public class StudioSVC implements IrisService {
|
||||
}
|
||||
}
|
||||
|
||||
private static BrokenPackException reportPackAdmissionFailure(
|
||||
public static BrokenPackException reportPackAdmissionFailure(
|
||||
VolmitSender sender,
|
||||
String dimm,
|
||||
StudioOpenCoordinator.StudioOpenKind openKind
|
||||
) {
|
||||
PackAdmission admission = admitPack(dimm, openKind);
|
||||
admission.messages().forEach(sender::sendMessage);
|
||||
return admission.failure();
|
||||
}
|
||||
|
||||
/** Why a studio of the pack {@code dimm} may not open, as the lines {@link #reportPackAdmissionFailure} would send; empty when it may. */
|
||||
public static Optional<String> packAdmissionDenial(String dimm, StudioOpenCoordinator.StudioOpenKind openKind) {
|
||||
PackAdmission admission = admitPack(dimm, openKind);
|
||||
return admission.failure() == null ? Optional.empty() : Optional.of(String.join("\n", admission.messages()));
|
||||
}
|
||||
|
||||
/** Whether the pack may open a studio, and the messages that tell its sender so; {@code failure} is null when it may. */
|
||||
private record PackAdmission(BrokenPackException failure, List<String> messages) {
|
||||
}
|
||||
|
||||
private static PackAdmission admitPack(String dimm, StudioOpenCoordinator.StudioOpenKind openKind) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
boolean force = openKind == StudioOpenCoordinator.StudioOpenKind.FORCED_STANDARD;
|
||||
Optional<String> unforcedStartupDenial = ServerConfigurator.worldCreationDenialReason(false);
|
||||
Optional<String> startupDenial = ServerConfigurator.worldCreationDenialReason(force);
|
||||
@@ -528,20 +554,20 @@ public class StudioSVC implements IrisService {
|
||||
packName, startupDenial, validation);
|
||||
if (failure == null) {
|
||||
if (force && unforcedStartupDenial.isPresent()) {
|
||||
sender.sendMessage("Force-opening Studio with the currently loaded registry state. The open may fail; restart remains required.");
|
||||
messages.add("Force-opening Studio with the currently loaded registry state. The open may fail; restart remains required.");
|
||||
}
|
||||
return null;
|
||||
return new PackAdmission(null, messages);
|
||||
}
|
||||
if (startupDenial.isPresent()) {
|
||||
sender.sendMessage(startupDenial.get());
|
||||
return failure;
|
||||
messages.add(startupDenial.get());
|
||||
return new PackAdmission(failure, messages);
|
||||
}
|
||||
sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_CANNOT_OPEN_STUDIO_PACK_HAS_BLOCKING_ERRORS, MessageArgument.untrusted("dimm", String.valueOf(dimm))));
|
||||
messages.add(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_CANNOT_OPEN_STUDIO_PACK_HAS_BLOCKING_ERRORS, MessageArgument.untrusted("dimm", String.valueOf(dimm))));
|
||||
for (String reason : failure.getReasons()) {
|
||||
sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_MESSAGE, MessageArgument.untrusted("reason", String.valueOf(reason))));
|
||||
messages.add(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_MESSAGE, MessageArgument.untrusted("reason", String.valueOf(reason))));
|
||||
}
|
||||
sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_FIX_PACK_RUN_IRIS_PACK_VALIDATE_REVALIDATE, MessageArgument.untrusted("dimm", String.valueOf(packName))));
|
||||
return failure;
|
||||
messages.add(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_FIX_PACK_RUN_IRIS_PACK_VALIDATE_REVALIDATE, MessageArgument.untrusted("dimm", String.valueOf(packName))));
|
||||
return new PackAdmission(failure, messages);
|
||||
}
|
||||
|
||||
static void retainPackRestartRequirement(PackDownloader.PackInstallResult result) {
|
||||
@@ -603,91 +629,6 @@ public class StudioSVC implements IrisService {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<StudioOpenCoordinator.StudioOpenResult> openTracked(
|
||||
VolmitSender sender,
|
||||
long seed,
|
||||
String dimension,
|
||||
StudioOpenCoordinator.StudioOpenKind openKind,
|
||||
Runnable beforeOpen,
|
||||
Consumer<World> onDone
|
||||
) {
|
||||
long requestedAtNanos = System.nanoTime();
|
||||
BrokenPackException failure = reportPackAdmissionFailure(sender, dimension, openKind);
|
||||
if (failure != null) {
|
||||
return CompletableFuture.failedFuture(failure);
|
||||
}
|
||||
return studioTransitions.submit(() -> replaceActiveProjectTracked(
|
||||
sender,
|
||||
seed,
|
||||
dimension,
|
||||
Objects.requireNonNull(openKind, "Studio open kind"),
|
||||
Objects.requireNonNull(beforeOpen, "Studio before-open callback"),
|
||||
Objects.requireNonNull(onDone, "Studio open completion callback"),
|
||||
requestedAtNanos));
|
||||
}
|
||||
|
||||
private CompletableFuture<StudioOpenCoordinator.StudioOpenResult> replaceActiveProjectTracked(
|
||||
VolmitSender sender,
|
||||
long seed,
|
||||
String dimension,
|
||||
StudioOpenCoordinator.StudioOpenKind openKind,
|
||||
Runnable beforeOpen,
|
||||
Consumer<World> onDone,
|
||||
long requestedAtNanos
|
||||
) {
|
||||
return closeActiveProject().thenCompose(closeResult -> {
|
||||
if (closeResult == null) {
|
||||
return CompletableFuture.failedFuture(
|
||||
new IllegalStateException("Studio close completed without a result."));
|
||||
}
|
||||
if (closeResult.failureCause() != null) {
|
||||
return CompletableFuture.failedFuture(closeResult.failureCause());
|
||||
}
|
||||
beforeOpen.run();
|
||||
return beginStudioOpenTracked(
|
||||
sender,
|
||||
seed,
|
||||
dimension,
|
||||
openKind,
|
||||
onDone,
|
||||
requestedAtNanos);
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<StudioOpenCoordinator.StudioOpenResult> beginStudioOpenTracked(
|
||||
VolmitSender sender,
|
||||
long seed,
|
||||
String dimension,
|
||||
StudioOpenCoordinator.StudioOpenKind openKind,
|
||||
Consumer<World> onDone,
|
||||
long requestedAtNanos
|
||||
) {
|
||||
IrisProject project = new IrisProject(new File(getWorkspaceFolder(), dimension));
|
||||
activeProject = project;
|
||||
CompletableFuture<StudioOpenCoordinator.StudioOpenResult> opening;
|
||||
try {
|
||||
opening = project.open(sender, seed, openKind, onDone, requestedAtNanos);
|
||||
} catch (IrisException exception) {
|
||||
if (activeProject == project) {
|
||||
activeProject = null;
|
||||
}
|
||||
return CompletableFuture.failedFuture(exception);
|
||||
}
|
||||
|
||||
activeOpen = opening;
|
||||
return opening.thenApply(result -> Objects.requireNonNull(
|
||||
result,
|
||||
"Studio open completed without a result."))
|
||||
.whenComplete((result, throwable) -> {
|
||||
if (activeOpen == opening) {
|
||||
activeOpen = null;
|
||||
}
|
||||
if (throwable != null && activeProject == project && !project.isOpen()) {
|
||||
activeProject = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> replaceActiveProject(
|
||||
VolmitSender sender,
|
||||
long seed,
|
||||
@@ -791,19 +732,13 @@ public class StudioSVC implements IrisService {
|
||||
CompletableFuture<StudioOpenCoordinator.StudioCloseResult> closeActiveProjectForReplacement(
|
||||
VolmitSender sender
|
||||
) {
|
||||
IrisProject project = activeProject;
|
||||
if (project == null) {
|
||||
StudioSlotOccupant toolWorld = activeToolWorld;
|
||||
if (toolWorld == null || !sender.isPlayer()) {
|
||||
return closeActiveProject();
|
||||
}
|
||||
JigsawStudioActivation.Request request = JigsawStudioActivation.getRequest(project.getName());
|
||||
if (request == null || !sender.isPlayer()) {
|
||||
return closeActiveProject();
|
||||
}
|
||||
UUID ownerId = sender.player().getUniqueId();
|
||||
return JigsawStudioService.get()
|
||||
.awaitCloseForReplacement(request.requestId(), ownerId)
|
||||
return toolWorld.prepareReplacement(Optional.of(sender.player().getUniqueId()))
|
||||
.thenCompose(ignored -> {
|
||||
if (activeProject != project) {
|
||||
if (activeToolWorld != toolWorld) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException(
|
||||
"The active Studio project changed while replacement was waiting to close."));
|
||||
}
|
||||
@@ -811,7 +746,62 @@ public class StudioSVC implements IrisService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the studio slot to a tool world: closes what holds the slot now, then runs {@code opening}, which creates the
|
||||
* world. The slot is free again when the opening fails, or when the world is {@link #releaseStudioSlot gone}.
|
||||
*/
|
||||
public CompletableFuture<Void> occupyStudioSlot(
|
||||
StudioSlotOccupant occupant,
|
||||
Supplier<CompletableFuture<?>> opening
|
||||
) {
|
||||
Objects.requireNonNull(occupant, "Studio slot occupant");
|
||||
Objects.requireNonNull(opening, "Studio slot opening");
|
||||
return studioTransitions.submit(() -> closeActiveProject().thenCompose(closeResult -> {
|
||||
if (closeResult == null) {
|
||||
return CompletableFuture.<Void>failedFuture(
|
||||
new IllegalStateException("Studio close completed without a result."));
|
||||
}
|
||||
if (closeResult.failureCause() != null) {
|
||||
return CompletableFuture.<Void>failedFuture(closeResult.failureCause());
|
||||
}
|
||||
activeToolWorld = occupant;
|
||||
return opening.get().<Void>handle((opened, failure) -> {
|
||||
if (failure == null) {
|
||||
return null;
|
||||
}
|
||||
releaseStudioSlot(occupant);
|
||||
throw failure instanceof java.util.concurrent.CompletionException completion
|
||||
? completion
|
||||
: new java.util.concurrent.CompletionException(failure);
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
/** Frees the studio slot when {@code occupant} still holds it. */
|
||||
public void releaseStudioSlot(StudioSlotOccupant occupant) {
|
||||
if (activeToolWorld == occupant) {
|
||||
activeToolWorld = null;
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<StudioOpenCoordinator.StudioCloseResult> closeToolWorld(StudioSlotOccupant toolWorld) {
|
||||
Optional<String> refusal = toolWorld.closeRefusal();
|
||||
if (refusal.isPresent()) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException(refusal.get()));
|
||||
}
|
||||
return toolWorld.close().handle((ignored, failure) -> {
|
||||
if (failure == null) {
|
||||
releaseStudioSlot(toolWorld);
|
||||
}
|
||||
return new StudioOpenCoordinator.StudioCloseResult(null, failure == null, failure == null, false, failure);
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<StudioOpenCoordinator.StudioCloseResult> closeActiveProject() {
|
||||
StudioSlotOccupant toolWorld = activeToolWorld;
|
||||
if (toolWorld != null) {
|
||||
return closeToolWorld(toolWorld);
|
||||
}
|
||||
IrisProject project = activeProject;
|
||||
if (project == null) {
|
||||
return CompletableFuture.completedFuture(new StudioOpenCoordinator.StudioCloseResult(
|
||||
@@ -823,15 +813,6 @@ public class StudioSVC implements IrisService {
|
||||
));
|
||||
}
|
||||
|
||||
JigsawStudioActivation.Request jigsawRequest = JigsawStudioActivation.getRequest(project.getName());
|
||||
if (jigsawRequest != null) {
|
||||
String protectionFailure = JigsawStudioService.get()
|
||||
.closeProtectionFailure(jigsawRequest.requestId());
|
||||
if (protectionFailure != null) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException(protectionFailure));
|
||||
}
|
||||
}
|
||||
|
||||
IrisLogging.debug("Closing Active Project");
|
||||
CompletableFuture<StudioOpenCoordinator.StudioCloseResult> closing = project.close();
|
||||
return closing.whenComplete((result, throwable) -> {
|
||||
@@ -1537,12 +1518,12 @@ public class StudioSVC implements IrisService {
|
||||
}
|
||||
|
||||
public IrisProject getActiveProject() {
|
||||
return activeProject;
|
||||
return currentProject();
|
||||
}
|
||||
|
||||
public void updateWorkspace() {
|
||||
if (isProjectOpen()) {
|
||||
new IrisCodeWorkspace(activeProject).updateWorkspace();
|
||||
new IrisCodeWorkspace(currentProject()).updateWorkspace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,676 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.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 java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
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 {
|
||||
public record Report(
|
||||
int total,
|
||||
int imported,
|
||||
int skipped,
|
||||
int failed,
|
||||
Map<String, String> successfulBundles,
|
||||
boolean retryRequired,
|
||||
Set<String> captureCandidates
|
||||
) {
|
||||
public Report(int total, int imported, int skipped, int failed) {
|
||||
this(total, imported, skipped, failed, Map.of(), false, Set.of());
|
||||
}
|
||||
|
||||
public Report(int total, int imported, int skipped, int failed, Map<String, String> successfulBundles) {
|
||||
this(total, imported, skipped, failed, successfulBundles, false, Set.of());
|
||||
}
|
||||
|
||||
public Report(int total, int imported, int skipped, int failed,
|
||||
Map<String, String> successfulBundles, boolean retryRequired) {
|
||||
this(total, imported, skipped, failed, successfulBundles, retryRequired, Set.of());
|
||||
}
|
||||
|
||||
public Report {
|
||||
successfulBundles = Collections.unmodifiableMap(new TreeMap<>(successfulBundles));
|
||||
captureCandidates = Collections.unmodifiableSet(new TreeSet<>(captureCandidates));
|
||||
}
|
||||
}
|
||||
|
||||
private BulkStructureImporter() {
|
||||
}
|
||||
|
||||
public static Report importAllVanilla(IrisData data, StructureImporter.Mode mode, boolean includeNonJigsaw, VolmitSender sender) {
|
||||
KList<String> keys = INMS.get().getStructureKeys();
|
||||
List<String> vanilla = new ArrayList<>();
|
||||
for (String k : keys) {
|
||||
if (k != null && !k.isBlank()) {
|
||||
vanilla.add(k);
|
||||
}
|
||||
}
|
||||
Collections.sort(vanilla);
|
||||
|
||||
int total = vanilla.size();
|
||||
int imported = 0;
|
||||
int skipped = 0;
|
||||
int failed = 0;
|
||||
TreeSet<String> 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))));
|
||||
|
||||
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;
|
||||
}
|
||||
String name = StructureImporter.deriveName(nk);
|
||||
|
||||
try {
|
||||
VillageImporter.Result jigsaw = VillageImporter.importVillage(data, 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))));
|
||||
continue;
|
||||
}
|
||||
|
||||
String message = jigsaw.message() == null ? "" : jigsaw.message();
|
||||
if (message.contains("is not a jigsaw structure")) {
|
||||
if (!includeNonJigsaw) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
StructureImporter.Result single = StructureImporter.importStructure(data, 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))));
|
||||
} 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))));
|
||||
} else {
|
||||
failed++;
|
||||
sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(single.message()))));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (message.startsWith("Skipped")) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
failed++;
|
||||
sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(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()))));
|
||||
}
|
||||
}
|
||||
|
||||
StructureIndexService.write(data);
|
||||
|
||||
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))));
|
||||
return new Report(total, imported, skipped, failed, Map.of(), false, captureCandidates);
|
||||
}
|
||||
|
||||
public static Report importTemplateGroups(IrisData data, StructureImporter.Mode mode, VolmitSender sender) {
|
||||
String[][] groups = {
|
||||
{"shipwreck", "minecraft:shipwreck", "shipwreck"},
|
||||
{"ruined_portal", "minecraft:ruined_portal", "ruined_portal"},
|
||||
{"ocean_ruin", "minecraft:ocean_ruin_cold", "underwater_ruin"},
|
||||
{"nether_fossil", "minecraft:nether_fossil", "nether_fossils"},
|
||||
};
|
||||
|
||||
int imported = 0;
|
||||
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));
|
||||
for (String[] g : groups) {
|
||||
try {
|
||||
StructureImporter.Result result = StructureImporter.importTemplateGroup(data, 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()))));
|
||||
} 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()))));
|
||||
}
|
||||
} 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()))));
|
||||
}
|
||||
}
|
||||
|
||||
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))));
|
||||
return new Report(groups.length, imported, skipped, failed);
|
||||
}
|
||||
|
||||
public static Report importAllTemplates(IrisData data, StructureImporter.Mode mode, VolmitSender sender) {
|
||||
List<String> templateKeys;
|
||||
try {
|
||||
templateKeys = enumerateTemplateKeys();
|
||||
} catch (Throwable e) {
|
||||
sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAILED_ENUMERATE_STRUCTURE_TEMPLATES_VIA_SERVER_RESOURCEMANAGER, MessageArgument.untrusted("e", String.valueOf(e))));
|
||||
return enumerationFailureReport();
|
||||
}
|
||||
|
||||
List<String> all = new ArrayList<>();
|
||||
for (String key : templateKeys) {
|
||||
if (key != null && !key.isBlank()) {
|
||||
all.add(key);
|
||||
}
|
||||
}
|
||||
Collections.sort(all);
|
||||
|
||||
int total = all.size();
|
||||
int imported = 0;
|
||||
int skipped = 0;
|
||||
int failed = 0;
|
||||
|
||||
if (total == 0) {
|
||||
sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_NO_STRUCTURE_TEMPLATES_WERE_FOUND_UNDER_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))));
|
||||
|
||||
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;
|
||||
}
|
||||
String name = templateNameFor(keyString);
|
||||
|
||||
try {
|
||||
StructureImporter.Result result = StructureImporter.importStructure(data, 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()))));
|
||||
}
|
||||
} 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()))));
|
||||
}
|
||||
|
||||
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))));
|
||||
}
|
||||
}
|
||||
|
||||
StructureIndexService.write(data);
|
||||
|
||||
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))));
|
||||
return new Report(total, imported, skipped, failed);
|
||||
}
|
||||
|
||||
public static Report importDatapackStructures(IrisData data, StructureImporter.Mode mode, VolmitSender sender) {
|
||||
return importDatapackStructures(
|
||||
data,
|
||||
mode,
|
||||
sender,
|
||||
null,
|
||||
null,
|
||||
StructureImporter.Ownership.EDITABLE
|
||||
);
|
||||
}
|
||||
|
||||
public static Report importManagedDatapackStructures(
|
||||
IrisData data,
|
||||
StructureImporter.Mode mode,
|
||||
VolmitSender sender,
|
||||
Set<String> allowedStructureKeys,
|
||||
Set<String> allowedTemplateKeys
|
||||
) {
|
||||
return importDatapackStructures(
|
||||
data,
|
||||
mode,
|
||||
sender,
|
||||
allowedStructureKeys,
|
||||
allowedTemplateKeys,
|
||||
StructureImporter.Ownership.MANAGED_DATAPACK
|
||||
);
|
||||
}
|
||||
|
||||
private static Report importDatapackStructures(
|
||||
IrisData data,
|
||||
StructureImporter.Mode mode,
|
||||
VolmitSender sender,
|
||||
Set<String> allowedStructureKeys,
|
||||
Set<String> allowedTemplateKeys,
|
||||
StructureImporter.Ownership ownership
|
||||
) {
|
||||
KList<String> keys = INMS.get().getStructureKeys();
|
||||
KeySelection structureSelection = selectDatapackKeys(keys, allowedStructureKeys);
|
||||
List<String> datapack = structureSelection.present();
|
||||
|
||||
int structureAttempts = structureSelection.total();
|
||||
int templateAttempts = 0;
|
||||
int imported = 0;
|
||||
int skipped = 0;
|
||||
int failed = structureSelection.missing().size();
|
||||
boolean retryRequired = false;
|
||||
Map<String, String> 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));
|
||||
} 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))));
|
||||
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")));
|
||||
}
|
||||
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;
|
||||
}
|
||||
String name = StructureImporter.deriveName(nk);
|
||||
|
||||
try {
|
||||
VillageImporter.Result jigsaw = VillageImporter.importVillage(
|
||||
data,
|
||||
nk,
|
||||
name,
|
||||
mode,
|
||||
ownership
|
||||
);
|
||||
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))));
|
||||
continue;
|
||||
}
|
||||
retryRequired |= jigsaw.retryableFailure();
|
||||
|
||||
String message = jigsaw.message() == null ? "" : jigsaw.message();
|
||||
if (message.contains("is not a jigsaw structure")) {
|
||||
StructureImporter.Result single = StructureImporter.importStructure(
|
||||
data,
|
||||
nk,
|
||||
name,
|
||||
mode,
|
||||
false,
|
||||
ownership
|
||||
);
|
||||
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))));
|
||||
} else if (single.message() != null && single.message().startsWith("Skipped")) {
|
||||
skipped++;
|
||||
} else if (single.message() != null && single.message().contains("No loadable structure NBT")) {
|
||||
skipped++;
|
||||
} 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()))));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (message.startsWith("Skipped")) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
failed++;
|
||||
sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_8, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(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()))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (allowedTemplateKeys == null || !allowedTemplateKeys.isEmpty()) {
|
||||
List<String> templateKeys = List.of();
|
||||
boolean enumerationSucceeded = false;
|
||||
try {
|
||||
templateKeys = enumerateTemplateKeys();
|
||||
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()))));
|
||||
}
|
||||
if (enumerationSucceeded) {
|
||||
KeySelection templateSelection = selectDatapackKeys(templateKeys, allowedTemplateKeys);
|
||||
List<String> datapackTemplates = templateSelection.present();
|
||||
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")));
|
||||
}
|
||||
if (!datapackTemplates.isEmpty()) {
|
||||
sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTING_DATAPACK_STRUCTURE_TEMPLATES, MessageArgument.untrusted("size", String.valueOf(datapackTemplates.size()))));
|
||||
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;
|
||||
}
|
||||
String name = templateNameFor(keyString);
|
||||
try {
|
||||
StructureImporter.Result result = StructureImporter.importStructure(
|
||||
data,
|
||||
nk,
|
||||
name,
|
||||
mode,
|
||||
true,
|
||||
ownership
|
||||
);
|
||||
if (result.success()) {
|
||||
imported++;
|
||||
successfulBundles.put(bundleKey(name), keyString);
|
||||
} else if (result.message() != null && result.message().startsWith("Skipped")) {
|
||||
skipped++;
|
||||
} 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()))));
|
||||
}
|
||||
} 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()))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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))));
|
||||
return datapackReport(
|
||||
structureAttempts,
|
||||
templateAttempts,
|
||||
imported,
|
||||
skipped,
|
||||
failed,
|
||||
successfulBundles,
|
||||
retryRequired);
|
||||
}
|
||||
|
||||
static boolean isAllowedDatapackKey(String key, Set<String> allowedKeys) {
|
||||
return allowedKeys == null ? !key.startsWith("minecraft:") : allowedKeys.contains(key);
|
||||
}
|
||||
|
||||
static boolean isCaptureCandidate(String jigsawMessage, String singleMessage) {
|
||||
return jigsawMessage != null
|
||||
&& jigsawMessage.contains("is not a jigsaw structure")
|
||||
&& singleMessage != null
|
||||
&& singleMessage.contains("No loadable structure NBT");
|
||||
}
|
||||
|
||||
static KeySelection selectDatapackKeys(Iterable<String> discoveredKeys, Set<String> allowedKeys) {
|
||||
TreeSet<String> discovered = normalizeKeys(discoveredKeys);
|
||||
TreeSet<String> present = new TreeSet<>();
|
||||
TreeSet<String> missing = new TreeSet<>();
|
||||
if (allowedKeys == null) {
|
||||
for (String key : discovered) {
|
||||
if (isAllowedDatapackKey(key, null)) {
|
||||
present.add(key);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
TreeSet<String> allowed = normalizeKeys(allowedKeys);
|
||||
for (String key : allowed) {
|
||||
if (discovered.contains(key)) {
|
||||
present.add(key);
|
||||
} else {
|
||||
missing.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new KeySelection(new ArrayList<>(present), new ArrayList<>(missing));
|
||||
}
|
||||
|
||||
static Report datapackReport(
|
||||
int structureAttempts,
|
||||
int templateAttempts,
|
||||
int imported,
|
||||
int skipped,
|
||||
int failed,
|
||||
Map<String, String> successfulBundles
|
||||
) {
|
||||
return new Report(structureAttempts + templateAttempts, imported, skipped, failed, successfulBundles);
|
||||
}
|
||||
|
||||
static Report datapackReport(
|
||||
int structureAttempts,
|
||||
int templateAttempts,
|
||||
int imported,
|
||||
int skipped,
|
||||
int failed,
|
||||
Map<String, String> successfulBundles,
|
||||
boolean retryRequired
|
||||
) {
|
||||
return new Report(
|
||||
structureAttempts + templateAttempts,
|
||||
imported,
|
||||
skipped,
|
||||
failed,
|
||||
successfulBundles,
|
||||
retryRequired);
|
||||
}
|
||||
|
||||
static Report enumerationFailureReport() {
|
||||
return new Report(1, 0, 0, 1, Map.of(), true);
|
||||
}
|
||||
|
||||
public static String templateNameFor(String key) {
|
||||
int colon = key.indexOf(':');
|
||||
String namespace = colon >= 0 ? key.substring(0, colon) : "minecraft";
|
||||
String path = colon >= 0 ? key.substring(colon + 1) : key;
|
||||
String safePath = path.toLowerCase().replaceAll("[^a-z0-9_/-]", "_");
|
||||
while (safePath.contains("//")) {
|
||||
safePath = safePath.replace("//", "/");
|
||||
}
|
||||
if (safePath.startsWith("/")) {
|
||||
safePath = safePath.substring(1);
|
||||
}
|
||||
return "minecraft".equals(namespace) ? safePath : namespace + "/" + safePath;
|
||||
}
|
||||
|
||||
private static List<String> 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<Object> endsWithNbt = location -> {
|
||||
String path = identifierPath(location);
|
||||
return path != null && path.endsWith(".nbt");
|
||||
};
|
||||
|
||||
Object resultMap = listResources.invoke(resourceManager, "structure", endsWithNbt);
|
||||
TreeSet<String> keys = new TreeSet<>();
|
||||
if (resultMap instanceof Map<?, ?> map) {
|
||||
for (Object location : map.keySet()) {
|
||||
String namespace = identifierNamespace(location);
|
||||
String path = identifierPath(location);
|
||||
if (namespace == null || path == null) {
|
||||
continue;
|
||||
}
|
||||
String stripped = path;
|
||||
if (stripped.startsWith("structure/")) {
|
||||
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<String> normalizeKeys(Iterable<String> keys) {
|
||||
TreeSet<String> normalized = new TreeSet<>();
|
||||
for (String key : keys) {
|
||||
if (key == null || key.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
normalized.add(key.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static String bundleKey(String name) {
|
||||
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<String> present, List<String> missing) {
|
||||
KeySelection {
|
||||
present = List.copyOf(present);
|
||||
missing = List.copyOf(missing);
|
||||
}
|
||||
|
||||
int total() {
|
||||
return present.size() + missing.size();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import art.arcane.iris.core.ServerConfigurator;
|
||||
import art.arcane.iris.core.WorldCreatorCompat;
|
||||
import art.arcane.iris.core.lifecycle.LifecycleOperationCoordinator;
|
||||
import art.arcane.iris.core.lifecycle.WorldLifecycleService;
|
||||
import art.arcane.iris.core.structure.authoring.StructureBundleNames;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.core.pack.AtomicDirectoryPublisher;
|
||||
@@ -189,7 +190,7 @@ public final class FeatureImporter {
|
||||
if (key.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
rows.add(new Row(group, key, BulkStructureImporter.templateNameFor(key)));
|
||||
rows.add(new Row(group, key, StructureBundleNames.templateName(key)));
|
||||
}
|
||||
rows.sort(Comparator.comparing(r -> r.group() + "/" + r.safeName()));
|
||||
return rows;
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.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.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 java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
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 StructureCaptureImporter() {
|
||||
}
|
||||
|
||||
public static Report importAllStructures(IrisData data, StructureImporter.Mode mode, VolmitSender sender) {
|
||||
return importStructures(data, mode, sender, null);
|
||||
}
|
||||
|
||||
public static Report importStructures(IrisData data, StructureImporter.Mode mode, VolmitSender sender,
|
||||
Set<String> 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));
|
||||
return new Report(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
KList<String> keys = INMS.get().getStructureKeys();
|
||||
if (keys == null || keys.isEmpty()) {
|
||||
return new Report(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
ArrayList<String> 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) {
|
||||
continue;
|
||||
}
|
||||
targets.add(key);
|
||||
}
|
||||
|
||||
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));
|
||||
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))));
|
||||
|
||||
World scratch = FeatureImporter.createScratchWorld(sender);
|
||||
if (scratch == null) {
|
||||
return new Report(total, 0, 0, total);
|
||||
}
|
||||
|
||||
int imported = 0;
|
||||
int skipped = 0;
|
||||
int failed = 0;
|
||||
int cellIndex = 0;
|
||||
|
||||
try {
|
||||
for (String key : targets) {
|
||||
String name = StructureImporter.deriveName(key);
|
||||
try {
|
||||
IrisObject object = captureOne(scratch, 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))));
|
||||
continue;
|
||||
}
|
||||
object.shrinkwrap();
|
||||
StructureImporter.Result result = StructureImporter.writeSinglePieceStructure(
|
||||
data, 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()))));
|
||||
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()))));
|
||||
} 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);
|
||||
}
|
||||
|
||||
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))));
|
||||
}
|
||||
}
|
||||
} 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))));
|
||||
return new Report(total, imported, skipped, failed);
|
||||
}
|
||||
|
||||
static List<String> selectCaptureKeys(Iterable<String> keys, Set<String> allowedStructureKeys) {
|
||||
TreeSet<String> allowed = null;
|
||||
if (allowedStructureKeys != null) {
|
||||
allowed = normalizeKeys(allowedStructureKeys);
|
||||
}
|
||||
TreeSet<String> selected = new TreeSet<>();
|
||||
for (String key : keys) {
|
||||
if (key == null || key.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String normalized = key.trim().toLowerCase(Locale.ROOT);
|
||||
if (allowed == null || allowed.contains(normalized)) {
|
||||
selected.add(normalized);
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(selected);
|
||||
}
|
||||
|
||||
private static TreeSet<String> normalizeKeys(Iterable<String> keys) {
|
||||
TreeSet<String> normalized = new TreeSet<>();
|
||||
for (String key : keys) {
|
||||
if (key == null || key.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
normalized.add(key.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
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;
|
||||
long seed = key.hashCode() * 0x9E3779B97F4A7C15L + cellIndex * 0x100000001B3L + 0x5DEECE66DL;
|
||||
|
||||
AtomicReference<IrisObject> objectRef = new AtomicReference<>();
|
||||
AtomicReference<Throwable> 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();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,608 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.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;
|
||||
import art.arcane.iris.core.structure.authoring.StructureKey;
|
||||
import art.arcane.iris.core.structure.authoring.StructureLoss;
|
||||
import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
|
||||
import art.arcane.iris.core.structure.authoring.StructureSource;
|
||||
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
|
||||
import art.arcane.iris.core.structure.authoring.StructureWriteMode;
|
||||
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 java.io.BufferedInputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class StructureImporter {
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
public enum Mode {
|
||||
OVERWRITE,
|
||||
ADD_ONLY
|
||||
}
|
||||
|
||||
enum Ownership {
|
||||
EDITABLE,
|
||||
MANAGED_DATAPACK;
|
||||
|
||||
StructureWriteResult write(
|
||||
IrisData data,
|
||||
StructureResourceBundle bundle,
|
||||
StructureWriteMode mode
|
||||
) {
|
||||
StructureTransactionWriter writer = new StructureTransactionWriter(data.getDataFolder().toPath());
|
||||
return this == MANAGED_DATAPACK
|
||||
? writer.writeManagedDatapack(bundle, mode)
|
||||
: writer.write(bundle, mode);
|
||||
}
|
||||
}
|
||||
|
||||
public record Result(
|
||||
boolean success,
|
||||
String message,
|
||||
int blocks,
|
||||
List<StructureLoss> losses,
|
||||
boolean retryableFailure
|
||||
) {
|
||||
public Result(boolean success, String message, int blocks, List<StructureLoss> losses) {
|
||||
this(success, message, blocks, losses, false);
|
||||
}
|
||||
|
||||
public Result {
|
||||
losses = List.copyOf(losses);
|
||||
}
|
||||
}
|
||||
|
||||
record CapturedStructure(
|
||||
IrisObject object,
|
||||
int blocks,
|
||||
int nonAirBlocks,
|
||||
int tiles,
|
||||
int width,
|
||||
int height,
|
||||
int depth,
|
||||
int structureMarkers,
|
||||
List<StructureCapability> capabilities,
|
||||
List<StructureLoss> losses
|
||||
) {
|
||||
CapturedStructure {
|
||||
Objects.requireNonNull(object);
|
||||
capabilities = List.copyOf(capabilities);
|
||||
losses = List.copyOf(losses);
|
||||
}
|
||||
}
|
||||
|
||||
private StructureImporter() {
|
||||
}
|
||||
|
||||
public static Mode parseMode(String s) {
|
||||
if (s == null || s.isBlank()) {
|
||||
return Mode.ADD_ONLY;
|
||||
}
|
||||
return switch (s.toLowerCase().replace('-', '_')) {
|
||||
case "add_only", "addonly", "add" -> Mode.ADD_ONLY;
|
||||
case "overwrite", "replace" -> Mode.OVERWRITE;
|
||||
default -> throw new IllegalArgumentException("Unknown structure import mode: " + s);
|
||||
};
|
||||
}
|
||||
|
||||
public static String deriveName(NamespacedKey key) {
|
||||
return (key.getNamespace() + "_" + key.getKey()).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(IrisData data, NamespacedKey key, String name, Mode mode, boolean objectOnly) {
|
||||
return importStructure(data, key, name, mode, objectOnly, Ownership.EDITABLE);
|
||||
}
|
||||
|
||||
static Result importStructure(
|
||||
IrisData data,
|
||||
NamespacedKey key,
|
||||
String name,
|
||||
Mode mode,
|
||||
boolean objectOnly,
|
||||
Ownership ownership
|
||||
) {
|
||||
Mode activeMode = mode == null ? Mode.ADD_ONLY : mode;
|
||||
Structure structure;
|
||||
try {
|
||||
structure = Bukkit.getStructureManager().loadStructure(key);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
return new Result(false, "Failed to load structure " + key + ": " + e.getMessage(), 0, List.of(), true);
|
||||
}
|
||||
if (structure == null || structure.getPalettes().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);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
return new Result(false, "Failed to capture structure " + key + ": " + e.getMessage(), 0, List.of(), true);
|
||||
}
|
||||
|
||||
IrisObject object = captured.object();
|
||||
int count = captured.blocks();
|
||||
int tiles = captured.tiles();
|
||||
int w = captured.width();
|
||||
int h = captured.height();
|
||||
int d = captured.depth();
|
||||
List<StructureLoss> losses = new ArrayList<>(captured.losses());
|
||||
if (captured.structureMarkers() > 0) {
|
||||
losses.add(StructureLoss.warning(
|
||||
StructureCapability.CONNECTORS,
|
||||
"connectors_not_imported",
|
||||
captured.structureMarkers() + " jigsaw or structure marker(s) were flattened without importing their structure graph."));
|
||||
}
|
||||
String writeNote = "";
|
||||
try {
|
||||
StructureKey sourceKey = StructureKey.parse(key.toString());
|
||||
StructureKey bundleKey = new StructureKey("iris", name);
|
||||
StructureSource.Kind sourceKind = key.getNamespace().equals("minecraft")
|
||||
? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK;
|
||||
StructureSource source = StructureSource.of(sourceKind, sourceKey);
|
||||
IrisStructureBundleFactory.SinglePieceOptions options = new IrisStructureBundleFactory.SinglePieceOptions(
|
||||
bundleKey, source, name, object, Math.max(w, d), "CENTER_HEIGHT", objectOnly,
|
||||
captured.capabilities(), losses);
|
||||
StructureResourceBundle bundle = IrisStructureBundleFactory.singlePiece(options);
|
||||
if (!objectOnly) {
|
||||
StructureResourceBundleGraphCompiler.requireViable(bundle);
|
||||
}
|
||||
StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY
|
||||
? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE;
|
||||
StructureWriteResult writeResult = ownership.write(data, bundle, writeMode);
|
||||
reportWriteFailure(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);
|
||||
return new Result(false, "Failed writing import for '" + name + "': " + e.getMessage(), count, losses,
|
||||
true);
|
||||
}
|
||||
|
||||
String lossSummary = losses.isEmpty() ? "" : ", " + losses.size() + " fidelity warning(s) recorded";
|
||||
return new Result(true, "Imported " + key + " as '" + name + "' (" + count + " blocks, " + tiles
|
||||
+ " tiles, " + w + "x" + h + "x" + d + lossSummary + ")" + writeNote, count, losses);
|
||||
}
|
||||
|
||||
static CapturedStructure captureStructure(Structure structure) {
|
||||
Structure activeStructure = Objects.requireNonNull(structure);
|
||||
if (activeStructure.getPalettes().isEmpty()) {
|
||||
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());
|
||||
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();
|
||||
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) {
|
||||
continue;
|
||||
}
|
||||
boolean structural = mat == Material.JIGSAW || mat == Material.STRUCTURE_BLOCK;
|
||||
if (structural) {
|
||||
structureMarkers++;
|
||||
}
|
||||
if (mat == Material.JIGSAW) {
|
||||
FinalStateResult finalState = readJigsawFinalState(block);
|
||||
BlockData resolved = finalState.blockData();
|
||||
if (finalState.invalidSourceState()) {
|
||||
invalidFinalStates++;
|
||||
}
|
||||
if (resolved == null || isAir(resolved)) {
|
||||
continue;
|
||||
}
|
||||
blockData = resolved;
|
||||
} else if (mat == Material.STRUCTURE_BLOCK) {
|
||||
continue;
|
||||
}
|
||||
object.setUnsigned(x, y, z, art.arcane.iris.platform.bukkit.BukkitBlockState.of(blockData));
|
||||
count++;
|
||||
if (!isAir(blockData)) {
|
||||
nonAirBlocks++;
|
||||
}
|
||||
if (!structural) {
|
||||
LegacyTileData tile = captureTile(block);
|
||||
if (tile != null) {
|
||||
object.setUnsignedTile(x, y, z, tile);
|
||||
tiles++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<StructureCapability> capabilities = new ArrayList<>();
|
||||
capabilities.add(StructureCapability.BLOCKS);
|
||||
if (tiles > 0) {
|
||||
capabilities.add(StructureCapability.BLOCK_ENTITIES);
|
||||
}
|
||||
return new CapturedStructure(
|
||||
object,
|
||||
count,
|
||||
nonAirBlocks,
|
||||
tiles,
|
||||
w,
|
||||
h,
|
||||
d,
|
||||
structureMarkers,
|
||||
capabilities,
|
||||
importLosses(activeStructure, 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 List<StructureLoss> importLosses(
|
||||
Structure structure,
|
||||
int structureMarkers,
|
||||
int invalidFinalStates
|
||||
) {
|
||||
List<StructureLoss> losses = new ArrayList<>();
|
||||
if (structure.getPaletteCount() > 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."));
|
||||
}
|
||||
if (structure.getEntityCount() > 0) {
|
||||
losses.add(StructureLoss.warning(
|
||||
StructureCapability.ENTITIES,
|
||||
"entities_not_imported",
|
||||
structure.getEntityCount() + " structure entit" + (structure.getEntityCount() == 1 ? "y was" : "ies were")
|
||||
+ " not converted into the Iris snapshot."));
|
||||
}
|
||||
if (structureMarkers > 0) {
|
||||
losses.add(StructureLoss.warning(
|
||||
StructureCapability.BLOCKS,
|
||||
"structure_markers_resolved",
|
||||
structureMarkers + " jigsaw or structure marker(s) were resolved to final blocks or omitted from the Iris snapshot."));
|
||||
}
|
||||
if (invalidFinalStates > 0) {
|
||||
losses.add(StructureLoss.warning(
|
||||
StructureCapability.BLOCKS,
|
||||
"invalid_jigsaw_final_state",
|
||||
invalidFinalStates + " jigsaw final-state value(s) were invalid and omitted from the Iris snapshot."));
|
||||
}
|
||||
return losses;
|
||||
}
|
||||
|
||||
private static void reportWriteFailure(StructureWriteResult result) {
|
||||
result.failure().ifPresent((Throwable failure) -> {
|
||||
IrisLogging.reportError(failure);
|
||||
});
|
||||
}
|
||||
|
||||
private static String writeResultNote(StructureWriteResult result) {
|
||||
return result.status() == StructureWriteResult.Status.COMMITTED_CLEANUP_REQUIRED
|
||||
? " (committed; staging cleanup is required, see console)" : "";
|
||||
}
|
||||
|
||||
private static String writeFailureMessage(String name, Mode mode, StructureWriteResult result) {
|
||||
if (result.status() == StructureWriteResult.Status.ADD_ONLY_CONFLICT) {
|
||||
return "Skipped (add-only): '" + name + "' already exists";
|
||||
}
|
||||
if (!result.conflicts().isEmpty()) {
|
||||
StructureWriteResult.Conflict conflict = result.conflicts().getFirst();
|
||||
return "Import conflict for '" + name + "': " + conflict.relativePath() + " is "
|
||||
+ conflict.reason().name().toLowerCase() + ". Existing authored files were preserved.";
|
||||
}
|
||||
String failure = result.failure().map(Throwable::getMessage).orElse(result.status().name());
|
||||
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)) {
|
||||
}
|
||||
return new FinalStateResult(null, false);
|
||||
}
|
||||
try {
|
||||
return new FinalStateResult(Bukkit.createBlockData(normalizeJigsawFinalState(finalState)), false);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return new FinalStateResult(null, true);
|
||||
}
|
||||
}
|
||||
|
||||
static String normalizeJigsawFinalState(String finalState) {
|
||||
if (finalState == null) {
|
||||
return null;
|
||||
}
|
||||
int propertiesStart = finalState.indexOf('[');
|
||||
String blockId = propertiesStart < 0 ? finalState : finalState.substring(0, propertiesStart);
|
||||
if (blockId.equals("minecraft:chisled_polished_blackstone")) {
|
||||
finalState = "minecraft:chiseled_polished_blackstone"
|
||||
+ (propertiesStart < 0 ? "" : finalState.substring(propertiesStart));
|
||||
propertiesStart = finalState.indexOf('[');
|
||||
}
|
||||
if (propertiesStart < 0 || !finalState.substring(0, propertiesStart).endsWith("_slab")
|
||||
|| finalState.contains("type=")) {
|
||||
return finalState;
|
||||
}
|
||||
return finalState.replaceAll("([\\[,])half=(top|bottom)(?=[,\\]])", "$1type=$2");
|
||||
}
|
||||
|
||||
private record FinalStateResult(BlockData blockData, boolean invalidSourceState) {
|
||||
}
|
||||
|
||||
private static LegacyTileData captureTile(BlockState block) {
|
||||
try {
|
||||
return LegacyTileData.fromBukkit(block);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Result importTemplateGroup(IrisData data, String groupName, String vanillaSource, String prefix, Mode mode) {
|
||||
Mode activeMode = mode == null ? Mode.ADD_ONLY : mode;
|
||||
File objectsRoot = new File(data.getDataFolder(), "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<File> iobs = new ArrayList<>();
|
||||
collectIob(prefixDir, iobs);
|
||||
if (iobs.isEmpty()) {
|
||||
return new Result(false, "No .iob templates under objects/" + prefix + " for " + groupName, 0, List.of());
|
||||
}
|
||||
iobs.sort(Comparator.comparing(File::getAbsolutePath));
|
||||
|
||||
String rootPath = objectsRoot.getAbsolutePath() + File.separator;
|
||||
List<String> pieceNames = new ArrayList<>();
|
||||
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());
|
||||
}
|
||||
pieceNames.add(rel);
|
||||
try {
|
||||
maxSpan = Math.max(maxSpan, readObjectSpan(iob));
|
||||
} catch (IOException e) {
|
||||
IrisLogging.reportError(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());
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void collectIob(File dir, List<File> 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")) {
|
||||
out.add(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int readObjectSpan(File iob) throws IOException {
|
||||
try (DataInputStream din = new DataInputStream(new BufferedInputStream(new FileInputStream(iob)))) {
|
||||
int w = din.readInt();
|
||||
int h = din.readInt();
|
||||
int d = din.readInt();
|
||||
if (w < 1 || h < 1 || d < 1) {
|
||||
throw new IOException("Invalid IOB dimensions " + w + "x" + h + "x" + d + " in " + iob);
|
||||
}
|
||||
return Math.max(w, d);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> poolJsonMulti(List<String> pieceNames) {
|
||||
List<Object> pieces = new ArrayList<>();
|
||||
for (String name : pieceNames) {
|
||||
Map<String, Object> entry = new LinkedHashMap<>();
|
||||
entry.put("piece", name);
|
||||
entry.put("weight", 1);
|
||||
pieces.add(entry);
|
||||
}
|
||||
Map<String, Object> pool = new LinkedHashMap<>();
|
||||
pool.put("pieces", pieces);
|
||||
return pool;
|
||||
}
|
||||
|
||||
public static Result writeSinglePieceStructure(
|
||||
IrisData data,
|
||||
String name,
|
||||
String vanillaSource,
|
||||
IrisObject object,
|
||||
String placeMode,
|
||||
Mode mode
|
||||
) {
|
||||
Mode activeMode = mode == null ? Mode.ADD_ONLY : mode;
|
||||
int span = Math.max(object.getW(), object.getD());
|
||||
try {
|
||||
StructureKey sourceKey = StructureKey.parse(vanillaSource, "minecraft");
|
||||
StructureSource.Kind sourceKind = sourceKey.namespace().equals("minecraft")
|
||||
? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK;
|
||||
IrisStructureBundleFactory.SinglePieceOptions options = new IrisStructureBundleFactory.SinglePieceOptions(
|
||||
new StructureKey("iris", name),
|
||||
StructureSource.of(sourceKind, sourceKey),
|
||||
name,
|
||||
object,
|
||||
span,
|
||||
placeMode,
|
||||
false,
|
||||
List.of(StructureCapability.BLOCKS, StructureCapability.IRIS_PLACEMENT),
|
||||
List.of());
|
||||
StructureResourceBundle bundle = IrisStructureBundleFactory.singlePiece(options);
|
||||
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);
|
||||
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);
|
||||
return new Result(false, "Failed writing capture for '" + name + "': " + e.getMessage(), 0, List.of(),
|
||||
true);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> structureJson(String name, String source, int maxSpan) {
|
||||
Map<String, Object> root = new LinkedHashMap<>();
|
||||
root.put("startPool", name);
|
||||
root.put("maxDepth", 1);
|
||||
root.put("maxSizeChunks", Math.max(1, (maxSpan / 16) + 1));
|
||||
root.put("placeMode", "CENTER_HEIGHT");
|
||||
root.put("vanillaSource", source);
|
||||
return root;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.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 com.google.gson.GsonBuilder;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public final class StructureIndexService {
|
||||
private static final String INDEX_PATH = ".iris/structure-index.json";
|
||||
private static final Set<String> GENERATED = ConcurrentHashMap.newKeySet();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public static File write(IrisData data) {
|
||||
List<String> structures = IrisPlatforms.get().structureHooks().structureKeys();
|
||||
List<String> sets = IrisPlatforms.get().structureHooks().structureSetKeys();
|
||||
|
||||
List<String> vanilla = new ArrayList<>();
|
||||
List<String> datapack = new ArrayList<>();
|
||||
for (String k : structures) {
|
||||
if (k.startsWith("minecraft:")) {
|
||||
vanilla.add(k);
|
||||
} else {
|
||||
datapack.add(k);
|
||||
}
|
||||
}
|
||||
|
||||
List<String> vanillaSets = new ArrayList<>();
|
||||
List<String> datapackSets = new ArrayList<>();
|
||||
for (String k : sets) {
|
||||
if (k.startsWith("minecraft:")) {
|
||||
vanillaSets.add(k);
|
||||
} else {
|
||||
datapackSets.add(k);
|
||||
}
|
||||
}
|
||||
|
||||
List<String> iris = new ArrayList<>(ModuleServices.structureKeys(data));
|
||||
|
||||
Collections.sort(vanilla);
|
||||
Collections.sort(datapack);
|
||||
Collections.sort(vanillaSets);
|
||||
Collections.sort(datapackSets);
|
||||
Collections.sort(iris);
|
||||
|
||||
Map<String, Object> structuresNode = new LinkedHashMap<>();
|
||||
structuresNode.put("vanilla", vanilla);
|
||||
structuresNode.put("datapack", datapack);
|
||||
|
||||
Map<String, Object> setsNode = new LinkedHashMap<>();
|
||||
setsNode.put("vanilla", vanillaSets);
|
||||
setsNode.put("datapack", datapackSets);
|
||||
|
||||
Map<String, Object> counts = new LinkedHashMap<>();
|
||||
counts.put("vanillaStructures", vanilla.size());
|
||||
counts.put("datapackStructures", datapack.size());
|
||||
counts.put("structureSets", sets.size());
|
||||
counts.put("irisStructures", iris.size());
|
||||
|
||||
Map<String, Object> root = new LinkedHashMap<>();
|
||||
root.put("note", "Generated index of every structure available at runtime. Toggle vanilla/datapack generation via the dimension importedStructures block (by structure key). Place structures via biome/region/dimension structures lists.");
|
||||
root.put("counts", counts);
|
||||
root.put("structures", structuresNode);
|
||||
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);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
static File indexFile(File dataFolder) {
|
||||
return new File(dataFolder, INDEX_PATH);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
-107
@@ -1,107 +0,0 @@
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class IrisStructureBundleFactory {
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
private IrisStructureBundleFactory() {
|
||||
}
|
||||
|
||||
public static StructureResourceBundle singlePiece(SinglePieceOptions options) throws IOException {
|
||||
SinglePieceOptions activeOptions = Objects.requireNonNull(options);
|
||||
StructureResourceBundle.Builder bundle = StructureResourceBundle.builder(activeOptions.bundleKey())
|
||||
.source(activeOptions.source())
|
||||
.backend(StructureBackend.SNAPSHOT)
|
||||
.capabilities(activeOptions.capabilities())
|
||||
.losses(activeOptions.losses())
|
||||
.resource("objects/" + activeOptions.resourceKey() + ".iob", serialize(activeOptions.object()))
|
||||
.textResource("jigsaw-pieces/" + activeOptions.resourceKey() + ".json",
|
||||
GSON.toJson(pieceJson(activeOptions.resourceKey())));
|
||||
if (!activeOptions.objectOnly()) {
|
||||
bundle.capability(StructureCapability.IRIS_PLACEMENT)
|
||||
.textResource("jigsaw-pools/" + activeOptions.resourceKey() + ".json",
|
||||
GSON.toJson(poolJson(activeOptions.resourceKey())))
|
||||
.textResource("structures/" + activeOptions.resourceKey() + ".json",
|
||||
GSON.toJson(structureJson(activeOptions)));
|
||||
}
|
||||
return bundle.build();
|
||||
}
|
||||
|
||||
private static byte[] serialize(IrisObject object) throws IOException {
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
object.write(output);
|
||||
return output.toByteArray();
|
||||
}
|
||||
|
||||
private static Map<String, Object> pieceJson(String resourceKey) {
|
||||
Map<String, Object> piece = new LinkedHashMap<>();
|
||||
piece.put("object", resourceKey);
|
||||
piece.put("connectors", new ArrayList<>());
|
||||
piece.put("rotatable", true);
|
||||
return piece;
|
||||
}
|
||||
|
||||
private static Map<String, Object> poolJson(String resourceKey) {
|
||||
Map<String, Object> entry = new LinkedHashMap<>();
|
||||
entry.put("piece", resourceKey);
|
||||
entry.put("weight", 1);
|
||||
List<Object> pieces = new ArrayList<>();
|
||||
pieces.add(entry);
|
||||
Map<String, Object> pool = new LinkedHashMap<>();
|
||||
pool.put("pieces", pieces);
|
||||
return pool;
|
||||
}
|
||||
|
||||
private static Map<String, Object> structureJson(SinglePieceOptions options) {
|
||||
Map<String, Object> structure = new LinkedHashMap<>();
|
||||
structure.put("startPool", options.resourceKey());
|
||||
structure.put("maxDepth", 1);
|
||||
structure.put("maxSizeChunks", Math.max(1, (options.maxSpan() / 16) + 1));
|
||||
structure.put("placeMode", options.placeMode());
|
||||
structure.put("vanillaSource", options.source().key().value());
|
||||
return structure;
|
||||
}
|
||||
|
||||
public record SinglePieceOptions(
|
||||
StructureKey bundleKey,
|
||||
StructureSource source,
|
||||
String resourceKey,
|
||||
IrisObject object,
|
||||
int maxSpan,
|
||||
String placeMode,
|
||||
boolean objectOnly,
|
||||
Collection<StructureCapability> capabilities,
|
||||
Collection<StructureLoss> losses
|
||||
) {
|
||||
public SinglePieceOptions {
|
||||
Objects.requireNonNull(bundleKey);
|
||||
Objects.requireNonNull(source);
|
||||
Objects.requireNonNull(resourceKey);
|
||||
Objects.requireNonNull(object);
|
||||
Objects.requireNonNull(placeMode);
|
||||
Objects.requireNonNull(capabilities);
|
||||
Objects.requireNonNull(losses);
|
||||
StructureResourceBundle.validateRelativePath("structures/" + resourceKey + ".json");
|
||||
if (maxSpan < 1) {
|
||||
throw new IllegalArgumentException("Structure span must be positive");
|
||||
}
|
||||
if (placeMode.isBlank()) {
|
||||
throw new IllegalArgumentException("Structure place mode cannot be blank");
|
||||
}
|
||||
capabilities = List.copyOf(capabilities);
|
||||
losses = List.copyOf(losses);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
public enum StructureCapability {
|
||||
BLOCKS,
|
||||
BLOCK_ENTITIES,
|
||||
ENTITIES,
|
||||
CONNECTORS,
|
||||
PROCESSORS,
|
||||
PROJECTION,
|
||||
LIST_ELEMENTS,
|
||||
FEATURE_ELEMENTS,
|
||||
LIQUID_SETTINGS,
|
||||
TERRAIN_ADAPTATION,
|
||||
MIRRORING,
|
||||
NATIVE_PLACEMENT,
|
||||
IRIS_PLACEMENT
|
||||
}
|
||||
-160
@@ -1,160 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
interface StructureFileOperations {
|
||||
boolean exists(Path path);
|
||||
|
||||
boolean isRegularFile(Path path);
|
||||
|
||||
default boolean isDirectory(Path path) {
|
||||
return Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS);
|
||||
}
|
||||
|
||||
byte[] readAllBytes(Path path) throws IOException;
|
||||
|
||||
String sha256(Path path) throws IOException;
|
||||
|
||||
void createDirectories(Path path) throws IOException;
|
||||
|
||||
void writeNew(Path path, byte[] content) throws IOException;
|
||||
|
||||
void move(Path source, Path target) throws IOException;
|
||||
|
||||
default void moveNew(Path source, Path target) throws IOException {
|
||||
move(source, target);
|
||||
}
|
||||
|
||||
void deleteIfExists(Path path) throws IOException;
|
||||
|
||||
void deleteTree(Path root) throws IOException;
|
||||
|
||||
default List<Path> list(Path root) throws IOException {
|
||||
try (Stream<Path> stream = Files.list(root)) {
|
||||
return stream.sorted().toList();
|
||||
}
|
||||
}
|
||||
|
||||
default List<Path> list(Path root, int maxEntries) throws IOException {
|
||||
List<Path> entries = list(root);
|
||||
return entries.size() <= maxEntries ? entries : entries.subList(0, maxEntries + 1);
|
||||
}
|
||||
|
||||
default void forceFile(Path path) throws IOException {
|
||||
try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) {
|
||||
channel.force(true);
|
||||
}
|
||||
}
|
||||
|
||||
default void forceDirectory(Path path) throws IOException {
|
||||
if (!Files.getFileStore(path).supportsFileAttributeView("posix")) {
|
||||
return;
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
|
||||
channel.force(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class NioStructureFileOperations implements StructureFileOperations {
|
||||
@Override
|
||||
public boolean exists(Path path) {
|
||||
return Files.exists(path, LinkOption.NOFOLLOW_LINKS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRegularFile(Path path) {
|
||||
return Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] readAllBytes(Path path) throws IOException {
|
||||
return Files.readAllBytes(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String sha256(Path path) throws IOException {
|
||||
try (InputStream input = Files.newInputStream(path)) {
|
||||
return StructureHash.sha256(input);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createDirectories(Path path) throws IOException {
|
||||
Files.createDirectories(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeNew(Path path, byte[] content) throws IOException {
|
||||
Files.write(path, content, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void move(Path source, Path target) throws IOException {
|
||||
try {
|
||||
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException e) {
|
||||
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveNew(Path source, Path target) throws IOException {
|
||||
Files.move(source, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteIfExists(Path path) throws IOException {
|
||||
Files.deleteIfExists(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteTree(Path root) throws IOException {
|
||||
if (!exists(root)) {
|
||||
return;
|
||||
}
|
||||
List<Path> paths;
|
||||
try (Stream<Path> stream = Files.walk(root)) {
|
||||
paths = stream.sorted(Comparator.reverseOrder()).toList();
|
||||
}
|
||||
for (Path path : paths) {
|
||||
Files.deleteIfExists(path);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Path> list(Path root, int maxEntries) throws IOException {
|
||||
try (Stream<Path> stream = Files.list(root)) {
|
||||
return stream.limit(maxEntries + 1L).sorted().toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class StructureHash {
|
||||
private static final Pattern SHA_256_PATTERN = Pattern.compile("[a-f0-9]{64}");
|
||||
|
||||
private StructureHash() {
|
||||
}
|
||||
|
||||
public static String sha256(byte[] content) {
|
||||
Objects.requireNonNull(content, "content");
|
||||
MessageDigest digest = createSha256Digest();
|
||||
return HexFormat.of().formatHex(digest.digest(content));
|
||||
}
|
||||
|
||||
public static String sha256(InputStream input) throws IOException {
|
||||
Objects.requireNonNull(input, "input");
|
||||
MessageDigest digest = createSha256Digest();
|
||||
byte[] buffer = new byte[8192];
|
||||
int read;
|
||||
while ((read = input.read(buffer)) >= 0) {
|
||||
if (read > 0) {
|
||||
digest.update(buffer, 0, read);
|
||||
}
|
||||
}
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
}
|
||||
|
||||
public static boolean isSha256(String value) {
|
||||
return value != null && SHA_256_PATTERN.matcher(value).matches();
|
||||
}
|
||||
|
||||
private static MessageDigest createSha256Digest() {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is not available", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public record StructureKey(String namespace, String path) implements Comparable<StructureKey> {
|
||||
private static final Pattern NAMESPACE_PATTERN = Pattern.compile("[a-z0-9._-]+");
|
||||
private static final Pattern PATH_PATTERN = Pattern.compile("[a-z0-9._/-]+");
|
||||
|
||||
public StructureKey {
|
||||
Objects.requireNonNull(namespace, "namespace");
|
||||
Objects.requireNonNull(path, "path");
|
||||
if (!NAMESPACE_PATTERN.matcher(namespace).matches()) {
|
||||
throw new IllegalArgumentException("Invalid structure namespace: " + namespace);
|
||||
}
|
||||
if (!PATH_PATTERN.matcher(path).matches()) {
|
||||
throw new IllegalArgumentException("Invalid structure path: " + path);
|
||||
}
|
||||
validatePathSegments(path);
|
||||
}
|
||||
|
||||
public static StructureKey parse(String value) {
|
||||
Objects.requireNonNull(value, "value");
|
||||
int separator = value.indexOf(':');
|
||||
if (separator <= 0 || separator == value.length() - 1 || separator != value.lastIndexOf(':')) {
|
||||
throw new IllegalArgumentException("Structure key must use namespace:path: " + value);
|
||||
}
|
||||
return new StructureKey(value.substring(0, separator), value.substring(separator + 1));
|
||||
}
|
||||
|
||||
public static StructureKey parse(String value, String defaultNamespace) {
|
||||
Objects.requireNonNull(value, "value");
|
||||
Objects.requireNonNull(defaultNamespace, "defaultNamespace");
|
||||
if (value.indexOf(':') < 0) {
|
||||
return new StructureKey(defaultNamespace, value);
|
||||
}
|
||||
return parse(value);
|
||||
}
|
||||
|
||||
public String value() {
|
||||
return namespace + ":" + path;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(StructureKey other) {
|
||||
int namespaceComparison = namespace.compareTo(other.namespace);
|
||||
if (namespaceComparison != 0) {
|
||||
return namespaceComparison;
|
||||
}
|
||||
return path.compareTo(other.path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return value();
|
||||
}
|
||||
|
||||
private static void validatePathSegments(String path) {
|
||||
if (path.startsWith("/") || path.endsWith("/") || path.contains("//")) {
|
||||
throw new IllegalArgumentException("Invalid structure path: " + path);
|
||||
}
|
||||
String[] segments = path.split("/");
|
||||
for (String segment : segments) {
|
||||
if (segment.equals(".") || segment.equals("..")) {
|
||||
throw new IllegalArgumentException("Invalid structure path: " + path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public record StructureLoss(
|
||||
StructureCapability capability,
|
||||
Severity severity,
|
||||
String code,
|
||||
String detail,
|
||||
String affectedResource
|
||||
) {
|
||||
private static final Pattern CODE_PATTERN = Pattern.compile("[a-z0-9._-]+");
|
||||
|
||||
public StructureLoss {
|
||||
Objects.requireNonNull(capability, "capability");
|
||||
Objects.requireNonNull(severity, "severity");
|
||||
Objects.requireNonNull(code, "code");
|
||||
Objects.requireNonNull(detail, "detail");
|
||||
Objects.requireNonNull(affectedResource, "affectedResource");
|
||||
if (!CODE_PATTERN.matcher(code).matches()) {
|
||||
throw new IllegalArgumentException("Invalid structure loss code: " + code);
|
||||
}
|
||||
if (detail.isBlank()) {
|
||||
throw new IllegalArgumentException("Structure loss detail cannot be blank");
|
||||
}
|
||||
}
|
||||
|
||||
public static StructureLoss warning(StructureCapability capability, String code, String detail) {
|
||||
return new StructureLoss(capability, Severity.WARNING, code, detail, "");
|
||||
}
|
||||
|
||||
public static StructureLoss error(StructureCapability capability, String code, String detail) {
|
||||
return new StructureLoss(capability, Severity.ERROR, code, detail, "");
|
||||
}
|
||||
|
||||
public StructureLoss affecting(String resource) {
|
||||
Objects.requireNonNull(resource, "resource");
|
||||
return new StructureLoss(capability, severity, code, detail, resource);
|
||||
}
|
||||
|
||||
public enum Severity {
|
||||
INFO,
|
||||
WARNING,
|
||||
ERROR
|
||||
}
|
||||
}
|
||||
-260
@@ -1,260 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
|
||||
public record StructureOwnershipManifest(
|
||||
int schemaVersion,
|
||||
StructureKey structure,
|
||||
StructureSource source,
|
||||
StructureBackend backend,
|
||||
List<StructureCapability> capabilities,
|
||||
List<StructureLoss> losses,
|
||||
Map<String, String> resourceHashes,
|
||||
Provenance provenance
|
||||
) {
|
||||
public static final int CURRENT_SCHEMA_VERSION = 1;
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
public StructureOwnershipManifest {
|
||||
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
|
||||
throw new IllegalArgumentException("Unsupported structure ownership manifest schema: " + schemaVersion);
|
||||
}
|
||||
Objects.requireNonNull(structure, "structure");
|
||||
Objects.requireNonNull(source, "source");
|
||||
Objects.requireNonNull(backend, "backend");
|
||||
Objects.requireNonNull(capabilities, "capabilities");
|
||||
Objects.requireNonNull(losses, "losses");
|
||||
Objects.requireNonNull(resourceHashes, "resourceHashes");
|
||||
provenance = provenance == null ? Provenance.created() : provenance;
|
||||
ArrayList<StructureCapability> orderedCapabilities = new ArrayList<>(capabilities);
|
||||
orderedCapabilities.sort(Comparator.naturalOrder());
|
||||
capabilities = List.copyOf(orderedCapabilities);
|
||||
losses = List.copyOf(losses);
|
||||
TreeMap<String, String> orderedHashes = new TreeMap<>();
|
||||
TreeMap<String, String> portablePaths = new TreeMap<>();
|
||||
for (Map.Entry<String, String> entry : resourceHashes.entrySet()) {
|
||||
String relativePath = StructureResourceBundle.validateRelativePath(entry.getKey());
|
||||
String portablePath = relativePath.toLowerCase(Locale.ROOT);
|
||||
String previousPath = portablePaths.putIfAbsent(portablePath, relativePath);
|
||||
if (previousPath != null) {
|
||||
throw new IllegalArgumentException(
|
||||
"Ownership manifest contains case-colliding resources: " + previousPath + " and " + relativePath
|
||||
);
|
||||
}
|
||||
String contentHash = Objects.requireNonNull(entry.getValue(), "contentHash");
|
||||
if (!StructureHash.isSha256(contentHash)) {
|
||||
throw new IllegalArgumentException("Invalid SHA-256 hash for resource " + relativePath);
|
||||
}
|
||||
orderedHashes.put(relativePath, contentHash);
|
||||
}
|
||||
resourceHashes = Collections.unmodifiableMap(orderedHashes);
|
||||
}
|
||||
|
||||
public StructureOwnershipManifest(
|
||||
int schemaVersion,
|
||||
StructureKey structure,
|
||||
StructureSource source,
|
||||
StructureBackend backend,
|
||||
List<StructureCapability> capabilities,
|
||||
List<StructureLoss> losses,
|
||||
Map<String, String> resourceHashes
|
||||
) {
|
||||
this(schemaVersion, structure, source, backend, capabilities, losses, resourceHashes, Provenance.created());
|
||||
}
|
||||
|
||||
public static StructureOwnershipManifest from(StructureResourceBundle bundle) {
|
||||
return from(bundle, Provenance.created());
|
||||
}
|
||||
|
||||
public static StructureOwnershipManifest from(StructureResourceBundle bundle, Provenance provenance) {
|
||||
Objects.requireNonNull(bundle, "bundle");
|
||||
Objects.requireNonNull(provenance, "provenance");
|
||||
TreeMap<String, String> hashes = new TreeMap<>();
|
||||
for (StructureResourceBundle.Resource resource : bundle.resources().values()) {
|
||||
hashes.put(resource.relativePath(), resource.contentHash());
|
||||
}
|
||||
return new StructureOwnershipManifest(
|
||||
CURRENT_SCHEMA_VERSION,
|
||||
bundle.key(),
|
||||
bundle.source(),
|
||||
bundle.backend(),
|
||||
new ArrayList<>(bundle.capabilities()),
|
||||
bundle.losses(),
|
||||
hashes,
|
||||
provenance
|
||||
);
|
||||
}
|
||||
|
||||
public static StructureOwnershipManifest fromJson(byte[] content) {
|
||||
Objects.requireNonNull(content, "content");
|
||||
StructureOwnershipManifest manifest = GSON.fromJson(
|
||||
new String(content, StandardCharsets.UTF_8),
|
||||
StructureOwnershipManifest.class
|
||||
);
|
||||
if (manifest == null) {
|
||||
throw new IllegalArgumentException("Structure ownership manifest is empty");
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
|
||||
public byte[] toJson() {
|
||||
return GSON.toJson(this).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public String relativePath() {
|
||||
return relativePath(structure);
|
||||
}
|
||||
|
||||
public static String relativePath(StructureKey structure) {
|
||||
Objects.requireNonNull(structure, "structure");
|
||||
String identityHash = StructureHash.sha256(structure.value().getBytes(StandardCharsets.UTF_8));
|
||||
return ".iris/structure-manifests/key-" + identityHash + ".json";
|
||||
}
|
||||
|
||||
public record Provenance(
|
||||
Origin origin,
|
||||
String receiptId,
|
||||
String planHash,
|
||||
String sourceClosureHash,
|
||||
long appliedAtEpochMilli,
|
||||
Map<String, String> sourceResourceHashes,
|
||||
Map<String, String> sourceToTargetPaths,
|
||||
RollbackDisposition rollbackDisposition
|
||||
) {
|
||||
public Provenance {
|
||||
origin = origin == null ? Origin.CREATED : origin;
|
||||
receiptId = normalize(receiptId);
|
||||
planHash = normalize(planHash);
|
||||
sourceClosureHash = normalize(sourceClosureHash);
|
||||
sourceResourceHashes = immutableHashes(sourceResourceHashes);
|
||||
sourceToTargetPaths = immutableMappings(sourceToTargetPaths);
|
||||
rollbackDisposition = rollbackDisposition == null
|
||||
? RollbackDisposition.NONE
|
||||
: rollbackDisposition;
|
||||
if (origin == Origin.CREATED) {
|
||||
if (!receiptId.isEmpty() || !planHash.isEmpty() || !sourceClosureHash.isEmpty()
|
||||
|| appliedAtEpochMilli != 0L || !sourceResourceHashes.isEmpty()
|
||||
|| !sourceToTargetPaths.isEmpty() || rollbackDisposition != RollbackDisposition.NONE) {
|
||||
throw new IllegalArgumentException("Created structure provenance cannot declare adoption metadata");
|
||||
}
|
||||
} else {
|
||||
requireUuid(receiptId);
|
||||
requireHash(planHash, "plan");
|
||||
requireHash(sourceClosureHash, "source closure");
|
||||
if (appliedAtEpochMilli <= 0L) {
|
||||
throw new IllegalArgumentException("Adoption provenance requires a positive application time");
|
||||
}
|
||||
if (sourceResourceHashes.isEmpty() || sourceToTargetPaths.isEmpty()) {
|
||||
throw new IllegalArgumentException("Adoption provenance requires source hashes and path mappings");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Provenance created() {
|
||||
return new Provenance(
|
||||
Origin.CREATED,
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
0L,
|
||||
Map.of(),
|
||||
Map.of(),
|
||||
RollbackDisposition.NONE
|
||||
);
|
||||
}
|
||||
|
||||
public boolean adopted() {
|
||||
return origin != Origin.CREATED;
|
||||
}
|
||||
|
||||
private static Map<String, String> immutableHashes(Map<String, String> hashes) {
|
||||
if (hashes == null || hashes.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
TreeMap<String, String> ordered = new TreeMap<>();
|
||||
for (Map.Entry<String, String> entry : hashes.entrySet()) {
|
||||
String relativePath = StructureResourceBundle.validateRelativePath(entry.getKey());
|
||||
String hash = Objects.requireNonNull(entry.getValue(), "source resource hash");
|
||||
requireHash(hash, "source resource");
|
||||
ordered.put(relativePath, hash);
|
||||
}
|
||||
return Collections.unmodifiableMap(ordered);
|
||||
}
|
||||
|
||||
private static Map<String, String> immutableMappings(Map<String, String> mappings) {
|
||||
if (mappings == null || mappings.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
TreeMap<String, String> ordered = new TreeMap<>();
|
||||
for (Map.Entry<String, String> entry : mappings.entrySet()) {
|
||||
String sourcePath = StructureResourceBundle.validateRelativePath(entry.getKey());
|
||||
String targetPath = StructureResourceBundle.validateRelativePath(
|
||||
Objects.requireNonNull(entry.getValue(), "target resource path"));
|
||||
ordered.put(sourcePath, targetPath);
|
||||
}
|
||||
return Collections.unmodifiableMap(ordered);
|
||||
}
|
||||
|
||||
private static void requireUuid(String value) {
|
||||
try {
|
||||
UUID.fromString(value);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IllegalArgumentException("Adoption receipt ID must be a UUID", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireHash(String value, String kind) {
|
||||
if (!StructureHash.isSha256(value)) {
|
||||
throw new IllegalArgumentException("Adoption " + kind + " hash must be SHA-256");
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
|
||||
public enum Origin {
|
||||
CREATED,
|
||||
ADOPTED_EXISTING,
|
||||
ADOPTED_CLONE,
|
||||
ADOPTED_MANAGED_CLONE,
|
||||
CONVERTED,
|
||||
MANAGED_DATAPACK
|
||||
}
|
||||
|
||||
public enum RollbackDisposition {
|
||||
NONE,
|
||||
DELETE_CREATED_IF_UNCHANGED
|
||||
}
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record StructureRecoveryResult(
|
||||
int restoredPreparedTransactions,
|
||||
int cleanedCommittedTransactions,
|
||||
int cleanedOrphanTransactions,
|
||||
List<Failure> failures
|
||||
) {
|
||||
public StructureRecoveryResult {
|
||||
if (restoredPreparedTransactions < 0
|
||||
|| cleanedCommittedTransactions < 0
|
||||
|| cleanedOrphanTransactions < 0) {
|
||||
throw new IllegalArgumentException("Structure recovery counts cannot be negative");
|
||||
}
|
||||
Objects.requireNonNull(failures, "failures");
|
||||
failures = List.copyOf(failures);
|
||||
}
|
||||
|
||||
public boolean successful() {
|
||||
return failures.isEmpty();
|
||||
}
|
||||
|
||||
public int recoveredTransactions() {
|
||||
return restoredPreparedTransactions + cleanedCommittedTransactions + cleanedOrphanTransactions;
|
||||
}
|
||||
|
||||
public record Failure(Path transactionRoot, Throwable cause) {
|
||||
public Failure {
|
||||
Objects.requireNonNull(transactionRoot, "transactionRoot");
|
||||
Objects.requireNonNull(cause, "cause");
|
||||
transactionRoot = transactionRoot.toAbsolutePath().normalize();
|
||||
}
|
||||
}
|
||||
}
|
||||
-234
@@ -1,234 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class StructureResourceBundle {
|
||||
private static final Pattern WINDOWS_RESERVED_NAME = Pattern.compile(
|
||||
"(?i)(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\..*)?"
|
||||
);
|
||||
|
||||
private final StructureKey key;
|
||||
private final StructureSource source;
|
||||
private final StructureBackend backend;
|
||||
private final Set<StructureCapability> capabilities;
|
||||
private final List<StructureLoss> losses;
|
||||
private final Map<String, Resource> resources;
|
||||
|
||||
private StructureResourceBundle(Builder builder) {
|
||||
key = builder.key;
|
||||
source = Objects.requireNonNull(builder.source, "source");
|
||||
backend = Objects.requireNonNull(builder.backend, "backend");
|
||||
capabilities = immutableCapabilities(builder.capabilities);
|
||||
losses = List.copyOf(builder.losses);
|
||||
resources = Collections.unmodifiableMap(new TreeMap<>(builder.resources));
|
||||
if (resources.isEmpty()) {
|
||||
throw new IllegalStateException("Structure resource bundle cannot be empty");
|
||||
}
|
||||
}
|
||||
|
||||
public static Builder builder(StructureKey key) {
|
||||
return new Builder(key);
|
||||
}
|
||||
|
||||
public StructureKey key() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public StructureSource source() {
|
||||
return source;
|
||||
}
|
||||
|
||||
public StructureBackend backend() {
|
||||
return backend;
|
||||
}
|
||||
|
||||
public Set<StructureCapability> capabilities() {
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
public List<StructureLoss> losses() {
|
||||
return losses;
|
||||
}
|
||||
|
||||
public Map<String, Resource> resources() {
|
||||
return resources;
|
||||
}
|
||||
|
||||
public static String validateRelativePath(String relativePath) {
|
||||
Objects.requireNonNull(relativePath, "relativePath");
|
||||
if (relativePath.isBlank() || relativePath.startsWith("/") || relativePath.endsWith("/")) {
|
||||
throw new IllegalArgumentException("Resource path must be a non-empty relative path: " + relativePath);
|
||||
}
|
||||
if (relativePath.indexOf('\\') >= 0 || relativePath.indexOf(':') >= 0 || relativePath.contains("//")) {
|
||||
throw new IllegalArgumentException("Resource path is not portable: " + relativePath);
|
||||
}
|
||||
String[] segments = relativePath.split("/");
|
||||
if (segments[0].equalsIgnoreCase(".iris")) {
|
||||
throw new IllegalArgumentException("Resource path uses the reserved .iris directory: " + relativePath);
|
||||
}
|
||||
for (String segment : segments) {
|
||||
validatePathSegment(relativePath, segment);
|
||||
}
|
||||
return relativePath;
|
||||
}
|
||||
|
||||
private static Set<StructureCapability> immutableCapabilities(EnumSet<StructureCapability> capabilities) {
|
||||
if (capabilities.isEmpty()) {
|
||||
return Set.of();
|
||||
}
|
||||
return Collections.unmodifiableSet(EnumSet.copyOf(capabilities));
|
||||
}
|
||||
|
||||
private static void validatePathSegment(String relativePath, String segment) {
|
||||
if (segment.isEmpty() || segment.equals(".") || segment.equals("..") || segment.endsWith(".") || segment.endsWith(" ")) {
|
||||
throw new IllegalArgumentException("Resource path is not portable: " + relativePath);
|
||||
}
|
||||
if (WINDOWS_RESERVED_NAME.matcher(segment).matches()) {
|
||||
throw new IllegalArgumentException("Resource path uses a reserved file name: " + relativePath);
|
||||
}
|
||||
for (int i = 0; i < segment.length(); i++) {
|
||||
char character = segment.charAt(i);
|
||||
if (Character.isISOControl(character) || character == '"' || character == '*' || character == '<'
|
||||
|| character == '>' || character == '?' || character == '|') {
|
||||
throw new IllegalArgumentException("Resource path is not portable: " + relativePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Builder {
|
||||
private final StructureKey key;
|
||||
private final EnumSet<StructureCapability> capabilities;
|
||||
private final List<StructureLoss> losses;
|
||||
private final Map<String, Resource> resources;
|
||||
private final Map<String, String> portableResourcePaths;
|
||||
private StructureSource source;
|
||||
private StructureBackend backend;
|
||||
|
||||
private Builder(StructureKey key) {
|
||||
this.key = Objects.requireNonNull(key, "key");
|
||||
capabilities = EnumSet.noneOf(StructureCapability.class);
|
||||
losses = new ArrayList<>();
|
||||
resources = new TreeMap<>();
|
||||
portableResourcePaths = new HashMap<>();
|
||||
}
|
||||
|
||||
public Builder source(StructureSource source) {
|
||||
this.source = Objects.requireNonNull(source, "source");
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder backend(StructureBackend backend) {
|
||||
this.backend = Objects.requireNonNull(backend, "backend");
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder capability(StructureCapability capability) {
|
||||
capabilities.add(Objects.requireNonNull(capability, "capability"));
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder capabilities(Collection<StructureCapability> capabilities) {
|
||||
Objects.requireNonNull(capabilities, "capabilities");
|
||||
for (StructureCapability capability : capabilities) {
|
||||
capability(capability);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder loss(StructureLoss loss) {
|
||||
losses.add(Objects.requireNonNull(loss, "loss"));
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder losses(Collection<StructureLoss> losses) {
|
||||
Objects.requireNonNull(losses, "losses");
|
||||
for (StructureLoss loss : losses) {
|
||||
loss(loss);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder resource(String relativePath, byte[] content) {
|
||||
Resource resource = new Resource(relativePath, content);
|
||||
String portablePath = resource.relativePath().toLowerCase(Locale.ROOT);
|
||||
String previousPath = portableResourcePaths.putIfAbsent(portablePath, resource.relativePath());
|
||||
if (previousPath != null) {
|
||||
throw new IllegalArgumentException("Duplicate structure resource: " + relativePath);
|
||||
}
|
||||
resources.put(resource.relativePath(), resource);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder textResource(String relativePath, String content) {
|
||||
Objects.requireNonNull(content, "content");
|
||||
return resource(relativePath, content.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public StructureResourceBundle build() {
|
||||
return new StructureResourceBundle(this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Resource {
|
||||
private final String relativePath;
|
||||
private final byte[] content;
|
||||
private final String contentHash;
|
||||
|
||||
private Resource(String relativePath, byte[] content) {
|
||||
this.relativePath = validateRelativePath(relativePath);
|
||||
Objects.requireNonNull(content, "content");
|
||||
this.content = content.clone();
|
||||
contentHash = StructureHash.sha256(this.content);
|
||||
}
|
||||
|
||||
public String relativePath() {
|
||||
return relativePath;
|
||||
}
|
||||
|
||||
public byte[] content() {
|
||||
return content.clone();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return content.length;
|
||||
}
|
||||
|
||||
public String contentHash() {
|
||||
return contentHash;
|
||||
}
|
||||
|
||||
byte[] contentForWrite() {
|
||||
return content;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public record StructureSource(Kind kind, StructureKey key, String version, String contentHash) {
|
||||
public StructureSource {
|
||||
Objects.requireNonNull(kind, "kind");
|
||||
Objects.requireNonNull(key, "key");
|
||||
Objects.requireNonNull(version, "version");
|
||||
Objects.requireNonNull(contentHash, "contentHash");
|
||||
if (!contentHash.isEmpty() && !StructureHash.isSha256(contentHash)) {
|
||||
throw new IllegalArgumentException("Source content hash must be SHA-256");
|
||||
}
|
||||
}
|
||||
|
||||
public static StructureSource of(Kind kind, StructureKey key) {
|
||||
return new StructureSource(kind, key, "", "");
|
||||
}
|
||||
|
||||
public static StructureSource identified(Kind kind, StructureKey key, String version, byte[] content) {
|
||||
return new StructureSource(kind, key, version, StructureHash.sha256(content));
|
||||
}
|
||||
|
||||
public enum Kind {
|
||||
IRIS,
|
||||
VANILLA,
|
||||
DATAPACK,
|
||||
MOD,
|
||||
UNKNOWN
|
||||
}
|
||||
}
|
||||
-143
@@ -1,143 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
record StructureTransactionJournal(
|
||||
int schemaVersion,
|
||||
UUID transactionId,
|
||||
Phase phase,
|
||||
List<Target> targets
|
||||
) {
|
||||
static final int CURRENT_SCHEMA_VERSION = 1;
|
||||
static final String FILE_NAME = "transaction.json";
|
||||
static final String NEXT_FILE_NAME = "transaction.json.next";
|
||||
private static final int MAX_TARGETS = 100_000;
|
||||
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
private static final Pattern MANIFEST_PATH = Pattern.compile(
|
||||
"\\.iris/structure-manifests/key-[a-f0-9]{64}\\.json"
|
||||
);
|
||||
|
||||
StructureTransactionJournal {
|
||||
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
|
||||
throw new IllegalArgumentException("Unsupported structure transaction schema: " + schemaVersion);
|
||||
}
|
||||
Objects.requireNonNull(transactionId, "transactionId");
|
||||
Objects.requireNonNull(phase, "phase");
|
||||
Objects.requireNonNull(targets, "targets");
|
||||
if (targets.isEmpty()) {
|
||||
throw new IllegalArgumentException("Structure transaction must contain at least one target");
|
||||
}
|
||||
if (targets.size() > MAX_TARGETS) {
|
||||
throw new IllegalArgumentException("Structure transaction contains too many targets");
|
||||
}
|
||||
ArrayList<Target> orderedTargets = new ArrayList<>(targets);
|
||||
orderedTargets.sort(Comparator.comparing(Target::relativePath));
|
||||
Set<String> portablePaths = new HashSet<>(orderedTargets.size());
|
||||
for (Target target : orderedTargets) {
|
||||
String portablePath = target.relativePath().toLowerCase(Locale.ROOT);
|
||||
if (!portablePaths.add(portablePath)) {
|
||||
throw new IllegalArgumentException("Structure transaction contains duplicate target "
|
||||
+ target.relativePath());
|
||||
}
|
||||
}
|
||||
targets = List.copyOf(orderedTargets);
|
||||
}
|
||||
|
||||
static StructureTransactionJournal prepared(UUID transactionId, List<Target> targets) {
|
||||
return new StructureTransactionJournal(CURRENT_SCHEMA_VERSION, transactionId, Phase.PREPARED, targets);
|
||||
}
|
||||
|
||||
static StructureTransactionJournal fromJson(byte[] content) {
|
||||
Objects.requireNonNull(content, "content");
|
||||
StructureTransactionJournal journal = GSON.fromJson(
|
||||
new String(content, StandardCharsets.UTF_8),
|
||||
StructureTransactionJournal.class
|
||||
);
|
||||
if (journal == null) {
|
||||
throw new IllegalArgumentException("Structure transaction journal is empty");
|
||||
}
|
||||
return journal;
|
||||
}
|
||||
|
||||
StructureTransactionJournal committed() {
|
||||
return new StructureTransactionJournal(schemaVersion, transactionId, Phase.COMMITTED, targets);
|
||||
}
|
||||
|
||||
byte[] toJson() {
|
||||
return GSON.toJson(this).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
enum Phase {
|
||||
PREPARED,
|
||||
COMMITTED
|
||||
}
|
||||
|
||||
record Target(
|
||||
String relativePath,
|
||||
boolean hadOriginal,
|
||||
String originalHash,
|
||||
String replacementHash
|
||||
) {
|
||||
Target {
|
||||
Objects.requireNonNull(relativePath, "relativePath");
|
||||
Objects.requireNonNull(originalHash, "originalHash");
|
||||
Objects.requireNonNull(replacementHash, "replacementHash");
|
||||
if (relativePath.startsWith(".iris/")) {
|
||||
StructureResourceBundle.validateRelativePath("transaction/" + relativePath);
|
||||
if (!MANIFEST_PATH.matcher(relativePath).matches()) {
|
||||
throw new IllegalArgumentException("Invalid internal structure transaction target: "
|
||||
+ relativePath);
|
||||
}
|
||||
} else {
|
||||
relativePath = StructureResourceBundle.validateRelativePath(relativePath);
|
||||
}
|
||||
if (hadOriginal && !StructureHash.isSha256(originalHash)) {
|
||||
throw new IllegalArgumentException("Structure transaction original hash is invalid for "
|
||||
+ relativePath);
|
||||
}
|
||||
if (!hadOriginal && !originalHash.isEmpty()) {
|
||||
throw new IllegalArgumentException("Structure transaction has a hash for a new target "
|
||||
+ relativePath);
|
||||
}
|
||||
if (!replacementHash.isEmpty() && !StructureHash.isSha256(replacementHash)) {
|
||||
throw new IllegalArgumentException("Structure transaction replacement hash is invalid for "
|
||||
+ relativePath);
|
||||
}
|
||||
if (!hadOriginal && replacementHash.isEmpty()) {
|
||||
throw new IllegalArgumentException("Structure transaction new target has no replacement hash for "
|
||||
+ relativePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-147
@@ -1,147 +0,0 @@
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
|
||||
public record StructureTransactionReadSet(
|
||||
Map<String, String> fileHashes,
|
||||
Set<String> absentPaths,
|
||||
Map<String, List<String>> directoryEntries
|
||||
) {
|
||||
public static final int MAX_ENTRIES = 100_000;
|
||||
|
||||
public StructureTransactionReadSet {
|
||||
Objects.requireNonNull(fileHashes, "fileHashes");
|
||||
Objects.requireNonNull(absentPaths, "absentPaths");
|
||||
Objects.requireNonNull(directoryEntries, "directoryEntries");
|
||||
TreeMap<String, String> orderedHashes = new TreeMap<>();
|
||||
for (Map.Entry<String, String> entry : fileHashes.entrySet()) {
|
||||
String path = validatePath(entry.getKey(), false);
|
||||
String hash = Objects.requireNonNull(entry.getValue(), "read-set file hash");
|
||||
if (!StructureHash.isSha256(hash)) {
|
||||
throw new IllegalArgumentException("Read-set file hash must be SHA-256 for " + path);
|
||||
}
|
||||
orderedHashes.put(path, hash);
|
||||
}
|
||||
TreeSet<String> orderedAbsent = new TreeSet<>();
|
||||
for (String path : absentPaths) {
|
||||
orderedAbsent.add(validatePath(path, false));
|
||||
}
|
||||
for (String path : orderedHashes.keySet()) {
|
||||
if (orderedAbsent.contains(path)) {
|
||||
throw new IllegalArgumentException("Read-set path cannot be both present and absent: " + path);
|
||||
}
|
||||
}
|
||||
TreeMap<String, List<String>> orderedDirectories = new TreeMap<>();
|
||||
TreeSet<String> uniqueEntries = new TreeSet<>(orderedHashes.keySet());
|
||||
uniqueEntries.addAll(orderedAbsent);
|
||||
for (Map.Entry<String, List<String>> entry : directoryEntries.entrySet()) {
|
||||
String directory = validatePath(entry.getKey(), true);
|
||||
uniqueEntries.add(directory);
|
||||
Objects.requireNonNull(entry.getValue(), "read-set directory entries");
|
||||
TreeSet<String> entries = new TreeSet<>();
|
||||
for (String child : entry.getValue()) {
|
||||
String childPath = validatePath(child, false);
|
||||
if (!childPath.startsWith(directory + "/")) {
|
||||
throw new IllegalArgumentException(
|
||||
"Read-set directory entry is outside " + directory + ": " + childPath);
|
||||
}
|
||||
entries.add(childPath);
|
||||
}
|
||||
uniqueEntries.addAll(entries);
|
||||
orderedDirectories.put(directory, List.copyOf(entries));
|
||||
}
|
||||
if (uniqueEntries.size() > MAX_ENTRIES) {
|
||||
throw new IllegalArgumentException("Read set exceeds " + MAX_ENTRIES + " entries");
|
||||
}
|
||||
fileHashes = Collections.unmodifiableMap(orderedHashes);
|
||||
absentPaths = Collections.unmodifiableSet(orderedAbsent);
|
||||
directoryEntries = Collections.unmodifiableMap(orderedDirectories);
|
||||
}
|
||||
|
||||
public static StructureTransactionReadSet empty() {
|
||||
return new StructureTransactionReadSet(Map.of(), Set.of(), Map.of());
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return fileHashes.isEmpty() && absentPaths.isEmpty() && directoryEntries.isEmpty();
|
||||
}
|
||||
|
||||
public List<String> paths() {
|
||||
TreeSet<String> paths = new TreeSet<>(fileHashes.keySet());
|
||||
paths.addAll(absentPaths);
|
||||
for (List<String> entries : directoryEntries.values()) {
|
||||
paths.addAll(entries);
|
||||
}
|
||||
return List.copyOf(paths);
|
||||
}
|
||||
|
||||
public static Builder builder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
private static String validatePath(String value, boolean directory) {
|
||||
Objects.requireNonNull(value, "read-set path");
|
||||
String normalized = value.trim();
|
||||
if (normalized.isEmpty() || !normalized.equals(value) || normalized.startsWith("/")
|
||||
|| normalized.endsWith("/") || normalized.indexOf('\\') >= 0 || normalized.contains(":")) {
|
||||
throw new IllegalArgumentException("Invalid read-set path: " + value);
|
||||
}
|
||||
Path path = Path.of(normalized).normalize();
|
||||
if (path.isAbsolute() || path.getNameCount() == 0 || path.startsWith("..")
|
||||
|| path.toString().equals(".")) {
|
||||
throw new IllegalArgumentException("Invalid read-set path: " + value);
|
||||
}
|
||||
String portable = path.toString().replace('\\', '/');
|
||||
if (!portable.equals(normalized)) {
|
||||
throw new IllegalArgumentException("Read-set path is not normalized: " + value);
|
||||
}
|
||||
if (!directory && normalized.endsWith("/.")) {
|
||||
throw new IllegalArgumentException("Invalid read-set file path: " + value);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
public static final class Builder {
|
||||
private final Map<String, String> fileHashes = new TreeMap<>();
|
||||
private final Set<String> absentPaths = new TreeSet<>();
|
||||
private final Map<String, List<String>> directoryEntries = new TreeMap<>();
|
||||
|
||||
public Builder file(String relativePath, String contentHash) {
|
||||
fileHashes.put(relativePath, contentHash);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder files(Map<String, String> hashes) {
|
||||
fileHashes.putAll(Objects.requireNonNull(hashes, "read-set files"));
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder absent(String relativePath) {
|
||||
absentPaths.add(relativePath);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder absent(Collection<String> relativePaths) {
|
||||
absentPaths.addAll(Objects.requireNonNull(relativePaths, "absent read-set paths"));
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder directory(String relativePath, Collection<String> entries) {
|
||||
directoryEntries.put(relativePath, new ArrayList<>(Objects.requireNonNull(entries, "directory entries")));
|
||||
return this;
|
||||
}
|
||||
|
||||
public StructureTransactionReadSet build() {
|
||||
return new StructureTransactionReadSet(fileHashes, absentPaths, directoryEntries);
|
||||
}
|
||||
}
|
||||
}
|
||||
-2394
File diff suppressed because it is too large.
Load diff
@@ -1,24 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
public enum StructureWriteMode {
|
||||
ADD_ONLY,
|
||||
OVERWRITE
|
||||
}
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public record StructureWriteOptions(StructureWriteMode mode, boolean dryRun, String expectedManifestHash) {
|
||||
public StructureWriteOptions {
|
||||
Objects.requireNonNull(mode, "mode");
|
||||
expectedManifestHash = expectedManifestHash == null ? "" : expectedManifestHash.trim();
|
||||
if (!expectedManifestHash.isEmpty() && !StructureHash.isSha256(expectedManifestHash)) {
|
||||
throw new IllegalArgumentException("Expected structure manifest hash must be SHA-256");
|
||||
}
|
||||
if (!expectedManifestHash.isEmpty() && mode != StructureWriteMode.OVERWRITE) {
|
||||
throw new IllegalArgumentException("Expected structure manifest hashes require overwrite mode");
|
||||
}
|
||||
}
|
||||
|
||||
public StructureWriteOptions(StructureWriteMode mode, boolean dryRun) {
|
||||
this(mode, dryRun, "");
|
||||
}
|
||||
|
||||
public static StructureWriteOptions addOnly() {
|
||||
return new StructureWriteOptions(StructureWriteMode.ADD_ONLY, false);
|
||||
}
|
||||
|
||||
public static StructureWriteOptions overwrite() {
|
||||
return new StructureWriteOptions(StructureWriteMode.OVERWRITE, false);
|
||||
}
|
||||
|
||||
public static StructureWriteOptions preview(StructureWriteMode mode) {
|
||||
return new StructureWriteOptions(mode, true);
|
||||
}
|
||||
|
||||
public static StructureWriteOptions overwriteExpected(String manifestHash) {
|
||||
return new StructureWriteOptions(StructureWriteMode.OVERWRITE, false, manifestHash);
|
||||
}
|
||||
}
|
||||
-147
@@ -1,147 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure.authoring;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public record StructureWriteResult(
|
||||
Status status,
|
||||
Action action,
|
||||
List<Conflict> conflicts,
|
||||
List<String> affectedResources,
|
||||
String manifestPath,
|
||||
Optional<Throwable> failure
|
||||
) {
|
||||
public StructureWriteResult {
|
||||
Objects.requireNonNull(status, "status");
|
||||
Objects.requireNonNull(action, "action");
|
||||
Objects.requireNonNull(conflicts, "conflicts");
|
||||
Objects.requireNonNull(affectedResources, "affectedResources");
|
||||
Objects.requireNonNull(manifestPath, "manifestPath");
|
||||
Objects.requireNonNull(failure, "failure");
|
||||
conflicts = List.copyOf(conflicts);
|
||||
affectedResources = List.copyOf(affectedResources);
|
||||
}
|
||||
|
||||
public boolean successful() {
|
||||
return switch (status) {
|
||||
case DRY_RUN, ADDED, OVERWRITTEN, UNCHANGED, COMMITTED_CLEANUP_REQUIRED -> true;
|
||||
case ADD_ONLY_CONFLICT, OWNERSHIP_CONFLICT, ROLLED_BACK, FAILED -> false;
|
||||
};
|
||||
}
|
||||
|
||||
public boolean committed() {
|
||||
return switch (status) {
|
||||
case ADDED, OVERWRITTEN, UNCHANGED, COMMITTED_CLEANUP_REQUIRED -> true;
|
||||
case DRY_RUN, ADD_ONLY_CONFLICT, OWNERSHIP_CONFLICT, ROLLED_BACK, FAILED -> false;
|
||||
};
|
||||
}
|
||||
|
||||
public enum Status {
|
||||
DRY_RUN,
|
||||
ADDED,
|
||||
OVERWRITTEN,
|
||||
UNCHANGED,
|
||||
ADD_ONLY_CONFLICT,
|
||||
OWNERSHIP_CONFLICT,
|
||||
ROLLED_BACK,
|
||||
FAILED,
|
||||
COMMITTED_CLEANUP_REQUIRED
|
||||
}
|
||||
|
||||
public enum Action {
|
||||
ADD,
|
||||
OVERWRITE,
|
||||
NONE
|
||||
}
|
||||
|
||||
public enum ConflictReason {
|
||||
RESOURCE_EXISTS,
|
||||
MANIFEST_EXISTS,
|
||||
UNOWNED_RESOURCE,
|
||||
MODIFIED_RESOURCE,
|
||||
MISSING_OWNED_RESOURCE,
|
||||
NON_FILE_RESOURCE,
|
||||
INVALID_MANIFEST,
|
||||
PROVENANCE_MISMATCH,
|
||||
STALE_MANIFEST,
|
||||
STALE_READ_SET
|
||||
}
|
||||
|
||||
public record Conflict(
|
||||
String relativePath,
|
||||
ConflictReason reason,
|
||||
String expectedHash,
|
||||
String actualHash,
|
||||
String detail
|
||||
) {
|
||||
public Conflict {
|
||||
Objects.requireNonNull(relativePath, "relativePath");
|
||||
Objects.requireNonNull(reason, "reason");
|
||||
Objects.requireNonNull(expectedHash, "expectedHash");
|
||||
Objects.requireNonNull(actualHash, "actualHash");
|
||||
Objects.requireNonNull(detail, "detail");
|
||||
}
|
||||
|
||||
public static Conflict at(String relativePath, ConflictReason reason) {
|
||||
return new Conflict(relativePath, reason, "", "", "");
|
||||
}
|
||||
|
||||
public static Conflict modified(String relativePath, String expectedHash, String actualHash) {
|
||||
return new Conflict(
|
||||
relativePath,
|
||||
ConflictReason.MODIFIED_RESOURCE,
|
||||
expectedHash,
|
||||
actualHash,
|
||||
"Resource content differs from its ownership manifest"
|
||||
);
|
||||
}
|
||||
|
||||
public static Conflict invalidManifest(String relativePath, String detail) {
|
||||
return new Conflict(relativePath, ConflictReason.INVALID_MANIFEST, "", "", detail);
|
||||
}
|
||||
|
||||
public static Conflict staleManifest(String relativePath, String expectedHash, String actualHash) {
|
||||
return new Conflict(
|
||||
relativePath,
|
||||
ConflictReason.STALE_MANIFEST,
|
||||
expectedHash,
|
||||
actualHash,
|
||||
"Ownership manifest changed after the graph edit was loaded"
|
||||
);
|
||||
}
|
||||
|
||||
public static Conflict staleReadSet(
|
||||
String relativePath,
|
||||
String expectedHash,
|
||||
String actualHash,
|
||||
String detail
|
||||
) {
|
||||
return new Conflict(
|
||||
relativePath,
|
||||
ConflictReason.STALE_READ_SET,
|
||||
expectedHash,
|
||||
actualHash,
|
||||
detail
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
package art.arcane.iris.core.structure.conversion;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public record IrisStructureAdoptionDiagnostic(
|
||||
Severity severity,
|
||||
Code code,
|
||||
String resource,
|
||||
String detail,
|
||||
String recommendation
|
||||
) implements Comparable<IrisStructureAdoptionDiagnostic> {
|
||||
public IrisStructureAdoptionDiagnostic {
|
||||
Objects.requireNonNull(severity, "severity");
|
||||
Objects.requireNonNull(code, "code");
|
||||
resource = normalize(resource);
|
||||
detail = requireText(detail, "detail");
|
||||
recommendation = normalize(recommendation);
|
||||
}
|
||||
|
||||
public String summary() {
|
||||
String location = resource.isEmpty() ? "" : " [" + resource + "]";
|
||||
String action = recommendation.isEmpty() ? "" : " " + recommendation;
|
||||
return severity + " " + code + location + ": " + detail + action;
|
||||
}
|
||||
|
||||
public boolean blocking() {
|
||||
return severity == Severity.ERROR;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(IrisStructureAdoptionDiagnostic other) {
|
||||
int severityComparison = severity.compareTo(other.severity);
|
||||
if (severityComparison != 0) {
|
||||
return severityComparison;
|
||||
}
|
||||
int codeComparison = code.compareTo(other.code);
|
||||
if (codeComparison != 0) {
|
||||
return codeComparison;
|
||||
}
|
||||
int resourceComparison = resource.compareTo(other.resource);
|
||||
if (resourceComparison != 0) {
|
||||
return resourceComparison;
|
||||
}
|
||||
return detail.compareTo(other.detail);
|
||||
}
|
||||
|
||||
private static String requireText(String value, String name) {
|
||||
String normalized = normalize(value);
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException("Adoption diagnostic " + name + " cannot be blank");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
public enum Severity {
|
||||
ERROR,
|
||||
WARNING,
|
||||
INFO
|
||||
}
|
||||
|
||||
public enum Code {
|
||||
SOURCE_GRAPH_INVALID,
|
||||
SOURCE_ALREADY_OWNED,
|
||||
SOURCE_RESOURCE_UNSAFE,
|
||||
SOURCE_RESOURCE_LIMIT,
|
||||
SOURCE_RESOURCE_CHANGED,
|
||||
TARGET_NAMESPACE_UNSUPPORTED,
|
||||
TARGET_RESOURCE_EXISTS,
|
||||
TARGET_RESOURCE_UNSAFE,
|
||||
TARGET_MAPPING_COLLISION,
|
||||
TARGET_REQUIRED_FOR_CLONE,
|
||||
MANAGED_INPUT_REQUIRES_CLONE,
|
||||
SHARED_DEPENDENCY,
|
||||
EXCLUSIVITY_UNPROVEN,
|
||||
IN_PLACE_AVAILABLE,
|
||||
CLONE_SELECTED,
|
||||
PLAN_BLOCKED,
|
||||
PLAN_EXPIRED,
|
||||
PLAN_UNKNOWN,
|
||||
PLAN_STALE,
|
||||
TRANSACTION_FAILED,
|
||||
APPLIED
|
||||
}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package art.arcane.iris.core.structure.conversion;
|
||||
|
||||
public enum IrisStructureAdoptionDisposition {
|
||||
IN_PLACE,
|
||||
CLONE_REQUIRED,
|
||||
BLOCKED
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
package art.arcane.iris.core.structure.conversion;
|
||||
|
||||
public enum IrisStructureAdoptionInputKind {
|
||||
UNOWNED_IRIS,
|
||||
MANAGED_DATAPACK
|
||||
}
|
||||
Loaded 100 of 514 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user