Move structure placement and jigsaw into the built-in modules jar

iris:structure places and locates structures and owns the structure commands; iris:jigsaw owns the model, the
assembler, the importers, the studio and the jigsaw commands. Both load from the jar, and the studio now lives with
its tool world: it is created by the first jigsaw command and closes with the world. The host's structure host,
model module, assemblies seam and studio host are gone. A datapack's structures are imported through the new
DatapackStructureImport service.
This commit is contained in:
piexel committed 2026-11-10 04:04:57 +01:00
1 parent ba8429952a
commit 543e8c615e
235 files changed
+1199 -1006

No files matched your search

@@ -18,17 +18,22 @@
package art.arcane.iris.builtin.structure;
import com.volmit.resource.ResourceId;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Iris extension: says that a text option names structures of Iris's structure model by key, which Iris completes in
* studio and carries along when it exports the pack. The structure model is Iris's own resource kind, whose class a
* module cannot see, so {@code @ResourceRef} cannot name it; to another host the option is plain text.
* Iris extension: says that a text option names structures of the pack's jigsaw module by key, which Iris completes in
* studio and carries along when it exports the pack. It stands for {@code @ResourceRef} of the structure kind, whose class
* lives in the module jar and so cannot be named from this exposed package; Iris resolves it by the kind's id, {@link #KIND}.
* To another host the option is plain text.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface IrisStructureRef {
/** The id of the resource kind of the structures, which {@code iris:jigsaw} registers. */
ResourceId KIND = ResourceId.parse("iris:jigsaw/structure");
}
@@ -1,41 +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.builtin.structure;
import com.volmit.stage.MantleStageContext;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Optional;
/**
* What {@code iris:structure} asks of Iris: Iris places its jigsaw structures itself. The structure model (structures,
* pools, pieces), the assembler that builds a structure from them and the locator that spreads them over the world are
* Iris's, shared with the jigsaw studio and the structure importers and exporters. Iris offers it as an extension of its
* worlds and of the settings of the pack it loads: {@code world.extension(StructureHost.class)}.
*/
public interface StructureHost {
/** Places the structures that start in the chunk whose mantle the mantle invocation {@code context} generates. */
void placeChunk(MantleStageContext context);
/** How far, in blocks along X and Z, a structure may write beyond the chunk it starts in. */
int reach();
/** The loot tables the structure gives its pieces' containers; empty when the pack has no such structure. */
Optional<List<String>> lootTables(ResourceId structure);
}
@@ -0,0 +1,31 @@
/*
* 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.builtin.structure;
import com.volmit.tooling.CommandContext;
/**
* What Iris's running worlds offer {@code iris:structure}'s {@code verify} command: whether each structure can generate
* in the world, which needs the world's native structure policy and biome reachability that only Iris itself reads.
* Ask for it with {@code world.extension(StructureVerifier.class)}.
*/
public interface StructureVerifier {
/** Reports to the sender of {@code context}, for every structure the platform registers and every structure the pack places, whether it can generate within {@code radiusChunks} of the world origin. */
void verify(CommandContext context, int radiusChunks);
}
@@ -0,0 +1,149 @@
/*
* 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.StructureVerifier;
import art.arcane.iris.core.structure.authoring.StructureIndexService;
import art.arcane.iris.core.structure.tooling.PlatformStructuresAccess;
import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece;
import art.arcane.iris.engine.framework.structure.assembly.Assembly;
import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.Argument;
import com.volmit.tooling.Command;
import com.volmit.tooling.CommandContext;
import com.volmit.tooling.PlatformStructures;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/** The {@code /iris module structure} commands of {@code iris:structure}: the index, one structure's graph, and the verification of a world's structures. */
public 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 long DEFAULT_RADIUS_CHUNKS = 48L;
private static final long MAX_RADIUS_CHUNKS = 1000L;
private static final char NAMESPACE_SEPARATOR = ':';
private static final String STRUCTURES_FOLDER = "structures";
private static final Argument<ResourceId> STRUCTURE = Argument.reading("structure", StructureCommands::readStructure)
.describe("The Iris structure to inspect")
.suggesting(StructureCommands::structureKeys);
private 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 StructureCommands() {
}
public 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(RADIUS)
.runs(StructureCommands::verify));
}
private static void list(CommandContext context) throws IOException {
Optional<PlatformStructures> platform = PlatformStructuresAccess.require(context);
if (platform.isEmpty()) {
return;
}
File index = StructureIndexService.write(context.pack(), platform.get());
context.sender().success("Wrote the structure index: " + index.getPath());
}
private static void info(CommandContext context) {
ResourceId id = context.get(STRUCTURE);
Assembly assembly = sampleAssembly(context, id).orElseThrow();
if (!assembly.hasOutput()) {
context.sender().error("Structure " + id + " assembled 0 pieces" + (assembly.detail().isBlank() ? "" : " (" + assembly.detail() + ")"));
return;
}
List<AssembledPiece> pieces = assembly.pieces();
int minX = Integer.MAX_VALUE;
int minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxZ = Integer.MIN_VALUE;
for (AssembledPiece piece : pieces) {
minX = Math.min(minX, piece.minX());
minZ = Math.min(minZ, piece.minZ());
maxX = Math.max(maxX, piece.maxX());
maxZ = Math.max(maxZ, piece.maxZ());
}
context.sender().success("Structure " + id + ": " + pieces.size() + " pieces, footprint " + (maxX - minX + 1) + "x"
+ (maxZ - minZ + 1) + " blocks (sample seed " + INFO_SAMPLE_SEED + ")");
}
private static Optional<Assembly> sampleAssembly(CommandContext context, ResourceId id) {
PackResources resources = context.pack().resources();
BlockPosition origin = new BlockPosition(0, INFO_ORIGIN_Y, 0);
for (StructureAssembly provider : context.pack().services(StructureAssembly.class)) {
Optional<Assembly> assembly = provider.assemble(resources, id, origin, new RNG(INFO_SAMPLE_SEED));
if (assembly.isPresent()) {
return assembly;
}
}
return Optional.empty();
}
private static void verify(CommandContext context) {
Optional<StructureVerifier> verifier = context.world().flatMap(world -> world.extension(StructureVerifier.class));
if (verifier.isEmpty()) {
context.sender().error("Stand in a world generated with this pack: verify reads the running world");
return;
}
verifier.get().verify(context, Math.toIntExact(context.get(RADIUS)));
}
private static ResourceId readStructure(String written, CommandContext context) {
PackResources resources = context.pack().resources();
ResourceId id = written.indexOf(NAMESPACE_SEPARATOR) < 0 ? resources.idOf(written) : ResourceId.parse(written);
boolean known = context.pack().services(StructureAssembly.class).stream().anyMatch(provider -> provider.knows(resources, id));
if (!known) {
throw new IllegalArgumentException("No " + STRUCTURES_FOLDER + " resource '" + written + "' in this pack");
}
return id;
}
private static List<String> structureKeys(CommandContext context) {
PackResources resources = context.pack().resources();
Set<String> keys = new LinkedHashSet<>();
for (StructureAssembly provider : context.pack().services(StructureAssembly.class)) {
provider.structures(resources).forEach(id -> keys.add(resources.idOf(id.path()).equals(id) ? id.path() : id.toString()));
}
return List.copyOf(keys);
}
}
@@ -0,0 +1,605 @@
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);
}
}
}
@@ -0,0 +1,78 @@
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);
}
}
@@ -0,0 +1,38 @@
package art.arcane.iris.core.runtime.jigsaw;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection;
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 JigsawDirection direction() {
return switch (this) {
case NORTH -> JigsawDirection.NORTH_NEGATIVE_Z;
case EAST -> JigsawDirection.EAST_POSITIVE_X;
case SOUTH -> JigsawDirection.SOUTH_POSITIVE_Z;
case WEST -> JigsawDirection.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);
}
}
@@ -0,0 +1,100 @@
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);
};
}
}
@@ -0,0 +1,10 @@
package art.arcane.iris.core.runtime.jigsaw;
public enum JigsawPlanarTopologyKind {
BLANK,
END,
STRAIGHT,
CORNER,
TEE,
CROSS
}
@@ -0,0 +1,31 @@
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;
}
}
@@ -0,0 +1,62 @@
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;
}
}
@@ -0,0 +1,6 @@
package art.arcane.iris.core.runtime.jigsaw;
public enum JigsawStudioBayKind {
PLANAR_WORKCELL,
SPATIAL_WORKCELL
}
@@ -0,0 +1,37 @@
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;
}
}
@@ -0,0 +1,30 @@
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;
}
}
@@ -0,0 +1,6 @@
package art.arcane.iris.core.runtime.jigsaw;
public enum JigsawStudioCompatibilityTarget {
IRIS_EXTENDED,
VANILLA_PORTABLE
}
@@ -0,0 +1,4 @@
package art.arcane.iris.core.runtime.jigsaw;
public record JigsawStudioControlPosition(int worldX, int worldY, int worldZ) {
}
@@ -0,0 +1,394 @@
package art.arcane.iris.core.runtime.jigsaw;
import art.arcane.iris.engine.framework.structure.ObjectFrame;
import art.arcane.iris.engine.framework.structure.StructureResources;
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.structure.jigsaw.JigsawDirection;
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.structure.IrisStructure;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.PackResources;
import com.volmit.tooling.ToolPack;
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() {
}
/**
* The studio layout of {@code structure}, the structure {@code structureKey} of {@code pack}, whose files are below {@code packRoot}.
*/
public static JigsawStudioLayout map(ToolPack pack, Path packRoot, String structureKey, IrisStructure structure) {
Source data = new Source(Objects.requireNonNull(pack, "Jigsaw Studio graph mapping requires a pack").resources(),
Objects.requireNonNull(packRoot, "Jigsaw Studio graph mapping requires the pack folder"), structureKey);
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);
BlockPosition configuredCell = structure.getCellSize();
JigsawStudioCellDimensions dimensions = configuredCell == null
? new JigsawStudioCellDimensions(15, 15, 15)
: new JigsawStudioCellDimensions(
Math.max(1, configuredCell.x()),
Math.max(1, configuredCell.y()),
Math.max(1, configuredCell.z()));
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(
ToolPack pack,
Path packRoot,
String structureKey,
IrisStructure structure,
JigsawStudioMode mode
) {
return catalog(new Source(Objects.requireNonNull(pack, "Jigsaw Studio catalog pack").resources(),
Objects.requireNonNull(packRoot, "Jigsaw Studio catalog pack folder"), structureKey), structure, mode);
}
private static JigsawStudioVariantCatalog catalog(Source data, IrisStructure structure, JigsawStudioMode mode) {
Source source = 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(
Source data,
JigsawStudioVariantCatalog catalog,
JigsawStudioCellDimensions configured
) {
int width = configured.width();
int height = configured.height();
int depth = configured.depth();
for (JigsawStudioVariant variant : catalog.spatialVariants()) {
ObjectFrame object = data.objectFrame(variant.objectKey());
if (object == null) {
continue;
}
int objectWidth = object.width();
int objectDepth = object.depth();
if (variant.rotatable()) {
int horizontalSpan = Math.max(objectWidth, objectDepth);
objectWidth = horizontalSpan;
objectDepth = horizontalSpan;
}
width = Math.max(width, objectWidth);
height = Math.max(height, object.height());
depth = Math.max(depth, objectDepth);
}
return new JigsawStudioCellDimensions(width, height, depth);
}
private static void traversePools(
Source 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.resources(), 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.resources(), 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(
Source data,
JigsawStudioMode mode,
OwnedResources owned,
String pieceKey,
Map<String, MutableVariant> variants
) {
if (variants.containsKey(pieceKey)) {
return;
}
IrisJigsawPiece piece = StructureResources.piece(data.resources(), 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(Source data, IrisStructure structure) {
String structureKey = data.structureKey();
if (structureKey == null || structureKey.isBlank()) {
return OwnedResources.empty();
}
try {
Path root = data.root().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(JigsawDirection 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(Source 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(
Source data,
IrisJigsawPiece piece,
JigsawStudioMode mode
) {
ObjectFrame object = data.objectFrame(piece.getObject());
if (object == null) {
return Optional.empty();
}
JigsawStudioCellDimensions sourceDimensions = new JigsawStudioCellDimensions(
object.width(),
object.height(),
object.depth());
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()));
}
}
/** What the mapper reads: the pack's resources, its folder for the ownership manifests, and the key of the mapped structure. */
record Source(PackResources resources, Path root, String structureKey) {
/** The declared size of the object the pack key {@code key} names; null when the pack has none. */
private ObjectFrame objectFrame(String key) {
return resources.objects().sizeOf(resources.idOf(key)).map(ObjectFrame::of).orElse(null);
}
}
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);
}
}
}
@@ -0,0 +1,344 @@
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);
}
}
@@ -0,0 +1,35 @@
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;
}
}
@@ -0,0 +1,6 @@
package art.arcane.iris.core.runtime.jigsaw;
public enum JigsawStudioMode {
PLANAR_JIGSAW,
SPATIAL_JIGSAW
}
@@ -0,0 +1,59 @@
package art.arcane.iris.core.runtime.jigsaw;
import art.arcane.iris.core.structure.DeclaredObjects;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* An object as the studio edits it: a declared size, and blocks and block entities at positions counted from the
* object's minimum corner.
*/
record JigsawStudioObject(
int width,
int height,
int depth,
Map<BlockPosition, BlockState> blocks,
Map<BlockPosition, BlockEntityData> blockEntities
) {
JigsawStudioObject {
blocks = Collections.unmodifiableMap(new LinkedHashMap<>(blocks));
blockEntities = Collections.unmodifiableMap(new LinkedHashMap<>(blockEntities));
}
/** An object of the given size without a block. */
static JigsawStudioObject empty(int width, int height, int depth) {
return new JigsawStudioObject(width, height, depth, Map.of(), Map.of());
}
static JigsawStudioObject of(GeneratedObject object) {
BlockPosition size = DeclaredObjects.sizeOf(object);
Map<BlockPosition, BlockState> blocks = new LinkedHashMap<>();
Map<BlockPosition, BlockEntityData> blockEntities = new LinkedHashMap<>();
for (ObjectBlock block : object.blocks()) {
BlockPosition corner = DeclaredObjects.fromCorner(object, block.position());
blocks.put(corner, block.state());
block.blockEntity().ifPresent(entity -> blockEntities.put(corner, entity));
}
return new JigsawStudioObject(size.x(), size.y(), size.z(), blocks, blockEntities);
}
/** This object's contents in an object of another size, with blocks and block entities the caller edited. */
JigsawStudioObject with(int width, int height, int depth,
Map<BlockPosition, BlockState> blocks, Map<BlockPosition, BlockEntityData> blockEntities) {
return new JigsawStudioObject(width, height, depth, blocks, blockEntities);
}
GeneratedObject toGenerated() {
DeclaredObjects.Builder builder = DeclaredObjects.builder(width, height, depth);
blocks.forEach((position, state) -> builder.state(position.x(), position.y(), position.z(), state));
blockEntities.forEach((position, entity) -> builder.blockEntity(position.x(), position.y(), position.z(), entity));
return builder.build();
}
}
@@ -0,0 +1,34 @@
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());
}
}
@@ -0,0 +1,442 @@
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) {
}
}
@@ -0,0 +1,22 @@
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");
}
}
}
@@ -0,0 +1,291 @@
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.structure.jigsaw.JigsawDirection;
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.core.structure.DeclaredObjects;
import art.arcane.iris.engine.object.structure.IrisStructure;
import com.volmit.geometry.BlockPosition;
import com.volmit.tooling.ObjectCodec;
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<JigsawDirection> SPATIAL_CONNECTOR_ORDER = List.of(
JigsawDirection.NORTH_NEGATIVE_Z,
JigsawDirection.SOUTH_POSITIVE_Z,
JigsawDirection.EAST_POSITIVE_X,
JigsawDirection.WEST_NEGATIVE_X,
JigsawDirection.UP_POSITIVE_Y,
JigsawDirection.DOWN_NEGATIVE_Y);
private JigsawStudioProjectCreator() {
}
public static StructureWriteResult create(Path packRoot, ObjectCodec codec, Options options) throws IOException {
Options activeOptions = Objects.requireNonNull(options, "Jigsaw Studio project options");
StructureResourceBundle bundle = bundle(codec, activeOptions);
StructureResourceBundleGraphCompiler.requireViable(bundle);
return new StructureTransactionWriter(packRoot).write(bundle, StructureWriteMode.ADD_ONLY);
}
static StructureResourceBundle bundle(ObjectCodec codec, 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 BlockPosition(
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, codec, structure, pool, options);
} else {
addSpatialDefaults(bundle, codec, 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();
}
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,
ObjectCodec codec,
IrisStructure structure,
IrisJigsawPool pool,
Options options
) throws IOException {
JigsawStudioCellDimensions dimensions = options.cellDimensions();
BlockPosition size = new BlockPosition(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 + codec.extension(), codec.encode(DeclaredObjects.empty(
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,
ObjectCodec codec,
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 + codec.extension(), codec.encode(DeclaredObjects.empty(
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++) {
JigsawDirection direction = SPATIAL_CONNECTOR_ORDER.get(index);
piece.getConnectors().add(new IrisJigsawConnector()
.setPosition(spatialConnectorPosition(dimensions, direction))
.setDirection(direction)
.setTop(direction.isVertical()
? JigsawDirection.NORTH_NEGATIVE_Z
: JigsawDirection.UP_POSITIVE_Y)
.setPool(poolKey)
.setName("iris:spatial")
.setTargetName("iris:spatial")
.setJoint(JigsawJoint.ROLLABLE)
.setFinalState("minecraft:structure_void"));
}
return piece;
}
private static BlockPosition spatialConnectorPosition(
JigsawStudioCellDimensions dimensions,
JigsawDirection direction
) {
int centerX = dimensions.width() / 2;
int centerY = dimensions.height() / 2;
int centerZ = dimensions.depth() / 2;
return switch (direction) {
case NORTH_NEGATIVE_Z -> new BlockPosition(centerX, centerY, 0);
case SOUTH_POSITIVE_Z -> new BlockPosition(centerX, centerY, dimensions.depth() - 1);
case EAST_POSITIVE_X -> new BlockPosition(dimensions.width() - 1, centerY, centerZ);
case WEST_NEGATIVE_X -> new BlockPosition(0, centerY, centerZ);
case UP_POSITIVE_Y -> new BlockPosition(centerX, dimensions.height() - 1, centerZ);
case DOWN_NEGATIVE_Y -> new BlockPosition(centerX, 0, centerZ);
};
}
private static IrisJigsawPiece planarPiece(
String objectKey,
String poolKey,
BlockPosition dimensions,
JigsawPlanarArchetype archetype
) {
IrisJigsawPiece piece = new IrisJigsawPiece().setObject(objectKey).setRotatable(true);
for (JigsawPlanarDirection planarDirection : archetype.canonicalTopology().directions()) {
JigsawDirection direction = planarDirection.direction();
piece.getConnectors().add(new IrisJigsawConnector()
.setPosition(IrisJigsawConnector.canonicalPlanarPosition(dimensions, direction))
.setDirection(direction)
.setTop(JigsawDirection.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;
}
}
}
@@ -0,0 +1,435 @@
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
) {
}
}
@@ -0,0 +1,689 @@
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);
}
}
}
@@ -0,0 +1,471 @@
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.structure.IrisStructure;
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.DataInputStream;
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);
int[] size = sampleSize(objectPath);
if (size[0] > dimensions.width()
|| size[1] > dimensions.height()
|| size[2] > dimensions.depth()) {
throw new IOException("Owned object '" + relativePath + "' is "
+ size[0] + "x" + size[1] + "x" + size[2]
+ " and does not fit the requested cell bounds");
}
}
}
/** The declared width, height and depth in the header of an {@code .iob} file. */
private static int[] sampleSize(Path objectPath) throws IOException {
try (DataInputStream header = new DataInputStream(Files.newInputStream(objectPath))) {
return new int[]{header.readInt(), header.readInt(), header.readInt()};
}
}
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
) {
}
}
@@ -0,0 +1,45 @@
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;
}
}
@@ -0,0 +1,111 @@
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;
}
}
@@ -0,0 +1,112 @@
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
) {
}
}
@@ -0,0 +1,141 @@
package art.arcane.iris.core.runtime.jigsaw;
import com.volmit.geometry.BlockPosition;
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 BlockPosition sourceToCanonicalPosition(
BlockPosition sourcePosition,
JigsawStudioCellDimensions sourceDimensions
) {
return rotatePosition(
sourcePosition,
sourceDimensions,
sourceToCanonicalQuarterTurns());
}
public BlockPosition canonicalToSourcePosition(
BlockPosition 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 BlockPosition rotatePosition(
BlockPosition position,
JigsawStudioCellDimensions dimensions,
int quarterTurns
) {
BlockPosition source = Objects.requireNonNull(position, "Jigsaw Studio variant position");
JigsawStudioCellDimensions bounds = Objects.requireNonNull(
dimensions,
"Jigsaw Studio variant position bounds");
if (source.x() < 0 || source.x() >= bounds.width()
|| source.y() < 0 || source.y() >= bounds.height()
|| source.z() < 0 || source.z() >= bounds.depth()) {
throw new IllegalArgumentException("Jigsaw Studio variant position is outside its object bounds");
}
return switch (Math.floorMod(quarterTurns, 4)) {
case 0 -> new BlockPosition(source.x(), source.y(), source.z());
case 1 -> new BlockPosition(
bounds.depth() - 1 - source.z(),
source.y(),
source.x());
case 2 -> new BlockPosition(
bounds.width() - 1 - source.x(),
source.y(),
bounds.depth() - 1 - source.z());
case 3 -> new BlockPosition(
source.z(),
source.y(),
bounds.width() - 1 - source.x());
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;
}
}
@@ -0,0 +1,95 @@
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();
}
}
@@ -0,0 +1,20 @@
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;
}
}
@@ -0,0 +1,48 @@
package art.arcane.iris.core.service;
import art.arcane.iris.engine.framework.structure.assembly.PieceTurn;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import java.util.Set;
/** The few block facts the studio needs, asked of api block states. */
public final class JigsawStudioBlocks {
public static final BlockState AIR = BlockState.parse("minecraft:air");
public static final String JIGSAW_BLOCK = "minecraft:jigsaw";
public static final String ORIENTATION_PROPERTY = "orientation";
private static final String CHEST_BLOCK = "minecraft:chest";
private static final String STRUCTURE_VOID_BLOCK = "minecraft:structure_void";
private static final Set<String> AIR_BLOCKS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
private JigsawStudioBlocks() {
}
public static boolean isAir(BlockState state) {
return AIR_BLOCKS.contains(state.material().toString());
}
public static boolean isJigsaw(BlockState state) {
return JIGSAW_BLOCK.equals(state.material().toString());
}
public static boolean isChest(BlockState state) {
return CHEST_BLOCK.equals(state.material().toString());
}
public static boolean isStructureVoid(BlockState state) {
return STRUCTURE_VOID_BLOCK.equals(state.material().toString());
}
public static BlockState jigsawMarker(String orientation) {
return BlockState.parse(JIGSAW_BLOCK + "[" + ORIENTATION_PROPERTY + "=" + orientation + "]");
}
/** {@code state} turned like {@code rotation}; null when the registry cannot turn the block. */
public static BlockState rotated(BlockRegistry registry, BlockState state, PieceTurn rotation) {
if (rotation.quarterTurns() == 0) {
return state;
}
return registry.tryRotate(state, rotation.blockTurn()).orElse(null);
}
}
@@ -0,0 +1,108 @@
package art.arcane.iris.core.service;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
import com.volmit.tooling.world.TextColor;
import com.volmit.tooling.world.ToolText;
import java.util.ArrayList;
import java.util.List;
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
) {
private static final String SEPARATOR = "-------------------";
private static final int SIDEBAR_LINE_CAPACITY = 11;
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();
}
/** Empty: the sidebar keeps the platform's own title. */
public ToolText sidebarTitle() {
return ToolText.EMPTY;
}
/** The sidebar lines for this context, top to bottom. */
public List<ToolText> sidebarLines() {
List<ToolText> lines = new ArrayList<>(SIDEBAR_LINE_CAPACITY);
lines.add(separator());
lines.add(ToolText.colored(TextColor.LIGHT_PURPLE, "Jigsaw Studio"));
lines.add(labelled("Structure", structureKey));
if (!insideWorkcell()) {
lines.add(labelled("Mode", modeDisplayName()));
lines.add(separator());
lines.add(ToolText.colored(TextColor.YELLOW, "Walk into a workcell"));
if (!controlHint.isEmpty()) {
lines.add(ToolText.colored(TextColor.GRAY, controlHint));
}
lines.add(separator());
return List.copyOf(lines);
}
lines.add(labelled("Workcell", workcellName));
if (!workcellRole.isEmpty() && !workcellRole.equals(workcellName)) {
lines.add(labelled("Role", workcellRole));
}
lines.add(labelled("Variant", variantName.isEmpty() ? "None" : variantName));
lines.add(labelled("State", state.displayName()));
lines.add(separator());
if (!controlHint.isEmpty()) {
lines.add(ToolText.colored(TextColor.YELLOW, controlHint));
}
lines.add(separator());
return List.copyOf(lines);
}
private static ToolText separator() {
return ToolText.builder()
.append(new ToolText.Span(SEPARATOR, TextColor.GRAY, false, false, true))
.build();
}
private static ToolText labelled(String label, String value) {
return ToolText.builder().aqua(label).gray(": " + value).build();
}
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();
}
}
@@ -0,0 +1,21 @@
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;
}
}
@@ -0,0 +1,9 @@
package art.arcane.iris.core.service;
public enum JigsawStudioEvaluationState {
PENDING,
VALID,
WARNING,
INVALID,
STALE
}
@@ -0,0 +1,50 @@
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();
}
}
@@ -0,0 +1,519 @@
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);
}
}
}
@@ -0,0 +1,107 @@
package art.arcane.iris.core.service;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMarkerKeyCodec;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
import com.volmit.geometry.BlockPosition;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
final class JigsawStudioMarkerParser {
private JigsawStudioMarkerParser() {
}
static IrisJigsawConnector parse(
Map<String, Object> nbt,
String 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 BlockPosition(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"));
}
/** The front and top a jigsaw block's {@code orientation} property names, such as {@code down_east}. */
static Directions directions(String orientation) {
String name = Objects.requireNonNull(orientation, "Jigsaw orientation").toLowerCase(Locale.ROOT);
return switch (name) {
case "down_east" -> new Directions(JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.EAST_POSITIVE_X);
case "down_north" -> new Directions(JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.NORTH_NEGATIVE_Z);
case "down_south" -> new Directions(JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.SOUTH_POSITIVE_Z);
case "down_west" -> new Directions(JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.WEST_NEGATIVE_X);
case "up_east" -> new Directions(JigsawDirection.UP_POSITIVE_Y, JigsawDirection.EAST_POSITIVE_X);
case "up_north" -> new Directions(JigsawDirection.UP_POSITIVE_Y, JigsawDirection.NORTH_NEGATIVE_Z);
case "up_south" -> new Directions(JigsawDirection.UP_POSITIVE_Y, JigsawDirection.SOUTH_POSITIVE_Z);
case "up_west" -> new Directions(JigsawDirection.UP_POSITIVE_Y, JigsawDirection.WEST_NEGATIVE_X);
case "west_up" -> new Directions(JigsawDirection.WEST_NEGATIVE_X, JigsawDirection.UP_POSITIVE_Y);
case "east_up" -> new Directions(JigsawDirection.EAST_POSITIVE_X, JigsawDirection.UP_POSITIVE_Y);
case "north_up" -> new Directions(JigsawDirection.NORTH_NEGATIVE_Z, JigsawDirection.UP_POSITIVE_Y);
case "south_up" -> new Directions(JigsawDirection.SOUTH_POSITIVE_Z, JigsawDirection.UP_POSITIVE_Y);
default -> throw new IllegalArgumentException("Unsupported jigsaw orientation '" + orientation + "'");
};
}
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(JigsawDirection front, JigsawDirection top) {
Directions {
Objects.requireNonNull(front, "Jigsaw front direction");
Objects.requireNonNull(top, "Jigsaw top direction");
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,95 @@
package art.arcane.iris.core.service;
import com.volmit.tooling.world.MenuButton;
import com.volmit.tooling.world.MenuClick;
import com.volmit.tooling.world.ToolItem;
import com.volmit.tooling.world.ToolText;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/** One slot of a studio menu: an icon with a name and lore, and what each kind of click on it does. */
final class JigsawStudioMenuElement {
private final String id;
private final List<ToolText> lore = new ArrayList<>();
private JigsawStudioMenuIcon icon = JigsawStudioMenuIcon.BARRIER;
private ToolText name = ToolText.EMPTY;
private boolean enchanted;
private Consumer<JigsawStudioMenuElement> onLeftClick;
private Consumer<JigsawStudioMenuElement> onRightClick;
private Consumer<JigsawStudioMenuElement> onShiftLeftClick;
private Consumer<JigsawStudioMenuElement> onShiftRightClick;
private Consumer<JigsawStudioMenuElement> onMiddleClick;
JigsawStudioMenuElement(String id) {
this.id = Objects.requireNonNull(id, "Jigsaw Studio menu element ID");
}
String id() {
return id;
}
JigsawStudioMenuElement setIcon(JigsawStudioMenuIcon icon) {
this.icon = Objects.requireNonNull(icon, "Jigsaw Studio menu icon");
return this;
}
JigsawStudioMenuElement setName(ToolText name) {
this.name = Objects.requireNonNull(name, "Jigsaw Studio menu name");
return this;
}
JigsawStudioMenuElement setEnchanted(boolean enchanted) {
this.enchanted = enchanted;
return this;
}
JigsawStudioMenuElement addLore(ToolText line) {
lore.add(Objects.requireNonNull(line, "Jigsaw Studio menu lore"));
return this;
}
JigsawStudioMenuElement onLeftClick(Consumer<JigsawStudioMenuElement> action) {
onLeftClick = action;
return this;
}
JigsawStudioMenuElement onRightClick(Consumer<JigsawStudioMenuElement> action) {
onRightClick = action;
return this;
}
JigsawStudioMenuElement onShiftLeftClick(Consumer<JigsawStudioMenuElement> action) {
onShiftLeftClick = action;
return this;
}
JigsawStudioMenuElement onShiftRightClick(Consumer<JigsawStudioMenuElement> action) {
onShiftRightClick = action;
return this;
}
JigsawStudioMenuElement onMiddleClick(Consumer<JigsawStudioMenuElement> action) {
onMiddleClick = action;
return this;
}
/** The api button for this element on {@code slot}. */
MenuButton toButton(int slot) {
ToolItem item = new ToolItem(icon.id(), name, List.copyOf(lore), enchanted, "");
return new MenuButton(slot, item, this::click);
}
private void click(MenuClick click) {
Consumer<JigsawStudioMenuElement> action = click.middle()
? onMiddleClick
: click.shift()
? click.right() ? onShiftRightClick : onShiftLeftClick
: click.right() ? onRightClick : onLeftClick;
if (action != null) {
action.accept(this);
}
}
}
@@ -0,0 +1,58 @@
package art.arcane.iris.core.service;
import com.volmit.resource.ResourceId;
import java.util.Locale;
/** The items the studio menus draw, named as the platform names them. */
enum JigsawStudioMenuIcon {
ARROW,
BARRIER,
BLUE_DYE,
BOOK,
CHEST,
CLOCK,
COMPARATOR,
COPPER_INGOT,
CRAFTING_TABLE,
EMERALD,
EMERALD_BLOCK,
ENDER_EYE,
GOLD_INGOT,
GOLD_NUGGET,
GRAY_DYE,
GRAY_WOOL,
GREEN_DYE,
IRON_BARS,
IRON_INGOT,
JIGSAW,
LAVA_BUCKET,
LEVER,
LIGHT_BLUE_DYE,
LIGHT_GRAY_WOOL,
LIME_DYE,
LIME_WOOL,
NAME_TAG,
NETHER_STAR,
ORANGE_WOOL,
PAPER,
PURPLE_DYE,
RECOVERY_COMPASS,
RED_DYE,
REDSTONE,
REDSTONE_TORCH,
REPEATER,
SCAFFOLDING,
STICK,
STRUCTURE_VOID,
TARGET,
TRIPWIRE_HOOK,
YELLOW_DYE,
YELLOW_WOOL;
private final ResourceId id = ResourceId.parse("minecraft:" + name().toLowerCase(Locale.ROOT));
ResourceId id() {
return id;
}
}
@@ -0,0 +1,290 @@
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();
}
}
@@ -0,0 +1,130 @@
package art.arcane.iris.core.service;
import com.volmit.tooling.world.MenuButton;
import com.volmit.tooling.world.ToolMenu;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolText;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
/**
* A studio menu the controller builds up element by element, the way it lays out a window: each element sits at a
* column counted from the middle of the row (left of it negative) and a row from the top. While the window is open every
* change is shown to the player, and a batch of changes is shown once.
*
* <p>Used on the viewer's thread only.
*/
final class JigsawStudioMenuWindow {
private static final int ROW_WIDTH = ToolMenu.SLOTS_PER_ROW;
private static final int MIDDLE_COLUMN = ROW_WIDTH / 2;
private final ToolPlayer viewer;
private final Map<Integer, JigsawStudioMenuElement> elements = new TreeMap<>();
private ToolText title = ToolText.EMPTY;
private int viewportRows = ToolMenu.MAX_ROWS;
private Runnable onClosed = () -> { };
private int batchDepth;
private boolean open;
private long shownGeneration;
JigsawStudioMenuWindow(ToolPlayer viewer) {
this.viewer = Objects.requireNonNull(viewer, "Jigsaw Studio menu viewer");
}
ToolPlayer getViewer() {
return viewer;
}
JigsawStudioMenuWindow setViewportHeight(int rows) {
viewportRows = Math.max(1, Math.min(ToolMenu.MAX_ROWS, rows));
return this;
}
JigsawStudioMenuWindow setTitle(ToolText title) {
this.title = Objects.requireNonNull(title, "Jigsaw Studio menu title");
return this;
}
JigsawStudioMenuWindow setTitle(String title) {
return setTitle(ToolText.plain(Objects.requireNonNull(title, "Jigsaw Studio menu title")));
}
JigsawStudioMenuWindow onClosed(Runnable onClosed) {
this.onClosed = Objects.requireNonNull(onClosed, "Jigsaw Studio menu close handler");
return this;
}
JigsawStudioMenuWindow setElement(int position, int row, JigsawStudioMenuElement element) {
elements.put(slotOf(position, row), element);
showUnlessBatching();
return this;
}
JigsawStudioMenuWindow clearElements() {
elements.clear();
showUnlessBatching();
return this;
}
JigsawStudioMenuWindow batch(Runnable changes) {
batchDepth++;
try {
changes.run();
} finally {
batchDepth--;
}
showUnlessBatching();
return this;
}
JigsawStudioMenuWindow open() {
open = true;
show();
return this;
}
JigsawStudioMenuWindow close() {
if (!open) {
return this;
}
open = false;
shownGeneration++;
viewer.closeMenu();
onClosed.run();
return this;
}
private static int slotOf(int position, int row) {
int column = Math.max(-MIDDLE_COLUMN, Math.min(MIDDLE_COLUMN, position)) + MIDDLE_COLUMN;
return row * ROW_WIDTH + column;
}
private void showUnlessBatching() {
if (open && batchDepth == 0) {
show();
}
}
private void show() {
long generation = ++shownGeneration;
List<MenuButton> buttons = new ArrayList<>(elements.size());
for (Map.Entry<Integer, JigsawStudioMenuElement> entry : elements.entrySet()) {
if (entry.getKey() >= 0 && entry.getKey() < viewportRows * ROW_WIDTH) {
buttons.add(entry.getValue().toButton(entry.getKey()));
}
}
viewer.openMenu(new ToolMenu(title, viewportRows, buttons, () -> closedByHost(generation)));
}
private void closedByHost(long generation) {
if (generation != shownGeneration || !open) {
return;
}
open = false;
onClosed.run();
}
}
@@ -0,0 +1,449 @@
package art.arcane.iris.core.service;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.framework.structure.assembly.PieceTurn;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
import com.volmit.ModuleLog;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.object.ObjectBlock;
import com.volmit.object.PlaceableObject;
import com.volmit.resource.PackResources;
import com.volmit.tooling.world.ToolWorld;
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.Optional;
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 static final BlockState AIR_STATE = BlockState.parse(AIR);
private static final int CHUNK_SHIFT = 4;
private final Map<UUID, RenderState> requests = new HashMap<>();
private final ModuleLog log;
public JigsawStudioPreviewRenderer(ModuleLog log) {
this.log = Objects.requireNonNull(log, "Jigsaw Studio preview log");
}
public static PreviewPlan plan(List<PlacedStructurePiece> pieces, PackResources pack) throws IOException {
BlockRegistry registry = pack.blocks();
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, pack);
appendFinalStates(blocks, piece, registry);
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(
ToolWorld world,
UUID requestId,
long generation,
PreviewPlan plan,
Consumer<RenderResult> completion
) {
ToolWorld 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.world() != activeWorld
? Map.of()
: old.blocks();
uncertain = old == null || old.world() != activeWorld
? 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, 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());
JigsawStudioThreads.onRegion(
log,
activeWorld,
chunkX,
chunkZ,
() -> applyChunk(
activeWorld,
activeRequestId,
generation,
chunk.getValue(),
remaining,
failed,
callback),
() -> {
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) {
clear(removed.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()) {
clear(state.world(), removalPositions(state));
}
}
private static void appendObject(
Map<BlockPosition, String> blocks,
PlacedStructurePiece piece,
PackResources pack
) throws IOException {
PieceTurn rotation = piece.getRotation();
PlaceableObject object = pack.objects().object(pack.idOf(piece.getObjectKey()))
.orElseThrow(() -> new IOException("Jigsaw Studio preview cannot find object '" + piece.getObjectKey() + "'"));
for (ObjectBlock block : object.geometry().blocks()) {
com.volmit.geometry.BlockPosition rotated = rotation.rotate(block.position());
putState(
blocks,
new BlockPosition(piece.getX() + rotated.x(), piece.getY() + rotated.y(), piece.getZ() + rotated.z()),
JigsawStudioBlocks.rotated(pack.blocks(), block.state(), rotation),
"object block");
}
}
private static void appendFinalStates(
Map<BlockPosition, String> blocks,
PlacedStructurePiece piece,
BlockRegistry registry
) throws IOException {
PieceTurn 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");
}
com.volmit.geometry.BlockPosition rotated = rotation.rotate(new com.volmit.geometry.BlockPosition(
connector.getPosition().x() - piece.getObject().center().x(),
connector.getPosition().y() - piece.getObject().center().y(),
connector.getPosition().z() - piece.getObject().center().z()));
BlockState source = registry.find(connector.getFinalState()).orElse(null);
putState(
blocks,
new BlockPosition(piece.getX() + rotated.x(), piece.getY() + rotated.y(), piece.getZ() + rotated.z()),
source == null ? null : JigsawStudioBlocks.rotated(registry, source, rotation),
"connector final state");
}
}
private static void putState(
Map<BlockPosition, String> blocks,
BlockPosition position,
BlockState 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(
ToolWorld 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, requestId, generation)) {
return;
}
for (BlockUpdate update : updates) {
world.setBlock(
new com.volmit.geometry.BlockPosition(update.position().x(), update.position().y(), update.position().z()),
BlockState.parse(update.stateKey()),
Optional.empty());
applied.add(update.position());
changed++;
}
} catch (RuntimeException exception) {
failed.set(true);
log.error("The Jigsaw Studio preview could not be rendered.", exception);
} finally {
synchronized (this) {
RenderState active = requests.get(requestId);
if (active != null
&& active.world() == world
&& 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.world() == world
&& 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(ToolWorld world, UUID requestId, long generation) {
RenderState state = requests.get(requestId);
return state != null && state.world() == world && 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 void clear(ToolWorld world, Set<BlockPosition> positions) {
Map<Long, List<BlockUpdate>> updates = new HashMap<>();
for (BlockPosition position : positions) {
updates.computeIfAbsent(
chunkKey(position.x() >> CHUNK_SHIFT, position.z() >> CHUNK_SHIFT),
ignored -> new ArrayList<>()).add(new BlockUpdate(position, AIR));
}
for (Map.Entry<Long, List<BlockUpdate>> chunk : updates.entrySet()) {
JigsawStudioThreads.onRegion(log, world, chunkX(chunk.getKey()), chunkZ(chunk.getKey()), () -> {
for (BlockUpdate update : chunk.getValue()) {
world.setBlock(
new com.volmit.geometry.BlockPosition(
update.position().x(), update.position().y(), update.position().z()),
AIR_STATE,
Optional.empty());
}
}, () -> { });
}
}
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(
ToolWorld world,
long generation,
Map<BlockPosition, String> blocks,
PreviewBounds bounds,
Set<BlockPosition> pending
) {
private RenderState {
Objects.requireNonNull(world, "Jigsaw Studio preview world");
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) {
}
}
@@ -0,0 +1,366 @@
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.JigsawStudioLayout;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog;
import com.volmit.tooling.ToolPack;
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;
/**
* Which Jigsaw Studio requests are active for each pack, which one is being opened, and the staged replacement of an
* active one. One registry belongs to one studio service; it holds no platform state.
*/
public final class JigsawStudioRegistry {
private final Map<String, ActiveRequest> active = new ConcurrentHashMap<>();
private final AtomicReference<UUID> openingOwner = new AtomicReference<>();
private final AtomicReference<StagedState> staged = new AtomicReference<>();
public JigsawStudioRequest activate(
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
ToolPack source
) {
JigsawStudioLayout layout = JigsawStudioLayout.create(
mode,
cellDimensions,
JigsawStudioVariantCatalog.empty());
return activate(
packKey,
structureKey,
mode,
compatibilityTarget,
cellDimensions,
source,
layout,
null
);
}
public JigsawStudioRequest activate(
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
ToolPack source,
JigsawStudioLayout initialLayout
) {
return activate(
packKey,
structureKey,
mode,
compatibilityTarget,
cellDimensions,
source,
initialLayout,
null
);
}
public synchronized JigsawStudioRequest activate(
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
ToolPack source,
JigsawStudioLayout initialLayout,
UUID ownerId
) {
if (staged.get() != null) {
throw new IllegalStateException("A Jigsaw Studio replacement is already staged");
}
if (ownerId != null && !ownerId.equals(openingOwner.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 synchronized StagedActivation stage(
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
ToolPack source,
JigsawStudioLayout initialLayout,
UUID ownerId,
UUID preservedRequestId
) {
UUID opening = openingOwner.get();
UUID activeOwner = activeOwnerId();
UUID requestedOwner = Objects.requireNonNull(ownerId, "Jigsaw Studio staged owner ID");
if (!requestedOwner.equals(opening)) {
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 activation = new StagedActivation(
UUID.randomUUID(), candidate.request(), candidate.session());
staged.set(new StagedState(activation, candidate, preserved, false));
return activation;
}
public 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 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 synchronized boolean rollback(StagedActivation expected) {
StagedState state = stagedState(expected);
if (state == null) {
return false;
}
staged.set(null);
return true;
}
public 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 openingOwner.compareAndSet(null, requestedOwner);
}
public void finishOpen(UUID ownerId) {
if (ownerId != null) {
openingOwner.compareAndSet(ownerId, null);
}
}
public UUID openingOwnerId() {
return openingOwner.get();
}
public UUID activeOwnerId() {
for (ActiveRequest activeRequest : active.values()) {
UUID ownerId = activeRequest.request().ownerId();
if (ownerId != null) {
return ownerId;
}
}
return null;
}
public 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 boolean deactivate(String packKey, UUID requestId) {
if (packKey == null || requestId == null) {
return false;
}
StagedState stagedState = staged.get();
if (stagedState != null && stagedState.preserved() != null
&& requestId.equals(stagedState.preserved().request().requestId())
&& normalize(packKey).equals(normalize(stagedState.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 boolean isActive(String packKey) {
return getRequest(packKey) != null;
}
public JigsawStudioRequest getRequest(String packKey) {
ActiveRequest activeRequest = active(packKey);
return activeRequest == null ? null : activeRequest.request();
}
public JigsawStudioSession getSession(String packKey) {
ActiveRequest activeRequest = active(packKey);
return activeRequest == null ? null : activeRequest.session();
}
public JigsawStudioLayout getLayout(String packKey) {
JigsawStudioSession session = getSession(packKey);
return session == null ? null : session.layout();
}
public JigsawStudioRequest getRequest(UUID requestId) {
ActiveRequest activeRequest = active(requestId);
return activeRequest == null ? null : activeRequest.request();
}
public JigsawStudioSession getSession(UUID requestId) {
ActiveRequest activeRequest = active(requestId);
return activeRequest == null ? null : activeRequest.session();
}
private ActiveRequest active(String packKey) {
if (packKey == null) {
return null;
}
return active.get(normalize(packKey));
}
private 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,
ToolPack source,
JigsawStudioLayout initialLayout,
UUID ownerId
) {
JigsawStudioRequest request = new JigsawStudioRequest(
UUID.randomUUID(),
packKey,
structureKey,
mode,
compatibilityTarget,
cellDimensions,
source,
JigsawStudioRequest.rootOf(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 StagedState stagedState(StagedActivation expected) {
StagedActivation activation = Objects.requireNonNull(expected, "Staged Jigsaw Studio activation");
StagedState state = staged.get();
return state != null && state.staged().stageId().equals(activation.stageId()) ? state : null;
}
private static String normalize(String key) {
return key.trim().toLowerCase(Locale.ROOT);
}
private record ActiveRequest(JigsawStudioRequest request, JigsawStudioSession session) {
}
private record StagedState(
StagedActivation staged,
ActiveRequest candidate,
ActiveRequest preserved,
boolean generationVisible
) {
}
public record StagedActivation(
UUID stageId,
JigsawStudioRequest 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");
}
}
}
}
@@ -0,0 +1,76 @@
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 com.volmit.tooling.ToolPack;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.Objects;
import java.util.UUID;
/**
* What one open Jigsaw Studio was asked to edit, and who owns it.
*
* @param source the pack whose structure is edited
* @param packRoot the pack's folder, which the graph editors write below, as {@link ToolPack#edit} hands it out
*/
public record JigsawStudioRequest(
UUID requestId,
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
ToolPack source,
Path packRoot,
UUID ownerId
) {
/** The folder of {@code pack}. */
public static Path rootOf(ToolPack pack) {
try {
return pack.edit(root -> root);
} catch (IOException failure) {
throw new UncheckedIOException("Cannot reach the folder of the pack", failure);
}
}
/** Makes {@code pack} read its files again after a tool changed them. */
public static void reload(ToolPack pack) {
try {
pack.edit(root -> null);
} catch (IOException failure) {
throw new UncheckedIOException("Cannot reload the pack", failure);
}
}
/** Makes the pack read the files again after the studio changed them. */
public void reloadSource() {
reload(source);
}
public JigsawStudioRequest {
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 pack");
packRoot = Objects.requireNonNull(packRoot, "Jigsaw Studio pack folder");
}
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;
}
}
@@ -0,0 +1,185 @@
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");
}
}
}
@@ -0,0 +1,111 @@
package art.arcane.iris.core.service;
import com.volmit.ModuleLog;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolWorld;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The studio's own clock: background work, and work that waits some game ticks before it hops to the thread that owns a
* player or a chunk. A tick is {@value #TICK_MILLIS} milliseconds here, as the server runs when it keeps up.
*/
final class JigsawStudioScheduler {
static final long TICK_MILLIS = 50L;
private static final int WORKER_THREADS = 2;
private static final long IDLE_WORKER_SECONDS = 30L;
private static final String THREAD_NAME_PREFIX = "jigsaw-studio-";
private final ModuleLog log;
private final ScheduledExecutorService executor;
private final Set<UUID> departedPlayers = ConcurrentHashMap.newKeySet();
JigsawStudioScheduler(ModuleLog log) {
this.log = log;
AtomicInteger threadNumber = new AtomicInteger();
ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(WORKER_THREADS, task -> {
Thread thread = new Thread(task, THREAD_NAME_PREFIX + threadNumber.incrementAndGet());
thread.setDaemon(true);
return thread;
});
pool.setRemoveOnCancelPolicy(true);
pool.setKeepAliveTime(IDLE_WORKER_SECONDS, TimeUnit.SECONDS);
pool.allowCoreThreadTimeOut(true);
this.executor = pool;
}
/** Runs {@code task} off the server's threads, as soon as a worker is free. */
void async(Runnable task) {
try {
executor.execute(guarded(task));
} catch (RejectedExecutionException stopped) {
log.debug("A Jigsaw Studio background task was dropped because the studio stopped.");
}
}
/** Runs {@code task} on a studio worker after {@code delayTicks}; it hops to a platform thread itself where it must. */
void later(int delayTicks, Runnable task) {
try {
executor.schedule(guarded(task), delayTicks * TICK_MILLIS, TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException stopped) {
log.debug("A Jigsaw Studio timer was dropped because the studio stopped.");
}
}
/**
* Runs {@code task} on the player's thread after {@code delayTicks}. {@code retired} runs instead when the player has
* left by then or the scheduler is stopped.
*/
void onPlayerLater(ToolPlayer player, Runnable task, int delayTicks, Runnable retired) {
Runnable hop = () -> {
if (departedPlayers.contains(player.id())) {
retired.run();
return;
}
JigsawStudioThreads.run(player, task);
};
try {
executor.schedule(guarded(hop), delayTicks * TICK_MILLIS, TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException stopped) {
retired.run();
}
}
/**
* Runs {@code task} on the thread that owns the chunk after {@code delayTicks}. {@code notScheduled} runs instead when
* the host cannot schedule it.
*/
void onRegionLater(ToolWorld world, int chunkX, int chunkZ, Runnable task, int delayTicks, Runnable notScheduled) {
Runnable hop = () -> JigsawStudioThreads.onRegion(log, world, chunkX, chunkZ, task, notScheduled);
try {
executor.schedule(guarded(hop), delayTicks * TICK_MILLIS, TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException stopped) {
notScheduled.run();
}
}
void playerEntered(UUID playerId) {
departedPlayers.remove(playerId);
}
void playerLeft(UUID playerId) {
departedPlayers.add(playerId);
}
private Runnable guarded(Runnable task) {
return () -> {
try {
task.run();
} catch (Throwable failure) {
log.error("A Jigsaw Studio background task failed.", failure);
}
};
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,89 @@
package art.arcane.iris.core.service;
import com.volmit.ModuleLog;
import com.volmit.geometry.BlockPosition;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolWorld;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BooleanSupplier;
/**
* Moves work onto the thread that owns a player or a chunk, the way the studio needs it: a method that must run on a
* player's thread asks {@link #owns} and, when it does not, hands itself to {@link #call}, which runs it at once when the
* caller already is that thread.
*/
final class JigsawStudioThreads {
private static final int CHUNK_SHIFT = 4;
private JigsawStudioThreads() {
}
/**
* Whether the calling thread is the one that owns the player. A player runs a task at once on their own thread and
* later on any other, so a probe task tells which this is.
*/
static boolean owns(ToolPlayer player) {
boolean[] ranDuringCall = {false};
boolean[] stillInCall = {true};
player.run(() -> ranDuringCall[0] = stillInCall[0]);
stillInCall[0] = false;
return ranDuringCall[0];
}
/**
* Runs {@code task} on the player's thread and returns what it returned. When the task has to wait for the thread it
* returns {@code true}, standing for "scheduled".
*/
static boolean call(ToolPlayer player, BooleanSupplier task) {
boolean[] result = {true};
player.run(() -> result[0] = task.getAsBoolean());
return result[0];
}
/** Runs {@code task} on the player's thread, now when the caller is that thread. */
static void run(ToolPlayer player, Runnable task) {
player.run(task);
}
/**
* Runs {@code task} on the thread that owns the chunk. {@code notScheduled} runs instead when the host cannot
* schedule it; a task that throws is reported to {@code log}.
*/
static void onRegion(
ModuleLog log,
ToolWorld world,
int chunkX,
int chunkZ,
Runnable task,
Runnable notScheduled
) {
AtomicBoolean started = new AtomicBoolean();
world.call(chunkOrigin(chunkX, chunkZ), () -> {
started.set(true);
runReporting(log, task);
return null;
}).whenComplete((ignored, failure) -> {
if (failure != null && !started.get()) {
notScheduled.run();
}
});
}
/** Whether the calling thread owns the chunk. */
static boolean ownsRegion(ToolWorld world, int chunkX, int chunkZ) {
return world.owns(chunkOrigin(chunkX, chunkZ));
}
static BlockPosition chunkOrigin(int chunkX, int chunkZ) {
return new BlockPosition(chunkX << CHUNK_SHIFT, 0, chunkZ << CHUNK_SHIFT);
}
private static void runReporting(ModuleLog log, Runnable task) {
try {
task.run();
} catch (Throwable failure) {
log.error("A Jigsaw Studio region task failed.", failure);
}
}
}
@@ -0,0 +1,62 @@
package art.arcane.iris.core.service;
import art.arcane.volmlib.util.collection.KMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.Strictness;
import com.google.gson.ToNumberPolicy;
import com.volmit.object.BlockEntityData;
import com.volmit.resource.ResourceId;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Map;
import java.util.Optional;
/**
* The block entities of the studio's jigsaw markers in the host's tile format, {@code iris:tile} version 1: the block's
* key and its NBT as JSON, which is the form the host keeps tile data in everywhere else.
*/
final class JigsawStudioTileCodec {
static final ResourceId TILE_FORMAT = ResourceId.parse("iris:tile");
static final int TILE_FORMAT_VERSION = 1;
private static final Gson GSON = new GsonBuilder()
.disableHtmlEscaping()
.setStrictness(Strictness.LENIENT)
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create();
private JigsawStudioTileCodec() {
}
static BlockEntityData encode(String blockKey, Map<String, Object> nbt) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
out.writeUTF(blockKey);
out.writeUTF(GSON.toJson(nbt));
} catch (IOException failure) {
throw new UncheckedIOException("Cannot store the NBT of " + blockKey, failure);
}
return new BlockEntityData(TILE_FORMAT, TILE_FORMAT_VERSION, bytes.toByteArray());
}
/** The NBT {@code data} holds; empty when it is not in the tile format. */
static Optional<KMap<String, Object>> nbt(BlockEntityData data) {
if (!TILE_FORMAT.equals(data.format()) || data.version() != TILE_FORMAT_VERSION) {
return Optional.empty();
}
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(data.payload()))) {
in.readUTF();
@SuppressWarnings("unchecked")
KMap<String, Object> nbt = GSON.fromJson(in.readUTF(), KMap.class);
return Optional.ofNullable(nbt);
} catch (IOException failure) {
throw new UncheckedIOException("Cannot read a block entity of format " + TILE_FORMAT, failure);
}
}
}
@@ -0,0 +1,132 @@
package art.arcane.iris.core.service;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.world.TextColor;
import com.volmit.tooling.world.ToolItem;
import com.volmit.tooling.world.ToolText;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
/** Turns a studio tool payload into the tool item a player holds, and the item back into the payload. */
public final class JigsawStudioToolCodec {
static final ResourceId TOOL_ITEM = ResourceId.parse("minecraft:stick");
static final String NAME_PREFIX = "Jigsaw Studio: ";
static final String SCHEMA_FIELD = "schema";
static final String ACTION_FIELD = "action";
static final String REQUEST_FIELD = "request";
static final String WORKCELL_FIELD = "workcell";
static final String PIECE_FIELD = "piece";
static final String POOL_FIELD = "pool";
static final String ENTRY_INDEX_FIELD = "entryIndex";
static final String AMOUNT_FIELD = "amount";
private static final Gson GSON = new Gson();
public ToolItem create(JigsawStudioToolPayload payload) {
JigsawStudioToolPayload binding = requireCurrentSchema(payload);
return new ToolItem(
TOOL_ITEM,
ToolText.colored(TextColor.AQUA, NAME_PREFIX + binding.action().displayName()),
lore(binding),
false,
encode(binding));
}
public Optional<JigsawStudioToolPayload> decode(ToolItem tool) {
if (tool == null || !TOOL_ITEM.equals(tool.item())) {
return Optional.empty();
}
return decode(tool.payload());
}
public boolean isTool(ToolItem tool) {
return decode(tool).isPresent();
}
String encode(JigsawStudioToolPayload payload) {
JigsawStudioToolPayload binding = requireCurrentSchema(payload);
JsonObject json = new JsonObject();
json.addProperty(SCHEMA_FIELD, binding.schemaVersion());
json.addProperty(ACTION_FIELD, binding.action().name());
json.addProperty(REQUEST_FIELD, binding.requestId().toString());
json.addProperty(WORKCELL_FIELD, binding.workcellId());
json.addProperty(PIECE_FIELD, binding.pieceKey());
json.addProperty(POOL_FIELD, binding.poolKey());
json.addProperty(ENTRY_INDEX_FIELD, binding.entryIndex());
json.addProperty(AMOUNT_FIELD, binding.amount());
return GSON.toJson(json);
}
Optional<JigsawStudioToolPayload> decode(String payload) {
if (payload == null || payload.isEmpty()) {
return Optional.empty();
}
try {
JsonObject json = GSON.fromJson(payload, JsonObject.class);
if (json == null
|| !json.has(SCHEMA_FIELD)
|| !json.has(ACTION_FIELD)
|| !json.has(REQUEST_FIELD)
|| json.get(SCHEMA_FIELD).getAsInt() != JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION) {
return Optional.empty();
}
return Optional.of(new JigsawStudioToolPayload(
json.get(SCHEMA_FIELD).getAsInt(),
JigsawStudioToolAction.valueOf(json.get(ACTION_FIELD).getAsString()),
UUID.fromString(json.get(REQUEST_FIELD).getAsString()),
optionalString(json, WORKCELL_FIELD),
optionalString(json, PIECE_FIELD),
optionalString(json, POOL_FIELD),
json.has(ENTRY_INDEX_FIELD)
? json.get(ENTRY_INDEX_FIELD).getAsInt()
: JigsawStudioToolPayload.NO_ENTRY_INDEX,
json.has(AMOUNT_FIELD) ? json.get(AMOUNT_FIELD).getAsInt() : 0));
} catch (IllegalArgumentException | IllegalStateException | UnsupportedOperationException
| JsonParseException 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(JsonObject json, String field) {
return json.has(field) ? json.get(field).getAsString() : "";
}
private static List<ToolText> lore(JigsawStudioToolPayload payload) {
List<ToolText> lore = new ArrayList<>();
if (!payload.workcellId().isEmpty()) {
lore.add(ToolText.colored(TextColor.GRAY, "Workcell: " + payload.workcellId()));
}
if (!payload.pieceKey().isEmpty()) {
lore.add(ToolText.colored(TextColor.GRAY, "Variant: " + payload.pieceKey()));
}
if (!payload.poolKey().isEmpty()) {
lore.add(ToolText.colored(TextColor.GRAY, "Pool: " + payload.poolKey()
+ (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]")));
}
if (payload.amount() != 0) {
lore.add(ToolText.colored(TextColor.GRAY, "Amount: " + payload.amount()));
}
lore.add(payload.action().destructive()
? ToolText.colored(TextColor.RED, "Right-click twice to confirm")
: ToolText.colored(TextColor.YELLOW, "Right-click to use"));
return List.copyOf(lore);
}
}
@@ -0,0 +1,91 @@
package art.arcane.iris.core.service;
import com.volmit.geometry.BlockPosition;
import com.volmit.tooling.world.BlockChange;
import com.volmit.tooling.world.ToolPlayer;
import com.volmit.tooling.world.ToolUse;
import com.volmit.tooling.world.ToolWorldListener;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* What a Jigsaw Studio world hears from its host: the world's players, blocks and commands, handed to the studio service
* that decides. The studio's id is the id of its request.
*/
final class JigsawStudioWorldListener implements ToolWorldListener {
private final JigsawStudioService service;
private final UUID studioId;
JigsawStudioWorldListener(JigsawStudioService service, UUID studioId) {
this.service = Objects.requireNonNull(service, "Jigsaw Studio service");
this.studioId = Objects.requireNonNull(studioId, "Jigsaw Studio ID");
}
@Override
public void entered(ToolPlayer player) {
service.playerEntered(player);
}
@Override
public void left(ToolPlayer player) {
service.playerLeft(player);
}
@Override
public void moved(ToolPlayer player, BlockPosition to) {
service.playerMoved(player, to);
}
@Override
public void teleported(ToolPlayer player, BlockPosition to) {
service.playerTeleported(player, to);
}
@Override
public void containerChanged(Optional<ToolPlayer> player, BlockPosition at) {
service.containerChanged(studioId, at);
}
@Override
public void sneakToggled(ToolPlayer player, boolean sneaking) {
service.sneakToggled(player, sneaking);
}
@Override
public boolean used(ToolPlayer player, ToolUse use) {
return service.playerUsed(studioId, player, use);
}
@Override
public boolean blockChanging(BlockChange change) {
return service.blockChanging(studioId, change);
}
@Override
public boolean command(Optional<ToolPlayer> sender, String line) {
return service.command(studioId, sender, line);
}
@Override
public void chunkLoaded(int chunkX, int chunkZ) {
service.chunkLoaded(studioId, chunkX, chunkZ);
}
@Override
public Optional<String> closeRefusal() {
return service.closeRefusal(studioId);
}
@Override
public CompletableFuture<Void> closing(Optional<ToolPlayer> by) {
return service.closing(studioId, by);
}
@Override
public void closed() {
service.worldClosed(studioId);
}
}
@@ -0,0 +1,565 @@
/*
* 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.structure.tooling.SenderText;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.PlatformStructures;
import com.volmit.tooling.Sender;
import com.volmit.tooling.ToolPack;
import com.volmit.tooling.world.TextColor;
import com.volmit.tooling.world.ToolText;
import java.io.IOException;
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 art.arcane.iris.core.structure.authoring.StructureBundleNames;
import art.arcane.iris.core.structure.authoring.StructureIndexService;
public final class BulkStructureImporter {
private static final int TEMPLATE_PROGRESS_INTERVAL = 50;
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(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode,
boolean includeNonJigsaw, Sender sender) {
List<ResourceId> vanilla = new ArrayList<>(platform.structures());
Collections.sort(vanilla);
int total = vanilla.size();
int imported = 0;
int skipped = 0;
int failed = 0;
TreeSet<String> captureCandidates = new TreeSet<>();
SenderText.send(sender, ToolText.builder()
.green("Importing ").white(String.valueOf(total))
.green(" vanilla & datapack structures (mode=" + mode + ", includeNonJigsaw=" + includeNonJigsaw + ")...")
.build());
for (ResourceId nk : vanilla) {
String keyString = nk.toString();
String name = StructureImporter.deriveName(nk);
try {
VillageImporter.Result jigsaw = VillageImporter.importVillage(pack, platform, nk, name, mode);
if (jigsaw.success()) {
imported++;
SenderText.send(sender, TextColor.GRAY, "[jigsaw] " + keyString + " -> " + 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(pack, platform, nk, name, mode);
if (single.success()) {
imported++;
SenderText.send(sender, TextColor.GRAY, "[single] " + keyString + " -> " + name);
} else if (single.message() != null && single.message().startsWith("Skipped")) {
skipped++;
} else if (isCaptureCandidate(message, single.message())) {
skipped++;
captureCandidates.add(keyString);
SenderText.send(sender, TextColor.YELLOW, "[skip] " + keyString
+ ": no single-template NBT - vanilla builds this in code or from separate piece templates (imported via the templates pass); nothing to import as one structure.");
} else {
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + single.message());
}
continue;
}
if (message.startsWith("Skipped")) {
skipped++;
continue;
}
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + message);
} catch (Throwable e) {
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage());
}
}
refreshIndex(pack, platform);
SenderText.send(sender, completion("Bulk import complete: ", imported, skipped, failed, total));
return new Report(total, imported, skipped, failed, Map.of(), false, captureCandidates);
}
public static Report importTemplateGroups(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode,
Sender 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;
SenderText.send(sender, TextColor.GREEN,
"Building single-template structures from imported pieces (one variant placed per generation)...");
for (String[] g : groups) {
try {
StructureImporter.Result result = StructureImporter.importTemplateGroup(pack, g[0], g[1], g[2], mode);
if (result.success()) {
imported++;
SenderText.send(sender, TextColor.GRAY, "[group] " + g[1] + " -> " + g[0] + " (" + result.blocks() + " variants)");
} else if (result.message() != null && result.message().startsWith("Skipped")) {
skipped++;
} else {
skipped++;
SenderText.send(sender, TextColor.YELLOW, "[skip] " + g[0] + ": " + result.message());
}
} catch (Throwable e) {
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + g[0] + ": " + e.getMessage());
}
}
refreshIndex(pack, platform);
SenderText.send(sender, ToolText.builder()
.green("Single-template structures: ").white(String.valueOf(imported))
.green(" built, ").white(String.valueOf(skipped))
.green(" skipped, ").white(String.valueOf(failed))
.green(" failed.").build());
return new Report(groups.length, imported, skipped, failed);
}
public static Report importAllTemplates(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode,
Sender sender) {
List<ResourceId> all;
try {
all = new ArrayList<>(platform.templates());
} catch (Throwable e) {
SenderText.send(sender, TextColor.RED,
"Failed to enumerate structure templates via the server ResourceManager: " + e.getMessage());
return enumerationFailureReport();
}
Collections.sort(all);
int total = all.size();
int imported = 0;
int skipped = 0;
int failed = 0;
if (total == 0) {
SenderText.send(sender, TextColor.YELLOW, "No structure templates were found under the 'structure' resource path.");
return new Report(0, 0, 0, 0);
}
SenderText.send(sender, ToolText.builder()
.green("Importing ").white(String.valueOf(total))
.green(" structure templates (mode=" + mode + ")...").build());
for (ResourceId nk : all) {
String keyString = nk.toString();
String name = templateNameFor(keyString);
try {
StructureImporter.Result result = StructureImporter.importStructure(pack, platform, nk, name, mode, true);
if (result.success()) {
imported++;
} else if (result.message() != null && result.message().startsWith("Skipped")) {
skipped++;
} else {
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + result.message());
}
} catch (Throwable e) {
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage());
}
int processed = imported + skipped + failed;
if (processed % TEMPLATE_PROGRESS_INTERVAL == 0) {
SenderText.send(sender, TextColor.GRAY, "..." + processed + "/" + total + " (" + imported
+ " imported, " + skipped + " skipped, " + failed + " failed)");
}
}
refreshIndex(pack, platform);
SenderText.send(sender, completion("Template import complete: ", imported, skipped, failed, total));
return new Report(total, imported, skipped, failed);
}
public static Report importDatapackStructures(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode,
Sender sender) {
return importDatapackStructures(
pack,
platform,
mode,
sender,
null,
null,
StructureImporter.Ownership.EDITABLE
);
}
public static Report importManagedDatapackStructures(
ToolPack pack,
PlatformStructures platform,
StructureImporter.Mode mode,
Sender sender,
Set<String> allowedStructureKeys,
Set<String> allowedTemplateKeys
) {
return importDatapackStructures(
pack,
platform,
mode,
sender,
allowedStructureKeys,
allowedTemplateKeys,
StructureImporter.Ownership.MANAGED_DATAPACK
);
}
private static Report importDatapackStructures(
ToolPack pack,
PlatformStructures platform,
StructureImporter.Mode mode,
Sender sender,
Set<String> allowedStructureKeys,
Set<String> allowedTemplateKeys,
StructureImporter.Ownership ownership
) {
KeySelection structureSelection = selectDatapackKeys(keysOf(platform.structures()), 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) {
SenderText.send(sender, TextColor.YELLOW,
"No datapack (non-minecraft) structures are registered. Ingest a datapack and restart first, then run this again.");
} else {
SenderText.send(sender, ToolText.builder()
.green("Importing ").white(String.valueOf(structureAttempts))
.green(" datapack structures (mode=" + mode + ")...").build());
for (String missingKey : structureSelection.missing()) {
SenderText.send(sender, TextColor.RED, "[fail] " + missingKey
+ ": allowed structure key is absent from the live registry");
}
for (String keyString : datapack) {
ResourceId nk = ResourceId.parse(keyString);
String name = StructureImporter.deriveName(nk);
try {
VillageImporter.Result jigsaw = VillageImporter.importVillage(
pack,
platform,
nk,
name,
mode,
ownership
);
if (jigsaw.success()) {
imported++;
successfulBundles.put(bundleKey(name), keyString);
SenderText.send(sender, TextColor.GRAY, "[jigsaw] " + keyString + " -> " + 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(
pack,
platform,
nk,
name,
mode,
false,
ownership
);
if (single.success()) {
imported++;
successfulBundles.put(bundleKey(name), keyString);
SenderText.send(sender, TextColor.GRAY, "[single] " + keyString + " -> " + name);
} else if (single.message() != null && single.message().startsWith("Skipped")) {
skipped++;
} else if (single.message() != null && single.message().contains("No loadable structure NBT")) {
skipped++;
} else {
failed++;
retryRequired |= single.retryableFailure();
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + single.message());
}
continue;
}
if (message.startsWith("Skipped")) {
skipped++;
continue;
}
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + message);
} catch (Throwable e) {
failed++;
retryRequired = true;
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage());
}
}
}
if (allowedTemplateKeys == null || !allowedTemplateKeys.isEmpty()) {
List<String> templateKeys = List.of();
boolean enumerationSucceeded = false;
try {
templateKeys = keysOf(platform.templates());
enumerationSucceeded = true;
} catch (Throwable e) {
templateAttempts++;
failed++;
retryRequired = true;
SenderText.send(sender, TextColor.YELLOW,
"Could not enumerate datapack templates via the server ResourceManager: " + 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()) {
SenderText.send(sender, TextColor.RED, "[fail] " + missingKey
+ ": allowed template key is absent from the live server resources");
}
if (!datapackTemplates.isEmpty()) {
SenderText.send(sender, ToolText.builder()
.green("Importing ").white(String.valueOf(datapackTemplates.size()))
.green(" datapack structure templates...").build());
for (String keyString : datapackTemplates) {
ResourceId nk = ResourceId.parse(keyString);
String name = templateNameFor(keyString);
try {
StructureImporter.Result result = StructureImporter.importStructure(
pack,
platform,
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();
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + result.message());
}
} catch (Throwable e) {
failed++;
retryRequired = true;
SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage());
}
}
}
}
}
refreshIndex(pack, platform);
SenderText.send(sender, ToolText.builder()
.green("Datapack structure import complete: ").white(String.valueOf(imported))
.green(" imported, ").white(String.valueOf(skipped))
.green(" skipped, ").white(String.valueOf(failed))
.green(" failed.").build());
return datapackReport(
structureAttempts,
templateAttempts,
imported,
skipped,
failed,
successfulBundles,
retryRequired);
}
private static ToolText completion(String label, int imported, int skipped, int failed, int total) {
return ToolText.builder()
.green(label).white(String.valueOf(imported))
.green(" imported, ").white(String.valueOf(skipped))
.green(" skipped, ").white(String.valueOf(failed))
.green(" failed (").white(String.valueOf(total))
.green(" total).").build();
}
private static List<String> keysOf(List<ResourceId> ids) {
return ids.stream().map(ResourceId::toString).toList();
}
private static void refreshIndex(ToolPack pack, PlatformStructures platform) {
try {
StructureIndexService.write(pack, platform);
} catch (IOException | RuntimeException e) {
pack.log().error("Could not refresh the structure index", e);
}
}
static boolean isAllowedDatapackKey(String key, Set<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) {
return StructureBundleNames.templateName(key);
}
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;
}
record KeySelection(List<String> present, List<String> missing) {
KeySelection {
present = List.copyOf(present);
missing = List.copyOf(missing);
}
int total() {
return present.size() + missing.size();
}
}
}
@@ -0,0 +1,120 @@
package art.arcane.iris.core.structure;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Objects as the structure tools write them: a declared size, with blocks placed from the object's minimum corner. Iris
* keeps an object's blocks as offsets from its center, which sits half the size in from that corner.
*/
public final class DeclaredObjects {
private static final BlockPosition ANCHOR = new BlockPosition(0, 0, 0);
private DeclaredObjects() {
}
public static Builder builder(int width, int height, int depth) {
return new Builder(width, height, depth);
}
/** An object of the given size without a block. */
public static GeneratedObject empty(int width, int height, int depth) {
return builder(width, height, depth).build();
}
/** The size {@code object} declares. */
public static BlockPosition sizeOf(GeneratedObject object) {
BlockBox bounds = object.bounds();
return new BlockPosition(bounds.maxX() - bounds.minX(), bounds.maxY() - bounds.minY(), bounds.maxZ() - bounds.minZ());
}
/**
* {@code object} cut down to the box its blocks fill, centered the way every object is; an object without blocks
* stays as it is.
*/
public static GeneratedObject shrinkwrapped(GeneratedObject object) {
List<ObjectBlock> blocks = object.blocks();
if (blocks.isEmpty()) {
return object;
}
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
int maxZ = Integer.MIN_VALUE;
for (ObjectBlock block : blocks) {
BlockPosition position = block.position();
minX = Math.min(minX, position.x());
minY = Math.min(minY, position.y());
minZ = Math.min(minZ, position.z());
maxX = Math.max(maxX, position.x());
maxY = Math.max(maxY, position.y());
maxZ = Math.max(maxZ, position.z());
}
Builder wrapped = builder(maxX - minX + 1, maxY - minY + 1, maxZ - minZ + 1);
for (ObjectBlock block : blocks) {
BlockPosition position = block.position();
wrapped.state(position.x() - minX, position.y() - minY, position.z() - minZ, block.state());
int cornerX = position.x() - minX;
int cornerY = position.y() - minY;
int cornerZ = position.z() - minZ;
block.blockEntity().ifPresent(entity -> wrapped.blockEntity(cornerX, cornerY, cornerZ, entity));
}
return wrapped.build();
}
/** {@code local}, an offset from the object's center, as a position counted from its minimum corner. */
public static BlockPosition fromCorner(GeneratedObject object, BlockPosition local) {
BlockBox bounds = object.bounds();
return new BlockPosition(local.x() - bounds.minX(), local.y() - bounds.minY(), local.z() - bounds.minZ());
}
public static final class Builder {
private final int width;
private final int height;
private final int depth;
private final Map<BlockPosition, BlockState> states = new LinkedHashMap<>();
private final Map<BlockPosition, BlockEntityData> entities = new LinkedHashMap<>();
private Builder(int width, int height, int depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
/** Sets the block at a position counted from the minimum corner. */
public Builder state(int x, int y, int z, BlockState state) {
states.put(new BlockPosition(x, y, z), state);
return this;
}
/** Gives the block at a position counted from the minimum corner a block entity. */
public Builder blockEntity(int x, int y, int z, BlockEntityData entity) {
entities.put(new BlockPosition(x, y, z), entity);
return this;
}
public GeneratedObject build() {
int centerX = width / 2;
int centerY = height / 2;
int centerZ = depth / 2;
List<ObjectBlock> blocks = new ArrayList<>(states.size());
states.forEach((position, state) -> blocks.add(new ObjectBlock(
new BlockPosition(position.x() - centerX, position.y() - centerY, position.z() - centerZ), state,
Optional.ofNullable(entities.get(position)))));
BlockBox declared = new BlockBox(-centerX, -centerY, -centerZ, width - centerX, height - centerY, depth - centerZ);
return new GeneratedObject(declared, ANCHOR, blocks, List.of());
}
}
}
@@ -0,0 +1,194 @@
/*
* 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.structure.tooling.SenderText;
import art.arcane.iris.engine.framework.structure.StructureResources;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.GeneratedObject;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.CapturedStructure;
import com.volmit.tooling.PlatformStructures;
import com.volmit.tooling.Sender;
import com.volmit.tooling.TemplateBlock;
import com.volmit.tooling.ToolPack;
import com.volmit.tooling.world.TextColor;
import com.volmit.tooling.world.ToolText;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
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 PROGRESS_INTERVAL = 10;
private StructureCaptureImporter() {
}
public static Report importAllStructures(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode,
Sender sender) {
return importStructures(pack, platform, mode, sender, null);
}
public static Report importStructures(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode,
Sender sender, Set<String> allowedStructureKeys) {
StructureImporter.Mode activeMode = mode == null ? StructureImporter.Mode.ADD_ONLY : mode;
if (!platform.supportsCapture()) {
SenderText.send(sender, TextColor.YELLOW,
"Structure capture is not supported by the active NMS binding; skipping the capture pass.");
return new Report(0, 0, 0, 0);
}
List<String> keys = platform.structures().stream().map(ResourceId::toString).toList();
if (keys.isEmpty()) {
return new Report(0, 0, 0, 0);
}
PackResources resources = pack.resources();
ArrayList<String> targets = new ArrayList<>();
for (String key : selectCaptureKeys(keys, allowedStructureKeys)) {
String name = StructureImporter.deriveName(key);
boolean alreadyImported = resources.ids(StructureResources.STRUCTURES).contains(resources.idOf(name));
if (alreadyImported && activeMode != StructureImporter.Mode.OVERWRITE) {
continue;
}
targets.add(key);
}
int total = targets.size();
if (total == 0) {
SenderText.send(sender, TextColor.GRAY,
"No code-generated structures left to capture (everything is already imported as a structure).");
return new Report(0, 0, 0, 0);
}
SenderText.send(sender, ToolText.builder()
.green("Capturing ").white(String.valueOf(total))
.green(" code-generated structures (no NBT template) into a scratch world (skipping any wider/taller than "
+ MAX_SPAN + " blocks)...").build());
Optional<PlatformStructures.CaptureArea> opened = platform.openCaptureArea(sender);
if (opened.isEmpty()) {
return new Report(total, 0, 0, total);
}
int imported = 0;
int skipped = 0;
int failed = 0;
int cellIndex = 0;
try (PlatformStructures.CaptureArea area = opened.get()) {
for (String key : targets) {
String name = StructureImporter.deriveName(key);
try {
GeneratedObject captured = captureOne(area, key, cellIndex++);
if (captured == null || captured.blocks().isEmpty()) {
skipped++;
SenderText.send(sender, TextColor.YELLOW, "[skip] " + key
+ ": did not place a capturable structure here (too large, wrong dimension, or no valid placement in a flat world). Stays vanilla-generated.");
continue;
}
GeneratedObject object = DeclaredObjects.shrinkwrapped(captured);
BlockPosition size = DeclaredObjects.sizeOf(object);
StructureImporter.Result result = StructureImporter.writeSinglePieceStructure(
pack, name, key, object, "CENTER_HEIGHT", activeMode);
if (!result.success()) {
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + key + ": " + result.message());
continue;
}
imported++;
SenderText.send(sender, TextColor.GRAY, "[capture] " + key + " -> objects/" + name + ".iob ("
+ size.x() + "x" + size.y() + "x" + size.z() + ")");
} catch (Throwable e) {
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + key + ": " + e.getMessage());
pack.log().error("Could not capture structure " + key, e);
}
int processed = imported + skipped + failed;
if (processed % PROGRESS_INTERVAL == 0) {
SenderText.send(sender, TextColor.GRAY, "..." + processed + "/" + total + " (" + imported
+ " captured, " + skipped + " skipped, " + failed + " failed)");
}
}
}
SenderText.send(sender, ToolText.builder()
.green("Structure capture complete: ").white(String.valueOf(imported))
.green(" captured, ").white(String.valueOf(skipped))
.green(" skipped, ").white(String.valueOf(failed))
.green(" failed (").white(String.valueOf(total))
.green(" total).").build());
return new Report(total, imported, skipped, failed);
}
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 GeneratedObject captureOne(PlatformStructures.CaptureArea area, String key, int cellIndex) {
long seed = key.hashCode() * 0x9E3779B97F4A7C15L + cellIndex * 0x100000001B3L + 0x5DEECE66DL;
Optional<CapturedStructure> captured = area.capture(ResourceId.parse(key), seed, MAX_SPAN);
return captured.map(StructureCaptureImporter::objectOf).orElse(null);
}
private static GeneratedObject objectOf(CapturedStructure captured) {
DeclaredObjects.Builder object = DeclaredObjects.builder(captured.size().x(), captured.size().y(), captured.size().z());
for (TemplateBlock block : captured.blocks()) {
object.state(block.position().x(), block.position().y(), block.position().z(), block.state());
block.blockEntity().ifPresent(entity ->
object.blockEntity(block.position().x(), block.position().y(), block.position().z(), entity));
}
return object.build();
}
}
@@ -0,0 +1,580 @@
/*
* 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.structure.authoring.IrisStructureBundleFactory;
import art.arcane.iris.core.structure.authoring.StructureBackend;
import art.arcane.iris.core.structure.authoring.StructureBundleNames;
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 com.volmit.object.GeneratedObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.PlatformStructures;
import com.volmit.tooling.StructureTemplate;
import com.volmit.tooling.TemplateBlock;
import com.volmit.tooling.ToolPack;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
public final class StructureImporter {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private static final String STRUCTURE_VOID = "minecraft:structure_void";
private static final String JIGSAW = "minecraft:jigsaw";
private static final String STRUCTURE_BLOCK = "minecraft:structure_block";
private static final Set<String> AIR_BLOCKS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
private static final String PLATFORM_NAMESPACE = "minecraft";
public enum Mode {
OVERWRITE,
ADD_ONLY
}
enum Ownership {
EDITABLE,
MANAGED_DATAPACK;
StructureWriteResult write(
ToolPack pack,
StructureResourceBundle bundle,
StructureWriteMode mode
) throws IOException {
return pack.edit(root -> {
StructureTransactionWriter writer = new StructureTransactionWriter(root);
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(
GeneratedObject 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(ResourceId key) {
return (key.namespace() + "_" + key.path()).replace('/', '_').replace(':', '_');
}
public static String deriveName(String key) {
return StructureBundleNames.structureName(key);
}
public static Result importStructure(ToolPack pack, PlatformStructures platform, ResourceId key, String name, Mode mode) {
return importStructure(pack, platform, key, name, mode, false, Ownership.EDITABLE);
}
public static Result importStructure(ToolPack pack, PlatformStructures platform, ResourceId key, String name, Mode mode,
boolean objectOnly) {
return importStructure(pack, platform, key, name, mode, objectOnly, Ownership.EDITABLE);
}
static Result importStructure(
ToolPack pack,
PlatformStructures platform,
ResourceId key,
String name,
Mode mode,
boolean objectOnly,
Ownership ownership
) {
Mode activeMode = mode == null ? Mode.ADD_ONLY : mode;
Optional<StructureTemplate> loaded;
try {
loaded = platform.template(key);
} catch (Throwable e) {
pack.log().error("Could not load structure template " + key, e);
return new Result(false, "Failed to load structure " + key + ": " + e.getMessage(), 0, List.of(), true);
}
if (loaded.isEmpty()) {
return new Result(false, "No loadable structure NBT for key " + key + " (jigsaw structures must be imported by their piece keys)", 0, List.of());
}
CapturedStructure captured;
try {
captured = captureStructure(loaded.get());
} catch (Throwable e) {
pack.log().error("Could not capture structure template " + key, e);
return new Result(false, "Failed to capture structure " + key + ": " + e.getMessage(), 0, List.of(), true);
}
GeneratedObject 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.namespace().equals(PLATFORM_NAMESPACE)
? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK;
StructureSource source = StructureSource.of(sourceKind, sourceKey);
IrisStructureBundleFactory.SinglePieceOptions options = new IrisStructureBundleFactory.SinglePieceOptions(
bundleKey, source, name, object, pack.objects(), 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(pack, bundle, writeMode);
reportWriteFailure(pack, writeResult);
if (!writeResult.successful()) {
return new Result(false, writeFailureMessage(name, activeMode, writeResult), count, losses,
writeResult.failure().isPresent());
}
writeNote = writeResultNote(writeResult);
} catch (StructureGraphValidationException e) {
return new Result(false, "Failed writing import for '" + name + "': " + e.getMessage(), count, losses);
} catch (Throwable e) {
pack.log().error("Could not write the import of " + key, e);
return new Result(false, "Failed writing import for '" + name + "': " + e.getMessage(), count, losses,
true);
}
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(StructureTemplate template) {
StructureTemplate activeTemplate = Objects.requireNonNull(template);
if (activeTemplate.paletteCount() < 1) {
throw new IllegalArgumentException("Structure has no palettes");
}
BlockPosition size = activeTemplate.size();
int w = Math.max(1, size.x());
int h = Math.max(1, size.y());
int d = Math.max(1, size.z());
DeclaredObjects.Builder object = DeclaredObjects.builder(w, h, d);
int count = 0;
int nonAirBlocks = 0;
int tiles = 0;
int structureMarkers = 0;
int invalidFinalStates = 0;
for (TemplateBlock block : activeTemplate.blocks()) {
int x = block.position().x();
int y = block.position().y();
int z = block.position().z();
if (x < 0 || y < 0 || z < 0 || x >= w || y >= h || z >= d) {
continue;
}
String material = block.state().material().toString();
if (material.equals(STRUCTURE_VOID)) {
continue;
}
boolean structural = material.equals(JIGSAW) || material.equals(STRUCTURE_BLOCK);
if (structural) {
structureMarkers++;
}
BlockState placed = block.state();
if (material.equals(JIGSAW)) {
FinalStateResult finalState = readJigsawFinalState(block);
if (finalState.invalidSourceState()) {
invalidFinalStates++;
}
if (finalState.state() == null || isAir(finalState.state())) {
continue;
}
placed = finalState.state();
} else if (material.equals(STRUCTURE_BLOCK)) {
continue;
}
object.state(x, y, z, placed);
count++;
if (!isAir(placed)) {
nonAirBlocks++;
}
if (!structural && block.blockEntity().isPresent()) {
object.blockEntity(x, y, z, block.blockEntity().get());
tiles++;
}
}
List<StructureCapability> capabilities = new ArrayList<>();
capabilities.add(StructureCapability.BLOCKS);
if (tiles > 0) {
capabilities.add(StructureCapability.BLOCK_ENTITIES);
}
return new CapturedStructure(
object.build(),
count,
nonAirBlocks,
tiles,
w,
h,
d,
structureMarkers,
capabilities,
importLosses(activeTemplate, structureMarkers, invalidFinalStates)
);
}
private static boolean isAir(BlockState state) {
return AIR_BLOCKS.contains(state.material().toString());
}
private static List<StructureLoss> importLosses(
StructureTemplate structure,
int structureMarkers,
int invalidFinalStates
) {
List<StructureLoss> losses = new ArrayList<>();
if (structure.paletteCount() > 1) {
losses.add(StructureLoss.warning(
StructureCapability.BLOCKS,
"palette_variants_not_imported",
"Only palette 0 was converted; " + (structure.paletteCount() - 1) + " additional palette(s) remain native-only."));
}
if (structure.entityCount() > 0) {
losses.add(StructureLoss.warning(
StructureCapability.ENTITIES,
"entities_not_imported",
structure.entityCount() + " structure entit" + (structure.entityCount() == 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(ToolPack pack, StructureWriteResult result) {
result.failure().ifPresent((Throwable failure) -> pack.log().error("Structure write failed", 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(TemplateBlock block) {
if (block.jigsawFinalState().isEmpty() || block.jigsawFinalState().get().isBlank()) {
return new FinalStateResult(null, false);
}
try {
return new FinalStateResult(BlockState.parse(withNamespace(normalizeJigsawFinalState(block.jigsawFinalState().get()))), false);
} catch (IllegalArgumentException e) {
return new FinalStateResult(null, true);
}
}
private static String withNamespace(String blockState) {
int propertiesStart = blockState.indexOf('[');
String blockId = propertiesStart < 0 ? blockState : blockState.substring(0, propertiesStart);
return blockId.indexOf(':') < 0 ? PLATFORM_NAMESPACE + ":" + blockState : blockState;
}
static String normalizeJigsawFinalState(String finalState) {
if (finalState == null) {
return null;
}
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(BlockState state, boolean invalidSourceState) {
}
public static Result importTemplateGroup(ToolPack pack, String groupName, String vanillaSource, String prefix, Mode mode) {
try {
return pack.edit(root -> importTemplateGroup(pack, root, groupName, vanillaSource, prefix, mode));
} catch (Throwable e) {
pack.log().error("Could not build group structure " + groupName, e);
return new Result(false, "Failed writing group structure '" + groupName + "': " + e.getMessage(), 0,
List.of(), true);
}
}
private static Result importTemplateGroup(ToolPack pack, Path root, String groupName, String vanillaSource,
String prefix, Mode mode) {
Mode activeMode = mode == null ? Mode.ADD_ONLY : mode;
String objectExtension = pack.objects().extension();
File objectsRoot = new File(root.toFile(), "objects");
File prefixDir = new File(objectsRoot, prefix);
if (!prefixDir.isDirectory()) {
return new Result(false, "No imported templates under objects/" + prefix + " for " + groupName, 0, List.of());
}
List<File> iobs = new ArrayList<>();
collectObjects(prefixDir, objectExtension, iobs);
if (iobs.isEmpty()) {
return new Result(false, "No " + objectExtension + " 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(objectExtension)) {
rel = rel.substring(0, rel.length() - objectExtension.length());
}
pieceNames.add(rel);
try {
maxSpan = Math.max(maxSpan, readObjectSpan(iob));
} catch (IOException e) {
pack.log().error("Could not read the imported object " + rel, e);
return new Result(false, "Cannot read imported object '" + rel + "': " + e.getMessage(), 0,
List.of(), true);
}
}
for (String piece : pieceNames) {
File pieceFile = new File(root.toFile(), "jigsaw-pieces/" + piece + ".json");
if (!pieceFile.isFile()) {
return new Result(false, "Missing imported jigsaw piece '" + piece
+ "'; import the source templates before building group '" + groupName + "'", 0, List.of());
}
}
StructureKey sourceKey = StructureKey.parse(vanillaSource, "minecraft");
StructureSource.Kind sourceKind = sourceKey.namespace().equals("minecraft")
? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK;
StructureResourceBundle bundle = StructureResourceBundle.builder(new StructureKey("iris", groupName))
.source(StructureSource.of(sourceKind, sourceKey))
.backend(StructureBackend.IRIS_ASSEMBLY)
.capability(StructureCapability.BLOCKS)
.capability(StructureCapability.IRIS_PLACEMENT)
.textResource("jigsaw-pools/" + groupName + ".json", GSON.toJson(poolJsonMulti(pieceNames)))
.textResource("structures/" + groupName + ".json",
GSON.toJson(structureJson(groupName, vanillaSource, maxSpan)))
.build();
StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY
? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE;
StructureWriteResult writeResult = new StructureTransactionWriter(root).write(bundle, writeMode);
reportWriteFailure(pack, writeResult);
if (!writeResult.successful()) {
return new Result(false, writeFailureMessage(groupName, activeMode, writeResult), 0, List.of(),
writeResult.failure().isPresent());
}
return new Result(true, "Built structure '" + groupName + "' from " + pieceNames.size()
+ " template variants" + writeResultNote(writeResult), pieceNames.size(), List.of());
}
private static void collectObjects(File dir, String extension, List<File> out) {
File[] files = dir.listFiles();
if (files == null) {
return;
}
for (File f : files) {
if (f.isDirectory()) {
collectObjects(f, extension, out);
} else if (f.getName().endsWith(extension)) {
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(
ToolPack pack,
String name,
String vanillaSource,
GeneratedObject object,
String placeMode,
Mode mode
) {
Mode activeMode = mode == null ? Mode.ADD_ONLY : mode;
BlockPosition size = DeclaredObjects.sizeOf(object);
int span = Math.max(size.x(), size.z());
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,
pack.objects(),
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 = Ownership.EDITABLE.write(pack, bundle, writeMode);
reportWriteFailure(pack, writeResult);
if (!writeResult.successful()) {
return new Result(false, writeFailureMessage(name, activeMode, writeResult), 0, List.of(),
writeResult.failure().isPresent());
}
return new Result(true, "Captured '" + vanillaSource + "' as '" + name + "'"
+ writeResultNote(writeResult), object.blocks().size(), List.of());
} catch (StructureGraphValidationException e) {
return new Result(false, "Failed writing capture for '" + name + "': " + e.getMessage(), 0, List.of());
} catch (Throwable e) {
pack.log().error("Could not write the capture of " + vanillaSource, e);
return new Result(false, "Failed writing capture for '" + name + "': " + e.getMessage(), 0, List.of(),
true);
}
}
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;
}
}
@@ -0,0 +1,755 @@
/*
* 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.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.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.structure.jigsaw.IrisJigsawBranchFailurePolicy;
import com.volmit.object.GeneratedObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.volmit.geometry.BlockFace;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.JigsawStructureInfo;
import com.volmit.tooling.PlatformStructures;
import com.volmit.tooling.StructureAccessException;
import com.volmit.tooling.StructureTemplate;
import com.volmit.tooling.TemplatePool;
import com.volmit.tooling.ToolPack;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public final class VillageImporter {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private static final Set<String> PRINTED_FAILURE_SIGNATURES = ConcurrentHashMap.newKeySet();
private static final String EMPTY_POOL_ELEMENT_TYPE = "EmptyPoolElement";
private static final String LIST_POOL_ELEMENT_TYPE = "ListPoolElement";
private static final String FEATURE_POOL_ELEMENT_TYPE = "FeaturePoolElement";
private static final String AIR_FINAL_STATE = "minecraft:air";
public record Result(
boolean success,
String message,
int pools,
int pieces,
List<StructureLoss> losses,
boolean retryableFailure
) {
public Result(boolean success, String message, int pools, int pieces, List<StructureLoss> losses) {
this(success, message, pools, pieces, losses, false);
}
public Result {
losses = List.copyOf(losses);
}
}
private VillageImporter() {
}
public static Result importVillage(ToolPack pack, PlatformStructures platform, ResourceId structureKey, String name,
StructureImporter.Mode mode) {
return importVillage(pack, platform, structureKey, name, mode, StructureImporter.Ownership.EDITABLE);
}
static Result importVillage(
ToolPack pack,
PlatformStructures platform,
ResourceId structureKey,
String name,
StructureImporter.Mode mode,
StructureImporter.Ownership ownership
) {
StructureImporter.Mode activeMode = mode == null ? StructureImporter.Mode.ADD_ONLY : mode;
List<StructureLoss> losses = new ArrayList<>();
boolean retryableFailure = false;
String writeNote = "";
JigsawStructureInfo structure;
try {
Optional<JigsawStructureInfo> info = platform.jigsaw(structureKey);
if (info.isEmpty()) {
return failed(platform.structures().contains(structureKey)
? "Structure " + structureKey + " is not a jigsaw structure; use 'import' for single-template structures"
: "No structure registered for key " + structureKey, losses);
}
structure = info.get();
} catch (StructureAccessException e) {
reportFailure(pack, e);
return failed(e.getMessage(), losses, e.retryable());
} catch (Throwable e) {
reportFailure(pack, e);
return failed("Failed to read jigsaw structure graph: " + e, losses, true);
}
int maxDepth = structure.maxDepth();
int maxDistanceFromCenter = structure.maxDistance();
Random random = new Random(structure.shuffleSeed());
String startPoolKey = structure.startPool().toString();
Set<String> visitedPools = new HashSet<>();
Deque<String> poolQueue = new ArrayDeque<>();
poolQueue.add(startPoolKey);
Map<String, Map<String, Object>> emittedPools = new LinkedHashMap<>();
Map<String, Map<String, Object>> emittedPieces = new LinkedHashMap<>();
Map<String, GeneratedObject> emittedObjects = new LinkedHashMap<>();
Map<String, ImportedTemplate> importedTemplates = new LinkedHashMap<>();
Set<StructureCapability> capabilities = new HashSet<>();
capabilities.add(StructureCapability.BLOCKS);
capabilities.add(StructureCapability.CONNECTORS);
capabilities.add(StructureCapability.IRIS_PLACEMENT);
List<String> fatalErrors = new ArrayList<>();
losses.add(StructureLoss.warning(
StructureCapability.NATIVE_PLACEMENT,
"native_placement_settings_not_imported",
"Native jigsaw placement settings other than the start pool, maximum depth, and maximum distance are not represented by the Iris assembly."));
int pieceBlocks = 0;
int emittedPoolMembers = 0;
while (!poolQueue.isEmpty()) {
String poolKey = poolQueue.poll();
if (!visitedPools.add(poolKey)) {
continue;
}
Optional<TemplatePool> registered;
try {
registered = platform.pool(ResourceId.parse(poolKey));
} catch (StructureAccessException e) {
reportFailure(pack, e);
retryableFailure = true;
fatalErrors.add(e.getMessage());
continue;
} catch (Throwable e) {
reportFailure(pack, e);
retryableFailure = true;
fatalErrors.add("pool " + poolKey + ": " + e.getMessage());
continue;
}
if (registered.isEmpty()) {
fatalErrors.add("pool " + poolKey + " is not registered");
continue;
}
TemplatePool pool = registered.get();
String irisPoolName = poolName(name, poolKey);
List<Object> pieceEntries = new ArrayList<>();
if (pool.fallbackFailure().isPresent()) {
retryableFailure = true;
losses.add(StructureLoss.warning(
StructureCapability.CONNECTORS,
"fallback_pool_not_imported",
"The fallback for source pool " + poolKey + " could not be resolved: " + pool.fallbackFailure().get())
.affecting("jigsaw-pools/" + irisPoolName + ".json"));
}
String fallbackKey = pool.fallback().map(ResourceId::toString).orElse(null);
if (fallbackKey != null && !fallbackKey.equals(poolKey)) {
poolQueue.add(fallbackKey);
}
List<TemplatePool.Member> templates = pool.members();
for (TemplatePool.Member member : templates) {
if (member instanceof TemplatePool.Absent) {
continue;
}
if (member instanceof TemplatePool.Unreadable unreadable) {
retryableFailure = true;
losses.add(unreadableMemberLoss(unreadable, poolKey).affecting("jigsaw-pools/" + irisPoolName + ".json"));
continue;
}
TemplatePool.Element element = (TemplatePool.Element) member;
int weight = element.weight();
if (element.omittedElements() > 0) {
losses.add(listElementFallbackLoss(element.listLevels(), element.omittedElements(), poolKey)
.affecting("jigsaw-pools/" + irisPoolName + ".json"));
}
if (element.template().isEmpty()) {
if (element.type().endsWith(EMPTY_POOL_ELEMENT_TYPE)) {
pieceEntries.add(emptyPoolEntry(weight));
emittedPoolMembers++;
} else {
StructureCapability unsupportedCapability = unsupportedCapability(element.type());
losses.add(StructureLoss.warning(
unsupportedCapability,
"unsupported_pool_element",
"Skipped unsupported " + element.type() + " in source pool " + poolKey + ".")
.affecting("jigsaw-pools/" + irisPoolName + ".json"));
}
continue;
}
ResourceId pieceNbtKey = element.template().get();
String templateLocation = pieceNbtKey.toString();
String irisPieceName = pieceName(name, templateLocation);
ImportedTemplate importedTemplate = importedTemplates.get(irisPieceName);
if (importedTemplate == null) {
Optional<StructureTemplate> sourceTemplate;
try {
sourceTemplate = platform.template(pieceNbtKey);
} catch (Throwable e) {
reportFailure(pack, e);
retryableFailure = true;
fatalErrors.add(templateLocation + ": failed to load structure template: " + failureDetail(e));
continue;
}
if (sourceTemplate.isEmpty()) {
fatalErrors.add(templateLocation + ": no loadable structure template was registered");
continue;
}
StructureImporter.CapturedStructure captured;
try {
captured = StructureImporter.captureStructure(sourceTemplate.get());
} catch (Throwable e) {
reportFailure(pack, e);
retryableFailure = true;
fatalErrors.add(templateLocation + ": failed to capture structure template: " + failureDetail(e));
continue;
}
for (StructureLoss loss : captured.losses()) {
losses.add(loss.affecting("objects/" + irisPieceName + pack.objects().extension()));
}
Connectors result = readConnectors(pack, element, random, name, irisPieceName);
retryableFailure |= result.retryableFailure();
importedTemplate = new ImportedTemplate(
captured.object(),
captured.blocks(),
captured.nonAirBlocks(),
result.json(),
captured.capabilities());
importedTemplates.put(irisPieceName, importedTemplate);
poolQueue.addAll(result.targetPoolKeys());
losses.addAll(result.losses());
}
PoolMemberNormalization normalization = normalizePoolMember(
poolKey,
irisPoolName,
poolKey.equals(startPoolKey),
templates.size(),
fallbackKey,
templateLocation,
irisPieceName,
weight,
importedTemplate.nonAirBlocks(),
importedTemplate.connectors());
losses.addAll(normalization.losses());
if (!emittedPieces.containsKey(irisPieceName)) {
pieceBlocks += importedTemplate.emittedBlocks(normalization);
capabilities.addAll(importedTemplate.emittedCapabilities(normalization));
if (normalization.disposition() == PoolMemberDisposition.PHYSICAL) {
emittedObjects.put(irisPieceName, importedTemplate.object());
emittedPieces.put(irisPieceName, pieceJson(
irisPieceName,
importedTemplate.connectors(),
importedTemplate.nonAirBlocks()));
}
}
if (!normalization.poolEntry().isEmpty()) {
pieceEntries.add(normalization.poolEntry());
emittedPoolMembers++;
}
}
Map<String, Object> poolJson = new LinkedHashMap<>();
poolJson.put("pieces", pieceEntries);
if (fallbackKey != null && !fallbackKey.equals(poolKey)) {
poolJson.put("fallback", poolName(name, fallbackKey));
}
emittedPools.put(irisPoolName, poolJson);
}
if (!fatalErrors.isEmpty()) {
return failed("Failed to capture the complete graph for " + structureKey + ": " + fatalErrors.getFirst()
+ (fatalErrors.size() == 1 ? "" : " (" + (fatalErrors.size() - 1) + " more)"), losses,
retryableFailure);
}
if (emittedPoolMembers == 0) {
return failed("Imported 0 attachable or empty pool members for " + structureKey, losses);
}
for (StructureLoss loss : losses) {
if (loss.capability() == StructureCapability.CONNECTORS) {
capabilities.remove(StructureCapability.CONNECTORS);
break;
}
}
try {
StructureKey sourceKey = StructureKey.parse(structureKey.toString());
StructureSource.Kind sourceKind = structureKey.namespace().equals("minecraft")
? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK;
StructureSource source = new StructureSource(sourceKind, sourceKey, structure.gameVersion(), "");
Map<String, byte[]> objectResources = new LinkedHashMap<>();
for (Map.Entry<String, GeneratedObject> entry : emittedObjects.entrySet()) {
objectResources.put(entry.getKey(), pack.objects().encode(entry.getValue()));
}
Map<String, Object> rootStructure = structureJson(
structureKey.toString(),
poolName(name, startPoolKey),
maxDepth,
maxDistanceFromCenter);
StructureResourceBundle bundle = buildBundle(
new StructureKey("iris", name),
source,
objectResources,
emittedPieces,
emittedPools,
rootStructure,
capabilities,
losses);
StructureResourceBundleGraphCompiler.requireViable(bundle);
StructureWriteMode writeMode = activeMode == StructureImporter.Mode.OVERWRITE
? StructureWriteMode.OVERWRITE : StructureWriteMode.ADD_ONLY;
StructureWriteResult writeResult = ownership.write(pack, bundle, writeMode);
reportWriteFailure(pack, writeResult);
if (!writeResult.successful()) {
return new Result(false, writeFailureMessage(name, writeResult), emittedPools.size(),
emittedPieces.size(), losses, writeResult.failure().isPresent());
}
writeNote = writeResultNote(writeResult);
} catch (StructureGraphValidationException e) {
return new Result(false, "Failed writing jigsaw resources for '" + name + "': " + e.getMessage(),
emittedPools.size(), emittedPieces.size(), losses, retryableFailure);
} catch (Throwable e) {
reportFailure(pack, e);
return new Result(false, "Failed writing jigsaw resources for '" + name + "': " + e,
emittedPools.size(), emittedPieces.size(), losses, true);
}
String msg = "Imported jigsaw structure " + structureKey + " as '" + name + "': " + emittedPieces.size() + " pieces, " + emittedPools.size() + " pools, " + pieceBlocks + " blocks";
if (!losses.isEmpty()) {
msg += " (" + losses.size() + " fidelity warning(s) recorded)";
}
return new Result(true, msg + writeNote, emittedPools.size(), emittedPieces.size(), losses);
}
static StructureResourceBundle buildBundle(
StructureKey bundleKey,
StructureSource source,
Map<String, byte[]> objects,
Map<String, Map<String, Object>> pieces,
Map<String, Map<String, Object>> pools,
Map<String, Object> structure,
Set<StructureCapability> capabilities,
List<StructureLoss> losses
) {
StructureResourceBundle.Builder bundle = StructureResourceBundle.builder(bundleKey)
.source(source)
.backend(StructureBackend.IRIS_ASSEMBLY)
.capabilities(capabilities)
.losses(losses);
for (Map.Entry<String, byte[]> entry : objects.entrySet()) {
bundle.resource("objects/" + entry.getKey() + ".iob", entry.getValue());
}
for (Map.Entry<String, Map<String, Object>> entry : pieces.entrySet()) {
bundle.textResource("jigsaw-pieces/" + entry.getKey() + ".json", GSON.toJson(entry.getValue()));
}
for (Map.Entry<String, Map<String, Object>> entry : pools.entrySet()) {
bundle.textResource("jigsaw-pools/" + entry.getKey() + ".json", GSON.toJson(entry.getValue()));
}
bundle.textResource("structures/" + bundleKey.path() + ".json", GSON.toJson(structure));
return bundle.build();
}
private record Connectors(
List<Map<String, Object>> json,
Set<String> targetPoolKeys,
List<StructureLoss> losses,
boolean retryableFailure
) {
}
record ImportedTemplate(
GeneratedObject object,
int blocks,
int nonAirBlocks,
List<Map<String, Object>> connectors,
List<StructureCapability> capabilities
) {
ImportedTemplate {
connectors = List.copyOf(connectors);
capabilities = List.copyOf(capabilities);
}
int emittedBlocks(PoolMemberNormalization normalization) {
return normalization.disposition() == PoolMemberDisposition.PHYSICAL ? blocks : 0;
}
List<StructureCapability> emittedCapabilities(PoolMemberNormalization normalization) {
return normalization.disposition() == PoolMemberDisposition.PHYSICAL ? capabilities : List.of();
}
}
enum PoolMemberDisposition {
PHYSICAL,
EMPTY,
OMITTED
}
record PoolMemberNormalization(
PoolMemberDisposition disposition,
Map<String, Object> poolEntry,
List<StructureLoss> losses
) {
PoolMemberNormalization {
poolEntry = Collections.unmodifiableMap(new LinkedHashMap<>(poolEntry));
losses = List.copyOf(losses);
}
}
private static StructureLoss unreadableMemberLoss(TemplatePool.Unreadable unreadable, String poolKey) {
if (unreadable.part() == TemplatePool.Part.ENTRY) {
return StructureLoss.warning(
StructureCapability.LIST_ELEMENTS,
"pool_entry_not_imported",
"A source entry in pool " + poolKey + " could not be read: " + unreadable.detail());
}
return StructureLoss.warning(
StructureCapability.BLOCKS,
"template_location_not_imported",
"A source template location in pool " + poolKey + " could not be read: " + unreadable.detail());
}
private static Connectors readConnectors(
ToolPack pack,
TemplatePool.Element element,
Random random,
String baseName,
String pieceName
) {
List<Map<String, Object>> connectors = new ArrayList<>();
Set<String> targets = new HashSet<>();
List<StructureLoss> losses = new ArrayList<>();
boolean retryableFailure = false;
String affectedResource = "jigsaw-pieces/" + pieceName + ".json";
try {
TemplatePool.Connectors read = element.connectors().read(random::nextLong);
if (read.availability() == TemplatePool.Availability.UNAVAILABLE) {
losses.add(StructureLoss.warning(
StructureCapability.CONNECTORS,
"connector_extraction_unavailable",
"The source pool element does not expose jigsaw connector extraction on this server version.")
.affecting(affectedResource));
return new Connectors(connectors, targets, losses, false);
}
if (read.availability() == TemplatePool.Availability.NO_COLLECTION) {
losses.add(StructureLoss.warning(
StructureCapability.CONNECTORS,
"connector_extraction_returned_null",
"The source pool element returned no connector collection.")
.affecting(affectedResource));
return new Connectors(connectors, targets, losses, false);
}
for (TemplatePool.Connector connector : read.connectors()) {
if (connector instanceof TemplatePool.UnreadableConnector unreadable) {
retryableFailure = true;
losses.add(StructureLoss.warning(
StructureCapability.CONNECTORS,
"connector_not_imported",
"A source jigsaw connector could not be converted: " + unreadable.detail())
.affecting(affectedResource));
continue;
}
TemplatePool.JigsawConnector jigsaw = (TemplatePool.JigsawConnector) connector;
connectors.add(connectorJson(jigsaw, baseName));
jigsaw.pool().ifPresent(pool -> targets.add(pool.toString()));
}
} catch (Throwable e) {
reportFailure(pack, e);
retryableFailure = true;
losses.add(StructureLoss.warning(
StructureCapability.CONNECTORS,
"connector_extraction_failed",
"Source jigsaw connectors could not be extracted: " + failureDetail(e))
.affecting(affectedResource));
}
return new Connectors(connectors, targets, losses, retryableFailure);
}
static Map<String, Object> connectorJson(TemplatePool.JigsawConnector jigsaw, String baseName) {
Map<String, Object> connector = new LinkedHashMap<>();
Map<String, Object> position = new LinkedHashMap<>();
position.put("x", jigsaw.position().x());
position.put("y", jigsaw.position().y());
position.put("z", jigsaw.position().z());
connector.put("position", position);
connector.put("direction", irisDirection(jigsaw.front()));
connector.put("top", irisDirection(jigsaw.top()));
connector.put("pool", jigsaw.pool().map(pool -> poolName(baseName, pool.toString())).orElse(""));
connector.put("name", jigsaw.name());
connector.put("targetName", jigsaw.target());
connector.put("joint", jigsaw.aligned() ? "ALIGNED" : "ROLLABLE");
connector.put("finalState", jigsaw.finalState()
.map(StructureImporter::normalizeJigsawFinalState)
.orElse(AIR_FINAL_STATE));
connector.put("selectionPriority", jigsaw.selectionPriority());
connector.put("placementPriority", jigsaw.placementPriority());
return connector;
}
private static String irisDirection(BlockFace front) {
return switch (front) {
case UP -> "UP_POSITIVE_Y";
case DOWN -> "DOWN_NEGATIVE_Y";
case SOUTH -> "SOUTH_POSITIVE_Z";
case EAST -> "EAST_POSITIVE_X";
case WEST -> "WEST_NEGATIVE_X";
default -> "NORTH_NEGATIVE_Z";
};
}
static StructureLoss listElementFallbackLoss(int listLevels, int omitted, String poolKey) {
String elementLabel = omitted == 1 ? "element" : "elements";
String levelLabel = listLevels == 1 ? "list level" : "nested list levels";
return StructureLoss.warning(
StructureCapability.LIST_ELEMENTS,
"list_pool_overlays_not_imported",
"Converted the first physical template from a ListPoolElement in source pool " + poolKey
+ " and omitted " + omitted + " colocated " + elementLabel
+ ", including their processors, across " + listLevels + " " + levelLabel + "."
);
}
static String poolName(String base, String poolKey) {
StructureKey key = StructureKey.parse(poolKey);
return base + "/pool/" + key.namespace() + "/" + key.path();
}
static String pieceName(String base, String templateLocation) {
StructureKey key = StructureKey.parse(templateLocation);
return base + "/piece/" + key.namespace() + "/" + key.path();
}
static Map<String, Object> pieceJson(
String pieceName,
List<Map<String, Object>> connectors,
int nonAirBlocks
) {
Map<String, Object> piece = new LinkedHashMap<>();
piece.put("object", pieceName);
piece.put("connectors", connectors);
piece.put("rotatable", true);
if (nonAirBlocks == 0) {
piece.put("collidable", false);
}
return piece;
}
static PoolMemberNormalization normalizePoolMember(
String sourcePoolKey,
String irisPoolName,
boolean startPoolMember,
int sourcePoolMembershipCount,
String sourceFallbackKey,
String templateLocation,
String irisPieceName,
int weight,
int nonAirBlocks,
List<Map<String, Object>> connectors
) {
if (!connectors.isEmpty() || startPoolMember) {
return new PoolMemberNormalization(
PoolMemberDisposition.PHYSICAL,
piecePoolEntry(irisPieceName, weight),
List.of());
}
if (sourceFallbackKey != null
&& !sourceFallbackKey.isBlank()
&& !sourceFallbackKey.equals(sourcePoolKey)) {
return new PoolMemberNormalization(
PoolMemberDisposition.PHYSICAL,
piecePoolEntry(irisPieceName, weight),
List.of());
}
String affectedResource = "jigsaw-pools/" + irisPoolName + ".json";
if (nonAirBlocks == 0 && sourcePoolMembershipCount == 1) {
StructureLoss loss = StructureLoss.warning(
StructureCapability.IRIS_PLACEMENT,
"connectorless_all_air_member_normalized_empty",
"Source pool member " + templateLocation + " in " + sourcePoolKey
+ " captured no non-air blocks and exposed no jigsaw connectors;"
+ " its singleton membership was normalized to an explicit empty Iris pool entry"
+ fallbackContext(sourcePoolKey, sourceFallbackKey) + ".")
.affecting(affectedResource);
return new PoolMemberNormalization(
PoolMemberDisposition.EMPTY,
emptyPoolEntry(weight),
List.of(loss));
}
if (nonAirBlocks == 0) {
StructureLoss loss = StructureLoss.warning(
StructureCapability.IRIS_PLACEMENT,
"connectorless_all_air_mixed_member_omitted",
"Source pool member " + templateLocation + " in " + sourcePoolKey
+ " captured no non-air blocks and exposed no jigsaw connectors;"
+ " it was omitted from the mixed " + sourcePoolMembershipCount + "-member pool"
+ fallbackContext(sourcePoolKey, sourceFallbackKey)
+ ", changing source selection weights and RNG consumption.")
.affecting(affectedResource);
return new PoolMemberNormalization(
PoolMemberDisposition.OMITTED,
Map.of(),
List.of(loss));
}
StructureLoss loss = StructureLoss.warning(
StructureCapability.BLOCKS,
"connectorless_non_air_member_omitted",
"Source pool member " + templateLocation + " in " + sourcePoolKey
+ " captured " + nonAirBlocks + " non-air block(s) but exposed no jigsaw connectors;"
+ " it was omitted because it cannot attach to the Iris assembly graph"
+ fallbackContext(sourcePoolKey, sourceFallbackKey)
+ ", changing source selection weights and RNG consumption while dropping those blocks.")
.affecting(affectedResource);
return new PoolMemberNormalization(
PoolMemberDisposition.OMITTED,
Map.of(),
List.of(loss));
}
private static String fallbackContext(String sourcePoolKey, String sourceFallbackKey) {
if (sourceFallbackKey == null || sourceFallbackKey.isBlank()) {
return " with no source fallback";
}
if (sourceFallbackKey.equals(sourcePoolKey)) {
return " with its source self-fallback";
}
return " before source fallback " + sourceFallbackKey;
}
static Map<String, Object> emptyPoolEntry(int weight) {
Map<String, Object> entry = new LinkedHashMap<>();
entry.put("empty", true);
entry.put("weight", weight);
return entry;
}
static Map<String, Object> piecePoolEntry(String pieceName, int weight) {
Map<String, Object> entry = new LinkedHashMap<>();
entry.put("piece", pieceName);
entry.put("weight", weight);
return entry;
}
static Map<String, Object> structureJson(
String source,
String startPool,
int maxDepth,
int maxDistanceFromCenter
) {
Map<String, Object> root = new LinkedHashMap<>();
root.put("startPool", startPool);
root.put("maxDepth", Math.max(1, Math.min(30, maxDepth)));
int maxSizeChunks = Math.max(1, Math.min(32, (Math.max(1, maxDistanceFromCenter) + 15) / 16));
root.put("maxSizeChunks", maxSizeChunks);
root.put("placeMode", "STRUCTURE_PIECE");
root.put("branchFailurePolicy", IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH.name());
root.put("vanillaSource", source);
return root;
}
private static StructureCapability unsupportedCapability(String elementType) {
if (elementType.endsWith(LIST_POOL_ELEMENT_TYPE)) {
return StructureCapability.LIST_ELEMENTS;
}
if (elementType.endsWith(FEATURE_POOL_ELEMENT_TYPE)) {
return StructureCapability.FEATURE_ELEMENTS;
}
return StructureCapability.BLOCKS;
}
private static Result failed(String message, List<StructureLoss> losses) {
return new Result(false, message, 0, 0, losses);
}
private static Result failed(String message, List<StructureLoss> losses, boolean retryableFailure) {
return new Result(false, message, 0, 0, losses, retryableFailure);
}
private static void reportFailure(ToolPack pack, Throwable failure) {
pack.log().error("Jigsaw structure import failed", failure);
}
/**
* True the first time a failure signature is seen. A bulk import repeats the same failure once
* per registered structure, so printing every trace buries the boot log in hundreds of copies
* of one problem; the per-structure "[fail] key: message" line still reports each occurrence.
*/
static boolean shouldPrintFullTrace(Throwable failure) {
if (failure == null) {
return false;
}
StackTraceElement[] trace = failure.getStackTrace();
String signature = failure.getClass().getName() + '|' + failure.getMessage()
+ '|' + (trace.length == 0 ? "" : trace[0].toString());
return PRINTED_FAILURE_SIGNATURES.add(signature);
}
static void resetFailureLogState() {
PRINTED_FAILURE_SIGNATURES.clear();
}
private static void reportWriteFailure(ToolPack pack, StructureWriteResult result) {
result.failure().ifPresent(failure -> reportFailure(pack, 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, 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(VillageImporter::failureDetail).orElse(result.status().name());
return "Failed writing jigsaw import for '" + name + "': " + failure;
}
private static String failureDetail(Throwable failure) {
String message = failure.getMessage();
return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message;
}
}
@@ -0,0 +1,104 @@
package art.arcane.iris.core.structure.authoring;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.volmit.object.GeneratedObject;
import com.volmit.tooling.ObjectCodec;
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() + activeOptions.codec().extension(),
activeOptions.codec().encode(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 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,
GeneratedObject object,
ObjectCodec codec,
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(codec);
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);
}
}
}
@@ -0,0 +1,25 @@
/*
* 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 StructureBackend {
NATIVE,
IRIS_ASSEMBLY,
SNAPSHOT
}
@@ -0,0 +1,63 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure.authoring;
import java.util.Locale;
/**
* The names the structure importers give the bundles they write, which Iris's datapack ingest predicts to know which
* bundles an import will leave and which it must clean up.
*/
public final class StructureBundleNames {
private static final String DEFAULT_NAMESPACE = "minecraft";
private static final String BUNDLE_PREFIX = "iris:";
private StructureBundleNames() {
}
/** The bundle a registered structure imports as, such as {@code iris:minecraft_village_plains_town_centers}. */
public static String ofStructure(String key) {
return BUNDLE_PREFIX + structureName(key);
}
/** The bundle a structure template imports as. */
public static String ofTemplate(String key) {
return BUNDLE_PREFIX + templateName(key);
}
/** The name an imported structure is filed under. */
public static String structureName(String key) {
return key.toLowerCase().replace('/', '_').replace(':', '_');
}
/** The name an imported structure template is filed under; templates of the platform's own namespace need no prefix. */
public static String templateName(String key) {
int colon = key.indexOf(':');
String namespace = colon >= 0 ? key.substring(0, colon) : DEFAULT_NAMESPACE;
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 DEFAULT_NAMESPACE.equals(namespace) ? safePath : namespace + "/" + safePath;
}
}
@@ -0,0 +1,35 @@
/*
* 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
}
@@ -0,0 +1,160 @@
/*
* 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();
}
}
}
@@ -0,0 +1,65 @@
/*
* 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);
}
}
}
@@ -0,0 +1,130 @@
/*
* 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.GsonBuilder;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.service.StructureLocator;
import com.volmit.tooling.PlatformStructures;
import com.volmit.tooling.ToolPack;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public final class StructureIndexService {
private static final String INDEX_PATH = ".iris/structure-index.json";
private static final String PLATFORM_NAMESPACE_PREFIX = "minecraft:";
private StructureIndexService() {
}
/** Writes the index of every structure the platform registers and the pack's modules know into the pack, and returns its file. */
public static File write(ToolPack pack, PlatformStructures platform) throws IOException {
List<String> structures = keysOf(platform.structures());
List<String> sets = keysOf(platform.structureSets());
List<String> iris = irisStructureKeys(pack);
return pack.edit(root -> writeIndex(pack, indexFile(root.toFile()), structures, sets, iris));
}
private static List<String> keysOf(List<ResourceId> ids) {
return ids.stream().map(ResourceId::toString).toList();
}
private static List<String> irisStructureKeys(ToolPack pack) {
PackResources resources = pack.resources();
Set<String> keys = new TreeSet<>();
for (StructureLocator provider : pack.services(StructureLocator.class)) {
for (ResourceId structure : provider.structures(resources)) {
keys.add(resources.idOf(structure.path()).equals(structure) ? structure.path() : structure.toString());
}
}
return new ArrayList<>(keys);
}
private static File writeIndex(ToolPack pack, File file, List<String> structures, List<String> sets, List<String> iris) {
List<String> vanilla = new ArrayList<>();
List<String> datapack = new ArrayList<>();
for (String k : structures) {
if (k.startsWith(PLATFORM_NAMESPACE_PREFIX)) {
vanilla.add(k);
} else {
datapack.add(k);
}
}
List<String> vanillaSets = new ArrayList<>();
List<String> datapackSets = new ArrayList<>();
for (String k : sets) {
if (k.startsWith(PLATFORM_NAMESPACE_PREFIX)) {
vanillaSets.add(k);
} else {
datapackSets.add(k);
}
}
Collections.sort(vanilla);
Collections.sort(datapack);
Collections.sort(vanillaSets);
Collections.sort(datapackSets);
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);
try {
file.getParentFile().mkdirs();
String json = new GsonBuilder().setPrettyPrinting().create().toJson(root);
Files.writeString(file.toPath(), json, StandardCharsets.UTF_8);
} catch (Throwable e) {
pack.log().error("Could not write the structure index " + file, e);
}
return file;
}
static File indexFile(File dataFolder) {
return new File(dataFolder, INDEX_PATH);
}
}
@@ -0,0 +1,87 @@
/*
* 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);
}
}
}
}
@@ -0,0 +1,65 @@
/*
* 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
}
}
@@ -0,0 +1,260 @@
/*
* 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
}
}
@@ -0,0 +1,56 @@
/*
* 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();
}
}
}
@@ -0,0 +1,234 @@
/*
* 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;
}
}
}
@@ -0,0 +1,49 @@
/*
* 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
}
}
@@ -0,0 +1,143 @@
/*
* 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);
}
}
}
}
@@ -0,0 +1,147 @@
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);
}
}
}
@@ -0,0 +1,24 @@
/*
* 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
}
@@ -0,0 +1,54 @@
/*
* 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);
}
}
@@ -0,0 +1,147 @@
/*
* 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
);
}
}
}
@@ -0,0 +1,88 @@
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
}
}
@@ -0,0 +1,7 @@
package art.arcane.iris.core.structure.conversion;
public enum IrisStructureAdoptionDisposition {
IN_PLACE,
CLONE_REQUIRED,
BLOCKED
}
@@ -0,0 +1,6 @@
package art.arcane.iris.core.structure.conversion;
public enum IrisStructureAdoptionInputKind {
UNOWNED_IRIS,
MANAGED_DATAPACK
}
@@ -0,0 +1,56 @@
package art.arcane.iris.core.structure.conversion;
import java.time.Duration;
import java.util.Objects;
public record IrisStructureAdoptionLimits(
int maxResources,
int maxJsonBytes,
int maxBinaryBytes,
long maxTotalBytes,
int maxStructuresScanned,
int maxDiagnostics,
int maxActivePlans,
Duration planTtl
) {
public IrisStructureAdoptionLimits {
if (maxResources < 1 || maxResources > 100_000) {
throw new IllegalArgumentException("Adoption resource limit must be between 1 and 100000");
}
if (maxJsonBytes < 1 || maxJsonBytes > 64 * 1024 * 1024) {
throw new IllegalArgumentException("Adoption JSON limit must be between 1 and 67108864 bytes");
}
if (maxBinaryBytes < 1 || maxBinaryBytes > 256 * 1024 * 1024) {
throw new IllegalArgumentException("Adoption binary limit must be between 1 and 268435456 bytes");
}
if (maxTotalBytes < 1L || maxTotalBytes > 1024L * 1024L * 1024L) {
throw new IllegalArgumentException("Adoption aggregate limit must be between 1 and 1073741824 bytes");
}
if (maxStructuresScanned < 1 || maxStructuresScanned > 100_000) {
throw new IllegalArgumentException("Adoption structure scan limit must be between 1 and 100000");
}
if (maxDiagnostics < 1 || maxDiagnostics > 10_000) {
throw new IllegalArgumentException("Adoption diagnostic limit must be between 1 and 10000");
}
if (maxActivePlans < 1 || maxActivePlans > 10_000) {
throw new IllegalArgumentException("Adoption active-plan limit must be between 1 and 10000");
}
planTtl = Objects.requireNonNull(planTtl, "planTtl");
if (planTtl.isNegative() || planTtl.isZero() || planTtl.compareTo(Duration.ofHours(24L)) > 0) {
throw new IllegalArgumentException("Adoption plan TTL must be between one nanosecond and 24 hours");
}
}
public static IrisStructureAdoptionLimits defaults() {
return new IrisStructureAdoptionLimits(
10_000,
8 * 1024 * 1024,
64 * 1024 * 1024,
1024L * 1024L * 1024L,
10_000,
1_000,
1_024,
Duration.ofMinutes(15L)
);
}
}
@@ -0,0 +1,107 @@
package art.arcane.iris.core.structure.conversion;
import art.arcane.iris.core.structure.authoring.StructureHash;
import art.arcane.iris.core.structure.authoring.StructureKey;
import art.arcane.iris.core.structure.authoring.StructureTransactionReadSet;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.UUID;
public record IrisStructureAdoptionPlan(
UUID planId,
Instant createdAt,
Instant expiresAt,
IrisStructureAdoptionRequest request,
StructureKey targetStructure,
IrisStructureAdoptionDisposition disposition,
List<IrisStructureAdoptionDiagnostic> diagnostics,
Map<String, String> sourceResourceHashes,
Map<String, String> sourceToTargetPaths,
StructureTransactionReadSet readSet,
long totalSourceBytes,
String sourceClosureHash,
String planHash
) {
public IrisStructureAdoptionPlan {
Objects.requireNonNull(planId, "planId");
Objects.requireNonNull(createdAt, "createdAt");
Objects.requireNonNull(expiresAt, "expiresAt");
Objects.requireNonNull(request, "request");
Objects.requireNonNull(targetStructure, "targetStructure");
Objects.requireNonNull(disposition, "disposition");
Objects.requireNonNull(diagnostics, "diagnostics");
diagnostics = sortedDiagnostics(diagnostics);
sourceResourceHashes = immutableMap(sourceResourceHashes);
sourceToTargetPaths = immutableMap(sourceToTargetPaths);
readSet = Objects.requireNonNull(readSet, "readSet");
if (!expiresAt.isAfter(createdAt)) {
throw new IllegalArgumentException("Adoption plan expiry must be after creation");
}
if (totalSourceBytes < 0L) {
throw new IllegalArgumentException("Adoption plan source bytes cannot be negative");
}
requireHash(sourceClosureHash, "source closure");
requireHash(planHash, "plan");
if (sourceResourceHashes.isEmpty() && disposition != IrisStructureAdoptionDisposition.BLOCKED) {
throw new IllegalArgumentException("Applicable adoption plan requires source resources");
}
}
public boolean canApply() {
return disposition != IrisStructureAdoptionDisposition.BLOCKED
&& diagnostics.stream().noneMatch(IrisStructureAdoptionDiagnostic::blocking);
}
public boolean expiredAt(Instant instant) {
return !Objects.requireNonNull(instant, "instant").isBefore(expiresAt);
}
public int resourceCount() {
return sourceResourceHashes.size();
}
public long errorCount() {
return diagnostics.stream().filter(IrisStructureAdoptionDiagnostic::blocking).count();
}
public long warningCount() {
return diagnostics.stream().filter(diagnostic ->
diagnostic.severity() == IrisStructureAdoptionDiagnostic.Severity.WARNING).count();
}
public List<String> summaryLines() {
ArrayList<String> lines = new ArrayList<>();
lines.add("Plan " + planId + " -> " + disposition + " for " + targetStructure.value());
lines.add(resourceCount() + " resources, " + totalSourceBytes + " bytes, "
+ errorCount() + " errors, " + warningCount() + " warnings");
for (IrisStructureAdoptionDiagnostic diagnostic : diagnostics) {
lines.add(diagnostic.summary());
}
return List.copyOf(lines);
}
private static List<IrisStructureAdoptionDiagnostic> sortedDiagnostics(
List<IrisStructureAdoptionDiagnostic> values
) {
ArrayList<IrisStructureAdoptionDiagnostic> ordered = new ArrayList<>(values);
ordered.sort(IrisStructureAdoptionDiagnostic::compareTo);
return List.copyOf(ordered);
}
private static Map<String, String> immutableMap(Map<String, String> values) {
Objects.requireNonNull(values, "plan values");
return Collections.unmodifiableMap(new TreeMap<>(values));
}
private static void requireHash(String value, String kind) {
if (!StructureHash.isSha256(value)) {
throw new IllegalArgumentException("Adoption " + kind + " hash must be SHA-256");
}
}
}
@@ -0,0 +1,82 @@
package art.arcane.iris.core.structure.conversion;
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 java.time.Instant;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.UUID;
public record IrisStructureAdoptionReceipt(
UUID receiptId,
UUID planId,
StructureOwnershipManifest.Origin origin,
Instant appliedAt,
StructureKey sourceStructure,
StructureKey targetStructure,
String sourceClosureHash,
String planHash,
Map<String, String> sourceResourceHashes,
Map<String, String> targetResourceHashes,
Map<String, String> sourceToTargetPaths,
StructureOwnershipManifest.RollbackDisposition rollbackDisposition
) {
public IrisStructureAdoptionReceipt {
Objects.requireNonNull(receiptId, "receiptId");
Objects.requireNonNull(planId, "planId");
Objects.requireNonNull(origin, "origin");
Objects.requireNonNull(appliedAt, "appliedAt");
Objects.requireNonNull(sourceStructure, "sourceStructure");
Objects.requireNonNull(targetStructure, "targetStructure");
requireHash(sourceClosureHash, "source closure");
requireHash(planHash, "plan");
sourceResourceHashes = immutableMap(sourceResourceHashes, true);
targetResourceHashes = immutableMap(targetResourceHashes, true);
sourceToTargetPaths = immutableMap(sourceToTargetPaths, false);
rollbackDisposition = Objects.requireNonNull(rollbackDisposition, "rollbackDisposition");
if (sourceResourceHashes.isEmpty() || targetResourceHashes.isEmpty() || sourceToTargetPaths.isEmpty()) {
throw new IllegalArgumentException("Adoption receipt requires source, target, and mapping entries");
}
}
public StructureOwnershipManifest.Provenance provenance() {
return new StructureOwnershipManifest.Provenance(
origin,
receiptId.toString(),
planHash,
sourceClosureHash,
appliedAt.toEpochMilli(),
sourceResourceHashes,
sourceToTargetPaths,
rollbackDisposition
);
}
public boolean rollbackAvailable() {
return rollbackDisposition != StructureOwnershipManifest.RollbackDisposition.NONE;
}
private static Map<String, String> immutableMap(Map<String, String> values, boolean hashes) {
Objects.requireNonNull(values, "receipt values");
TreeMap<String, String> ordered = new TreeMap<>();
for (Map.Entry<String, String> entry : values.entrySet()) {
String key = Objects.requireNonNull(entry.getKey(), "receipt map key");
String value = Objects.requireNonNull(entry.getValue(), "receipt map value");
if (hashes) {
requireHash(value, "resource");
}
ordered.put(key, value);
}
return Collections.unmodifiableMap(ordered);
}
private static void requireHash(String value, String kind) {
if (!StructureHash.isSha256(value)) {
throw new IllegalArgumentException("Adoption receipt " + kind + " hash must be SHA-256");
}
}
}
@@ -0,0 +1,54 @@
package art.arcane.iris.core.structure.conversion;
import art.arcane.iris.core.structure.authoring.StructureKey;
import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
import java.util.Objects;
import java.util.Optional;
public record IrisStructureAdoptionRequest(
String sourceStructure,
Optional<StructureKey> requestedTarget,
IrisStructureAdoptionStrategy strategy,
IrisStructureAdoptionInputKind inputKind
) {
public IrisStructureAdoptionRequest {
sourceStructure = requireInternalKey(sourceStructure);
requestedTarget = Objects.requireNonNull(requestedTarget, "requestedTarget");
strategy = Objects.requireNonNull(strategy, "strategy");
inputKind = Objects.requireNonNull(inputKind, "inputKind");
}
public static IrisStructureAdoptionRequest unowned(String sourceStructure) {
return new IrisStructureAdoptionRequest(
sourceStructure,
Optional.empty(),
IrisStructureAdoptionStrategy.AUTO,
IrisStructureAdoptionInputKind.UNOWNED_IRIS
);
}
public static IrisStructureAdoptionRequest cloneTo(String sourceStructure, StructureKey target) {
return new IrisStructureAdoptionRequest(
sourceStructure,
Optional.of(Objects.requireNonNull(target, "target")),
IrisStructureAdoptionStrategy.CLONE,
IrisStructureAdoptionInputKind.UNOWNED_IRIS
);
}
public StructureKey sourceOwnershipKey() {
return new StructureKey("iris", sourceStructure);
}
private static String requireInternalKey(String value) {
Objects.requireNonNull(value, "sourceStructure");
String normalized = value.trim();
if (!normalized.equals(value)) {
throw new IllegalArgumentException("Source structure key cannot contain surrounding whitespace");
}
StructureResourceBundle.validateRelativePath("structures/" + normalized + ".json");
new StructureKey("iris", normalized);
return normalized;
}
}
@@ -0,0 +1,54 @@
package art.arcane.iris.core.structure.conversion;
import art.arcane.iris.core.structure.authoring.StructureWriteResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
public record IrisStructureAdoptionResult(
Status status,
UUID planId,
List<IrisStructureAdoptionDiagnostic> diagnostics,
Optional<IrisStructureAdoptionReceipt> receipt,
Optional<StructureWriteResult> writeResult
) {
public IrisStructureAdoptionResult {
Objects.requireNonNull(status, "status");
Objects.requireNonNull(planId, "planId");
Objects.requireNonNull(diagnostics, "diagnostics");
Objects.requireNonNull(receipt, "receipt");
Objects.requireNonNull(writeResult, "writeResult");
diagnostics = List.copyOf(diagnostics);
if (status == Status.APPLIED && receipt.isEmpty()) {
throw new IllegalArgumentException("Applied adoption result requires a receipt");
}
if (status != Status.APPLIED && receipt.isPresent()) {
throw new IllegalArgumentException("Failed adoption result cannot expose a receipt");
}
}
public boolean successful() {
return status == Status.APPLIED;
}
public List<String> summaryLines() {
ArrayList<String> lines = new ArrayList<>();
lines.add("Adoption plan " + planId + ": " + status);
for (IrisStructureAdoptionDiagnostic diagnostic : diagnostics) {
lines.add(diagnostic.summary());
}
return List.copyOf(lines);
}
public enum Status {
APPLIED,
BLOCKED,
EXPIRED,
UNKNOWN_PLAN,
STALE,
FAILED
}
}
@@ -0,0 +1,7 @@
package art.arcane.iris.core.structure.conversion;
public enum IrisStructureAdoptionStrategy {
AUTO,
IN_PLACE,
CLONE
}
@@ -0,0 +1,160 @@
package art.arcane.iris.core.structure.export;
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.stream.Stream;
final class AtomicDatapackPublisher {
Publication publish(
Map<String, byte[]> resources,
Path output,
VanillaJigsawExportFormat format,
boolean replaceExisting
) throws IOException {
Path parent = output.getParent();
if (parent == null) {
throw new IOException("Export output has no parent directory: " + output);
}
Files.createDirectories(parent);
Path staging = Files.createTempDirectory(parent, ".iris-jigsaw-export-");
List<String> cleanupWarnings = new ArrayList<>();
try {
Path artifact = format == VanillaJigsawExportFormat.DIRECTORY
? createDirectoryArtifact(staging, resources)
: createZipArtifact(staging, resources);
replaceAtomically(artifact, output, replaceExisting, cleanupWarnings);
} finally {
try {
deleteTree(staging);
} catch (IOException exception) {
cleanupWarnings.add("Could not remove export staging path '" + staging + "': " + exception.getMessage());
}
}
return new Publication(List.copyOf(cleanupWarnings));
}
private Path createDirectoryArtifact(Path staging, Map<String, byte[]> resources) throws IOException {
Path root = staging.resolve("pack");
Files.createDirectory(root);
for (String resource : sortedPaths(resources)) {
Path target = root.resolve(resource).normalize();
if (!target.startsWith(root)) {
throw new IOException("Export resource escapes staging root: " + resource);
}
Files.createDirectories(target.getParent());
Files.write(target, resources.get(resource));
}
return root;
}
private Path createZipArtifact(Path staging, Map<String, byte[]> resources) throws IOException {
Path zip = staging.resolve("pack.zip");
try (ZipOutputStream output = new ZipOutputStream(Files.newOutputStream(zip))) {
for (String resource : sortedPaths(resources)) {
ZipEntry entry = new ZipEntry(resource);
entry.setTime(0L);
output.putNextEntry(entry);
output.write(resources.get(resource));
output.closeEntry();
}
}
return zip;
}
private void replaceAtomically(
Path artifact,
Path output,
boolean replaceExisting,
List<String> cleanupWarnings
) throws IOException {
Path backup = null;
if (Files.exists(output)) {
if (!replaceExisting) {
throw new IOException("Export output already exists: " + output);
}
backup = uniqueBackup(output);
atomicMove(output, backup);
}
try {
atomicMove(artifact, output);
} catch (IOException publicationFailure) {
if (backup != null && Files.exists(backup) && !Files.exists(output)) {
try {
atomicMove(backup, output);
} catch (IOException restoreFailure) {
publicationFailure.addSuppressed(restoreFailure);
}
}
throw publicationFailure;
}
if (backup != null) {
try {
deleteTree(backup);
} catch (IOException exception) {
cleanupWarnings.add("Export succeeded, but the replaced output backup remains at '"
+ backup + "': " + exception.getMessage());
}
}
}
private void atomicMove(Path source, Path target) throws IOException {
try {
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException exception) {
throw new IOException("Filesystem does not support an atomic export move from '"
+ source + "' to '" + target + "'.", exception);
}
}
private Path uniqueBackup(Path output) {
return output.resolveSibling("." + output.getFileName() + ".iris-backup-" + UUID.randomUUID());
}
private List<String> sortedPaths(Map<String, byte[]> resources) {
List<String> paths = new ArrayList<>(resources.keySet());
paths.sort(String::compareTo);
return paths;
}
private void deleteTree(Path root) throws IOException {
if (!Files.exists(root)) {
return;
}
try (Stream<Path> paths = Files.walk(root)) {
List<Path> ordered = paths.sorted(Comparator.reverseOrder()).toList();
IOException failure = null;
for (Path path : ordered) {
try {
Files.deleteIfExists(path);
} catch (IOException exception) {
if (failure == null) {
failure = exception;
} else {
failure.addSuppressed(exception);
}
}
}
if (failure != null) {
throw failure;
}
}
}
record Publication(List<String> cleanupWarnings) {
Publication {
cleanupWarnings = List.copyOf(cleanupWarnings);
}
}
}
@@ -0,0 +1,82 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure.export;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import com.volmit.object.ObjectBlock;
import com.volmit.object.PlaceableObject;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* What an exporter reads of a pack object: its declared size and its blocks and block entities at positions counted from
* the object's corner, with the blocks only the platform can place or that need a block entity noted.
*
* @param customBlocks where the stored block is a custom-content block
* @param blocksNeedingEntity where the stored block is of a kind that carries a block entity
*/
public record ObjectContents(int width, int height, int depth, Map<BlockPosition, BlockState> blocks,
Map<BlockPosition, BlockEntityData> blockEntities, Set<BlockPosition> customBlocks,
Set<BlockPosition> blocksNeedingEntity) {
public ObjectContents {
blocks = Map.copyOf(blocks);
blockEntities = Map.copyOf(blockEntities);
customBlocks = Set.copyOf(customBlocks);
blocksNeedingEntity = Set.copyOf(blocksNeedingEntity);
}
/** An object with these blocks and nothing special about any of them. */
public static ObjectContents plain(int width, int height, int depth, Map<BlockPosition, BlockState> blocks,
Map<BlockPosition, BlockEntityData> blockEntities) {
return new ObjectContents(width, height, depth, blocks, blockEntities, Set.of(), Set.of());
}
/** {@code object} as its blocks lie in its declared box; {@code registry} says which are custom or hold block entities. */
public static ObjectContents of(PlaceableObject object, BlockRegistry registry) {
BlockPosition center = object.center();
Map<BlockPosition, BlockState> blocks = new LinkedHashMap<>();
Map<BlockPosition, BlockEntityData> entities = new LinkedHashMap<>();
Set<BlockPosition> custom = new LinkedHashSet<>();
Set<BlockPosition> needingEntity = new LinkedHashSet<>();
for (ObjectBlock block : object.geometry().blocks()) {
BlockPosition position = block.position().add(center);
blocks.put(position, block.state());
block.blockEntity().ifPresent(entity -> entities.put(position, entity));
if (registry.hasTrait(block.state(), BlockTrait.CUSTOM)) {
custom.add(position);
}
if (registry.hasTrait(block.state(), BlockTrait.STORAGE)) {
needingEntity.add(position);
}
}
return new ObjectContents(object.width(), object.height(), object.depth(), blocks, entities, custom, needingEntity);
}
/** The block the object's offsets count from, relative to its corner. */
public BlockPosition center() {
return new BlockPosition(width / 2, height / 2, depth / 2);
}
}
@@ -0,0 +1,88 @@
package art.arcane.iris.core.structure.export;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
record VanillaBlockState(String name, Map<String, String> properties) {
private static final Pattern PROPERTY_NAME = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PROPERTY_VALUE = Pattern.compile("[a-z0-9_.-]+");
VanillaBlockState {
properties = Collections.unmodifiableMap(new LinkedHashMap<>(properties));
}
static VanillaBlockState parse(String value) {
if (value == null) {
throw new IllegalArgumentException("Block state must not be null");
}
String source = value.trim();
int propertiesStart = source.indexOf('[');
String name = propertiesStart < 0 ? source : source.substring(0, propertiesStart);
if (!VanillaResourceIdentifier.validIdentifier(name)) {
throw new IllegalArgumentException("Invalid block identifier '" + name + "'");
}
if (!name.startsWith("minecraft:")) {
throw new IllegalArgumentException("Vanilla cannot resolve non-Minecraft block '" + name + "'");
}
if (propertiesStart < 0) {
return new VanillaBlockState(name, Map.of());
}
if (!source.endsWith("]") || source.indexOf('[', propertiesStart + 1) >= 0) {
throw new IllegalArgumentException("Invalid property block in '" + value + "'");
}
String body = source.substring(propertiesStart + 1, source.length() - 1);
if (body.isEmpty()) {
throw new IllegalArgumentException("Empty property block in '" + value + "'");
}
Map<String, String> properties = new TreeMap<>();
for (String property : body.split(",", -1)) {
int separator = property.indexOf('=');
if (separator <= 0 || separator != property.lastIndexOf('=') || separator == property.length() - 1) {
throw new IllegalArgumentException("Invalid block property '" + property + "'");
}
String propertyName = property.substring(0, separator);
String propertyValue = property.substring(separator + 1);
if (!PROPERTY_NAME.matcher(propertyName).matches() || !PROPERTY_VALUE.matcher(propertyValue).matches()) {
throw new IllegalArgumentException("Invalid block property '" + property + "'");
}
if (properties.put(propertyName, propertyValue) != null) {
throw new IllegalArgumentException("Duplicate block property '" + propertyName + "'");
}
}
return new VanillaBlockState(name, properties);
}
String canonical() {
if (properties.isEmpty()) {
return name;
}
StringBuilder builder = new StringBuilder(name).append('[');
boolean first = true;
for (Map.Entry<String, String> property : properties.entrySet()) {
if (!first) {
builder.append(',');
}
builder.append(property.getKey()).append('=').append(property.getValue());
first = false;
}
return builder.append(']').toString();
}
CompoundTag toNbt() {
CompoundTag state = new CompoundTag();
state.putString("Name", name);
if (!properties.isEmpty()) {
CompoundTag propertyTag = new CompoundTag();
for (Map.Entry<String, String> property : properties.entrySet()) {
propertyTag.putString(property.getKey(), property.getValue());
}
state.put("Properties", propertyTag);
}
return state;
}
}
@@ -0,0 +1,74 @@
package art.arcane.iris.core.structure.export;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
public final class VanillaJigsawDatapackExporter {
public VanillaJigsawExportValidation validate(VanillaJigsawExportRequest request) {
VanillaJigsawExportCompiler.Compilation compilation = new VanillaJigsawExportCompiler().compile(request);
List<String> resources = new ArrayList<>(compilation.resources().keySet());
resources.sort(String::compareTo);
return new VanillaJigsawExportValidation(resources, compilation.diagnostics());
}
public VanillaJigsawExportResult export(VanillaJigsawExportRequest request) {
if (Files.exists(request.output()) && !request.replaceExisting()) {
VanillaJigsawExportDiagnostic diagnostic = new VanillaJigsawExportDiagnostic(
VanillaJigsawExportDiagnostic.Severity.ERROR,
VanillaJigsawExportDiagnostic.Code.OUTPUT_EXISTS,
request.output().toString(),
"Export output already exists and replaceExisting is false.");
return new VanillaJigsawExportResult(
VanillaJigsawExportResult.Status.REJECTED,
request.output(),
List.of(),
List.of(diagnostic));
}
VanillaJigsawExportCompiler.Compilation compilation = new VanillaJigsawExportCompiler().compile(request);
if (compilation.hasErrors()) {
return new VanillaJigsawExportResult(
VanillaJigsawExportResult.Status.REJECTED,
request.output(),
List.of(),
compilation.diagnostics());
}
List<VanillaJigsawExportDiagnostic> diagnostics = new ArrayList<>(compilation.diagnostics());
try {
AtomicDatapackPublisher.Publication publication = new AtomicDatapackPublisher().publish(
compilation.resources(),
request.output(),
request.format(),
request.replaceExisting());
for (String warning : publication.cleanupWarnings()) {
diagnostics.add(new VanillaJigsawExportDiagnostic(
VanillaJigsawExportDiagnostic.Severity.WARNING,
VanillaJigsawExportDiagnostic.Code.CLEANUP_FAILED,
request.output().toString(),
warning));
}
} catch (IOException exception) {
diagnostics.add(new VanillaJigsawExportDiagnostic(
VanillaJigsawExportDiagnostic.Severity.ERROR,
VanillaJigsawExportDiagnostic.Code.PUBLICATION_FAILED,
request.output().toString(),
"Atomic datapack publication failed: " + exception.getMessage()));
return new VanillaJigsawExportResult(
VanillaJigsawExportResult.Status.FAILED,
request.output(),
List.of(),
diagnostics);
}
List<String> resources = new ArrayList<>(compilation.resources().keySet());
resources.sort(String::compareTo);
return new VanillaJigsawExportResult(
VanillaJigsawExportResult.Status.EXPORTED,
request.output(),
resources,
diagnostics);
}
}
@@ -0,0 +1,816 @@
package art.arcane.iris.core.structure.export;
import art.arcane.iris.engine.framework.structure.CompiledStructureGraph;
import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver;
import art.arcane.iris.engine.framework.structure.StructureGraphCompilation;
import art.arcane.iris.engine.framework.structure.StructureGraphCompiler;
import art.arcane.iris.engine.framework.structure.StructureGraphDiagnostic;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility;
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.IrisJigsawWorkcellArchetype;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.volmlib.util.math.IrisBlockVector;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
final class VanillaJigsawExportCompiler {
private static final int MAX_DEPTH = 20;
private static final int MAX_HORIZONTAL_DISTANCE = 128;
private static final int MAX_VERTICAL_DISTANCE = 4064;
private static final int MIN_ABSOLUTE_Y = -2032;
private static final int MAX_ABSOLUTE_Y = 2031;
private static final int MAX_POOL_WEIGHT = 150;
private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create();
Compilation compile(VanillaJigsawExportRequest request) {
List<VanillaJigsawExportDiagnostic> diagnostics = new ArrayList<>();
validateIdentity(request, diagnostics);
validateSettings(request.settings(), diagnostics);
IrisStructure structure;
try {
structure = request.source().loadStructure();
} catch (RuntimeException exception) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.SOURCE_STRUCTURE_MISSING,
request.source().structureKey(),
"Could not load Iris structure '" + request.source().structureKey() + "': "
+ exception.getMessage());
return rejected(diagnostics);
}
if (structure == null) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.SOURCE_STRUCTURE_MISSING,
request.source().structureKey(),
"Iris structure '" + request.source().structureKey() + "' does not exist.");
return rejected(diagnostics);
}
validateStructure(request.source().structureKey(), structure, request.settings(), diagnostics);
StructureGraphCompilation graphCompilation;
try {
graphCompilation = StructureGraphCompiler.compile(
request.source().structureKey(), structure, request.source().resolver());
} catch (RuntimeException exception) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.GRAPH_VALIDATION,
request.source().structureKey(),
"Structure graph compilation failed: " + exception.getMessage());
return rejected(diagnostics);
}
addGraphDiagnostics(graphCompilation, diagnostics);
CompiledStructureGraph graph = graphCompilation.getGraph();
validateGraph(graph, request.source(), diagnostics);
if (hasErrors(diagnostics)) {
return rejected(diagnostics);
}
try {
Map<String, byte[]> resources = createResources(request, graph);
return new Compilation(resources, List.copyOf(diagnostics));
} catch (IOException | RuntimeException exception) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.SERIALIZATION_FAILED,
request.source().structureKey(),
"Vanilla datapack serialization failed: " + exception.getMessage());
return rejected(diagnostics);
}
}
private void validateIdentity(
VanillaJigsawExportRequest request,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
if (!VanillaResourceIdentifier.validNamespace(request.namespace())) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_NAMESPACE,
request.namespace(),
"Datapack namespace must match [a-z0-9_.-]+.");
}
if (!VanillaResourceIdentifier.validPath(request.resourcePath())) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_RESOURCE_PATH,
request.resourcePath(),
"Datapack resource path must use lowercase resource-path characters without traversal.");
}
}
private void validateSettings(
VanillaJigsawExportSettings settings,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
if (settings.biomes().isEmpty()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_BIOME,
"biomes",
"At least one biome identifier is required.");
}
for (String biome : settings.biomes()) {
if (!VanillaResourceIdentifier.validIdentifier(biome)) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_BIOME,
biome,
"Biome identifier '" + biome + "' is not a valid namespaced identifier.");
}
}
if (settings.startHeight() < MIN_ABSOLUTE_Y || settings.startHeight() > MAX_ABSOLUTE_Y) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_SETTINGS,
"start_height",
"Absolute start height must be between " + MIN_ABSOLUTE_Y + " and " + MAX_ABSOLUTE_Y + ".");
}
if (settings.maxDistanceVertical() < 1 || settings.maxDistanceVertical() > MAX_VERTICAL_DISTANCE) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_MAX_DISTANCE,
"max_distance_from_center.vertical",
"Vertical maximum distance must be between 1 and " + MAX_VERTICAL_DISTANCE + ".");
}
if (settings.spacing() < 0 || settings.spacing() > 4096
|| settings.separation() < 0 || settings.separation() > 4096
|| settings.spacing() <= settings.separation()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_SETTINGS,
"random_spread",
"Random-spread spacing and separation must be within 0..4096, with spacing greater than separation.");
}
if (settings.salt() < 0) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_SETTINGS,
"random_spread.salt",
"Random-spread salt must be non-negative.");
}
if (!Float.isFinite(settings.frequency()) || settings.frequency() < 0.0F || settings.frequency() > 1.0F) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_SETTINGS,
"random_spread.frequency",
"Random-spread frequency must be finite and within 0..1.");
}
}
private void validateStructure(
String structureKey,
IrisStructure structure,
VanillaJigsawExportSettings settings,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
if (structure.resolvedCompatibility() != IrisJigsawCompatibility.VANILLA_PORTABLE) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_COMPATIBILITY,
structureKey,
"Strict export requires compatibility VANILLA_PORTABLE.");
}
if (!structure.stampsPiecesWhereAssembled()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_PLACE_MODE,
structureKey,
"Vanilla export requires placeMode STRUCTURE_PIECE; Iris terrain and stilt modes have no vanilla jigsaw equivalent.");
}
if (structure.getEdit() != null && !structure.getEdit().isEmpty()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_EDIT,
structureKey,
"Structure-wide Iris block edits cannot be represented losslessly by vanilla template pools.");
}
if (structure.getLoot() != null && !structure.getLoot().isEmpty()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_LOOT,
structureKey,
"Structure-wide Iris loot injection cannot be represented losslessly by this vanilla exporter.");
}
if (structure.getThemeSets() != null && !structure.getThemeSets().isEmpty()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_THEME_METADATA,
structureKey,
"Coherent Iris theme selection has no lossless vanilla jigsaw representation.");
}
if (structure.isRequireCaps()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_REQUIRED_CAPS,
structureKey,
"Vanilla jigsaws cannot enforce Iris requireCaps terminal-closure semantics.");
}
if (structure.getMaxDepth() < 1 || structure.getMaxDepth() > MAX_DEPTH) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_MAX_DEPTH,
structureKey,
"Minecraft 26.2 jigsaw size must be within 0..20; Iris export requires 1..20.");
}
long horizontalDistance = (long) structure.getMaxSizeChunks() * 16L;
if (horizontalDistance < 1L || horizontalDistance > MAX_HORIZONTAL_DISTANCE) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_MAX_DISTANCE,
structureKey,
"Iris maxSizeChunks maps to " + horizontalDistance
+ " blocks, outside Minecraft 26.2's 1..128 horizontal limit.");
}
int terrainPadding = settings.terrainAdaptation() == VanillaJigsawExportSettings.TerrainAdaptation.NONE
? 0 : 12;
if (horizontalDistance + terrainPadding > MAX_HORIZONTAL_DISTANCE) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_MAX_DISTANCE,
structureKey,
"Horizontal distance plus vanilla terrain-adaptation padding must not exceed 128 blocks.");
}
}
private void addGraphDiagnostics(
StructureGraphCompilation graphCompilation,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
for (StructureGraphDiagnostic diagnostic : graphCompilation.getDiagnostics()) {
VanillaJigsawExportDiagnostic.Severity severity = diagnostic.severity()
== StructureGraphDiagnostic.Severity.ERROR
? VanillaJigsawExportDiagnostic.Severity.ERROR
: VanillaJigsawExportDiagnostic.Severity.WARNING;
diagnostics.add(new VanillaJigsawExportDiagnostic(
severity,
VanillaJigsawExportDiagnostic.Code.GRAPH_VALIDATION,
diagnostic.code().name(),
diagnostic.message()));
}
}
private void validateGraph(
CompiledStructureGraph graph,
VanillaJigsawExportSource source,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell> workcells =
resolvedWorkcells(graph.getStructure());
for (Map.Entry<String, IrisJigsawPool> poolEntry : graph.getPools().entrySet()) {
String poolKey = poolEntry.getKey();
if (!VanillaResourceIdentifier.validPath(poolKey)) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_RESOURCE_PATH,
poolKey,
"Iris pool keys must be valid lowercase resource paths for vanilla export.");
}
validatePool(graph, workcells, poolKey, poolEntry.getValue(), diagnostics);
}
for (Map.Entry<String, IrisJigsawPiece> pieceEntry : graph.getPieces().entrySet()) {
if (!pieceEnabled(workcells, pieceEntry.getValue())) {
continue;
}
String pieceKey = pieceEntry.getKey();
if (!VanillaResourceIdentifier.validPath(pieceKey)) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_RESOURCE_PATH,
pieceKey,
"Iris piece keys must be valid lowercase resource paths for vanilla export.");
}
validatePiece(graph, source, pieceKey, pieceEntry.getValue(), diagnostics);
}
}
private void validatePool(
CompiledStructureGraph graph,
Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell> workcells,
String poolKey,
IrisJigsawPool pool,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
if (pool.isMandatoryFallback()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_REQUIRED_CAPS,
poolKey,
"Vanilla template pools cannot enforce Iris mandatoryFallback terminal closure.");
}
if (pool.getFallback() != null && !pool.getFallback().isBlank()
&& !VanillaResourceIdentifier.validPath(pool.getFallback().trim())) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_RESOURCE_PATH,
poolKey,
"Fallback pool key '" + pool.getFallback() + "' is not a valid vanilla resource path.");
}
if (pool.getPieces() == null) {
return;
}
for (int index = 0; index < pool.getPieces().size(); index++) {
IrisJigsawPieceEntry entry = pool.getPieces().get(index);
if (entry == null) {
continue;
}
if (!entry.isEmpty()
&& !pieceEnabled(workcells, graph.getPieces().get(trim(entry.getPiece())))) {
continue;
}
if (entry.getWeight() < 1 || entry.getWeight() > MAX_POOL_WEIGHT) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_POOL_WEIGHT,
poolKey + "/pieces[" + index + "]",
"Minecraft 26.2 template-pool weights must be within 1..150.");
}
if (entry.getChance() != 1D) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_CHANCE,
poolKey + "/pieces[" + index + "]",
"Independent Iris membership chance cannot be represented by vanilla pool weights.");
}
if (!entry.isEmpty() && !VanillaResourceIdentifier.validPath(trim(entry.getPiece()))) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_RESOURCE_PATH,
poolKey + "/pieces[" + index + "]",
"Piece key '" + entry.getPiece() + "' is not a valid vanilla resource path.");
}
}
}
private void validatePiece(
CompiledStructureGraph graph,
VanillaJigsawExportSource source,
String pieceKey,
IrisJigsawPiece piece,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
if (piece.getThemes() != null && !piece.getThemes().isEmpty()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_THEME_METADATA,
pieceKey,
"Iris piece theme membership has no vanilla template-pool equivalent.");
}
IrisJigsawPieceRules rules = piece.resolvedRules();
if (rules.getMinimumDepth() != 0
|| rules.getMaximumDepth() != 30
|| rules.getMinimumPlacements() != 0
|| rules.getMaximumPlacements() != 0
|| rules.isTerminal()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_PIECE_RULES,
pieceKey,
"Iris depth, placement-count, and terminal rules cannot be serialized losslessly to vanilla.");
}
if (!piece.isRotatable()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_FIXED_ROTATION,
pieceKey,
"Vanilla template pools do not provide an exact fixed-rotation equivalent for Iris rotatable=false.");
}
if (!piece.isCollidable()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_NON_COLLIDABLE_PIECE,
pieceKey,
"Vanilla template pools cannot serialize Iris collidable=false assembly metadata.");
}
ObjectContents object = source.contents(trim(piece.getObject()));
if (object == null) {
return;
}
validateObject(pieceKey, object, diagnostics);
validateConnectors(graph, pieceKey, piece, object, diagnostics);
}
private void validateObject(
String pieceKey,
ObjectContents object,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
ObjectContents contents = object;
if (!contents.blockEntities().isEmpty()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_TILE_DATA,
pieceKey,
"The .iob contains tile payloads; exact registry-aware block-entity NBT export is not available in core.");
}
for (Map.Entry<BlockPosition, BlockState> entry : contents.blocks().entrySet()) {
BlockState state = entry.getValue();
BlockPosition position = entry.getKey();
String resource = pieceKey + "@" + new IrisBlockVector(
position.x() - object.center().x(),
position.y() - object.center().y(),
position.z() - object.center().z());
int x = position.x();
int y = position.y();
int z = position.z();
if (x < 0 || x >= object.width() || y < 0 || y >= object.height() || z < 0 || z >= object.depth()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_BLOCK_STATE,
resource,
"The .iob contains a block outside its declared dimensions.");
continue;
}
if (contents.customBlocks().contains(position)) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_CUSTOM_BLOCK,
resource,
"Custom-content block '" + state.key() + "' is not available in unmodded vanilla.");
continue;
}
if (contents.blocksNeedingEntity().contains(position)) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_BLOCK_ENTITY,
resource,
"Block '" + state.key() + "' requires block-entity NBT that core cannot export losslessly.");
}
try {
VanillaBlockState parsed = VanillaBlockState.parse(state.key());
if (parsed.name().equals("minecraft:jigsaw")
|| parsed.name().equals("minecraft:structure_block")
|| parsed.name().equals("minecraft:structure_void")) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_MARKER_BLOCK,
resource,
"Marker block '" + parsed.name() + "' must be represented by Iris connector metadata, not object blocks.");
}
} catch (IllegalArgumentException exception) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_BLOCK_STATE,
resource,
exception.getMessage());
}
}
}
private void validateConnectors(
CompiledStructureGraph graph,
String pieceKey,
IrisJigsawPiece piece,
ObjectContents object,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
if (piece.getConnectors() == null) {
return;
}
Set<String> positions = new LinkedHashSet<>();
Map<BlockPosition, BlockState> storedBlocks = object.blocks();
for (int index = 0; index < piece.getConnectors().size(); index++) {
IrisJigsawConnector connector = piece.getConnectors().get(index);
if (connector == null) {
continue;
}
String resource = pieceKey + "/connectors[" + index + "]";
if (connector.getChannel() != null && !connector.getChannel().isBlank()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_CHANNEL,
resource,
"Iris connector channels have no vanilla jigsaw NBT equivalent.");
}
validateConnectorIdentifier(connector.getName(), resource + "/name", diagnostics);
validateConnectorIdentifier(connector.getTargetName(), resource + "/target", diagnostics);
String poolKey = trim(connector.getPool());
if (!VanillaResourceIdentifier.validPath(poolKey) || !graph.getPools().containsKey(poolKey)) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_RESOURCE_PATH,
resource + "/pool",
"Connector pool '" + connector.getPool() + "' cannot be mapped to an exported template pool.");
}
try {
VanillaStructureTemplateEncoder.orientation(connector.getDirection(), connector.getTop());
} catch (IllegalArgumentException | NullPointerException exception) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_CONNECTOR_ORIENTATION,
resource,
exception.getMessage() == null ? "Connector orientation is incomplete." : exception.getMessage());
}
BlockPosition position = connector.getPosition();
if (position == null || !inside(position, object)) {
continue;
}
String positionKey = position.x() + "," + position.y() + "," + position.z();
if (!positions.add(positionKey)) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.DUPLICATE_CONNECTOR_POSITION,
resource,
"Multiple vanilla jigsaw block entities cannot occupy " + positionKey + ".");
}
validateFinalState(storedBlocks, connector, resource, diagnostics);
}
}
private void validateConnectorIdentifier(
String value,
String resource,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
try {
VanillaResourceIdentifier.normalizeConnectorIdentifier(value);
} catch (IllegalArgumentException exception) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_CONNECTOR_ID,
resource,
exception.getMessage());
}
}
private void validateFinalState(
Map<BlockPosition, BlockState> storedBlocks,
IrisJigsawConnector connector,
String resource,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
VanillaBlockState configured;
try {
configured = VanillaBlockState.parse(connector.getFinalState());
} catch (IllegalArgumentException exception) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_CONNECTOR_FINAL_STATE,
resource,
exception.getMessage());
return;
}
BlockPosition position = connector.getPosition();
BlockState objectState = storedBlocks.get(position);
String expectedSource = objectState == null ? "minecraft:structure_void" : objectState.key();
try {
VanillaBlockState expected = VanillaBlockState.parse(expectedSource);
if (!configured.canonical().equals(expected.canonical())) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_CONNECTOR_FINAL_STATE,
resource,
"Connector finalState '" + configured.canonical() + "' does not match the .iob block '"
+ expected.canonical() + "' at that position. Use minecraft:structure_void for an absent block.");
}
} catch (IllegalArgumentException exception) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_CONNECTOR_FINAL_STATE,
resource,
"The .iob block under the connector is not vanilla-compatible: " + exception.getMessage());
}
}
private Map<String, byte[]> createResources(
VanillaJigsawExportRequest request,
CompiledStructureGraph graph
) throws IOException {
Map<String, byte[]> resources = new LinkedHashMap<>();
putJson(resources, "pack.mcmeta", packMetadata(request));
putJson(resources, biomeTagPath(request), biomeTag(request));
putJson(resources, processorPath(request), processorList());
putJson(resources, structurePath(request), structure(request, graph.getStructure()));
putJson(resources, structureSetPath(request), structureSet(request));
for (Map.Entry<String, IrisJigsawPool> poolEntry : graph.getPools().entrySet()) {
putJson(resources,
poolPath(request, poolEntry.getKey()),
templatePool(request, graph, poolEntry.getValue()));
}
VanillaStructureTemplateEncoder encoder = new VanillaStructureTemplateEncoder();
Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell> workcells =
resolvedWorkcells(graph.getStructure());
for (Map.Entry<String, IrisJigsawPiece> pieceEntry : graph.getPieces().entrySet()) {
if (!pieceEnabled(workcells, pieceEntry.getValue())) {
continue;
}
ObjectContents object = request.source().contents(trim(pieceEntry.getValue().getObject()));
byte[] template = encoder.encode(
object,
pieceEntry.getValue(),
poolKey -> poolIdentifier(request, trim(poolKey)));
resources.put(templatePath(request, pieceEntry.getKey()), template);
}
return resources;
}
private JsonObject packMetadata(VanillaJigsawExportRequest request) {
JsonObject pack = new JsonObject();
pack.addProperty("description", request.description());
JsonArray minimum = new JsonArray();
minimum.add(107);
minimum.add(1);
pack.add("min_format", minimum);
pack.addProperty("max_format", 107);
JsonObject root = new JsonObject();
root.add("pack", pack);
return root;
}
private JsonObject biomeTag(VanillaJigsawExportRequest request) {
JsonObject root = new JsonObject();
root.addProperty("replace", false);
JsonArray values = new JsonArray();
for (String biome : request.settings().biomes()) {
values.add(biome);
}
root.add("values", values);
return root;
}
private JsonObject processorList() {
JsonObject root = new JsonObject();
root.add("processors", new JsonArray());
return root;
}
private JsonObject structure(VanillaJigsawExportRequest request, IrisStructure structure) {
VanillaJigsawExportSettings settings = request.settings();
JsonObject root = new JsonObject();
root.addProperty("type", "minecraft:jigsaw");
root.addProperty("biomes", "#" + request.namespace() + ":" + request.resourcePath());
int horizontalDistance = structure.getMaxSizeChunks() * 16;
if (horizontalDistance == settings.maxDistanceVertical()) {
root.addProperty("max_distance_from_center", horizontalDistance);
} else {
JsonObject distance = new JsonObject();
distance.addProperty("horizontal", horizontalDistance);
distance.addProperty("vertical", settings.maxDistanceVertical());
root.add("max_distance_from_center", distance);
}
if (settings.projectHeightmap() != VanillaJigsawExportSettings.ProjectHeightmap.NONE) {
root.addProperty("project_start_to_heightmap", settings.projectHeightmap().serializedName());
}
root.addProperty("size", structure.getMaxDepth());
root.add("spawn_overrides", new JsonObject());
JsonObject startHeight = new JsonObject();
startHeight.addProperty("absolute", settings.startHeight());
root.add("start_height", startHeight);
root.addProperty("start_pool", poolIdentifier(request, trim(structure.getStartPool())));
root.addProperty("step", settings.generationStep().serializedName());
root.addProperty("terrain_adaptation", settings.terrainAdaptation().serializedName());
root.addProperty("use_expansion_hack", settings.expansionHack());
return root;
}
private JsonObject structureSet(VanillaJigsawExportRequest request) {
JsonObject structureEntry = new JsonObject();
structureEntry.addProperty("structure", structureIdentifier(request));
structureEntry.addProperty("weight", 1);
JsonArray structures = new JsonArray();
structures.add(structureEntry);
VanillaJigsawExportSettings settings = request.settings();
JsonObject placement = new JsonObject();
placement.addProperty("type", "minecraft:random_spread");
placement.addProperty("frequency", settings.frequency());
placement.addProperty("salt", settings.salt());
placement.addProperty("separation", settings.separation());
placement.addProperty("spacing", settings.spacing());
placement.addProperty("spread_type", settings.spreadType().serializedName());
JsonObject root = new JsonObject();
root.add("placement", placement);
root.add("structures", structures);
return root;
}
private JsonObject templatePool(
VanillaJigsawExportRequest request,
CompiledStructureGraph graph,
IrisJigsawPool pool
) {
JsonObject root = new JsonObject();
String fallback = trim(pool.getFallback());
root.addProperty("fallback", fallback.isEmpty() ? "minecraft:empty" : poolIdentifier(request, fallback));
JsonArray elements = new JsonArray();
Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell> workcells =
resolvedWorkcells(graph.getStructure());
if (pool.getPieces() != null) {
for (IrisJigsawPieceEntry entry : pool.getPieces()) {
if (!entry.isEmpty()
&& !pieceEnabled(workcells, graph.getPieces().get(trim(entry.getPiece())))) {
continue;
}
JsonObject weightedElement = new JsonObject();
JsonObject element = new JsonObject();
if (entry.isEmpty()) {
element.addProperty("element_type", "minecraft:empty_pool_element");
} else {
element.addProperty("element_type", "minecraft:single_pool_element");
element.addProperty("location", templateIdentifier(request, trim(entry.getPiece())));
element.addProperty("processors", processorIdentifier(request));
element.addProperty("projection", "rigid");
}
weightedElement.add("element", element);
weightedElement.addProperty("weight", entry.getWeight());
elements.add(weightedElement);
}
}
root.add("elements", elements);
return root;
}
private static Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell>
resolvedWorkcells(IrisStructure structure) {
return structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW
? PlanarJigsawWorkcellResolver.resolve(structure)
: Map.of();
}
private static boolean pieceEnabled(
Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell> workcells,
IrisJigsawPiece piece
) {
return workcells.isEmpty()
|| piece == null
|| PlanarJigsawWorkcellResolver.workcell(workcells, piece).enabled();
}
private void putJson(Map<String, byte[]> resources, String path, JsonObject value) {
resources.put(path, (GSON.toJson(value) + "\n").getBytes(StandardCharsets.UTF_8));
}
private String biomeTagPath(VanillaJigsawExportRequest request) {
return "data/" + request.namespace() + "/tags/worldgen/biome/" + request.resourcePath() + ".json";
}
private String processorPath(VanillaJigsawExportRequest request) {
return "data/" + request.namespace() + "/worldgen/processor_list/"
+ request.resourcePath() + "/empty.json";
}
private String structurePath(VanillaJigsawExportRequest request) {
return "data/" + request.namespace() + "/worldgen/structure/" + request.resourcePath() + ".json";
}
private String structureSetPath(VanillaJigsawExportRequest request) {
return "data/" + request.namespace() + "/worldgen/structure_set/" + request.resourcePath() + ".json";
}
private String poolPath(VanillaJigsawExportRequest request, String poolKey) {
return "data/" + request.namespace() + "/worldgen/template_pool/"
+ request.resourcePath() + "/pool/" + poolKey + ".json";
}
private String templatePath(VanillaJigsawExportRequest request, String pieceKey) {
return "data/" + request.namespace() + "/structure/"
+ request.resourcePath() + "/piece/" + pieceKey + ".nbt";
}
private String structureIdentifier(VanillaJigsawExportRequest request) {
return request.namespace() + ":" + request.resourcePath();
}
private String processorIdentifier(VanillaJigsawExportRequest request) {
return request.namespace() + ":" + request.resourcePath() + "/empty";
}
private String poolIdentifier(VanillaJigsawExportRequest request, String poolKey) {
return request.namespace() + ":" + request.resourcePath() + "/pool/" + poolKey;
}
private String templateIdentifier(VanillaJigsawExportRequest request, String pieceKey) {
return request.namespace() + ":" + request.resourcePath() + "/piece/" + pieceKey;
}
private boolean inside(BlockPosition position, ObjectContents object) {
return position.x() >= 0 && position.x() < object.width()
&& position.y() >= 0 && position.y() < object.height()
&& position.z() >= 0 && position.z() < object.depth();
}
private boolean hasErrors(List<VanillaJigsawExportDiagnostic> diagnostics) {
for (VanillaJigsawExportDiagnostic diagnostic : diagnostics) {
if (diagnostic.isBlocking()) {
return true;
}
}
return false;
}
private Compilation rejected(List<VanillaJigsawExportDiagnostic> diagnostics) {
return new Compilation(Map.of(), List.copyOf(diagnostics));
}
private void addError(
List<VanillaJigsawExportDiagnostic> diagnostics,
VanillaJigsawExportDiagnostic.Code code,
String resource,
String message
) {
diagnostics.add(new VanillaJigsawExportDiagnostic(
VanillaJigsawExportDiagnostic.Severity.ERROR,
code,
resource,
message));
}
private String trim(String value) {
return value == null ? "" : value.trim();
}
record Compilation(
Map<String, byte[]> resources,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
Compilation {
resources = Map.copyOf(resources);
diagnostics = List.copyOf(diagnostics);
}
boolean hasErrors() {
for (VanillaJigsawExportDiagnostic diagnostic : diagnostics) {
if (diagnostic.isBlocking()) {
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,58 @@
package art.arcane.iris.core.structure.export;
import java.util.Objects;
public record VanillaJigsawExportDiagnostic(Severity severity, Code code, String resource, String message) {
public VanillaJigsawExportDiagnostic {
Objects.requireNonNull(severity);
Objects.requireNonNull(code);
resource = resource == null ? "" : resource;
Objects.requireNonNull(message);
}
public boolean isBlocking() {
return severity == Severity.ERROR;
}
public enum Severity {
ERROR,
WARNING
}
public enum Code {
SOURCE_STRUCTURE_MISSING,
GRAPH_VALIDATION,
INVALID_NAMESPACE,
INVALID_RESOURCE_PATH,
INVALID_BIOME,
INVALID_SETTINGS,
UNSUPPORTED_COMPATIBILITY,
UNSUPPORTED_PLACE_MODE,
UNSUPPORTED_EDIT,
UNSUPPORTED_LOOT,
UNSUPPORTED_THEME_METADATA,
UNSUPPORTED_CHANCE,
UNSUPPORTED_PIECE_RULES,
UNSUPPORTED_REQUIRED_CAPS,
UNSUPPORTED_CHANNEL,
UNSUPPORTED_FIXED_ROTATION,
UNSUPPORTED_NON_COLLIDABLE_PIECE,
UNSUPPORTED_TILE_DATA,
UNSUPPORTED_BLOCK_ENTITY,
UNSUPPORTED_CUSTOM_BLOCK,
UNSUPPORTED_MARKER_BLOCK,
INVALID_MAX_DEPTH,
INVALID_MAX_DISTANCE,
INVALID_POOL_WEIGHT,
INVALID_CONNECTOR,
INVALID_CONNECTOR_ID,
INVALID_CONNECTOR_ORIENTATION,
INVALID_CONNECTOR_FINAL_STATE,
DUPLICATE_CONNECTOR_POSITION,
INVALID_BLOCK_STATE,
OUTPUT_EXISTS,
SERIALIZATION_FAILED,
PUBLICATION_FAILED,
CLEANUP_FAILED
}
}
@@ -0,0 +1,6 @@
package art.arcane.iris.core.structure.export;
public enum VanillaJigsawExportFormat {
DIRECTORY,
ZIP
}
@@ -0,0 +1,113 @@
package art.arcane.iris.core.structure.export;
import java.nio.file.Path;
import java.util.Objects;
public final class VanillaJigsawExportRequest {
private final VanillaJigsawExportSource source;
private final Path output;
private final String namespace;
private final String resourcePath;
private final String description;
private final VanillaJigsawExportFormat format;
private final VanillaJigsawExportSettings settings;
private final boolean replaceExisting;
private VanillaJigsawExportRequest(Builder builder) {
source = builder.source;
output = builder.output.toAbsolutePath().normalize();
namespace = builder.namespace;
resourcePath = builder.resourcePath;
description = builder.description;
format = builder.format;
settings = builder.settings;
replaceExisting = builder.replaceExisting;
}
public static Builder builder(VanillaJigsawExportSource source, Path output) {
return new Builder(source, output);
}
public VanillaJigsawExportSource source() {
return source;
}
public Path output() {
return output;
}
public String namespace() {
return namespace;
}
public String resourcePath() {
return resourcePath;
}
public String description() {
return description;
}
public VanillaJigsawExportFormat format() {
return format;
}
public VanillaJigsawExportSettings settings() {
return settings;
}
public boolean replaceExisting() {
return replaceExisting;
}
public static final class Builder {
private final VanillaJigsawExportSource source;
private final Path output;
private String namespace = "iris";
private String resourcePath;
private String description = "Iris vanilla jigsaw export for Minecraft 26.2";
private VanillaJigsawExportFormat format = VanillaJigsawExportFormat.DIRECTORY;
private VanillaJigsawExportSettings settings = VanillaJigsawExportSettings.defaults();
private boolean replaceExisting;
private Builder(VanillaJigsawExportSource source, Path output) {
this.source = Objects.requireNonNull(source);
this.output = Objects.requireNonNull(output);
resourcePath = source.structureKey();
}
public Builder namespace(String value) {
namespace = Objects.requireNonNull(value).trim();
return this;
}
public Builder resourcePath(String value) {
resourcePath = Objects.requireNonNull(value).trim();
return this;
}
public Builder description(String value) {
description = Objects.requireNonNull(value);
return this;
}
public Builder format(VanillaJigsawExportFormat value) {
format = Objects.requireNonNull(value);
return this;
}
public Builder settings(VanillaJigsawExportSettings value) {
settings = Objects.requireNonNull(value);
return this;
}
public Builder replaceExisting(boolean value) {
replaceExisting = value;
return this;
}
public VanillaJigsawExportRequest build() {
return new VanillaJigsawExportRequest(this);
}
}
}
@@ -0,0 +1,38 @@
package art.arcane.iris.core.structure.export;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
public record VanillaJigsawExportResult(
Status status,
Path output,
List<String> resources,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
public VanillaJigsawExportResult {
Objects.requireNonNull(status);
Objects.requireNonNull(output);
resources = List.copyOf(resources);
diagnostics = List.copyOf(diagnostics);
}
public boolean isSuccess() {
return status == Status.EXPORTED;
}
public boolean hasBlockingDiagnostics() {
for (VanillaJigsawExportDiagnostic diagnostic : diagnostics) {
if (diagnostic.isBlocking()) {
return true;
}
}
return false;
}
public enum Status {
EXPORTED,
REJECTED,
FAILED
}
}
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff. Show more