Enforce declared bounds and make importedStructures a typed check

The settings decoder now enforces @MinNumber/@MaxNumber on every option
a pack writes, nested ones included, naming the full path. Module
resource files get the same check. Pack validation reports every
dimension, region and biome whose settings fail to decode as a blocking
error; before, the failure only logged and the pack passed.

With that in place, batch 9 S15 replaces 120 lines of hand-written JSON
checks of importedStructures with a typed check beside StructureValidator
for what types cannot say: blank keys and a structure set without a
namespace. @MinItems stays unenforced for now (OPEN_QUESTIONS 57).
This commit is contained in:
piexel committed 2026-11-06 07:53:57 +01:00
1 parent d1a9c2c68b
commit 1bcd846fb5
11 files changed
+404 -303

No files matched your search

@@ -45,8 +45,10 @@ import art.arcane.iris.util.common.parallel.MultiBurst;
import art.arcane.volmlib.util.scheduling.ChronoLatch;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import java.io.DataInputStream;
@@ -66,6 +68,7 @@ import java.util.Comparator;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -108,6 +111,8 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
protected ChronoLatch sec;
private volatile boolean firstAccessOverflowed;
private final Options options;
@Getter(AccessLevel.NONE)
private final Map<String, LoadFailure> loadFailures = new ConcurrentHashMap<>();
public ResourceLoader(
File root,
@@ -414,10 +419,12 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
protected T loadFile(File j, String name) {
String rawText = null;
boolean readAsJson = false;
try {
PrecisionStopwatch p = PrecisionStopwatch.start();
rawText = IO.readAll(j);
JSONObject parsed = new JSONObject(rawText);
readAsJson = true;
Optional<Level> moduleTarget = ModuleTargets.ofResource(objectClass);
JsonSchemaValidator.validateTopLevelKeys(parsed, rawText, j, resourceTypeName, objectClass, moduleKeys(moduleTarget));
T t = getManager().getGson()
@@ -429,14 +436,30 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
getManager().preprocessObject(t);
logLoad(j, t);
tlt.addAndGet(p.getMilliseconds());
loadFailures.remove(name);
return t;
} catch (Throwable e) {
IrisLogging.reportError(e);
failLoad(j, rawText, e);
loadFailures.put(name, new LoadFailure(rawText != null && !readAsJson, failureMessage(e)));
return null;
}
}
/** Why a file failed to load: it is not JSON, or its JSON does not read into the resource. */
public record LoadFailure(boolean invalidJson, String message) {
}
/** The failure of each key whose file failed its last load; a key that loads again leaves it. */
public Map<String, LoadFailure> loadFailures() {
return Map.copyOf(loadFailures);
}
private static String failureMessage(Throwable failure) {
String message = failure.getMessage();
return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message;
}
/** The keys the pack's modules read at {@code target}; none for resources that hold no module settings. */
private Set<String> moduleKeys(Optional<Level> target) {
return target.map(found -> getManager().getModules().settings().keys(found)).orElse(Set.of());
@@ -0,0 +1,158 @@
/*
* 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.modules;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.SerializedName;
import com.volmit.config.JsonForms;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* The bounds IrisApi's {@link MinNumber} and {@link MaxNumber} declare, enforced on decoded settings. Only options the
* JSON writes are checked: a default is the module's own choice.
* <p>
* {@code @MinItems} is not enforced yet: most options carrying {@code @MinItems(1)} default to an empty list, and
* packs write {@code []} for them (OPEN_QUESTIONS 57).
*/
final class DeclaredBounds {
private static final List<String> LIBRARY_PACKAGES = List.of("java.", "javax.", "com.google.gson.");
private DeclaredBounds() {
}
/**
* Checks every option of {@code decoded} that {@code written} holds, and the options of the settings objects
* below it, naming each as {@code path.option}, or {@code option} for an empty path.
*
* @throws JsonParseException naming the first option out of its bounds
*/
static void require(Object decoded, JsonObject written, String path) {
for (Class<?> type = decoded.getClass(); readsFields(type); type = type.getSuperclass()) {
for (Field field : type.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
continue;
}
JsonElement member = written.get(memberName(field));
if (member != null) {
requireOption(decoded, field, member, path.isEmpty() ? memberName(field) : path + "." + memberName(field));
}
}
}
}
/**
* Checks the option {@code field} of {@code owner}, written as {@code written} and named {@code path}, such as the
* root option of a rooted feature, which the pack writes as the whole value under the feature's key.
*/
static void requireOption(Object owner, Field field, JsonElement written, String path) {
Object value = valueOf(field, owner);
requireWithinBounds(field, value, path);
requireNested(value, written, path);
}
private static void requireWithinBounds(Field field, Object value, String path) {
MinNumber minimum = field.getAnnotation(MinNumber.class);
if (minimum != null && value instanceof Number number && number.doubleValue() < minimum.value()) {
throw new JsonParseException(path + " is " + number + "; it must be at least " + label(minimum.value()));
}
MaxNumber maximum = field.getAnnotation(MaxNumber.class);
if (maximum != null && value instanceof Number number && number.doubleValue() > maximum.value()) {
throw new JsonParseException(path + " is " + number + "; it must be at most " + label(maximum.value()));
}
}
private static void requireNested(Object value, JsonElement written, String path) {
if (value == null) {
return;
}
if (written.isJsonArray()) {
requireItems(value, written.getAsJsonArray(), path);
return;
}
if (written.isJsonObject() && readsFields(value.getClass())) {
require(value, written.getAsJsonObject(), path);
}
}
private static void requireItems(Object value, JsonArray written, String path) {
List<?> items = itemsOf(value);
for (int index = 0; index < Math.min(items.size(), written.size()); index++) {
Object item = items.get(index);
JsonElement writtenItem = written.get(index);
if (item != null && writtenItem.isJsonObject() && readsFields(item.getClass())) {
require(item, writtenItem.getAsJsonObject(), path + "[" + index + "]");
}
}
}
private static boolean readsFields(Class<?> type) {
if (type == null || type == Object.class || type.isPrimitive() || type.isArray() || type.isEnum()
|| type.isInterface() || type.isAnnotationPresent(JsonForms.class)) {
return false;
}
String name = type.getName();
return LIBRARY_PACKAGES.stream().noneMatch(name::startsWith);
}
private static String memberName(Field field) {
SerializedName serializedName = field.getAnnotation(SerializedName.class);
return serializedName == null ? field.getName() : serializedName.value();
}
private static Object valueOf(Field field, Object owner) {
try {
field.setAccessible(true);
return field.get(owner);
} catch (ReflectiveOperationException | RuntimeException unreadable) {
return null;
}
}
private static List<?> itemsOf(Object value) {
if (value instanceof List<?> list) {
return list;
}
if (value instanceof Collection<?> collection) {
return new ArrayList<>(collection);
}
if (!value.getClass().isArray()) {
return List.of();
}
List<Object> items = new ArrayList<>();
for (int index = 0; index < Array.getLength(value); index++) {
items.add(Array.get(value, index));
}
return items;
}
private static String label(double bound) {
return bound == Math.rint(bound) && Math.abs(bound) < 1e15 ? Long.toString((long) bound) : Double.toString(bound);
}
}
@@ -24,7 +24,9 @@ import art.arcane.volmlib.util.json.JSONTokener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
@@ -148,6 +150,10 @@ public final class ModuleSettingsDecoder {
if (decoded == null) {
throw new JsonParseException("the file holds null");
}
JsonElement written = JsonParser.parseString(json);
if (written.isJsonObject()) {
DeclaredBounds.require(decoded, written.getAsJsonObject(), "");
}
return decoded;
}
@@ -172,10 +178,12 @@ public final class ModuleSettingsDecoder {
private IrisFeature read(FeatureDescriptor<?> feature, Object value, String resource) {
try {
requireShape(feature, value);
IrisFeature decoded = gson.fromJson(settingsJson(feature, value), feature.type());
String json = settingsJson(feature, value);
IrisFeature decoded = gson.fromJson(json, feature.type());
if (decoded == null) {
throw new JsonParseException("the value is null");
}
requireDeclaredBounds(feature, decoded, JsonParser.parseString(json));
return decoded;
} catch (RuntimeException failure) {
throw new IllegalArgumentException("Cannot read settings " + feature.id() + " under \"" + feature.key() + "\" in "
@@ -183,6 +191,20 @@ public final class ModuleSettingsDecoder {
}
}
/** Checks the bounds of the options the pack wrote; a snippet reference's file is not checked. */
private static void requireDeclaredBounds(FeatureDescriptor<?> feature, IrisFeature decoded, JsonElement written) {
if (!written.isJsonObject()) {
return;
}
JsonObject options = written.getAsJsonObject();
if (feature.root().isEmpty()) {
DeclaredBounds.require(decoded, options, feature.key());
return;
}
String root = feature.root().get();
DeclaredBounds.requireOption(decoded, rootOption(feature, root).field(), options.get(root), feature.key());
}
/** The settings object the value stands for: the value itself, or the root option holding it. */
private static String settingsJson(FeatureDescriptor<?> feature, Object value) {
return feature.root()
@@ -34,8 +34,9 @@ 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.
* A pack whose modules fail to load gets that failure as its error. Before the validators run, every dimension, region
* and biome file that does not load is an error ({@link PackLoadFailures}): validators never see its settings. A
* validator that throws gets an error naming its module, and the others still run.
*/
final class ModulePackValidation {
private ModulePackValidation() {
@@ -65,7 +66,10 @@ final class ModulePackValidation {
} catch (PackModulesException failure) {
return new Findings(List.of(failure.getMessage()), List.of());
}
return validate(data, validators);
List<String> errors = new ArrayList<>(PackLoadFailures.of(data));
Findings modules = validate(data, validators);
errors.addAll(modules.errors());
return new Findings(errors, modules.warnings());
}
/** Runs {@code validators} on the pack {@code data} holds, in order. */
@@ -48,7 +48,6 @@ final class PackDimensionValidator {
continue;
}
validateImportedStructurePolicy(dimensionKey, dimJson, blockingErrors, warnings);
validateDimensionHeights(packFolder, dimensionKey, dimJson, blockingErrors);
validateWorldBoundary(dimensionKey, dimJson, blockingErrors);
@@ -95,126 +94,6 @@ final class PackDimensionValidator {
}
}
/** The dimension's {@code importedStructures} settings of the iris:structure module, which the platform's own structures follow. */
static final String STRUCTURE_SETTINGS = "importedStructures";
static void validateImportedStructurePolicy(String dimensionKey, JSONObject dimension,
List<String> blockingErrors, List<String> warnings) {
if (!dimension.has(STRUCTURE_SETTINGS)) {
return;
}
if (dimension.isNull(STRUCTURE_SETTINGS)) {
blockingErrors.add("Dimension '" + dimensionKey + "' importedStructures must be an object.");
return;
}
JSONObject policy = dimension.optJSONObject(STRUCTURE_SETTINGS);
if (policy == null) {
blockingErrors.add("Dimension '" + dimensionKey + "' importedStructures must be an object.");
return;
}
if (policy.has("mode")) {
blockingErrors.add("Dimension '" + dimensionKey
+ "' importedStructures.mode is not supported. Native structures are enabled by default; deny families in importedStructures.disabled or complete keys in importedStructures.disabledExact.");
}
if (policy.has("enabled")) {
blockingErrors.add("Dimension '" + dimensionKey
+ "' importedStructures.enabled is not supported. Native structures are enabled by default; deny families in importedStructures.disabled or complete keys in importedStructures.disabledExact.");
}
validateStructureKeyList(dimensionKey, policy, "disabled", blockingErrors);
validateStructureKeyList(dimensionKey, policy, "disabledExact", blockingErrors);
validateFrequencyOverrides(dimensionKey, policy, blockingErrors);
JSONArray adjustments = policy.optJSONArray("adjustments");
if (adjustments == null) {
if (policy.has("adjustments")) {
blockingErrors.add("Dimension '" + dimensionKey
+ "' importedStructures.adjustments must be an array.");
}
return;
}
for (int index = 0; index < adjustments.length(); index++) {
JSONObject adjustment = adjustments.optJSONObject(index);
if (adjustment == null) {
blockingErrors.add("Dimension '" + dimensionKey
+ "' importedStructures.adjustments has a non-object entry at index " + index + ".");
continue;
}
if (adjustment.has("clearVegetation")) {
warnings.add("Dimension '" + dimensionKey + "' importedStructures.adjustments[" + index
+ "].clearVegetation was removed and is ignored. Vegetation is always cleared inside structure piece envelopes.");
}
validateStructureKeyList(dimensionKey, adjustment, "match", blockingErrors);
validateAdjustmentYBand(dimensionKey, adjustment, index, blockingErrors);
PackStructurePlacementValidator.validateNativeTerrain("Dimension '" + dimensionKey
+ "' importedStructures.adjustments[" + index + "]", adjustment, blockingErrors);
}
}
private static void validateFrequencyOverrides(String dimensionKey, JSONObject policy,
List<String> blockingErrors) {
if (!policy.has("frequencyOverrides")) {
return;
}
JSONArray overrides = policy.optJSONArray("frequencyOverrides");
if (overrides == null) {
blockingErrors.add("Dimension '" + dimensionKey
+ "' importedStructures.frequencyOverrides must be an array.");
return;
}
for (int index = 0; index < overrides.length(); index++) {
JSONObject override = overrides.optJSONObject(index);
String path = "Dimension '" + dimensionKey
+ "' importedStructures.frequencyOverrides[" + index + "]";
if (override == null) {
blockingErrors.add(path + " must be an object.");
continue;
}
Object rawKey = override.opt("structureSet");
if (!(rawKey instanceof String key)
|| key.isBlank()
|| !PackValidator.RESOURCE_KEY_PATTERN.matcher(key.trim()).matches()) {
blockingErrors.add(path + ".structureSet must be a namespaced registry key.");
}
PackJsonFieldChecks.validateOptionalDoubleRange(
path, override, "multiplier", 0.01D, 16D, blockingErrors);
}
}
private static void validateAdjustmentYBand(String dimensionKey, JSONObject adjustment, int index,
List<String> blockingErrors) {
if (!adjustment.has("yBand") || adjustment.opt("yBand") == JSONObject.NULL) {
return;
}
String path = "Dimension '" + dimensionKey
+ "' importedStructures.adjustments[" + index + "].yBand";
JSONObject band = adjustment.optJSONObject("yBand");
if (band == null) {
blockingErrors.add(path + " must be an object.");
return;
}
PackJsonFieldChecks.validateOptionalIntegerRange(path, band, "min", -4064, 4064, blockingErrors);
PackJsonFieldChecks.validateOptionalIntegerRange(path, band, "max", -4064, 4064, blockingErrors);
}
private static void validateStructureKeyList(String dimensionKey, JSONObject owner, String field,
List<String> blockingErrors) {
if (!owner.has(field)) {
return;
}
JSONArray keys = owner.optJSONArray(field);
if (keys == null) {
blockingErrors.add("Dimension '" + dimensionKey + "' structure policy field '"
+ field + "' must be an array.");
return;
}
for (int index = 0; index < keys.length(); index++) {
Object value = keys.opt(index);
if (!(value instanceof String key) || key.isBlank()) {
blockingErrors.add("Dimension '" + dimensionKey + "' structure policy field '"
+ field + "' has a blank or non-string entry at index " + index + ".");
}
}
}
private static int countBiomeRefs(JSONObject regionJson, String field, File biomesFolder, String regionKey, List<String> warnings) {
JSONArray arr = regionJson.optJSONArray(field);
if (arr == null) {
@@ -0,0 +1,54 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.pack;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.ResourceLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;
/**
* The dimension, region and biome files of a pack whose JSON Iris cannot load, one blocking error each, such as module
* settings with an option outside its declared bounds. A file that is not JSON at all is left to
* {@link PackObjectSurfaceValidator#validateHostFilesParse}, so it is reported once.
*/
final class PackLoadFailures {
private PackLoadFailures() {
}
static List<String> of(IrisData data) {
List<String> blockingErrors = new ArrayList<>();
addFailures(blockingErrors, "Dimension", data.getDimensionLoader());
addFailures(blockingErrors, "Region", data.getRegionLoader());
addFailures(blockingErrors, "Biome", data.getBiomeLoader());
return blockingErrors;
}
private static void addFailures(List<String> blockingErrors, String resourceType, ResourceLoader<?> loader) {
Arrays.stream(loader.getPossibleKeys()).sorted().forEach(key -> loader.load(key, false));
new TreeMap<>(loader.loadFailures()).forEach((key, failure) -> {
if (!failure.invalidJson()) {
blockingErrors.add(resourceType + " '" + key + "' cannot be loaded: " + failure.message());
}
});
}
}
@@ -490,7 +490,7 @@ final class PackStructurePlacementValidator {
private static void validateImportedStructureAdjustmentEnvelopes(
String dimensionKey, JSONObject dimension, RegistrySnapshot registries,
List<String> blockingErrors) {
JSONObject policy = dimension.optJSONObject(PackDimensionValidator.STRUCTURE_SETTINGS);
JSONObject policy = dimension.optJSONObject("importedStructures");
if (policy == null) {
return;
}
@@ -0,0 +1,74 @@
/*
* 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.engine.framework.structure;
import art.arcane.iris.builtin.structure.StructureAdjustment;
import art.arcane.iris.builtin.structure.StructureSetFrequency;
import art.arcane.iris.builtin.structure.StructureSettings;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.validation.Problem;
import com.volmit.validation.Subject;
import com.volmit.validation.ValidationContext;
import java.util.List;
import java.util.regex.Pattern;
/**
* Checks of the dimension's {@code importedStructures} settings that their types cannot state: a key in a list is
* not blank, and a structure set is a namespaced registry key. Shapes, enum names and bounds are the decoder's.
*/
final class ImportedStructuresValidation {
private static final String SETTINGS_KEY = "importedStructures";
private static final Pattern REGISTRY_KEY = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+");
private ImportedStructuresValidation() {
}
static void validate(ValidationContext pack) {
for (Entry<StructureSettings> entry : pack.settings().declared(StructureSettings.class)) {
validate(pack, Subject.resource(entry.source()), entry.value());
}
}
private static void validate(ValidationContext pack, Subject subject, StructureSettings settings) {
requireKeys(pack, subject, SETTINGS_KEY + ".disabled", settings.disabled());
requireKeys(pack, subject, SETTINGS_KEY + ".disabledExact", settings.disabledExact());
List<StructureSetFrequency> overrides = settings.frequencyOverrides();
for (int index = 0; index < overrides.size(); index++) {
String structureSet = overrides.get(index).structureSet().trim();
if (!REGISTRY_KEY.matcher(structureSet).matches()) {
pack.report(Problem.error(subject, SETTINGS_KEY + ".frequencyOverrides[" + index
+ "].structureSet is \"" + structureSet + "\"; it must be a namespaced key such as minecraft:villages"));
}
}
List<StructureAdjustment> adjustments = settings.adjustments();
for (int index = 0; index < adjustments.size(); index++) {
requireKeys(pack, subject, SETTINGS_KEY + ".adjustments[" + index + "].match", adjustments.get(index).match());
}
}
private static void requireKeys(ValidationContext pack, Subject subject, String path, List<String> keys) {
for (int index = 0; index < keys.size(); index++) {
String key = keys.get(index);
if (key == null || key.isBlank()) {
pack.report(Problem.error(subject, path + "[" + index + "] is blank; write a structure key"));
}
}
}
}
@@ -34,7 +34,8 @@ import java.util.Set;
/**
* Module {@code iris:structure}'s check of a pack: every structure a dimension, region or biome places must assemble
* ({@link StructureGraphValidation}), and a dimension that replaces a vanilla structure with an Iris one may only use
* structures that always assemble and fit ({@link NativeReplacementValidation}). Graph diagnostics keep their
* structures that always assemble and fit ({@link NativeReplacementValidation}), and its {@code importedStructures}
* name real keys ({@link ImportedStructuresValidation}). Graph diagnostics keep their
* severity; everything else is an error, as when Iris's own pack validator ran these checks.
*/
public final class StructureValidator implements Validator {
@@ -48,6 +49,7 @@ public final class StructureValidator implements Validator {
graphs.problems().forEach(pack::report);
NativeReplacementValidation.validate(data.getDataFolder(), graphs.replacementOutputStructures(), graphs.sampledVerticalEnvelopes())
.forEach(pack::report);
ImportedStructuresValidation.validate(pack);
}
/**
@@ -1,187 +1,91 @@
package art.arcane.iris.core.pack;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.util.ArrayList;
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.assertTrue;
/** A dimension's {@code importedStructures} as pack validation sees it: decoded into its typed settings, then checked. */
public class PackValidatorImportedStructurePolicyTest {
@Test
public void denyOnlyPolicyAcceptsDisabledKeysAndAdjustments() {
JSONObject policy = new JSONObject()
.put("disabled", new JSONArray().put("minecraft:stronghold"))
.put("disabledExact", new JSONArray().put("minecraft:ruined_portal"))
.put("frequencyOverrides", new JSONArray().put(new JSONObject()
.put("structureSet", "minecraft:nether_complexes")
.put("multiplier", 1.1D)))
.put("adjustments", new JSONArray().put(new JSONObject()
.put("match", new JSONArray().put("minecraft:village"))));
List<String> errors = validate(policy);
private static final String CANNOT_LOAD = "Dimension 'main' cannot be loaded: Cannot read settings iris:structure"
+ " under \"importedStructures\" in Dimension main: ";
assertTrue(errors.isEmpty());
}
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void malformedFrequencyOverridesAreRejected() {
JSONObject policy = new JSONObject()
.put("frequencyOverrides", new JSONArray()
.put("minecraft:nether_complexes")
.put(new JSONObject().put("structureSet", "nether_complexes"))
.put(new JSONObject()
.put("structureSet", "minecraft:ruined_portals")
.put("multiplier", 0D))
.put(new JSONObject()
.put("structureSet", "minecraft:nether_fossils")
.put("multiplier", "often")));
List<String> errors = validate(policy);
assertEquals(4, errors.size());
assertTrue(errors.stream().anyMatch(error -> error.contains("frequencyOverrides[0] must be an object")));
assertTrue(errors.stream().anyMatch(error -> error.contains("frequencyOverrides[1].structureSet")));
assertTrue(errors.stream().anyMatch(error -> error.contains("frequencyOverrides[2].multiplier must be at least")));
assertTrue(errors.stream().anyMatch(error -> error.contains("frequencyOverrides[3].multiplier must be a number")));
}
@Test
public void encaseTerrainAndYBandAdjustmentsAreAccepted() {
JSONObject policy = new JSONObject()
.put("adjustments", new JSONArray().put(new JSONObject()
.put("match", new JSONArray().put("minecraft:stronghold"))
.put("yBand", new JSONObject().put("min", -120).put("max", -20))
.put("terrain", new JSONObject()
.put("mode", "ENCASE")
.put("horizontalPadding", 4)
.put("ceilingPadding", 4)
.put("floorPadding", 4)
.put("encasePalette", new JSONObject()
.put("palette", new JSONArray()
.put(new JSONObject()
.put("block", "minecraft:stone_bricks")
.put("weight", 6))
.put(new JSONObject()
.put("block", "minecraft:cobblestone")
.put("weight", 1)))))));
List<String> errors = validate(policy);
public void theShippingPolicyShapesAreAccepted() throws Exception {
List<String> errors = validate("""
{"disabled": ["minecraft:stronghold"], "disabledExact": ["minecraft:ruined_portal"],
"frequencyOverrides": [{"structureSet": "minecraft:nether_complexes", "multiplier": 1.1}],
"adjustments": [
{"match": ["minecraft:stronghold"], "yBand": {"min": -120, "max": -20},
"terrain": {"mode": "ENCASE", "horizontalPadding": 4, "ceilingPadding": 4, "floorPadding": 4,
"encasePalette": {"palette": [{"block": "minecraft:stone_bricks", "weight": 6}]}}},
{"match": ["towns_and_towers:"], "terrain": {"mode": "VACUUM"}}
]}
""");
assertTrue(errors.toString(), errors.isEmpty());
}
@Test
public void nonObjectEncasePaletteIsRejected() {
JSONObject policy = new JSONObject()
.put("adjustments", new JSONArray().put(new JSONObject()
.put("match", new JSONArray().put("minecraft:stronghold"))
.put("terrain", new JSONObject()
.put("mode", "ENCASE")
.put("encasePalette", "minecraft:stone_bricks"))));
List<String> errors = validate(policy);
public void anOptionAboveItsBoundBlocksThePackNamingItsPath() throws Exception {
List<String> errors = validate("{\"frequencyOverrides\": [{\"structureSet\": \"minecraft:villages\", \"multiplier\": 99}]}");
assertEquals(List.of(CANNOT_LOAD + "importedStructures.frequencyOverrides[0].multiplier is 99.0; it must be at most 16"), errors);
}
@Test
public void aBoundInsideNestedSettingsNamesTheWholePath() throws Exception {
List<String> errors = validate("{\"adjustments\": [{\"match\": [\"minecraft:stronghold\"], \"yBand\": {\"min\": -5000}}]}");
assertEquals(List.of(CANNOT_LOAD + "importedStructures.adjustments[0].yBand.min is -5000; it must be at least -4064"), errors);
}
@Test
public void anUnknownTerrainModeBlocksThePack() throws Exception {
List<String> errors = validate("{\"adjustments\": [{\"match\": [\"minecraft:stronghold\"], \"terrain\": {\"mode\": \"SINK\"}}]}");
assertEquals(1, errors.size());
assertTrue(errors.get(0), errors.get(0)
.contains("adjustments[0].terrain.encasePalette must be an object"));
assertTrue(errors.get(0), errors.get(0).startsWith(CANNOT_LOAD) && errors.get(0).contains("\"SINK\" is not one of"));
}
@Test
public void malformedYBandAndTerrainAdjustmentsAreRejected() {
JSONObject policy = new JSONObject()
.put("adjustments", new JSONArray()
.put(new JSONObject()
.put("match", new JSONArray().put("minecraft:stronghold"))
.put("yBand", -120))
.put(new JSONObject()
.put("match", new JSONArray().put("minecraft:trial_chambers"))
.put("yBand", new JSONObject().put("min", -9000))
.put("terrain", new JSONObject().put("mode", "SOLIDIFY"))));
List<String> errors = validate(policy);
public void blankKeysAndAStructureSetWithoutNamespaceAreErrors() throws Exception {
List<String> errors = validate("""
{"disabled": ["minecraft:village", " "],
"frequencyOverrides": [{"structureSet": "villages"}],
"adjustments": [{"match": [""]}]}
""");
assertEquals(3, errors.size());
assertTrue(errors.stream().anyMatch(error ->
error.contains("adjustments[0].yBand must be an object")));
assertTrue(errors.stream().anyMatch(error ->
error.contains("adjustments[1].yBand.min")));
assertTrue(errors.stream().anyMatch(error ->
error.contains("adjustments[1].terrain.mode")));
assertEquals(List.of(
"pack:dimension/main: importedStructures.disabled[1] is blank; write a structure key",
"pack:dimension/main: importedStructures.frequencyOverrides[0].structureSet is \"villages\"; it must be a"
+ " namespaced key such as minecraft:villages",
"pack:dimension/main: importedStructures.adjustments[0].match[0] is blank; write a structure key"), errors);
}
@Test
public void legacyModeAndEnabledWhitelistAreRejected() {
JSONObject policy = new JSONObject()
.put("mode", "ALL_OFF")
.put("enabled", new JSONArray().put("minecraft:monument"));
List<String> errors = validate(policy);
assertEquals(2, errors.size());
assertTrue(errors.get(0).contains("importedStructures.mode is not supported"));
assertTrue(errors.get(1).contains("importedStructures.enabled is not supported"));
/** The blocking errors of a pack whose one dimension declares {@code policy} as its {@code importedStructures}. */
private List<String> validate(String policy) throws Exception {
File pack = temporaryFolder.newFolder("pack");
write(pack, "dimensions/main.json", "{\"regions\": [\"region\"], \"importedStructures\": " + policy + "}");
write(pack, "regions/region.json", "{\"landBiomes\": [\"biome\"]}");
write(pack, "biomes/biome.json", "{\"name\": \"Biome\"}");
return PackValidator.validate(pack).getBlockingErrors();
}
@Test
public void explicitNullsAndWrongShapesAreRejected() {
JSONObject policy = new JSONObject()
.put("disabled", JSONObject.NULL)
.put("disabledExact", new JSONObject())
.put("frequencyOverrides", JSONObject.NULL)
.put("adjustments", new JSONObject());
List<String> errors = validate(policy);
assertEquals(4, errors.size());
assertTrue(errors.stream().anyMatch(error -> error.contains("'disabled' must be an array")));
assertTrue(errors.stream().anyMatch(error -> error.contains("'disabledExact' must be an array")));
assertTrue(errors.stream().anyMatch(error -> error.contains("frequencyOverrides must be an array")));
assertTrue(errors.stream().anyMatch(error -> error.contains("adjustments must be an array")));
}
@Test
public void blankOrNonStringExactKeysAreRejected() {
JSONObject policy = new JSONObject()
.put("disabledExact", new JSONArray().put(" ").put(4));
List<String> errors = validate(policy);
assertEquals(2, errors.size());
assertTrue(errors.get(0).contains("'disabledExact' has a blank or non-string entry at index 0"));
assertTrue(errors.get(1).contains("'disabledExact' has a blank or non-string entry at index 1"));
}
@Test
public void explicitNullPolicyIsRejectedWhileOmissionUsesDefaults() {
List<String> missingErrors = new ArrayList<>();
PackDimensionValidator.validateImportedStructurePolicy("overworld", new JSONObject(),
missingErrors, new ArrayList<>());
assertTrue(missingErrors.isEmpty());
List<String> nullErrors = new ArrayList<>();
PackDimensionValidator.validateImportedStructurePolicy("overworld",
new JSONObject().put("importedStructures", JSONObject.NULL), nullErrors, new ArrayList<>());
assertEquals(List.of("Dimension 'overworld' importedStructures must be an object."), nullErrors);
}
@Test
public void removedClearVegetationAdjustmentWarnsWithoutBlockingThePack() {
JSONObject policy = new JSONObject()
.put("adjustments", new JSONArray().put(new JSONObject()
.put("match", new JSONArray().put("minecraft:village"))
.put("clearVegetation", true)));
List<String> errors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
PackDimensionValidator.validateImportedStructurePolicy("overworld",
new JSONObject().put("importedStructures", policy), errors, warnings);
assertTrue(errors.toString(), errors.isEmpty());
assertEquals(1, warnings.size());
assertTrue(warnings.get(0), warnings.get(0)
.contains("adjustments[0].clearVegetation was removed and is ignored"));
}
private List<String> validate(JSONObject policy) {
List<String> errors = new ArrayList<>();
PackDimensionValidator.validateImportedStructurePolicy("overworld",
new JSONObject().put("importedStructures", policy), errors, new ArrayList<>());
return errors;
private void write(File root, String relative, String content) throws Exception {
Path target = new File(root, relative).toPath();
Files.createDirectories(target.getParent());
Files.writeString(target, content, StandardCharsets.UTF_8);
}
}
@@ -1,7 +1,5 @@
package art.arcane.iris.core.pack;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
@@ -77,23 +75,6 @@ public class PackValidatorStructureTerrainBackendTest {
}
}
@Test
public void acceptsNativeOnlyTerrainModesForImportedStructureAdjustments() {
for (String mode : List.of("VACUUM", "ENCASE")) {
JSONObject policy = new JSONObject().put("adjustments", new JSONArray().put(
new JSONObject()
.put("match", new JSONArray().put("towns_and_towers:"))
.put("terrain", new JSONObject().put("mode", mode))));
List<String> errors = new ArrayList<>();
PackDimensionValidator.validateImportedStructurePolicy(
"overworld", new JSONObject().put("importedStructures", policy),
errors, new ArrayList<>());
assertTrue(mode + ": " + errors, errors.isEmpty());
}
}
private void writePlacement(File pack, String relativePath, String placementId,
String structureKey, boolean nativeStructure,
String terrainMode) throws Exception {