Let the structure model and the assembler speak the api

This commit is contained in:
piexel committed 2026-11-10 02:02:47 +01:00
1 parent 6ecfbbaa6e
commit ff23e2fb7b
122 files changed
+3030 -2014

No files matched your search

@@ -63,8 +63,14 @@ public final class IrisModuleHost {
"iris:spawn", "iris:prepare", "iris:anchor", "iris:validate", "iris:bore", "iris:blocks", "iris:stilt", "iris:vacuum",
"iris:snow", "iris:vanilla-features", "iris:carve", "iris:deposit", "iris:decorant", "iris:terrain", "iris:objects",
"iris:floating");
/** Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. */
public static final String HOST_TYPE_PACKAGE = "art.arcane.iris.engine.object";
/**
* Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. The
* structure model (engine.object.structure) is not among them: it speaks the api's vocabulary and its module describes it.
*/
public static final String[] HOST_TYPE_PACKAGES = Stream.of("annotations", "compatibility", "image", "material", "noise",
"placement", "prefab", "runtime", "terrain", "value", "world")
.map(subpackage -> "art.arcane.iris.engine.object." + subpackage)
.toArray(String[]::new);
private static final String[] JAR_COPY_FOLDER = {"cache", "module-jars"};
private static final String BUNDLED_JAR_RESOURCE = "/" + MissingBuiltInModules.JAR_NAME;
private static final String BUNDLED_JAR_TEMPORARY_PREFIX = "iris-built-in-modules-";
@@ -98,14 +104,14 @@ public final class IrisModuleHost {
/** Whether {@code type} is one of Iris's own classes that built-in settings may hold. */
public static boolean isHostType(Class<?> type) {
return type.getName().startsWith(HOST_TYPE_PACKAGE + ".");
return Stream.of(HOST_TYPE_PACKAGES).anyMatch(hostPackage -> type.getName().startsWith(hostPackage + "."));
}
private static ModuleHost build() {
return ModuleHost.of(builtInModules())
.exposing(EXPOSED_PACKAGES.toArray(String[]::new))
.reservingFields(ModuleTargets.reservedFields())
.describingHostTypesIn(HOST_TYPE_PACKAGE)
.describingHostTypesIn(HOST_TYPE_PACKAGES)
.reservingFolders(IrisData.ownFolderNames().toArray(String[]::new))
.bundlingJars(bundledJars())
.copyingJarsTo(jarCopyRoot())
@@ -28,9 +28,11 @@ import com.volmit.config.PackSettings;
import com.volmit.config.SettingsStack;
import com.volmit.resource.PackResources;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* The settings a whole pack declares, for validators: every dimension of the pack, then every region, then every
@@ -51,6 +53,12 @@ final class PackDeclaredSettings implements PackSettings {
return data.getPackResources();
}
/** The pack's folder is offered as a {@link File}, for checks that read the files of the pack as written. */
@Override
public <T> Optional<T> extension(Class<T> type) {
return HostExtensions.as(type, type == File.class ? data.getDataFolder() : null);
}
@Override
public <F extends IrisFeature> SettingsStack<F> declared(Class<F> featureType) {
List<Entry<F>> entries = new ArrayList<>();
@@ -18,10 +18,10 @@
package art.arcane.iris.core.modules;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.StructureAssembler;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.value.IrisPosition;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.PackResources;
/**
* Structure assembly for Iris's own tools, the commands and studio, which run outside any module's stage, service or hook and so
@@ -31,8 +31,8 @@ public final class StructureAssemblies {
private StructureAssemblies() {
}
/** The assembler of {@code structure}, compiled from the pack {@code data} serves, for a start at {@code origin}. */
public static StructureAssembler forData(IrisData data, IrisStructure structure, IrisPosition origin) {
return StructureAssembler.forData(data, structure, origin, IrisModuleHost.hostLog());
/** The assembler of {@code structure}, the structure {@code structureKey} of {@code pack}, for a start at {@code origin}. */
public static StructureAssembler forPack(PackResources pack, String structureKey, IrisStructure structure, BlockPosition origin) {
return StructureAssembler.forPack(pack, structureKey, structure, origin, IrisModuleHost.hostLog());
}
}
@@ -20,13 +20,12 @@ package art.arcane.iris.core.modules;
import art.arcane.iris.core.structure.StructureIndexService;
import art.arcane.iris.core.structure.tooling.PlatformStructuresAccess;
import art.arcane.iris.core.tooling.IrisToolPack;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.framework.structure.StructureAssemblyResult;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.Argument;
import com.volmit.tooling.Command;
@@ -79,7 +78,7 @@ final class StructureCommands {
ResourceId id = context.get(STRUCTURE);
IrisStructure structure = context.pack().resources().require(StructureResources.STRUCTURES, id);
StructureAssemblyResult assembly = StructureAssemblies
.forData(IrisToolPack.dataOf(context.pack()), structure, new IrisPosition(0, INFO_ORIGIN_Y, 0))
.forPack(context.pack().resources(), id.path(), structure, new BlockPosition(0, INFO_ORIGIN_Y, 0))
.assemble(new RNG(INFO_SAMPLE_SEED));
if (!assembly.hasOutput()) {
context.sender().error("Structure " + id + " assembled 0 pieces (check startPool '" + structure.getStartPool() + "')");
@@ -20,7 +20,9 @@ package art.arcane.iris.core.modules;
import art.arcane.iris.core.structure.tooling.JigsawCommands;
import art.arcane.iris.core.structure.tooling.JigsawStudioHost;
import art.arcane.iris.engine.framework.structure.JigsawStructureAssembly;
import art.arcane.iris.engine.framework.structure.StructureLocating;
import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.engine.framework.structure.StructureValidator;
import art.arcane.iris.engine.framework.structure.StructureVanillaStructures;
@@ -61,6 +63,7 @@ public final class StructureModelModule implements IrisModule {
public void setup(ModuleSetup setup) {
var registry = setup.registry();
registry.registerValidator(new StructureValidator());
registry.registerService(StructureAssembly.class, new JigsawStructureAssembly(setup.log()));
registry.registerService(StructureLocator.class, new StructureLocating());
registry.registerService(VanillaStructures.class, new StructureVanillaStructures());
setup.tooling().registerCommand(StructureCommands.root());
@@ -18,6 +18,7 @@
package art.arcane.iris.core.pack;
import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.iris.builtin.structure.IrisStructureRef;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.IrisRegistrant;
@@ -60,6 +61,13 @@ public final class ModuleResourceClosure {
private static final String JSON_EXTENSION = ".json";
private static final int PRETTY_INDENT = 4;
/**
* The structure model ships with Iris while the loot kind ships in the built-in modules jar, so the model cannot name
* the kind with {@code @ResourceRef} (a pack without the jar could not load it). Until both move into the jar the
* closure knows this one reference.
*/
private static final Field STRUCTURE_LOOT_FIELD = structureLootField();
private final IrisData data;
private final Map<Class<?>, ResourceKind<?>> kindsByType = new HashMap<>();
private final Map<ResourceKind<?>, Map<String, Object>> found = new LinkedHashMap<>();
@@ -164,6 +172,14 @@ public final class ModuleResourceClosure {
}
}
private static Field structureLootField() {
try {
return IrisStructure.class.getDeclaredField("loot");
} catch (NoSuchFieldException missing) {
throw new IllegalStateException("The structure model has no loot field", missing);
}
}
/** The class of the resources the field names by key, or null when it names none. */
private static Class<?> referencedType(Field field) {
ResourceRef reference = field.getAnnotation(ResourceRef.class);
@@ -173,6 +189,9 @@ public final class ModuleResourceClosure {
if (field.isAnnotationPresent(IrisStructureRef.class)) {
return IrisStructure.class;
}
if (field.equals(STRUCTURE_LOOT_FIELD)) {
return LootTable.class;
}
RegistryListResource registry = field.getAnnotation(RegistryListResource.class);
return registry == null ? null : registry.value();
}
@@ -1,6 +1,6 @@
package art.arcane.iris.core.runtime.jigsaw;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection;
public enum JigsawPlanarDirection {
NORTH(1),
@@ -18,12 +18,12 @@ public enum JigsawPlanarDirection {
return bit;
}
public IrisDirection irisDirection() {
public JigsawDirection direction() {
return switch (this) {
case NORTH -> IrisDirection.NORTH_NEGATIVE_Z;
case EAST -> IrisDirection.EAST_POSITIVE_X;
case SOUTH -> IrisDirection.SOUTH_POSITIVE_Z;
case WEST -> IrisDirection.WEST_NEGATIVE_X;
case NORTH -> JigsawDirection.NORTH_NEGATIVE_Z;
case EAST -> JigsawDirection.EAST_POSITIVE_X;
case SOUTH -> JigsawDirection.SOUTH_POSITIVE_Z;
case WEST -> JigsawDirection.WEST_NEGATIVE_X;
};
}
@@ -9,14 +9,13 @@ 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.value.IrisDirection;
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.IrisJigsawPool;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
import art.arcane.volmlib.util.math.IrisBlockVector;
@@ -91,14 +90,14 @@ public final class JigsawStudioGraphEditor {
.setObject(normalizedPiece)
.setRotatable(true);
if (topology != null) {
IrisPosition cellSize = new IrisPosition(
BlockPosition cellSize = new BlockPosition(
dimensions.width(), dimensions.height(), dimensions.depth());
for (JigsawPlanarDirection planarDirection : topology.directions()) {
IrisDirection direction = planarDirection.irisDirection();
JigsawDirection direction = planarDirection.direction();
piece.getConnectors().add(new IrisJigsawConnector()
.setPosition(IrisJigsawConnector.canonicalPlanarPosition(cellSize, direction))
.setDirection(direction)
.setTop(IrisDirection.UP_POSITIVE_Y)
.setTop(JigsawDirection.UP_POSITIVE_Y)
.setPool(normalizedPool)
.setName("iris:planar")
.setTargetName("iris:planar")
@@ -632,11 +631,11 @@ public final class JigsawStudioGraphEditor {
Path packRoot,
String structureKey,
String pieceKey,
IrisPosition position,
BlockPosition position,
String channel
) throws IOException {
String normalizedPiece = JigsawStudioProjectCreator.Options.requireResourceKey(pieceKey);
IrisPosition connectorPosition = Objects.requireNonNull(position, "Jigsaw connector position");
BlockPosition connectorPosition = Objects.requireNonNull(position, "Jigsaw connector position");
String normalizedChannel = normalizeChannel(channel);
OwnedGraph graph = loadOwnedGraph(packRoot, structureKey);
String pieceResource = "jigsaw-pieces/" + normalizedPiece + ".json";
@@ -669,8 +668,8 @@ public final class JigsawStudioGraphEditor {
}
if (!found) {
throw new IOException("Piece '" + normalizedPiece + "' has no connector at "
+ connectorPosition.getX() + "," + connectorPosition.getY() + ","
+ connectorPosition.getZ());
+ connectorPosition.x() + "," + connectorPosition.y() + ","
+ connectorPosition.z());
}
return write(graph, bundle.build());
}
@@ -1301,7 +1300,7 @@ public final class JigsawStudioGraphEditor {
connectorResize.targetCanonical(),
resizedSourceDimensions,
quarterTurns);
connectorResize.connector().setPosition(sourcePosition.toIrisPosition());
connectorResize.connector().setPosition(sourcePosition.toBlockPosition());
if (!connectorResize.sourceCanonical().equals(connectorResize.targetCanonical())) {
relocatedConnectors++;
}
@@ -1370,9 +1369,9 @@ public final class JigsawStudioGraphEditor {
List<ConnectorResize> planned = new ArrayList<>(connectors.size());
Set<LocalPosition> sourcePositions = new LinkedHashSet<>();
Set<LocalPosition> targetPositions = new LinkedHashSet<>();
IrisPosition sourceSize = dimensionsPosition(sourceDimensions);
IrisPosition canonicalSize = dimensionsPosition(canonicalDimensions);
IrisPosition targetSize = dimensionsPosition(targetDimensions);
BlockPosition sourceSize = dimensionsPosition(sourceDimensions);
BlockPosition canonicalSize = dimensionsPosition(canonicalDimensions);
BlockPosition targetSize = dimensionsPosition(targetDimensions);
for (int index = 0; index < connectors.size(); index++) {
IrisJigsawConnector connector = connectors.get(index);
if (connector == null || connector.getPosition() == null || connector.getDirection() == null
@@ -1396,7 +1395,7 @@ public final class JigsawStudioGraphEditor {
sourceDimensions.width(),
sourceDimensions.depth(),
quarterTurns);
IrisDirection canonicalDirection = rotateHorizontalDirection(
JigsawDirection canonicalDirection = rotateHorizontalDirection(
connector.getDirection(),
quarterTurns);
LocalPosition expectedSource = LocalPosition.from(IrisJigsawConnector.canonicalPlanarPosition(
@@ -1585,7 +1584,7 @@ public final class JigsawStudioGraphEditor {
};
}
private static IrisDirection rotateHorizontalDirection(IrisDirection direction, int quarterTurns) {
private static JigsawDirection rotateHorizontalDirection(JigsawDirection direction, int quarterTurns) {
JigsawPlanarDirection planarDirection = switch (direction) {
case NORTH_NEGATIVE_Z -> JigsawPlanarDirection.NORTH;
case EAST_POSITIVE_X -> JigsawPlanarDirection.EAST;
@@ -1594,11 +1593,11 @@ public final class JigsawStudioGraphEditor {
case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> throw new IllegalArgumentException(
"Planar connector direction must be horizontal");
};
return planarDirection.rotateClockwise(quarterTurns).irisDirection();
return planarDirection.rotateClockwise(quarterTurns).direction();
}
private static IrisPosition dimensionsPosition(JigsawStudioCellDimensions dimensions) {
return new IrisPosition(dimensions.width(), dimensions.height(), dimensions.depth());
private static BlockPosition dimensionsPosition(JigsawStudioCellDimensions dimensions) {
return new BlockPosition(dimensions.width(), dimensions.height(), dimensions.depth());
}
private static boolean inside(LocalPosition position, JigsawStudioCellDimensions dimensions) {
@@ -1831,10 +1830,6 @@ public final class JigsawStudioGraphEditor {
}
private record LocalPosition(int x, int y, int z) {
private static LocalPosition from(IrisPosition position) {
return new LocalPosition(position.getX(), position.getY(), position.getZ());
}
private static LocalPosition from(BlockPosition position) {
return new LocalPosition(position.x(), position.y(), position.z());
}
@@ -1843,10 +1838,6 @@ public final class JigsawStudioGraphEditor {
return new BlockPosition(x, y, z);
}
private IrisPosition toIrisPosition() {
return new IrisPosition(x, y, z);
}
private String describe() {
return x + "," + y + "," + z;
}
@@ -1,23 +1,23 @@
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.loader.IrisData;
import art.arcane.iris.core.structure.authoring.StructureKey;
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.object.structure.jigsaw.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.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
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.io.File;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
@@ -38,20 +38,24 @@ public final class JigsawStudioGraphMapper {
private JigsawStudioGraphMapper() {
}
public static JigsawStudioLayout map(IrisData data, IrisStructure structure) {
Objects.requireNonNull(data, "Jigsaw Studio graph mapping requires pack data");
/**
* 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);
IrisPosition configuredCell = structure.getCellSize();
BlockPosition configuredCell = structure.getCellSize();
JigsawStudioCellDimensions dimensions = configuredCell == null
? new JigsawStudioCellDimensions(15, 15, 15)
: new JigsawStudioCellDimensions(
Math.max(1, configuredCell.getX()),
Math.max(1, configuredCell.getY()),
Math.max(1, configuredCell.getZ()));
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(
@@ -77,11 +81,18 @@ public final class JigsawStudioGraphMapper {
}
public static JigsawStudioVariantCatalog catalog(
IrisData data,
ToolPack pack,
Path packRoot,
String structureKey,
IrisStructure structure,
JigsawStudioMode mode
) {
IrisData source = Objects.requireNonNull(data, "Jigsaw Studio catalog pack data");
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);
@@ -123,37 +134,34 @@ public final class JigsawStudioGraphMapper {
}
static JigsawStudioCellDimensions expandSpatialDimensions(
IrisData data,
Source data,
JigsawStudioVariantCatalog catalog,
JigsawStudioCellDimensions configured
) {
if (data.getObjectLoader() == null) {
return configured;
}
int width = configured.width();
int height = configured.height();
int depth = configured.depth();
for (JigsawStudioVariant variant : catalog.spatialVariants()) {
IrisObject object = data.getObjectLoader().load(variant.objectKey());
ObjectFrame object = data.objectFrame(variant.objectKey());
if (object == null) {
continue;
}
int objectWidth = object.getW();
int objectDepth = object.getD();
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.getH());
height = Math.max(height, object.height());
depth = Math.max(depth, objectDepth);
}
return new JigsawStudioCellDimensions(width, height, depth);
}
private static void traversePools(
IrisData data,
Source data,
JigsawStudioMode mode,
OwnedResources owned,
ArrayDeque<String> pools,
@@ -166,7 +174,7 @@ public final class JigsawStudioGraphMapper {
if (!visitedPools.add(poolKey)) {
continue;
}
IrisJigsawPool pool = StructureResources.pool(data.getPackResources(), poolKey);
IrisJigsawPool pool = StructureResources.pool(data.resources(), poolKey);
if (pool == null) {
continue;
}
@@ -180,7 +188,7 @@ public final class JigsawStudioGraphMapper {
continue;
}
String pieceKey = entry.getPiece();
IrisJigsawPiece piece = StructureResources.piece(data.getPackResources(), pieceKey);
IrisJigsawPiece piece = StructureResources.piece(data.resources(), pieceKey);
if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) {
continue;
}
@@ -202,7 +210,7 @@ public final class JigsawStudioGraphMapper {
}
private static void addOwnedVariant(
IrisData data,
Source data,
JigsawStudioMode mode,
OwnedResources owned,
String pieceKey,
@@ -211,21 +219,20 @@ public final class JigsawStudioGraphMapper {
if (variants.containsKey(pieceKey)) {
return;
}
IrisJigsawPiece piece = StructureResources.piece(data.getPackResources(), pieceKey);
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(IrisData data, IrisStructure structure) {
String structureKey = structure.getLoadKey();
File dataFolder = data.getDataFolder();
if (structureKey == null || structureKey.isBlank() || dataFolder == null) {
private static OwnedResources ownedResources(Source data, IrisStructure structure) {
String structureKey = data.structureKey();
if (structureKey == null || structureKey.isBlank()) {
return OwnedResources.empty();
}
try {
Path root = dataFolder.toPath().toAbsolutePath().normalize();
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)) {
@@ -255,7 +262,7 @@ public final class JigsawStudioGraphMapper {
}
}
private static int directionBit(IrisDirection direction) {
private static int directionBit(JigsawDirection direction) {
return switch (direction) {
case NORTH_NEGATIVE_Z -> JigsawPlanarDirection.NORTH.bit();
case EAST_POSITIVE_X -> JigsawPlanarDirection.EAST.bit();
@@ -310,7 +317,7 @@ public final class JigsawStudioGraphMapper {
memberships.add(membership);
}
private JigsawStudioVariant build(IrisData data) {
private JigsawStudioVariant build(Source data) {
Optional<JigsawStudioCellDimensions> dimensions = objectDimensions(data, piece, mode);
return new JigsawStudioVariant(
pieceKey,
@@ -329,21 +336,18 @@ public final class JigsawStudioGraphMapper {
}
private static Optional<JigsawStudioCellDimensions> objectDimensions(
IrisData data,
Source data,
IrisJigsawPiece piece,
JigsawStudioMode mode
) {
if (data.getObjectLoader() == null) {
return Optional.empty();
}
IrisObject object = data.getObjectLoader().load(piece.getObject());
ObjectFrame object = data.objectFrame(piece.getObject());
if (object == null) {
return Optional.empty();
}
JigsawStudioCellDimensions sourceDimensions = new JigsawStudioCellDimensions(
object.getW(),
object.getH(),
object.getD());
object.width(),
object.height(),
object.depth());
if (mode == JigsawStudioMode.SPATIAL_JIGSAW) {
return Optional.of(sourceDimensions);
}
@@ -359,6 +363,14 @@ public final class JigsawStudioGraphMapper {
}
}
/** 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,
@@ -11,7 +11,7 @@ import art.arcane.iris.core.structure.authoring.StructureWriteResult;
import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.object.structure.jigsaw.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;
@@ -21,8 +21,8 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import com.volmit.geometry.BlockPosition;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -36,13 +36,13 @@ import java.util.Objects;
public final class JigsawStudioProjectCreator {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private static final List<IrisDirection> SPATIAL_CONNECTOR_ORDER = List.of(
IrisDirection.NORTH_NEGATIVE_Z,
IrisDirection.SOUTH_POSITIVE_Z,
IrisDirection.EAST_POSITIVE_X,
IrisDirection.WEST_NEGATIVE_X,
IrisDirection.UP_POSITIVE_Y,
IrisDirection.DOWN_NEGATIVE_Y);
private 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() {
}
@@ -64,7 +64,7 @@ public final class JigsawStudioProjectCreator {
.setMode(toModelMode(options.mode()))
.setCompatibility(toModelCompatibility(options.compatibilityTarget()))
.setBranchFailurePolicy(toBranchFailurePolicy(options.compatibilityTarget()))
.setCellSize(new IrisPosition(
.setCellSize(new BlockPosition(
options.cellDimensions().width(),
options.cellDimensions().height(),
options.cellDimensions().depth()));
@@ -123,7 +123,7 @@ public final class JigsawStudioProjectCreator {
Options options
) throws IOException {
JigsawStudioCellDimensions dimensions = options.cellDimensions();
IrisPosition size = new IrisPosition(dimensions.width(), dimensions.height(), dimensions.depth());
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);
@@ -209,13 +209,13 @@ public final class JigsawStudioProjectCreator {
.setRotatable(true)
.setRules(new IrisJigsawPieceRules().setMaximumPlacements(16));
for (int index = 0; index < connectorCount; index++) {
IrisDirection direction = SPATIAL_CONNECTOR_ORDER.get(index);
JigsawDirection direction = SPATIAL_CONNECTOR_ORDER.get(index);
piece.getConnectors().add(new IrisJigsawConnector()
.setPosition(spatialConnectorPosition(dimensions, direction))
.setDirection(direction)
.setTop(direction.isVertical()
? IrisDirection.NORTH_NEGATIVE_Z
: IrisDirection.UP_POSITIVE_Y)
? JigsawDirection.NORTH_NEGATIVE_Z
: JigsawDirection.UP_POSITIVE_Y)
.setPool(poolKey)
.setName("iris:spatial")
.setTargetName("iris:spatial")
@@ -225,36 +225,36 @@ public final class JigsawStudioProjectCreator {
return piece;
}
private static IrisPosition spatialConnectorPosition(
private static BlockPosition spatialConnectorPosition(
JigsawStudioCellDimensions dimensions,
IrisDirection direction
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 IrisPosition(centerX, centerY, 0);
case SOUTH_POSITIVE_Z -> new IrisPosition(centerX, centerY, dimensions.depth() - 1);
case EAST_POSITIVE_X -> new IrisPosition(dimensions.width() - 1, centerY, centerZ);
case WEST_NEGATIVE_X -> new IrisPosition(0, centerY, centerZ);
case UP_POSITIVE_Y -> new IrisPosition(centerX, dimensions.height() - 1, centerZ);
case DOWN_NEGATIVE_Y -> new IrisPosition(centerX, 0, centerZ);
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,
IrisPosition dimensions,
BlockPosition dimensions,
JigsawPlanarArchetype archetype
) {
IrisJigsawPiece piece = new IrisJigsawPiece().setObject(objectKey).setRotatable(true);
for (JigsawPlanarDirection planarDirection : archetype.canonicalTopology().directions()) {
IrisDirection direction = planarDirection.irisDirection();
JigsawDirection direction = planarDirection.direction();
piece.getConnectors().add(new IrisJigsawConnector()
.setPosition(IrisJigsawConnector.canonicalPlanarPosition(dimensions, direction))
.setDirection(direction)
.setTop(IrisDirection.UP_POSITIVE_Y)
.setTop(JigsawDirection.UP_POSITIVE_Y)
.setPool(poolKey)
.setName("iris:planar")
.setTargetName("iris:planar")
@@ -12,9 +12,7 @@ import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCo
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.volmlib.util.math.IrisBlockVector;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
@@ -22,6 +20,7 @@ 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;
@@ -270,17 +269,24 @@ public final class JigsawStudioStructureEditor {
continue;
}
Path objectPath = resolveOwnedResource(root, relativePath);
IrisBlockVector size = IrisObject.sampleSize(objectPath.toFile());
if (size.getBlockX() > dimensions.width()
|| size.getBlockY() > dimensions.height()
|| size.getBlockZ() > dimensions.depth()) {
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.getBlockX() + "x" + size.getBlockY() + "x" + size.getBlockZ()
+ 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,
@@ -1,6 +1,6 @@
package art.arcane.iris.core.runtime.jigsaw;
import art.arcane.iris.engine.object.value.IrisPosition;
import com.volmit.geometry.BlockPosition;
import java.util.List;
import java.util.Objects;
@@ -61,8 +61,8 @@ public record JigsawStudioVariant(
.canonicalToSourceQuarterTurns(topology);
}
public IrisPosition sourceToCanonicalPosition(
IrisPosition sourcePosition,
public BlockPosition sourceToCanonicalPosition(
BlockPosition sourcePosition,
JigsawStudioCellDimensions sourceDimensions
) {
return rotatePosition(
@@ -71,8 +71,8 @@ public record JigsawStudioVariant(
sourceToCanonicalQuarterTurns());
}
public IrisPosition canonicalToSourcePosition(
IrisPosition canonicalPosition,
public BlockPosition canonicalToSourcePosition(
BlockPosition canonicalPosition,
JigsawStudioCellDimensions sourceDimensions
) {
JigsawStudioCellDimensions canonicalDimensions = canonicalDimensions(sourceDimensions);
@@ -98,34 +98,34 @@ public record JigsawStudioVariant(
return !memberships.isEmpty();
}
private static IrisPosition rotatePosition(
IrisPosition position,
private static BlockPosition rotatePosition(
BlockPosition position,
JigsawStudioCellDimensions dimensions,
int quarterTurns
) {
IrisPosition source = Objects.requireNonNull(position, "Jigsaw Studio variant position");
BlockPosition source = Objects.requireNonNull(position, "Jigsaw Studio variant position");
JigsawStudioCellDimensions bounds = Objects.requireNonNull(
dimensions,
"Jigsaw Studio variant position bounds");
if (source.getX() < 0 || source.getX() >= bounds.width()
|| source.getY() < 0 || source.getY() >= bounds.height()
|| source.getZ() < 0 || source.getZ() >= bounds.depth()) {
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 IrisPosition(source.getX(), source.getY(), source.getZ());
case 1 -> new IrisPosition(
bounds.depth() - 1 - source.getZ(),
source.getY(),
source.getX());
case 2 -> new IrisPosition(
bounds.width() - 1 - source.getX(),
source.getY(),
bounds.depth() - 1 - source.getZ());
case 3 -> new IrisPosition(
source.getZ(),
source.getY(),
bounds.width() - 1 - source.getX());
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");
};
}
@@ -1,6 +1,6 @@
package art.arcane.iris.core.service;
import art.arcane.iris.engine.object.prefab.ObjectTurn;
import art.arcane.iris.engine.framework.structure.assembly.PieceTurn;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
@@ -39,8 +39,8 @@ public final class JigsawStudioBlocks {
}
/** {@code state} turned like {@code rotation}; null when the registry cannot turn the block. */
public static BlockState rotated(BlockRegistry registry, BlockState state, ObjectTurn rotation) {
if (!rotation.canRotate()) {
public static BlockState rotated(BlockRegistry registry, BlockState state, PieceTurn rotation) {
if (rotation.quarterTurns() == 0) {
return state;
}
return registry.tryRotate(state, rotation.blockTurn()).orElse(null);
@@ -1,10 +1,10 @@
package art.arcane.iris.core.service;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMarkerKeyCodec;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
import com.volmit.geometry.BlockPosition;
import java.util.Locale;
import java.util.Map;
@@ -31,7 +31,7 @@ final class JigsawStudioMarkerParser {
throw new IllegalArgumentException("Unsupported jigsaw joint '" + jointName + "'", exception);
}
return new IrisJigsawConnector()
.setPosition(new IrisPosition(x, y, z))
.setPosition(new BlockPosition(x, y, z))
.setDirection(directions.front())
.setTop(directions.top())
.setPool(JigsawStudioMarkerKeyCodec.decodePool(requiredString(properties, "pool")))
@@ -48,18 +48,18 @@ final class JigsawStudioMarkerParser {
static Directions directions(String orientation) {
String name = Objects.requireNonNull(orientation, "Jigsaw orientation").toLowerCase(Locale.ROOT);
return switch (name) {
case "down_east" -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.EAST_POSITIVE_X);
case "down_north" -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.NORTH_NEGATIVE_Z);
case "down_south" -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.SOUTH_POSITIVE_Z);
case "down_west" -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.WEST_NEGATIVE_X);
case "up_east" -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.EAST_POSITIVE_X);
case "up_north" -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.NORTH_NEGATIVE_Z);
case "up_south" -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.SOUTH_POSITIVE_Z);
case "up_west" -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.WEST_NEGATIVE_X);
case "west_up" -> new Directions(IrisDirection.WEST_NEGATIVE_X, IrisDirection.UP_POSITIVE_Y);
case "east_up" -> new Directions(IrisDirection.EAST_POSITIVE_X, IrisDirection.UP_POSITIVE_Y);
case "north_up" -> new Directions(IrisDirection.NORTH_NEGATIVE_Z, IrisDirection.UP_POSITIVE_Y);
case "south_up" -> new Directions(IrisDirection.SOUTH_POSITIVE_Z, IrisDirection.UP_POSITIVE_Y);
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 + "'");
};
}
@@ -98,7 +98,7 @@ final class JigsawStudioMarkerParser {
return (int) longValue;
}
record Directions(IrisDirection front, IrisDirection top) {
record Directions(JigsawDirection front, JigsawDirection top) {
Directions {
Objects.requireNonNull(front, "Jigsaw front direction");
Objects.requireNonNull(top, "Jigsaw top direction");
@@ -1,13 +1,14 @@
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 art.arcane.iris.engine.object.prefab.ObjectTurn;
import art.arcane.volmlib.util.math.IrisBlockVector;
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;
@@ -39,7 +40,8 @@ public final class JigsawStudioPreviewRenderer {
this.log = Objects.requireNonNull(log, "Jigsaw Studio preview log");
}
public static PreviewPlan plan(List<PlacedStructurePiece> pieces, BlockRegistry registry) throws IOException {
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"));
@@ -64,7 +66,7 @@ public final class JigsawStudioPreviewRenderer {
maximumX = Math.max(maximumX, piece.getMaxX());
maximumY = Math.max(maximumY, piece.getMaxY());
maximumZ = Math.max(maximumZ, piece.getMaxZ());
appendObject(blocks, piece, registry);
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 "
@@ -188,19 +190,17 @@ public final class JigsawStudioPreviewRenderer {
private static void appendObject(
Map<BlockPosition, String> blocks,
PlacedStructurePiece piece,
BlockRegistry registry
PackResources pack
) throws IOException {
ObjectTurn rotation = piece.getRotation();
for (ObjectBlock block : piece.getObject().geometry().blocks()) {
IrisBlockVector rotated = rotation.rotate(new IrisBlockVector(
block.position().x(), block.position().y(), block.position().z()));
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.getBlockX(),
piece.getY() + rotated.getBlockY(),
piece.getZ() + rotated.getBlockZ()),
JigsawStudioBlocks.rotated(registry, block.state(), rotation),
new BlockPosition(piece.getX() + rotated.x(), piece.getY() + rotated.y(), piece.getZ() + rotated.z()),
JigsawStudioBlocks.rotated(pack.blocks(), block.state(), rotation),
"object block");
}
}
@@ -210,7 +210,7 @@ public final class JigsawStudioPreviewRenderer {
PlacedStructurePiece piece,
BlockRegistry registry
) throws IOException {
ObjectTurn rotation = piece.getRotation();
PieceTurn rotation = piece.getRotation();
if (piece.getPiece().getConnectors() == null) {
return;
}
@@ -218,18 +218,14 @@ public final class JigsawStudioPreviewRenderer {
if (connector == null || connector.getPosition() == null) {
throw new IOException("Jigsaw Studio preview contains an incomplete connector");
}
IrisBlockVector signed = new IrisBlockVector(
connector.getPosition().getX() - piece.getObject().center().x(),
connector.getPosition().getY() - piece.getObject().center().y(),
connector.getPosition().getZ() - piece.getObject().center().z());
IrisBlockVector rotated = rotation.rotate(signed);
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.getBlockX(),
piece.getY() + rotated.getBlockY(),
piece.getZ() + rotated.getBlockZ()),
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");
}
@@ -1,12 +1,12 @@
package art.arcane.iris.core.service;
import art.arcane.iris.core.loader.IrisData;
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;
@@ -31,7 +31,7 @@ public final class JigsawStudioRegistry {
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source
ToolPack source
) {
JigsawStudioLayout layout = JigsawStudioLayout.create(
mode,
@@ -55,7 +55,7 @@ public final class JigsawStudioRegistry {
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
ToolPack source,
JigsawStudioLayout initialLayout
) {
return activate(
@@ -76,7 +76,7 @@ public final class JigsawStudioRegistry {
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
ToolPack source,
JigsawStudioLayout initialLayout,
UUID ownerId
) {
@@ -109,7 +109,7 @@ public final class JigsawStudioRegistry {
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
ToolPack source,
JigsawStudioLayout initialLayout,
UUID ownerId,
UUID preservedRequestId
@@ -299,7 +299,7 @@ public final class JigsawStudioRegistry {
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
ToolPack source,
JigsawStudioLayout initialLayout,
UUID ownerId
) {
@@ -311,6 +311,7 @@ public final class JigsawStudioRegistry {
compatibilityTarget,
cellDimensions,
source,
JigsawStudioRequest.rootOf(source),
ownerId);
JigsawStudioLayout layout = Objects.requireNonNull(initialLayout, "Initial Jigsaw Studio layout");
if (layout.mode() != mode) {
@@ -1,14 +1,22 @@
package art.arcane.iris.core.service;
import art.arcane.iris.core.loader.IrisData;
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. */
/**
* 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,
@@ -16,9 +24,33 @@ public record JigsawStudioRequest(
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
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");
@@ -29,7 +61,8 @@ public record JigsawStudioRequest(
"Jigsaw Studio compatibility target"
);
cellDimensions = Objects.requireNonNull(cellDimensions, "Jigsaw Studio cell dimensions");
source = Objects.requireNonNull(source, "Jigsaw Studio source data");
source = Objects.requireNonNull(source, "Jigsaw Studio source pack");
packRoot = Objects.requireNonNull(packRoot, "Jigsaw Studio pack folder");
}
private static String requireKey(String value, String name) {
@@ -1,7 +1,6 @@
package art.arcane.iris.core.service;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype;
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarDirection;
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology;
@@ -36,12 +35,11 @@ import art.arcane.iris.engine.framework.structure.StructureGraphCompiler;
import art.arcane.iris.engine.framework.structure.StructureGraphDiagnostic;
import art.arcane.iris.engine.framework.structure.StructureGraphResolver;
import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection;
import art.arcane.iris.engine.framework.structure.assembly.PieceTurn;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet;
import art.arcane.iris.engine.object.prefab.ObjectTurn;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
import art.arcane.iris.engine.platform.studio.generators.JigsawStudioGenerator;
@@ -138,9 +136,9 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
"help", "list", "me", "msg", "ping", "pl", "plugins", "r", "reply", "rules",
"say", "tell", "ver", "version", "w", "whisper");
private static final Comparator<IrisJigsawConnector> NEW_CONNECTOR_SOURCE_POSITION_ORDER = Comparator
.comparingInt((IrisJigsawConnector connector) -> connector.getPosition().getX())
.thenComparingInt(connector -> connector.getPosition().getY())
.thenComparingInt(connector -> connector.getPosition().getZ());
.comparingInt((IrisJigsawConnector connector) -> connector.getPosition().x())
.thenComparingInt(connector -> connector.getPosition().y())
.thenComparingInt(connector -> connector.getPosition().z());
private final ModuleLog log;
private final JigsawStudioRegistry registry = new JigsawStudioRegistry();
private final JigsawStudioScheduler scheduler;
@@ -999,7 +997,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
throw new IOException("Jigsaw Studio undo failed: "
+ writeFailure(result.writeResult()));
}
request.source().invalidateStructureResources();
request.reloadSource();
JigsawStudioLayout restoredLayout = loadMappedLayout(studio);
VariantReloadRequest reload = activeReloads.get(result.pieceKey());
Optional<VariantReloadRequest> activeReload = reload == null
@@ -1380,7 +1378,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
archetype,
dimensions);
}
request.source().invalidateStructureResources();
request.reloadSource();
String resizeSummary = capacityResult == null
? ""
: " Verified " + capacityResult.checkedVariants() + " existing variant"
@@ -2379,7 +2377,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
return false;
}
BlockPosition playerAt = player.position();
IrisPosition origin = new IrisPosition(playerAt.x(), playerAt.y(), playerAt.z());
BlockPosition origin = new BlockPosition(playerAt.x(), playerAt.y(), playerAt.z());
JigsawStudioRequest request = studio.generator().getRequest();
ToolPack pack = studio.generator().getPack();
scheduler.async(() -> {
@@ -2389,8 +2387,8 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
if (structure == null) {
throw new IOException("The active structure resource no longer exists");
}
StructureAssembler assembler = StructureAssembler.forData(
request.source(), structure, origin, pack.log());
StructureAssembler assembler = StructureAssembler.forPack(
request.source().resources(), request.structureKey(), structure, origin, pack.log());
StructureAssemblyResult assembly = assembler.assemble(new RNG(seed));
if (!assembly.hasOutput()) {
message(player, "The active graph assembled zero preview pieces.");
@@ -2515,8 +2513,9 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
throw new IOException("The active structure resource no longer exists");
}
StructureGraphCompilation compilation = StructureGraphCompiler.compile(
request.structureKey(),
structure,
StructureGraphResolver.forData(request.source()));
StructureGraphResolver.forPack(request.source().resources()));
StructureGraphDiagnostic firstError = firstDiagnostic(
compilation,
StructureGraphDiagnostic.Severity.ERROR);
@@ -2526,7 +2525,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
generation,
firstError.code() + ": " + firstError.message());
} else {
IrisPosition origin = previewOrigin(studio.generator().getLayout(), structure);
BlockPosition origin = previewOrigin(studio.generator().getLayout(), structure);
StructureAssembler assembler = StructureAssembler.forCompilation(compilation, origin);
StructureAssemblyResult assembly = assembler.assemble(new RNG(PREVIEW_SEED));
computation = evaluationForAssembly(
@@ -2535,7 +2534,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
compilation,
assembly,
studio.generator().getLayout().mode(),
studio.generator().getPack().resources().blocks());
studio.generator().getPack().resources());
}
} catch (Throwable exception) {
reportError(exception);
@@ -2550,7 +2549,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
StructureGraphCompilation compilation,
StructureAssemblyResult assembly,
JigsawStudioMode mode,
BlockRegistry blocks
PackResources pack
) throws IOException {
if (assembly.status().isFailure()) {
return invalidEvaluation(
@@ -2574,7 +2573,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
JigsawStudioPreviewRenderer.PreviewPlan.empty());
}
List<PlacedStructurePiece> aligned = alignPreviewPieces(assembly.pieces(), mode);
JigsawStudioPreviewRenderer.PreviewPlan plan = JigsawStudioPreviewRenderer.plan(aligned, blocks);
JigsawStudioPreviewRenderer.PreviewPlan plan = JigsawStudioPreviewRenderer.plan(aligned, pack);
StructureGraphDiagnostic firstWarning = firstDiagnostic(
compilation,
StructureGraphDiagnostic.Severity.WARNING);
@@ -2667,9 +2666,9 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
return null;
}
private static IrisPosition previewOrigin(JigsawStudioLayout layout, IrisStructure structure) {
private static BlockPosition previewOrigin(JigsawStudioLayout layout, IrisStructure structure) {
int radius = Math.max(1, structure.getMaxSizeChunks()) * 16;
return new IrisPosition(
return new BlockPosition(
-radius - 32,
0,
Math.max(16, layout.extentZ() / 2));
@@ -2691,6 +2690,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
for (PlacedStructurePiece piece : pieces) {
aligned.add(new PlacedStructurePiece(
piece.getPiece(),
piece.getObjectKey(),
piece.getObject(),
piece.getX(),
piece.getY() + shiftY,
@@ -3709,13 +3709,12 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
private static JigsawStudioLayout loadMappedLayout(ActiveStudio studio) throws IOException {
JigsawStudioRequest request = studio.generator().getRequest();
IrisData source = request.source();
source.invalidateStructureResources();
IrisStructure structure = StructureResources.structure(source.getPackResources(), request.structureKey());
request.reloadSource();
IrisStructure structure = StructureResources.structure(request.source().resources(), request.structureKey());
if (structure == null) {
throw new IOException("The structure could not be reloaded after the graph transaction");
}
return JigsawStudioGraphMapper.map(source, structure);
return JigsawStudioGraphMapper.map(request.source(), request.packRoot(), request.structureKey(), structure);
}
public boolean showAssemblyPreview(ToolPlayer player, List<PlacedStructurePiece> pieces) {
@@ -5774,7 +5773,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
int sourceDepth = (quarterTurns & 1) == 0
? displayDimensions.depth()
: displayDimensions.width();
ObjectTurn rotation = ObjectTurn.of(0, -90.0D * quarterTurns, 0);
PieceTurn rotation = PieceTurn.aroundY(-90 * quarterTurns);
Map<LocalPosition, IrisJigsawConnector> displayed = new HashMap<>(source.getConnectors().size());
for (IrisJigsawConnector sourceConnector : source.getConnectors()) {
LocalPosition sourcePosition = connectorPosition(sourceConnector, "source piece");
@@ -5786,9 +5785,9 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
sourceDepth,
quarterTurns);
IrisJigsawConnector connector = CapturedConnector.from(sourceConnector).toConnector()
.setPosition(new IrisPosition(position.x(), position.y(), position.z()))
.setDirection(rotation.rotate(sourceConnector.getDirection()))
.setTop(rotation.rotate(sourceConnector.getTop()));
.setPosition(new BlockPosition(position.x(), position.y(), position.z()))
.setDirection(sourceConnector.getDirection().turnedBy(rotation.quarterTurns()))
.setTop(sourceConnector.getTop().turnedBy(rotation.quarterTurns()));
if (displayed.put(position, connector) != null) {
throw new IOException("Jigsaw Studio source piece has duplicate displayed connector position "
+ connectorLocation(position));
@@ -5903,7 +5902,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
: captureBounds.dimensions().width();
int sourceHeight = captureBounds.dimensions().height();
List<ObjectBlock> objectBlocks = new ArrayList<>();
ObjectTurn inverseRotation = ObjectTurn.of(0, 90.0D * quarterTurns, 0);
PieceTurn inverseRotation = PieceTurn.aroundY(90 * quarterTurns);
List<IrisJigsawConnector> connectors = new ArrayList<>();
Set<LocalPosition> capturedBlocks = new HashSet<>();
Set<LocalPosition> capturedConnectors = new HashSet<>();
@@ -5959,9 +5958,9 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
}
IrisJigsawConnector connector = capturedConnector.toConnector();
if (quarterTurns != 0) {
connector.setPosition(new IrisPosition(position.x(), position.y(), position.z()));
connector.setDirection(inverseRotation.rotate(connector.getDirection()));
connector.setTop(inverseRotation.rotate(connector.getTop()));
connector.setPosition(new BlockPosition(position.x(), position.y(), position.z()));
connector.setDirection(connector.getDirection().turnedBy(inverseRotation.quarterTurns()));
connector.setTop(connector.getTop().turnedBy(inverseRotation.quarterTurns()));
BlockState finalState = registry.find(connector.getFinalState()).orElse(null);
if (finalState == null) {
throw new IOException("Captured connector final state cannot be parsed at "
@@ -6051,8 +6050,8 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
if (connector == null || connector.getPosition() == null) {
throw new IOException("Jigsaw Studio " + owner + " contains a connector without a position");
}
IrisPosition position = connector.getPosition();
return new LocalPosition(position.getX(), position.getY(), position.getZ());
BlockPosition position = connector.getPosition();
return new LocalPosition(position.x(), position.y(), position.z());
}
private static String connectorLocation(LocalPosition position) {
@@ -6478,24 +6477,24 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
? displayDimensions.depth()
: displayDimensions.width();
LocalPosition position = inversePosition(
captured.getPosition().getX(),
captured.getPosition().getY(),
captured.getPosition().getZ(),
captured.getPosition().x(),
captured.getPosition().y(),
captured.getPosition().z(),
sourceWidth,
sourceDepth,
quarterTurns);
ObjectTurn inverseRotation = ObjectTurn.of(0, 90.0D * quarterTurns, 0);
PieceTurn inverseRotation = PieceTurn.aroundY(90 * quarterTurns);
IrisJigsawConnector sourceOriented = CapturedConnector.from(captured).toConnector()
.setPosition(new IrisPosition(position.x(), position.y(), position.z()))
.setDirection(inverseRotation.rotate(captured.getDirection()))
.setTop(inverseRotation.rotate(captured.getTop()));
.setPosition(new BlockPosition(position.x(), position.y(), position.z()))
.setDirection(captured.getDirection().turnedBy(inverseRotation.quarterTurns()))
.setTop(captured.getTop().turnedBy(inverseRotation.quarterTurns()));
restoreCapturedMetadata(sourceOriented, sourcePiece);
captured.setName(sourceOriented.getName());
captured.setTargetName(sourceOriented.getTargetName());
captured.setChannel(sourceOriented.getChannel());
}
private static IrisJigsawConnector connectorAt(IrisJigsawPiece piece, IrisPosition position) {
private static IrisJigsawConnector connectorAt(IrisJigsawPiece piece, BlockPosition position) {
if (piece == null || piece.getConnectors() == null || position == null) {
return null;
}
@@ -7087,7 +7086,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
}
for (JigsawStudioGenerator.RenderedConnector renderedConnector : rendered.connectors()) {
IrisJigsawConnector connector = renderedConnector.connector();
IrisDirection direction = connector.getDirection();
JigsawDirection direction = connector.getDirection();
drawConnectorLine(
playerLocation,
bay.bounds().originX() + renderedConnector.x() + 0.5D,
@@ -7107,7 +7106,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
double startX,
double startY,
double startZ,
IrisDirection direction,
JigsawDirection direction,
int color,
ParticleBudget budget
) {
@@ -8182,8 +8181,8 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
int x,
int y,
int z,
IrisDirection direction,
IrisDirection top,
JigsawDirection direction,
JigsawDirection top,
String pool,
String name,
String targetName,
@@ -8206,11 +8205,11 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
static CapturedConnector from(IrisJigsawConnector connector) {
IrisJigsawConnector source = Objects.requireNonNull(connector, "Jigsaw Studio captured connector");
IrisPosition position = source.getPosition();
BlockPosition position = source.getPosition();
return new CapturedConnector(
position.getX(),
position.getY(),
position.getZ(),
position.x(),
position.y(),
position.z(),
source.getDirection(),
source.getTop(),
source.getPool(),
@@ -8225,7 +8224,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act
IrisJigsawConnector toConnector() {
return new IrisJigsawConnector()
.setPosition(new IrisPosition(x, y, z))
.setPosition(new BlockPosition(x, y, z))
.setDirection(direction)
.setTop(top)
.setPool(pool)
@@ -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);
}
}
@@ -13,8 +13,6 @@ 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.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.volmlib.util.math.IrisBlockVector;
import com.volmit.block.BlockState;
@@ -66,10 +64,11 @@ final class VanillaJigsawExportCompiler {
return rejected(diagnostics);
}
validateStructure(structure, request.settings(), diagnostics);
validateStructure(request.source().structureKey(), structure, request.settings(), diagnostics);
StructureGraphCompilation graphCompilation;
try {
graphCompilation = StructureGraphCompiler.compile(structure, request.source().resolver());
graphCompilation = StructureGraphCompiler.compile(
request.source().structureKey(), structure, request.source().resolver());
} catch (RuntimeException exception) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.GRAPH_VALIDATION,
@@ -79,7 +78,7 @@ final class VanillaJigsawExportCompiler {
}
addGraphDiagnostics(graphCompilation, diagnostics);
CompiledStructureGraph graph = graphCompilation.getGraph();
validateGraph(graph, diagnostics);
validateGraph(graph, request.source(), diagnostics);
if (hasErrors(diagnostics)) {
return rejected(diagnostics);
}
@@ -167,6 +166,7 @@ final class VanillaJigsawExportCompiler {
}
private void validateStructure(
String structureKey,
IrisStructure structure,
VanillaJigsawExportSettings settings,
List<VanillaJigsawExportDiagnostic> diagnostics
@@ -174,50 +174,50 @@ final class VanillaJigsawExportCompiler {
if (structure.resolvedCompatibility() != IrisJigsawCompatibility.VANILLA_PORTABLE) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_COMPATIBILITY,
structureKey(structure),
structureKey,
"Strict export requires compatibility VANILLA_PORTABLE.");
}
if (!structure.stampsPiecesWhereAssembled()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_PLACE_MODE,
structureKey(structure),
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),
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),
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(structure),
structureKey,
"Coherent Iris theme selection has no lossless vanilla jigsaw representation.");
}
if (structure.isRequireCaps()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_REQUIRED_CAPS,
structureKey(structure),
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(structure),
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(structure),
structureKey,
"Iris maxSizeChunks maps to " + horizontalDistance
+ " blocks, outside Minecraft 26.2's 1..128 horizontal limit.");
}
@@ -226,7 +226,7 @@ final class VanillaJigsawExportCompiler {
if (horizontalDistance + terrainPadding > MAX_HORIZONTAL_DISTANCE) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_MAX_DISTANCE,
structureKey(structure),
structureKey,
"Horizontal distance plus vanilla terrain-adaptation padding must not exceed 128 blocks.");
}
}
@@ -250,6 +250,7 @@ final class VanillaJigsawExportCompiler {
private void validateGraph(
CompiledStructureGraph graph,
VanillaJigsawExportSource source,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell> workcells =
@@ -275,7 +276,7 @@ final class VanillaJigsawExportCompiler {
pieceKey,
"Iris piece keys must be valid lowercase resource paths for vanilla export.");
}
validatePiece(graph, pieceKey, pieceEntry.getValue(), diagnostics);
validatePiece(graph, source, pieceKey, pieceEntry.getValue(), diagnostics);
}
}
@@ -334,6 +335,7 @@ final class VanillaJigsawExportCompiler {
private void validatePiece(
CompiledStructureGraph graph,
VanillaJigsawExportSource source,
String pieceKey,
IrisJigsawPiece piece,
List<VanillaJigsawExportDiagnostic> diagnostics
@@ -367,7 +369,7 @@ final class VanillaJigsawExportCompiler {
pieceKey,
"Vanilla template pools cannot serialize Iris collidable=false assembly metadata.");
}
IrisObject object = graph.getObjects().get(trim(piece.getObject()));
ObjectContents object = source.contents(trim(piece.getObject()));
if (object == null) {
return;
}
@@ -377,10 +379,10 @@ final class VanillaJigsawExportCompiler {
private void validateObject(
String pieceKey,
IrisObject object,
ObjectContents object,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
IrisObject.ApiContents contents = object.apiContents();
ObjectContents contents = object;
if (!contents.blockEntities().isEmpty()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_TILE_DATA,
@@ -391,13 +393,13 @@ final class VanillaJigsawExportCompiler {
BlockState state = entry.getValue();
BlockPosition position = entry.getKey();
String resource = pieceKey + "@" + new IrisBlockVector(
position.x() - object.getCenter().getX(),
position.y() - object.getCenter().getY(),
position.z() - object.getCenter().getZ());
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.getW() || y < 0 || y >= object.getH() || z < 0 || z >= object.getD()) {
if (x < 0 || x >= object.width() || y < 0 || y >= object.height() || z < 0 || z >= object.depth()) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.INVALID_BLOCK_STATE,
resource,
@@ -440,14 +442,14 @@ final class VanillaJigsawExportCompiler {
CompiledStructureGraph graph,
String pieceKey,
IrisJigsawPiece piece,
IrisObject object,
ObjectContents object,
List<VanillaJigsawExportDiagnostic> diagnostics
) {
if (piece.getConnectors() == null) {
return;
}
Set<String> positions = new LinkedHashSet<>();
Map<BlockPosition, BlockState> storedBlocks = object.apiContents().blocks();
Map<BlockPosition, BlockState> storedBlocks = object.blocks();
for (int index = 0; index < piece.getConnectors().size(); index++) {
IrisJigsawConnector connector = piece.getConnectors().get(index);
if (connector == null) {
@@ -477,11 +479,11 @@ final class VanillaJigsawExportCompiler {
resource,
exception.getMessage() == null ? "Connector orientation is incomplete." : exception.getMessage());
}
IrisPosition position = connector.getPosition();
BlockPosition position = connector.getPosition();
if (position == null || !inside(position, object)) {
continue;
}
String positionKey = position.getX() + "," + position.getY() + "," + position.getZ();
String positionKey = position.x() + "," + position.y() + "," + position.z();
if (!positions.add(positionKey)) {
addError(diagnostics,
VanillaJigsawExportDiagnostic.Code.DUPLICATE_CONNECTOR_POSITION,
@@ -523,8 +525,8 @@ final class VanillaJigsawExportCompiler {
exception.getMessage());
return;
}
IrisPosition position = connector.getPosition();
BlockState objectState = storedBlocks.get(new BlockPosition(position.getX(), position.getY(), position.getZ()));
BlockPosition position = connector.getPosition();
BlockState objectState = storedBlocks.get(position);
String expectedSource = objectState == null ? "minecraft:structure_void" : objectState.key();
try {
VanillaBlockState expected = VanillaBlockState.parse(expectedSource);
@@ -567,7 +569,7 @@ final class VanillaJigsawExportCompiler {
if (!pieceEnabled(workcells, pieceEntry.getValue())) {
continue;
}
IrisObject object = graph.getObjects().get(trim(pieceEntry.getValue().getObject()));
ObjectContents object = request.source().contents(trim(pieceEntry.getValue().getObject()));
byte[] template = encoder.encode(
object,
pieceEntry.getValue(),
@@ -757,10 +759,10 @@ final class VanillaJigsawExportCompiler {
return request.namespace() + ":" + request.resourcePath() + "/piece/" + pieceKey;
}
private boolean inside(IrisPosition position, IrisObject object) {
return position.getX() >= 0 && position.getX() < object.getW()
&& position.getY() >= 0 && position.getY() < object.getH()
&& position.getZ() >= 0 && position.getZ() < object.getD();
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) {
@@ -789,11 +791,6 @@ final class VanillaJigsawExportCompiler {
message));
}
private String structureKey(IrisStructure structure) {
String key = structure.getLoadKey();
return key == null || key.isBlank() ? "<unloaded>" : key;
}
private String trim(String value) {
return value == null ? "" : value.trim();
}
@@ -1,48 +1,57 @@
package art.arcane.iris.core.structure.export;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.structure.StructureGraphResolver;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.engine.object.structure.IrisStructure;
import com.volmit.resource.PackResources;
import java.util.Objects;
import java.util.function.Function;
public final class VanillaJigsawExportSource {
private final String structureKey;
private final IrisData data;
private final PackResources pack;
private final IrisStructure structure;
private final StructureGraphResolver resolver;
private final Function<String, ObjectContents> objects;
private VanillaJigsawExportSource(
String structureKey,
IrisData data,
PackResources pack,
IrisStructure structure,
StructureGraphResolver resolver
StructureGraphResolver resolver,
Function<String, ObjectContents> objects
) {
this.structureKey = requireKey(structureKey);
this.data = data;
this.pack = pack;
this.structure = structure;
this.resolver = resolver;
this.objects = objects;
}
public static VanillaJigsawExportSource forData(IrisData data, String structureKey) {
public static VanillaJigsawExportSource forPack(PackResources pack, String structureKey) {
Objects.requireNonNull(pack);
return new VanillaJigsawExportSource(
structureKey,
Objects.requireNonNull(data),
pack,
null,
StructureGraphResolver.forData(data));
StructureGraphResolver.forPack(pack),
key -> pack.objects().object(pack.idOf(key)).map(object -> ObjectContents.of(object, pack.blocks())).orElse(null));
}
/** A source of {@code structure} whose pieces' objects {@code objects} reads, for a structure that is not in a pack. */
public static VanillaJigsawExportSource forStructure(
String structureKey,
IrisStructure structure,
StructureGraphResolver resolver
StructureGraphResolver resolver,
Function<String, ObjectContents> objects
) {
return new VanillaJigsawExportSource(
structureKey,
null,
Objects.requireNonNull(structure),
Objects.requireNonNull(resolver));
Objects.requireNonNull(resolver),
Objects.requireNonNull(objects));
}
public String structureKey() {
@@ -53,13 +62,18 @@ public final class VanillaJigsawExportSource {
if (structure != null) {
return structure;
}
return StructureResources.structure(data.getPackResources(), structureKey);
return StructureResources.structure(pack, structureKey);
}
public StructureGraphResolver resolver() {
return resolver;
}
/** What the object the pack key {@code objectKey} names holds; null when there is none. */
public ObjectContents contents(String objectKey) {
return objects.apply(objectKey);
}
private static String requireKey(String value) {
String key = Objects.requireNonNull(value).trim();
if (key.isEmpty()) {
@@ -1,10 +1,8 @@
package art.arcane.iris.core.structure.export;
import art.arcane.iris.engine.object.value.IrisDirection;
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.IrisJigsawPiece;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.volmlib.util.nbt.io.NBTUtil;
import art.arcane.volmlib.util.nbt.io.NamedTag;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
@@ -29,7 +27,7 @@ final class VanillaStructureTemplateEncoder {
.thenComparingInt(entry -> entry.position().z());
byte[] encode(
IrisObject object,
ObjectContents object,
IrisJigsawPiece piece,
Function<String, String> poolIdentifier
) throws IOException {
@@ -49,7 +47,7 @@ final class VanillaStructureTemplateEncoder {
}
CompoundTag root = new CompoundTag();
root.put("size", intList(object.getW(), object.getH(), object.getD()));
root.put("size", intList(object.width(), object.height(), object.depth()));
root.put("palette", palette(paletteStates));
root.put("blocks", blocks(orderedBlocks, paletteIndexes));
root.put("entities", new ListTag<>(CompoundTag.class));
@@ -60,9 +58,9 @@ final class VanillaStructureTemplateEncoder {
return output.toByteArray();
}
private Map<BlockPosition, BlockEntry> objectBlocks(IrisObject object) {
private Map<BlockPosition, BlockEntry> objectBlocks(ObjectContents object) {
Map<BlockPosition, BlockEntry> blocks = new LinkedHashMap<>();
for (var entry : object.apiContents().blocks().entrySet()) {
for (var entry : object.blocks().entrySet()) {
BlockPosition position = new BlockPosition(entry.getKey().x(), entry.getKey().y(), entry.getKey().z());
VanillaBlockState state = VanillaBlockState.parse(entry.getValue().key());
blocks.put(position, new BlockEntry(position, state, null));
@@ -76,9 +74,9 @@ final class VanillaStructureTemplateEncoder {
Function<String, String> poolIdentifier
) {
for (IrisJigsawConnector connector : piece.getConnectors()) {
IrisPosition sourcePosition = connector.getPosition();
var sourcePosition = connector.getPosition();
BlockPosition position = new BlockPosition(
sourcePosition.getX(), sourcePosition.getY(), sourcePosition.getZ());
sourcePosition.x(), sourcePosition.y(), sourcePosition.z());
String orientation = orientation(connector.getDirection(), connector.getTop());
VanillaBlockState state = VanillaBlockState.parse(
"minecraft:jigsaw[orientation=" + orientation + "]");
@@ -100,23 +98,23 @@ final class VanillaStructureTemplateEncoder {
return nbt;
}
static String orientation(IrisDirection front, IrisDirection top) {
if (front == IrisDirection.UP_POSITIVE_Y || front == IrisDirection.DOWN_NEGATIVE_Y) {
if (top == IrisDirection.NORTH_NEGATIVE_Z
|| top == IrisDirection.SOUTH_POSITIVE_Z
|| top == IrisDirection.EAST_POSITIVE_X
|| top == IrisDirection.WEST_NEGATIVE_X) {
static String orientation(JigsawDirection front, JigsawDirection top) {
if (front == JigsawDirection.UP_POSITIVE_Y || front == JigsawDirection.DOWN_NEGATIVE_Y) {
if (top == JigsawDirection.NORTH_NEGATIVE_Z
|| top == JigsawDirection.SOUTH_POSITIVE_Z
|| top == JigsawDirection.EAST_POSITIVE_X
|| top == JigsawDirection.WEST_NEGATIVE_X) {
return directionName(front) + "_" + directionName(top);
}
throw new IllegalArgumentException("Vertical jigsaw fronts require a horizontal top direction");
}
if (top != IrisDirection.UP_POSITIVE_Y) {
if (top != JigsawDirection.UP_POSITIVE_Y) {
throw new IllegalArgumentException("Horizontal jigsaw fronts require an upward top direction");
}
return directionName(front) + "_up";
}
private static String directionName(IrisDirection direction) {
private static String directionName(JigsawDirection direction) {
return switch (direction) {
case UP_POSITIVE_Y -> "up";
case DOWN_NEGATIVE_Y -> "down";
@@ -18,7 +18,7 @@
package art.arcane.iris.core.structure.tooling;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.service.JigsawStudioRequest;
import art.arcane.iris.core.structure.authoring.StructureKey;
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
@@ -82,7 +82,6 @@ final class AdoptionCommands {
return;
}
StudioUse use = begun.get();
IrisData data = use.host().dataOf(context.pack());
String sourceKey;
Optional<StructureKey> targetKey;
IrisStructureAdoptionStrategy adoptionStrategy;
@@ -91,14 +90,14 @@ final class AdoptionCommands {
sourceKey = parseAdoptionSource(context.get(SOURCE));
targetKey = parseAdoptionTarget(context.get(TARGET));
adoptionStrategy = parseAdoptionStrategy(context.get(STRATEGY));
root = canonicalAdoptionRoot(data.getDataFolder().toPath());
root = canonicalAdoptionRoot(JigsawStudioRequest.rootOf(context.pack()));
} catch (IOException | IllegalArgumentException exception) {
use.error("Could not inspect adoption source: " + exception.getMessage());
return;
}
UUID ownerId = use.player().id();
use.say(TextColor.GRAY, "Inspecting Jigsaw adoption source '" + sourceKey + "' asynchronously...");
runAdoptionInspect(use, ownerId, data, root, sourceKey, targetKey, adoptionStrategy);
runAdoptionInspect(use, ownerId, root, sourceKey, targetKey, adoptionStrategy);
}
private void apply(CommandContext context) {
@@ -176,7 +175,6 @@ final class AdoptionCommands {
private static void runAdoptionInspect(
StudioUse use,
UUID ownerId,
IrisData data,
Path root,
String sourceKey,
Optional<StructureKey> targetKey,
@@ -197,13 +195,12 @@ final class AdoptionCommands {
failure = throwable;
use.pack().log().error("Failed to inspect Jigsaw adoption source '" + sourceKey + "'.", throwable);
}
finishAdoptionInspect(use, ownerId, data, service, plan, failure);
finishAdoptionInspect(use, ownerId, service, plan, failure);
}
private static void finishAdoptionInspect(
StudioUse use,
UUID ownerId,
IrisData data,
IrisStructureAdoptionService service,
IrisStructureAdoptionPlan plan,
Throwable failure
@@ -216,7 +213,7 @@ final class AdoptionCommands {
pruneAdoptionPlanBindings();
if (service.plan(plan.planId()).isPresent()) {
ADOPTION_PLANS.put(plan.planId(), new AdoptionPlanBinding(
ownerId, use.pack(), data, service, plan));
ownerId, use.pack(), service, plan));
}
reportAdoptionPlan(use, plan);
}
@@ -236,7 +233,7 @@ final class AdoptionCommands {
return;
}
StructureKey target = result.receipt().orElseThrow().targetStructure();
binding.data().invalidateStructureResources();
JigsawStudioRequest.reload(binding.pack());
StudioLifecycleCommands.openProject(use.onPack(binding.pack()), target.path());
}
@@ -337,7 +334,6 @@ final class AdoptionCommands {
private record AdoptionPlanBinding(
UUID ownerId,
ToolPack pack,
IrisData data,
IrisStructureAdoptionService service,
IrisStructureAdoptionPlan plan
) {
@@ -31,10 +31,9 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant;
import art.arcane.iris.core.service.JigsawStudioService;
import art.arcane.iris.core.structure.tooling.GraphMutations.PieceWorkcellResolution;
import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext;
import art.arcane.iris.engine.framework.structure.ObjectFrame;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.value.IrisPosition;
import com.volmit.geometry.BlockPosition;
import com.volmit.tooling.Argument;
import com.volmit.tooling.Command;
@@ -208,20 +207,20 @@ final class GraphEditCommands {
use.error("The active variant is read-only. Adopt it into this project before editing it.");
return;
}
IrisObject object = active.request().source().getObjectLoader().load(activeVariant.objectKey());
ObjectFrame object = GraphMutations.objectFrame(active, activeVariant.objectKey());
if (object == null) {
use.error("The active variant object '" + activeVariant.objectKey() + "' is missing.");
return;
}
IrisPosition canonicalPosition = new IrisPosition(
BlockPosition canonicalPosition = new BlockPosition(
target.x() - bay.bounds().originX(),
target.y() - bay.bounds().originY(),
target.z() - bay.bounds().originZ());
IrisPosition position;
BlockPosition position;
try {
position = activeVariant.canonicalToSourcePosition(
canonicalPosition,
new JigsawStudioCellDimensions(object.getW(), object.getH(), object.getD()));
new JigsawStudioCellDimensions(object.width(), object.height(), object.depth()));
} catch (IllegalArgumentException exception) {
use.error("Connector channel update failed: " + exception.getMessage());
return;
@@ -232,7 +231,7 @@ final class GraphEditCommands {
: channel.trim();
runGraphMutation(use, active, () -> {
JigsawStudioGraphEditor.updateConnectorChannel(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
activeVariant.pieceKey(),
position,
@@ -242,8 +241,8 @@ final class GraphEditCommands {
"",
"",
"Persisted connector channel '" + normalized + "' on piece '"
+ activeVariant.pieceKey() + "' at " + position.getX() + "," + position.getY()
+ "," + position.getZ() + ".");
+ activeVariant.pieceKey() + "' at " + position.x() + "," + position.y()
+ "," + position.z() + ".");
});
}
@@ -281,7 +280,7 @@ final class GraphEditCommands {
String fallback = NONE.equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey;
runGraphMutation(use, active, () -> {
JigsawStudioGraphEditor.createPool(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
poolKey,
fallback);
@@ -334,7 +333,7 @@ final class GraphEditCommands {
String topologyText = selectedTopology == null ? "blank spatial" : selectedTopology.name();
runGraphMutation(use, active, () -> {
JigsawStudioGraphEditor.createPiece(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
poolKey,
pieceKey,
@@ -363,7 +362,7 @@ final class GraphEditCommands {
String poolKey = context.get(OWNED_POOL);
String pieceKey = context.get(EXISTING_PIECE);
int weight = context.get(OPTIONAL_WEIGHT).intValue();
IrisJigsawPiece piece = StructureResources.piece(active.request().source().getPackResources(), pieceKey);
IrisJigsawPiece piece = StructureResources.piece(active.request().source().resources(), pieceKey);
if (piece == null) {
use.error("No jigsaw piece '" + pieceKey + "' exists in this pack.");
return;
@@ -372,7 +371,7 @@ final class GraphEditCommands {
use.error("Jigsaw piece '" + pieceKey + "' does not declare an object.");
return;
}
IrisObject object = active.request().source().getObjectLoader().load(piece.getObject());
ObjectFrame object = GraphMutations.objectFrame(active, piece.getObject());
if (object == null) {
use.error("Jigsaw piece '" + pieceKey + "' has no loadable object.");
return;
@@ -386,10 +385,10 @@ final class GraphEditCommands {
return;
}
if (!resolution.fits()) {
IrisPosition required = resolution.requiredDimensions();
BlockPosition required = resolution.requiredDimensions();
JigsawStudioCellDimensions capacity = resolution.workcell().capacity();
use.error("Jigsaw piece '" + pieceKey + "' requires " + required.getX() + "x"
+ required.getY() + "x" + required.getZ() + " in " + resolution.workcell().displayName()
use.error("Jigsaw piece '" + pieceKey + "' requires " + required.x() + "x"
+ required.y() + "x" + required.z() + " in " + resolution.workcell().displayName()
+ ", but that workcell capacity is " + capacity.width() + "x" + capacity.height()
+ "x" + capacity.depth() + ".");
return;
@@ -397,7 +396,7 @@ final class GraphEditCommands {
String objectKey = piece.getObject();
runGraphMutation(use, active, () -> {
if (!JigsawStudioGraphEditor.ownsPiece(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
pieceKey,
objectKey)) {
@@ -405,7 +404,7 @@ final class GraphEditCommands {
+ "use piece create for a new owned piece");
}
JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.addPiece(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
poolKey,
pieceKey,
@@ -442,7 +441,7 @@ final class GraphEditCommands {
String pieceKey = selected.pieceKey();
runGraphMutation(use, active, () -> {
JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.removePiece(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
poolKey,
pieceKey);
@@ -482,7 +481,7 @@ final class GraphEditCommands {
String pieceKey = selected.pieceKey();
runGraphMutation(use, active, () -> {
JigsawStudioGraphEditor.updateRotatable(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
pieceKey,
rotatable);
@@ -585,7 +584,7 @@ final class GraphEditCommands {
String pieceKey = selected.pieceKey();
runGraphMutation(use, active, () -> {
JigsawStudioPoolEditor.WeightUpdate update = JigsawStudioPoolEditor.updateWeight(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
poolKey,
pieceKey,
@@ -727,7 +726,7 @@ final class GraphEditCommands {
}
runGraphMutation(use, active, () -> {
JigsawStudioStructureEditor.updateLimits(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
maxDepth,
maxSizeChunks);
@@ -755,7 +754,7 @@ final class GraphEditCommands {
String fallback = NONE.equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey;
runGraphMutation(use, active, () -> {
JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.updateFallback(
active.request().source().getDataFolder().toPath(),
active.request().packRoot(),
active.request().structureKey(),
poolKey,
fallback);
@@ -18,7 +18,6 @@
package art.arcane.iris.core.structure.tooling;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
@@ -26,16 +25,18 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphMapper;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant;
import art.arcane.iris.core.service.JigsawStudioRequest;
import art.arcane.iris.core.service.JigsawStudioService;
import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext;
import art.arcane.iris.engine.framework.structure.ObjectFrame;
import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype;
import art.arcane.iris.engine.object.value.IrisPosition;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.PackResources;
import java.io.IOException;
import java.util.HashSet;
@@ -58,13 +59,19 @@ final class GraphMutations {
}
static JigsawStudioLayout loadPersistedLayout(ActiveContext context) throws IOException {
IrisData source = context.request().source();
source.invalidateStructureResources();
IrisStructure structure = StructureResources.structure(source.getPackResources(), context.request().structureKey());
JigsawStudioRequest request = context.request();
request.reloadSource();
IrisStructure structure = StructureResources.structure(request.source().resources(), request.structureKey());
if (structure == null) {
throw new IOException("The structure could not be reloaded after the graph transaction");
}
return JigsawStudioGraphMapper.map(source, structure);
return JigsawStudioGraphMapper.map(request.source(), request.packRoot(), request.structureKey(), structure);
}
/** The declared size of the pack object {@code objectKey} names in the studio's pack; null when it has none. */
static ObjectFrame objectFrame(ActiveContext context, String objectKey) {
PackResources resources = context.request().source().resources();
return resources.objects().sizeOf(resources.idOf(objectKey)).map(ObjectFrame::of).orElse(null);
}
static JigsawStudioService.CommandGraphMutationResult mappedMutationResult(
@@ -93,23 +100,23 @@ final class GraphMutations {
static PieceWorkcellResolution resolvePieceWorkcell(
JigsawStudioLayout layout,
IrisJigsawPiece piece,
IrisObject object
ObjectFrame object
) {
JigsawStudioLayout activeLayout = Objects.requireNonNull(layout, "Jigsaw Studio layout");
IrisJigsawPiece activePiece = Objects.requireNonNull(piece, "Jigsaw piece");
IrisObject activeObject = Objects.requireNonNull(object, "Jigsaw piece object");
ObjectFrame activeObject = Objects.requireNonNull(object, "Jigsaw piece object");
String workcellId;
IrisPosition requiredDimensions;
BlockPosition requiredDimensions;
if (activeLayout.mode() == JigsawStudioMode.PLANAR_JIGSAW) {
IrisJigsawWorkcellArchetype modelArchetype = IrisJigsawWorkcellArchetype.fromPiece(activePiece);
workcellId = JigsawPlanarArchetype.fromModel(modelArchetype).stableId();
requiredDimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(activePiece, activeObject);
} else {
workcellId = JigsawStudioLayout.SPATIAL_WORKCELL_ID;
requiredDimensions = new IrisPosition(
activeObject.getW(),
activeObject.getH(),
activeObject.getD());
requiredDimensions = new BlockPosition(
activeObject.width(),
activeObject.height(),
activeObject.depth());
}
JigsawStudioBay workcell = activeLayout.get(workcellId);
if (workcell == null) {
@@ -120,7 +127,7 @@ final class GraphMutations {
static String nextThemeKey(ActiveContext context) throws IOException {
IrisStructure structure = StructureResources.structure(
context.request().source().getPackResources(),
context.request().source().resources(),
context.request().structureKey());
if (structure == null) {
throw new IOException("The active jigsaw structure could not be loaded");
@@ -146,7 +153,7 @@ final class GraphMutations {
record PieceWorkcellResolution(
JigsawStudioBay workcell,
IrisPosition requiredDimensions
BlockPosition requiredDimensions
) {
PieceWorkcellResolution {
workcell = Objects.requireNonNull(workcell, "Jigsaw Studio workcell");
@@ -155,9 +162,9 @@ final class GraphMutations {
boolean fits() {
JigsawStudioCellDimensions capacity = workcell.capacity();
return requiredDimensions.getX() <= capacity.width()
&& requiredDimensions.getY() <= capacity.height()
&& requiredDimensions.getZ() <= capacity.depth();
return requiredDimensions.x() <= capacity.width()
&& requiredDimensions.y() <= capacity.height()
&& requiredDimensions.z() <= capacity.depth();
}
}
}
@@ -103,8 +103,8 @@ final class JigsawExportCommand {
VanillaJigsawExportRequest request;
try {
request = VanillaJigsawExportRequest.builder(
VanillaJigsawExportSource.forData(
active.request().source(), active.request().structureKey()), destination)
VanillaJigsawExportSource.forPack(
active.request().source().resources(), active.request().structureKey()), destination)
.namespace(context.get(NAMESPACE))
.resourcePath(active.request().structureKey())
.format(exportFormat)
@@ -18,7 +18,6 @@
package art.arcane.iris.core.structure.tooling;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.service.JigsawStudioService;
import com.volmit.tooling.Sender;
import com.volmit.tooling.ToolPack;
@@ -28,16 +27,13 @@ import java.util.concurrent.CompletableFuture;
/**
* What the jigsaw commands need from the server that runs the Jigsaw Studio and that no api type offers: the studio
* itself, the pack's data, whether a pack may open a studio, and the server's one open studio. The adapter that runs a
* itself, whether a pack may open a studio, and the server's one open studio. The adapter that runs a
* studio implements it; a platform without one has none, and the commands then say so.
*/
public interface JigsawStudioHost {
/** The studio, which keeps the sessions of its players. */
JigsawStudioService studio();
/** The pack's data, for the resources the studio still reads through it. */
IrisData dataOf(ToolPack pack);
/** The key the studio files {@code pack} under. */
String packKey(ToolPack pack);
@@ -18,7 +18,6 @@
package art.arcane.iris.core.structure.tooling;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget;
@@ -295,7 +294,6 @@ final class StudioLifecycleCommands {
use.error("The current Jigsaw Studio is waiting for autosave. Wait for it to finish or close with discard=true.");
return;
}
IrisData data = host.dataOf(pack);
IrisStructure irisStructure = StructureResources.structure(pack.resources(), structure);
if (irisStructure == null) {
use.error("No Iris jigsaw structure '" + structure + "' exists in this pack.");
@@ -304,7 +302,7 @@ final class StudioLifecycleCommands {
JigsawStudioLayout layout;
try {
layout = JigsawStudioGraphMapper.map(data, irisStructure);
layout = JigsawStudioGraphMapper.map(pack, JigsawStudioRequest.rootOf(pack), structure, irisStructure);
} catch (RuntimeException exception) {
pack.log().error("Failed to map Jigsaw Studio graph '" + structure + "'.", exception);
use.error("Could not map this jigsaw graph: " + exception.getMessage());
@@ -341,7 +339,7 @@ final class StudioLifecycleCommands {
layout.mode(),
compatibilityOf(irisStructure),
layout.cellDimensions(),
data,
pack,
layout,
playerId,
closingRequestId);
@@ -19,17 +19,16 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.engine.framework.structure.ColumnHeights;
import art.arcane.iris.engine.framework.structure.NativeStartPlanner;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.structure.StructureGraphCatalog;
import art.arcane.iris.engine.framework.structure.StructureGraphCompilation;
import art.arcane.iris.engine.framework.structure.StructureAssemblyResult;
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.iris.engine.framework.structure.assembly.StructureStamp;
import art.arcane.iris.engine.framework.structure.assembly.Viability;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.builtin.structure.StructureAnchorMode;
import art.arcane.iris.builtin.structure.StructureCarveShape;
import art.arcane.iris.builtin.structure.StructurePlacement;
@@ -39,9 +38,9 @@ import art.arcane.iris.builtin.structure.NativeStructureSuppression;
import art.arcane.iris.builtin.structure.StructureDistribution;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.core.modules.IrisModuleHost;
import com.volmit.ModuleLog;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.Collections;
@@ -171,7 +170,7 @@ public final class IrisStructureLocator {
return false;
}
for (StructurePlacement placement : index(engine).placements) {
if (placement.hasIrisStructures() && matches(placement, key, engine.getData())) {
if (placement.hasIrisStructures() && matches(placement, key, engine)) {
return true;
}
}
@@ -516,32 +515,33 @@ public final class IrisStructureLocator {
if (selectedKey == null || selectedKey.isBlank()) {
throw new IllegalStateException("Iris structure placement selected a blank structure key");
}
IrisStructure structure = StructureResources.structure(engine.getData().getPackResources(), selectedKey);
if (structure == null) {
PackResources pack = engine.getData().getPackResources();
ResourceId structureId = pack.idOf(selectedKey);
StructureAssembly provider = providerOf(engine, structureId);
if (provider == null) {
throw new IllegalStateException("Iris structure placement references missing structure '"
+ selectedKey + "'");
}
StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure, IrisModuleHost.hostLog());
if (!compilation.isAssemblyViable()) {
if (!provider.viability(pack, structureId).isViable()) {
throw new IllegalStateException("Iris structure '" + selectedKey
+ "' has no runtime-viable assembly graph");
}
StructureAssembler assembler = StructureAssembler.forData(
engine.getData(), structure, new IrisPosition(originX, baseY, originZ), IrisModuleHost.hostLog());
StructureAssemblyResult assembly = assembler.assemble(rng);
Assembly assembly = provider.assemble(pack, structureId, new BlockPosition(originX, baseY, originZ), rng)
.orElseThrow();
if (!requirePlacementOutput(placement, selectedKey, cx, cz,
assembly.hasOutput(), "runtime assembly produced " + assembly.status() + ": " + assembly.detail())) {
return null;
}
KList<PlacedStructurePiece> pieces = new KList<>(assembly.pieces());
StructureStamp stamp = provider.stamp(pack, structureId).orElseThrow();
KList<AssembledPiece> pieces = new KList<>(assembly.pieces());
pieces = alignCavePieces(pieces, placement, baseY);
pieces = alignSurfacePieces(pieces, placement, structure, baseY);
pieces = alignSurfacePieces(pieces, placement, stamp, baseY);
if (!requirePlacementOutput(placement, selectedKey, cx, cz,
pieces != null && !pieces.isEmpty(), "surface alignment produced no pieces")) {
return null;
}
boolean exactY = hasExactY(placement, structure, pieces);
boolean exactY = hasExactY(placement, stamp, pieces);
int worldMin = engine.getMinHeight() + 1;
int worldMax = engine.getMinHeight() + engine.getHeight() - 1;
@@ -569,7 +569,7 @@ public final class IrisStructureLocator {
}
}
long configuredRadius = (long) Math.max(1, structure.getMaxSizeChunks()) * 16L;
long configuredRadius = (long) Math.max(1, provider.reachChunks(pack, structureId).orElse(1)) * 16L;
int structureRadius = (int) Math.min(Integer.MAX_VALUE, configuredRadius);
boolean withinBounds = fitsHorizontalBounds(pieces, originX, originZ, structureRadius)
&& (!exactY || fitsVerticalBounds(pieces, worldMin, worldMax));
@@ -577,7 +577,29 @@ public final class IrisStructureLocator {
"assembled pieces exceed the configured structure or world bounds")) {
return null;
}
return new ResolvedPlacement(placement, selectedKey, structure, pieces, rng, originX, baseY, originZ, exactY);
return new ResolvedPlacement(placement, selectedKey, stamp, pieces, rng, originX, baseY, originZ, exactY);
}
/**
* The first provider of {@link StructureAssembly} among the modules of the engine's pack that knows {@code structure};
* null when none does.
*/
public static StructureAssembly providerOf(Engine engine, ResourceId structure) {
PackResources pack = engine.getData().getPackResources();
for (StructureAssembly provider : engine.getGeneration().world().services(StructureAssembly.class)) {
if (provider.knows(pack, structure)) {
return provider;
}
}
return null;
}
/** How the pieces of the pack structure {@code key} are stamped; null when no module knows the structure. */
public static StructureStamp stampOf(Engine engine, String key) {
PackResources pack = engine.getData().getPackResources();
ResourceId structure = pack.idOf(key);
StructureAssembly provider = providerOf(engine, structure);
return provider == null ? null : provider.stamp(pack, structure).orElse(null);
}
public static boolean requirePlacementOutput(StructurePlacement placement, String structureKey,
@@ -599,7 +621,7 @@ public final class IrisStructureLocator {
+ ". Native generation is suppressed and will not be used as a fallback");
}
static boolean fitsWorldBounds(KList<PlacedStructurePiece> pieces, int worldMin, int worldMax,
static boolean fitsWorldBounds(KList<AssembledPiece> pieces, int worldMin, int worldMax,
int originX, int originZ, int structureRadius) {
int[] bounds = computeBounds(pieces);
if (bounds == null) {
@@ -610,7 +632,6 @@ public final class IrisStructureLocator {
}
private static ResolvedStart resolveInChunk(Engine engine, String key, int cx, int cz) {
IrisData data = engine.getData();
String normalizedKey = normalize(key);
if (hasNativePlacement(engine, key)) {
for (NativeStartPlanner.Plan plan : NativeStartPlanner.plansAt(engine, cx, cz)) {
@@ -621,7 +642,7 @@ public final class IrisStructureLocator {
}
KList<StructurePlacement> placements = StructurePlacementScope.placementsAt(engine, cx, cz);
for (StructurePlacement placement : placements) {
if (!matches(placement, key, data)) {
if (!matches(placement, key, engine)) {
continue;
}
if (placement.hasNativeStructures()) {
@@ -676,7 +697,7 @@ public final class IrisStructureLocator {
return randomInclusive(rng, bandMin, bandMax);
}
static Integer resolveVerticalShift(KList<PlacedStructurePiece> pieces, StructurePlacement placement,
static Integer resolveVerticalShift(KList<AssembledPiece> pieces, StructurePlacement placement,
int baseY, int worldMin, int worldMax) {
int[] bounds = computeBounds(pieces);
if (bounds == null) {
@@ -701,7 +722,7 @@ public final class IrisStructureLocator {
return 0;
}
static Integer resolveUndergroundBurialShift(Engine engine, KList<PlacedStructurePiece> pieces,
static Integer resolveUndergroundBurialShift(Engine engine, KList<AssembledPiece> pieces,
StructurePlacement placement, int baseY,
int worldMin, int worldMax) {
int[] bounds = computeBounds(pieces);
@@ -729,8 +750,7 @@ public final class IrisStructureLocator {
return null;
}
Long2IntOpenHashMap surfaceHeights = new Long2IntOpenHashMap();
surfaceHeights.defaultReturnValue(Integer.MIN_VALUE);
ColumnHeights surfaceHeights = new ColumnHeights(Integer.MIN_VALUE);
if (bore || forceCarve && carveShape == StructureCarveShape.BOX) {
maximumShift = resolveBurialEnvelopeShift(
engine,
@@ -746,14 +766,14 @@ public final class IrisStructureLocator {
return null;
}
} else {
for (PlacedStructurePiece piece : pieces) {
for (AssembledPiece piece : pieces) {
maximumShift = resolveBurialEnvelopeShift(
engine,
piece.getMinX() - sideExtension,
piece.getMaxX() + sideExtension,
piece.getMinZ() - sideExtension,
piece.getMaxZ() + sideExtension,
piece.getMaxY() + topExtension,
piece.minX() - sideExtension,
piece.maxX() + sideExtension,
piece.minZ() - sideExtension,
piece.maxZ() + sideExtension,
piece.maxY() + topExtension,
maximumShift,
surfaceHeights
);
@@ -767,7 +787,7 @@ public final class IrisStructureLocator {
private static int resolveBurialEnvelopeShift(Engine engine, int minX, int maxX, int minZ, int maxZ,
int envelopeTopY, int maximumShift,
Long2IntOpenHashMap surfaceHeights) {
ColumnHeights surfaceHeights) {
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
long columnKey = ((long) x << 32) ^ (z & 0xffffffffL);
@@ -793,8 +813,8 @@ public final class IrisStructureLocator {
return placement.structures().get(rng.nextInt(placement.structures().size()));
}
static KList<PlacedStructurePiece> alignCavePieces(
KList<PlacedStructurePiece> pieces,
static KList<AssembledPiece> alignCavePieces(
KList<AssembledPiece> pieces,
StructurePlacement placement,
int anchorY
) {
@@ -815,24 +835,24 @@ public final class IrisStructureLocator {
return shiftPieces(pieces, anchorY - targetY);
}
private static KList<PlacedStructurePiece> alignSurfacePieces(KList<PlacedStructurePiece> pieces,
private static KList<AssembledPiece> alignSurfacePieces(KList<AssembledPiece> pieces,
StructurePlacement placement,
IrisStructure structure, int baseY) {
StructureStamp stamp, int baseY) {
if (placement.isAnchoredUnderground() || pieces.size() <= 1
|| structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT)) {
|| stamp.placeMode().placeMode().has(PlaceTrait.FREE_HEIGHT)) {
return pieces;
}
int[] bounds = computeBounds(pieces);
return bounds == null ? pieces : shiftPieces(pieces, baseY - bounds[1]);
}
static boolean hasExactY(StructurePlacement placement, IrisStructure structure,
KList<PlacedStructurePiece> pieces) {
static boolean hasExactY(StructurePlacement placement, StructureStamp stamp,
KList<AssembledPiece> pieces) {
return placement.isAnchoredUnderground() || pieces.size() > 1
|| structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT);
|| stamp.placeMode().placeMode().has(PlaceTrait.FREE_HEIGHT);
}
private static boolean fitsVerticalBounds(KList<PlacedStructurePiece> pieces, int worldMin, int worldMax) {
private static boolean fitsVerticalBounds(KList<AssembledPiece> pieces, int worldMin, int worldMax) {
int[] bounds = computeBounds(pieces);
return bounds != null && fitsVerticalBounds(bounds, worldMin, worldMax);
}
@@ -841,7 +861,7 @@ public final class IrisStructureLocator {
return bounds[1] >= worldMin && bounds[4] <= worldMax;
}
private static boolean fitsHorizontalBounds(KList<PlacedStructurePiece> pieces, int originX, int originZ,
private static boolean fitsHorizontalBounds(KList<AssembledPiece> pieces, int originX, int originZ,
int structureRadius) {
int[] bounds = computeBounds(pieces);
return bounds != null && fitsHorizontalBounds(bounds, originX, originZ, structureRadius);
@@ -852,18 +872,15 @@ public final class IrisStructureLocator {
&& bounds[2] >= originZ - structureRadius && bounds[5] <= originZ + structureRadius;
}
private static KList<PlacedStructurePiece> shiftPieces(KList<PlacedStructurePiece> pieces, int shiftY) {
KList<PlacedStructurePiece> shifted = new KList<>();
for (PlacedStructurePiece piece : pieces) {
shifted.add(new PlacedStructurePiece(
piece.getPiece(), piece.getObject(), piece.getX(), piece.getY() + shiftY, piece.getZ(), piece.getRotation(),
piece.getMinX(), piece.getMinY() + shiftY, piece.getMinZ(),
piece.getMaxX(), piece.getMaxY() + shiftY, piece.getMaxZ()));
private static KList<AssembledPiece> shiftPieces(KList<AssembledPiece> pieces, int shiftY) {
KList<AssembledPiece> shifted = new KList<>();
for (AssembledPiece piece : pieces) {
shifted.add(piece.shiftedUp(shiftY));
}
return shifted;
}
private static int[] computeBounds(KList<PlacedStructurePiece> pieces) {
private static int[] computeBounds(KList<AssembledPiece> pieces) {
if (pieces == null || pieces.isEmpty()) {
return null;
}
@@ -873,13 +890,13 @@ public final class IrisStructureLocator {
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
int maxZ = Integer.MIN_VALUE;
for (PlacedStructurePiece piece : pieces) {
minX = Math.min(minX, piece.getMinX());
minY = Math.min(minY, piece.getMinY());
minZ = Math.min(minZ, piece.getMinZ());
maxX = Math.max(maxX, piece.getMaxX());
maxY = Math.max(maxY, piece.getMaxY());
maxZ = Math.max(maxZ, piece.getMaxZ());
for (AssembledPiece piece : pieces) {
minX = Math.min(minX, piece.minX());
minY = Math.min(minY, piece.minY());
minZ = Math.min(minZ, piece.minZ());
maxX = Math.max(maxX, piece.maxX());
maxY = Math.max(maxY, piece.maxY());
maxZ = Math.max(maxZ, piece.maxZ());
}
return new int[]{minX, minY, minZ, maxX, maxY, maxZ};
}
@@ -897,7 +914,7 @@ public final class IrisStructureLocator {
boolean hasDensity = false;
for (StructurePlacement placement : index(engine).placements) {
if (!isSearchablePlacement(engine, placement)
|| !matches(placement, key, engine.getData())) {
|| !matches(placement, key, engine)) {
continue;
}
if (placement.distribution() == StructureDistribution.RANDOM_SPREAD) {
@@ -1016,8 +1033,8 @@ public final class IrisStructureLocator {
private record PlacementAnchor(int x, int y, int z) {
}
private static boolean matches(StructurePlacement placement, String key, IrisData data) {
if (placement == null || key == null || data == null) {
private static boolean matches(StructurePlacement placement, String key, Engine engine) {
if (placement == null || key == null || engine == null || engine.getData() == null) {
return false;
}
String normalizedKey = normalize(key);
@@ -1030,13 +1047,12 @@ public final class IrisStructureLocator {
if (structureKey == null || structureKey.isBlank()) {
continue;
}
IrisStructure structure = StructureResources.structure(data.getPackResources(), structureKey);
if (structure == null) {
StructureStamp stamp = stampOf(engine, structureKey);
if (stamp == null) {
continue;
}
if (normalize(structureKey).equals(normalizedKey)
|| normalize(structure.getLoadKey()).equals(normalizedKey)
|| normalize(structure.getVanillaSource()).equals(normalizedKey)) {
|| normalize(stamp.vanillaSource()).equals(normalizedKey)) {
return true;
}
}
@@ -1046,8 +1062,7 @@ public final class IrisStructureLocator {
static boolean matchesResolved(ResolvedPlacement resolved, String key) {
String normalizedKey = normalize(key);
return normalize(resolved.structureKey()).equals(normalizedKey)
|| normalize(resolved.structure().getLoadKey()).equals(normalizedKey)
|| normalize(resolved.structure().getVanillaSource()).equals(normalizedKey);
|| normalize(resolved.stamp().vanillaSource()).equals(normalizedKey);
}
private static String normalize(String key) {
@@ -1072,7 +1087,6 @@ public final class IrisStructureLocator {
}
private static LocatableIndex buildLocatableIndex(Engine engine) {
IrisData data = engine.getData();
Set<String> keys = new LinkedHashSet<>();
Set<String> normalizedKeys = new LinkedHashSet<>();
Set<String> editableKeys = new LinkedHashSet<>();
@@ -1091,17 +1105,15 @@ public final class IrisStructureLocator {
continue;
}
for (String structureKey : placement.structures()) {
IrisStructure structure = StructureResources.structure(data.getPackResources(), structureKey);
if (structure == null) {
StructureStamp stamp = stampOf(engine, structureKey);
if (stamp == null) {
throw new IllegalStateException(
"Iris structure placement references missing structure '" + structureKey + "'");
}
addLocatableKey(structureKey, keys, normalizedKeys);
addLocatableKey(structureKey, editableKeys, normalizedEditableKeys);
addLocatableKey(structure.getLoadKey(), keys, normalizedKeys);
addLocatableKey(structure.getLoadKey(), editableKeys, normalizedEditableKeys);
addLocatableKey(structure.getVanillaSource(), keys, normalizedKeys);
addLocatableKey(structure.getVanillaSource(), editableKeys, normalizedEditableKeys);
addLocatableKey(stamp.vanillaSource(), keys, normalizedKeys);
addLocatableKey(stamp.vanillaSource(), editableKeys, normalizedEditableKeys);
}
}
return new LocatableIndex(
@@ -1123,19 +1135,17 @@ public final class IrisStructureLocator {
}
private static PlacementIndex build(Engine engine) {
IrisData data = engine.getData();
ModuleLog log = IrisModuleHost.hostLog();
Set<String> loadKeys = new LinkedHashSet<>();
Set<String> normalizedLoadKeys = new LinkedHashSet<>();
Set<String> vanillaAliases = new LinkedHashSet<>();
Set<String> suppressedVanillaSources = new LinkedHashSet<>();
List<StructurePlacement> placements = new ArrayList<>();
collect(StructurePlacementScope.placementsOf(engine.getDimension()), data, log, loadKeys, normalizedLoadKeys, vanillaAliases,
collect(StructurePlacementScope.placementsOf(engine.getDimension()), engine, loadKeys, normalizedLoadKeys, vanillaAliases,
suppressedVanillaSources, placements, true);
KList<IrisRegion> regions = engine.getDimension().getAllRegions(engine);
if (regions != null) {
for (IrisRegion region : regions) {
collect(StructurePlacementScope.placementsOf(region), data, log,
collect(StructurePlacementScope.placementsOf(region), engine,
loadKeys, normalizedLoadKeys, vanillaAliases,
suppressedVanillaSources, placements, false);
}
@@ -1143,7 +1153,7 @@ public final class IrisStructureLocator {
KList<IrisBiome> biomes = engine.getDimension().getReachableBiomes(engine);
if (biomes != null) {
for (IrisBiome biome : biomes) {
collect(StructurePlacementScope.placementsOf(biome), data, log,
collect(StructurePlacementScope.placementsOf(biome), engine,
loadKeys, normalizedLoadKeys, vanillaAliases,
suppressedVanillaSources, placements, false);
}
@@ -1172,7 +1182,7 @@ public final class IrisStructureLocator {
return Collections.unmodifiableSet(nativeKeys);
}
private static void collect(List<StructurePlacement> source, IrisData data, ModuleLog log, Set<String> loadKeys,
private static void collect(List<StructurePlacement> source, Engine engine, Set<String> loadKeys,
Set<String> normalizedLoadKeys, Set<String> vanillaAliases,
Set<String> suppressedVanillaSources,
List<StructurePlacement> placements, boolean allowNativeSuppression) {
@@ -1209,8 +1219,8 @@ public final class IrisStructureLocator {
? "REPLACE_SOURCE contains a blank Iris structure reference"
: "Iris structure placement contains a blank structure reference");
}
IrisStructure structure = StructureResources.structure(data.getPackResources(), structureKey);
if (structure == null) {
StructureStamp stamp = stampOf(engine, structureKey);
if (stamp == null) {
throw new IllegalStateException((replacesNative
? "REPLACE_SOURCE references missing Iris structure '"
: "Iris structure placement references missing structure '")
@@ -1218,20 +1228,18 @@ public final class IrisStructureLocator {
}
loadKeys.add(structureKey);
normalizedLoadKeys.add(normalize(structureKey));
if (structure.getLoadKey() != null && !structure.getLoadKey().isBlank()) {
loadKeys.add(structure.getLoadKey());
normalizedLoadKeys.add(normalize(structure.getLoadKey()));
}
if (structure.getVanillaSource() != null && !structure.getVanillaSource().isBlank()) {
vanillaAliases.add(normalize(structure.getVanillaSource()));
if (!stamp.vanillaSource().isBlank()) {
vanillaAliases.add(normalize(stamp.vanillaSource()));
}
if (replacesNative) {
String vanillaSource = structure.getVanillaSource();
if (vanillaSource == null || !NAMESPACED_RESOURCE_KEY.matcher(vanillaSource).matches()) {
String vanillaSource = stamp.vanillaSource();
if (!NAMESPACED_RESOURCE_KEY.matcher(vanillaSource).matches()) {
throw new IllegalStateException("REPLACE_SOURCE structure '" + structureKey
+ "' must declare a valid namespaced vanillaSource");
}
if (!StructureGraphCatalog.guaranteesRuntimeOutput(data, structure, log)) {
PackResources pack = engine.getData().getPackResources();
ResourceId structureId = pack.idOf(structureKey);
if (providerOf(engine, structureId).viability(pack, structureId) != Viability.GUARANTEED) {
throw new IllegalStateException("REPLACE_SOURCE structure '" + structureKey
+ "' is not runtime-viable; native generation will not be used as a fallback");
}
@@ -1242,8 +1250,8 @@ public final class IrisStructureLocator {
}
}
public record ResolvedPlacement(StructurePlacement placement, String structureKey, IrisStructure structure,
KList<PlacedStructurePiece> pieces, RNG rng,
public record ResolvedPlacement(StructurePlacement placement, String structureKey, StructureStamp stamp,
KList<AssembledPiece> pieces, RNG rng,
int originX, int baseY, int originZ, boolean exactY) {
}
@@ -18,9 +18,9 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.framework.structure.ObjectFrame;
import art.arcane.iris.engine.framework.structure.assembly.PieceTurn;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.prefab.ObjectTurn;
import lombok.AllArgsConstructor;
import lombok.Data;
@@ -28,11 +28,14 @@ import lombok.Data;
@AllArgsConstructor
public class PlacedStructurePiece {
private final IrisJigsawPiece piece;
private final IrisObject object;
/** The pack key of the piece's object. */
private final String objectKey;
/** The declared size of the piece's object. */
private final ObjectFrame object;
private final int x;
private final int y;
private final int z;
private final ObjectTurn rotation;
private final PieceTurn rotation;
private final int minX;
private final int minY;
private final int minZ;
@@ -18,8 +18,9 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.structure.CompiledStructureGraph;
import art.arcane.iris.engine.framework.structure.ObjectFrame;
import art.arcane.iris.engine.framework.structure.assembly.PieceTurn;
import art.arcane.iris.engine.framework.structure.JigsawPoolSelection;
import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver;
import art.arcane.iris.engine.framework.structure.StructureAssemblyResult;
@@ -29,7 +30,7 @@ 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.framework.structure.StructureGraphResolver;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode;
@@ -37,15 +38,14 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.prefab.ObjectTurn;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.PackResources;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
@@ -79,9 +79,9 @@ public final class StructureAssembler {
this.resolver = options.resolver();
this.graph = options.graph();
this.structure = options.structure();
this.originX = options.origin().getX();
this.originY = options.origin().getY();
this.originZ = options.origin().getZ();
this.originX = options.origin().x();
this.originY = options.origin().y();
this.originZ = options.origin().z();
this.planarWorkcells = this.structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW
? PlanarJigsawWorkcellResolver.resolve(this.structure)
: Map.of();
@@ -90,23 +90,25 @@ public final class StructureAssembler {
? this.structure.getMaxSizeChunks() * 16 : 0;
}
public static StructureAssembler forData(IrisData data, IrisStructure structure, IrisPosition origin, ModuleLog log) {
IrisData activeData = Objects.requireNonNull(data, "Structure assembly data must not be null");
/** An assembler of {@code structure}, the pack's structure {@code structureKey}, from {@code origin}. */
public static StructureAssembler forPack(PackResources pack, String structureKey, IrisStructure structure, BlockPosition origin,
ModuleLog log) {
PackResources activePack = Objects.requireNonNull(pack, "Structure assembly pack must not be null");
IrisStructure activeStructure = Objects.requireNonNull(
structure, "Structure assembly structure must not be null");
return forCompilation(StructureGraphCatalog.compile(activeData, activeStructure, log), origin);
return forCompilation(StructureGraphCatalog.compile(activePack, structureKey, activeStructure, log), origin);
}
public static StructureAssembler forResolver(StructureGraphResolver resolver, IrisStructure structure,
IrisPosition origin) {
public static StructureAssembler forResolver(String structureKey, StructureGraphResolver resolver, IrisStructure structure,
BlockPosition origin) {
StructureGraphResolver activeResolver = Objects.requireNonNull(
resolver, "Structure assembly resolver must not be null");
IrisStructure activeStructure = Objects.requireNonNull(
structure, "Structure assembly structure must not be null");
return forCompilation(StructureGraphCompiler.compile(activeStructure, activeResolver), origin);
return forCompilation(StructureGraphCompiler.compile(structureKey, activeStructure, activeResolver), origin);
}
public static StructureAssembler forCompilation(StructureGraphCompilation compilation, IrisPosition origin) {
public static StructureAssembler forCompilation(StructureGraphCompilation compilation, BlockPosition origin) {
StructureGraphCompilation activeCompilation = Objects.requireNonNull(
compilation, "Structure graph compilation must not be null");
if (activeCompilation.hasErrors()) {
@@ -120,17 +122,17 @@ public final class StructureAssembler {
public StructureAssemblyResult assemble(RNG rng) {
Objects.requireNonNull(rng, "Structure assembly RNG must not be null");
if (radius == 0) {
throw new IllegalStateException("Structure '" + structure.getLoadKey()
throw new IllegalStateException("Structure '" + graph.getStructureKey()
+ "' has maxSizeChunks outside 1.." + MAX_SIZE_CHUNKS);
}
if (structure.getMaxDepth() < 1 || structure.getMaxDepth() > MAX_DEPTH) {
throw new IllegalStateException("Structure '" + structure.getLoadKey()
throw new IllegalStateException("Structure '" + graph.getStructureKey()
+ "' has maxDepth outside 1.." + MAX_DEPTH);
}
String startPoolKey = normalize(structure.getStartPool());
IrisJigsawPool startPool = resolver.loadPool(startPoolKey);
if (startPool == null || startPool.getPieces() == null || startPool.getPieces().isEmpty()) {
throw new IllegalStateException("Structure '" + structure.getLoadKey()
throw new IllegalStateException("Structure '" + graph.getStructureKey()
+ "' has no resolvable start pool '" + startPoolKey + "'");
}
@@ -160,7 +162,7 @@ public final class StructureAssembler {
}
IrisJigsawPieceEntry startEntry = weightedPick(startEntries, rng);
if (startEntry == null) {
throw new IllegalStateException("Structure '" + structure.getLoadKey()
throw new IllegalStateException("Structure '" + graph.getStructureKey()
+ "' start pool has no positively weighted entry");
}
if (startEntry.isEmpty()) {
@@ -171,23 +173,23 @@ public final class StructureAssembler {
String startPieceKey = normalize(startEntry.getPiece());
IrisJigsawPiece startPiece = resolver.loadPiece(startPieceKey);
if (startPiece == null) {
throw new IllegalStateException("Structure '" + structure.getLoadKey()
throw new IllegalStateException("Structure '" + graph.getStructureKey()
+ "' start pool references missing piece '" + startPieceKey + "'");
}
String startObjectKey = normalize(startPiece.getObject());
IrisObject startObject = resolver.loadObject(startObjectKey);
ObjectFrame startObject = resolver.loadObject(startObjectKey);
if (startObject == null) {
throw new IllegalStateException("Structure '" + structure.getLoadKey()
throw new IllegalStateException("Structure '" + graph.getStructureKey()
+ "' start piece references missing object '" + startObjectKey + "'");
}
if (startPiece.getConnectors() == null) {
throw new IllegalStateException("Structure '" + structure.getLoadKey()
throw new IllegalStateException("Structure '" + graph.getStructureKey()
+ "' start piece has no connector list");
}
int startRotY = startPiece.isRotatable() ? Y_DEGREES[rng.i(Y_DEGREES.length)] : 0;
ObjectTurn startRot = ObjectTurn.of(0, startRotY, 0);
PlacedStructurePiece start = build(startPiece, startObject, originX, originY, originZ, startRot);
PieceTurn startRot = PieceTurn.aroundY(startRotY);
PlacedStructurePiece start = build(startPiece, startObjectKey, startObject, originX, originY, originZ, startRot);
placed.add(start);
registerPlacedPiece(consumedConnectors, start, null);
incrementPlacement(placementCounts, startPieceKey);
@@ -216,7 +218,7 @@ public final class StructureAssembler {
IrisJigsawPool pool = resolver.loadPool(connector.pool);
if (pool == null) {
throw new IllegalStateException("Structure '" + structure.getLoadKey()
throw new IllegalStateException("Structure '" + graph.getStructureKey()
+ "' references missing connector pool '" + connector.pool + "'");
}
@@ -380,7 +382,7 @@ public final class StructureAssembler {
if (objectKey.isEmpty()) {
throw assemblyFailure("piece '" + pieceName + "' has no object key");
}
IrisObject object = resolver.loadObject(objectKey);
ObjectFrame object = resolver.loadObject(objectKey);
if (object == null) {
throw assemblyFailure("piece '" + pieceName + "' references missing object '"
+ objectKey + "'");
@@ -404,27 +406,27 @@ public final class StructureAssembler {
continue;
}
IrisDirection needed = connector.facing.reverse();
JigsawDirection needed = connector.facing.reverse();
int[] rotations = piece.isRotatable() ? rotationCandidates(connector.joint, rng) : NO_ROTATION;
for (int yDeg : rotations) {
ObjectTurn rot = ObjectTurn.of(0, yDeg, 0);
IrisDirection rotatedFace = rot.rotate(cb.getDirection());
PieceTurn rot = PieceTurn.aroundY(yDeg);
JigsawDirection rotatedFace = rotate(rot, cb.getDirection());
if (rotatedFace != needed) {
continue;
}
if (connector.joint == JigsawJoint.ALIGNED && rot.rotate(cb.getTop()) != connector.top) {
if (connector.joint == JigsawJoint.ALIGNED && rotate(rot, cb.getTop()) != connector.top) {
continue;
}
IrisPosition rcr = connectorOffset(object, cb, rot);
BlockPosition rcr = connectorOffset(object, cb, rot);
int wcx = connector.wx + connector.facing.x();
int wcy = connector.wy + connector.facing.y();
int wcz = connector.wz + connector.facing.z();
int px = wcx - rcr.getX();
int py = wcy - rcr.getY();
int pz = wcz - rcr.getZ();
int px = wcx - rcr.x();
int py = wcy - rcr.y();
int pz = wcz - rcr.z();
PlacedStructurePiece candidate = build(piece, object, px, py, pz, rot);
PlacedStructurePiece candidate = build(piece, objectKey, object, px, py, pz, rot);
if (!withinRadius(candidate) || collides(placed, candidate)) {
continue;
}
@@ -527,7 +529,7 @@ public final class StructureAssembler {
|| isMatched(matchedExisting, existingPiece, existingConnector)) {
continue;
}
IrisPosition target = connectorTarget(existingPiece, existingConnector);
BlockPosition target = connectorTarget(existingPiece, existingConnector);
if (!contains(candidatePiece, target)) {
continue;
}
@@ -556,7 +558,7 @@ public final class StructureAssembler {
|| normalize(candidateConnector.getPool()).isEmpty()) {
continue;
}
IrisPosition target = connectorTarget(candidatePiece, candidateConnector);
BlockPosition target = connectorTarget(candidatePiece, candidateConnector);
PlacedStructurePiece occupied = containingPiece(placed, target);
if (occupied == null) {
continue;
@@ -706,7 +708,8 @@ public final class StructureAssembler {
if (piece == null || piece.getConnectors() == null) {
continue;
}
IrisObject object = resolver.loadObject(normalize(piece.getObject()));
String objectKey = normalize(piece.getObject());
ObjectFrame object = resolver.loadObject(objectKey);
if (object == null) {
continue;
}
@@ -717,18 +720,19 @@ public final class StructureAssembler {
}
int[] rotations = piece.isRotatable() ? Y_DEGREES : NO_ROTATION;
for (int yDegrees : rotations) {
ObjectTurn rotation = ObjectTurn.of(0, yDegrees, 0);
if (rotation.rotate(connector.getDirection()) != source.facing().reverse()
PieceTurn rotation = PieceTurn.aroundY(yDegrees);
if (rotate(rotation, connector.getDirection()) != source.facing().reverse()
|| source.joint() == JigsawJoint.ALIGNED
&& rotation.rotate(connector.getTop()) != source.top()) {
&& rotate(rotation, connector.getTop()) != source.top()) {
continue;
}
IrisPosition offset = connectorOffset(object, connector, rotation);
int logicalX = source.wx() + source.facing().x() - offset.getX();
int logicalY = source.wy() + source.facing().y() - offset.getY();
int logicalZ = source.wz() + source.facing().z() - offset.getZ();
BlockPosition offset = connectorOffset(object, connector, rotation);
int logicalX = source.wx() + source.facing().x() - offset.x();
int logicalY = source.wy() + source.facing().y() - offset.y();
int logicalZ = source.wz() + source.facing().z() - offset.z();
PlacedStructurePiece reservation = build(
piece,
objectKey,
object,
logicalX,
logicalY,
@@ -749,49 +753,49 @@ public final class StructureAssembler {
PlacedStructurePiece targetPiece,
Set<IrisJigsawConnector> unavailable
) {
IrisPosition target = connectorTarget(sourcePiece, sourceConnector);
IrisDirection sourceFacing = sourcePiece.getRotation().rotate(sourceConnector.getDirection());
IrisDirection sourceTop = sourcePiece.getRotation().rotate(sourceConnector.getTop());
BlockPosition target = connectorTarget(sourcePiece, sourceConnector);
JigsawDirection sourceFacing = rotate(sourcePiece.getRotation(), sourceConnector.getDirection());
JigsawDirection sourceTop = rotate(sourcePiece.getRotation(), sourceConnector.getTop());
for (IrisJigsawConnector candidate : targetPiece.getPiece().getConnectors()) {
if (unavailable.contains(candidate)
|| !Objects.equals(sourceConnector.getChannel(), candidate.getChannel())
|| !Objects.equals(sourceConnector.getTargetName(), candidate.getName())) {
continue;
}
IrisPosition candidatePosition = connectorPosition(targetPiece, candidate);
BlockPosition candidatePosition = connectorPosition(targetPiece, candidate);
if (!target.equals(candidatePosition)
|| targetPiece.getRotation().rotate(candidate.getDirection()) != sourceFacing.reverse()) {
|| rotate(targetPiece.getRotation(), candidate.getDirection()) != sourceFacing.reverse()) {
continue;
}
if (sourceConnector.getJoint() != JigsawJoint.ALIGNED
|| targetPiece.getRotation().rotate(candidate.getTop()) == sourceTop) {
|| rotate(targetPiece.getRotation(), candidate.getTop()) == sourceTop) {
return candidate;
}
}
return null;
}
private IrisPosition connectorPosition(PlacedStructurePiece piece, IrisJigsawConnector connector) {
IrisPosition center = logicalCenter(piece);
IrisPosition offset = connectorOffset(piece.getObject(), connector, piece.getRotation());
return new IrisPosition(
center.getX() + offset.getX(),
center.getY() + offset.getY(),
center.getZ() + offset.getZ());
private BlockPosition connectorPosition(PlacedStructurePiece piece, IrisJigsawConnector connector) {
BlockPosition center = logicalCenter(piece);
BlockPosition offset = connectorOffset(piece.getObject(), connector, piece.getRotation());
return new BlockPosition(
center.x() + offset.x(),
center.y() + offset.y(),
center.z() + offset.z());
}
private IrisPosition connectorTarget(PlacedStructurePiece piece, IrisJigsawConnector connector) {
IrisPosition position = connectorPosition(piece, connector);
IrisDirection facing = piece.getRotation().rotate(connector.getDirection());
return new IrisPosition(
position.getX() + facing.x(),
position.getY() + facing.y(),
position.getZ() + facing.z());
private BlockPosition connectorTarget(PlacedStructurePiece piece, IrisJigsawConnector connector) {
BlockPosition position = connectorPosition(piece, connector);
JigsawDirection facing = rotate(piece.getRotation(), connector.getDirection());
return new BlockPosition(
position.x() + facing.x(),
position.y() + facing.y(),
position.z() + facing.z());
}
private PlacedStructurePiece containingPiece(
KList<PlacedStructurePiece> pieces,
IrisPosition position
BlockPosition position
) {
for (PlacedStructurePiece piece : pieces) {
if (contains(piece, position)) {
@@ -801,10 +805,10 @@ public final class StructureAssembler {
return null;
}
private boolean contains(PlacedStructurePiece piece, IrisPosition position) {
return position.getX() >= piece.getMinX() && position.getX() <= piece.getMaxX()
&& position.getY() >= piece.getMinY() && position.getY() <= piece.getMaxY()
&& position.getZ() >= piece.getMinZ() && position.getZ() <= piece.getMaxZ();
private boolean contains(PlacedStructurePiece piece, BlockPosition position) {
return position.x() >= piece.getMinX() && position.x() <= piece.getMaxX()
&& position.y() >= piece.getMinY() && position.y() <= piece.getMaxY()
&& position.z() >= piece.getMinZ() && position.z() <= piece.getMaxZ();
}
private boolean isMatched(
@@ -824,24 +828,24 @@ public final class StructureAssembler {
int targetY,
int targetZ
) {
requireConnector(candidate, candidatePiece.getObject().getLoadKey());
requireConnector(candidate, candidatePiece.getObjectKey());
if (!Objects.equals(source.channel(), candidate.getChannel())
|| !Objects.equals(source.targetName(), candidate.getName())) {
return false;
}
IrisPosition rotated = connectorOffset(
BlockPosition rotated = connectorOffset(
candidatePiece.getObject(), candidate, candidatePiece.getRotation());
IrisPosition center = logicalCenter(candidatePiece);
if (center.getX() + rotated.getX() != targetX
|| center.getY() + rotated.getY() != targetY
|| center.getZ() + rotated.getZ() != targetZ) {
BlockPosition center = logicalCenter(candidatePiece);
if (center.x() + rotated.x() != targetX
|| center.y() + rotated.y() != targetY
|| center.z() + rotated.z() != targetZ) {
return false;
}
if (candidatePiece.getRotation().rotate(candidate.getDirection()) != source.facing().reverse()) {
if (rotate(candidatePiece.getRotation(), candidate.getDirection()) != source.facing().reverse()) {
return false;
}
return source.joint() != JigsawJoint.ALIGNED
|| candidatePiece.getRotation().rotate(candidate.getTop()) == source.top();
|| rotate(candidatePiece.getRotation(), candidate.getTop()) == source.top();
}
private void registerPlacedPiece(
@@ -890,15 +894,15 @@ public final class StructureAssembler {
Deque<PieceExpansion> pending,
Map<PlacedStructurePiece, Map<IrisJigsawConnector, OpenConnector>> openConnectors,
PlacedStructurePiece p,
IrisObject object, int depth, int pieceDepth, IrisJigsawConnector skip,
ObjectFrame object, int depth, int pieceDepth, IrisJigsawConnector skip,
int placementPriority) {
if (p.getPiece().getConnectors() == null) {
throw assemblyFailure("placed piece for object '" + object.getLoadKey() + "' has no connector list");
throw assemblyFailure("placed piece for object '" + p.getObjectKey() + "' has no connector list");
}
List<OpenConnector> connectors = new ArrayList<>();
Map<IrisJigsawConnector, OpenConnector> definitions = new IdentityHashMap<>();
for (IrisJigsawConnector con : orderedConnectors(p.getPiece().getConnectors(), skip)) {
requireConnector(con, object.getLoadKey());
requireConnector(con, p.getObjectKey());
if (con.getPool() == null || con.getPool().isBlank()) {
continue;
}
@@ -914,21 +918,21 @@ public final class StructureAssembler {
private OpenConnector openConnector(
PlacedStructurePiece piece,
IrisObject object,
ObjectFrame object,
IrisJigsawConnector connector,
int depth,
int pieceDepth
) {
IrisPosition offset = connectorOffset(object, connector, piece.getRotation());
IrisPosition center = logicalCenter(piece);
BlockPosition offset = connectorOffset(object, connector, piece.getRotation());
BlockPosition center = logicalCenter(piece);
return new OpenConnector(
piece,
connector,
center.getX() + offset.getX(),
center.getY() + offset.getY(),
center.getZ() + offset.getZ(),
piece.getRotation().rotate(connector.getDirection()),
piece.getRotation().rotate(connector.getTop()),
center.x() + offset.x(),
center.y() + offset.y(),
center.z() + offset.z(),
rotate(piece.getRotation(), connector.getDirection()),
rotate(piece.getRotation(), connector.getTop()),
normalize(connector.getPool()),
connector.getName(),
connector.getTargetName(),
@@ -968,29 +972,30 @@ public final class StructureAssembler {
throw assemblyFailure("piece expansion queue was unexpectedly empty");
}
private PlacedStructurePiece build(IrisJigsawPiece piece, IrisObject object, int x, int y, int z, ObjectTurn rot) {
int width = Math.max(1, object.getW());
int height = Math.max(1, object.getH());
int depth = Math.max(1, object.getD());
private PlacedStructurePiece build(IrisJigsawPiece piece, String objectKey, ObjectFrame object, int x, int y, int z, PieceTurn rot) {
int width = Math.max(1, object.width());
int height = Math.max(1, object.height());
int depth = Math.max(1, object.depth());
if (structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW) {
IrisPosition dimensions = rotatedDimensions(object, rot);
IrisPosition offset = planarPlacementOffset(object, rot);
int minX = x - dimensions.getX() / 2;
int minY = y - dimensions.getY() / 2;
int minZ = z - dimensions.getZ() / 2;
BlockPosition dimensions = rotatedDimensions(object, rot);
BlockPosition offset = planarPlacementOffset(object, rot);
int minX = x - dimensions.x() / 2;
int minY = y - dimensions.y() / 2;
int minZ = z - dimensions.z() / 2;
return new PlacedStructurePiece(
piece,
objectKey,
object,
x + offset.getX(),
y + offset.getY(),
z + offset.getZ(),
x + offset.x(),
y + offset.y(),
z + offset.z(),
rot,
minX,
minY,
minZ,
minX + dimensions.getX() - 1,
minY + dimensions.getY() - 1,
minZ + dimensions.getZ() - 1);
minX + dimensions.x() - 1,
minY + dimensions.y() - 1,
minZ + dimensions.z() - 1);
}
int localMinX = -(width / 2);
int localMinY = -(height / 2);
@@ -998,15 +1003,15 @@ public final class StructureAssembler {
int localMaxX = localMinX + width - 1;
int localMaxY = localMinY + height - 1;
int localMaxZ = localMinZ + depth - 1;
IrisPosition rotatedMin = rot.rotate(new IrisPosition(localMinX, localMinY, localMinZ));
IrisPosition rotatedMax = rot.rotate(new IrisPosition(localMaxX, localMaxY, localMaxZ));
int minX = Math.min(rotatedMin.getX(), rotatedMax.getX());
int minY = Math.min(rotatedMin.getY(), rotatedMax.getY());
int minZ = Math.min(rotatedMin.getZ(), rotatedMax.getZ());
int maxX = Math.max(rotatedMin.getX(), rotatedMax.getX());
int maxY = Math.max(rotatedMin.getY(), rotatedMax.getY());
int maxZ = Math.max(rotatedMin.getZ(), rotatedMax.getZ());
return new PlacedStructurePiece(piece, object, x, y, z, rot,
BlockPosition rotatedMin = rot.rotate(new BlockPosition(localMinX, localMinY, localMinZ));
BlockPosition rotatedMax = rot.rotate(new BlockPosition(localMaxX, localMaxY, localMaxZ));
int minX = Math.min(rotatedMin.x(), rotatedMax.x());
int minY = Math.min(rotatedMin.y(), rotatedMax.y());
int minZ = Math.min(rotatedMin.z(), rotatedMax.z());
int maxX = Math.max(rotatedMin.x(), rotatedMax.x());
int maxY = Math.max(rotatedMin.y(), rotatedMax.y());
int maxZ = Math.max(rotatedMin.z(), rotatedMax.z());
return new PlacedStructurePiece(piece, objectKey, object, x, y, z, rot,
x + minX, y + minY, z + minZ, x + maxX, y + maxY, z + maxZ);
}
@@ -1041,70 +1046,74 @@ public final class StructureAssembler {
return shuffled;
}
private IrisPosition centerOf(IrisObject object) {
return new IrisPosition(object.getW() / 2, object.getH() / 2, object.getD() / 2);
private BlockPosition centerOf(ObjectFrame object) {
return object.center();
}
private IrisPosition connectorOffset(
IrisObject object,
private BlockPosition connectorOffset(
ObjectFrame object,
IrisJigsawConnector connector,
ObjectTurn rotation
PieceTurn rotation
) {
if (structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW) {
IrisPosition dimensions = rotatedDimensions(object, rotation);
IrisPosition position = IrisJigsawConnector.canonicalPlanarPosition(
BlockPosition dimensions = rotatedDimensions(object, rotation);
BlockPosition position = IrisJigsawConnector.canonicalPlanarPosition(
dimensions,
rotation.rotate(connector.getDirection()));
return new IrisPosition(
position.getX() - dimensions.getX() / 2,
position.getY() - dimensions.getY() / 2,
position.getZ() - dimensions.getZ() / 2);
rotate(rotation, connector.getDirection()));
return new BlockPosition(
position.x() - dimensions.x() / 2,
position.y() - dimensions.y() / 2,
position.z() - dimensions.z() / 2);
}
IrisPosition center = centerOf(object);
IrisPosition relative = new IrisPosition(
connector.getPosition().getX() - center.getX(),
connector.getPosition().getY() - center.getY(),
connector.getPosition().getZ() - center.getZ());
BlockPosition center = centerOf(object);
BlockPosition relative = new BlockPosition(
connector.getPosition().x() - center.x(),
connector.getPosition().y() - center.y(),
connector.getPosition().z() - center.z());
return rotation.rotate(relative);
}
private IrisPosition logicalCenter(PlacedStructurePiece piece) {
private BlockPosition logicalCenter(PlacedStructurePiece piece) {
if (structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW) {
return new IrisPosition(piece.getX(), piece.getY(), piece.getZ());
return new BlockPosition(piece.getX(), piece.getY(), piece.getZ());
}
IrisPosition offset = planarPlacementOffset(piece.getObject(), piece.getRotation());
return new IrisPosition(
piece.getX() - offset.getX(),
piece.getY() - offset.getY(),
piece.getZ() - offset.getZ());
BlockPosition offset = planarPlacementOffset(piece.getObject(), piece.getRotation());
return new BlockPosition(
piece.getX() - offset.x(),
piece.getY() - offset.y(),
piece.getZ() - offset.z());
}
private IrisPosition rotatedDimensions(IrisObject object, ObjectTurn rotation) {
int width = Math.max(1, object.getW());
int height = Math.max(1, object.getH());
int depth = Math.max(1, object.getD());
private BlockPosition rotatedDimensions(ObjectFrame object, PieceTurn rotation) {
int width = Math.max(1, object.width());
int height = Math.max(1, object.height());
int depth = Math.max(1, object.depth());
return quarterTurns(rotation) % 2 == 0
? new IrisPosition(width, height, depth)
: new IrisPosition(depth, height, width);
? new BlockPosition(width, height, depth)
: new BlockPosition(depth, height, width);
}
private IrisPosition planarPlacementOffset(IrisObject object, ObjectTurn rotation) {
int width = Math.max(1, object.getW());
int depth = Math.max(1, object.getD());
private BlockPosition planarPlacementOffset(ObjectFrame object, PieceTurn rotation) {
int width = Math.max(1, object.width());
int depth = Math.max(1, object.depth());
return switch (quarterTurns(rotation)) {
case 0 -> new IrisPosition();
case 1 -> new IrisPosition(0, 0, width % 2 == 0 ? -1 : 0);
case 2 -> new IrisPosition(
case 0 -> new BlockPosition(0, 0, 0);
case 1 -> new BlockPosition(0, 0, width % 2 == 0 ? -1 : 0);
case 2 -> new BlockPosition(
width % 2 == 0 ? -1 : 0,
0,
depth % 2 == 0 ? -1 : 0);
case 3 -> new IrisPosition(depth % 2 == 0 ? -1 : 0, 0, 0);
case 3 -> new BlockPosition(depth % 2 == 0 ? -1 : 0, 0, 0);
default -> throw new IllegalStateException("Unsupported planar quarter-turn count");
};
}
private int quarterTurns(ObjectTurn rotation) {
return switch (rotation.rotate(IrisDirection.NORTH_NEGATIVE_Z)) {
private static JigsawDirection rotate(PieceTurn turn, JigsawDirection direction) {
return direction.turnedBy(turn.quarterTurns());
}
private int quarterTurns(PieceTurn rotation) {
return switch (rotate(rotation, JigsawDirection.NORTH_NEGATIVE_Z)) {
case NORTH_NEGATIVE_Z -> 0;
case WEST_NEGATIVE_X -> 1;
case SOUTH_POSITIVE_Z -> 2;
@@ -1280,7 +1289,7 @@ public final class StructureAssembler {
}
private IllegalStateException assemblyFailure(String detail) {
return new IllegalStateException("Structure '" + structure.getLoadKey() + "' assembly failed: " + detail);
return new IllegalStateException("Structure '" + graph.getStructureKey() + "' assembly failed: " + detail);
}
private static IllegalStateException invalidGraph(StructureGraphCompilation compilation) {
@@ -1300,7 +1309,7 @@ public final class StructureAssembler {
}
private record OpenConnector(PlacedStructurePiece sourcePiece, IrisJigsawConnector sourceConnector,
int wx, int wy, int wz, IrisDirection facing, IrisDirection top,
int wx, int wy, int wz, JigsawDirection facing, JigsawDirection top,
String pool, String name,
String targetName, String channel, JigsawJoint joint, int depth,
int pieceDepth, int placementPriority) {
@@ -1347,7 +1356,7 @@ public final class StructureAssembler {
private record AssemblyOptions(StructureGraphResolver resolver, CompiledStructureGraph graph,
IrisStructure structure,
IrisPosition origin) {
BlockPosition origin) {
private AssemblyOptions {
Objects.requireNonNull(resolver, "Structure assembly resolver must not be null");
Objects.requireNonNull(graph, "Compiled structure graph must not be null");
@@ -0,0 +1,173 @@
/*
* 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.engine.framework.structure;
/**
* A height for each world column (keys packed from X and Z), which only grows. It visits its columns in the order the
* open-addressing table of the primitive map this replaces did, because the order in which a structure's foundations
* are written to the mantle is part of what a world generated: a column map of the standard library would order them
* differently.
*/
public final class ColumnHeights {
private static final long PHI = 0x9E3779B97F4A7C15L;
private static final int INITIAL_SLOTS = 32;
private static final float LOAD_FACTOR = 0.75f;
/** Receives one column and its height. */
@FunctionalInterface
public interface ColumnVisitor {
void visit(long column, int height);
}
private final int missing;
private long[] keys = new long[INITIAL_SLOTS + 1];
private int[] heights = new int[INITIAL_SLOTS + 1];
private int slots = INITIAL_SLOTS;
private int mask = INITIAL_SLOTS - 1;
private int maxFill = maxFill(INITIAL_SLOTS);
private boolean hasColumnZero;
private int size;
/** @param missing what {@link #get} answers for a column that has no height */
public ColumnHeights(int missing) {
this.missing = missing;
}
public int size() {
return size;
}
public boolean containsKey(long column) {
if (column == 0L) {
return hasColumnZero;
}
int slot = slotOf(column);
while (keys[slot] != 0L) {
if (keys[slot] == column) {
return true;
}
slot = (slot + 1) & mask;
}
return false;
}
public int get(long column) {
if (column == 0L) {
return hasColumnZero ? heights[slots] : missing;
}
int slot = slotOf(column);
while (keys[slot] != 0L) {
if (keys[slot] == column) {
return heights[slot];
}
slot = (slot + 1) & mask;
}
return missing;
}
public void put(long column, int height) {
if (column == 0L) {
if (!hasColumnZero) {
hasColumnZero = true;
grow();
}
heights[slots] = height;
return;
}
int slot = slotOf(column);
while (keys[slot] != 0L) {
if (keys[slot] == column) {
heights[slot] = height;
return;
}
slot = (slot + 1) & mask;
}
keys[slot] = column;
heights[slot] = height;
grow();
}
/** Visits the columns in table order: the column 0 first, then the slots from the last to the first. */
public void forEach(ColumnVisitor visitor) {
int remaining = size;
if (hasColumnZero) {
visitor.visit(0L, heights[slots]);
remaining--;
}
for (int slot = slots - 1; slot >= 0 && remaining > 0; slot--) {
if (keys[slot] != 0L) {
visitor.visit(keys[slot], heights[slot]);
remaining--;
}
}
}
private void grow() {
if (size++ >= maxFill) {
rehash(slotsFor(size + 1));
}
}
private void rehash(int newSlots) {
long[] oldKeys = keys;
int[] oldHeights = heights;
int oldSlots = slots;
int newMask = newSlots - 1;
long[] newKeys = new long[newSlots + 1];
int[] newHeights = new int[newSlots + 1];
int source = oldSlots;
for (int remaining = size - (hasColumnZero ? 1 : 0); remaining-- != 0; ) {
while (oldKeys[--source] == 0L) {
continue;
}
int slot = hash(oldKeys[source], newMask);
while (newKeys[slot] != 0L) {
slot = (slot + 1) & newMask;
}
newKeys[slot] = oldKeys[source];
newHeights[slot] = oldHeights[source];
}
newHeights[newSlots] = oldHeights[oldSlots];
keys = newKeys;
heights = newHeights;
slots = newSlots;
mask = newMask;
maxFill = maxFill(newSlots);
}
private int slotOf(long column) {
return hash(column, mask);
}
private static int hash(long column, int tableMask) {
long mixed = column * PHI;
mixed ^= mixed >>> 32;
return (int) (mixed ^ (mixed >>> 16)) & tableMask;
}
private static int maxFill(int tableSlots) {
return Math.min((int) Math.ceil(tableSlots * LOAD_FACTOR), tableSlots - 1);
}
/** The table size for {@code expected} entries: the next power of two of {@code expected / loadFactor}, at least 2. */
private static int slotsFor(int expected) {
long wanted = Math.max(2L, (long) Math.ceil(expected / LOAD_FACTOR));
return (int) Long.highestOneBit(wanted - 1) << 1;
}
}
@@ -2,7 +2,6 @@ package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.structure.IrisStructure;
import java.util.Collections;
@@ -13,14 +12,18 @@ import java.util.Objects;
import java.util.Set;
public final class CompiledStructureGraph {
private static final String UNKEYED = "<unloaded>";
private final String structureKey;
private final IrisStructure structure;
private final Map<String, IrisJigsawPool> pools;
private final Map<String, IrisJigsawPiece> pieces;
private final Map<String, IrisObject> objects;
private final Map<String, ObjectFrame> objects;
private final Set<String> reachablePools;
private final Set<String> reachablePieces;
private CompiledStructureGraph(Builder builder) {
structureKey = builder.structureKey;
structure = builder.structure;
pools = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pools));
pieces = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pieces));
@@ -29,17 +32,17 @@ public final class CompiledStructureGraph {
reachablePieces = Collections.unmodifiableSet(new LinkedHashSet<>(builder.reachablePieces));
}
static Builder builder(IrisStructure structure) {
return new Builder(structure);
static Builder builder(String structureKey, IrisStructure structure) {
return new Builder(structureKey, structure);
}
public IrisStructure getStructure() {
return structure;
}
/** The pack key of the structure, or a placeholder when the graph was compiled for a structure without one. */
public String getStructureKey() {
String key = structure.getLoadKey();
return key == null || key.isBlank() ? "<unloaded>" : key;
return structureKey == null || structureKey.isBlank() ? UNKEYED : structureKey;
}
public Map<String, IrisJigsawPool> getPools() {
@@ -50,7 +53,7 @@ public final class CompiledStructureGraph {
return pieces;
}
public Map<String, IrisObject> getObjects() {
public Map<String, ObjectFrame> getObjects() {
return objects;
}
@@ -63,14 +66,16 @@ public final class CompiledStructureGraph {
}
static final class Builder {
private final String structureKey;
private final IrisStructure structure;
private final Map<String, IrisJigsawPool> pools = new LinkedHashMap<>();
private final Map<String, IrisJigsawPiece> pieces = new LinkedHashMap<>();
private final Map<String, IrisObject> objects = new LinkedHashMap<>();
private final Map<String, ObjectFrame> objects = new LinkedHashMap<>();
private final Set<String> reachablePools = new LinkedHashSet<>();
private final Set<String> reachablePieces = new LinkedHashSet<>();
private Builder(IrisStructure structure) {
private Builder(String structureKey, IrisStructure structure) {
this.structureKey = structureKey;
this.structure = Objects.requireNonNull(structure);
}
@@ -82,7 +87,7 @@ public final class CompiledStructureGraph {
return pieces;
}
Map<String, IrisObject> objects() {
Map<String, ObjectFrame> objects() {
return objects;
}
@@ -1,6 +1,5 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.object.prefab.IrisObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
@@ -23,7 +22,7 @@ public final class IrisObjectFrameReader {
private IrisObjectFrameReader() {
}
public static IrisObject readBounds(InputStream stream, String resourceName) throws IOException {
public static ObjectFrame readBounds(InputStream stream, String resourceName) throws IOException {
String activeResourceName = resourceName == null || resourceName.isBlank()
? "<unknown>" : resourceName;
try {
@@ -41,7 +40,7 @@ public final class IrisObjectFrameReader {
}
}
private static IrisObject readBounds(byte[] content, String resourceName) throws IOException {
private static ObjectFrame readBounds(byte[] content, String resourceName) throws IOException {
ByteArrayInputStream bytes = new ByteArrayInputStream(content);
DataInputStream input = new DataInputStream(bytes);
int width = input.readInt();
@@ -88,7 +87,7 @@ public final class IrisObjectFrameReader {
}
int tileStart = content.length - bytes.available();
requireCompleteTileFraming(content, tileStart, tileCount, width, height, depth, resourceName);
return new IrisObject(width, height, depth);
return new ObjectFrame(width, height, depth);
}
private static void requireCompleteTileFraming(
@@ -0,0 +1,107 @@
/*
* 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.engine.framework.structure;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.framework.StructureAssembler;
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.iris.engine.framework.structure.assembly.StructureStamp;
import art.arcane.iris.engine.framework.structure.assembly.Viability;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
/**
* How {@code iris:jigsaw} builds the structures of the pack's {@code structures} folder: it assembles them from their
* jigsaw pools and pieces ({@link StructureAssembler}) and tells the placement how they are stamped. It knows exactly the
* structures the pack has a structure file for.
*/
public final class JigsawStructureAssembly implements StructureAssembly {
private final ModuleLog log;
public JigsawStructureAssembly(ModuleLog log) {
this.log = Objects.requireNonNull(log, "log");
}
@Override
public boolean knows(PackResources pack, ResourceId structure) {
return structureOf(pack, structure) != null;
}
@Override
public OptionalInt reachChunks(PackResources pack, ResourceId structure) {
IrisStructure known = structureOf(pack, structure);
return known == null ? OptionalInt.empty() : OptionalInt.of(known.getMaxSizeChunks());
}
@Override
public Optional<StructureStamp> stamp(PackResources pack, ResourceId structure) {
IrisStructure known = structureOf(pack, structure);
if (known == null) {
return Optional.empty();
}
List<String> loot = known.getLoot() == null ? List.of()
: known.getLoot().stream().filter(table -> table != null && !table.isBlank()).toList();
return Optional.of(new StructureStamp(known.getPlaceMode(), known.getEdit(), loot,
known.getVanillaSource() == null ? "" : known.getVanillaSource()));
}
@Override
public Viability viability(PackResources pack, ResourceId structure) {
IrisStructure known = structureOf(pack, structure);
if (known == null) {
return Viability.NOT_VIABLE;
}
String key = structure.path();
if (!StructureGraphCatalog.compile(pack, key, known, log).isAssemblyViable()) {
return Viability.NOT_VIABLE;
}
return StructureGraphCatalog.guaranteesRuntimeOutput(pack, key, known, log) ? Viability.GUARANTEED : Viability.VIABLE;
}
@Override
public Optional<Assembly> assemble(PackResources pack, ResourceId structure, BlockPosition origin, RNG random) {
IrisStructure known = structureOf(pack, structure);
if (known == null) {
return Optional.empty();
}
StructureAssemblyResult result = StructureAssembler.forPack(pack, structure.path(), known, origin, log).assemble(random);
return Optional.of(new Assembly(result.status(), result.detail(), result.pieces().stream()
.map(piece -> assembled(pack, piece)).toList()));
}
private static AssembledPiece assembled(PackResources pack, PlacedStructurePiece piece) {
return new AssembledPiece(pack.idOf(piece.getObjectKey()), piece.getX(), piece.getY(), piece.getZ(), piece.getRotation(),
piece.getMinX(), piece.getMinY(), piece.getMinZ(), piece.getMaxX(), piece.getMaxY(), piece.getMaxZ());
}
private static IrisStructure structureOf(PackResources pack, ResourceId structure) {
return StructureResources.structure(pack, structure.path());
}
}
@@ -20,7 +20,6 @@ package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.core.pack.PackValidationIo;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import com.volmit.validation.Problem;
@@ -77,14 +76,14 @@ public final class NativeReplacementValidation {
if (!resourceFolder.isDirectory()) {
continue;
}
List<File> resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder);
List<File> resourceFiles = PackJsonFiles.listRecursive(resourceFolder);
resourceFiles.sort(Comparator.comparing(File::getPath));
for (File resourceFile : resourceFiles) {
JSONObject resource = PackValidationIo.readJson(resourceFile);
JSONObject resource = PackJsonFiles.read(resourceFile);
if (resource == null) {
continue;
}
String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile);
String resourceKey = PackJsonFiles.keyOf(resourceFolder, resourceFile);
Subject file = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION);
for (String error : validateResource(folderName, resourceKey, resource, structures, viableStructures, verticalEnvelopes)) {
problems.add(Problem.error(file, error));
@@ -97,10 +96,10 @@ public final class NativeReplacementValidation {
private static Map<String, JSONObject> readStructures(File packFolder) {
File structuresFolder = new File(packFolder, StructureResources.STRUCTURES.folder());
Map<String, JSONObject> structures = new HashMap<>();
for (File structureFile : PackValidationIo.listJsonRecursive(structuresFolder)) {
JSONObject structure = PackValidationIo.readJson(structureFile);
for (File structureFile : PackJsonFiles.listRecursive(structuresFolder)) {
JSONObject structure = PackJsonFiles.read(structureFile);
if (structure != null) {
structures.put(PackValidationIo.deriveKey(structuresFolder, structureFile), structure);
structures.put(PackJsonFiles.keyOf(structuresFolder, structureFile), structure);
}
}
return structures;
@@ -0,0 +1,37 @@
/*
* 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.engine.framework.structure;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
/**
* The declared size of a pack object, which is all a jigsaw graph reads of it: connectors are placed against the size, and
* its center, which the object's offsets count from, is half the size.
*/
public record ObjectFrame(int width, int height, int depth) {
public static ObjectFrame of(BlockBox size) {
return new ObjectFrame(size.maxX() - size.minX(), size.maxY() - size.minY(), size.maxZ() - size.minZ());
}
/** 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,68 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure;
import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/** The JSON files of a pack folder as written, for the checks that read values the host would have read as defaults. */
final class PackJsonFiles {
private static final String JSON_EXTENSION = ".json";
private PackJsonFiles() {
}
/** Every {@code .json} file below {@code root}, in no particular order; none when it cannot be listed. */
static List<File> listRecursive(File root) {
List<File> files = new ArrayList<>();
try (Stream<Path> walk = Files.walk(root.toPath())) {
walk.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(JSON_EXTENSION))
.forEach(path -> files.add(path.toFile()));
} catch (Throwable ignored) {
return files;
}
return files;
}
/** The JSON object {@code file} holds, or null when it cannot be read or parsed. */
static JSONObject read(File file) {
try {
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8));
} catch (java.io.IOException | RuntimeException unreadable) {
return null;
}
}
/** The key of {@code file} in {@code folder}: its path below it without {@code .json}, or null for other files. */
static String keyOf(File folder, File file) {
String relative = folder.toPath().relativize(file.toPath()).toString().replace(File.separatorChar, '/');
if (!relative.endsWith(JSON_EXTENSION)) {
return null;
}
return relative.substring(0, relative.length() - JSON_EXTENSION.length());
}
}
@@ -3,9 +3,8 @@ package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import com.volmit.geometry.BlockPosition;
import java.util.Collections;
import java.util.EnumMap;
@@ -27,16 +26,16 @@ public final class PlanarJigsawWorkcellResolver {
EnumMap<IrisJigsawWorkcellArchetype, ResolvedWorkcell> resolved =
new EnumMap<>(IrisJigsawWorkcellArchetype.class);
if (source.getPlanarWorkcells() == null || source.getPlanarWorkcells().isEmpty()) {
IrisPosition fallback = source.getCellSize() == null
? new IrisPosition(DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE)
BlockPosition fallback = source.getCellSize() == null
? new BlockPosition(DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE)
: source.getCellSize();
for (IrisJigsawWorkcellArchetype archetype : IrisJigsawWorkcellArchetype.values()) {
ResolvedWorkcell workcell = new ResolvedWorkcell(
archetype,
"",
fallback.getX(),
fallback.getY(),
fallback.getZ(),
fallback.x(),
fallback.y(),
fallback.z(),
true);
validate(workcell);
resolved.put(archetype, workcell);
@@ -86,14 +85,14 @@ public final class PlanarJigsawWorkcellResolver {
return workcell;
}
public static IrisPosition canonicalDimensions(IrisJigsawPiece piece, IrisObject object) {
public static BlockPosition canonicalDimensions(IrisJigsawPiece piece, ObjectFrame object) {
IrisJigsawPiece sourcePiece = Objects.requireNonNull(piece, "Planar jigsaw piece");
IrisObject sourceObject = Objects.requireNonNull(object, "Planar jigsaw object");
ObjectFrame sourceObject = Objects.requireNonNull(object, "Planar jigsaw object");
IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.fromPiece(sourcePiece);
int quarterTurns = archetype.sourceToCanonicalQuarterTurns(sourcePiece);
return Math.floorMod(quarterTurns, 2) == 0
? new IrisPosition(sourceObject.getW(), sourceObject.getH(), sourceObject.getD())
: new IrisPosition(sourceObject.getD(), sourceObject.getH(), sourceObject.getW());
? new BlockPosition(sourceObject.width(), sourceObject.height(), sourceObject.depth())
: new BlockPosition(sourceObject.depth(), sourceObject.height(), sourceObject.width());
}
public record ResolvedWorkcell(
@@ -109,13 +108,13 @@ public final class PlanarJigsawWorkcellResolver {
displayName = normalizeDisplayName(displayName);
}
public IrisPosition dimensions() {
return new IrisPosition(width, height, depth);
public BlockPosition dimensions() {
return new BlockPosition(width, height, depth);
}
public boolean contains(IrisPosition dimensions) {
IrisPosition size = Objects.requireNonNull(dimensions, "Planar jigsaw object dimensions");
return size.getX() <= width && size.getY() <= height && size.getZ() <= depth;
public boolean contains(BlockPosition dimensions) {
BlockPosition size = Objects.requireNonNull(dimensions, "Planar jigsaw object dimensions");
return size.x() <= width && size.y() <= height && size.z() <= depth;
}
}
@@ -1,70 +1,69 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.IrisPackResources;
import art.arcane.iris.engine.framework.StructureAssembler;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.volmlib.util.math.RNG;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.volmit.ModuleLog;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.PackResources;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Compiled structure graphs, kept per resource snapshot of the pack: every reload of the pack's resources starts a new
* snapshot ({@link IrisData#getPackResources()}), so nothing stale is ever read and nothing is invalidated by hand.
* snapshot ({@link PackResources#snapshotId()}), so nothing stale is ever read and nothing is invalidated by hand.
*/
public final class StructureGraphCatalog {
private static final Cache<IrisPackResources, ConcurrentMap<String, StructureGraphCompilation>> CACHE =
Caffeine.newBuilder().weakKeys().build();
private static final Cache<IrisPackResources, ConcurrentMap<String, Boolean>> RUNTIME_OUTPUT =
Caffeine.newBuilder().weakKeys().build();
private static final Map<PackResources, ConcurrentMap<String, StructureGraphCompilation>> CACHE =
Collections.synchronizedMap(new WeakHashMap<>());
private static final Map<PackResources, ConcurrentMap<String, Boolean>> RUNTIME_OUTPUT =
Collections.synchronizedMap(new WeakHashMap<>());
private static final BlockPosition SAMPLE_ORIGIN = new BlockPosition(0, 64, 0);
private static final List<Long> RUNTIME_SAMPLE_SEEDS = List.of(
0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L);
private StructureGraphCatalog() {
}
public static StructureGraphCompilation compile(IrisData data, IrisStructure structure, ModuleLog log) {
IrisData activeData = Objects.requireNonNull(data);
/** The compilation of {@code structure}, the pack's structure {@code structureKey} (blank for one that is not in the pack, which is not kept). */
public static StructureGraphCompilation compile(PackResources pack, String structureKey, IrisStructure structure, ModuleLog log) {
PackResources activePack = Objects.requireNonNull(pack);
IrisStructure activeStructure = Objects.requireNonNull(structure);
String structureKey = activeStructure.getLoadKey();
if (structureKey == null || structureKey.isBlank()) {
return compileAndReport(activeData, activeStructure, log);
return compileAndReport(activePack, structureKey, activeStructure, log);
}
ConcurrentMap<String, StructureGraphCompilation> catalog = CACHE.get(
activeData.getPackResources(), ignored -> new ConcurrentHashMap<>());
return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure, log));
ConcurrentMap<String, StructureGraphCompilation> catalog = CACHE.computeIfAbsent(
activePack, ignored -> new ConcurrentHashMap<>());
return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activePack, structureKey, activeStructure, log));
}
public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure, ModuleLog log) {
IrisData activeData = Objects.requireNonNull(data);
public static boolean guaranteesRuntimeOutput(PackResources pack, String structureKey, IrisStructure structure, ModuleLog log) {
PackResources activePack = Objects.requireNonNull(pack);
IrisStructure activeStructure = Objects.requireNonNull(structure);
if (!compile(activeData, activeStructure, log).guaranteesAssemblyOutput()) {
if (!compile(activePack, structureKey, activeStructure, log).guaranteesAssemblyOutput()) {
return false;
}
String structureKey = activeStructure.getLoadKey();
if (structureKey == null || structureKey.isBlank()) {
return sampleRuntimeAssembly(activeData, activeStructure, log);
return sampleRuntimeAssembly(activePack, structureKey, activeStructure, log);
}
ConcurrentMap<String, Boolean> catalog = RUNTIME_OUTPUT.get(
activeData.getPackResources(), ignored -> new ConcurrentHashMap<>());
ConcurrentMap<String, Boolean> catalog = RUNTIME_OUTPUT.computeIfAbsent(
activePack, ignored -> new ConcurrentHashMap<>());
return catalog.computeIfAbsent(
structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure, log));
structureKey, ignored -> sampleRuntimeAssembly(activePack, structureKey, activeStructure, log));
}
private static StructureGraphCompilation compileAndReport(IrisData data, IrisStructure structure, ModuleLog log) {
private static StructureGraphCompilation compileAndReport(PackResources pack, String structureKey, IrisStructure structure, ModuleLog log) {
StructureGraphCompilation compilation = StructureGraphCompiler.compile(
structure, StructureGraphResolver.forData(data));
String structureKey = structure.getLoadKey() == null || structure.getLoadKey().isBlank()
? "<unkeyed>" : structure.getLoadKey();
structureKey, structure, StructureGraphResolver.forPack(pack));
String reportedKey = structureKey == null || structureKey.isBlank() ? "<unkeyed>" : structureKey;
for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) {
String message = "[StructureGraph:" + structureKey + "] " + diagnostic.message();
String message = "[StructureGraph:" + reportedKey + "] " + diagnostic.message();
if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) {
log.error(message, null);
} else {
@@ -72,17 +71,16 @@ public final class StructureGraphCatalog {
}
}
if (!compilation.isAssemblyViable()) {
log.error("[StructureGraph:" + structureKey
log.error("[StructureGraph:" + reportedKey
+ "] Graph rejected because deterministic assembly did not complete.", null);
}
return compilation;
}
private static boolean sampleRuntimeAssembly(IrisData data, IrisStructure structure, ModuleLog log) {
private static boolean sampleRuntimeAssembly(PackResources pack, String structureKey, IrisStructure structure, ModuleLog log) {
for (long seed : RUNTIME_SAMPLE_SEEDS) {
try {
StructureAssembler assembler = StructureAssembler.forData(
data, structure, new IrisPosition(0, 64, 0), log);
StructureAssembler assembler = StructureAssembler.forPack(pack, structureKey, structure, SAMPLE_ORIGIN, log);
StructureAssemblyResult result = assembler.assemble(new RNG(seed));
if (!result.hasOutput()) {
return false;
@@ -6,7 +6,6 @@ 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.IrisJigsawThemeSet;
import art.arcane.iris.engine.object.prefab.IrisObject;
import java.util.ArrayList;
import java.util.Collections;
@@ -96,7 +95,7 @@ public final class StructureGraphCompilation {
if (piece == null || !JigsawPoolSelection.pieceEligible(piece, theme, 0, 0)) {
continue;
}
IrisObject object = graph.getObjects().get(normalize(piece.getObject()));
ObjectFrame object = graph.getObjects().get(normalize(piece.getObject()));
if (object == null || !fitsStartRadius(object)) {
return false;
}
@@ -185,9 +184,9 @@ public final class StructureGraphCompilation {
return false;
}
private boolean fitsStartRadius(IrisObject object) {
private boolean fitsStartRadius(ObjectFrame object) {
long radius = (long) graph.getStructure().getMaxSizeChunks() * 16L;
return axisFitsRadius(object.getW(), radius) && axisFitsRadius(object.getD(), radius);
return axisFitsRadius(object.width(), radius) && axisFitsRadius(object.depth(), radius);
}
private List<String> themes() {
@@ -2,7 +2,7 @@ package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.framework.StructureAssembler;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection;
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.IrisJigsawConnector;
@@ -13,12 +13,11 @@ 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.IrisJigsawWorkcellArchetype;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.geometry.BlockPosition;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -44,9 +43,10 @@ public final class StructureGraphCompiler {
private StructureGraphCompiler() {
}
public static StructureGraphCompilation compile(IrisStructure structure, StructureGraphResolver resolver) {
/** @param structureKey the pack key of {@code structure}, which the diagnostics name it by; blank for one without a key */
public static StructureGraphCompilation compile(String structureKey, IrisStructure structure, StructureGraphResolver resolver) {
CompilationState state = new CompilationState(
Objects.requireNonNull(structure), Objects.requireNonNull(resolver));
structureKey, Objects.requireNonNull(structure), Objects.requireNonNull(resolver));
state.loadClosure();
state.detectFallbackCycles();
state.analyzeReachability();
@@ -66,6 +66,7 @@ public final class StructureGraphCompiler {
}
private static final class CompilationState {
private final String structureKey;
private final IrisStructure structure;
private final StructureGraphResolver resolver;
private final CompiledStructureGraph.Builder graph;
@@ -89,10 +90,11 @@ public final class StructureGraphCompiler {
private Map<IrisJigsawWorkcellArchetype, PlanarJigsawWorkcellResolver.ResolvedWorkcell>
planarWorkcells = Map.of();
private CompilationState(IrisStructure structure, StructureGraphResolver resolver) {
private CompilationState(String structureKey, IrisStructure structure, StructureGraphResolver resolver) {
this.structureKey = structureKey;
this.structure = structure;
this.resolver = resolver;
this.graph = CompiledStructureGraph.builder(structure);
this.graph = CompiledStructureGraph.builder(structureKey, structure);
}
private void loadClosure() {
@@ -145,7 +147,7 @@ public final class StructureGraphCompiler {
}
private void validateThemes() {
KList<IrisJigsawThemeSet> themeSets = structure.getThemeSets();
List<IrisJigsawThemeSet> themeSets = structure.getThemeSets();
if (themeSets == null) {
addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME,
"Structure '" + structureKey() + "' declares a null themeSets list.",
@@ -235,7 +237,7 @@ public final class StructureGraphCompiler {
graph.pools().put(key, pool);
List<PoolEntryReference> entries = new ArrayList<>();
poolEntries.put(key, entries);
KList<IrisJigsawPieceEntry> configuredEntries = pool.getPieces();
List<IrisJigsawPieceEntry> configuredEntries = pool.getPieces();
if (configuredEntries == null || configuredEntries.isEmpty()) {
if (key.equals(normalize(structure.getStartPool()))) {
addDiagnostic(StructureGraphDiagnostic.Code.EMPTY_START_POOL,
@@ -339,13 +341,13 @@ public final class StructureGraphCompiler {
}
graph.pieces().put(key, piece);
IrisObject object = loadPieceObject(key, piece);
ObjectFrame object = loadPieceObject(key, piece);
validatePieceMetadata(key, piece);
scanConnectors(key, piece, object);
}
private void validatePieceMetadata(String pieceKey, IrisJigsawPiece piece) {
KList<String> themes = piece.getThemes();
List<String> themes = piece.getThemes();
if (themes == null) {
addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME,
"Jigsaw piece '" + pieceKey + "' declares a null themes list.",
@@ -419,7 +421,7 @@ public final class StructureGraphCompiler {
&& !rules.isTerminal();
}
private IrisObject loadPieceObject(String pieceKey, IrisJigsawPiece piece) {
private ObjectFrame loadPieceObject(String pieceKey, IrisJigsawPiece piece) {
String objectKey = normalize(piece.getObject());
pieceObjects.put(pieceKey, objectKey);
if (objectKey.isEmpty()) {
@@ -438,7 +440,7 @@ public final class StructureGraphCompiler {
return graph.objects().get(objectKey);
}
IrisObject object = resolver.loadObject(objectKey);
ObjectFrame object = resolver.loadObject(objectKey);
if (object == null) {
missingObjects.add(objectKey);
addDiagnostic(StructureGraphDiagnostic.Code.MISSING_OBJECT,
@@ -447,20 +449,20 @@ public final class StructureGraphCompiler {
return null;
}
graph.objects().put(objectKey, object);
if (object.getW() < 1 || object.getH() < 1 || object.getD() < 1) {
if (object.width() < 1 || object.height() < 1 || object.depth() < 1) {
addDiagnostic(StructureGraphDiagnostic.Code.INVALID_OBJECT_BOUNDS,
"Object '" + objectKey + "' used by jigsaw piece '" + pieceKey
+ "' has invalid dimensions " + object.getW() + "x" + object.getH() + "x"
+ object.getD() + ".",
+ "' has invalid dimensions " + object.width() + "x" + object.height() + "x"
+ object.depth() + ".",
"object-bounds:" + objectKey);
}
return object;
}
private void scanConnectors(String pieceKey, IrisJigsawPiece piece, IrisObject object) {
private void scanConnectors(String pieceKey, IrisJigsawPiece piece, ObjectFrame object) {
List<ConnectorReference> references = new ArrayList<>();
pieceConnectors.put(pieceKey, references);
KList<IrisJigsawConnector> connectors = piece.getConnectors();
List<IrisJigsawConnector> connectors = piece.getConnectors();
if (connectors == null) {
addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR,
"Jigsaw piece '" + pieceKey + "' declares a null connector list.",
@@ -552,7 +554,7 @@ public final class StructureGraphCompiler {
}
private boolean validatePlanarConnector(String pieceKey, int index, IrisJigsawConnector connector,
IrisObject object, boolean validDirection, boolean validTop,
ObjectFrame object, boolean validDirection, boolean validTop,
boolean validPosition) {
if (structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW) {
return true;
@@ -568,7 +570,7 @@ public final class StructureGraphCompiler {
"connector:planar-direction:" + pieceKey + ":" + index);
valid = false;
}
if (validTop && connector.getTop() != IrisDirection.UP_POSITIVE_Y) {
if (validTop && connector.getTop() != JigsawDirection.UP_POSITIVE_Y) {
addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_CONNECTOR,
"Jigsaw piece '" + pieceKey + "' connectors[" + index + "] has top "
+ connector.getTop().name()
@@ -582,8 +584,8 @@ public final class StructureGraphCompiler {
|| object == null || !validPosition) {
return valid;
}
IrisPosition objectSize = new IrisPosition(object.getW(), object.getH(), object.getD());
IrisPosition expected = IrisJigsawConnector.canonicalPlanarPosition(
BlockPosition objectSize = new BlockPosition(object.width(), object.height(), object.depth());
BlockPosition expected = IrisJigsawConnector.canonicalPlanarPosition(
objectSize, connector.getDirection());
if (!expected.equals(connector.getPosition())) {
addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_CONNECTOR,
@@ -596,7 +598,7 @@ public final class StructureGraphCompiler {
return valid;
}
private String invalidPositionMessage(String pieceKey, int index, IrisPosition position, IrisObject object) {
private String invalidPositionMessage(String pieceKey, int index, BlockPosition position, ObjectFrame object) {
if (position == null) {
return "Jigsaw piece '" + pieceKey + "' connectors[" + index
+ "] does not declare a position.";
@@ -606,17 +608,17 @@ public final class StructureGraphCompiler {
+ "] position " + position + " cannot be checked because its object is missing.";
}
return "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] position " + position
+ " is outside object bounds 0.." + (object.getW() - 1) + ", 0.." + (object.getH() - 1)
+ ", 0.." + (object.getD() - 1) + ".";
+ " is outside object bounds 0.." + (object.width() - 1) + ", 0.." + (object.height() - 1)
+ ", 0.." + (object.depth() - 1) + ".";
}
private boolean isValidPosition(IrisPosition position, IrisObject object) {
private boolean isValidPosition(BlockPosition position, ObjectFrame object) {
if (position == null || object == null) {
return false;
}
return position.getX() >= 0 && position.getX() < object.getW()
&& position.getY() >= 0 && position.getY() < object.getH()
&& position.getZ() >= 0 && position.getZ() < object.getD();
return position.x() >= 0 && position.x() < object.width()
&& position.y() >= 0 && position.y() < object.height()
&& position.z() >= 0 && position.z() < object.depth();
}
private void detectFallbackCycles() {
@@ -785,21 +787,21 @@ public final class StructureGraphCompiler {
for (String pieceKey : graph.reachablePieces()) {
IrisJigsawPiece piece = graph.pieces().get(pieceKey);
String objectKey = pieceObjects.get(pieceKey);
IrisObject object = graph.objects().get(objectKey);
ObjectFrame object = graph.objects().get(objectKey);
if (piece == null || object == null) {
continue;
}
PlanarJigsawWorkcellResolver.ResolvedWorkcell workcell =
PlanarJigsawWorkcellResolver.workcell(planarWorkcells, piece);
IrisPosition dimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(piece, object);
BlockPosition dimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(piece, object);
if (workcell.contains(dimensions)) {
continue;
}
addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_OBJECT_SIZE,
"Object '" + objectKey + "' used by reachable planar piece '" + pieceKey
+ "' is " + object.getW() + "x" + object.getH() + "x" + object.getD()
+ " and canonically occupies " + dimensions.getX() + "x" + dimensions.getY()
+ "x" + dimensions.getZ() + "; it does not fit " + workcell.archetype()
+ "' is " + object.width() + "x" + object.height() + "x" + object.depth()
+ " and canonically occupies " + dimensions.x() + "x" + dimensions.y()
+ "x" + dimensions.z() + "; it does not fit " + workcell.archetype()
+ " workcell " + workcell.width() + "x" + workcell.height() + "x"
+ workcell.depth() + ".",
"object:planar-size:" + pieceKey);
@@ -985,9 +987,9 @@ public final class StructureGraphCompiler {
return false;
}
IrisDirection sourceDirection = rotateDirection(
JigsawDirection sourceDirection = rotateDirection(
sourceConnector.getDirection(), source.rotation());
IrisDirection candidateDirection = rotateDirection(
JigsawDirection candidateDirection = rotateDirection(
candidateConnector.getDirection(), candidateRotation);
if (candidateDirection != sourceDirection.reverse()) {
return false;
@@ -995,8 +997,8 @@ public final class StructureGraphCompiler {
if (sourceConnector.getJoint() != JigsawJoint.ALIGNED) {
return true;
}
IrisDirection sourceTop = rotateDirection(sourceConnector.getTop(), source.rotation());
IrisDirection candidateTop = rotateDirection(candidateConnector.getTop(), candidateRotation);
JigsawDirection sourceTop = rotateDirection(sourceConnector.getTop(), source.rotation());
JigsawDirection candidateTop = rotateDirection(candidateConnector.getTop(), candidateRotation);
return candidateTop == sourceTop;
}
@@ -1116,7 +1118,7 @@ public final class StructureGraphCompiler {
for (long seed : ASSEMBLY_SEEDS) {
try {
StructureAssembler assembler = StructureAssembler.forCompilation(
compilation, new IrisPosition(0, 64, 0));
compilation, new BlockPosition(0, 64, 0));
StructureAssemblyResult result = assembler.assemble(new RNG(seed));
List<String> pieces = new ArrayList<>(result.pieces().size());
for (PlacedStructurePiece placed : result.pieces()) {
@@ -1175,8 +1177,7 @@ public final class StructureGraphCompiler {
}
private String structureKey() {
String key = structure.getLoadKey();
return key == null || key.isBlank() ? "<unloaded>" : key;
return structureKey == null || structureKey.isBlank() ? "<unloaded>" : structureKey;
}
}
@@ -1188,18 +1189,18 @@ public final class StructureGraphCompiler {
return piece.isRotatable() ? Y_ROTATIONS : NO_ROTATION;
}
private static IrisDirection rotateDirection(IrisDirection direction, int degrees) {
private static JigsawDirection rotateDirection(JigsawDirection direction, int degrees) {
if (direction.isVertical()) {
return direction;
}
int turns = Math.floorMod(degrees, 360) / 90;
IrisDirection rotated = direction;
JigsawDirection rotated = direction;
for (int turn = 0; turn < turns; turn++) {
rotated = switch (rotated) {
case NORTH_NEGATIVE_Z -> IrisDirection.WEST_NEGATIVE_X;
case WEST_NEGATIVE_X -> IrisDirection.SOUTH_POSITIVE_Z;
case SOUTH_POSITIVE_Z -> IrisDirection.EAST_POSITIVE_X;
case EAST_POSITIVE_X -> IrisDirection.NORTH_NEGATIVE_Z;
case NORTH_NEGATIVE_Z -> JigsawDirection.WEST_NEGATIVE_X;
case WEST_NEGATIVE_X -> JigsawDirection.SOUTH_POSITIVE_Z;
case SOUTH_POSITIVE_Z -> JigsawDirection.EAST_POSITIVE_X;
case EAST_POSITIVE_X -> JigsawDirection.NORTH_NEGATIVE_Z;
case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> rotated;
};
}
@@ -1,9 +1,8 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.prefab.IrisObject;
import com.volmit.resource.PackResources;
import java.util.Objects;
@@ -12,10 +11,11 @@ public interface StructureGraphResolver {
IrisJigsawPiece loadPiece(String key);
IrisObject loadObject(String key);
/** The declared size of the pack object {@code key} names; null when the pack has none. */
ObjectFrame loadObject(String key);
static StructureGraphResolver forData(IrisData data) {
return new IrisDataStructureGraphResolver(Objects.requireNonNull(data));
static StructureGraphResolver forPack(PackResources pack) {
return new PackStructureGraphResolver(Objects.requireNonNull(pack));
}
static StructureGraphResolver forCompiledGraph(CompiledStructureGraph graph) {
@@ -23,26 +23,29 @@ public interface StructureGraphResolver {
}
}
final class IrisDataStructureGraphResolver implements StructureGraphResolver {
private final IrisData data;
final class PackStructureGraphResolver implements StructureGraphResolver {
private final PackResources pack;
IrisDataStructureGraphResolver(IrisData data) {
this.data = data;
PackStructureGraphResolver(PackResources pack) {
this.pack = pack;
}
@Override
public IrisJigsawPool loadPool(String key) {
return StructureResources.pool(data.getPackResources(), key);
return StructureResources.pool(pack, key);
}
@Override
public IrisJigsawPiece loadPiece(String key) {
return StructureResources.piece(data.getPackResources(), key);
return StructureResources.piece(pack, key);
}
@Override
public IrisObject loadObject(String key) {
return data.load(IrisObject.class, key, false);
public ObjectFrame loadObject(String key) {
if (key == null || key.isBlank()) {
return null;
}
return pack.objects().sizeOf(pack.idOf(key)).map(ObjectFrame::of).orElse(null);
}
}
@@ -64,7 +67,7 @@ final class CompiledStructureGraphResolver implements StructureGraphResolver {
}
@Override
public IrisObject loadObject(String key) {
public ObjectFrame loadObject(String key) {
return graph.getObjects().get(normalize(key));
}
@@ -18,21 +18,21 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.framework.StructureAssembler;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.value.IrisPosition;
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.validation.Problem;
import com.volmit.validation.Severity;
import com.volmit.validation.Subject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -65,43 +65,43 @@ public final class StructureGraphValidation {
private StructureGraphValidation() {
}
/** Checks every structure of the pack {@code data} holds. */
public static Validation validate(IrisData data) {
return validate(data, null);
/** Checks every structure of {@code pack}, whose objects are the files below {@code packFolder}. */
public static Validation validate(PackResources pack, File packFolder) {
return validate(pack, packFolder, null);
}
/** Checks the structures of the pack {@code data} holds whose keys are in {@code activeStructureKeys}, or all when it is null. */
public static Validation validate(IrisData data, Set<String> activeStructureKeys) {
/** Checks the structures of {@code pack} whose keys are in {@code activeStructureKeys}, or all when it is null. */
public static Validation validate(PackResources pack, File packFolder, Set<String> activeStructureKeys) {
List<Problem> problems = new ArrayList<>();
Set<String> replacementOutputStructures = new LinkedHashSet<>();
Map<String, List<SampledVerticalEnvelope>> sampledVerticalEnvelopes = new LinkedHashMap<>();
PackStructureResolver resolver = new PackStructureResolver(data);
for (ResourceId id : data.getPackResources().ids(StructureResources.STRUCTURES)) {
PackStructureResolver resolver = new PackStructureResolver(pack, packFolder);
for (ResourceId id : pack.ids(StructureResources.STRUCTURES)) {
String structureKey = id.path();
if (activeStructureKeys != null && !activeStructureKeys.contains(structureKey)) {
continue;
}
IrisStructure structure = StructureResources.structure(data.getPackResources(), structureKey);
IrisStructure structure = StructureResources.structure(pack, structureKey);
if (structure == null) {
continue;
}
validateStructure(structure, resolver, problems, replacementOutputStructures, sampledVerticalEnvelopes);
validateStructure(structureKey, structure, resolver, problems, replacementOutputStructures, sampledVerticalEnvelopes);
}
return new Validation(problems, replacementOutputStructures, sampledVerticalEnvelopes);
}
private static void validateStructure(
String structureKey,
IrisStructure structure,
StructureGraphResolver resolver,
List<Problem> problems,
Set<String> replacementOutputStructures,
Map<String, List<SampledVerticalEnvelope>> sampledVerticalEnvelopes
) {
String structureKey = structure.getLoadKey();
Subject file = Subject.file(StructureResources.STRUCTURES.folder() + "/" + structureKey + JSON_EXTENSION);
StructureGraphCompilation compilation;
try {
compilation = StructureGraphCompiler.compile(structure, resolver);
compilation = StructureGraphCompiler.compile(structureKey, structure, resolver);
} catch (MalformedObjectResourceException e) {
problems.add(Problem.error(file, e.getMessage()));
return;
@@ -139,7 +139,7 @@ public final class StructureGraphValidation {
for (long seed : GEOMETRY_SAMPLE_SEEDS) {
try {
StructureAssembler assembler = StructureAssembler.forCompilation(
compilation, new IrisPosition(0, GEOMETRY_SAMPLE_ORIGIN_Y, 0));
compilation, new BlockPosition(0, GEOMETRY_SAMPLE_ORIGIN_Y, 0));
StructureAssemblyResult result = assembler.assemble(new RNG(seed));
if (result.status().isFailure()) {
failures.add("seed " + seed + " returned " + result.status() + ": " + result.detail());
@@ -257,28 +257,28 @@ public final class StructureGraphValidation {
/** Pools and pieces from the pack's structure resources; objects as far as their bounds, read from their files once each. */
private static final class PackStructureResolver implements StructureGraphResolver {
private final IrisData data;
private final PackResources pack;
private final Path objectsRoot;
private final Map<String, IrisObject> objects = new HashMap<>();
private final Map<String, ObjectFrame> objects = new HashMap<>();
private final Set<String> missingObjects = new LinkedHashSet<>();
private PackStructureResolver(IrisData data) {
this.data = data;
this.objectsRoot = data.getDataFolder().toPath().toAbsolutePath().normalize().resolve(OBJECTS_FOLDER);
private PackStructureResolver(PackResources pack, File packFolder) {
this.pack = pack;
this.objectsRoot = packFolder.toPath().toAbsolutePath().normalize().resolve(OBJECTS_FOLDER);
}
@Override
public IrisJigsawPool loadPool(String key) {
return StructureResources.pool(data.getPackResources(), key);
return StructureResources.pool(pack, key);
}
@Override
public IrisJigsawPiece loadPiece(String key) {
return StructureResources.piece(data.getPackResources(), key);
return StructureResources.piece(pack, key);
}
@Override
public IrisObject loadObject(String key) {
public ObjectFrame loadObject(String key) {
if (objects.containsKey(key)) {
return objects.get(key);
}
@@ -286,7 +286,7 @@ public final class StructureGraphValidation {
return null;
}
Path file = resolveObject(key);
IrisObject object = file == null ? null : readObjectBounds(file);
ObjectFrame object = file == null ? null : readObjectBounds(file);
if (object == null) {
missingObjects.add(key);
return null;
@@ -306,7 +306,7 @@ public final class StructureGraphValidation {
return file;
}
private IrisObject readObjectBounds(Path file) {
private ObjectFrame readObjectBounds(Path file) {
try (BufferedInputStream input = new BufferedInputStream(Files.newInputStream(file))) {
return IrisObjectFrameReader.readBounds(input, file.toString());
} catch (IOException e) {
@@ -22,12 +22,11 @@ import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
import art.arcane.iris.engine.framework.StructureAssembler;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.volmlib.util.math.RNG;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.volmit.geometry.BlockPosition;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -49,8 +48,8 @@ public final class StructureResourceBundleGraphCompiler {
public static List<StructureGraphCompilation> compile(StructureResourceBundle bundle) {
BundleGraph graph = parse(Objects.requireNonNull(bundle));
List<StructureGraphCompilation> compilations = new ArrayList<>(graph.structures().size());
for (IrisStructure structure : graph.structures().values()) {
compilations.add(StructureGraphCompiler.compile(structure, graph.resolver()));
for (Map.Entry<String, IrisStructure> structure : graph.structures().entrySet()) {
compilations.add(StructureGraphCompiler.compile(structure.getKey(), structure.getValue(), graph.resolver()));
}
return List.copyOf(compilations);
}
@@ -60,8 +59,9 @@ public final class StructureResourceBundleGraphCompiler {
if (graph.structures().isEmpty()) {
throw new StructureGraphValidationException("Structure bundle does not contain a root structure resource");
}
for (IrisStructure structure : graph.structures().values()) {
StructureGraphCompilation compilation = StructureGraphCompiler.compile(structure, graph.resolver());
for (Map.Entry<String, IrisStructure> structure : graph.structures().entrySet()) {
StructureGraphCompilation compilation = StructureGraphCompiler.compile(
structure.getKey(), structure.getValue(), graph.resolver());
if (!compilation.isAssemblyViable()) {
throw new StructureGraphValidationException(
"Structure bundle graph is not viable: " + viabilityFailure(compilation));
@@ -90,14 +90,11 @@ public final class StructureResourceBundleGraphCompiler {
Map<String, IrisStructure> structures = new LinkedHashMap<>();
Map<String, IrisJigsawPool> pools = new LinkedHashMap<>();
Map<String, IrisJigsawPiece> pieces = new LinkedHashMap<>();
Map<String, IrisObject> objects = new LinkedHashMap<>();
Map<String, ObjectFrame> objects = new LinkedHashMap<>();
for (StructureResourceBundle.Resource resource : activeBundle.resources().values()) {
String path = resource.relativePath();
if (matches(path, "structures/", ".json")) {
IrisStructure structure = readJson(resource, IrisStructure.class);
String key = key(path, "structures/", ".json");
structure.setLoadKey(key);
structures.put(key, structure);
structures.put(key(path, "structures/", ".json"), readJson(resource, IrisStructure.class));
} else if (matches(path, "jigsaw-pools/", ".json")) {
pools.put(key(path, "jigsaw-pools/", ".json"), readJson(resource, IrisJigsawPool.class));
} else if (matches(path, "jigsaw-pieces/", ".json")) {
@@ -114,7 +111,7 @@ public final class StructureResourceBundleGraphCompiler {
for (long seed : ASSEMBLY_SEEDS) {
try {
StructureAssembler assembler = StructureAssembler.forCompilation(
compilation, new IrisPosition(0, 64, 0));
compilation, new BlockPosition(0, 64, 0));
StructureAssemblyResult result = assembler.assemble(new RNG(seed));
if (result.status().isFailure()) {
throw new StructureGraphValidationException("Structure bundle graph '" + structureKey
@@ -157,7 +154,7 @@ public final class StructureResourceBundleGraphCompiler {
return value;
}
private static IrisObject readObjectBounds(StructureResourceBundle.Resource resource) {
private static ObjectFrame readObjectBounds(StructureResourceBundle.Resource resource) {
try (ByteArrayInputStream input = new ByteArrayInputStream(resource.content())) {
return IrisObjectFrameReader.readBounds(input, resource.relativePath());
} catch (IOException e) {
@@ -168,7 +165,7 @@ public final class StructureResourceBundleGraphCompiler {
private record BundleResolver(
Map<String, IrisJigsawPool> pools,
Map<String, IrisJigsawPiece> pieces,
Map<String, IrisObject> objects
Map<String, ObjectFrame> objects
) implements StructureGraphResolver {
private BundleResolver {
pools = Map.copyOf(pools);
@@ -187,7 +184,7 @@ public final class StructureResourceBundleGraphCompiler {
}
@Override
public IrisObject loadObject(String key) {
public ObjectFrame loadObject(String key) {
return objects.get(key);
}
}
@@ -18,11 +18,9 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.IrisValidationContext;
import art.arcane.iris.core.pack.PackValidationIo;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.builtin.structure.StructurePlacementSettings;
import com.volmit.config.FeatureSettings;
import com.volmit.validation.Problem;
import com.volmit.validation.ValidationContext;
import com.volmit.validation.Validator;
@@ -30,6 +28,7 @@ import com.volmit.validation.Validator;
import java.io.File;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@@ -43,16 +42,15 @@ import java.util.stream.Collectors;
* severity; everything else is an error, as when Iris's own pack validator ran these checks.
*/
public final class StructureValidator implements Validator {
private static final List<String> STRUCTURE_HOST_FOLDERS = List.of("dimensions", "regions", "biomes");
private static final String STRUCTURES_FIELD = "structures";
@Override
public void validate(ValidationContext pack) {
IrisData data = IrisValidationContext.of(pack).data();
StructureGraphValidation.Validation graphs = StructureGraphValidation.validate(data, placedStructureKeys(data.getDataFolder()));
File packFolder = pack.settings().extension(File.class).orElse(null);
StructureGraphValidation.Validation graphs = packFolder == null
? new StructureGraphValidation.Validation(List.of(), Set.of(), Map.of())
: StructureGraphValidation.validate(pack.resources(), packFolder, placedStructureKeys(pack));
graphs.problems().forEach(pack::report);
reportUnlessAssemblyReported(pack, StructureReferenceValidation.validate(pack.resources()), graphs.problems());
NativeReplacementValidation.validate(data.getDataFolder(), graphs.replacementOutputStructures(), graphs.sampledVerticalEnvelopes())
NativeReplacementValidation.validate(packFolder, graphs.replacementOutputStructures(), graphs.sampledVerticalEnvelopes())
.forEach(pack::report);
StructurePlacementValidation.validate(pack);
ImportedStructuresValidation.validate(pack);
@@ -64,43 +62,14 @@ public final class StructureValidator implements Validator {
references.stream().filter(problem -> !reported.contains(problem.message())).forEach(pack::report);
}
/**
* The keys of the structures the dimension, region and biome files of the pack in {@code packFolder} place, read
* from their JSON as written, like the other checks of these files.
*/
public static Set<String> placedStructureKeys(File packFolder) {
/** The keys of the structures the dimensions, regions and biomes of the pack place, whether or not a dimension reaches them. */
public static Set<String> placedStructureKeys(ValidationContext pack) {
Set<String> structureKeys = new LinkedHashSet<>();
if (packFolder == null || !packFolder.isDirectory()) {
return structureKeys;
}
for (String folderName : STRUCTURE_HOST_FOLDERS) {
File resourceFolder = new File(packFolder, folderName);
if (!resourceFolder.isDirectory()) {
continue;
}
for (File resourceFile : PackValidationIo.listJsonRecursive(resourceFolder)) {
addPlacedKeys(structureKeys, PackValidationIo.readJson(resourceFile));
for (FeatureSettings.Entry<StructurePlacementSettings> declared : pack.settings().declared(StructurePlacementSettings.class).entries()) {
for (StructurePlacement placement : declared.value().placements()) {
placement.structures().stream().filter(key -> key != null && !key.isBlank()).forEach(structureKeys::add);
}
}
return Set.copyOf(structureKeys);
}
private static void addPlacedKeys(Set<String> structureKeys, JSONObject resource) {
JSONArray placements = resource == null ? null : resource.optJSONArray(STRUCTURES_FIELD);
if (placements == null) {
return;
}
for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) {
JSONObject placement = placements.optJSONObject(placementIndex);
JSONArray references = placement == null ? null : placement.optJSONArray(STRUCTURES_FIELD);
if (references == null) {
continue;
}
for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) {
if (references.opt(referenceIndex) instanceof String structureKey && !structureKey.isBlank()) {
structureKeys.add(structureKey);
}
}
}
}
}
@@ -0,0 +1,40 @@
/*
* 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.engine.framework.structure.assembly;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/**
* One piece of an assembled structure: the pack object, where its origin lands, how it is turned and the blocks it covers.
* Heights are world Y, and the bounds are inclusive.
*/
public record AssembledPiece(ResourceId object, int x, int y, int z, PieceTurn turn,
int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
public AssembledPiece {
Objects.requireNonNull(object, "object");
Objects.requireNonNull(turn, "turn");
}
/** This piece moved up by {@code shiftY} blocks. */
public AssembledPiece shiftedUp(int shiftY) {
return new AssembledPiece(object, x, y + shiftY, z, turn, minX, minY + shiftY, minZ, maxX, maxY + shiftY, maxZ);
}
}
@@ -0,0 +1,38 @@
/*
* 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.engine.framework.structure.assembly;
import art.arcane.iris.engine.framework.structure.StructureAssemblyStatus;
import java.util.List;
import java.util.Objects;
/** What a {@link StructureAssembly} built: how the assembly ended, why when it did not complete, and the pieces in placement order. */
public record Assembly(StructureAssemblyStatus status, String detail, List<AssembledPiece> pieces) {
public Assembly {
Objects.requireNonNull(status, "status");
Objects.requireNonNull(detail, "detail");
pieces = List.copyOf(pieces);
}
/** Whether the assembly completed with pieces to place. */
public boolean hasOutput() {
return status == StructureAssemblyStatus.COMPLETE && !pieces.isEmpty();
}
}
@@ -0,0 +1,70 @@
/*
* 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.engine.framework.structure.assembly;
import com.volmit.block.BlockTurn;
import com.volmit.geometry.BlockPosition;
/**
* How a structure's assembly turns a piece: around the vertical axis by whole quarter turns, in the direction Iris's
* object rotation turns (north becomes west).
*
* @param yDegrees degrees around Y; a multiple of 90
*/
public record PieceTurn(int yDegrees) {
public static final PieceTurn NONE = new PieceTurn(0);
private static final int QUARTER_TURN_DEGREES = 90;
private static final int QUARTER_TURNS_PER_CIRCLE = 4;
public PieceTurn {
if (yDegrees % QUARTER_TURN_DEGREES != 0) {
throw new IllegalArgumentException("A piece turns by whole quarter turns, not " + yDegrees + " degrees");
}
}
public static PieceTurn aroundY(int yDegrees) {
return new PieceTurn(yDegrees);
}
/** The quarter turns this turn makes, 0 to 3. */
public int quarterTurns() {
return Math.floorMod(yDegrees / QUARTER_TURN_DEGREES, QUARTER_TURNS_PER_CIRCLE);
}
/** The directions this turn turns, for the facing, axis and connections of block states. */
public BlockTurn blockTurn() {
return (x, y, z) -> switch (quarterTurns()) {
case 1 -> new BlockTurn.Direction(z, y, -x);
case 2 -> new BlockTurn.Direction(-x, y, -z);
case 3 -> new BlockTurn.Direction(-z, y, x);
default -> new BlockTurn.Direction(x, y, z);
};
}
/** {@code position} turned around the origin. */
public BlockPosition rotate(BlockPosition position) {
return switch (quarterTurns()) {
case 1 -> new BlockPosition(position.z(), position.y(), -position.x());
case 2 -> new BlockPosition(-position.x(), position.y(), -position.z());
case 3 -> new BlockPosition(-position.z(), position.y(), position.x());
default -> position;
};
}
}
@@ -0,0 +1,56 @@
/*
* 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.engine.framework.structure.assembly;
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.service.Providers;
import com.volmit.service.Service;
import java.util.Optional;
import java.util.OptionalInt;
/**
* Builds the pieces of a structure the pack names; the placement decides where they go and fits them to the terrain.
* Every method answers empty, or {@link Viability#NOT_VIABLE}, for a structure this provider does not know, so a module
* offering another kind of structure answers only for its own. The placement asks the first provider that knows it.
*/
@Service(Providers.FIRST)
public interface StructureAssembly {
/** Whether this provider knows {@code structure}. Validation and the commands ask this. */
boolean knows(PackResources pack, ResourceId structure);
/** How far, in chunks from its start, the structure may reach; empty when this provider does not know it. */
OptionalInt reachChunks(PackResources pack, ResourceId structure);
/** How the pieces are stamped; empty when this provider does not know it. */
Optional<StructureStamp> stamp(PackResources pack, ResourceId structure);
/** Whether the structure can produce pieces at all. */
Viability viability(PackResources pack, ResourceId structure);
/**
* The pieces from {@code origin}, drawing from {@code random}; empty when this provider does not know the structure.
* The placement draws its origin, anchor and structure from the same random before this continues on it, so the
* draws stay in one order whoever assembles.
*/
Optional<Assembly> assemble(PackResources pack, ResourceId structure, BlockPosition origin, RNG random);
}
@@ -0,0 +1,42 @@
/*
* 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.engine.framework.structure.assembly;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.builtin.blocks.ObjectReplace;
import java.util.List;
import java.util.Objects;
/**
* How the pieces of an assembled structure are stamped into the world.
*
* @param placeMode the place mode each piece is stamped with
* @param edits the find-and-replace block edits applied to every piece
* @param loot the loot tables the containers of the pieces draw from, blank names left out
* @param vanillaSource the platform structure this structure stands in for, blank for a hand-authored one
*/
public record StructureStamp(ObjectPlaceMode placeMode, List<ObjectReplace> edits, List<String> loot, String vanillaSource) {
public StructureStamp {
Objects.requireNonNull(placeMode, "placeMode");
edits = List.copyOf(edits);
loot = List.copyOf(loot);
Objects.requireNonNull(vanillaSource, "vanillaSource");
}
}
@@ -0,0 +1,33 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.assembly;
/** Whether a structure can produce pieces. */
public enum Viability {
/** Its pieces cannot be assembled, or its graph has errors. */
NOT_VIABLE,
/** Assembly completes for the samples tried, but a start or branch may still come up empty. */
VIABLE,
/** Every start and branch ends in pieces, so a placement of it always produces a structure. */
GUARANTEED;
public boolean isViable() {
return this != NOT_VIABLE;
}
}
@@ -1,15 +1,8 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.prefab.ObjectTurn;
import art.arcane.iris.util.common.data.B;
import art.arcane.volmlib.util.math.IrisBlockVector;
import art.arcane.volmlib.util.collection.KList;
import it.unimi.dsi.fastutil.longs.Long2LongMap;
import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public final class StructureCarvingFootprint {
static final int DEFAULT_MAX_CELLS = 1_048_576;
@@ -38,14 +31,6 @@ public final class StructureCarvingFootprint {
sourceMaxY = data.sourceMaxY();
}
static StructureCarvingFootprint from(KList<PlacedStructurePiece> pieces, int padding) {
return from(pieces, padding, DEFAULT_MAX_CELLS);
}
static StructureCarvingFootprint from(KList<PlacedStructurePiece> pieces, int padding, int maxCells) {
return fromColumns(sink -> emitPieceColumns(pieces, sink), padding, maxCells);
}
/**
* Builds a footprint from any per-column occupancy source. The source reports one contribution per
* occupied column; overlapping contributions merge into a single column whose vertical extents span
@@ -80,10 +65,10 @@ public final class StructureCarvingFootprint {
int[] sourceMinY = new int[sourceCount];
int[] sourceMaxY = new int[sourceCount];
int sourceId = 0;
for (Long2LongMap.Entry entry : sources.columns().long2LongEntrySet()) {
int localX = unpackX(entry.getLongKey()) - bounds.minX();
int localZ = unpackZ(entry.getLongKey()) - bounds.minZ();
long heights = entry.getLongValue();
for (Map.Entry<Long, Long> entry : sources.columns().entrySet()) {
int localX = unpackX(entry.getKey()) - bounds.minX();
int localZ = unpackZ(entry.getKey()) - bounds.minZ();
long heights = entry.getValue();
sourceX[sourceId] = localX;
sourceZ[sourceId] = localZ;
sourceMinY[sourceId] = unpackMinY(heights);
@@ -170,7 +155,7 @@ public final class StructureCarvingFootprint {
}
private static SourceCollection collectSources(ColumnSource source) {
Long2LongOpenHashMap columns = new Long2LongOpenHashMap();
Map<Long, Long> columns = new HashMap<>();
MutableBounds bounds = new MutableBounds();
boolean usable = source.emit((worldX, worldZ, minY, maxY) -> {
mergeColumn(columns, worldX, worldZ, minY, maxY);
@@ -182,36 +167,6 @@ public final class StructureCarvingFootprint {
return columns.isEmpty() ? null : new SourceCollection(columns, bounds.freeze());
}
private static boolean emitPieceColumns(KList<PlacedStructurePiece> pieces, ColumnSink sink) {
if (pieces == null) {
return true;
}
for (PlacedStructurePiece piece : pieces) {
if (piece == null) {
continue;
}
IrisObject object = piece.getObject();
ObjectTurn rotation = piece.getRotation();
if (object == null || rotation == null || object.getBlocks() == null) {
continue;
}
for (IrisBlockVector local : object.getBlocks().keys()) {
if (local == null || B.isAir(object.getBlocks().get(local))) {
continue;
}
IrisBlockVector rotated = rotation.rotate(local.clone());
long worldX = (long) piece.getX() + rotated.getBlockX();
long worldY = (long) piece.getY() + rotated.getBlockY();
long worldZ = (long) piece.getZ() + rotated.getBlockZ();
if (!fitsInteger(worldX) || !fitsInteger(worldY) || !fitsInteger(worldZ)) {
return false;
}
sink.column((int) worldX, (int) worldZ, (int) worldY, (int) worldY);
}
}
return true;
}
private static Bounds paddedBounds(MutableBoundsSnapshot sourceBounds, int padding, int maxCells) {
long paddedMinX = (long) sourceBounds.minX() - padding;
long paddedMaxX = (long) sourceBounds.maxX() + padding;
@@ -233,7 +188,7 @@ public final class StructureCarvingFootprint {
(int) width, (int) depth, cellCount);
}
private static void mergeColumn(Long2LongOpenHashMap columns, int x, int z, int minY, int maxY) {
private static void mergeColumn(Map<Long, Long> columns, int x, int z, int minY, int maxY) {
long key = pack(x, z);
if (!columns.containsKey(key)) {
columns.put(key, packHeights(minY, maxY));
@@ -430,7 +385,7 @@ public final class StructureCarvingFootprint {
int[] nearestSourceIds, int[] sourceMinY, int[] sourceMaxY) {
}
private record SourceCollection(Long2LongOpenHashMap columns, MutableBoundsSnapshot bounds) {
private record SourceCollection(Map<Long, Long> columns, MutableBoundsSnapshot bounds) {
}
private record MutableBoundsSnapshot(int minX, int maxX, int minZ, int maxZ) {
@@ -1,7 +1,7 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.engine.framework.structure.ColumnHeights;
import art.arcane.iris.spi.PlatformBlockState;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
@@ -12,7 +12,7 @@ final class StructureFoundationPlanner {
private StructureFoundationPlanner() {
}
static void recordBaseCell(Long2IntOpenHashMap columns, int x, int y, int z,
static void recordBaseCell(ColumnHeights columns, int x, int y, int z,
PlatformBlockState state, boolean supportNonOccluding) {
if (columns == null || state == null
|| !(supportNonOccluding ? state.isSolid() : state.isOccluding())) {
@@ -0,0 +1,51 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece;
import com.volmit.geometry.BlockPosition;
import java.util.List;
import java.util.function.Function;
/** The columns an assembled structure occupies, for the carve footprint. */
final class StructurePieceColumns {
private StructurePieceColumns() {
}
/** One block of a piece object: where it lies from the object's center, and whether it is air. */
record PieceBlock(BlockPosition offset, boolean air) {
}
/**
* Reports a column for every block of every piece that is not air, at the height the block lands, in the
* order of the pieces; false when a block lands outside the integer range.
*/
static boolean emit(List<AssembledPiece> pieces, Function<AssembledPiece, List<PieceBlock>> blocksOf,
StructureCarvingFootprint.ColumnSink sink) {
if (pieces == null) {
return true;
}
for (AssembledPiece piece : pieces) {
if (piece == null) {
continue;
}
List<PieceBlock> blocks = blocksOf.apply(piece);
if (blocks == null) {
continue;
}
for (PieceBlock block : blocks) {
if (block.air()) {
continue;
}
BlockPosition rotated = piece.turn().rotate(block.offset());
long worldX = (long) piece.x() + rotated.x();
long worldY = (long) piece.y() + rotated.y();
long worldZ = (long) piece.z() + rotated.z();
if (worldX != (int) worldX || worldY != (int) worldY || worldZ != (int) worldZ) {
return false;
}
sink.column((int) worldX, (int) worldZ, (int) worldY, (int) worldY);
}
}
return true;
}
}
@@ -20,15 +20,17 @@ package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.engine.framework.structure.ColumnHeights;
import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece;
import art.arcane.iris.engine.framework.structure.assembly.PieceTurn;
import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly;
import art.arcane.iris.engine.framework.structure.assembly.StructureStamp;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.prepare.ObjectRotation;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.modules.ModuleObjectPlacement;
import art.arcane.iris.engine.object.prefab.ObjectTurn;
import art.arcane.volmlib.util.cache.CacheKey;
import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.framework.StructurePlacementScope;
import art.arcane.iris.core.modules.PlacementMarkers;
import art.arcane.iris.engine.framework.TreeBlockMaterial;
@@ -39,7 +41,6 @@ import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.builtin.structure.StructureCarveShape;
import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.builtin.structure.StructureStilts;
@@ -61,8 +62,7 @@ import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterStructurePOI;
import art.arcane.volmlib.util.math.RNG;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import com.volmit.geometry.BlockPosition;
import java.util.ArrayList;
import java.util.HashMap;
@@ -112,8 +112,8 @@ public class StructurePlacing {
}
String key = resolved.structureKey();
IrisStructure structure = resolved.structure();
KList<PlacedStructurePiece> pieces = resolvedPiecesOrNull(resolved, cx, cz);
StructureStamp stamp = resolved.stamp();
KList<AssembledPiece> pieces = resolvedPiecesOrNull(resolved, cx, cz);
if (pieces == null) {
return;
}
@@ -139,36 +139,36 @@ public class StructurePlacing {
+ " is not implemented for structure '" + key + "'");
}
ObjectPlaceMode mode = structure.getPlaceMode();
ObjectPlaceMode mode = stamp.placeMode();
int failedPieces = 0;
StructureStilts stilt = placement.stilt().orElse(null);
Long2IntOpenHashMap foundationColumns = stilt == null
? null : new Long2IntOpenHashMap();
ColumnHeights foundationColumns = stilt == null
? null : new ColumnHeights(0);
boolean supportNonOccluding = stilt != null && stilt.supportNonOccluding();
if (placement.isAnchoredUnderground()) {
ObjectPlaceMode undergroundMode = mode.placeMode().has(PlaceTrait.CAVE_ANCHORED)
? mode : ObjectPlaceMode.STRUCTURE_PIECE;
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, undergroundMode, p.getY(), rng,
for (AssembledPiece p : pieces) {
if (placeObject(writer, key, stamp, p, undergroundMode, p.y(), rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
}
} else if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
for (AssembledPiece p : pieces) {
if (placeObject(writer, key, stamp, p, ObjectPlaceMode.STRUCTURE_PIECE, p.y(), rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
}
} else if (pieces.size() == 1) {
if (placeObject(writer, structure, pieces.getFirst(), mode, -1, rng,
if (placeObject(writer, key, stamp, pieces.getFirst(), mode, -1, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
} else {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
for (AssembledPiece p : pieces) {
if (placeObject(writer, key, stamp, p, ObjectPlaceMode.STRUCTURE_PIECE, p.y(), rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
@@ -180,7 +180,7 @@ public class StructurePlacing {
}
}
private void placeFoundation(MantleWriter writer, Long2IntOpenHashMap columns,
private void placeFoundation(MantleWriter writer, ColumnHeights columns,
StructureStilts settings, RNG rng,
boolean surfaceStructure) {
PaletteSpec palette = settings.palette().orElseThrow(
@@ -188,14 +188,13 @@ public class StructurePlacing {
PaletteSampler picker = engine.getData().getPackResources().blocks().palette(palette, rng.getSeed());
int mantleOffset = engine.getMinHeight();
int maxDepth = Math.max(1, settings.maxDepth());
for (Long2IntMap.Entry column : columns.long2IntEntrySet()) {
int worldX = StructureFoundationPlanner.unpackX(column.getLongKey());
int worldZ = StructureFoundationPlanner.unpackZ(column.getLongKey());
int foundationY = column.getIntValue();
columns.forEach((column, foundationY) -> {
int worldX = StructureFoundationPlanner.unpackX(column);
int worldZ = StructureFoundationPlanner.unpackZ(column);
PlatformBlockState foundationState = writer.getDataIfPresent(
worldX, foundationY, worldZ, PlatformBlockState.class);
if (foundationState == null || !foundationState.isSolid()) {
continue;
return;
}
int terrainHeight = engine.getMantle().trueHeight(worldX, worldZ);
int groundY = StructureFoundationPlanner.findGroundY(
@@ -212,12 +211,12 @@ public class StructurePlacing {
overlay, carved, y, terrainHeight);
});
if (groundY == StructureFoundationPlanner.NO_GROUND) {
continue;
return;
}
StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> {
writeFoundationSupport(writer, picker, worldX, y, worldZ, mantleOffset);
});
}
});
}
/** Writes the stilt palette's block at the column's mantle height, clearing any carve there. */
@@ -233,7 +232,7 @@ public class StructurePlacing {
writer.set(worldX, mantleY, worldZ, support);
}
static KList<PlacedStructurePiece> resolvedPiecesOrNull(
static KList<AssembledPiece> resolvedPiecesOrNull(
IrisStructureLocator.ResolvedPlacement resolved,
int chunkX,
int chunkZ
@@ -241,7 +240,7 @@ public class StructurePlacing {
if (resolved == null) {
return null;
}
KList<PlacedStructurePiece> pieces = resolved.pieces();
KList<AssembledPiece> pieces = resolved.pieces();
if (!IrisStructureLocator.requirePlacementOutput(
resolved.placement(), resolved.structureKey(), chunkX, chunkZ,
pieces != null && !pieces.isEmpty(), "placement application received no assembled pieces")) {
@@ -258,7 +257,7 @@ public class StructurePlacing {
+ " assembled piece(s)");
}
private void boreStructure(MantleWriter writer, KList<PlacedStructurePiece> pieces,
private void boreStructure(MantleWriter writer, KList<AssembledPiece> pieces,
StructureTerrain terrain) {
int[] bounds = computePieceBounds(pieces);
if (bounds == null) {
@@ -288,7 +287,7 @@ public class StructurePlacing {
}
}
private void forceCarveStructure(MantleWriter writer, KList<PlacedStructurePiece> pieces,
private void forceCarveStructure(MantleWriter writer, KList<AssembledPiece> pieces,
StructureTerrain terrain) {
int[] bounds = computePieceBounds(pieces);
if (bounds == null) {
@@ -310,8 +309,8 @@ public class StructurePlacing {
}
long work = overboreCandidateVolume(bounds, margin, upExtension, floorCut);
StructureCarvingFootprint footprint = StructureCarvingFootprint.from(
pieces, margin, Integer.MAX_VALUE);
StructureCarvingFootprint footprint = StructureCarvingFootprint.fromColumns(
sink -> StructurePieceColumns.emit(pieces, this::blocksOf, sink), margin, Integer.MAX_VALUE);
if (footprint == null) {
throw new IllegalStateException("Structure force-carve footprint is empty or exceeds addressable memory");
}
@@ -419,18 +418,20 @@ public class StructurePlacing {
int mantleOffset = engine.getMinHeight();
int worldHeight = engine.getHeight();
Map<String, ObjectMarkerBounds> intersectingObjects = new HashMap<>();
for (PlacedStructurePiece piece : resolved.pieces()) {
for (IrisBlockVector local : piece.getObject().getBlocks().keys()) {
PlatformBlockState structureState = piece.getObject().getBlocks().get(local);
for (AssembledPiece piece : resolved.pieces()) {
IrisObject object = objectOf(piece);
for (IrisBlockVector local : object.getBlocks().keys()) {
PlatformBlockState structureState = object.getBlocks().get(local);
if (!isOccupiedStructureState(structureState)) {
continue;
}
IrisBlockVector rotated = piece.getRotation().rotate(local.clone());
int y = piece.getY() - mantleOffset + rotated.getBlockY();
BlockPosition rotated = piece.turn().rotate(
new BlockPosition(local.getBlockX(), local.getBlockY(), local.getBlockZ()));
int y = piece.y() - mantleOffset + rotated.y();
if (y >= 0 && y < worldHeight) {
collectIntersectingObjectTreeMarker(
writer, piece.getX() + rotated.getBlockX(), y,
piece.getZ() + rotated.getBlockZ(), intersectingObjects);
writer, piece.x() + rotated.x(), y,
piece.z() + rotated.z(), intersectingObjects);
}
}
}
@@ -520,7 +521,29 @@ public class StructurePlacing {
Math.max(0, horizontalSpan - 1), Math.max(0, verticalSpan - 1), worldHeight);
}
private int[] computePieceBounds(KList<PlacedStructurePiece> pieces) {
private List<StructurePieceColumns.PieceBlock> blocksOf(AssembledPiece piece) {
IrisObject object = objectOf(piece);
if (object == null || object.getBlocks() == null) {
return null;
}
List<StructurePieceColumns.PieceBlock> blocks = new ArrayList<>();
for (IrisBlockVector local : object.getBlocks().keys()) {
if (local != null) {
blocks.add(new StructurePieceColumns.PieceBlock(
new BlockPosition(local.getBlockX(), local.getBlockY(), local.getBlockZ()),
B.isAir(object.getBlocks().get(local))));
}
}
return blocks;
}
/** The object of {@code piece}, loaded from the engine's pack. */
private IrisObject objectOf(AssembledPiece piece) {
String key = engine.getData().getPackResources().keyOf(piece.object());
return engine.getData().load(IrisObject.class, key, false);
}
private int[] computePieceBounds(KList<AssembledPiece> pieces) {
if (pieces == null || pieces.isEmpty()) {
return null;
}
@@ -530,29 +553,29 @@ public class StructurePlacing {
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
int maxZ = Integer.MIN_VALUE;
for (PlacedStructurePiece p : pieces) {
minX = Math.min(minX, p.getMinX());
minY = Math.min(minY, p.getMinY());
minZ = Math.min(minZ, p.getMinZ());
maxX = Math.max(maxX, p.getMaxX());
maxY = Math.max(maxY, p.getMaxY());
maxZ = Math.max(maxZ, p.getMaxZ());
for (AssembledPiece p : pieces) {
minX = Math.min(minX, p.minX());
minY = Math.min(minY, p.minY());
minZ = Math.min(minZ, p.minZ());
maxX = Math.max(maxX, p.maxX());
maxY = Math.max(maxY, p.maxY());
maxZ = Math.max(maxZ, p.maxZ());
}
return new int[]{minX, minY, minZ, maxX, maxY, maxZ};
}
/** A placement of the piece object {@code objectKey} whose containers draw from the structure's loot tables. */
public static ObjectPlacement lootPlacement(IrisStructure structure, String objectKey) {
return lootPlacementBuilder(structure, objectKey).build();
/** A placement of the piece object {@code objectKey} whose containers draw from the stamp's loot tables. */
public static ObjectPlacement lootPlacement(StructureStamp stamp, String objectKey) {
return lootPlacementBuilder(stamp, objectKey).build();
}
private static ObjectPlacement.Builder lootPlacementBuilder(IrisStructure structure, String objectKey) {
private static ObjectPlacement.Builder lootPlacementBuilder(StructureStamp stamp, String objectKey) {
ObjectPlacement.Builder placement = ObjectPlacement.builder().place(List.of(objectKey));
if (structure.getLoot() == null) {
if (stamp.loot().isEmpty()) {
return placement;
}
List<ObjectLoot> loot = new ArrayList<>();
for (String lootTable : structure.getLoot()) {
for (String lootTable : stamp.loot()) {
if (lootTable != null && !lootTable.isBlank()) {
loot.add(new ObjectLoot(lootTable, 1));
}
@@ -560,22 +583,22 @@ public class StructurePlacing {
return placement.loot(loot);
}
private int placeObject(MantleWriter writer, IrisStructure structure, PlacedStructurePiece p,
ObjectPlaceMode mode, int y, RNG rng, Long2IntOpenHashMap foundationColumns,
private int placeObject(MantleWriter writer, String structureKey, StructureStamp stamp, AssembledPiece p,
ObjectPlaceMode mode, int y, RNG rng, ColumnHeights foundationColumns,
boolean supportNonOccluding) {
IrisObject object = p.getObject();
IrisObject object = objectOf(p);
String objectKey = object.getLoadKey();
ObjectPlacement.Builder builder = lootPlacementBuilder(structure, objectKey).mode(mode).rotation(moduleRotation(p.getRotation()));
if (!structure.getEdit().isEmpty()) {
builder.edit(structure.getEdit());
ObjectPlacement.Builder builder = lootPlacementBuilder(stamp, objectKey).mode(mode).rotation(moduleRotation(p.turn()));
if (!stamp.edits().isEmpty()) {
builder.edit(new KList<>(stamp.edits()));
}
if (!mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) {
builder.forcePlace(true);
}
ObjectPlacement config = builder.build();
int placeY = (y == -1) ? -1 : y - engine.getMinHeight();
String marker = structurePlacementMarker(structure, p, objectKey);
return ModuleObjectPlacement.place(object, p.getX(), placeY, p.getZ(), writer, config, rng, (position, state) -> {
String marker = structurePlacementMarker(structureKey, p, objectKey);
return ModuleObjectPlacement.place(object, p.x(), placeY, p.z(), writer, config, rng, (position, state) -> {
StructureFoundationPlanner.recordBaseCell(
foundationColumns, position.getX(), position.getY(), position.getZ(), state,
supportNonOccluding);
@@ -586,8 +609,8 @@ public class StructurePlacing {
}
/** The placement rotation that turns a placed piece the way {@code turn} does. */
public static ObjectRotation moduleRotation(ObjectTurn turn) {
return ObjectRotation.of(turn.xDegrees(), turn.yDegrees(), turn.zDegrees());
public static ObjectRotation moduleRotation(PieceTurn turn) {
return ObjectRotation.of(0, turn.yDegrees(), 0);
}
static boolean shouldWriteStructureMarker(PlatformBlockState state) {
@@ -604,12 +627,11 @@ public class StructurePlacing {
return hash & Integer.MAX_VALUE;
}
private static String structurePlacementMarker(IrisStructure structure, PlacedStructurePiece piece, String objectKey) {
String structureKey = structure.getLoadKey();
private static String structurePlacementMarker(String structureKey, AssembledPiece piece, String objectKey) {
if (structureKey == null || structureKey.isBlank() || objectKey == null || objectKey.isBlank()) {
return null;
}
int placementId = structurePlacementId(structureKey, objectKey, piece.getX(), piece.getY(), piece.getZ());
int placementId = structurePlacementId(structureKey, objectKey, piece.x(), piece.y(), piece.z());
return PlacementMarkers.encodeStructure(objectKey, placementId, structureKey);
}
@@ -640,9 +662,11 @@ public class StructurePlacing {
|| terrain.resolvedMode() == StructureTerrainMode.BORE
? Math.max(0, terrain.horizontalPadding()) : 0;
for (String key : placement.structures()) {
IrisStructure structure = StructureResources.structure(engine.getData().getPackResources(), key);
if (structure != null) {
max = Math.max(max, Math.max(1, structure.getMaxSizeChunks()) * 16 + carvePadding);
var pack = engine.getData().getPackResources();
var structure = pack.idOf(key);
StructureAssembly provider = IrisStructureLocator.providerOf(engine, structure);
if (provider != null) {
max = Math.max(max, Math.max(1, provider.reachChunks(pack, structure).orElse(1)) * 16 + carvePadding);
}
}
}
@@ -12,11 +12,10 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession;
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant;
import art.arcane.iris.core.service.JigsawStudioBlocks;
import art.arcane.iris.core.service.JigsawStudioRequest;
import art.arcane.iris.engine.object.value.IrisDirection;
import art.arcane.iris.engine.framework.structure.assembly.PieceTurn;
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.IrisJigsawPiece;
import art.arcane.iris.engine.object.prefab.ObjectTurn;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
import art.arcane.volmlib.util.collection.KList;
import com.volmit.block.BlockRegistry;
@@ -426,7 +425,7 @@ public final class JigsawStudioGenerator implements ChunkPainter {
"object '" + variant.objectKey() + "' does not fit workcell '" + workcell.stableId() + "'");
}
ObjectTurn rotation = ObjectTurn.of(0, -90.0D * quarterTurns, 0);
PieceTurn rotation = PieceTurn.aroundY(-90 * quarterTurns);
List<RenderedBlock> blocks = renderBlocks(resources.blocks(), object, dimensions, quarterTurns, rotation);
if (blocks == null) {
return RenderedBay.invalid(
@@ -434,7 +433,7 @@ public final class JigsawStudioGenerator implements ChunkPainter {
"object '" + variant.objectKey() + "' contains an invalid or out-of-bounds block");
}
ConnectorRenderResult connectors = renderConnectors(piece, object, dimensions, quarterTurns, rotation);
ConnectorRenderResult connectors = renderConnectors(variant.pieceKey(), piece, object, dimensions, quarterTurns, rotation);
if (!connectors.failure().isEmpty()) {
return RenderedBay.invalid(dimensions, connectors.failure());
}
@@ -446,7 +445,7 @@ public final class JigsawStudioGenerator implements ChunkPainter {
PlaceableObject object,
JigsawStudioCellDimensions dimensions,
int quarterTurns,
ObjectTurn rotation
PieceTurn rotation
) {
BlockPosition center = object.center();
List<ObjectBlock> sourceBlocks = object.geometry().blocks();
@@ -491,15 +490,16 @@ public final class JigsawStudioGenerator implements ChunkPainter {
}
private ConnectorRenderResult renderConnectors(
String pieceKey,
IrisJigsawPiece piece,
PlaceableObject object,
JigsawStudioCellDimensions dimensions,
int quarterTurns,
ObjectTurn rotation
PieceTurn rotation
) {
KList<IrisJigsawConnector> sourceConnectors = piece.getConnectors();
List<IrisJigsawConnector> sourceConnectors = piece.getConnectors();
if (sourceConnectors == null) {
return ConnectorRenderResult.invalid("piece '" + piece.getLoadKey() + "' has no connector list");
return ConnectorRenderResult.invalid("piece '" + pieceKey + "' has no connector list");
}
List<RenderedConnector> connectors = new ArrayList<>(sourceConnectors.size());
for (int index = 0; index < sourceConnectors.size(); index++) {
@@ -507,29 +507,29 @@ public final class JigsawStudioGenerator implements ChunkPainter {
if (!validConnectorMetadata(source)) {
return ConnectorRenderResult.invalid("connector " + index + " has incomplete metadata");
}
IrisPosition sourcePosition = source.getPosition();
BlockPosition sourcePosition = source.getPosition();
if (!inside(
sourcePosition.getX(),
sourcePosition.getY(),
sourcePosition.getZ(),
sourcePosition.x(),
sourcePosition.y(),
sourcePosition.z(),
object.width(),
object.height(),
object.depth())) {
return ConnectorRenderResult.invalid("connector " + index + " is outside its object bounds");
}
RotatedPosition position = rotatePosition(
sourcePosition.getX(),
sourcePosition.getY(),
sourcePosition.getZ(),
sourcePosition.x(),
sourcePosition.y(),
sourcePosition.z(),
object.width(),
object.depth(),
quarterTurns);
IrisDirection front = quarterTurns == 0
JigsawDirection front = quarterTurns == 0
? source.getDirection()
: rotation.rotate(source.getDirection());
IrisDirection top = quarterTurns == 0
: source.getDirection().turnedBy(rotation.quarterTurns());
JigsawDirection top = quarterTurns == 0
? source.getTop()
: rotation.rotate(source.getTop());
: source.getTop().turnedBy(rotation.quarterTurns());
String orientation;
try {
orientation = orientation(front, top);
@@ -543,7 +543,7 @@ public final class JigsawStudioGenerator implements ChunkPainter {
+ source.getFinalState() + "' cannot be parsed and rotated");
}
IrisJigsawConnector connector = copyConnector(source)
.setPosition(new IrisPosition(position.x(), position.y(), position.z()))
.setPosition(new BlockPosition(position.x(), position.y(), position.z()))
.setDirection(front)
.setTop(top)
.setFinalState(finalState);
@@ -562,7 +562,7 @@ public final class JigsawStudioGenerator implements ChunkPainter {
return ConnectorRenderResult.valid(connectors);
}
private String rotatedFinalState(String finalState, ObjectTurn rotation, int quarterTurns) {
private String rotatedFinalState(String finalState, PieceTurn rotation, int quarterTurns) {
BlockRegistry registry = pack.resources().blocks();
BlockState state = registry.find(finalState).orElse(null);
if (state == null) {
@@ -712,16 +712,16 @@ public final class JigsawStudioGenerator implements ChunkPainter {
};
}
static String orientation(IrisDirection front, IrisDirection top) {
IrisDirection activeFront = Objects.requireNonNull(front, "Jigsaw connector front");
IrisDirection activeTop = Objects.requireNonNull(top, "Jigsaw connector top");
if (activeFront == IrisDirection.UP_POSITIVE_Y || activeFront == IrisDirection.DOWN_NEGATIVE_Y) {
static String orientation(JigsawDirection front, JigsawDirection top) {
JigsawDirection activeFront = Objects.requireNonNull(front, "Jigsaw connector front");
JigsawDirection activeTop = Objects.requireNonNull(top, "Jigsaw connector top");
if (activeFront == JigsawDirection.UP_POSITIVE_Y || activeFront == JigsawDirection.DOWN_NEGATIVE_Y) {
if (activeTop.isVertical()) {
throw new IllegalArgumentException("Vertical jigsaw fronts require a horizontal top direction");
}
return directionName(activeFront) + "_" + directionName(activeTop);
}
if (activeTop != IrisDirection.UP_POSITIVE_Y) {
if (activeTop != JigsawDirection.UP_POSITIVE_Y) {
throw new IllegalArgumentException("Horizontal jigsaw fronts require an upward top direction");
}
return directionName(activeFront) + "_up";
@@ -763,10 +763,10 @@ public final class JigsawStudioGenerator implements ChunkPainter {
private static IrisJigsawConnector copyConnector(IrisJigsawConnector source) {
return new IrisJigsawConnector()
.setPosition(new IrisPosition(
source.getPosition().getX(),
source.getPosition().getY(),
source.getPosition().getZ()))
.setPosition(new BlockPosition(
source.getPosition().x(),
source.getPosition().y(),
source.getPosition().z()))
.setDirection(source.getDirection())
.setTop(source.getTop())
.setPool(source.getPool())
@@ -779,7 +779,7 @@ public final class JigsawStudioGenerator implements ChunkPainter {
.setPlacementPriority(source.getPlacementPriority());
}
private static String directionName(IrisDirection direction) {
private static String directionName(JigsawDirection direction) {
return switch (direction) {
case UP_POSITIVE_Y -> "up";
case DOWN_NEGATIVE_Y -> "down";
@@ -884,7 +884,7 @@ public final class JigsawStudioGenerator implements ChunkPainter {
@FunctionalInterface
interface FinalStateRenderer {
String render(String finalState, ObjectTurn rotation, int quarterTurns);
String render(String finalState, PieceTurn rotation, int quarterTurns);
}
record RotatedPosition(int x, int y, int z) {