diff --git a/core/src/main/java/art/arcane/iris/builtin/package-info.java b/core/src/main/java/art/arcane/iris/builtin/package-info.java new file mode 100644 index 000000000..b42f61abb --- /dev/null +++ b/core/src/main/java/art/arcane/iris/builtin/package-info.java @@ -0,0 +1,30 @@ +/* + * 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 . + */ + +/** + * The public face of Iris's built-in modules: their stage constants and the settings and output types + * of those stages. {@link art.arcane.iris.core.modules.IrisModuleHost} exposes this package, with its + * subpackages, to pack modules, so a pack jar can {@code requires(...)} a built-in stage and read its + * output. Everything here is part of what packs compile against. + *

+ * Keep implementation out of it: stage bodies and anything that uses Iris internals live in the + * built-in module classes outside this package, which packs cannot see. One subpackage per built-in + * module, named after the module path, such as {@code art.arcane.iris.builtin.deposit} for + * {@code iris:deposit}. + */ +package art.arcane.iris.builtin; diff --git a/core/src/main/java/art/arcane/iris/core/loader/IrisData.java b/core/src/main/java/art/arcane/iris/core/loader/IrisData.java index 47bcd2db8..ea89e263b 100644 --- a/core/src/main/java/art/arcane/iris/core/loader/IrisData.java +++ b/core/src/main/java/art/arcane/iris/core/loader/IrisData.java @@ -31,6 +31,7 @@ import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.core.modules.PackModuleSet; import art.arcane.iris.core.pack.PackDirectoryResolver; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; @@ -106,6 +107,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { private final int id; private final boolean datapackCompiler; private volatile boolean closed = false; + private final PackModuleSet modules; private ResourceLoader biomeLoader; private ResourceLoader lootLoader; private ResourceLoader regionLoader; @@ -139,6 +141,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { private IrisData(File dataFolder, boolean datapackCompiler) { this.dataFolder = dataFolder; + this.modules = new PackModuleSet(dataFolder); this.id = RNG.r.imax(); this.datapackCompiler = datapackCompiler; if (datapackCompiler) { @@ -418,6 +421,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { public void close() { closed = true; dump(); + modules.close(); synchronized (engines) { engines.clear(); } diff --git a/core/src/main/java/art/arcane/iris/core/loader/IrisRegistrant.java b/core/src/main/java/art/arcane/iris/core/loader/IrisRegistrant.java index 35aac5081..782818ba2 100644 --- a/core/src/main/java/art/arcane/iris/core/loader/IrisRegistrant.java +++ b/core/src/main/java/art/arcane/iris/core/loader/IrisRegistrant.java @@ -19,6 +19,7 @@ package art.arcane.iris.core.loader; import com.google.gson.GsonBuilder; +import art.arcane.iris.core.modules.ModuleSettings; import art.arcane.iris.spi.IrisLogging; import lombok.Data; import lombok.EqualsAndHashCode; @@ -34,6 +35,7 @@ public abstract class IrisRegistrant { private transient String loadKey; private transient File loadFile; + private transient ModuleSettings moduleSettings = ModuleSettings.NONE; public abstract String getFolderName(); diff --git a/core/src/main/java/art/arcane/iris/core/loader/JsonFieldNames.java b/core/src/main/java/art/arcane/iris/core/loader/JsonFieldNames.java new file mode 100644 index 000000000..17f825649 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/loader/JsonFieldNames.java @@ -0,0 +1,70 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.loader; + +import com.google.gson.annotations.SerializedName; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The JSON keys Gson reads for a class: every non-static, non-transient field, inherited ones included, + * under its {@link SerializedName} and alternates when it has one. + */ +public final class JsonFieldNames { + private static final ConcurrentHashMap, Set> CACHE = new ConcurrentHashMap<>(); + + private JsonFieldNames() { + } + + public static Set of(Class type) { + return CACHE.computeIfAbsent(type, JsonFieldNames::collect); + } + + private static Set collect(Class type) { + Set names = new LinkedHashSet<>(); + for (Class current = type; current != null && current != Object.class; current = current.getSuperclass()) { + for (Field field : current.getDeclaredFields()) { + if (isSerialized(field)) { + addNames(field, names); + } + } + } + return Collections.unmodifiableSet(names); + } + + private static boolean isSerialized(Field field) { + int modifiers = field.getModifiers(); + return !Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && !field.isSynthetic(); + } + + private static void addNames(Field field, Set names) { + SerializedName serialized = field.getAnnotation(SerializedName.class); + if (serialized == null) { + names.add(field.getName()); + return; + } + names.add(serialized.value()); + Collections.addAll(names, serialized.alternate()); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/loader/JsonSchemaValidator.java b/core/src/main/java/art/arcane/iris/core/loader/JsonSchemaValidator.java index 8857a35fa..ea92e2734 100644 --- a/core/src/main/java/art/arcane/iris/core/loader/JsonSchemaValidator.java +++ b/core/src/main/java/art/arcane/iris/core/loader/JsonSchemaValidator.java @@ -3,38 +3,46 @@ package art.arcane.iris.core.loader; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.format.C; import art.arcane.volmlib.util.json.JSONObject; -import com.google.gson.annotations.SerializedName; import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; final class JsonSchemaValidator { - private static final ConcurrentHashMap, Set> FIELD_CACHE = new ConcurrentHashMap<>(); private static final int SUGGESTION_MAX_DISTANCE = 4; private JsonSchemaValidator() { } - static void validateTopLevelKeys(JSONObject parsed, String rawText, File file, String resourceTypeName, Class objectClass) { + /** + * 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, + Set moduleKeys) { if (parsed == null || objectClass == null) { return; } - Set known = FIELD_CACHE.computeIfAbsent(objectClass, JsonSchemaValidator::collectFieldNames); + Set fields = JsonFieldNames.of(objectClass); for (String key : parsed.keySet()) { - if (known.contains(key)) { + if (fields.contains(key) || moduleKeys.contains(key)) { continue; } - reportUnknownKey(key, rawText, file, resourceTypeName, known); + reportUnknownKey(key, rawText, file, resourceTypeName, union(fields, moduleKeys)); } } + private static Set union(Set fields, Set moduleKeys) { + if (moduleKeys.isEmpty()) { + return fields; + } + Set known = new LinkedHashSet<>(fields); + known.addAll(moduleKeys); + return known; + } + static void reportLoadFailure(File file, String rawText, String resourceTypeName, Throwable error) { String message = error.getMessage(); if (message == null || message.isBlank()) { @@ -77,31 +85,6 @@ final class JsonSchemaValidator { IrisLogging.warn(out.toString()); } - private static Set collectFieldNames(Class cls) { - Set names = new LinkedHashSet<>(); - Class c = cls; - while (c != null && c != Object.class) { - for (Field field : c.getDeclaredFields()) { - int mods = field.getModifiers(); - if (Modifier.isStatic(mods) || Modifier.isTransient(mods)) { - continue; - } - if (field.isSynthetic()) { - continue; - } - SerializedName serialized = field.getAnnotation(SerializedName.class); - if (serialized != null) { - names.add(serialized.value()); - Collections.addAll(names, serialized.alternate()); - } else { - names.add(field.getName()); - } - } - c = c.getSuperclass(); - } - return Collections.unmodifiableSet(names); - } - private static int findLineForKey(String rawText, String key) { if (rawText == null || key == null) { return -1; diff --git a/core/src/main/java/art/arcane/iris/core/loader/ResourceLoader.java b/core/src/main/java/art/arcane/iris/core/loader/ResourceLoader.java index 7bc7248a6..6a3a21e18 100644 --- a/core/src/main/java/art/arcane/iris/core/loader/ResourceLoader.java +++ b/core/src/main/java/art/arcane/iris/core/loader/ResourceLoader.java @@ -37,6 +37,9 @@ import art.arcane.volmlib.util.io.CustomOutputStream; import art.arcane.volmlib.util.io.IO; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; +import art.arcane.iris.core.modules.ModuleSettings; +import art.arcane.iris.core.modules.ModuleTargets; +import com.volmit.FeatureAttachment.Target; import art.arcane.iris.util.common.parallel.BurstExecutor; import art.arcane.iris.util.common.parallel.MultiBurst; import art.arcane.volmlib.util.scheduling.ChronoLatch; @@ -64,6 +67,7 @@ import java.util.HashSet; import java.util.HexFormat; import java.util.Locale; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; @@ -414,9 +418,11 @@ public class ResourceLoader implements MeteredCache { PrecisionStopwatch p = PrecisionStopwatch.start(); rawText = IO.readAll(j); JSONObject parsed = new JSONObject(rawText); - JsonSchemaValidator.validateTopLevelKeys(parsed, rawText, j, resourceTypeName, objectClass); + Optional moduleTarget = ModuleTargets.ofResource(objectClass); + JsonSchemaValidator.validateTopLevelKeys(parsed, rawText, j, resourceTypeName, objectClass, moduleKeys(moduleTarget)); T t = getManager().getGson() .fromJson(preprocess(parsed).toString(0), objectClass); + moduleTarget.ifPresent(target -> t.setModuleSettings(decodeModuleSettings(target, parsed, name))); t.setLoadKey(name); t.setLoadFile(j); t.setLoader(manager); @@ -431,6 +437,15 @@ public class ResourceLoader implements MeteredCache { } } + /** The ids and aliases the pack's modules read at {@code target}; none for resources that hold no module settings. */ + private Set moduleKeys(Optional target) { + return target.map(found -> getManager().getModules().settings().keys(found)).orElse(Set.of()); + } + + private ModuleSettings decodeModuleSettings(Target target, JSONObject json, String name) { + return getManager().getModules().settings().decode(target, json, resourceTypeName + " " + name); + } + protected JSONObject preprocess(JSONObject j) { return j; } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisApiLogger.java b/core/src/main/java/art/arcane/iris/core/modules/IrisApiLogger.java new file mode 100644 index 000000000..099c4248b --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisApiLogger.java @@ -0,0 +1,70 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.spi.IrisLogging; + +import java.text.MessageFormat; +import java.util.ResourceBundle; + +/** + * Writes IrisApi's pack load log, the module summary and the missing-classes warning, to Iris's log. + * Passed to the module host rather than installed as a {@link System.LoggerFinder}, which the JDK only + * looks up on the system class loader, where a plugin's classes are not. + */ +final class IrisApiLogger implements System.Logger { + private final String name; + + IrisApiLogger(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isLoggable(Level level) { + return level != Level.OFF; + } + + @Override + public void log(Level level, ResourceBundle bundle, String message, Throwable thrown) { + if (thrown != null) { + IrisLogging.reportError(message, thrown); + return; + } + emit(level, message); + } + + @Override + public void log(Level level, ResourceBundle bundle, String format, Object... parameters) { + emit(level, parameters == null || parameters.length == 0 ? format : MessageFormat.format(format, parameters)); + } + + private static void emit(Level level, String message) { + switch (level) { + case ERROR -> IrisLogging.error(message); + case WARNING -> IrisLogging.warn(message); + case INFO -> IrisLogging.info(message); + default -> IrisLogging.debug(message); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java new file mode 100644 index 000000000..0eefdfc97 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.spi.IrisPlatforms; +import com.volmit.IrisModule; +import com.volmit.host.ModuleHost; +import com.volmit.host.PackModules; + +import java.nio.file.Path; +import java.util.List; + +/** + * 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, 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. */ + public static final String BUILT_IN_API_PACKAGE = "art.arcane.iris.builtin"; + static final String RESERVED_NAMESPACE = "iris"; + private static final String[] JAR_COPY_FOLDER = {"cache", "module-jars"}; + private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir"; + private static final List BUILT_IN_MODULES = List.of(); + + private IrisModuleHost() { + } + + public static ModuleHost get() { + return Holder.HOST; + } + + private static ModuleHost build() { + return ModuleHost.of(BUILT_IN_MODULES) + .exposing(BUILT_IN_API_PACKAGE) + .reservingNamespaces(RESERVED_NAMESPACE) + .reservingFields(ModuleTargets.reservedFields()) + .copyingJarsTo(jarCopyRoot()) + .loggingTo(new IrisApiLogger(PackModules.class.getName())); + } + + /** Under the plugin's cache folder when a platform is bound; tests and the standalone probe use the JDK's temporary directory. */ + private static Path jarCopyRoot() { + if (!IrisPlatforms.isBound()) { + return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY)); + } + return IrisPlatforms.get().dataFolderNoCreate(JAR_COPY_FOLDER).toPath(); + } + + private static final class Holder { + private static final ModuleHost HOST = build(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java new file mode 100644 index 000000000..3e1477f1d --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java @@ -0,0 +1,73 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import com.volmit.IrisFeature; +import com.volmit.host.ConfiguredSettings; + +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; + +/** + * Module settings one dimension, region or biome declares, at most one value per settings type. + */ +public final class ModuleSettings { + public static final ModuleSettings NONE = new ModuleSettings(Map.of()); + + private final Map, IrisFeature> values; + + private ModuleSettings(Map, IrisFeature> values) { + this.values = Map.copyOf(values); + } + + static ModuleSettings of(Map, IrisFeature> values) { + return values.isEmpty() ? NONE : new ModuleSettings(values); + } + + public Optional find(Class type) { + return Optional.ofNullable(type.cast(values.get(type))); + } + + public Collection values() { + return values.values(); + } + + public boolean isEmpty() { + return values.isEmpty(); + } + + /** These settings, each type that {@code moreSpecific} also declares taking its value instead. */ + public ModuleSettings overriddenBy(ModuleSettings moreSpecific) { + if (moreSpecific.isEmpty()) { + return this; + } + if (isEmpty()) { + return moreSpecific; + } + Map, IrisFeature> merged = new LinkedHashMap<>(values); + merged.putAll(moreSpecific.values); + return new ModuleSettings(merged); + } + + public ConfiguredSettings configured() { + return isEmpty() ? ConfiguredSettings.none() : ConfiguredSettings.of(values.values().toArray(IrisFeature[]::new)); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java new file mode 100644 index 000000000..17bc64aee --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java @@ -0,0 +1,200 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.volmlib.util.json.JSONObject; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.block.BlockState; +import com.volmit.config.Snippet; +import com.volmit.host.FeatureCatalog; +import com.volmit.host.FeatureDescriptor; +import com.volmit.host.ObjectRegistration; +import com.volmit.resource.ResourceId; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.EnumMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Function; +import java.util.stream.Stream; + +/** + * Reads the module settings a dimension, region or biome declares: each settings feature of the pack at + * that target, under its id or, for built-ins, its alias. Settings are created with their no-argument + * constructor and the JSON is read into them, so an omitted option keeps its default. A {@link Snippet} + * type may be written as {@code "snippet/"}, read from {@code snippet//.json}. + */ +public final class ModuleSettingsDecoder { + private static final String SNIPPET_PREFIX = "snippet/"; + private static final String SNIPPET_FOLDER = "snippet"; + private static final String JSON_EXTENSION = ".json"; + + private final Map>> settings = new EnumMap<>(Target.class); + private final Map> keys = new EnumMap<>(Target.class); + private final Path packFolder; + private final Gson gson; + + ModuleSettingsDecoder(FeatureCatalog catalog, Path packFolder) { + this.packFolder = packFolder; + this.gson = new GsonBuilder() + .registerTypeAdapter(BlockState.class, textAdapter(BlockState::parse, BlockState::key)) + .registerTypeAdapter(ResourceId.class, textAdapter(ResourceId::parse, ResourceId::toString)) + .registerTypeAdapterFactory(new SnippetReferences()) + .create(); + for (Target target : Target.values()) { + settings.put(target, settingsAt(catalog, target)); + keys.put(target, keysAt(catalog, target)); + } + } + + /** Every JSON key the pack's modules read at {@code target}: feature ids and built-in aliases, object generators' included. */ + public Set keys(Target target) { + return keys.get(target); + } + + /** + * Decodes the settings {@code json} declares for {@code target}. + * + * @param resource names the file in errors, such as {@code biome desert/dunes} + * @throws IllegalArgumentException when the JSON holds both a feature's alias and its id, or a value + * that does not decode into the settings type + */ + public ModuleSettings decode(Target target, JSONObject json, String resource) { + Map, IrisFeature> values = new LinkedHashMap<>(); + for (FeatureDescriptor feature : settings.get(target)) { + presentKey(feature, json, resource).ifPresent(key -> values.put(feature.type(), read(feature, json.get(key), key, resource))); + } + return ModuleSettings.of(values); + } + + private static Optional presentKey(FeatureDescriptor feature, JSONObject json, String resource) { + boolean hasKey = json.has(feature.key()); + Optional alias = feature.alias().filter(json::has); + if (hasKey && alias.isPresent()) { + throw new IllegalArgumentException(resource + " sets both \"" + alias.get() + "\" and \"" + feature.key() + + "\", the alias and the id of settings " + feature.id() + "; keep one"); + } + return hasKey ? Optional.of(feature.key()) : alias; + } + + private IrisFeature read(FeatureDescriptor feature, Object value, String key, String resource) { + try { + IrisFeature decoded = gson.fromJson(JSONObject.valueToString(value), feature.type()); + if (decoded == null) { + throw new JsonParseException("the value is null"); + } + return decoded; + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Cannot read settings " + feature.id() + " under \"" + key + "\" in " + + resource + ": " + failure.getMessage(), failure); + } + } + + private static List> settingsAt(FeatureCatalog catalog, Target target) { + return catalog.settings().stream() + .filter(feature -> feature.attachment().targets().contains(target)) + .toList(); + } + + private static Set keysAt(FeatureCatalog catalog, Target target) { + Stream> objects = catalog.objects().stream().map(ObjectRegistration::descriptor); + Set found = new TreeSet<>(); + Stream.concat(catalog.settings().stream(), objects) + .filter(feature -> feature.attachment().targets().contains(target)) + .forEach(feature -> { + found.add(feature.key()); + feature.alias().ifPresent(found::add); + }); + return Set.copyOf(found); + } + + private static TypeAdapter textAdapter(Function parse, Function write) { + return new TypeAdapter() { + @Override + public void write(JsonWriter out, T value) throws IOException { + out.value(write.apply(value)); + } + + @Override + public T read(JsonReader in) throws IOException { + return parse.apply(in.nextString()); + } + }.nullSafe(); + } + + /** Lets a {@link Snippet} type be written as a reference to a snippet file. */ + private final class SnippetReferences implements TypeAdapterFactory { + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + Snippet snippet = type.getRawType().getAnnotation(Snippet.class); + if (snippet == null) { + return null; + } + TypeAdapter delegate = gson.getDelegateAdapter(this, type); + return new TypeAdapter() { + @Override + public void write(JsonWriter out, T value) throws IOException { + delegate.write(out, value); + } + + @Override + public T read(JsonReader in) throws IOException { + if (in.peek() != JsonToken.STRING) { + return delegate.read(in); + } + return delegate.fromJson(readSnippet(snippet.value(), in.nextString())); + } + }; + } + } + + private String readSnippet(String snippetFolder, String reference) { + if (!reference.startsWith(SNIPPET_PREFIX)) { + throw new JsonParseException("\"" + reference + "\" is neither an object nor a snippet reference; write the object," + + " or snippet/ for the file " + SNIPPET_FOLDER + "/" + snippetFolder + "/" + JSON_EXTENSION); + } + Path folder = packFolder.resolve(SNIPPET_FOLDER).resolve(snippetFolder).normalize(); + Path file = folder.resolve(reference.substring(SNIPPET_PREFIX.length()) + JSON_EXTENSION).normalize(); + if (!file.startsWith(folder) || !Files.isRegularFile(file)) { + throw new JsonParseException("Snippet " + reference + " has no file " + packFolder.relativize(file)); + } + try { + return Files.readString(file); + } catch (IOException failure) { + throw new UncheckedIOException("Cannot read snippet " + packFolder.relativize(file), failure); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleTargets.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleTargets.java new file mode 100644 index 000000000..ba0dfdc49 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleTargets.java @@ -0,0 +1,60 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.core.loader.JsonFieldNames; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import com.volmit.FeatureAttachment.Target; + +import java.util.EnumMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Which Iris class holds the JSON of each attachment target that module settings can appear in. + */ +public final class ModuleTargets { + private static final Map> HOLDERS = Map.of( + Target.DIMENSION, IrisDimension.class, + Target.REGION, IrisRegion.class, + Target.BIOME, IrisBiome.class, + Target.OBJECT_PLACEMENT, IrisObjectPlacement.class); + + private ModuleTargets() { + } + + /** The target whose JSON a resource of {@code resourceType} is, if module settings can appear in it. */ + public static Optional ofResource(Class resourceType) { + return HOLDERS.entrySet().stream() + .filter(entry -> entry.getValue() == resourceType) + .map(Map.Entry::getKey) + .findFirst(); + } + + /** Iris's own JSON fields per target, which no built-in alias may take. */ + static Map> reservedFields() { + Map> fields = new EnumMap<>(Target.class); + HOLDERS.forEach((target, holder) -> fields.put(target, JsonFieldNames.of(holder))); + return fields; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/PackModuleSet.java b/core/src/main/java/art/arcane/iris/core/modules/PackModuleSet.java new file mode 100644 index 000000000..37b2faff6 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/PackModuleSet.java @@ -0,0 +1,88 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.spi.IrisLogging; +import com.volmit.host.LoadedPack; + +import java.io.File; + +/** + * The modules of one pack folder, loaded with {@link IrisModuleHost} the first time something needs + * them and closed with the pack data that owns them. A failed load is reported once and remembered, so + * every later use fails with the same error instead of loading the jars again. + */ +public final class PackModuleSet implements AutoCloseable { + private enum State { NOT_LOADED, LOADED, FAILED, CLOSED } + + private final File packFolder; + private State state = State.NOT_LOADED; + private LoadedPack pack; + private ModuleSettingsDecoder settings; + private PackModulesException failure; + + public PackModuleSet(File packFolder) { + this.packFolder = packFolder; + } + + /** The loaded pack, its built-in modules included. */ + public synchronized LoadedPack pack() { + requireLoaded(); + return pack; + } + + public synchronized ModuleSettingsDecoder settings() { + requireLoaded(); + return settings; + } + + @Override + public synchronized void close() { + if (state == State.LOADED) { + pack.close(); + } + pack = null; + settings = null; + state = State.CLOSED; + } + + private void requireLoaded() { + switch (state) { + case NOT_LOADED -> load(); + case FAILED -> throw failure; + case CLOSED -> throw new IllegalStateException("The modules of pack " + packFolder.getName() + " are closed"); + case LOADED -> { + } + } + } + + private void load() { + try { + LoadedPack loaded = LoadedPack.load(packFolder.toPath(), IrisModuleHost.get()); + pack = loaded; + settings = new ModuleSettingsDecoder(loaded.catalog(), packFolder.toPath()); + state = State.LOADED; + } catch (RuntimeException loadFailure) { + failure = new PackModulesException(packFolder, loadFailure); + state = State.FAILED; + IrisLogging.error(failure.getMessage()); + throw failure; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/PackModulesException.java b/core/src/main/java/art/arcane/iris/core/modules/PackModulesException.java new file mode 100644 index 000000000..5356538a3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/PackModulesException.java @@ -0,0 +1,28 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import java.io.File; + +/** A pack whose modules failed to load. The message names the pack and carries IrisApi's load error. */ +public final class PackModulesException extends RuntimeException { + public PackModulesException(File packFolder, RuntimeException cause) { + super("Pack " + packFolder.getName() + " cannot load its modules: " + cause.getMessage(), cause); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleSettingsDecoderTest.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleSettingsDecoderTest.java new file mode 100644 index 000000000..f8484f004 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleSettingsDecoderTest.java @@ -0,0 +1,164 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.volmlib.util.json.JSONObject; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; +import com.volmit.config.Feature; +import com.volmit.config.Snippet; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleHost; +import com.volmit.resource.ResourceId; +import com.volmit.stage.Stage; +import com.volmit.stage.StageGraph; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class ModuleSettingsDecoderTest { + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private Path packFolder; + private LoadedPack pack; + private ModuleSettingsDecoder decoder; + + @Feature(id = "iris:moss", name = "Moss", alias = "moss", targets = {Target.BIOME, Target.REGION}) + public static final class MossSettings implements IrisFeature { + private int radius = 3; + private BlockState block = new BlockState("minecraft:moss_block"); + private ResourceId palette = ResourceId.parse("iris:moss/default"); + private Patch patch = new Patch(); + } + + @Snippet("moss-patch") + public static final class Patch { + private int size = 1; + } + + public static final class MossModule implements IrisModule { + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:moss", "Moss", "1"); + } + + @Override + public void install(StageGraph graph) { + graph.define(Stage.chunk("iris:moss/spread")).when(MossSettings.class).run((context, moss) -> { + }); + } + } + + @Before + public void loadPack() throws IOException { + packFolder = folder.newFolder("pack").toPath(); + pack = LoadedPack.load(packFolder, ModuleHost.of(List.of(new MossModule())).copyingJarsTo(folder.newFolder("copies").toPath())); + decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder); + } + + @After + public void closePack() { + pack.close(); + } + + private MossSettings moss(String json) { + return decoder.decode(Target.BIOME, new JSONObject(json), "biome desert/dunes").find(MossSettings.class).orElseThrow(); + } + + @Test + public void readsSettingsUnderTheirIdOrBuiltInAliasKeepingOmittedDefaults() { + MossSettings byId = moss("{\"iris:moss\": {\"radius\": 7, \"block\": \"minecraft:oak_log[axis=y]\"}}"); + MossSettings byAlias = moss("{\"moss\": {\"palette\": \"iris:moss/wet\"}}"); + + assertEquals(7, byId.radius); + assertEquals(BlockState.parse("minecraft:oak_log[axis=y]"), byId.block); + assertEquals(ResourceId.parse("iris:moss/default"), byId.palette); + assertEquals(3, byAlias.radius); + assertEquals(ResourceId.parse("iris:moss/wet"), byAlias.palette); + assertEquals(1, byAlias.patch.size); + } + + @Test + public void declaresNothingWhereNoKeyIsPresent() { + assertSame(ModuleSettings.NONE, decoder.decode(Target.BIOME, new JSONObject("{\"name\": \"Dunes\"}"), "biome desert/dunes")); + assertSame(ModuleSettings.NONE, decoder.decode(Target.DIMENSION, new JSONObject("{\"moss\": {}}"), "dimension overworld")); + } + + @Test + public void bothTheAliasAndTheIdInOneObjectFail() { + IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, + () -> moss("{\"moss\": {}, \"iris:moss\": {}}")); + + assertEquals("biome desert/dunes sets both \"moss\" and \"iris:moss\", the alias and the id of settings iris:moss; keep one", + failure.getMessage()); + } + + @Test + public void snippetTypesReadSnippetFilesFromTheirFolder() throws IOException { + Path snippets = Files.createDirectories(packFolder.resolve("snippet/moss-patch")); + Files.writeString(snippets.resolve("wide.json"), "{\"size\": 9}"); + + assertEquals(9, moss("{\"moss\": {\"patch\": \"snippet/wide\"}}").patch.size); + + IllegalArgumentException missing = assertThrows(IllegalArgumentException.class, + () -> moss("{\"moss\": {\"patch\": \"snippet/narrow\"}}")); + assertTrue(missing.getMessage(), missing.getMessage().contains("Snippet snippet/narrow has no file snippet/moss-patch/narrow.json")); + } + + @Test + public void badValuesNameTheSettingsKeyAndResource() { + IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, + () -> moss("{\"moss\": {\"block\": \"stone\"}}")); + + assertTrue(failure.getMessage(), failure.getMessage().startsWith("Cannot read settings iris:moss under \"moss\" in biome desert/dunes: ")); + } + + @Test + public void listsTheKeysModulesReadPerTarget() { + assertEquals(Set.of("iris:moss", "moss"), decoder.keys(Target.BIOME)); + assertEquals(Set.of(), decoder.keys(Target.DIMENSION)); + } + + @Test + public void moreSpecificSettingsReplaceLessSpecificOnesOfTheSameType() { + ModuleSettings region = decoder.decode(Target.REGION, new JSONObject("{\"moss\": {\"radius\": 2}}"), "region hot"); + ModuleSettings biome = decoder.decode(Target.BIOME, new JSONObject("{\"moss\": {\"radius\": 5}}"), "biome desert/dunes"); + + assertEquals(5, region.overriddenBy(biome).find(MossSettings.class).orElseThrow().radius); + assertEquals(2, region.overriddenBy(ModuleSettings.NONE).find(MossSettings.class).orElseThrow().radius); + assertEquals(5, ModuleSettings.NONE.overriddenBy(biome).find(MossSettings.class).orElseThrow().radius); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/PackModuleSetTest.java b/core/src/test/java/art/arcane/iris/core/modules/PackModuleSetTest.java new file mode 100644 index 000000000..8d9be5ed8 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/PackModuleSetTest.java @@ -0,0 +1,62 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class PackModuleSetTest { + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + @Test + public void loadsOnFirstUseAndClosesWithItsOwner() throws IOException { + PackModuleSet modules = new PackModuleSet(folder.newFolder("plain")); + + assertSame(modules.pack(), modules.pack()); + assertTrue(modules.pack().packModules().isEmpty()); + + modules.close(); + assertThrows(IllegalStateException.class, modules::pack); + } + + @Test + public void aFailedLoadIsRememberedWithThePackNamed() throws IOException { + File pack = folder.newFolder("broken"); + Files.writeString(Files.createDirectories(pack.toPath().resolve("modules")).resolve("empty.jar"), "not a jar"); + PackModuleSet modules = new PackModuleSet(pack); + + PackModulesException first = assertThrows(PackModulesException.class, modules::pack); + PackModulesException second = assertThrows(PackModulesException.class, modules::settings); + + assertSame(first, second); + assertTrue(first.getMessage(), first.getMessage().startsWith("Pack broken cannot load its modules: ")); + modules.close(); + } +}