mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
Serve module resource kinds through IrisPackResources, run module validators wherever packs are validated, and drop the structure, jigsaw pool and piece loaders and validators from core
This commit is contained in:
1 parent
12c315bb52
commit
2f3ba3cebe
55 files changed
+1770
-1060
No files matched your search
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.localization.BukkitCommandMessages;
|
||||
import art.arcane.iris.core.localization.BukkitCommandMessagesExtended;
|
||||
@@ -315,7 +316,7 @@ public class CommandFind implements DirectorExecutor {
|
||||
Set<String> unplacedEditableKeys = new LinkedHashSet<>();
|
||||
Set<String> locatableEditableKeys = normalizedStructureKeys(
|
||||
IrisStructureLocator.locatableEditableKeys(engine));
|
||||
for (String editableKey : engine.getData().getStructureLoader().getPossibleKeys()) {
|
||||
for (String editableKey : StructureResources.structureKeys(engine.getData())) {
|
||||
String normalizedKey = normalizeStructureKey(editableKey);
|
||||
if (!isUnplacedEditableCandidate(
|
||||
normalizedKey, registeredKeys.keySet(), locatableEditableKeys,
|
||||
|
||||
+7
-7
@@ -1,5 +1,6 @@
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.pack.BrokenPackException;
|
||||
@@ -262,7 +263,7 @@ public class CommandJigsaw implements DirectorExecutor {
|
||||
if (data == null) {
|
||||
return;
|
||||
}
|
||||
IrisStructure irisStructure = data.load(IrisStructure.class, structure, false);
|
||||
IrisStructure irisStructure = StructureResources.structure(data, structure);
|
||||
if (irisStructure == null) {
|
||||
sendError(commandSender, "No Iris jigsaw structure '" + structure + "' exists in this pack.");
|
||||
return;
|
||||
@@ -1215,7 +1216,7 @@ public class CommandJigsaw implements DirectorExecutor {
|
||||
static JigsawStudioLayout loadPersistedLayout(ActiveContext context) throws IOException {
|
||||
IrisData source = context.request().source();
|
||||
source.invalidateStructureResources();
|
||||
IrisStructure structure = source.load(IrisStructure.class, context.request().structureKey(), false);
|
||||
IrisStructure structure = StructureResources.structure(source, context.request().structureKey());
|
||||
if (structure == null) {
|
||||
throw new IOException("The structure could not be reloaded after the graph transaction");
|
||||
}
|
||||
@@ -1274,10 +1275,9 @@ public class CommandJigsaw implements DirectorExecutor {
|
||||
}
|
||||
|
||||
static String nextThemeKey(ActiveContext context) throws IOException {
|
||||
IrisStructure structure = context.request().source().load(
|
||||
IrisStructure.class,
|
||||
context.request().structureKey(),
|
||||
false);
|
||||
IrisStructure structure = StructureResources.structure(
|
||||
context.request().source(),
|
||||
context.request().structureKey());
|
||||
if (structure == null) {
|
||||
throw new IOException("The active jigsaw structure could not be loaded");
|
||||
}
|
||||
@@ -1749,7 +1749,7 @@ public class CommandJigsaw implements DirectorExecutor {
|
||||
sendError(this, "Open a Jigsaw Studio project first.");
|
||||
return;
|
||||
}
|
||||
IrisJigsawPiece piece = context.request().source().getJigsawPieceLoader().load(pieceKey);
|
||||
IrisJigsawPiece piece = StructureResources.piece(context.request().source(), pieceKey);
|
||||
if (piece == null) {
|
||||
sendError(this, "No jigsaw piece '" + pieceKey + "' exists in this pack.");
|
||||
return;
|
||||
|
||||
+3
-2
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
@@ -301,7 +302,7 @@ public class CommandStructure implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_4, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
return;
|
||||
}
|
||||
IrisStructure s = data.load(IrisStructure.class, structure, false);
|
||||
IrisStructure s = StructureResources.structure(data, structure);
|
||||
if (s == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_NO_IRIS_STRUCTURE_THIS_PACK, MessageArgument.untrusted("structure", structure)));
|
||||
return;
|
||||
@@ -339,7 +340,7 @@ public class CommandStructure implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_5, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
return;
|
||||
}
|
||||
IrisStructure s = data.load(IrisStructure.class, structure, false);
|
||||
IrisStructure s = StructureResources.structure(data, structure);
|
||||
if (s == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_NO_IRIS_STRUCTURE_THIS_PACK_2, MessageArgument.untrusted("structure", structure)));
|
||||
return;
|
||||
|
||||
+1
-1
@@ -207,7 +207,7 @@ public class IrisStructureLocateCommandContractTest {
|
||||
assertTrue(method.indexOf("DatapackIngestService.installed()") > method.indexOf("J.a(() ->"));
|
||||
assertTrue(source.contains("engine.getDimension().getDatapackImports()"));
|
||||
assertTrue(source.contains("snapshot.configuredImportUrls().contains(importUrl)"));
|
||||
assertTrue(source.contains("engine.getData().getStructureLoader().getPossibleKeys()"));
|
||||
assertTrue(source.contains("StructureResources.structureKeys(engine.getData())"));
|
||||
assertFalse(method.contains("commandSender.sendMessage(exclusion"));
|
||||
}
|
||||
|
||||
|
||||
+2
@@ -20,6 +20,7 @@ package art.arcane.iris.modded;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.core.project.ModuleResourceSchemas;
|
||||
import art.arcane.iris.core.project.SchemaBuilder;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
@@ -95,6 +96,7 @@ public final class ModdedWorkspaceGenerator {
|
||||
schemas.put(immediateSchemas ? loader.buildSchemaImmediately() : loader.buildSchema());
|
||||
}
|
||||
}
|
||||
ModuleResourceSchemas.entries(data, immediateSchemas).forEach(schemas::put);
|
||||
|
||||
for (Class<?> snippetClass : data.resolveSnippets()) {
|
||||
try {
|
||||
|
||||
+5
-4
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.modded.command;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.modded.ModdedIrisLog;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
@@ -140,7 +141,7 @@ public final class ModdedStructureCommands {
|
||||
return 0;
|
||||
}
|
||||
String key = keyRaw.trim();
|
||||
IrisStructure structure = data.load(IrisStructure.class, key, false);
|
||||
IrisStructure structure = StructureResources.structure(data, key);
|
||||
if (structure == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STRUCTURE_COMMANDS_NO_IRIS_STRUCTURE_THIS_PACK, MessageArgument.untrusted("key", key)));
|
||||
return 0;
|
||||
@@ -180,7 +181,7 @@ public final class ModdedStructureCommands {
|
||||
return 0;
|
||||
}
|
||||
String key = keyRaw.trim();
|
||||
IrisStructure structure = data.load(IrisStructure.class, key, false);
|
||||
IrisStructure structure = StructureResources.structure(data, key);
|
||||
if (structure == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STRUCTURE_COMMANDS_NO_IRIS_STRUCTURE_THIS_PACK_2, MessageArgument.untrusted("key", key)));
|
||||
return 0;
|
||||
@@ -226,8 +227,8 @@ public final class ModdedStructureCommands {
|
||||
ModdedCommandFeedback.tab(context.getSource());
|
||||
try {
|
||||
Engine engine = IrisModdedCommands.engineFor(context.getSource().getLevel());
|
||||
if (engine != null && engine.getData().getStructureLoader() != null) {
|
||||
return SharedSuggestionProvider.suggest(engine.getData().getStructureLoader().getPossibleKeys(), builder);
|
||||
if (engine != null) {
|
||||
return SharedSuggestionProvider.suggest(StructureResources.structureKeys(engine.getData()), builder);
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
|
||||
+16
-17
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.modded.command;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.modded.ModdedIrisLog;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.IrisStructureLocator;
|
||||
@@ -72,7 +73,7 @@ final class ModdedUnregisteredStructures {
|
||||
entry.status().label(), entry.key(), entry.reason());
|
||||
}
|
||||
ModdedIrisLog.info("[Iris goto unregistered] Inventory scope is the live registry, this pack's "
|
||||
+ "nativeStructures placements, and structureLoader editable resources. This is deterministic "
|
||||
+ "nativeStructures placements, and its editable Iris structures. This is deterministic "
|
||||
+ "eligibility analysis and performs no chunk search; absent unmanaged datapack resources "
|
||||
+ "cannot be inferred after registry loading.");
|
||||
IrisModdedCommands.ok(source, "Iris wrote " + excluded.size() + " structure candidate(s) for "
|
||||
@@ -136,23 +137,21 @@ final class ModdedUnregisteredStructures {
|
||||
"Configured by an Iris nativeStructures placement, but absent from the live structure registry; "
|
||||
+ "install or enable the datapack or mod that provides this key."));
|
||||
}
|
||||
if (engine.getData().getStructureLoader() != null) {
|
||||
for (String key : engine.getData().getStructureLoader().getPossibleKeys()) {
|
||||
String normalizedKey = ModdedCommandSuggestions.normalizeKey(key);
|
||||
if (normalizedKey.isEmpty() || eligibleRegisteredKeys.contains(normalizedKey)
|
||||
|| excluded.containsKey(normalizedKey)) {
|
||||
continue;
|
||||
}
|
||||
boolean registered = registeredKeys.contains(normalizedKey);
|
||||
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key);
|
||||
boolean locatableEditable = IrisStructureLocator.hasLocatableEditablePlacement(engine, key);
|
||||
if (!registered && !nativePlacement && locatableEditable) {
|
||||
continue;
|
||||
}
|
||||
boolean configured = IrisStructureLocator.hasEditablePlacement(engine, key);
|
||||
excluded.putIfAbsent(normalizedKey, new ExcludedStructure(
|
||||
ReportStatus.UNPLACED, key.trim(), editableExclusionReason(configured)));
|
||||
for (String key : StructureResources.structureKeys(engine.getData())) {
|
||||
String normalizedKey = ModdedCommandSuggestions.normalizeKey(key);
|
||||
if (normalizedKey.isEmpty() || eligibleRegisteredKeys.contains(normalizedKey)
|
||||
|| excluded.containsKey(normalizedKey)) {
|
||||
continue;
|
||||
}
|
||||
boolean registered = registeredKeys.contains(normalizedKey);
|
||||
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key);
|
||||
boolean locatableEditable = IrisStructureLocator.hasLocatableEditablePlacement(engine, key);
|
||||
if (!registered && !nativePlacement && locatableEditable) {
|
||||
continue;
|
||||
}
|
||||
boolean configured = IrisStructureLocator.hasEditablePlacement(engine, key);
|
||||
excluded.putIfAbsent(normalizedKey, new ExcludedStructure(
|
||||
ReportStatus.UNPLACED, key.trim(), editableExclusionReason(configured)));
|
||||
}
|
||||
return List.copyOf(excluded.values());
|
||||
}
|
||||
|
||||
+1
-1
@@ -184,7 +184,7 @@ public class IrisModdedStructureCommandTest {
|
||||
assertTrue(tree.contains("ModdedUnregisteredStructures.print(context.getSource())"));
|
||||
assertTrue(command.contains("ModdedCommandSuggestions.isEligibleRegisteredStructure("));
|
||||
assertTrue(command.contains("ModdedLocateCommands.registeredStructureUnavailableMessage("));
|
||||
assertTrue(command.contains("engine.getData().getStructureLoader().getPossibleKeys()"));
|
||||
assertTrue(command.contains("StructureResources.structureKeys(engine.getData())"));
|
||||
assertTrue(command.contains("IrisStructureLocator.hasLocatableEditablePlacement(engine, key)"));
|
||||
assertTrue(command.contains("ModdedIrisLog.info(\"[Iris goto unregistered] [{}] {} - {}\""));
|
||||
assertTrue(command.contains("UNREGISTERED(\"unregistered\")"));
|
||||
|
||||
@@ -50,15 +50,12 @@ import art.arcane.iris.engine.object.prefab.IrisObjectScale;
|
||||
import art.arcane.iris.engine.object.terrain.IrisGenerator;
|
||||
import art.arcane.iris.engine.object.image.IrisImage;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMap;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
|
||||
import art.arcane.iris.engine.object.loot.IrisLootTable;
|
||||
import art.arcane.iris.engine.object.marker.IrisMarker;
|
||||
import art.arcane.iris.engine.object.mod.IrisMod;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.iris.engine.object.prefab.matter.IrisMatterObject;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
@@ -96,6 +93,7 @@ import java.util.Optional;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Data
|
||||
@@ -107,9 +105,16 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
// engine-hosting IrisData (and its pack graph) for the JVM lifetime.
|
||||
private static final Set<IrisData> ENGINE_HOLDERS =
|
||||
Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>()));
|
||||
/** Every resource type Iris loads itself for generation, studio and validation; module resource kinds come on top. */
|
||||
private static final List<Class<? extends IrisRegistrant>> RUNTIME_RESOURCE_TYPES = List.of(IrisLootTable.class,
|
||||
IrisSpawner.class, IrisEntity.class, IrisRegion.class, IrisBiome.class, IrisMod.class, IrisDimension.class,
|
||||
IrisGenerator.class, IrisMarker.class, IrisBlockData.class, IrisExpression.class, IrisObject.class, IrisImage.class,
|
||||
IrisImageMap.class, IrisMatterObject.class);
|
||||
/** Pack folders Iris reads that hold no resources of its loaders: snippets and module jars. */
|
||||
private static final List<String> OTHER_OWN_FOLDERS = List.of("snippet", "modules");
|
||||
private final File dataFolder;
|
||||
private final int id;
|
||||
private final boolean datapackCompiler;
|
||||
private final Purpose purpose;
|
||||
private volatile boolean closed = false;
|
||||
private final PackModuleSet modules;
|
||||
@EqualsAndHashCode.Exclude
|
||||
@@ -130,9 +135,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
private ResourceLoader<IrisMatterObject> matterLoader;
|
||||
private ResourceLoader<IrisImage> imageLoader;
|
||||
private ResourceLoader<IrisImageMap> imageMapLoader;
|
||||
private ResourceLoader<IrisStructure> structureLoader;
|
||||
private ResourceLoader<IrisJigsawPool> jigsawPoolLoader;
|
||||
private ResourceLoader<IrisJigsawPiece> jigsawPieceLoader;
|
||||
private KMap<String, KList<String>> possibleSnippets;
|
||||
private Gson gson;
|
||||
private Gson snippetLoader;
|
||||
@@ -142,19 +144,29 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient List<Engine> engines = new ArrayList<>();
|
||||
|
||||
private IrisData(File dataFolder) {
|
||||
this(dataFolder, false);
|
||||
/** What an instance is opened for, which decides its loaders and whether opening it may change the pack. */
|
||||
private enum Purpose {
|
||||
/** Generation and studio: every loader, registered with Iris's services; interrupted structure transactions are recovered. */
|
||||
RUNTIME,
|
||||
/** The datapack compiler at bootstrap: only the loaders it reads, without Iris's services. */
|
||||
DATAPACK_COMPILER,
|
||||
/** Validating a pack: every loader, without Iris's services, and nothing in the pack is written. */
|
||||
VALIDATION
|
||||
}
|
||||
|
||||
private IrisData(File dataFolder, boolean datapackCompiler) {
|
||||
private IrisData(File dataFolder) {
|
||||
this(dataFolder, Purpose.RUNTIME);
|
||||
}
|
||||
|
||||
private IrisData(File dataFolder, Purpose purpose) {
|
||||
this.dataFolder = dataFolder;
|
||||
this.modules = new PackModuleSet(dataFolder, this::getGson);
|
||||
this.id = RNG.r.imax();
|
||||
this.datapackCompiler = datapackCompiler;
|
||||
if (datapackCompiler) {
|
||||
hotloadedDatapackCompiler();
|
||||
} else {
|
||||
hotloaded();
|
||||
this.purpose = purpose;
|
||||
switch (purpose) {
|
||||
case RUNTIME -> hotloaded();
|
||||
case DATAPACK_COMPILER -> hotloadedDatapackCompiler();
|
||||
case VALIDATION -> openForValidation();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +179,27 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
}
|
||||
|
||||
public static IrisData openDatapackCompiler(File dataFolder) {
|
||||
return new IrisData(dataFolder, true);
|
||||
return new IrisData(dataFolder, Purpose.DATAPACK_COMPILER);
|
||||
}
|
||||
|
||||
/** A detached instance that reads the pack as generation would, for validating it: it writes nothing into the pack
|
||||
* and needs none of Iris's services. Close it when done.
|
||||
*/
|
||||
public static IrisData openValidation(File dataFolder) {
|
||||
return new IrisData(dataFolder, Purpose.VALIDATION);
|
||||
}
|
||||
|
||||
/** Every folder below a pack's root that Iris reads itself, which no module resource kind may read. */
|
||||
public static Set<String> ownFolderNames() {
|
||||
Set<String> folders = new TreeSet<>(OTHER_OWN_FOLDERS);
|
||||
for (Class<? extends IrisRegistrant> type : RUNTIME_RESOURCE_TYPES) {
|
||||
try {
|
||||
folders.add(type.getConstructor().newInstance().getFolderName());
|
||||
} catch (ReflectiveOperationException failure) {
|
||||
throw new IllegalStateException("Iris resource type " + type.getName() + " cannot be created", failure);
|
||||
}
|
||||
}
|
||||
return Set.copyOf(folders);
|
||||
}
|
||||
|
||||
public static Optional<IrisData> getLoaded(File dataFolder) {
|
||||
@@ -265,14 +297,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
return loadAny(IrisGenerator.class, key, nearest);
|
||||
}
|
||||
|
||||
public static IrisJigsawPool loadAnyJigsawPool(String key, @Nullable IrisData nearest) {
|
||||
return loadAny(IrisJigsawPool.class, key, nearest);
|
||||
}
|
||||
|
||||
public static IrisJigsawPiece loadAnyJigsawPiece(String key, @Nullable IrisData nearest) {
|
||||
return loadAny(IrisJigsawPiece.class, key, nearest);
|
||||
}
|
||||
|
||||
public static <T extends IrisRegistrant> T loadAny(Class<T> type, String key, @Nullable IrisData nearest) {
|
||||
try {
|
||||
if (nearest != null) {
|
||||
@@ -444,9 +468,9 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
try {
|
||||
IrisRegistrant rr = registrant.getConstructor().newInstance();
|
||||
ResourceLoader<T> r = null;
|
||||
ResourceLoader.Options options = datapackCompiler
|
||||
? ResourceLoader.Options.datapackCompiler()
|
||||
: ResourceLoader.Options.runtime();
|
||||
ResourceLoader.Options options = purpose == Purpose.RUNTIME
|
||||
? ResourceLoader.Options.runtime()
|
||||
: ResourceLoader.Options.datapackCompiler();
|
||||
if (registrant.equals(IrisObject.class)) {
|
||||
r = (ResourceLoader<T>) new ObjectResourceLoader(dataFolder, this, rr.getFolderName(),
|
||||
rr.getTypeName(), options);
|
||||
@@ -476,6 +500,22 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
StructureGraphCatalog.invalidate(this);
|
||||
IrisObjectScale.invalidate(this);
|
||||
closed = false;
|
||||
dataFolder.mkdirs();
|
||||
recoverStructureTransactions();
|
||||
loadRuntimeResources();
|
||||
|
||||
for (Engine engine : getEngines()) {
|
||||
engine.hotload();
|
||||
}
|
||||
}
|
||||
|
||||
private void openForValidation() {
|
||||
closed = false;
|
||||
loadRuntimeResources();
|
||||
}
|
||||
|
||||
/** The runtime loaders, the pack's Gson and a new snapshot of its resources, module resource kinds included. */
|
||||
private void loadRuntimeResources() {
|
||||
possibleSnippets = new KMap<>();
|
||||
builder = new GsonBuilder()
|
||||
.addDeserializationExclusionStrategy(this)
|
||||
@@ -486,9 +526,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
.registerTypeAdapter(MantleFlag.class, new MantleFlagAdapter())
|
||||
.setPrettyPrinting();
|
||||
KMap<Class<? extends IrisRegistrant>, ResourceLoader<? extends IrisRegistrant>> replacement = new KMap<>();
|
||||
File packs = dataFolder;
|
||||
packs.mkdirs();
|
||||
recoverStructureTransactions();
|
||||
this.lootLoader = registerLoader(IrisLootTable.class, replacement);
|
||||
this.spawnerLoader = registerLoader(IrisSpawner.class, replacement);
|
||||
this.entityLoader = registerLoader(IrisEntity.class, replacement);
|
||||
@@ -504,18 +541,11 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
this.imageLoader = registerLoader(IrisImage.class, replacement);
|
||||
this.imageMapLoader = registerLoader(IrisImageMap.class, replacement);
|
||||
this.matterLoader = registerLoader(IrisMatterObject.class, replacement);
|
||||
this.structureLoader = registerLoader(IrisStructure.class, replacement);
|
||||
this.jigsawPoolLoader = registerLoader(IrisJigsawPool.class, replacement);
|
||||
this.jigsawPieceLoader = registerLoader(IrisJigsawPiece.class, replacement);
|
||||
builder.registerTypeAdapterFactory(KeyedType::createTypeAdapter);
|
||||
|
||||
gson = builder.create();
|
||||
loaders = replacement;
|
||||
packResources = new IrisPackResources(this);
|
||||
|
||||
for (Engine engine : getEngines()) {
|
||||
engine.hotload();
|
||||
}
|
||||
}
|
||||
|
||||
private void hotloadedDatapackCompiler() {
|
||||
@@ -547,25 +577,44 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
}
|
||||
}
|
||||
|
||||
/** Forgets everything read so far: the loaders' caches and the module resources, which a new snapshot reads again. */
|
||||
public void dump() {
|
||||
StructureGraphCatalog.invalidate(this);
|
||||
IrisObjectScale.invalidate(this);
|
||||
for (ResourceLoader<?> i : loaders.values()) {
|
||||
i.clearCache();
|
||||
}
|
||||
reloadModuleResources();
|
||||
}
|
||||
|
||||
/** Reads objects and module resources (structures, jigsaw pools and pieces among them) again after a tool rewrote their files. */
|
||||
public synchronized void invalidateStructureResources() {
|
||||
StructureGraphCatalog.invalidate(this);
|
||||
invalidateLoader(objectLoader);
|
||||
invalidateLoader(structureLoader);
|
||||
invalidateLoader(jigsawPoolLoader);
|
||||
invalidateLoader(jigsawPieceLoader);
|
||||
reloadModuleResources();
|
||||
for (Engine engine : getEngines()) {
|
||||
IrisStructureLocator.invalidate(engine);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a new snapshot of the pack's resources, so the files of every module resource kind are listed and read
|
||||
* again, after a tool added, rewrote or deleted some. Iris's own loaders keep their caches.
|
||||
*/
|
||||
public void reloadModuleResources() {
|
||||
packResources = new IrisPackResources(this);
|
||||
}
|
||||
|
||||
/** The folders below the pack root that hold its resources: Iris's loaders' and its modules' resource kinds'. */
|
||||
public List<String> resourceFolderNames() {
|
||||
Set<String> folders = new TreeSet<>();
|
||||
for (ResourceLoader<?> loader : loaders.values()) {
|
||||
folders.add(loader.getFolderName());
|
||||
}
|
||||
folders.addAll(packResources.moduleFolderNames());
|
||||
return List.copyOf(folders);
|
||||
}
|
||||
|
||||
private void recoverStructureTransactions() {
|
||||
StructureRecoveryResult recovery = new StructureTransactionWriter(dataFolder.toPath())
|
||||
.recoverIncompleteTransactions();
|
||||
|
||||
@@ -10,7 +10,8 @@ import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
final class JsonSchemaValidator {
|
||||
/** Warns about JSON a pack file holds that its type ignores, and reports a file that failed to load with the line at fault. */
|
||||
public final class JsonSchemaValidator {
|
||||
private static final int SUGGESTION_MAX_DISTANCE = 4;
|
||||
|
||||
private JsonSchemaValidator() {
|
||||
@@ -20,7 +21,7 @@ final class JsonSchemaValidator {
|
||||
* Warns about every top-level key that is neither a field of {@code objectClass} nor one of
|
||||
* {@code moduleKeys}, the ids and aliases the pack's modules read at this resource's target.
|
||||
*/
|
||||
static void validateTopLevelKeys(JSONObject parsed, String rawText, File file, String resourceTypeName, Class<?> objectClass,
|
||||
public static void validateTopLevelKeys(JSONObject parsed, String rawText, File file, String resourceTypeName, Class<?> objectClass,
|
||||
Set<String> moduleKeys) {
|
||||
if (parsed == null || objectClass == null) {
|
||||
return;
|
||||
@@ -43,7 +44,7 @@ final class JsonSchemaValidator {
|
||||
return known;
|
||||
}
|
||||
|
||||
static void reportLoadFailure(File file, String rawText, String resourceTypeName, Throwable error) {
|
||||
public static void reportLoadFailure(File file, String rawText, String resourceTypeName, Throwable error) {
|
||||
String message = error.getMessage();
|
||||
if (message == null || message.isBlank()) {
|
||||
message = error.getClass().getSimpleName();
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.actuator.BiomeModule;
|
||||
import art.arcane.iris.engine.actuator.DecorantModule;
|
||||
import art.arcane.iris.engine.actuator.TerrainModule;
|
||||
@@ -43,7 +44,8 @@ import java.util.stream.Stream;
|
||||
/**
|
||||
* The one {@link ModuleHost} every pack load uses: Iris's built-in modules, the built-in module API
|
||||
* package exposed to packs, Iris's own JSON fields, the reserved {@code iris} namespace, Iris's pack object
|
||||
* model as host types, a jar copy directory under the plugin's cache, and Iris's log.
|
||||
* model as host types, the pack folders Iris reads itself, a jar copy directory under the plugin's cache, and
|
||||
* Iris's log.
|
||||
*/
|
||||
public final class IrisModuleHost {
|
||||
/** Exposed to pack modules, with its subpackages; see its package documentation. */
|
||||
@@ -83,6 +85,7 @@ public final class IrisModuleHost {
|
||||
.reservingNamespaces(RESERVED_NAMESPACE)
|
||||
.reservingFields(ModuleTargets.reservedFields())
|
||||
.describingHostTypesIn(HOST_TYPE_PACKAGE)
|
||||
.reservingFolders(IrisData.ownFolderNames().toArray(String[]::new))
|
||||
.copyingJarsTo(jarCopyRoot())
|
||||
.loggingTo(new IrisApiLogger(PackModules.class.getName()));
|
||||
}
|
||||
|
||||
@@ -25,13 +25,16 @@ import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import com.volmit.block.BlockRegistry;
|
||||
import com.volmit.host.ResourceKindRegistration;
|
||||
import com.volmit.object.GeneratedObject;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKey;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import com.volmit.world.PackBiome;
|
||||
import com.volmit.world.PackRegion;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -44,29 +47,44 @@ import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The resources of one loaded snapshot of an Iris pack, which every chunk, mantle and placement stage of that
|
||||
* snapshot shares. Each load or hotload of the pack's data makes a new one, with a new {@link #snapshotId()}.
|
||||
* snapshot shares. Each load or hotload of the pack's data makes a new one, with a new {@link #snapshotId()}, and so
|
||||
* does every reload of its module resources ({@link IrisData#dump()}, {@link IrisData#invalidateStructureResources()}).
|
||||
* <p>
|
||||
* Three kinds of resource are served, by the type the key asks for: {@link GeneratedObject} (a pack object, as
|
||||
* its geometry), {@link PackBiome} and {@link PackRegion}. All use the id {@code <pack namespace>:<key>} that
|
||||
* {@link PackResourceIds} gives the pack's biomes in a biome sample, so one id can name a biome and a region.
|
||||
* An id the pack lacks, or of another namespace, is absent; any other type fails with
|
||||
* {@link IllegalArgumentException}. A resource that exists but cannot be loaded fails with
|
||||
* {@link IllegalStateException}. Each resource is built once and kept for the snapshot.
|
||||
* Served by the type the key asks for: {@link GeneratedObject} (a pack object, as its geometry), {@link PackBiome},
|
||||
* {@link PackRegion}, and the type of every {@link ResourceKind} the pack's modules register, read from the kind's
|
||||
* folder ({@link ModuleResourceFiles}). All use the id {@code <pack namespace>:<key>} that {@link PackResourceIds}
|
||||
* gives the pack's biomes in a biome sample, so one id can name a biome and a region. An id the pack lacks, or of
|
||||
* another namespace, is absent; any other type fails with {@link IllegalArgumentException}. A resource that exists
|
||||
* but cannot be loaded fails with {@link IllegalStateException}. Each resource is built once and kept for the
|
||||
* snapshot. The module kinds are looked up the first time one is asked for, which loads the pack's modules.
|
||||
*/
|
||||
public final class IrisPackResources implements PackResources {
|
||||
private static final String SERVED_TYPES = "GeneratedObject, PackBiome and PackRegion";
|
||||
private static final String SERVED_TYPES = "GeneratedObject, PackBiome, PackRegion and the types of the pack's module resource kinds";
|
||||
|
||||
private final IrisData data;
|
||||
private final PackResourceIds ids;
|
||||
private final UUID snapshotId = UUID.randomUUID();
|
||||
private final BlockRegistry blocks = new IrisBlockRegistry();
|
||||
private final Map<Class<?>, Kind<?, ?>> kinds;
|
||||
private final Map<Class<?>, Kind<?>> irisKinds;
|
||||
private final Supplier<List<ResourceKind<?>>> moduleKindList;
|
||||
private volatile Map<Class<?>, Kind<?>> moduleKinds;
|
||||
private volatile List<String> moduleFolders;
|
||||
|
||||
public IrisPackResources(IrisData data) {
|
||||
this(data, () -> data.getModules().pack().catalog().resourceKinds().stream()
|
||||
.<ResourceKind<?>>map(ResourceKindRegistration::kind)
|
||||
.toList());
|
||||
}
|
||||
|
||||
/** @param moduleKinds the resource kinds of the pack's modules, asked for once, when a module kind is first needed */
|
||||
IrisPackResources(IrisData data, Supplier<List<ResourceKind<?>>> moduleKinds) {
|
||||
this.data = data;
|
||||
this.ids = new PackResourceIds(data.getDataFolder());
|
||||
this.kinds = Map.of(
|
||||
GeneratedObject.class, new Kind<IrisObject, GeneratedObject>(ids, data::getObjectLoader, (id, object) -> object.getGeometry()),
|
||||
PackBiome.class, new Kind<IrisBiome, PackBiome>(ids, data::getBiomeLoader, this::biomeOf),
|
||||
PackRegion.class, new Kind<IrisRegion, PackRegion>(ids, data::getRegionLoader, this::regionOf));
|
||||
this.moduleKindList = moduleKinds;
|
||||
this.irisKinds = Map.of(
|
||||
GeneratedObject.class, Kind.<IrisObject, GeneratedObject>ofLoader(ids, data::getObjectLoader, (id, object) -> object.getGeometry()),
|
||||
PackBiome.class, Kind.<IrisBiome, PackBiome>ofLoader(ids, data::getBiomeLoader, this::biomeOf),
|
||||
PackRegion.class, Kind.<IrisRegion, PackRegion>ofLoader(ids, data::getRegionLoader, this::regionOf));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -87,11 +105,59 @@ public final class IrisPackResources implements PackResources {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked") // The kinds are keyed by the type they serve.
|
||||
public <T> Optional<T> find(ResourceKey<T> key) {
|
||||
Kind<?, T> kind = (Kind<?, T>) kinds.get(key.type());
|
||||
if (kind == null) {
|
||||
throw new IllegalArgumentException("Iris serves pack resources of " + SERVED_TYPES + ", not " + key.type().getName());
|
||||
return ((Kind<T>) kindOf(key.type())).find(key.id());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourceId> ids(Class<?> type) {
|
||||
return kindOf(type).ids();
|
||||
}
|
||||
|
||||
/** The id of the resource the pack names by {@code packKey}, such as {@code overworld:castle/keep} for {@code castle/keep}. */
|
||||
public ResourceId idOf(String packKey) {
|
||||
return ids.of(packKey);
|
||||
}
|
||||
|
||||
/** The folders the pack's module resource kinds read, which loads the pack's modules. */
|
||||
public List<String> moduleFolderNames() {
|
||||
List<String> folders = moduleFolders;
|
||||
if (folders == null) {
|
||||
folders = moduleKindList.get().stream().map(ResourceKind::folder).sorted().toList();
|
||||
moduleFolders = folders;
|
||||
}
|
||||
return kind.find(key.id());
|
||||
return folders;
|
||||
}
|
||||
|
||||
private Kind<?> kindOf(Class<?> type) {
|
||||
Kind<?> iris = irisKinds.get(type);
|
||||
if (iris != null) {
|
||||
return iris;
|
||||
}
|
||||
Kind<?> module = moduleKinds().get(type);
|
||||
if (module == null) {
|
||||
throw new IllegalArgumentException("Iris serves pack resources of " + SERVED_TYPES + ", not " + type.getName());
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
||||
private Map<Class<?>, Kind<?>> moduleKinds() {
|
||||
Map<Class<?>, Kind<?>> kinds = moduleKinds;
|
||||
if (kinds != null) {
|
||||
return kinds;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (moduleKinds == null) {
|
||||
Map<Class<?>, Kind<?>> found = new HashMap<>();
|
||||
moduleKindList.get().forEach(kind -> found.put(kind.type(), moduleKind(kind)));
|
||||
moduleKinds = Map.copyOf(found);
|
||||
}
|
||||
return moduleKinds;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> Kind<T> moduleKind(ResourceKind<T> kind) {
|
||||
ModuleResourceFiles<T> files = new ModuleResourceFiles<>(data, kind);
|
||||
return new Kind<>(ids, files::keys, (id, key) -> files.read(key));
|
||||
}
|
||||
|
||||
private PackBiome biomeOf(ResourceId id, IrisBiome biome) {
|
||||
@@ -107,18 +173,28 @@ public final class IrisPackResources implements PackResources {
|
||||
return keys.stream().map(ids::of).toList();
|
||||
}
|
||||
|
||||
/** One kind of pack resource: the loader that serves its keys, an index from ids to keys and what was built so far. */
|
||||
private static final class Kind<R extends IrisRegistrant, T> {
|
||||
/** One kind of pack resource: the keys the pack has, how a key's resource is read, an index from ids to keys and what was read so far. */
|
||||
private static final class Kind<T> {
|
||||
private final PackResourceIds ids;
|
||||
private final Supplier<ResourceLoader<R>> loader;
|
||||
private final BiFunction<ResourceId, R, T> conversion;
|
||||
private final Supplier<Collection<String>> keys;
|
||||
private final BiFunction<ResourceId, String, T> read;
|
||||
private final Map<ResourceId, T> built = new ConcurrentHashMap<>();
|
||||
private volatile Map<ResourceId, String> keysById;
|
||||
|
||||
Kind(PackResourceIds ids, Supplier<ResourceLoader<R>> loader, BiFunction<ResourceId, R, T> conversion) {
|
||||
/** {@code read} gives the resource of a key, or null when it exists but fails to load. */
|
||||
Kind(PackResourceIds ids, Supplier<Collection<String>> keys, BiFunction<ResourceId, String, T> read) {
|
||||
this.ids = ids;
|
||||
this.loader = loader;
|
||||
this.conversion = conversion;
|
||||
this.keys = keys;
|
||||
this.read = read;
|
||||
}
|
||||
|
||||
/** A kind Iris's own loader serves, each loaded resource converted into what IrisApi hands out. */
|
||||
static <R extends IrisRegistrant, T> Kind<T> ofLoader(PackResourceIds ids, Supplier<ResourceLoader<R>> loader,
|
||||
BiFunction<ResourceId, R, T> conversion) {
|
||||
return new Kind<>(ids, () -> Arrays.asList(loader.get().getPossibleKeys()), (id, key) -> {
|
||||
R resource = loader.get().load(key);
|
||||
return resource == null ? null : conversion.apply(id, resource);
|
||||
});
|
||||
}
|
||||
|
||||
Optional<T> find(ResourceId id) {
|
||||
@@ -130,15 +206,18 @@ public final class IrisPackResources implements PackResources {
|
||||
if (key == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
R resource = loader.get().load(key);
|
||||
if (resource == null) {
|
||||
T made = read.apply(id, key);
|
||||
if (made == null) {
|
||||
throw new IllegalStateException("Pack resource " + id + " exists but failed to load");
|
||||
}
|
||||
T made = conversion.apply(id, resource);
|
||||
T raced = built.putIfAbsent(id, made);
|
||||
return Optional.of(raced != null ? raced : made);
|
||||
}
|
||||
|
||||
List<ResourceId> ids() {
|
||||
return keysById().keySet().stream().sorted().toList();
|
||||
}
|
||||
|
||||
/** The pack's keys by the ids they get, built on first use; a key whose id another key already has is left out. */
|
||||
private Map<ResourceId, String> keysById() {
|
||||
Map<ResourceId, String> index = keysById;
|
||||
@@ -146,7 +225,7 @@ public final class IrisPackResources implements PackResources {
|
||||
return index;
|
||||
}
|
||||
Map<ResourceId, String> indexed = new HashMap<>();
|
||||
for (String key : loader.get().getPossibleKeys()) {
|
||||
for (String key : keys.get()) {
|
||||
indexed.putIfAbsent(ids.of(key), key);
|
||||
}
|
||||
keysById = Map.copyOf(indexed);
|
||||
|
||||
@@ -27,6 +27,7 @@ import com.volmit.FeatureAttachment.Target;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.FeatureSettings.Entry;
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.resource.ResourceId;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -38,9 +39,9 @@ import java.util.List;
|
||||
* {@link #of(PackSettings)}.
|
||||
*/
|
||||
public final class IrisPackSettings implements PackSettings {
|
||||
private static final String DIMENSION = "dimension";
|
||||
private static final String REGION = "region";
|
||||
private static final String BIOME = "biome";
|
||||
static final String DIMENSION = "dimension";
|
||||
static final String REGION = "region";
|
||||
static final String BIOME = "biome";
|
||||
|
||||
private final Engine engine;
|
||||
private final PackResourceIds ids;
|
||||
@@ -67,19 +68,19 @@ public final class IrisPackSettings implements PackSettings {
|
||||
public <F extends IrisFeature> List<Entry<F>> declared(Class<F> featureType) {
|
||||
IrisDimension dimension = engine.getDimension();
|
||||
List<Entry<F>> entries = new ArrayList<>();
|
||||
addEntry(entries, featureType, Target.DIMENSION, DIMENSION, dimension);
|
||||
addEntry(entries, featureType, Target.DIMENSION, ids.of(DIMENSION, dimension.getLoadKey()), dimension);
|
||||
for (IrisRegion region : dimension.getAllRegions(engine)) {
|
||||
addEntry(entries, featureType, Target.REGION, REGION, region);
|
||||
addEntry(entries, featureType, Target.REGION, ids.of(REGION, region.getLoadKey()), region);
|
||||
}
|
||||
for (IrisBiome biome : dimension.getReachableBiomes(engine)) {
|
||||
addEntry(entries, featureType, Target.BIOME, BIOME, biome);
|
||||
addEntry(entries, featureType, Target.BIOME, ids.of(BIOME, biome.getLoadKey()), biome);
|
||||
}
|
||||
return List.copyOf(entries);
|
||||
}
|
||||
|
||||
private <F extends IrisFeature> void addEntry(List<Entry<F>> entries, Class<F> featureType, Target level, String kind,
|
||||
IrisRegistrant owner) {
|
||||
owner.getModuleSettings().find(featureType)
|
||||
.ifPresent(value -> entries.add(new Entry<>(level, ids.of(kind, owner.getLoadKey()), value)));
|
||||
/** Adds {@code owner}'s settings of {@code featureType}, if it declares them, as an entry from {@code source}. */
|
||||
static <F extends IrisFeature> void addEntry(List<Entry<F>> entries, Class<F> featureType, Target level, ResourceId source,
|
||||
IrisRegistrant owner) {
|
||||
owner.getModuleSettings().find(featureType).ifPresent(value -> entries.add(new Entry<>(level, source, value)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.validation.Problem;
|
||||
import com.volmit.validation.ValidationContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* What one module validator sees of a pack Iris validates: the pack's resources and its settings as Iris loads them
|
||||
* ({@link PackDeclaredSettings}), and the problems it reported. Built-in validators that still read Iris's own pack
|
||||
* data reach it through {@link #of(ValidationContext)}, as built-in stages reach the engine through their carriers.
|
||||
*/
|
||||
public final class IrisValidationContext implements ValidationContext {
|
||||
private final IrisData data;
|
||||
private final PackSettings settings;
|
||||
private final List<Problem> problems = new ArrayList<>();
|
||||
|
||||
private IrisValidationContext(IrisData data) {
|
||||
this.data = data;
|
||||
this.settings = new PackDeclaredSettings(data);
|
||||
}
|
||||
|
||||
/** A context for one validator run over the pack {@code data} holds. */
|
||||
public static IrisValidationContext forPack(IrisData data) {
|
||||
return new IrisValidationContext(Objects.requireNonNull(data, "data"));
|
||||
}
|
||||
|
||||
/** Iris's own view of {@code context}, which Iris hands to every validator it runs. */
|
||||
public static IrisValidationContext of(ValidationContext context) {
|
||||
if (!(context instanceof IrisValidationContext irisContext)) {
|
||||
throw new IllegalArgumentException("Built-in validators check packs Iris validates, not " + context);
|
||||
}
|
||||
return irisContext;
|
||||
}
|
||||
|
||||
/** The pack's data, opened for this validation. */
|
||||
public IrisData data() {
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackResources resources() {
|
||||
return data.getPackResources();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackSettings settings() {
|
||||
return settings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void report(Problem problem) {
|
||||
problems.add(Objects.requireNonNull(problem, "problem"));
|
||||
}
|
||||
|
||||
/** What the validator reported, in order. */
|
||||
public List<Problem> problems() {
|
||||
return List.copyOf(problems);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.core.loader.JsonSchemaValidator;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The files of one module resource kind in a pack: every {@code .json} file below the kind's folder, keyed by its
|
||||
* path below the folder without the extension, and each file read into a new resource of the kind.
|
||||
* <p>
|
||||
* A file is read with the pack's module decoder, which hands Iris's own classes to the pack's Gson, so a built-in
|
||||
* kind such as structures reads exactly as Iris's loaders read. A resource that is one of Iris's registrants gets its
|
||||
* key, file and pack data, as a loader would set them. A file that fails to read is reported with the line at fault,
|
||||
* like a loader's, and gives no resource. Unknown keys are reported for Iris's own classes only: the check caches
|
||||
* field names per class, which would keep a pack module's classes loaded after the pack closes.
|
||||
*/
|
||||
public final class ModuleResourceFiles<T> {
|
||||
private static final String JSON_EXTENSION = ".json";
|
||||
private static final char FOLDER_SEPARATOR = '/';
|
||||
|
||||
private final IrisData data;
|
||||
private final ResourceKind<T> kind;
|
||||
private final Path folder;
|
||||
private final String typeName;
|
||||
|
||||
ModuleResourceFiles(IrisData data, ResourceKind<T> kind) {
|
||||
this.data = data;
|
||||
this.kind = kind;
|
||||
this.folder = data.getDataFolder().toPath().resolve(kind.folder());
|
||||
this.typeName = typeName(kind);
|
||||
}
|
||||
|
||||
/** The key of every file of the kind, in key order; none when the pack has no folder for it. */
|
||||
List<String> keys() {
|
||||
if (!Files.isDirectory(folder)) {
|
||||
return List.of();
|
||||
}
|
||||
try (Stream<Path> files = Files.walk(folder)) {
|
||||
return files.filter(Files::isRegularFile)
|
||||
.map(this::keyOf)
|
||||
.filter(Objects::nonNull)
|
||||
.sorted()
|
||||
.toList();
|
||||
} catch (IOException failure) {
|
||||
throw new UncheckedIOException("Cannot list the files of resource kind " + kind.id() + " in " + folder, failure);
|
||||
}
|
||||
}
|
||||
|
||||
/** The file of {@code key} read into a new resource, or null when it fails to read, which is reported. */
|
||||
T read(String key) {
|
||||
File file = folder.resolve(key + JSON_EXTENSION).toFile();
|
||||
String json = null;
|
||||
try {
|
||||
json = Files.readString(file.toPath(), StandardCharsets.UTF_8);
|
||||
reportUnknownKeys(json, file);
|
||||
T resource = data.getModules().settings().decodeResource(kind.type(), json);
|
||||
describeOrigin(resource, key, file);
|
||||
return resource;
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
JsonSchemaValidator.reportLoadFailure(file, json, typeName, failure);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String keyOf(Path file) {
|
||||
String relative = folder.relativize(file).toString().replace(file.getFileSystem().getSeparator(), String.valueOf(FOLDER_SEPARATOR));
|
||||
if (!relative.endsWith(JSON_EXTENSION) || relative.length() == JSON_EXTENSION.length()) {
|
||||
return null;
|
||||
}
|
||||
return relative.substring(0, relative.length() - JSON_EXTENSION.length());
|
||||
}
|
||||
|
||||
private void reportUnknownKeys(String json, File file) {
|
||||
if (!IrisModuleHost.isHostType(kind.type())) {
|
||||
return;
|
||||
}
|
||||
JsonSchemaValidator.validateTopLevelKeys(new JSONObject(json), json, file, typeName, kind.type(), Set.of());
|
||||
}
|
||||
|
||||
private void describeOrigin(T resource, String key, File file) {
|
||||
if (!(resource instanceof IrisRegistrant registrant)) {
|
||||
return;
|
||||
}
|
||||
registrant.setLoadKey(key);
|
||||
registrant.setLoadFile(file);
|
||||
registrant.setLoader(data);
|
||||
}
|
||||
|
||||
/** What load reports and studio call a resource of {@code kind}: an Iris registrant's own type name, such as Structure, or else the kind's id. */
|
||||
public static String typeName(ResourceKind<?> kind) {
|
||||
if (!IrisRegistrant.class.isAssignableFrom(kind.type())) {
|
||||
return kind.id().toString();
|
||||
}
|
||||
try {
|
||||
return ((IrisRegistrant) kind.type().getConstructor().newInstance()).getTypeName();
|
||||
} catch (ReflectiveOperationException failure) {
|
||||
return kind.id().toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,21 @@ public final class ModuleSettingsDecoder {
|
||||
return ModuleSettings.of(values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the JSON of a module resource file into a new {@code type}, created with its no-argument constructor so an
|
||||
* omitted option keeps its default. Iris's own classes, which built-in resource kinds may read into, are read by
|
||||
* the pack's Gson like every Iris resource.
|
||||
*
|
||||
* @throws RuntimeException when the JSON does not decode into {@code type}
|
||||
*/
|
||||
public <T> T decodeResource(Class<T> type, String json) {
|
||||
T decoded = gson.fromJson(json, type);
|
||||
if (decoded == null) {
|
||||
throw new JsonParseException("the file holds null");
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
|
||||
private static Optional<String> presentKey(FeatureDescriptor<?> feature, JSONObject json, String resource) {
|
||||
boolean hasKey = json.has(feature.key());
|
||||
Optional<String> alias = feature.alias().filter(json::has);
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import com.volmit.FeatureAttachment.Target;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.FeatureSettings.Entry;
|
||||
import com.volmit.config.PackSettings;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The settings a whole pack declares, for validators: every dimension of the pack, then every region, then every
|
||||
* biome, each in key order, whether a dimension reaches it or not. A file that fails to load declares nothing; its
|
||||
* loader reports it.
|
||||
*/
|
||||
final class PackDeclaredSettings implements PackSettings {
|
||||
private final IrisData data;
|
||||
private final PackResourceIds ids;
|
||||
|
||||
PackDeclaredSettings(IrisData data) {
|
||||
this.data = data;
|
||||
this.ids = new PackResourceIds(data.getDataFolder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <F extends IrisFeature> List<Entry<F>> declared(Class<F> featureType) {
|
||||
List<Entry<F>> entries = new ArrayList<>();
|
||||
addEntries(entries, featureType, Target.DIMENSION, IrisPackSettings.DIMENSION, data.getDimensionLoader());
|
||||
addEntries(entries, featureType, Target.REGION, IrisPackSettings.REGION, data.getRegionLoader());
|
||||
addEntries(entries, featureType, Target.BIOME, IrisPackSettings.BIOME, data.getBiomeLoader());
|
||||
return List.copyOf(entries);
|
||||
}
|
||||
|
||||
private <F extends IrisFeature, R extends IrisRegistrant> void addEntries(List<Entry<F>> entries, Class<F> featureType,
|
||||
Target level, String kind, ResourceLoader<R> loader) {
|
||||
for (String key : Arrays.stream(loader.getPossibleKeys()).sorted().toList()) {
|
||||
R owner = loader.load(key, false);
|
||||
if (owner != null) {
|
||||
IrisPackSettings.addEntry(entries, featureType, level, ids.of(kind, key), owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.core.project.ModuleResourceSchemas;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.IrisWorld;
|
||||
@@ -375,6 +376,7 @@ public class IrisPack {
|
||||
schemas.put(r.buildSchema());
|
||||
}
|
||||
}
|
||||
ModuleResourceSchemas.entries(dm, false).forEach(schemas::put);
|
||||
|
||||
settings.put("json.schemas", schemas);
|
||||
ws.put("settings", settings);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* 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.pack;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisValidationContext;
|
||||
import art.arcane.iris.core.modules.PackModulesException;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import com.volmit.host.ValidatorRegistration;
|
||||
import com.volmit.validation.Problem;
|
||||
import com.volmit.validation.Severity;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Runs the validators of a pack's modules, built-in ones included, on the pack as Iris loads it, opened just for
|
||||
* this ({@link IrisData#openValidation}) and closed afterwards. Each problem becomes the text
|
||||
* {@code <subject>: <message>}; errors block the pack like Iris's own validators' errors, warnings are only shown.
|
||||
* A pack whose modules fail to load gets that failure as its error. A validator that throws gets an error naming its
|
||||
* module, and the others still run.
|
||||
*/
|
||||
final class ModulePackValidation {
|
||||
private ModulePackValidation() {
|
||||
}
|
||||
|
||||
/** What the pack's validators found. */
|
||||
record Findings(List<String> errors, List<String> warnings) {
|
||||
Findings {
|
||||
errors = List.copyOf(errors);
|
||||
warnings = List.copyOf(warnings);
|
||||
}
|
||||
}
|
||||
|
||||
static Findings validate(File packFolder) {
|
||||
IrisData data = IrisData.openValidation(packFolder);
|
||||
try {
|
||||
return validate(data);
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
private static Findings validate(IrisData data) {
|
||||
List<ValidatorRegistration> validators;
|
||||
try {
|
||||
validators = data.getModules().pack().catalog().validators();
|
||||
} catch (PackModulesException failure) {
|
||||
return new Findings(List.of(failure.getMessage()), List.of());
|
||||
}
|
||||
return validate(data, validators);
|
||||
}
|
||||
|
||||
/** Runs {@code validators} on the pack {@code data} holds, in order. */
|
||||
static Findings validate(IrisData data, List<ValidatorRegistration> validators) {
|
||||
List<String> errors = new ArrayList<>();
|
||||
List<String> warnings = new ArrayList<>();
|
||||
for (ValidatorRegistration validator : validators) {
|
||||
run(validator, data, errors, warnings);
|
||||
}
|
||||
return new Findings(errors, warnings);
|
||||
}
|
||||
|
||||
private static void run(ValidatorRegistration registration, IrisData data, List<String> errors, List<String> warnings) {
|
||||
IrisValidationContext context = IrisValidationContext.forPack(data);
|
||||
try {
|
||||
registration.validator().validate(context);
|
||||
} catch (RuntimeException failure) {
|
||||
IrisLogging.reportError(failure);
|
||||
errors.add("Module " + registration.module() + " failed while validating the pack: " + failure);
|
||||
}
|
||||
for (Problem problem : context.problems()) {
|
||||
(problem.severity() == Severity.ERROR ? errors : warnings).add(text(problem));
|
||||
}
|
||||
}
|
||||
|
||||
private static String text(Problem problem) {
|
||||
return problem.subject() + ": " + problem.message();
|
||||
}
|
||||
}
|
||||
@@ -1,341 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.pack;
|
||||
|
||||
import art.arcane.iris.engine.object.placement.ObjectPlaceMode;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class PackNativeStructureValidator {
|
||||
private PackNativeStructureValidator() {
|
||||
}
|
||||
|
||||
static List<String> validateNativeStructureReplacements(
|
||||
File packFolder,
|
||||
Set<String> replacementOutputStructures,
|
||||
Map<String, List<StructureGraphPackValidator.SampledVerticalEnvelope>> sampledVerticalEnvelopes
|
||||
) {
|
||||
List<String> blockingErrors = new ArrayList<>();
|
||||
if (packFolder == null || !packFolder.isDirectory()) {
|
||||
return blockingErrors;
|
||||
}
|
||||
Set<String> viableStructures = replacementOutputStructures == null
|
||||
? Set.of() : replacementOutputStructures;
|
||||
Map<String, List<StructureGraphPackValidator.SampledVerticalEnvelope>> verticalEnvelopes =
|
||||
sampledVerticalEnvelopes == null ? Map.of() : sampledVerticalEnvelopes;
|
||||
File structuresFolder = new File(packFolder, PackValidator.STRUCTURES_FOLDER);
|
||||
Map<String, JSONObject> structures = new HashMap<>();
|
||||
for (File structureFile : PackValidationIo.listJsonRecursive(structuresFolder)) {
|
||||
JSONObject structure = PackValidationIo.readJson(structureFile);
|
||||
if (structure != null) {
|
||||
structures.put(PackValidationIo.deriveKey(structuresFolder, structureFile), structure);
|
||||
}
|
||||
}
|
||||
|
||||
for (String folderName : PackValidator.STRUCTURE_HOST_FOLDERS) {
|
||||
File resourceFolder = new File(packFolder, folderName);
|
||||
if (!resourceFolder.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
List<File> resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder);
|
||||
resourceFiles.sort(Comparator.comparing(File::getPath));
|
||||
String resourceType = PackStructurePlacementValidator.structureHostType(folderName);
|
||||
for (File resourceFile : resourceFiles) {
|
||||
JSONObject resource = PackValidationIo.readJson(resourceFile);
|
||||
if (resource == null) {
|
||||
continue;
|
||||
}
|
||||
JSONArray placements = resource.optJSONArray("structures");
|
||||
if (placements == null) {
|
||||
continue;
|
||||
}
|
||||
String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile);
|
||||
for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) {
|
||||
JSONObject placement = placements.optJSONObject(placementIndex);
|
||||
if (placement == null || !placement.has("nativeSuppression")) {
|
||||
continue;
|
||||
}
|
||||
Object rawSuppression = placement.opt("nativeSuppression");
|
||||
if (!(rawSuppression instanceof String suppression)) {
|
||||
blockingErrors.add(resourceType + " '" + resourceKey + "' structures["
|
||||
+ placementIndex + "].nativeSuppression must be NONE or REPLACE_SOURCE.");
|
||||
continue;
|
||||
}
|
||||
if ("NONE".equals(suppression)) {
|
||||
continue;
|
||||
}
|
||||
if (!"REPLACE_SOURCE".equals(suppression)) {
|
||||
blockingErrors.add(resourceType + " '" + resourceKey + "' structures["
|
||||
+ placementIndex + "].nativeSuppression has unsupported value '"
|
||||
+ suppression + "'. Use NONE or REPLACE_SOURCE.");
|
||||
continue;
|
||||
}
|
||||
if (!PackValidator.DIMENSIONS_FOLDER.equals(folderName)) {
|
||||
blockingErrors.add(resourceType + " '" + resourceKey + "' structures["
|
||||
+ placementIndex + "] requests REPLACE_SOURCE, but native replacement is only"
|
||||
+ " valid on dimension-level placements.");
|
||||
continue;
|
||||
}
|
||||
JSONArray references = placement.optJSONArray("structures");
|
||||
JSONArray nativeStructures = placement.optJSONArray("nativeStructures");
|
||||
if (nativeStructures != null && nativeStructures.length() > 0) {
|
||||
continue;
|
||||
}
|
||||
if (references == null || references.length() == 0) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "] requests REPLACE_SOURCE without any structure backend.");
|
||||
continue;
|
||||
}
|
||||
for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) {
|
||||
Object rawReference = references.opt(referenceIndex);
|
||||
if (!(rawReference instanceof String structureKey) || structureKey.isBlank()) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "].structures[" + referenceIndex
|
||||
+ "] must name an Iris structure for REPLACE_SOURCE.");
|
||||
continue;
|
||||
}
|
||||
JSONObject structure = structures.get(structureKey);
|
||||
if (structure == null) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "] cannot REPLACE_SOURCE with missing or invalid structure '"
|
||||
+ structureKey + "'.");
|
||||
continue;
|
||||
}
|
||||
String vanillaSource = structure.optString("vanillaSource", "").trim();
|
||||
if (!PackValidator.RESOURCE_KEY_PATTERN.matcher(vanillaSource).matches()) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "] requests REPLACE_SOURCE for structure '" + structureKey
|
||||
+ "', but its vanillaSource is not a valid namespaced registry key.");
|
||||
}
|
||||
if (!viableStructures.contains(structureKey)) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "] requests REPLACE_SOURCE for structure '" + structureKey
|
||||
+ "', but that structure is not runtime-viable. Native generation will not"
|
||||
+ " be used as a fallback.");
|
||||
continue;
|
||||
}
|
||||
validateReplacementVerticalEnvelope(
|
||||
resourceKey,
|
||||
resource,
|
||||
placementIndex,
|
||||
placement,
|
||||
structureKey,
|
||||
structure,
|
||||
verticalEnvelopes.get(structureKey),
|
||||
blockingErrors);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return blockingErrors;
|
||||
}
|
||||
|
||||
private static void validateReplacementVerticalEnvelope(
|
||||
String dimensionKey,
|
||||
JSONObject dimension,
|
||||
int placementIndex,
|
||||
JSONObject placement,
|
||||
String structureKey,
|
||||
JSONObject structure,
|
||||
List<StructureGraphPackValidator.SampledVerticalEnvelope> sampledVerticalEnvelopes,
|
||||
List<String> blockingErrors
|
||||
) {
|
||||
String context = "Dimension '" + dimensionKey + "' structures[" + placementIndex
|
||||
+ "] REPLACE_SOURCE structure '" + structureKey + "'";
|
||||
if (sampledVerticalEnvelopes == null || sampledVerticalEnvelopes.isEmpty()) {
|
||||
blockingErrors.add(context + " has no sampled vertical envelope. Native generation will not"
|
||||
+ " be used as a fallback.");
|
||||
return;
|
||||
}
|
||||
|
||||
DimensionVerticalBounds worldBounds = resolveDimensionVerticalBounds(dimension, context, blockingErrors);
|
||||
PlacementVerticalBounds placementBounds = resolvePlacementVerticalBounds(placement, context, blockingErrors);
|
||||
ObjectPlaceMode placeMode = resolvePlaceMode(structure, context, blockingErrors);
|
||||
if (worldBounds == null || placementBounds == null || placeMode == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (StructureGraphPackValidator.SampledVerticalEnvelope sampled : sampledVerticalEnvelopes) {
|
||||
boolean exactY = placementBounds.underground()
|
||||
|| sampled.pieceCount() > 1
|
||||
|| placeMode == ObjectPlaceMode.STRUCTURE_PIECE
|
||||
|| placeMode == ObjectPlaceMode.FLOATING;
|
||||
if (!exactY) {
|
||||
continue;
|
||||
}
|
||||
|
||||
long minimumYOffset = sampled.minimumYOffset();
|
||||
long maximumYOffset = sampled.maximumYOffset();
|
||||
boolean surfaceAligned = !placementBounds.underground()
|
||||
&& sampled.pieceCount() > 1
|
||||
&& placeMode != ObjectPlaceMode.STRUCTURE_PIECE
|
||||
&& placeMode != ObjectPlaceMode.FLOATING;
|
||||
if (surfaceAligned) {
|
||||
maximumYOffset -= minimumYOffset;
|
||||
minimumYOffset = 0L;
|
||||
}
|
||||
|
||||
boolean fitsConfiguredRange;
|
||||
if (placementBounds.underground()) {
|
||||
long minimumAnchor = Math.max(
|
||||
Math.max(placementBounds.minimumY(), worldBounds.minimumY()),
|
||||
worldBounds.minimumY() - minimumYOffset);
|
||||
long maximumAnchor = Math.min(
|
||||
Math.min(placementBounds.maximumY(), worldBounds.maximumY()),
|
||||
worldBounds.maximumY() - maximumYOffset);
|
||||
fitsConfiguredRange = minimumAnchor <= maximumAnchor;
|
||||
} else {
|
||||
long minimumTerrainY = Math.max(placementBounds.minimumY(), worldBounds.minimumY());
|
||||
long maximumTerrainY = Math.min(placementBounds.maximumY(), worldBounds.maximumY());
|
||||
fitsConfiguredRange = minimumTerrainY <= maximumTerrainY
|
||||
&& minimumTerrainY + minimumYOffset >= worldBounds.minimumY()
|
||||
&& maximumTerrainY + maximumYOffset <= worldBounds.maximumY();
|
||||
}
|
||||
if (fitsConfiguredRange) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String alignment = surfaceAligned ? "surface-aligned " : "";
|
||||
blockingErrors.add(context + " sampled seed " + sampled.seed() + " has an " + alignment
|
||||
+ "exact-Y piece envelope " + minimumYOffset + ".." + maximumYOffset
|
||||
+ " relative to its anchor, which cannot fit placement band "
|
||||
+ placementBounds.minimumY() + ".." + placementBounds.maximumY()
|
||||
+ " inside writable world " + worldBounds.minimumY() + ".." + worldBounds.maximumY()
|
||||
+ ". Native generation will not be used as a fallback.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static DimensionVerticalBounds resolveDimensionVerticalBounds(
|
||||
JSONObject dimension,
|
||||
String context,
|
||||
List<String> blockingErrors
|
||||
) {
|
||||
long dimensionMinimum = -64L;
|
||||
long dimensionMaximum = 320L;
|
||||
if (dimension.has("dimensionHeight")) {
|
||||
JSONObject dimensionHeight = dimension.optJSONObject("dimensionHeight");
|
||||
if (dimensionHeight == null) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight"
|
||||
+ " must be an object.");
|
||||
return null;
|
||||
}
|
||||
Long configuredMinimum = integralJsonNumber(dimensionHeight, "min", 16L);
|
||||
Long configuredMaximum = integralJsonNumber(dimensionHeight, "max", 32L);
|
||||
if (configuredMinimum == null || configuredMaximum == null) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight"
|
||||
+ " min and max must be finite integer values.");
|
||||
return null;
|
||||
}
|
||||
dimensionMinimum = configuredMinimum;
|
||||
dimensionMaximum = configuredMaximum;
|
||||
}
|
||||
|
||||
long writableMinimum = dimensionMinimum + 1L;
|
||||
long writableMaximum = dimensionMaximum - 1L;
|
||||
if (writableMinimum > writableMaximum) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight "
|
||||
+ dimensionMinimum + ".." + dimensionMaximum + " has no writable structure range.");
|
||||
return null;
|
||||
}
|
||||
return new DimensionVerticalBounds(writableMinimum, writableMaximum);
|
||||
}
|
||||
|
||||
private static PlacementVerticalBounds resolvePlacementVerticalBounds(
|
||||
JSONObject placement,
|
||||
String context,
|
||||
List<String> blockingErrors
|
||||
) {
|
||||
boolean underground = false;
|
||||
if (placement.has("underground")) {
|
||||
Object rawUnderground = placement.opt("underground");
|
||||
if (!(rawUnderground instanceof Boolean configuredUnderground)) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because underground"
|
||||
+ " must be true or false.");
|
||||
return null;
|
||||
}
|
||||
underground = configuredUnderground;
|
||||
}
|
||||
Long configuredMinimum = integralJsonNumber(placement, "minHeight", -2032L);
|
||||
Long configuredMaximum = integralJsonNumber(placement, "maxHeight", 2032L);
|
||||
if (configuredMinimum == null || configuredMaximum == null) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because minHeight and"
|
||||
+ " maxHeight must be finite integer values.");
|
||||
return null;
|
||||
}
|
||||
long minimumY = underground
|
||||
? Math.min(configuredMinimum, configuredMaximum) : configuredMinimum;
|
||||
long maximumY = underground
|
||||
? Math.max(configuredMinimum, configuredMaximum) : configuredMaximum;
|
||||
return new PlacementVerticalBounds(minimumY, maximumY, underground);
|
||||
}
|
||||
|
||||
private static ObjectPlaceMode resolvePlaceMode(
|
||||
JSONObject structure,
|
||||
String context,
|
||||
List<String> blockingErrors
|
||||
) {
|
||||
if (!structure.has("placeMode")) {
|
||||
return ObjectPlaceMode.STRUCTURE_PIECE;
|
||||
}
|
||||
Object rawPlaceMode = structure.opt("placeMode");
|
||||
if (!(rawPlaceMode instanceof String placeModeName)) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because placeMode must name"
|
||||
+ " an Iris object place mode.");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return ObjectPlaceMode.valueOf(placeModeName);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because placeMode '"
|
||||
+ placeModeName + "' is not supported.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Long integralJsonNumber(JSONObject owner, String field, long defaultValue) {
|
||||
if (!owner.has(field)) {
|
||||
return defaultValue;
|
||||
}
|
||||
Object rawValue = owner.opt(field);
|
||||
if (!(rawValue instanceof Number number)) {
|
||||
return null;
|
||||
}
|
||||
double value = number.doubleValue();
|
||||
if (!Double.isFinite(value) || value != Math.rint(value)
|
||||
|| value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
|
||||
return null;
|
||||
}
|
||||
return (long) value;
|
||||
}
|
||||
|
||||
private record DimensionVerticalBounds(long minimumY, long maximumY) {
|
||||
}
|
||||
|
||||
private record PlacementVerticalBounds(long minimumY, long maximumY, boolean underground) {
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,6 @@ import art.arcane.volmlib.util.json.JSONObject;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -32,46 +31,6 @@ final class PackObjectSurfaceValidator {
|
||||
private PackObjectSurfaceValidator() {
|
||||
}
|
||||
|
||||
static Set<String> collectPlacedStructureKeys(File packFolder) {
|
||||
Set<String> structureKeys = new LinkedHashSet<>();
|
||||
if (packFolder == null || !packFolder.isDirectory()) {
|
||||
return structureKeys;
|
||||
}
|
||||
for (String folderName : PackValidator.STRUCTURE_HOST_FOLDERS) {
|
||||
File resourceFolder = new File(packFolder, folderName);
|
||||
if (!resourceFolder.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
for (File resourceFile : PackValidationIo.listJsonRecursive(resourceFolder)) {
|
||||
JSONObject resource = PackValidationIo.readJson(resourceFile);
|
||||
if (resource == null) {
|
||||
continue;
|
||||
}
|
||||
JSONArray placements = resource.optJSONArray("structures");
|
||||
if (placements == null) {
|
||||
continue;
|
||||
}
|
||||
for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) {
|
||||
JSONObject placement = placements.optJSONObject(placementIndex);
|
||||
if (placement == null) {
|
||||
continue;
|
||||
}
|
||||
JSONArray references = placement.optJSONArray("structures");
|
||||
if (references == null) {
|
||||
continue;
|
||||
}
|
||||
for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) {
|
||||
Object rawReference = references.opt(referenceIndex);
|
||||
if (rawReference instanceof String structureKey && !structureKey.isBlank()) {
|
||||
structureKeys.add(structureKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Set.copyOf(structureKeys);
|
||||
}
|
||||
|
||||
static List<String> validateUnsupportedStructureTransforms(File packFolder) {
|
||||
List<String> blockingErrors = new ArrayList<>();
|
||||
if (packFolder == null || !packFolder.isDirectory()) {
|
||||
|
||||
@@ -35,7 +35,8 @@ public final class PackValidationIo {
|
||||
private PackValidationIo() {
|
||||
}
|
||||
|
||||
static JSONObject readJson(File file) {
|
||||
/** The JSON object {@code file} holds, or null when it cannot be read or parsed. */
|
||||
public static JSONObject readJson(File file) {
|
||||
try {
|
||||
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8));
|
||||
} catch (IOException | RuntimeException parseFailure) {
|
||||
@@ -79,7 +80,8 @@ public final class PackValidationIo {
|
||||
return true;
|
||||
}
|
||||
|
||||
static List<File> listJsonRecursive(File root) {
|
||||
/** Every {@code .json} file below {@code root}, in no particular order; none when it cannot be listed. */
|
||||
public static List<File> listJsonRecursive(File root) {
|
||||
List<File> out = new ArrayList<>();
|
||||
try (Stream<Path> stream = Files.walk(root.toPath())) {
|
||||
stream.filter(Files::isRegularFile)
|
||||
@@ -90,7 +92,8 @@ public final class PackValidationIo {
|
||||
return out;
|
||||
}
|
||||
|
||||
static String deriveKey(File resourceFolder, File resourceFile) {
|
||||
/** The key of {@code resourceFile} in {@code resourceFolder}: its path below it without {@code .json}, or null for other files. */
|
||||
public static String deriveKey(File resourceFolder, File resourceFile) {
|
||||
Path relative = resourceFolder.toPath().relativize(resourceFile.toPath());
|
||||
String str = relative.toString().replace(File.separatorChar, '/');
|
||||
if (!str.endsWith(".json")) {
|
||||
|
||||
@@ -23,6 +23,11 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Validates a pack before Iris loads it, packages it or opens it in studio: Iris's own checks of its files, then the
|
||||
* validators the pack's modules register ({@link ModulePackValidation}). Blocking errors stop the pack from loading;
|
||||
* warnings are only shown.
|
||||
*/
|
||||
public final class PackValidator {
|
||||
static final String TRASH_ROOT = ".iris-trash";
|
||||
static final String DATAPACK_IMPORTS = "datapack-imports";
|
||||
@@ -93,15 +98,6 @@ public final class PackValidator {
|
||||
blockingErrors.addAll(PackObjectSurfaceValidator.validateUnsupportedStructureTransforms(packFolder));
|
||||
blockingErrors.addAll(PackObjectSurfaceValidator.validateStructureGraph(
|
||||
packFolder, validateLiveRegistries));
|
||||
StructureGraphPackValidator.Validation compiledStructures =
|
||||
StructureGraphPackValidator.validate(
|
||||
packFolder.toPath(), PackObjectSurfaceValidator.collectPlacedStructureKeys(packFolder));
|
||||
addDistinct(blockingErrors, compiledStructures.errors());
|
||||
addDistinct(warnings, compiledStructures.warnings());
|
||||
blockingErrors.addAll(PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
packFolder,
|
||||
compiledStructures.replacementOutputStructures(),
|
||||
compiledStructures.sampledVerticalEnvelopes()));
|
||||
blockingErrors.addAll(PackSpawnValidator.validateSpawnerEntityReferences(
|
||||
new File(packFolder, "spawners"), new File(packFolder, "entities")));
|
||||
blockingErrors.addAll(PackSpawnValidator.validateCustomBiomeSpawns(
|
||||
@@ -120,6 +116,10 @@ public final class PackValidator {
|
||||
addDistinct(ContentKeyValidator.strictContent() ? blockingErrors : warnings, contentKeys.strict());
|
||||
addDistinct(warnings, contentKeys.advisory());
|
||||
|
||||
ModulePackValidation.Findings modules = ModulePackValidation.validate(packFolder);
|
||||
addDistinct(blockingErrors, modules.errors());
|
||||
addDistinct(warnings, modules.warnings());
|
||||
|
||||
return new PackValidationResult(packName, blockingErrors, warnings, validatedAt);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,351 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.pack;
|
||||
|
||||
import art.arcane.iris.engine.framework.PlacedStructurePiece;
|
||||
import art.arcane.iris.engine.framework.StructureAssembler;
|
||||
import art.arcane.iris.engine.framework.structure.IrisObjectFrameReader;
|
||||
import art.arcane.iris.engine.framework.structure.StructureAssemblyResult;
|
||||
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.StructureGraphAssemblySample;
|
||||
import art.arcane.iris.engine.framework.structure.StructureGraphResolver;
|
||||
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 java.io.BufferedInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
final class StructureGraphPackValidator {
|
||||
private static final Gson GSON = new GsonBuilder().create();
|
||||
private static final List<Long> GEOMETRY_SAMPLE_SEEDS = List.of(
|
||||
0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L);
|
||||
private static final int GEOMETRY_SAMPLE_ORIGIN_Y = 64;
|
||||
|
||||
private StructureGraphPackValidator() {
|
||||
}
|
||||
|
||||
static Validation validate(Path packRoot) {
|
||||
return validate(packRoot, null);
|
||||
}
|
||||
|
||||
static Validation validate(Path packRoot, Set<String> activeStructureKeys) {
|
||||
Path normalizedRoot = packRoot.toAbsolutePath().normalize();
|
||||
Path structuresRoot = normalizedRoot.resolve("structures");
|
||||
Set<String> errors = new LinkedHashSet<>();
|
||||
Set<String> warnings = new LinkedHashSet<>();
|
||||
Set<String> replacementOutputStructures = new LinkedHashSet<>();
|
||||
Map<String, List<SampledVerticalEnvelope>> sampledVerticalEnvelopes = new LinkedHashMap<>();
|
||||
FileResolver resolver = new FileResolver(normalizedRoot);
|
||||
for (Path structureFile : listJsonFiles(structuresRoot)) {
|
||||
String structureKey = resourceKey(structuresRoot, structureFile, ".json");
|
||||
if (structureKey.equals("structure-index")) {
|
||||
continue;
|
||||
}
|
||||
IrisStructure structure = readJson(structureFile, IrisStructure.class);
|
||||
if (structure == null) {
|
||||
continue;
|
||||
}
|
||||
structure.setLoadKey(structureKey);
|
||||
if (activeStructureKeys != null && !activeStructureKeys.contains(structureKey)) {
|
||||
continue;
|
||||
}
|
||||
StructureGraphCompilation compilation;
|
||||
try {
|
||||
compilation = StructureGraphCompiler.compile(structure, resolver);
|
||||
} catch (MalformedObjectResourceException e) {
|
||||
errors.add(e.getMessage());
|
||||
continue;
|
||||
}
|
||||
for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) {
|
||||
if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) {
|
||||
errors.add(diagnostic.message());
|
||||
} else {
|
||||
warnings.add(diagnostic.message());
|
||||
}
|
||||
}
|
||||
if (!compilation.isAssemblyViable()) {
|
||||
errors.add("Structure '" + structureKey
|
||||
+ "' does not produce a complete deterministic assembly and will not generate"
|
||||
+ failedSampleSummary(compilation) + ".");
|
||||
continue;
|
||||
}
|
||||
RuntimeGeometryValidation geometry = validateRuntimeGeometry(compilation);
|
||||
if (geometry.failures().isEmpty()) {
|
||||
sampledVerticalEnvelopes.put(structureKey, geometry.sampledVerticalEnvelopes());
|
||||
if (compilation.guaranteesAssemblyOutput() && geometry.outputForEverySample()) {
|
||||
replacementOutputStructures.add(structureKey);
|
||||
}
|
||||
} else {
|
||||
errors.add("Structure '" + structureKey
|
||||
+ "' fails sampled collision- and radius-aware assembly: "
|
||||
+ String.join("; ", geometry.failures()) + ".");
|
||||
}
|
||||
}
|
||||
return new Validation(
|
||||
List.copyOf(errors), List.copyOf(warnings), Set.copyOf(replacementOutputStructures),
|
||||
immutableEnvelopes(sampledVerticalEnvelopes));
|
||||
}
|
||||
|
||||
private static RuntimeGeometryValidation validateRuntimeGeometry(
|
||||
StructureGraphCompilation compilation
|
||||
) {
|
||||
List<String> failures = new ArrayList<>();
|
||||
List<SampledVerticalEnvelope> sampledVerticalEnvelopes = new ArrayList<>();
|
||||
boolean outputForEverySample = true;
|
||||
for (long seed : GEOMETRY_SAMPLE_SEEDS) {
|
||||
try {
|
||||
StructureAssembler assembler = StructureAssembler.forCompilation(
|
||||
compilation, new IrisPosition(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());
|
||||
} else if (!result.hasOutput()) {
|
||||
outputForEverySample = false;
|
||||
} else {
|
||||
sampledVerticalEnvelopes.add(sampleVerticalEnvelope(seed, result.pieces()));
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
failures.add("seed " + seed + " threw " + e.getClass().getSimpleName()
|
||||
+ ": " + failureMessage(e));
|
||||
}
|
||||
}
|
||||
return new RuntimeGeometryValidation(
|
||||
List.copyOf(failures), outputForEverySample, List.copyOf(sampledVerticalEnvelopes));
|
||||
}
|
||||
|
||||
private static SampledVerticalEnvelope sampleVerticalEnvelope(
|
||||
long seed,
|
||||
List<PlacedStructurePiece> pieces
|
||||
) {
|
||||
int minimumY = Integer.MAX_VALUE;
|
||||
int maximumY = Integer.MIN_VALUE;
|
||||
for (PlacedStructurePiece piece : pieces) {
|
||||
minimumY = Math.min(minimumY, piece.getMinY());
|
||||
maximumY = Math.max(maximumY, piece.getMaxY());
|
||||
}
|
||||
return new SampledVerticalEnvelope(
|
||||
seed,
|
||||
pieces.size(),
|
||||
Math.subtractExact(minimumY, GEOMETRY_SAMPLE_ORIGIN_Y),
|
||||
Math.subtractExact(maximumY, GEOMETRY_SAMPLE_ORIGIN_Y));
|
||||
}
|
||||
|
||||
private static Map<String, List<SampledVerticalEnvelope>> immutableEnvelopes(
|
||||
Map<String, List<SampledVerticalEnvelope>> sampledVerticalEnvelopes
|
||||
) {
|
||||
Map<String, List<SampledVerticalEnvelope>> immutable = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<SampledVerticalEnvelope>> entry : sampledVerticalEnvelopes.entrySet()) {
|
||||
immutable.put(entry.getKey(), List.copyOf(entry.getValue()));
|
||||
}
|
||||
return Map.copyOf(immutable);
|
||||
}
|
||||
|
||||
private static String failureMessage(RuntimeException exception) {
|
||||
return exception.getMessage() == null || exception.getMessage().isBlank()
|
||||
? "no failure detail" : exception.getMessage();
|
||||
}
|
||||
|
||||
private static String failedSampleSummary(StructureGraphCompilation compilation) {
|
||||
List<String> failures = new ArrayList<>();
|
||||
for (StructureGraphAssemblySample sample : compilation.getAssemblySamples()) {
|
||||
if (sample.outcome().isComplete()) {
|
||||
continue;
|
||||
}
|
||||
failures.add("seed " + sample.seed() + " placed " + sample.outcome().pieceKeys().size()
|
||||
+ " piece(s), status=" + sample.outcome().status()
|
||||
+ ": " + sample.outcome().detail());
|
||||
if (failures.size() == 3) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return failures.isEmpty() ? "" : " (" + String.join("; ", failures) + ")";
|
||||
}
|
||||
|
||||
private static List<Path> listJsonFiles(Path root) {
|
||||
if (!Files.isDirectory(root)) {
|
||||
return List.of();
|
||||
}
|
||||
try (Stream<Path> paths = Files.walk(root)) {
|
||||
return paths.filter(Files::isRegularFile)
|
||||
.filter(path -> path.getFileName().toString().endsWith(".json"))
|
||||
.sorted()
|
||||
.toList();
|
||||
} catch (IOException e) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static String resourceKey(Path root, Path file, String extension) {
|
||||
String relative = root.relativize(file).toString().replace(file.getFileSystem().getSeparator(), "/");
|
||||
return relative.substring(0, relative.length() - extension.length());
|
||||
}
|
||||
|
||||
private static <T> T readJson(Path file, Class<T> type) {
|
||||
try {
|
||||
return GSON.fromJson(Files.readString(file, StandardCharsets.UTF_8), type);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
record Validation(
|
||||
List<String> errors,
|
||||
List<String> warnings,
|
||||
Set<String> replacementOutputStructures,
|
||||
Map<String, List<SampledVerticalEnvelope>> sampledVerticalEnvelopes
|
||||
) {
|
||||
Validation {
|
||||
errors = List.copyOf(errors);
|
||||
warnings = List.copyOf(warnings);
|
||||
replacementOutputStructures = Set.copyOf(replacementOutputStructures);
|
||||
sampledVerticalEnvelopes = immutableEnvelopes(sampledVerticalEnvelopes);
|
||||
}
|
||||
}
|
||||
|
||||
record SampledVerticalEnvelope(long seed, int pieceCount, int minimumYOffset, int maximumYOffset) {
|
||||
SampledVerticalEnvelope {
|
||||
if (pieceCount <= 0) {
|
||||
throw new IllegalArgumentException("Sampled vertical envelope must contain at least one piece");
|
||||
}
|
||||
if (maximumYOffset < minimumYOffset) {
|
||||
throw new IllegalArgumentException("Sampled vertical envelope maximum Y cannot be below minimum Y");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record RuntimeGeometryValidation(
|
||||
List<String> failures,
|
||||
boolean outputForEverySample,
|
||||
List<SampledVerticalEnvelope> sampledVerticalEnvelopes
|
||||
) {
|
||||
}
|
||||
|
||||
private static final class FileResolver implements StructureGraphResolver {
|
||||
private final Path packRoot;
|
||||
private final Map<String, IrisJigsawPool> pools = new HashMap<>();
|
||||
private final Map<String, IrisJigsawPiece> pieces = new HashMap<>();
|
||||
private final Map<String, IrisObject> objects = new HashMap<>();
|
||||
private final Set<String> missingPools = new LinkedHashSet<>();
|
||||
private final Set<String> missingPieces = new LinkedHashSet<>();
|
||||
private final Set<String> missingObjects = new LinkedHashSet<>();
|
||||
|
||||
private FileResolver(Path packRoot) {
|
||||
this.packRoot = packRoot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPool loadPool(String key) {
|
||||
if (pools.containsKey(key)) {
|
||||
return pools.get(key);
|
||||
}
|
||||
if (missingPools.contains(key)) {
|
||||
return null;
|
||||
}
|
||||
Path file = resolve("jigsaw-pools", key, ".json");
|
||||
IrisJigsawPool pool = file == null ? null : readJson(file, IrisJigsawPool.class);
|
||||
if (pool == null) {
|
||||
missingPools.add(key);
|
||||
return null;
|
||||
}
|
||||
pools.put(key, pool);
|
||||
return pool;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPiece loadPiece(String key) {
|
||||
if (pieces.containsKey(key)) {
|
||||
return pieces.get(key);
|
||||
}
|
||||
if (missingPieces.contains(key)) {
|
||||
return null;
|
||||
}
|
||||
Path file = resolve("jigsaw-pieces", key, ".json");
|
||||
IrisJigsawPiece piece = file == null ? null : readJson(file, IrisJigsawPiece.class);
|
||||
if (piece == null) {
|
||||
missingPieces.add(key);
|
||||
return null;
|
||||
}
|
||||
pieces.put(key, piece);
|
||||
return piece;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisObject loadObject(String key) {
|
||||
if (objects.containsKey(key)) {
|
||||
return objects.get(key);
|
||||
}
|
||||
if (missingObjects.contains(key)) {
|
||||
return null;
|
||||
}
|
||||
Path file = resolve("objects", key, ".iob");
|
||||
IrisObject object = file == null ? null : readObjectBounds(file);
|
||||
if (object == null) {
|
||||
missingObjects.add(key);
|
||||
return null;
|
||||
}
|
||||
objects.put(key, object);
|
||||
return object;
|
||||
}
|
||||
|
||||
private Path resolve(String folder, String key, String extension) {
|
||||
if (key == null || key.isBlank() || key.indexOf('\\') >= 0 || key.indexOf(':') >= 0) {
|
||||
return null;
|
||||
}
|
||||
Path root = packRoot.resolve(folder).normalize();
|
||||
Path file = root.resolve(key + extension).normalize();
|
||||
if (!file.startsWith(root) || !Files.isRegularFile(file)) {
|
||||
return null;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private IrisObject readObjectBounds(Path file) {
|
||||
try (BufferedInputStream input = new BufferedInputStream(Files.newInputStream(file))) {
|
||||
return IrisObjectFrameReader.readBounds(input, file.toString());
|
||||
} catch (IOException e) {
|
||||
throw new MalformedObjectResourceException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class MalformedObjectResourceException extends RuntimeException {
|
||||
private MalformedObjectResourceException(String message, IOException cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -232,6 +232,7 @@ public class IrisCodeWorkspace {
|
||||
for (ObjectType type : dm.getModules().pack().schema().snippets()) {
|
||||
schemaEntries.add(moduleSnippetSchema(dm, type, immediateSchemas));
|
||||
}
|
||||
schemaEntries.addAll(ModuleResourceSchemas.entries(dm, immediateSchemas));
|
||||
|
||||
schemaEntries.sort(Comparator.comparing(entry -> entry.getString("url")));
|
||||
for (JSONObject entry : schemaEntries) {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.project;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.PackModulesException;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.format.Form;
|
||||
import art.arcane.volmlib.util.io.IO;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import com.volmit.host.schema.ResourceKindSchema;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The studio schemas of a pack's module resource kinds, written the way Iris's loaders write theirs: one schema file
|
||||
* per kind, {@code .iris/schema/<folder>-schema.json}, and a workspace entry matching every JSON file below the
|
||||
* kind's folder. Every workspace Iris writes adds these next to its loaders' entries.
|
||||
*/
|
||||
public final class ModuleResourceSchemas {
|
||||
private static final String SCHEMA_FOLDER = ".iris/schema/";
|
||||
private static final String SCHEMA_SUFFIX = "-schema.json";
|
||||
private static final int FOLDER_MATCH_DEPTH = 8;
|
||||
|
||||
private ModuleResourceSchemas() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace entries of {@code data}'s module resource kinds, writing each kind's schema file now when
|
||||
* {@code immediate}, or in the background. A pack whose modules fail to load gets none; its load reported why.
|
||||
*/
|
||||
public static List<JSONObject> entries(IrisData data, boolean immediate) {
|
||||
List<ResourceKindSchema> kinds;
|
||||
try {
|
||||
kinds = data.getModules().pack().schema().resources();
|
||||
} catch (PackModulesException failedModules) {
|
||||
return List.of();
|
||||
}
|
||||
List<JSONObject> entries = new ArrayList<>();
|
||||
for (ResourceKindSchema kind : kinds) {
|
||||
entries.add(entry(data, kind, immediate));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static JSONObject entry(IrisData data, ResourceKindSchema kind, boolean immediate) {
|
||||
File schemaFile = new File(data.getDataFolder(), SCHEMA_FOLDER + kind.folder() + SCHEMA_SUFFIX);
|
||||
if (immediate) {
|
||||
write(schemaFile, SchemaBuilder.moduleResource(kind, data));
|
||||
} else {
|
||||
J.attemptAsync(() -> write(schemaFile, SchemaBuilder.moduleResource(kind, data)));
|
||||
}
|
||||
KList<String> fileMatches = new KList<>();
|
||||
for (int depth = 1; depth < FOLDER_MATCH_DEPTH; depth++) {
|
||||
fileMatches.add("/" + kind.folder() + Form.repeat("/*", depth) + ".json");
|
||||
}
|
||||
JSONObject entry = new JSONObject();
|
||||
entry.put("fileMatch", new JSONArray(fileMatches.toArray()));
|
||||
entry.put("url", "./" + SCHEMA_FOLDER + kind.folder() + SCHEMA_SUFFIX);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static void write(File schemaFile, JSONObject schema) {
|
||||
try {
|
||||
IO.writeAll(schemaFile, schema.toString(4));
|
||||
} catch (IOException failure) {
|
||||
throw new UncheckedIOException("Could not write schema " + schemaFile.getAbsolutePath(), failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import com.volmit.host.schema.PackSchema;
|
||||
import com.volmit.host.schema.SchemaOption;
|
||||
import com.volmit.host.schema.TextFormat;
|
||||
import com.volmit.host.schema.ValueKind;
|
||||
import com.volmit.resource.ResourceId;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -38,8 +39,9 @@ import java.util.function.Function;
|
||||
/**
|
||||
* Renders the settings a pack's modules add, described by IrisApi as a {@link PackSchema}, into the JSON
|
||||
* schema studio writes: each feature as a property of its target under its id and, for built-ins, its
|
||||
* alias, each settings class once as a definition, references as completion lists. Settings with one option
|
||||
* also accept that option's bare value; Iris's own classes in built-in settings use Iris's own definitions.
|
||||
* alias, each settings class once as a definition, references as completion lists (resource references as the keys
|
||||
* of the module resource kind they name). Settings with one option also accept that option's bare value; Iris's own
|
||||
* classes in built-in settings use Iris's own definitions.
|
||||
*/
|
||||
final class ModuleSchemaRenderer {
|
||||
private static final String DEFINITION_PREFIX = "module-";
|
||||
@@ -53,6 +55,11 @@ final class ModuleSchemaRenderer {
|
||||
void complete(JSONObject property, Reference reference, TextFormat format);
|
||||
}
|
||||
|
||||
/** Points a string property at the keys of the pack's resources of a module resource kind. */
|
||||
interface ResourceCompletions {
|
||||
void complete(JSONObject property, ResourceId kind);
|
||||
}
|
||||
|
||||
/** The definition key of Iris's own description of one of its classes, built the first time it is asked for. */
|
||||
interface HostDefinitions {
|
||||
String definition(String typeName);
|
||||
@@ -61,15 +68,17 @@ final class ModuleSchemaRenderer {
|
||||
private final PackSchema schema;
|
||||
private final Map<String, JSONObject> definitions;
|
||||
private final ReferenceCompletions references;
|
||||
private final ResourceCompletions resources;
|
||||
private final HostDefinitions hostDefinitions;
|
||||
private final Function<String, List<String>> snippetFiles;
|
||||
|
||||
/** {@code snippetFiles} lists the snippet references a pack has for a snippet folder, such as {@code snippet/thick}. */
|
||||
ModuleSchemaRenderer(PackSchema schema, Map<String, JSONObject> definitions, ReferenceCompletions references,
|
||||
HostDefinitions hostDefinitions, Function<String, List<String>> snippetFiles) {
|
||||
ResourceCompletions resources, HostDefinitions hostDefinitions, Function<String, List<String>> snippetFiles) {
|
||||
this.schema = schema;
|
||||
this.definitions = definitions;
|
||||
this.references = references;
|
||||
this.resources = resources;
|
||||
this.hostDefinitions = hostDefinitions;
|
||||
this.snippetFiles = snippetFiles;
|
||||
}
|
||||
@@ -89,8 +98,8 @@ final class ModuleSchemaRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
/** The schema of a snippet file of {@code type}, which holds one object of it. */
|
||||
JSONObject snippetFileSchema(ObjectType type) {
|
||||
/** The schema of a file that holds one object of {@code type}: a snippet file, or a file of a module resource kind. */
|
||||
JSONObject fileSchema(ObjectType type) {
|
||||
JSONObject file = objectSchema(type);
|
||||
file.put("$schema", "http://json-schema.org/draft-07/schema#");
|
||||
JSONObject fileDefinitions = new JSONObject();
|
||||
@@ -192,6 +201,10 @@ final class ModuleSchemaRenderer {
|
||||
value.put("type", "string");
|
||||
references.complete(value, reference.reference(), reference.format());
|
||||
}
|
||||
case ValueKind.ResourceReferenceKind resource -> {
|
||||
value.put("type", "string");
|
||||
resources.complete(value, resource.kind());
|
||||
}
|
||||
case ValueKind.EnumKind enumKind -> {
|
||||
value.put("type", "string");
|
||||
value.put("enum", new JSONArray(enumKind.constants().stream().map(ValueKind.EnumConstant::name).toList()));
|
||||
|
||||
@@ -25,7 +25,9 @@ import art.arcane.iris.spi.PlatformNumericRange;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFiles;
|
||||
import art.arcane.iris.core.modules.ModuleTargets;
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
@@ -57,8 +59,13 @@ import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import com.volmit.config.Reference;
|
||||
import com.volmit.host.ResourceKindRegistration;
|
||||
import com.volmit.host.schema.ObjectType;
|
||||
import com.volmit.host.schema.ResourceKindSchema;
|
||||
import com.volmit.host.schema.TextFormat;
|
||||
import com.volmit.host.schema.ValueKind;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.awt.GraphicsEnvironment;
|
||||
@@ -99,7 +106,19 @@ public class SchemaBuilder {
|
||||
|
||||
/** The schema of a module snippet file, which holds one object of {@code type}. */
|
||||
public static JSONObject moduleSnippet(ObjectType type, IrisData data) {
|
||||
return new SchemaBuilder(type.getClass(), data).moduleSchemas().snippetFileSchema(type);
|
||||
return new SchemaBuilder(type.getClass(), data).moduleSchemas().fileSchema(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* The schema of a file of a module resource kind: Iris's own description of the class a built-in kind reads into,
|
||||
* as its loader described it, or the module's description of its class.
|
||||
*/
|
||||
public static JSONObject moduleResource(ResourceKindSchema kind, IrisData data) {
|
||||
if (kind.type() instanceof ValueKind.HostKind host) {
|
||||
return new SchemaBuilder(hostType(host.type()), data).construct();
|
||||
}
|
||||
ObjectType type = data.getModules().pack().schema().type(((ValueKind.ObjectKind) kind.type()).type());
|
||||
return new SchemaBuilder(kind.getClass(), data).moduleSchemas().fileSchema(type);
|
||||
}
|
||||
|
||||
public JSONObject construct() {
|
||||
@@ -372,7 +391,7 @@ public class SchemaBuilder {
|
||||
private ModuleSchemaRenderer moduleSchemas() {
|
||||
if (moduleSchemas == null) {
|
||||
moduleSchemas = new ModuleSchemaRenderer(data.getModules().pack().schema(), definitions,
|
||||
this::completeReference, this::hostDefinition, data::getPossibleSnippets);
|
||||
this::completeReference, this::completeResourceReference, this::hostDefinition, data::getPossibleSnippets);
|
||||
}
|
||||
return moduleSchemas;
|
||||
}
|
||||
@@ -423,20 +442,55 @@ public class SchemaBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/** Points {@code property} at the keys of the pack's resources of {@code type}; null when the pack has no such loader. */
|
||||
private ResourceLoader<?> putPackResourceRef(JSONObject property, Class<?> type) {
|
||||
/** A list of pack resource keys studio completes: the folder the resources live in and what they are called. */
|
||||
private record PackResourceList(String folder, String typeName) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Points {@code property} at the keys of the pack's resources of {@code type}, read by Iris's loader for it or by
|
||||
* the module resource kind read into it; null when the pack has neither.
|
||||
*/
|
||||
private PackResourceList putPackResourceRef(JSONObject property, Class<?> type) {
|
||||
ResourceLoader<?> loader = data.getLoaders().get(type);
|
||||
if (loader == null) {
|
||||
return null;
|
||||
if (loader != null) {
|
||||
return putResourceKeys(property, new PackResourceList(loader.getFolderName(), loader.getResourceTypeName()),
|
||||
Arrays.asList(loader.getPossibleKeys()));
|
||||
}
|
||||
String key = "erz" + loader.getFolderName();
|
||||
return moduleKinds().stream()
|
||||
.filter(kind -> kind.type() == type)
|
||||
.findFirst()
|
||||
.map(kind -> putModuleResourceRef(property, kind))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/** Completion for a module option naming a resource of the module resource kind {@code kindId}. */
|
||||
private void completeResourceReference(JSONObject property, ResourceId kindId) {
|
||||
moduleKinds().stream()
|
||||
.filter(kind -> kind.id().equals(kindId))
|
||||
.findFirst()
|
||||
.ifPresent(kind -> putModuleResourceRef(property, kind));
|
||||
}
|
||||
|
||||
private PackResourceList putModuleResourceRef(JSONObject property, ResourceKind<?> kind) {
|
||||
List<String> keys = data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList();
|
||||
return putResourceKeys(property, new PackResourceList(kind.folder(), ModuleResourceFiles.typeName(kind)), keys);
|
||||
}
|
||||
|
||||
private PackResourceList putResourceKeys(JSONObject property, PackResourceList list, List<String> keys) {
|
||||
String key = "erz" + list.folder();
|
||||
if (!definitions.containsKey(key)) {
|
||||
JSONObject keys = new JSONObject();
|
||||
keys.put("enum", new JSONArray(loader.getPossibleKeys()));
|
||||
definitions.put(key, keys);
|
||||
JSONObject enumeration = new JSONObject();
|
||||
enumeration.put("enum", new JSONArray(keys.toArray(new String[0])));
|
||||
definitions.put(key, enumeration);
|
||||
}
|
||||
property.put("$ref", "#/definitions/" + key);
|
||||
return loader;
|
||||
return list;
|
||||
}
|
||||
|
||||
private List<ResourceKind<?>> moduleKinds() {
|
||||
return data.getModules().pack().catalog().resourceKinds().stream()
|
||||
.<ResourceKind<?>>map(ResourceKindRegistration::kind)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void buildProperties(JSONObject properties, JSONArray required, JSONArray extended, Class<?> c) {
|
||||
@@ -518,11 +572,11 @@ public class SchemaBuilder {
|
||||
|
||||
if (k.isAnnotationPresent(RegistryListResource.class)) {
|
||||
RegistryListResource rr = k.getDeclaredAnnotation(RegistryListResource.class);
|
||||
ResourceLoader<?> loader = putPackResourceRef(prop, rr.value());
|
||||
PackResourceList resources = putPackResourceRef(prop, rr.value());
|
||||
|
||||
if (loader != null) {
|
||||
fancyType = "Iris " + loader.getResourceTypeName();
|
||||
description.add(SYMBOL_TYPE__N + " Must be a valid " + loader.getFolderName() + " (use ctrl+space for auto complete!)");
|
||||
if (resources != null) {
|
||||
fancyType = "Iris " + resources.typeName();
|
||||
description.add(SYMBOL_TYPE__N + " Must be a valid " + resources.folder() + " (use ctrl+space for auto complete!)");
|
||||
} else {
|
||||
IrisLogging.error("Cannot find Registry Loader for type " + rr.value() + " used in " + k.getDeclaringClass().getCanonicalName() + " in field " + k.getName());
|
||||
}
|
||||
@@ -532,8 +586,8 @@ public class SchemaBuilder {
|
||||
if (!definitions.containsKey(key)) {
|
||||
JSONObject j = new JSONObject();
|
||||
j.put("enum", new JSONArray(StructureSchemaKeys.collect(
|
||||
Arrays.asList(data.getStructureLoader().getPossibleKeys()),
|
||||
Arrays.asList(data.getJigsawPieceLoader().getPossibleKeys())).toArray(new String[0])));
|
||||
StructureResources.structureKeys(data),
|
||||
StructureResources.pieceKeys(data)).toArray(new String[0])));
|
||||
definitions.put(key, j);
|
||||
}
|
||||
|
||||
@@ -719,12 +773,12 @@ public class SchemaBuilder {
|
||||
if (k.isAnnotationPresent(RegistryListResource.class)) {
|
||||
RegistryListResource rr = k.getDeclaredAnnotation(RegistryListResource.class);
|
||||
JSONObject items = new JSONObject();
|
||||
ResourceLoader<?> loader = putPackResourceRef(items, rr.value());
|
||||
PackResourceList resources = putPackResourceRef(items, rr.value());
|
||||
|
||||
if (loader != null) {
|
||||
fancyType = "List<" + loader.getResourceTypeName() + ">";
|
||||
if (resources != null) {
|
||||
fancyType = "List<" + resources.typeName() + ">";
|
||||
prop.put("items", items);
|
||||
description.add(SYMBOL_TYPE__N + " Must be a valid " + loader.getResourceTypeName() + " (use ctrl+space for auto complete!)");
|
||||
description.add(SYMBOL_TYPE__N + " Must be a valid " + resources.typeName() + " (use ctrl+space for auto complete!)");
|
||||
} else {
|
||||
IrisLogging.error("Cannot find Registry Loader for type (list schema) " + rr.value() + " used in " + k.getDeclaringClass().getCanonicalName() + " in field " + k.getName());
|
||||
}
|
||||
@@ -735,8 +789,8 @@ public class SchemaBuilder {
|
||||
if (!definitions.containsKey(key)) {
|
||||
JSONObject j = new JSONObject();
|
||||
j.put("enum", new JSONArray(StructureSchemaKeys.collect(
|
||||
Arrays.asList(data.getStructureLoader().getPossibleKeys()),
|
||||
Arrays.asList(data.getJigsawPieceLoader().getPossibleKeys())).toArray(new String[0])));
|
||||
StructureResources.structureKeys(data),
|
||||
StructureResources.pieceKeys(data)).toArray(new String[0])));
|
||||
definitions.put(key, j);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.structure.authoring.StructureKey;
|
||||
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
|
||||
@@ -165,7 +166,7 @@ public final class JigsawStudioGraphMapper {
|
||||
if (!visitedPools.add(poolKey)) {
|
||||
continue;
|
||||
}
|
||||
IrisJigsawPool pool = data.getJigsawPoolLoader().load(poolKey);
|
||||
IrisJigsawPool pool = StructureResources.pool(data, poolKey);
|
||||
if (pool == null) {
|
||||
continue;
|
||||
}
|
||||
@@ -179,7 +180,7 @@ public final class JigsawStudioGraphMapper {
|
||||
continue;
|
||||
}
|
||||
String pieceKey = entry.getPiece();
|
||||
IrisJigsawPiece piece = data.getJigsawPieceLoader().load(pieceKey);
|
||||
IrisJigsawPiece piece = StructureResources.piece(data, pieceKey);
|
||||
if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
@@ -210,7 +211,7 @@ public final class JigsawStudioGraphMapper {
|
||||
if (variants.containsKey(pieceKey)) {
|
||||
return;
|
||||
}
|
||||
IrisJigsawPiece piece = data.getJigsawPieceLoader().load(pieceKey);
|
||||
IrisJigsawPiece piece = StructureResources.piece(data, pieceKey);
|
||||
if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,5 +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.nms.INMS;
|
||||
import art.arcane.iris.core.runtime.InPlaceChunkRegenerator;
|
||||
@@ -2470,8 +2471,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC
|
||||
JigsawStudioActivation.Request request = studio.generator().getRequest();
|
||||
J.a(() -> {
|
||||
try {
|
||||
IrisStructure structure = request.source().load(
|
||||
IrisStructure.class, request.structureKey(), false);
|
||||
IrisStructure structure = StructureResources.structure(
|
||||
request.source(), request.structureKey());
|
||||
if (structure == null) {
|
||||
throw new IOException("The active structure resource no longer exists");
|
||||
}
|
||||
@@ -2598,10 +2599,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC
|
||||
EvaluationComputation computation;
|
||||
try {
|
||||
JigsawStudioActivation.Request request = studio.generator().getRequest();
|
||||
IrisStructure structure = request.source().load(
|
||||
IrisStructure.class,
|
||||
request.structureKey(),
|
||||
false);
|
||||
IrisStructure structure = StructureResources.structure(
|
||||
request.source(),
|
||||
request.structureKey());
|
||||
if (structure == null) {
|
||||
throw new IOException("The active structure resource no longer exists");
|
||||
}
|
||||
@@ -2801,7 +2801,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC
|
||||
|
||||
private static IrisStructure loadStudioStructure(ActiveStudio studio) {
|
||||
JigsawStudioActivation.Request request = studio.generator().getRequest();
|
||||
return request.source().load(IrisStructure.class, request.structureKey(), false);
|
||||
return StructureResources.structure(request.source(), request.structureKey());
|
||||
}
|
||||
|
||||
private static boolean canResizeVariantToCapacity(
|
||||
@@ -3797,7 +3797,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC
|
||||
JigsawStudioActivation.Request request = studio.generator().getRequest();
|
||||
IrisData source = request.source();
|
||||
source.invalidateStructureResources();
|
||||
IrisStructure structure = source.load(IrisStructure.class, request.structureKey(), false);
|
||||
IrisStructure structure = StructureResources.structure(source, request.structureKey());
|
||||
if (structure == null) {
|
||||
throw new IOException("The structure could not be reloaded after the graph transaction");
|
||||
}
|
||||
@@ -7069,7 +7069,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC
|
||||
throw new IOException("variant '" + activeVariant.pieceKey()
|
||||
+ "' does not belong to workcell '" + currentBay.stableId() + "'");
|
||||
}
|
||||
IrisJigsawPiece piece = source.getJigsawPieceLoader().load(activeVariant.pieceKey(), false);
|
||||
IrisJigsawPiece piece = StructureResources.piece(source, activeVariant.pieceKey());
|
||||
if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) {
|
||||
throw new IOException("piece '" + activeVariant.pieceKey() + "' is missing or has no object");
|
||||
}
|
||||
|
||||
@@ -18,11 +18,10 @@
|
||||
|
||||
package art.arcane.iris.core.structure;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import java.io.File;
|
||||
@@ -90,11 +89,8 @@ public final class StructureIndexService {
|
||||
}
|
||||
}
|
||||
|
||||
List<String> iris = new ArrayList<>();
|
||||
if (data.getStructureLoader() != null) {
|
||||
Collections.addAll(iris, data.getStructureLoader().getPossibleKeys());
|
||||
iris.removeIf(LEGACY_INDEX_KEY::equals);
|
||||
}
|
||||
List<String> iris = new ArrayList<>(StructureResources.structureKeys(data));
|
||||
iris.removeIf(LEGACY_INDEX_KEY::equals);
|
||||
|
||||
Collections.sort(vanilla);
|
||||
Collections.sort(datapack);
|
||||
@@ -145,11 +141,8 @@ public final class StructureIndexService {
|
||||
static void removeLegacyIndex(IrisData data) {
|
||||
File legacyFile = legacyIndexFile(data.getDataFolder());
|
||||
try {
|
||||
Files.deleteIfExists(legacyFile.toPath());
|
||||
ResourceLoader<IrisStructure> structureLoader = data.getStructureLoader();
|
||||
if (structureLoader != null) {
|
||||
structureLoader.getLoadCache().invalidate(LEGACY_INDEX_KEY);
|
||||
structureLoader.clearList();
|
||||
if (Files.deleteIfExists(legacyFile.toPath())) {
|
||||
data.invalidateStructureResources();
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError("Failed to remove legacy structure index '"
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
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.object.structure.IrisStructure;
|
||||
@@ -52,7 +53,7 @@ public final class VanillaJigsawExportSource {
|
||||
if (structure != null) {
|
||||
return structure;
|
||||
}
|
||||
return data.load(IrisStructure.class, structureKey, false);
|
||||
return StructureResources.structure(data, structureKey);
|
||||
}
|
||||
|
||||
public StructureGraphResolver resolver() {
|
||||
|
||||
@@ -20,7 +20,6 @@ package art.arcane.iris.engine;
|
||||
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.engine.EngineRuntime.BiomeMaxes;
|
||||
import art.arcane.iris.engine.IrisEngine.LifecycleState;
|
||||
import art.arcane.iris.engine.framework.EngineEffects;
|
||||
@@ -150,10 +149,8 @@ final class EngineRuntimeBuilder {
|
||||
try {
|
||||
if (!engine.backgroundTasks.scheduleTrackedTask(() -> {
|
||||
try {
|
||||
File[] roots = engine.getData().getLoaders()
|
||||
.values()
|
||||
File[] roots = engine.getData().resourceFolderNames()
|
||||
.stream()
|
||||
.map(ResourceLoader::getFolderName)
|
||||
.map(name -> new File(engine.getData().getDataFolder(), name))
|
||||
.filter(File::exists)
|
||||
.filter(File::isDirectory)
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
package art.arcane.iris.engine.framework;
|
||||
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.core.IrisSettings;
|
||||
import art.arcane.iris.engine.framework.render.RenderType;
|
||||
@@ -461,7 +462,7 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer,
|
||||
|
||||
if (marker.structureAware()) {
|
||||
IrisObject placedObject = getData().getObjectLoader().load(object);
|
||||
IrisStructure structure = getData().load(IrisStructure.class, marker.structureKey(), false);
|
||||
IrisStructure structure = StructureResources.structure(getData(), marker.structureKey());
|
||||
IrisObjectPlacement placement = placedObject == null || structure == null
|
||||
? null
|
||||
: structure.createLootPlacement(object);
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package art.arcane.iris.engine.platform.studio.generators;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarDirection;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation;
|
||||
@@ -424,7 +425,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
|
||||
private RenderedBay buildRenderedBay(JigsawStudioBay workcell, JigsawStudioVariant variant) {
|
||||
IrisJigsawPiece piece = request.source().getJigsawPieceLoader().load(variant.pieceKey(), false);
|
||||
IrisJigsawPiece piece = StructureResources.piece(request.source(), variant.pieceKey());
|
||||
if (piece == null) {
|
||||
return RenderedBay.invalid(
|
||||
workcell.bounds().dimensions(),
|
||||
|
||||
+6
-2
@@ -1,6 +1,8 @@
|
||||
package art.arcane.iris.util.common.director.specialhandlers;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.PackModulesException;
|
||||
import art.arcane.iris.core.pack.PackDirectoryResolver;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.util.common.director.DirectorParameterHandler;
|
||||
@@ -46,9 +48,11 @@ public final class IrisStructureHandler implements DirectorParameterHandler<Stri
|
||||
return type == String.class;
|
||||
}
|
||||
|
||||
/** A pack whose modules fail to load has no structures to offer; its failure was reported when it loaded. */
|
||||
private static void addStructureKeys(Set<String> keys, IrisData data) {
|
||||
for (String key : data.getStructureLoader().getPossibleKeys()) {
|
||||
keys.add(key);
|
||||
try {
|
||||
keys.addAll(StructureResources.structureKeys(data));
|
||||
} catch (PackModulesException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ public class IrisPackResourcesTest {
|
||||
when(regionLoader.getPossibleKeys()).thenReturn(new String[]{"desert"});
|
||||
when(regionLoader.load("desert")).thenReturn(desert);
|
||||
|
||||
resources = new IrisPackResources(data);
|
||||
resources = new IrisPackResources(data, List::of);
|
||||
}
|
||||
|
||||
private ResourceId id(String path) {
|
||||
@@ -103,7 +103,7 @@ public class IrisPackResourcesTest {
|
||||
|
||||
@Test
|
||||
public void everySnapshotHasItsOwnId() {
|
||||
assertNotEquals(resources.snapshotId(), new IrisPackResources(data).snapshotId());
|
||||
assertNotEquals(resources.snapshotId(), new IrisPackResources(data, List::of).snapshotId());
|
||||
assertEquals(resources.snapshotId(), resources.snapshotId());
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ public class IrisPackResourcesTest {
|
||||
@Test
|
||||
public void aResourceThatExistsButFailsToLoadIsAnErrorNotAbsent() {
|
||||
when(objectLoader.getPossibleKeys()).thenReturn(new String[]{"trees/broken"});
|
||||
IrisPackResources fresh = new IrisPackResources(data);
|
||||
IrisPackResources fresh = new IrisPackResources(data, List::of);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> fresh.find(new ResourceKey<>(id("trees/broken"), GeneratedObject.class)));
|
||||
}
|
||||
@@ -180,7 +180,7 @@ public class IrisPackResourcesTest {
|
||||
IrisObject object = mock(IrisObject.class);
|
||||
when(object.getGeometry()).thenReturn(tree);
|
||||
when(objectLoader.load("Trees/Oak")).thenReturn(object);
|
||||
IrisPackResources fresh = new IrisPackResources(data);
|
||||
IrisPackResources fresh = new IrisPackResources(data, List::of);
|
||||
|
||||
assertSame(tree, fresh.require(new ResourceKey<>(id("trees/oak"), GeneratedObject.class)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
import com.volmit.host.FeatureCatalog;
|
||||
import com.volmit.host.ModuleRegistry;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A pack whose module resources (structures, jigsaw pools, pieces or any other kind) a test sets by key, served by a
|
||||
* mocked {@link IrisPackResources} the way lookups by pack key find them, such as
|
||||
* {@code StructureResources.structure(data, key)}: ids in namespace {@code test}, a key absent unless set.
|
||||
*/
|
||||
public final class ModuleResourceFixture {
|
||||
private static final String NAMESPACE = "test";
|
||||
private static final Map<IrisPackResources, ModuleResourceFixture> SERVED = new IdentityHashMap<>();
|
||||
|
||||
private final IrisPackResources resources;
|
||||
private final Map<Class<?>, List<ResourceId>> ids = new HashMap<>();
|
||||
|
||||
private ModuleResourceFixture(IrisPackResources resources) {
|
||||
this.resources = resources;
|
||||
}
|
||||
|
||||
/** Makes {@code data} (a mock) serve the structures, pools and pieces set on the returned fixture, none at first. */
|
||||
public static synchronized ModuleResourceFixture serve(IrisData data) {
|
||||
IrisPackResources resources = mock(IrisPackResources.class);
|
||||
when(data.getPackResources()).thenReturn(resources);
|
||||
when(resources.idOf(anyString())).thenAnswer(invocation -> idOf(invocation.getArgument(0)));
|
||||
ModuleResourceFixture fixture = new ModuleResourceFixture(resources);
|
||||
SERVED.put(resources, fixture);
|
||||
return fixture;
|
||||
}
|
||||
|
||||
/** The fixture {@code data} (a mock) already serves from, or a new one. */
|
||||
public static synchronized ModuleResourceFixture of(IrisData data) {
|
||||
ModuleResourceFixture served = SERVED.get(data.getPackResources());
|
||||
return served != null ? served : serve(data);
|
||||
}
|
||||
|
||||
/** The catalog of a pack with only {@code modules}, as built-ins: their resource kinds, validators and other registrations. */
|
||||
public static FeatureCatalog catalogOf(IrisModule... modules) {
|
||||
ModuleRegistry registry = new ModuleRegistry();
|
||||
for (IrisModule module : modules) {
|
||||
registry.register(DiscoveredModule.builtIn(module));
|
||||
}
|
||||
return registry.freeze();
|
||||
}
|
||||
|
||||
/** Serves {@code resource} as the resource of {@code kind} the pack names by {@code key}. */
|
||||
public <T> ModuleResourceFixture resource(ResourceKind<T> kind, String key, T resource) {
|
||||
ResourceId id = idOf(key);
|
||||
when(resources.find(kind.key(id))).thenReturn(Optional.of(resource));
|
||||
List<ResourceId> kindIds = ids.computeIfAbsent(kind.type(), ignored -> new ArrayList<>());
|
||||
kindIds.add(id);
|
||||
when(resources.ids(kind.type())).thenReturn(kindIds.stream().sorted().toList());
|
||||
return this;
|
||||
}
|
||||
|
||||
private static ResourceId idOf(String key) {
|
||||
return new ResourceId(NAMESPACE, key.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9_./-]", "_"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import javax.tools.DiagnosticCollector;
|
||||
import javax.tools.JavaCompiler;
|
||||
import javax.tools.JavaFileObject;
|
||||
import javax.tools.StandardJavaFileManager;
|
||||
import javax.tools.ToolProvider;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** Compiles a pack module's sources against the Iris API on the test classpath into {@code <pack>/modules/<jar>}. */
|
||||
public final class PackModuleJar {
|
||||
private static final String SERVICE_ENTRY = "META-INF/services/com.volmit.IrisModule";
|
||||
|
||||
private PackModuleJar() {
|
||||
}
|
||||
|
||||
/** @param sources Java sources by binary class name; {@code entryClass} is the module's entry point */
|
||||
public static void write(Path pack, String jarName, String entryClass, Map<String, String> sources) throws IOException {
|
||||
Path work = Files.createTempDirectory("iris-pack-module-src");
|
||||
Path classes = Files.createDirectories(work.resolve("classes"));
|
||||
compile(work, classes, sources);
|
||||
Path jar = Files.createDirectories(pack.resolve("modules")).resolve(jarName);
|
||||
try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar))) {
|
||||
addClasses(output, classes);
|
||||
output.putNextEntry(new JarEntry(SERVICE_ENTRY));
|
||||
output.write((entryClass + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
output.closeEntry();
|
||||
}
|
||||
}
|
||||
|
||||
private static void compile(Path work, Path classes, Map<String, String> sources) throws IOException {
|
||||
List<Path> files = new ArrayList<>();
|
||||
for (Map.Entry<String, String> source : sources.entrySet()) {
|
||||
Path file = work.resolve("src").resolve(source.getKey().replace('.', '/') + ".java");
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, source.getValue(), StandardCharsets.UTF_8);
|
||||
files.add(file);
|
||||
}
|
||||
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
|
||||
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
|
||||
try (StandardJavaFileManager manager = compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) {
|
||||
List<String> options = List.of("-classpath", System.getProperty("java.class.path"), "-d", classes.toString());
|
||||
boolean compiled = compiler.getTask(null, manager, diagnostics, options, null, manager.getJavaFileObjectsFromPaths(files)).call();
|
||||
if (!compiled) {
|
||||
throw new IllegalStateException("Module sources do not compile: " + diagnostics.getDiagnostics());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void addClasses(JarOutputStream output, Path classes) throws IOException {
|
||||
try (Stream<Path> files = Files.walk(classes)) {
|
||||
for (Path file : files.filter(Files::isRegularFile).sorted().toList()) {
|
||||
output.putNextEntry(new JarEntry(classes.relativize(file).toString().replace('\\', '/')));
|
||||
output.write(Files.readAllBytes(file));
|
||||
output.closeEntry();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package art.arcane.iris.core.modules;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.pack.PackValidationResult;
|
||||
import art.arcane.iris.core.pack.PackValidator;
|
||||
import art.arcane.iris.core.project.ModuleResourceSchemas;
|
||||
import art.arcane.iris.core.project.SchemaTestPlatform;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import com.volmit.host.ResourceKindRegistration;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* A pack module that declares a resource kind of its own class and a validator, loaded from a real jar in the
|
||||
* pack's {@code modules} folder: Iris reads the kind's folder generically, serves it through PackResources, describes
|
||||
* it for studio and runs the validator wherever it validates the pack.
|
||||
*/
|
||||
public class PackModuleResourceKindTest {
|
||||
private static final String MODULE = """
|
||||
package pack.castle;
|
||||
|
||||
import com.volmit.*;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import com.volmit.stage.StageGraph;
|
||||
|
||||
public final class CastleModule implements IrisModule {
|
||||
public static final ResourceKind<Keep> KEEPS = ResourceKind.of("example:castle/keep", "keeps", Keep.class);
|
||||
|
||||
public ModuleInfo info() { return ModuleInfo.of("example:castle", "Castles", "1"); }
|
||||
public void install(StageGraph graph) {}
|
||||
public void register(FeatureRegistry registry) {
|
||||
registry.registerResourceKind(KEEPS);
|
||||
registry.registerValidator(new KeepValidator());
|
||||
}
|
||||
}
|
||||
""";
|
||||
private static final String KEEP = """
|
||||
package pack.castle;
|
||||
|
||||
import com.volmit.config.*;
|
||||
|
||||
@Desc("A keep of a castle")
|
||||
public final class Keep {
|
||||
@Desc("Towers on the walls") @MinNumber(1)
|
||||
private int towers = 4;
|
||||
@ResourceRef(Keep.class)
|
||||
private String next = "";
|
||||
|
||||
public int towers() { return towers; }
|
||||
public String next() { return next; }
|
||||
}
|
||||
""";
|
||||
private static final String VALIDATOR = """
|
||||
package pack.castle;
|
||||
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.validation.*;
|
||||
|
||||
public final class KeepValidator implements Validator {
|
||||
public void validate(ValidationContext pack) {
|
||||
for (ResourceId id : pack.resources().ids(Keep.class)) {
|
||||
Keep keep = pack.resources().require(CastleModule.KEEPS.key(id));
|
||||
if (keep.towers() > 8) {
|
||||
pack.report(Problem.error(Subject.file("keeps/" + id.path() + ".json"), "Keep has " + keep.towers() + " towers; at most 8 fit."));
|
||||
}
|
||||
ResourceId next = new ResourceId(id.namespace(), keep.next().isEmpty() ? id.path() : keep.next());
|
||||
if (pack.resources().find(CastleModule.KEEPS.key(next)).isEmpty()) {
|
||||
pack.report(Problem.warning(Subject.resource(id), "Keep leads to missing keep " + keep.next() + "."));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
private static final String HOST_FOLDER_MODULE = """
|
||||
package pack.greedy;
|
||||
|
||||
import com.volmit.*;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import com.volmit.stage.StageGraph;
|
||||
|
||||
public final class GreedyModule implements IrisModule {
|
||||
public ModuleInfo info() { return ModuleInfo.of("example:greedy", "Greedy", "1"); }
|
||||
public void install(StageGraph graph) {}
|
||||
public void register(FeatureRegistry registry) {
|
||||
registry.registerResourceKind(ResourceKind.of("example:greedy/biome", "biomes", Grab.class));
|
||||
}
|
||||
}
|
||||
""";
|
||||
private static final String GRAB = """
|
||||
package pack.greedy;
|
||||
|
||||
public final class Grab {
|
||||
}
|
||||
""";
|
||||
|
||||
@Rule
|
||||
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
|
||||
@Test
|
||||
public void aPackModulesKindIsReadFromItsFolderAndServedByType() throws Exception {
|
||||
Path pack = castlePack("castles");
|
||||
write(pack, "keeps/main.json", "{\"towers\":6,\"next\":\"towers/north\"}");
|
||||
write(pack, "keeps/towers/north.json", "{}");
|
||||
IrisData data = IrisData.openValidation(pack.toFile());
|
||||
try {
|
||||
ResourceKind<?> keeps = keepKind(data);
|
||||
ResourceId main = new ResourceId("castles", "main");
|
||||
|
||||
assertEquals(List.of(main, new ResourceId("castles", "towers/north")), data.getPackResources().ids(keeps.type()));
|
||||
Object keep = data.getPackResources().find(keeps.key(main)).orElseThrow();
|
||||
assertEquals(6, keep.getClass().getMethod("towers").invoke(keep));
|
||||
assertEquals("towers/north", keep.getClass().getMethod("next").invoke(keep));
|
||||
Object north = data.getPackResources().find(keeps.key(new ResourceId("castles", "towers/north"))).orElseThrow();
|
||||
assertEquals("an omitted field keeps its default", 4, north.getClass().getMethod("towers").invoke(north));
|
||||
assertSame("read once per pack load", keep, data.getPackResources().find(keeps.key(main)).orElseThrow());
|
||||
assertTrue(data.getPackResources().find(keeps.key(new ResourceId("castles", "missing"))).isEmpty());
|
||||
assertTrue(data.getPackResources().moduleFolderNames().containsAll(List.of("keeps", "structures")));
|
||||
assertTrue(data.resourceFolderNames().contains("keeps"));
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aModuleResourceThatFailsToReadIsAnErrorNotAbsent() throws Exception {
|
||||
Path pack = castlePack("broken-castles");
|
||||
write(pack, "keeps/main.json", "{\"towers\":\"many\"}");
|
||||
IrisData data = IrisData.openValidation(pack.toFile());
|
||||
try {
|
||||
ResourceKind<?> keeps = keepKind(data);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> data.getPackResources().find(keeps.key(new ResourceId("broken-castles", "main"))));
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void packValidationRunsThePackModulesValidatorWithItsSeverities() throws Exception {
|
||||
Path pack = castlePack("validated-castles");
|
||||
write(pack, "keeps/main.json", "{\"towers\":12,\"next\":\"gone\"}");
|
||||
|
||||
PackValidationResult result = PackValidator.validate(pack.toFile());
|
||||
|
||||
assertTrue(result.getBlockingErrors().toString(),
|
||||
result.getBlockingErrors().contains("keeps/main.json: Keep has 12 towers; at most 8 fit."));
|
||||
assertTrue(result.getWarnings().toString(),
|
||||
result.getWarnings().contains("validated-castles:main: Keep leads to missing keep gone."));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void studioDescribesTheKindFromItsClassAndCompletesReferencesWithItsKeys() throws Exception {
|
||||
Path pack = castlePack("studio-castles");
|
||||
write(pack, "keeps/main.json", "{}");
|
||||
write(pack, "keeps/towers/north.json", "{}");
|
||||
IrisData data = IrisData.openValidation(pack.toFile());
|
||||
try (SchemaTestPlatform ignored = SchemaTestPlatform.bind(temporaryFolder.getRoot())) {
|
||||
JSONObject entry = ModuleResourceSchemas.entries(data, true).stream()
|
||||
.filter(candidate -> candidate.getString("url").equals("./.iris/schema/keeps-schema.json"))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
assertEquals("/keeps/*.json", entry.getJSONArray("fileMatch").getString(0));
|
||||
JSONObject schema = new JSONObject(Files.readString(pack.resolve(".iris/schema/keeps-schema.json")));
|
||||
JSONObject properties = schema.getJSONObject("properties");
|
||||
assertEquals("A keep of a castle", schema.getString("description"));
|
||||
assertEquals(1, properties.getJSONObject("towers").getInt("minimum"));
|
||||
assertEquals("#/definitions/erzkeeps", properties.getJSONObject("next").getString("$ref"));
|
||||
assertEquals("[\"main\",\"towers/north\"]",
|
||||
schema.getJSONObject("definitions").getJSONObject("erzkeeps").getJSONArray("enum").toString());
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aKindMayNotReadAFolderIrisReadsItself() throws Exception {
|
||||
Path pack = temporaryFolder.newFolder("greedy").toPath();
|
||||
PackModuleJar.write(pack, "greedy.jar", "pack.greedy.GreedyModule",
|
||||
Map.of("pack.greedy.GreedyModule", HOST_FOLDER_MODULE, "pack.greedy.Grab", GRAB));
|
||||
IrisData data = IrisData.openValidation(pack.toFile());
|
||||
try {
|
||||
PackModulesException failure = assertThrows(PackModulesException.class, () -> data.getModules().pack());
|
||||
|
||||
assertEquals("Pack greedy cannot load its modules: Resource kind example:greedy/biome of module example:greedy"
|
||||
+ " from modules/greedy.jar reads folder 'biomes', which the host reads itself; give the kind a folder of"
|
||||
+ " its own", failure.getMessage());
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
private Path castlePack(String name) throws Exception {
|
||||
File pack = temporaryFolder.newFolder(name);
|
||||
write(pack.toPath(), "dimensions/main.json", "{\"regions\":[\"region\"]}");
|
||||
write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[\"biome\"]}");
|
||||
write(pack.toPath(), "biomes/biome.json", "{\"name\":\"Biome\"}");
|
||||
PackModuleJar.write(pack.toPath(), "castle.jar", "pack.castle.CastleModule",
|
||||
Map.of("pack.castle.CastleModule", MODULE, "pack.castle.Keep", KEEP, "pack.castle.KeepValidator", VALIDATOR));
|
||||
return pack.toPath();
|
||||
}
|
||||
|
||||
private static ResourceKind<?> keepKind(IrisData data) {
|
||||
return data.getModules().pack().catalog().resourceKinds().stream()
|
||||
.map(ResourceKindRegistration::kind)
|
||||
.filter(kind -> kind.id().toString().equals("example:castle/keep"))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
private static void write(Path root, String relative, String content) throws Exception {
|
||||
Path path = root.resolve(relative);
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, content, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package art.arcane.iris.core.pack;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisPackResources;
|
||||
import art.arcane.iris.core.modules.IrisValidationContext;
|
||||
import com.volmit.FeatureRegistry;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
import com.volmit.host.ValidatorRegistration;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.stage.StageGraph;
|
||||
import com.volmit.validation.Problem;
|
||||
import com.volmit.validation.Subject;
|
||||
import com.volmit.validation.Validator;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
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 static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Module validators run where Iris validates packs, and what they report keeps its severity. */
|
||||
public class ModulePackValidationTest {
|
||||
@Rule
|
||||
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
|
||||
@Test
|
||||
public void errorsBlockAndWarningsOnlyShowEachWithItsSubject() {
|
||||
IrisData data = packData();
|
||||
Validator validator = pack -> {
|
||||
pack.report(Problem.error(Subject.file("keeps/main.json"), "Keep main has no walls."));
|
||||
pack.report(Problem.warning(Subject.resource(ResourceId.parse("castles:main")), "Keep main is very tall."));
|
||||
};
|
||||
|
||||
ModulePackValidation.Findings findings = ModulePackValidation.validate(data, List.of(registration("example:keeps", validator)));
|
||||
|
||||
assertEquals(List.of("keeps/main.json: Keep main has no walls."), findings.errors());
|
||||
assertEquals(List.of("castles:main: Keep main is very tall."), findings.warnings());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aValidatorThatThrowsFailsValidationNamingItsModuleAndTheOthersStillRun() {
|
||||
IrisData data = packData();
|
||||
Validator broken = pack -> {
|
||||
pack.report(Problem.warning(Subject.file("keeps/main.json"), "Reported before failing."));
|
||||
throw new IllegalStateException("no walls to count");
|
||||
};
|
||||
Validator healthy = pack -> pack.report(Problem.error(Subject.file("keeps/other.json"), "Still checked."));
|
||||
|
||||
ModulePackValidation.Findings findings = ModulePackValidation.validate(data,
|
||||
List.of(registration("example:broken", broken), registration("example:healthy", healthy)));
|
||||
|
||||
assertEquals(List.of("Module example:broken from host classpath failed while validating the pack:"
|
||||
+ " java.lang.IllegalStateException: no walls to count", "keeps/other.json: Still checked."), findings.errors());
|
||||
assertEquals(List.of("keeps/main.json: Reported before failing."), findings.warnings());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validatorsSeeThePacksResourcesAndIrisSeesItsOwnData() {
|
||||
IrisData data = packData();
|
||||
IrisPackResources resources = mock(IrisPackResources.class);
|
||||
when(data.getPackResources()).thenReturn(resources);
|
||||
List<Object> seen = new ArrayList<>();
|
||||
Validator validator = pack -> {
|
||||
seen.add(pack.resources());
|
||||
seen.add(IrisValidationContext.of(pack).data());
|
||||
};
|
||||
|
||||
ModulePackValidation.validate(data, List.of(registration("example:keeps", validator)));
|
||||
|
||||
assertSame(resources, seen.get(0));
|
||||
assertSame(data, seen.get(1));
|
||||
assertThrows(IllegalArgumentException.class, () -> IrisValidationContext.of(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void packValidationRunsTheValidatorsOfThePacksModulesAndReportsModulesThatFailToLoad() throws Exception {
|
||||
File pack = minimalPack("broken-modules");
|
||||
Files.createDirectories(pack.toPath().resolve("modules"));
|
||||
Files.writeString(pack.toPath().resolve("modules/broken.jar"), "not a jar", StandardCharsets.UTF_8);
|
||||
|
||||
PackValidationResult result = PackValidator.validate(pack);
|
||||
|
||||
assertTrue(result.getBlockingErrors().toString(), result.getBlockingErrors().stream()
|
||||
.anyMatch(error -> error.startsWith("Pack broken-modules cannot load its modules: ")));
|
||||
}
|
||||
|
||||
private IrisData packData() {
|
||||
IrisData data = mock(IrisData.class);
|
||||
when(data.getDataFolder()).thenReturn(temporaryFolder.getRoot());
|
||||
return data;
|
||||
}
|
||||
|
||||
private File minimalPack(String name) throws Exception {
|
||||
File pack = temporaryFolder.newFolder(name);
|
||||
write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}");
|
||||
write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}");
|
||||
write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}");
|
||||
return pack;
|
||||
}
|
||||
|
||||
private static ValidatorRegistration registration(String moduleId, Validator validator) {
|
||||
IrisModule module = new IrisModule() {
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of(moduleId, "Test", "1");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void install(StageGraph graph) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void register(FeatureRegistry registry) {
|
||||
}
|
||||
};
|
||||
return new ValidatorRegistration(validator, DiscoveredModule.builtIn(module));
|
||||
}
|
||||
|
||||
private static void write(File root, String relative, String content) throws Exception {
|
||||
Path path = root.toPath().resolve(relative);
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, content, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
package art.arcane.iris.core.pack;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.NativeReplacementValidation;
|
||||
import art.arcane.iris.engine.framework.structure.StructureGraphValidation;
|
||||
import art.arcane.iris.engine.framework.structure.StructureValidator;
|
||||
import com.volmit.validation.Problem;
|
||||
import art.arcane.iris.spi.IrisPlatform;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.spi.PlatformStructureHooks;
|
||||
@@ -53,7 +57,7 @@ public class PackValidatorStructureGraphTest {
|
||||
write(pack, "structures/regional.json", "{}");
|
||||
write(pack, "structures/library.json", "{}");
|
||||
|
||||
assertEquals(Set.of("active", "regional"), PackObjectSurfaceValidator.collectPlacedStructureKeys(pack));
|
||||
assertEquals(Set.of("active", "regional"), StructureValidator.placedStructureKeys(pack));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -69,7 +73,7 @@ public class PackValidatorStructureGraphTest {
|
||||
+ "\"lobeFrequency\":0.02,\"lobeStrength\":0.85}}]}");
|
||||
|
||||
assertTrue(PackObjectSurfaceValidator.validateStructureGraph(pack).isEmpty());
|
||||
assertTrue(PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
assertTrue(nativeReplacementErrors(
|
||||
pack, Set.of(), Map.of()).isEmpty());
|
||||
}
|
||||
|
||||
@@ -584,7 +588,7 @@ public class PackValidatorStructureGraphTest {
|
||||
+ "\"nativeSuppression\":\"REPLACE_SOURCE\"}]}");
|
||||
write(pack, "structures/city.json", "{\"vanillaSource\":\"minecraft:ancient_city\"}");
|
||||
|
||||
assertTrue(PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
assertTrue(nativeReplacementErrors(
|
||||
pack, Set.of("city"), sampledEnvelope("city", 1, 0, 0)).isEmpty());
|
||||
}
|
||||
|
||||
@@ -595,7 +599,7 @@ public class PackValidatorStructureGraphTest {
|
||||
+ "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}],"
|
||||
+ "\"nativeSuppression\":\"REPLACE_SOURCE\"}]}");
|
||||
|
||||
assertTrue(PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
assertTrue(nativeReplacementErrors(
|
||||
pack, Set.of(), Map.of()).isEmpty());
|
||||
}
|
||||
|
||||
@@ -606,7 +610,7 @@ public class PackValidatorStructureGraphTest {
|
||||
+ "\"nativeSuppression\":\"REPLACE_SOURCE\"}]}");
|
||||
write(pack, "structures/city.json", "{\"vanillaSource\":\"minecraft:ancient_city\"}");
|
||||
|
||||
List<String> errors = PackNativeStructureValidator.validateNativeStructureReplacements(pack, Set.of(), Map.of());
|
||||
List<String> errors = nativeReplacementErrors(pack, Set.of(), Map.of());
|
||||
|
||||
assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("not runtime-viable")));
|
||||
assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("will not be used as a fallback")));
|
||||
@@ -619,7 +623,7 @@ public class PackValidatorStructureGraphTest {
|
||||
+ "\"nativeSuppression\":\"REPLACE_SOURCE\"}]}");
|
||||
write(pack, "structures/city.json", "{\"vanillaSource\":\"\"}");
|
||||
|
||||
List<String> errors = PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
List<String> errors = nativeReplacementErrors(
|
||||
pack, Set.of("city"), sampledEnvelope("city", 1, -1, 1));
|
||||
|
||||
assertTrue(errors.toString(), errors.stream().anyMatch(
|
||||
@@ -633,7 +637,7 @@ public class PackValidatorStructureGraphTest {
|
||||
+ "\"nativeSuppression\":\"REPLACE_SOURCE\"}]}");
|
||||
write(pack, "structures/city.json", "{\"vanillaSource\":\"minecraft:ancient_city\"}");
|
||||
|
||||
List<String> errors = PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
List<String> errors = nativeReplacementErrors(
|
||||
pack, Set.of("city"), sampledEnvelope("city", 1, -1, 1));
|
||||
|
||||
assertTrue(errors.toString(), errors.stream().anyMatch(
|
||||
@@ -644,7 +648,7 @@ public class PackValidatorStructureGraphTest {
|
||||
public void rejectsUndergroundReplacementBelowDimensionWritableRange() throws Exception {
|
||||
File pack = replacementPack("below", "STRUCTURE_PIECE", true, -80, -80);
|
||||
|
||||
List<String> errors = PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
List<String> errors = nativeReplacementErrors(
|
||||
pack, Set.of("city"), sampledEnvelope("city", 1, -5, 4));
|
||||
|
||||
assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("sampled seed 0")
|
||||
@@ -658,7 +662,7 @@ public class PackValidatorStructureGraphTest {
|
||||
public void rejectsUndergroundReplacementAboveDimensionWritableRange() throws Exception {
|
||||
File pack = replacementPack("above", "STRUCTURE_PIECE", true, 318, 318);
|
||||
|
||||
List<String> errors = PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
List<String> errors = nativeReplacementErrors(
|
||||
pack, Set.of("city"), sampledEnvelope("city", 1, -5, 4));
|
||||
|
||||
assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("sampled seed 0")
|
||||
@@ -671,7 +675,7 @@ public class PackValidatorStructureGraphTest {
|
||||
public void surfaceAlignsMultiPieceEnvelopeBeforeCheckingWorldBounds() throws Exception {
|
||||
File pack = replacementPack("surface-aligned", "CENTER_HEIGHT", false, 290, 290);
|
||||
|
||||
List<String> errors = PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
List<String> errors = nativeReplacementErrors(
|
||||
pack, Set.of("city"), sampledEnvelope("city", 2, -30, 10));
|
||||
|
||||
assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("surface-aligned")
|
||||
@@ -683,7 +687,7 @@ public class PackValidatorStructureGraphTest {
|
||||
public void doesNotApplyExactYEnvelopeGateToSingleSurfacePiece() throws Exception {
|
||||
File pack = replacementPack("surface-single", "CENTER_HEIGHT", false, -63, 319);
|
||||
|
||||
List<String> errors = PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
List<String> errors = nativeReplacementErrors(
|
||||
pack, Set.of("city"), sampledEnvelope("city", 1, -500, 500));
|
||||
|
||||
assertTrue(errors.toString(), errors.isEmpty());
|
||||
@@ -693,7 +697,7 @@ public class PackValidatorStructureGraphTest {
|
||||
public void validatesEverySurfaceExactYAnchorAgainstWritableWorldBounds() throws Exception {
|
||||
File pack = replacementPack("surface-exact-range", "STRUCTURE_PIECE", false, -63, 319);
|
||||
|
||||
List<String> errors = PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
List<String> errors = nativeReplacementErrors(
|
||||
pack, Set.of("city"), sampledEnvelope("city", 1, -5, 4));
|
||||
|
||||
assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("sampled seed 0")
|
||||
@@ -706,7 +710,7 @@ public class PackValidatorStructureGraphTest {
|
||||
public void acceptsSurfaceExactYWhenEveryConfiguredAnchorFits() throws Exception {
|
||||
File pack = replacementPack("surface-exact-safe", "STRUCTURE_PIECE", false, -58, 315);
|
||||
|
||||
List<String> errors = PackNativeStructureValidator.validateNativeStructureReplacements(
|
||||
List<String> errors = nativeReplacementErrors(
|
||||
pack, Set.of("city"), sampledEnvelope("city", 1, -5, 4));
|
||||
|
||||
assertTrue(errors.toString(), errors.isEmpty());
|
||||
@@ -756,7 +760,7 @@ public class PackValidatorStructureGraphTest {
|
||||
}
|
||||
|
||||
PackValidationResult result = PackValidator.validate(pack);
|
||||
String expected = "Malformed Iris object resource " + object + ": EOFException";
|
||||
String expected = "structures/castle.json: Malformed Iris object resource " + object + ": EOFException";
|
||||
|
||||
assertTrue(result.getBlockingErrors().toString(), result.getBlockingErrors().contains(expected));
|
||||
assertFalse(result.getBlockingErrors().toString(), result.getBlockingErrors().stream().anyMatch(
|
||||
@@ -930,14 +934,24 @@ public class PackValidatorStructureGraphTest {
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, List<StructureGraphPackValidator.SampledVerticalEnvelope>> sampledEnvelope(
|
||||
private static List<String> nativeReplacementErrors(
|
||||
File pack,
|
||||
Set<String> replacementOutputStructures,
|
||||
Map<String, List<StructureGraphValidation.SampledVerticalEnvelope>> sampledVerticalEnvelopes
|
||||
) {
|
||||
return NativeReplacementValidation.validate(pack, replacementOutputStructures, sampledVerticalEnvelopes).stream()
|
||||
.map(Problem::message)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private Map<String, List<StructureGraphValidation.SampledVerticalEnvelope>> sampledEnvelope(
|
||||
String structureKey,
|
||||
int pieceCount,
|
||||
int minimumYOffset,
|
||||
int maximumYOffset
|
||||
) {
|
||||
return Map.of(structureKey, List.of(
|
||||
new StructureGraphPackValidator.SampledVerticalEnvelope(
|
||||
new StructureGraphValidation.SampledVerticalEnvelope(
|
||||
0L, pieceCount, minimumYOffset, maximumYOffset)));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
package art.arcane.iris.core.project;
|
||||
|
||||
import art.arcane.iris.engine.mantle.components.StructureModule;
|
||||
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.PackModuleSet;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFixture;
|
||||
import com.volmit.host.LoadedPack;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
@@ -64,6 +68,12 @@ public class IrisImageMapSchemaTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
private static IrisData schemaData() {
|
||||
IrisData data = mock(IrisData.class);
|
||||
LoadedPack pack = mock(LoadedPack.class);
|
||||
PackModuleSet modules = mock(PackModuleSet.class);
|
||||
when(pack.catalog()).thenReturn(ModuleResourceFixture.catalogOf(new StructureModule()));
|
||||
when(modules.pack()).thenReturn(pack);
|
||||
when(data.getModules()).thenReturn(modules);
|
||||
ModuleResourceFixture.serve(data);
|
||||
KMap<Class<? extends IrisRegistrant>, ResourceLoader<? extends IrisRegistrant>> loaders = new KMap<>();
|
||||
when(data.getLoaders()).thenReturn(loaders);
|
||||
when(data.getPossibleSnippets(anyString())).thenReturn(new KList<>());
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.core.project;
|
||||
|
||||
import art.arcane.iris.engine.mantle.components.StructureModule;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
@@ -25,7 +26,6 @@ import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.engine.object.material.IrisBlockData;
|
||||
import art.arcane.iris.engine.object.noise.expression.IrisExpression;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
|
||||
import art.arcane.iris.engine.object.structure.vanilla.IrisVanillaStructureAdjustment;
|
||||
@@ -60,6 +60,7 @@ import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import art.arcane.iris.core.modules.PackModuleSet;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFixture;
|
||||
import com.volmit.FeatureAttachment.Target;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.IrisModule;
|
||||
@@ -318,7 +319,7 @@ public class SchemaBuilderParityTest {
|
||||
}
|
||||
|
||||
private static IrisData structureSchemaData() {
|
||||
return structureSchemaData(new PackSchema(List.of(), List.of()));
|
||||
return structureSchemaData(new PackSchema(List.of(), List.of(), List.of()));
|
||||
}
|
||||
|
||||
/** {@code modules} is what the pack's modules add to its JSON. */
|
||||
@@ -327,21 +328,17 @@ public class SchemaBuilderParityTest {
|
||||
LoadedPack pack = mock(LoadedPack.class);
|
||||
PackModuleSet moduleSet = mock(PackModuleSet.class);
|
||||
when(pack.schema()).thenReturn(modules);
|
||||
when(pack.catalog()).thenReturn(ModuleResourceFixture.catalogOf(new StructureModule()));
|
||||
when(moduleSet.pack()).thenReturn(pack);
|
||||
when(data.getModules()).thenReturn(moduleSet);
|
||||
ResourceLoader<IrisStructure> structureLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
ModuleResourceFixture.serve(data);
|
||||
ResourceLoader<IrisExpression> expressionLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisBlockData> blockLoader = mock(ResourceLoader.class);
|
||||
KMap<Class<? extends IrisRegistrant>, ResourceLoader<? extends IrisRegistrant>> loaders = new KMap<>();
|
||||
loaders.put(IrisExpression.class, expressionLoader);
|
||||
when(data.getStructureLoader()).thenReturn(structureLoader);
|
||||
when(data.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
when(data.getBlockLoader()).thenReturn(blockLoader);
|
||||
when(data.getLoaders()).thenReturn(loaders);
|
||||
when(data.getPossibleSnippets(anyString())).thenReturn(new KList<>());
|
||||
when(structureLoader.getPossibleKeys()).thenReturn(new String[0]);
|
||||
when(pieceLoader.getPossibleKeys()).thenReturn(new String[0]);
|
||||
when(blockLoader.getPossibleKeys()).thenReturn(new String[0]);
|
||||
when(expressionLoader.getPossibleKeys()).thenReturn(new String[0]);
|
||||
when(expressionLoader.getFolderName()).thenReturn("expressions");
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package art.arcane.iris.core.project;
|
||||
|
||||
import art.arcane.iris.spi.IrisPlatform;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.spi.PlatformRegistries;
|
||||
import org.mockito.Answers;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Binds a platform whose registries list nothing, so studio schemas can be built in a test; closing restores the previous one. */
|
||||
public final class SchemaTestPlatform implements AutoCloseable {
|
||||
private final IrisPlatform previous;
|
||||
|
||||
private SchemaTestPlatform(File dataFolder) {
|
||||
previous = IrisPlatforms.isBound() ? IrisPlatforms.get() : null;
|
||||
IrisPlatforms.unbind();
|
||||
IrisPlatform platform = mock(IrisPlatform.class, Answers.CALLS_REAL_METHODS);
|
||||
PlatformRegistries registries = mock(PlatformRegistries.class);
|
||||
when(platform.dataFolder()).thenReturn(dataFolder);
|
||||
when(platform.registries()).thenReturn(registries);
|
||||
IrisPlatforms.bind(platform);
|
||||
}
|
||||
|
||||
public static SchemaTestPlatform bind(File dataFolder) {
|
||||
return new SchemaTestPlatform(dataFolder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
IrisPlatforms.unbind();
|
||||
if (previous != null) {
|
||||
IrisPlatforms.bind(previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-28
@@ -1,7 +1,9 @@
|
||||
package art.arcane.iris.core.runtime.jigsaw;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFixture;
|
||||
import art.arcane.iris.core.structure.authoring.StructureBackend;
|
||||
import art.arcane.iris.core.structure.authoring.StructureKey;
|
||||
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
|
||||
@@ -63,16 +65,13 @@ public class JigsawStudioGraphMapperTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void catalogPreservesDuplicateWeightedPoolEntries() {
|
||||
IrisData data = mock(IrisData.class);
|
||||
ResourceLoader<IrisJigsawPool> poolLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
when(data.getJigsawPoolLoader()).thenReturn(poolLoader);
|
||||
when(data.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(data);
|
||||
|
||||
IrisJigsawPool start = new IrisJigsawPool().setPieces(new KList<>());
|
||||
start.getPieces().add(new IrisJigsawPieceEntry("village/end", 2).setChance(0.25D));
|
||||
start.getPieces().add(new IrisJigsawPieceEntry("village/end", 7));
|
||||
start.getPieces().add(new IrisJigsawPieceEntry("village/east", 5));
|
||||
when(poolLoader.load("village/start")).thenReturn(start);
|
||||
resources.resource(StructureResources.POOLS, "village/start", start);
|
||||
IrisJigsawPiece endPiece = planarPiece("village/end", IrisDirection.NORTH_NEGATIVE_Z)
|
||||
.setRules(new IrisJigsawPieceRules()
|
||||
.setMinimumDepth(1)
|
||||
@@ -81,8 +80,8 @@ public class JigsawStudioGraphMapperTest {
|
||||
.setMaximumPlacements(2)
|
||||
.setTerminal(true));
|
||||
endPiece.getThemes().add("spruce");
|
||||
when(pieceLoader.load("village/end")).thenReturn(endPiece);
|
||||
when(pieceLoader.load("village/east")).thenReturn(planarPiece(
|
||||
resources.resource(StructureResources.PIECES, "village/end", endPiece);
|
||||
resources.resource(StructureResources.PIECES, "village/east", planarPiece(
|
||||
"village/east", IrisDirection.EAST_POSITIVE_X));
|
||||
IrisStructure structure = new IrisStructure()
|
||||
.setStartPool("village/start")
|
||||
@@ -108,14 +107,11 @@ public class JigsawStudioGraphMapperTest {
|
||||
public void ownedUnassignedPiecesRequireOwnedObjectForEditing() throws Exception {
|
||||
Path root = temporaryFolder.newFolder("pack").toPath();
|
||||
IrisData data = mock(IrisData.class);
|
||||
ResourceLoader<IrisJigsawPool> poolLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
when(data.getDataFolder()).thenReturn(root.toFile());
|
||||
when(data.getJigsawPoolLoader()).thenReturn(poolLoader);
|
||||
when(data.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
when(pieceLoader.load("village/orphan")).thenReturn(planarPiece(
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(data);
|
||||
resources.resource(StructureResources.PIECES, "village/orphan", planarPiece(
|
||||
"village/orphan", IrisDirection.NORTH_NEGATIVE_Z));
|
||||
when(pieceLoader.load("village/incomplete")).thenReturn(planarPiece(
|
||||
resources.resource(StructureResources.PIECES, "village/incomplete", planarPiece(
|
||||
"village/incomplete", IrisDirection.EAST_POSITIVE_X));
|
||||
|
||||
IrisStructure structure = new IrisStructure()
|
||||
@@ -156,12 +152,9 @@ public class JigsawStudioGraphMapperTest {
|
||||
public void managedDatapackManifestResourcesRemainReadOnly() throws Exception {
|
||||
Path root = temporaryFolder.newFolder("managed-pack").toPath();
|
||||
IrisData data = mock(IrisData.class);
|
||||
ResourceLoader<IrisJigsawPool> poolLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
when(data.getDataFolder()).thenReturn(root.toFile());
|
||||
when(data.getJigsawPoolLoader()).thenReturn(poolLoader);
|
||||
when(data.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
when(pieceLoader.load("village/managed")).thenReturn(planarPiece(
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(data);
|
||||
resources.resource(StructureResources.PIECES, "village/managed", planarPiece(
|
||||
"village/managed", IrisDirection.NORTH_NEGATIVE_Z));
|
||||
|
||||
IrisStructure structure = new IrisStructure()
|
||||
@@ -238,18 +231,15 @@ public class JigsawStudioGraphMapperTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void mapsAuthorLabelsAndCanonicalPerVariantDimensionsIndependently() {
|
||||
IrisData data = mock(IrisData.class);
|
||||
ResourceLoader<IrisJigsawPool> poolLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisObject> objectLoader = mock(ResourceLoader.class);
|
||||
when(data.getJigsawPoolLoader()).thenReturn(poolLoader);
|
||||
when(data.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(data);
|
||||
when(data.getObjectLoader()).thenReturn(objectLoader);
|
||||
IrisJigsawPool start = new IrisJigsawPool().setPieces(new KList<>());
|
||||
start.getPieces().add(new IrisJigsawPieceEntry("village/east-gate", 1));
|
||||
when(poolLoader.load("village/start")).thenReturn(start);
|
||||
resources.resource(StructureResources.POOLS, "village/start", start);
|
||||
IrisJigsawPiece gate = planarPiece("village/east-gate", IrisDirection.EAST_POSITIVE_X)
|
||||
.setDisplayName("East Gatehouse");
|
||||
when(pieceLoader.load("village/east-gate")).thenReturn(gate);
|
||||
resources.resource(StructureResources.PIECES, "village/east-gate", gate);
|
||||
when(objectLoader.load("village/east-gate")).thenReturn(new IrisObject(7, 3, 5));
|
||||
IrisStructure structure = new IrisStructure()
|
||||
.setStartPool("village/start")
|
||||
@@ -280,8 +270,7 @@ public class JigsawStudioGraphMapperTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void mapsSpatialWorkcellLabelWithoutChangingItsCanonicalRole() {
|
||||
IrisData data = mock(IrisData.class);
|
||||
when(data.getJigsawPoolLoader()).thenReturn(mock(ResourceLoader.class));
|
||||
when(data.getJigsawPieceLoader()).thenReturn(mock(ResourceLoader.class));
|
||||
ModuleResourceFixture.serve(data);
|
||||
IrisStructure structure = new IrisStructure()
|
||||
.setStartPool("stronghold/missing")
|
||||
.setMode(IrisJigsawMode.SPATIAL_JIGSAW)
|
||||
@@ -298,8 +287,7 @@ public class JigsawStudioGraphMapperTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void planarMapPreservesIndependentEmptyAndDisabledWorkcellBounds() {
|
||||
IrisData data = mock(IrisData.class);
|
||||
when(data.getJigsawPoolLoader()).thenReturn(mock(ResourceLoader.class));
|
||||
when(data.getJigsawPieceLoader()).thenReturn(mock(ResourceLoader.class));
|
||||
ModuleResourceFixture.serve(data);
|
||||
IrisStructure structure = new IrisStructure()
|
||||
.setStartPool("village/missing")
|
||||
.setMode(IrisJigsawMode.PLANAR_JIGSAW);
|
||||
|
||||
+7
-11
@@ -1,5 +1,7 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFixture;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBounds;
|
||||
@@ -522,16 +524,12 @@ public class JigsawStudioServiceCaptureTest {
|
||||
when(request.structureKey()).thenReturn("qa/profile_final");
|
||||
IrisData source = mock(IrisData.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ResourceLoader<IrisObject> objectLoader = mock(ResourceLoader.class);
|
||||
when(request.source()).thenReturn(source);
|
||||
when(source.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(source);
|
||||
when(source.getObjectLoader()).thenReturn(objectLoader);
|
||||
when(pieceLoader.load("test/end", false))
|
||||
.thenReturn(new IrisJigsawPiece().setObject("test/end"));
|
||||
when(pieceLoader.load("test/straight", false))
|
||||
.thenReturn(new IrisJigsawPiece().setObject("test/straight"));
|
||||
resources.resource(StructureResources.PIECES, "test/end", new IrisJigsawPiece().setObject("test/end"));
|
||||
resources.resource(StructureResources.PIECES, "test/straight", new IrisJigsawPiece().setObject("test/straight"));
|
||||
when(objectLoader.load("test/end", false)).thenReturn(new IrisObject(16, 16, 16));
|
||||
when(objectLoader.load("test/straight", false)).thenReturn(new IrisObject(16, 16, 16));
|
||||
JigsawStudioGenerator generator = mock(JigsawStudioGenerator.class);
|
||||
@@ -648,15 +646,13 @@ public class JigsawStudioServiceCaptureTest {
|
||||
when(request.ownerId()).thenReturn(ownerId);
|
||||
IrisData source = mock(IrisData.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ResourceLoader<IrisObject> objectLoader = mock(ResourceLoader.class);
|
||||
IrisJigsawPiece piece = new IrisJigsawPiece().setObject("test/end");
|
||||
IrisObject object = new IrisObject(16, 16, 16);
|
||||
when(request.source()).thenReturn(source);
|
||||
when(source.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(source);
|
||||
when(source.getObjectLoader()).thenReturn(objectLoader);
|
||||
when(pieceLoader.load("test/end", false)).thenReturn(piece);
|
||||
resources.resource(StructureResources.PIECES, "test/end", piece);
|
||||
when(objectLoader.load("test/end", false)).thenReturn(object);
|
||||
JigsawStudioGenerator generator = mock(JigsawStudioGenerator.class);
|
||||
when(generator.getRequest()).thenReturn(request);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package art.arcane.iris.core.structure;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFixture;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.iris.spi.IrisPlatform;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.spi.PlatformStructureHooks;
|
||||
import art.arcane.volmlib.util.data.KCache;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
@@ -27,6 +27,7 @@ import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -75,19 +76,23 @@ public class StructureIndexServiceTest {
|
||||
Files.createDirectories(legacyIndex.toPath().getParent());
|
||||
Files.writeString(legacyIndex.toPath(), "{}", StandardCharsets.UTF_8);
|
||||
IrisData data = mock(IrisData.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ResourceLoader<IrisStructure> structureLoader = mock(ResourceLoader.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
KCache<String, IrisStructure> loadCache = mock(KCache.class);
|
||||
when(data.getDataFolder()).thenReturn(pack);
|
||||
when(data.getStructureLoader()).thenReturn(structureLoader);
|
||||
when(structureLoader.getLoadCache()).thenReturn(loadCache);
|
||||
|
||||
StructureIndexService.removeLegacyIndex(data);
|
||||
|
||||
assertFalse(legacyIndex.exists());
|
||||
verify(loadCache).invalidate("structure-index");
|
||||
verify(structureLoader).clearList();
|
||||
verify(data).invalidateStructureResources();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structureResourcesStayUntouchedWithoutALegacyIndex() throws Exception {
|
||||
File pack = temporaryFolder.newFolder("pack");
|
||||
IrisData data = mock(IrisData.class);
|
||||
when(data.getDataFolder()).thenReturn(pack);
|
||||
|
||||
StructureIndexService.removeLegacyIndex(data);
|
||||
|
||||
verify(data, never()).invalidateStructureResources();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,16 +102,12 @@ public class StructureIndexServiceTest {
|
||||
Files.createDirectories(legacyIndex.toPath().getParent());
|
||||
Files.writeString(legacyIndex.toPath(), "{}", StandardCharsets.UTF_8);
|
||||
IrisData data = mock(IrisData.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ResourceLoader<IrisStructure> structureLoader = mock(ResourceLoader.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
KCache<String, IrisStructure> loadCache = mock(KCache.class);
|
||||
IrisPlatform platform = mock(IrisPlatform.class);
|
||||
PlatformStructureHooks structureHooks = mock(PlatformStructureHooks.class);
|
||||
when(data.getDataFolder()).thenReturn(pack);
|
||||
when(data.getStructureLoader()).thenReturn(structureLoader);
|
||||
when(structureLoader.getLoadCache()).thenReturn(loadCache);
|
||||
when(structureLoader.getPossibleKeys()).thenReturn(new String[]{"castle", "structure-index"});
|
||||
ModuleResourceFixture.serve(data)
|
||||
.resource(StructureResources.STRUCTURES, "castle", new IrisStructure())
|
||||
.resource(StructureResources.STRUCTURES, "structure-index", new IrisStructure());
|
||||
when(structureHooks.structureKeys()).thenReturn(List.of("minecraft:village", "example:castle"));
|
||||
when(structureHooks.structureSetKeys()).thenReturn(List.of("minecraft:villages"));
|
||||
|
||||
@@ -123,9 +124,8 @@ public class StructureIndexServiceTest {
|
||||
assertEquals(StructureIndexService.indexFile(pack), index);
|
||||
assertTrue(index.isFile());
|
||||
assertFalse(legacyIndex.exists());
|
||||
InOrder order = inOrder(loadCache, structureLoader, structureHooks);
|
||||
order.verify(loadCache).invalidate("structure-index");
|
||||
order.verify(structureLoader).clearList();
|
||||
InOrder order = inOrder(data, structureHooks);
|
||||
order.verify(data).invalidateStructureResources();
|
||||
order.verify(structureHooks).structureKeys();
|
||||
order.verify(structureHooks).structureSetKeys();
|
||||
assertNull(StructureIndexService.writeOnce(data));
|
||||
|
||||
+15
-12
@@ -18,6 +18,8 @@
|
||||
|
||||
package art.arcane.iris.engine.framework;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFixture;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.structure.StructureGraphCatalog;
|
||||
import art.arcane.iris.engine.object.value.IrisDirection;
|
||||
@@ -111,7 +113,7 @@ public class IrisStructureLocatorContractTest {
|
||||
IrisStructure structure = new IrisStructure();
|
||||
structure.setLoadKey("test:city");
|
||||
structure.setVanillaSource("source:city");
|
||||
when(data.load(IrisStructure.class, "test:city_definition", false)).thenReturn(structure);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city_definition", structure);
|
||||
|
||||
IrisStructurePlacement editable = new IrisStructurePlacement();
|
||||
editable.getStructures().add("test:city_definition");
|
||||
@@ -182,7 +184,7 @@ public class IrisStructureLocatorContractTest {
|
||||
IrisStructure structure = new IrisStructure();
|
||||
structure.setLoadKey("test:city");
|
||||
structure.setVanillaSource("minecraft:ancient_city");
|
||||
when(data.load(IrisStructure.class, "test:city", false)).thenReturn(structure);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure);
|
||||
registerSinglePieceGraph(data, structure, "test:city");
|
||||
|
||||
IrisStructurePlacement placement = new IrisStructurePlacement();
|
||||
@@ -211,7 +213,7 @@ public class IrisStructureLocatorContractTest {
|
||||
IrisStructure structure = new IrisStructure();
|
||||
structure.setLoadKey("test:city");
|
||||
structure.setVanillaSource("minecraft:ancient_city");
|
||||
when(data.load(IrisStructure.class, "test:city", false)).thenReturn(structure);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure);
|
||||
registerSinglePieceGraph(data, structure, "test:city");
|
||||
|
||||
IrisStructurePlacement placement = new IrisStructurePlacement();
|
||||
@@ -270,11 +272,11 @@ public class IrisStructureLocatorContractTest {
|
||||
when(targetObject.getW()).thenReturn(100);
|
||||
when(targetObject.getH()).thenReturn(1);
|
||||
when(targetObject.getD()).thenReturn(1);
|
||||
when(data.load(IrisStructure.class, "test:city", false)).thenReturn(structure);
|
||||
when(data.load(IrisJigsawPool.class, "test:start", false)).thenReturn(startPool);
|
||||
when(data.load(IrisJigsawPool.class, "test:target", false)).thenReturn(targetPool);
|
||||
when(data.load(IrisJigsawPiece.class, "test:start-piece", false)).thenReturn(startPiece);
|
||||
when(data.load(IrisJigsawPiece.class, "test:target-piece", false)).thenReturn(targetPiece);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.POOLS, "test:start", startPool);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.POOLS, "test:target", targetPool);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.PIECES, "test:start-piece", startPiece);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.PIECES, "test:target-piece", targetPiece);
|
||||
when(data.load(IrisObject.class, "test:start-object", false)).thenReturn(startObject);
|
||||
when(data.load(IrisObject.class, "test:target-object", false)).thenReturn(targetObject);
|
||||
assertFalse(StructureGraphCatalog.compile(data, structure).isAssemblyViable());
|
||||
@@ -300,7 +302,7 @@ public class IrisStructureLocatorContractTest {
|
||||
IrisData data = mock(IrisData.class);
|
||||
IrisStructure structure = new IrisStructure();
|
||||
structure.setLoadKey("test:city");
|
||||
when(data.load(IrisStructure.class, "test:city", false)).thenReturn(structure);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure);
|
||||
registerSinglePieceGraph(data, structure, "test:city");
|
||||
IrisStructurePlacement placement = new IrisStructurePlacement()
|
||||
.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE);
|
||||
@@ -321,6 +323,7 @@ public class IrisStructureLocatorContractTest {
|
||||
@Test
|
||||
public void missingNonReplacementStructureFailsInsteadOfBeingSkipped() {
|
||||
IrisData data = mock(IrisData.class);
|
||||
ModuleResourceFixture.serve(data);
|
||||
IrisStructurePlacement placement = new IrisStructurePlacement();
|
||||
placement.getStructures().add("test:missing");
|
||||
IrisDimension dimension = mock(IrisDimension.class);
|
||||
@@ -800,7 +803,7 @@ public class IrisStructureLocatorContractTest {
|
||||
IrisData data = mock(IrisData.class);
|
||||
IrisStructure structure = new IrisStructure();
|
||||
structure.setLoadKey("test:density");
|
||||
when(data.load(IrisStructure.class, "test:density", false)).thenReturn(structure);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:density", structure);
|
||||
registerSinglePieceGraph(data, structure, "test:density");
|
||||
|
||||
IrisStructurePlacement placement = new IrisStructurePlacement();
|
||||
@@ -839,8 +842,8 @@ public class IrisStructureLocatorContractTest {
|
||||
when(object.getW()).thenReturn(1);
|
||||
when(object.getH()).thenReturn(1);
|
||||
when(object.getD()).thenReturn(1);
|
||||
when(data.load(IrisJigsawPool.class, poolKey, false)).thenReturn(pool);
|
||||
when(data.load(IrisJigsawPiece.class, pieceKey, false)).thenReturn(piece);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.POOLS, poolKey, pool);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.PIECES, pieceKey, piece);
|
||||
when(data.load(IrisObject.class, objectKey, false)).thenReturn(object);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
package art.arcane.iris.engine.framework;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFixture;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.structure.StructureAssemblyResult;
|
||||
import art.arcane.iris.engine.framework.structure.StructureAssemblyStatus;
|
||||
@@ -1195,15 +1197,15 @@ public class StructureAssemblerTest {
|
||||
private final IrisData data = mock(IrisData.class);
|
||||
|
||||
private Fixture() {
|
||||
when(data.load(IrisJigsawPool.class, "terminal", false)).thenReturn(new IrisJigsawPool());
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.POOLS, "terminal", new IrisJigsawPool());
|
||||
}
|
||||
|
||||
private void pool(String key, IrisJigsawPool pool) {
|
||||
when(data.load(IrisJigsawPool.class, key, false)).thenReturn(pool);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.POOLS, key, pool);
|
||||
}
|
||||
|
||||
private void piece(String key, IrisJigsawPiece piece) {
|
||||
when(data.load(IrisJigsawPiece.class, key, false)).thenReturn(piece);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.PIECES, key, piece);
|
||||
}
|
||||
|
||||
private void object(String key, IrisObject object) {
|
||||
|
||||
+31
-20
@@ -16,8 +16,9 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.pack;
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
@@ -34,7 +35,8 @@ import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StructureGraphPackValidatorTest {
|
||||
/** The structure module's graph check, run on real pack folders the way Iris opens a pack to validate it. */
|
||||
public class StructureGraphValidationTest {
|
||||
@Rule
|
||||
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
|
||||
@@ -49,7 +51,7 @@ public class StructureGraphPackValidatorTest {
|
||||
+ "\"direction\":\"NORTH_NEGATIVE_Z\",\"pool\":\"castle/start\",\"name\":\"path\",\"targetName\":\"path\"}]}");
|
||||
writeObjectHeader(pack.resolve("objects/castle/start.iob"), 1, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertTrue(validation.errors().stream().anyMatch(message -> message.contains("non-positive weight 0")));
|
||||
assertTrue(validation.errors().stream().anyMatch(message -> message.contains("outside object bounds")));
|
||||
@@ -67,7 +69,7 @@ public class StructureGraphPackValidatorTest {
|
||||
"{\"object\":\"castle/piece\",\"connectors\":[]}");
|
||||
writeObjectHeader(pack.resolve("objects/castle/piece.iob"), 1, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertTrue(validation.errors().stream().anyMatch(message -> message.contains("fallback cycle")));
|
||||
}
|
||||
@@ -89,7 +91,7 @@ public class StructureGraphPackValidatorTest {
|
||||
writeObjectHeader(pack.resolve("objects/castle/start.iob"), 1, 1, 1);
|
||||
writeObjectHeader(pack.resolve("objects/castle/target.iob"), 1, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertTrue(validation.errors().stream().anyMatch(
|
||||
message -> message.contains("does not produce a complete deterministic assembly")));
|
||||
@@ -116,7 +118,7 @@ public class StructureGraphPackValidatorTest {
|
||||
writeObjectHeader(pack.resolve("objects/castle/start.iob"), 1, 1, 1);
|
||||
writeObjectHeader(pack.resolve("objects/castle/target.iob"), 1, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
|
||||
}
|
||||
@@ -138,8 +140,8 @@ public class StructureGraphPackValidatorTest {
|
||||
writeObjectHeader(pack.resolve("objects/library/start.iob"), 1, 1, 1);
|
||||
writeObjectHeader(pack.resolve("objects/library/target.iob"), 1, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation =
|
||||
StructureGraphPackValidator.validate(pack, Set.of());
|
||||
StructureGraphValidation.Validation validation =
|
||||
validate(pack, Set.of());
|
||||
|
||||
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
|
||||
assertTrue(validation.warnings().toString(), validation.warnings().isEmpty());
|
||||
@@ -156,7 +158,7 @@ public class StructureGraphPackValidatorTest {
|
||||
Path object = pack.resolve("objects/castle/start.iob");
|
||||
writeTruncatedObjectHeader(object, 1, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertEquals(List.of("Malformed Iris object resource " + object
|
||||
+ ": EOFException"), validation.errors());
|
||||
@@ -172,8 +174,8 @@ public class StructureGraphPackValidatorTest {
|
||||
"{\"object\":\"library/start\",\"connectors\":[]}");
|
||||
writeTruncatedObjectHeader(pack.resolve("objects/library/start.iob"), 1, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation =
|
||||
StructureGraphPackValidator.validate(pack, Set.of());
|
||||
StructureGraphValidation.Validation validation =
|
||||
validate(pack, Set.of());
|
||||
|
||||
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
|
||||
}
|
||||
@@ -188,7 +190,7 @@ public class StructureGraphPackValidatorTest {
|
||||
"{\"object\":\"castle/start\",\"connectors\":[]}");
|
||||
writeSignedObject(pack.resolve("objects/castle/start.iob"), 18, 31, 41, -9, -15, -20);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertFalse(validation.errors().toString(),
|
||||
validation.errors().stream().anyMatch(message -> message.contains("missing object")));
|
||||
@@ -205,8 +207,8 @@ public class StructureGraphPackValidatorTest {
|
||||
"{\"object\":\"castle/start\",\"connectors\":[]}");
|
||||
writeObjectHeader(pack.resolve("objects/castle/start.iob"), 3, 9, 3);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
List<StructureGraphPackValidator.SampledVerticalEnvelope> envelopes =
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
List<StructureGraphValidation.SampledVerticalEnvelope> envelopes =
|
||||
validation.sampledVerticalEnvelopes().get("castle");
|
||||
|
||||
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
|
||||
@@ -215,7 +217,7 @@ public class StructureGraphPackValidatorTest {
|
||||
&& envelope.minimumYOffset() == -4
|
||||
&& envelope.maximumYOffset() == 4));
|
||||
assertThrows(UnsupportedOperationException.class,
|
||||
() -> envelopes.add(new StructureGraphPackValidator.SampledVerticalEnvelope(1L, 1, 0, 0)));
|
||||
() -> envelopes.add(new StructureGraphValidation.SampledVerticalEnvelope(1L, 1, 0, 0)));
|
||||
assertThrows(UnsupportedOperationException.class,
|
||||
() -> validation.sampledVerticalEnvelopes().put("other", List.of()));
|
||||
}
|
||||
@@ -233,7 +235,7 @@ public class StructureGraphPackValidatorTest {
|
||||
+ "\"name\":\"source\",\"targetName\":\"door\"}]}" );
|
||||
writeObjectHeader(pack.resolve("objects/castle/start.iob"), 1, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
|
||||
}
|
||||
@@ -245,7 +247,7 @@ public class StructureGraphPackValidatorTest {
|
||||
write(pack, "jigsaw-pools/castle/start.json",
|
||||
"{\"pieces\":[{\"empty\":true,\"weight\":1}]}");
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
|
||||
assertFalse(validation.replacementOutputStructures().contains("castle"));
|
||||
@@ -262,7 +264,7 @@ public class StructureGraphPackValidatorTest {
|
||||
"{\"object\":\"castle/start\",\"connectors\":[]}");
|
||||
writeObjectHeader(pack.resolve("objects/castle/start.iob"), 1, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
|
||||
assertFalse(validation.replacementOutputStructures().contains("castle"));
|
||||
@@ -279,7 +281,7 @@ public class StructureGraphPackValidatorTest {
|
||||
"{\"object\":\"castle/start\",\"connectors\":[]}");
|
||||
writeObjectHeader(pack.resolve("objects/castle/start.iob"), 34, 1, 1);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
|
||||
assertFalse(validation.replacementOutputStructures().contains("castle"));
|
||||
@@ -310,13 +312,22 @@ public class StructureGraphPackValidatorTest {
|
||||
writeObjectHeader(pack.resolve("objects/castle/start.iob"), 3, 3, 3);
|
||||
writeObjectHeader(pack.resolve("objects/castle/recursive.iob"), 3, 3, 3);
|
||||
|
||||
StructureGraphPackValidator.Validation validation = StructureGraphPackValidator.validate(pack);
|
||||
StructureGraphValidation.Validation validation = validate(pack, null);
|
||||
|
||||
assertTrue(validation.errors().toString(), validation.errors().stream().anyMatch(
|
||||
message -> message.contains("does not produce a complete deterministic assembly")
|
||||
&& message.contains("seed 0")));
|
||||
}
|
||||
|
||||
private static StructureGraphValidation.Validation validate(Path pack, Set<String> activeStructureKeys) {
|
||||
IrisData data = IrisData.openValidation(pack.toFile());
|
||||
try {
|
||||
return StructureGraphValidation.validate(data, activeStructureKeys);
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void write(Path root, String relativePath, String content) throws Exception {
|
||||
Path file = root.resolve(relativePath);
|
||||
Files.createDirectories(file.getParent());
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisModuleHost;
|
||||
import art.arcane.iris.core.project.ModuleResourceSchemas;
|
||||
import art.arcane.iris.core.project.SchemaTestPlatform;
|
||||
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.volmlib.util.json.JSONObject;
|
||||
import com.volmit.host.ResourceKindRegistration;
|
||||
import com.volmit.host.ValidatorRegistration;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* The pilot: structures, jigsaw pools and pieces are resource kinds of module {@code iris:structure}, read from the
|
||||
* folders and files packs have always had, and Iris has no loaders of its own for them any more.
|
||||
*/
|
||||
public class StructureResourcesTest {
|
||||
@Rule
|
||||
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
|
||||
@Test
|
||||
public void theStructureModuleOwnsTheKindsAndTheirValidator() throws Exception {
|
||||
IrisData data = IrisData.openValidation(castlePack("owned").toFile());
|
||||
try {
|
||||
var catalog = data.getModules().pack().catalog();
|
||||
|
||||
assertEquals(List.of("iris:structure/piece", "iris:structure/pool", "iris:structure/structure"),
|
||||
catalog.resourceKinds().stream().map(registration -> registration.kind().id().toString()).toList());
|
||||
assertEquals(List.of("jigsaw-pieces", "jigsaw-pools", "structures"),
|
||||
catalog.resourceKinds().stream().map(ResourceKindRegistration::kind).map(kind -> kind.folder()).toList());
|
||||
assertTrue(catalog.validators().stream().map(ValidatorRegistration::validator).anyMatch(StructureValidator.class::isInstance));
|
||||
assertFalse(data.getLoaders().containsKey(IrisStructure.class));
|
||||
assertFalse(data.getLoaders().containsKey(IrisJigsawPool.class));
|
||||
assertFalse(data.getLoaders().containsKey(IrisJigsawPiece.class));
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structuresPoolsAndPiecesAreReadThroughPackResources() throws Exception {
|
||||
Path pack = castlePack("castles");
|
||||
IrisData data = IrisData.openValidation(pack.toFile());
|
||||
try {
|
||||
IrisStructure castle = StructureResources.structure(data, "castle");
|
||||
|
||||
assertEquals("castle/start", castle.getStartPool());
|
||||
assertEquals(5, castle.getMaxDepth());
|
||||
assertEquals("castle", castle.getLoadKey());
|
||||
assertEquals(pack.resolve("structures/castle.json").toFile(), castle.getLoadFile());
|
||||
assertSame(data, castle.getLoader());
|
||||
assertSame(castle, data.getPackResources().find(StructureResources.STRUCTURES.key(new ResourceId("castles", "castle"))).orElseThrow());
|
||||
assertEquals("castle/start", StructureResources.pool(data, "castle/start").getPieces().getFirst().getPiece());
|
||||
assertEquals("castle/start", StructureResources.piece(data, "castle/start").getObject());
|
||||
assertEquals(List.of("castle"), StructureResources.structureKeys(data));
|
||||
assertEquals(List.of("castle/start"), StructureResources.pieceKeys(data));
|
||||
assertNull(StructureResources.structure(data, "missing"));
|
||||
assertNull(StructureResources.structure(data, " "));
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aBrokenStructureIsAbsentToLookupsButAnErrorToPackResources() throws Exception {
|
||||
Path pack = castlePack("broken");
|
||||
write(pack, "structures/ruin.json", "{\"maxDepth\":");
|
||||
IrisData data = IrisData.openValidation(pack.toFile());
|
||||
try {
|
||||
assertNull(StructureResources.structure(data, "ruin"));
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> data.getPackResources().find(StructureResources.STRUCTURES.key(new ResourceId("broken", "ruin"))));
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rewrittenFilesAreReadAgainAfterInvalidationDumpAndHotload() throws Exception {
|
||||
Path pack = castlePack("reloaded");
|
||||
IrisData data = IrisData.openValidation(pack.toFile());
|
||||
try {
|
||||
assertEquals(5, StructureResources.structure(data, "castle").getMaxDepth());
|
||||
write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\",\"maxDepth\":9}");
|
||||
write(pack, "structures/tower.json", "{\"startPool\":\"castle/start\"}");
|
||||
assertEquals("a snapshot keeps what it read", 5, StructureResources.structure(data, "castle").getMaxDepth());
|
||||
|
||||
data.invalidateStructureResources();
|
||||
assertEquals(9, StructureResources.structure(data, "castle").getMaxDepth());
|
||||
assertEquals(List.of("castle", "tower"), StructureResources.structureKeys(data));
|
||||
|
||||
write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\",\"maxDepth\":3}");
|
||||
data.dump();
|
||||
assertEquals(3, StructureResources.structure(data, "castle").getMaxDepth());
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
|
||||
IrisData runtime = IrisData.openRuntime(pack.toFile());
|
||||
try {
|
||||
assertEquals(3, StructureResources.structure(runtime, "castle").getMaxDepth());
|
||||
write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\",\"maxDepth\":2}");
|
||||
runtime.hotloaded();
|
||||
assertEquals(2, StructureResources.structure(runtime, "castle").getMaxDepth());
|
||||
} finally {
|
||||
runtime.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void studioDescribesStructuresAsIrisDoesAndCompletesTheirPools() throws Exception {
|
||||
Path pack = castlePack("studio");
|
||||
IrisData data = IrisData.openValidation(pack.toFile());
|
||||
try (SchemaTestPlatform ignored = SchemaTestPlatform.bind(temporaryFolder.getRoot())) {
|
||||
List<JSONObject> entries = ModuleResourceSchemas.entries(data, true);
|
||||
|
||||
assertEquals(List.of("./.iris/schema/jigsaw-pieces-schema.json", "./.iris/schema/jigsaw-pools-schema.json",
|
||||
"./.iris/schema/structures-schema.json"), entries.stream().map(entry -> entry.getString("url")).toList());
|
||||
JSONObject structures = new JSONObject(Files.readString(pack.resolve(".iris/schema/structures-schema.json")));
|
||||
JSONObject startPool = structures.getJSONObject("properties").getJSONObject("startPool");
|
||||
assertEquals("#/definitions/erzjigsaw-pools", startPool.getString("$ref"));
|
||||
assertEquals("[\"castle/start\"]",
|
||||
structures.getJSONObject("definitions").getJSONObject("erzjigsaw-pools").getJSONArray("enum").toString());
|
||||
} finally {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void irisReservesTheFoldersItStillReadsItself() {
|
||||
var reserved = IrisModuleHost.get().reservedFolders();
|
||||
|
||||
assertTrue(reserved.containsAll(List.of("biomes", "regions", "dimensions", "objects", "snippet", "modules")));
|
||||
assertFalse(reserved.contains("structures"));
|
||||
assertFalse(reserved.contains("jigsaw-pools"));
|
||||
assertFalse(reserved.contains("jigsaw-pieces"));
|
||||
}
|
||||
|
||||
private Path castlePack(String name) throws Exception {
|
||||
File pack = temporaryFolder.newFolder(name);
|
||||
write(pack.toPath(), "dimensions/main.json", "{\"regions\":[\"region\"]}");
|
||||
write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[\"biome\"]}");
|
||||
write(pack.toPath(), "biomes/biome.json", "{\"name\":\"Biome\"}");
|
||||
write(pack.toPath(), "structures/castle.json", "{\"startPool\":\"castle/start\",\"maxDepth\":5}");
|
||||
write(pack.toPath(), "jigsaw-pools/castle/start.json", "{\"pieces\":[{\"piece\":\"castle/start\"}]}");
|
||||
write(pack.toPath(), "jigsaw-pieces/castle/start.json", "{\"object\":\"castle/start\",\"connectors\":[]}");
|
||||
return pack.toPath();
|
||||
}
|
||||
|
||||
private static void write(Path root, String relative, String content) throws Exception {
|
||||
Path path = root.resolve(relative);
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, content, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
+10
-12
@@ -1,5 +1,7 @@
|
||||
package art.arcane.iris.engine.platform.studio.generators;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFixture;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.ResourceLoader;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype;
|
||||
@@ -62,9 +64,8 @@ public class JigsawStudioGeneratorTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void connectorBlocksAreHiddenByDefaultAndCanBeShownPerWorkcell() {
|
||||
IrisData source = mock(IrisData.class);
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisObject> objectLoader = mock(ResourceLoader.class);
|
||||
when(source.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(source);
|
||||
when(source.getObjectLoader()).thenReturn(objectLoader);
|
||||
IrisJigsawConnector connector = new IrisJigsawConnector()
|
||||
.setPosition(new IrisPosition(1, 1, 1))
|
||||
@@ -82,7 +83,7 @@ public class JigsawStudioGeneratorTest {
|
||||
PlatformBlockState stone = mock(PlatformBlockState.class);
|
||||
IrisObject object = new IrisObject(3, 3, 3);
|
||||
object.setUnsigned(1, 1, 1, stone);
|
||||
when(pieceLoader.load("test/room", false)).thenReturn(piece);
|
||||
resources.resource(StructureResources.PIECES, "test/room", piece);
|
||||
when(objectLoader.load("test/room", false)).thenReturn(object);
|
||||
JigsawStudioVariant variant = new JigsawStudioVariant(
|
||||
"test/room",
|
||||
@@ -332,9 +333,8 @@ public class JigsawStudioGeneratorTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void rendersSourceVariantInCanonicalOrientationAndRotatesFinalState() {
|
||||
IrisData source = mock(IrisData.class);
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisObject> objectLoader = mock(ResourceLoader.class);
|
||||
when(source.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(source);
|
||||
when(source.getObjectLoader()).thenReturn(objectLoader);
|
||||
IrisJigsawConnector connector = new IrisJigsawConnector()
|
||||
.setPosition(new IrisPosition(2, 1, 1))
|
||||
@@ -357,7 +357,7 @@ public class JigsawStudioGeneratorTest {
|
||||
TileData sourceTile = new TileData("minecraft:chest", tileProperties);
|
||||
object.setUnsigned(0, 0, 0, sourceBlock);
|
||||
object.setUnsignedTile(0, 0, 0, sourceTile);
|
||||
when(pieceLoader.load("village/east", false)).thenReturn(piece);
|
||||
resources.resource(StructureResources.PIECES, "village/east", piece);
|
||||
when(objectLoader.load("village/east", false)).thenReturn(object);
|
||||
JigsawStudioVariant variant = planarVariant("village/east", JigsawPlanarTopology.EAST_END);
|
||||
GeneratorFixture fixture = fixture(
|
||||
@@ -385,9 +385,8 @@ public class JigsawStudioGeneratorTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void invalidRotatedFinalStateFailsRenderPrecisely() {
|
||||
IrisData source = mock(IrisData.class);
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisObject> objectLoader = mock(ResourceLoader.class);
|
||||
when(source.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(source);
|
||||
when(source.getObjectLoader()).thenReturn(objectLoader);
|
||||
IrisJigsawConnector connector = new IrisJigsawConnector()
|
||||
.setPosition(new IrisPosition(2, 1, 1))
|
||||
@@ -402,7 +401,7 @@ public class JigsawStudioGeneratorTest {
|
||||
.setObject("village/east")
|
||||
.setConnectors(new KList<>());
|
||||
piece.getConnectors().add(connector);
|
||||
when(pieceLoader.load("village/east", false)).thenReturn(piece);
|
||||
resources.resource(StructureResources.PIECES, "village/east", piece);
|
||||
when(objectLoader.load("village/east", false)).thenReturn(new IrisObject(3, 3, 3));
|
||||
JigsawStudioVariant variant = planarVariant("village/east", JigsawPlanarTopology.EAST_END);
|
||||
GeneratorFixture fixture = fixture(
|
||||
@@ -422,14 +421,13 @@ public class JigsawStudioGeneratorTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void renderCacheIncludesLoadGenerationAndSupportsExplicitInvalidation() {
|
||||
IrisData source = mock(IrisData.class);
|
||||
ResourceLoader<IrisJigsawPiece> pieceLoader = mock(ResourceLoader.class);
|
||||
ResourceLoader<IrisObject> objectLoader = mock(ResourceLoader.class);
|
||||
when(source.getJigsawPieceLoader()).thenReturn(pieceLoader);
|
||||
ModuleResourceFixture resources = ModuleResourceFixture.serve(source);
|
||||
when(source.getObjectLoader()).thenReturn(objectLoader);
|
||||
IrisJigsawPiece piece = new IrisJigsawPiece()
|
||||
.setObject("stronghold/hall")
|
||||
.setConnectors(new KList<>());
|
||||
when(pieceLoader.load("stronghold/hall", false)).thenReturn(piece);
|
||||
resources.resource(StructureResources.PIECES, "stronghold/hall", piece);
|
||||
when(objectLoader.load("stronghold/hall", false)).thenReturn(new IrisObject(3, 3, 3));
|
||||
JigsawStudioVariant variant = new JigsawStudioVariant(
|
||||
"stronghold/hall",
|
||||
|
||||
@@ -124,7 +124,13 @@ public class PackTypeBukkitPurityGateTest {
|
||||
"art.arcane.iris.engine.object.prefab.IrisObject",
|
||||
"art.arcane.iris.engine.object.image.IrisImage",
|
||||
"art.arcane.iris.engine.object.image.IrisImageMap",
|
||||
"art.arcane.iris.engine.object.prefab.matter.IrisMatterObject",
|
||||
"art.arcane.iris.engine.object.prefab.matter.IrisMatterObject");
|
||||
|
||||
/**
|
||||
* Iris's classes that built-in modules' resource kinds read from a pack with the same Gson, so they are roots
|
||||
* as much as the loaders' (see {@code StructureResources}).
|
||||
*/
|
||||
private static final List<String> MODULE_RESOURCE_ROOTS = List.of(
|
||||
"art.arcane.iris.engine.object.structure.IrisStructure",
|
||||
"art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool",
|
||||
"art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece");
|
||||
@@ -488,6 +494,7 @@ public class PackTypeBukkitPurityGateTest {
|
||||
/** The Gson roots, the extra pack-reachable types, and every {@code @Snippet} class. */
|
||||
private static List<String> gateTypes() throws Exception {
|
||||
Set<String> types = new LinkedHashSet<>(GSON_REGISTERED_ROOTS);
|
||||
types.addAll(MODULE_RESOURCE_ROOTS);
|
||||
types.addAll(ADDITIONAL_PACK_TYPES);
|
||||
types.addAll(snippetTypes());
|
||||
return new ArrayList<>(types);
|
||||
|
||||
+6
-4
@@ -1,5 +1,7 @@
|
||||
package art.arcane.iris.util.common.director.specialhandlers;
|
||||
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.modules.ModuleResourceFixture;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.IrisStructureLocator;
|
||||
@@ -102,8 +104,8 @@ public class StructureHandlerTest {
|
||||
custom.setLoadKey("iris:custom");
|
||||
IrisStructure collision = new IrisStructure();
|
||||
collision.setLoadKey("pack:collision");
|
||||
when(data.load(IrisStructure.class, "iris:custom_definition", false)).thenReturn(custom);
|
||||
when(data.load(IrisStructure.class, "iris:collision_definition", false)).thenReturn(collision);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:custom_definition", custom);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:collision_definition", collision);
|
||||
when(engine.getData()).thenReturn(data);
|
||||
when(engine.getDimension()).thenReturn(dimension);
|
||||
when(engine.getWorld()).thenReturn(world);
|
||||
@@ -173,8 +175,8 @@ public class StructureHandlerTest {
|
||||
placements.add(editablePlacement("iris:replacement_definition"));
|
||||
placements.add(nativePlacement("minecraft:explicit", StructureDistribution.RANDOM_SPREAD, 1.0));
|
||||
|
||||
when(data.load(IrisStructure.class, "iris:editable_definition", false)).thenReturn(editable);
|
||||
when(data.load(IrisStructure.class, "iris:replacement_definition", false)).thenReturn(replacement);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:editable_definition", editable);
|
||||
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:replacement_definition", replacement);
|
||||
when(engine.getData()).thenReturn(data);
|
||||
when(engine.getDimension()).thenReturn(dimension);
|
||||
when(engine.getWorld()).thenReturn(world);
|
||||
|
||||
Reference in new issue
Block a user