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 eeadba878..fa561fff7 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 @@ -142,7 +142,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { private IrisData(File dataFolder, boolean datapackCompiler) { this.dataFolder = dataFolder; - this.modules = new PackModuleSet(dataFolder); + this.modules = new PackModuleSet(dataFolder, this::getGson); this.id = RNG.r.imax(); this.datapackCompiler = datapackCompiler; if (datapackCompiler) { diff --git a/core/src/main/java/art/arcane/iris/core/modules/ChunkModuleSettings.java b/core/src/main/java/art/arcane/iris/core/modules/ChunkModuleSettings.java index 893af89ca..89cc78886 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ChunkModuleSettings.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ChunkModuleSettings.java @@ -20,26 +20,23 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.engine.framework.Engine; -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 com.volmit.IrisFeature; import com.volmit.config.FeatureSettings; -import com.volmit.host.ConfiguredSettings; -import com.volmit.resource.ResourceId; +import java.util.ArrayList; import java.util.List; /** - * Module settings at world positions, for one engine. - *

- * The settings that activate a chunk's stages come from its dimension, then the region and then the - * biome at the chunk's center column, each type taking the most specific declaration: a biome's value - * replaces its region's, a region's the dimension's. Iris resolves single-valued settings, such as a - * cave profile, the same way. {@link #at} keeps the targets apart, as {@link FeatureSettings} promises. + * Module settings at world columns, for one engine: the dimension's entry, then the entry of the column's + * region, then the one of its surface biome. Each level that declares the settings is its own entry; levels + * stack and are never merged, so a module sees all of them and decides what several mean. */ final class ChunkModuleSettings implements FeatureSettings { + private static final String DIMENSION = "dimension"; + private static final String REGION = "region"; + private static final String BIOME = "biome"; + private final Engine engine; private final PackResourceIds ids; @@ -48,34 +45,21 @@ final class ChunkModuleSettings implements FeatureSettings { this.ids = ids; } - static ConfiguredSettings configured(IrisDimension dimension, IrisRegion region, IrisBiome biome) { - return settingsOf(dimension) - .overriddenBy(settingsOf(region)) - .overriddenBy(settingsOf(biome)) - .configured(); - } - @Override - public List> at(Class featureType, Target target, int worldX, int worldY, int worldZ) { - return switch (target) { - case DIMENSION -> entries(featureType, "dimension", engine.getDimension()); - case REGION -> entries(featureType, "region", engine.getRegion(worldX, worldZ)); - case BIOME -> entries(featureType, "biome", engine.getSurfaceBiome(worldX, worldZ)); - case OBJECT_PLACEMENT -> List.of(); - }; + public List> at(Class featureType, int worldX, int worldZ) { + List> entries = new ArrayList<>(Target.values().length); + addEntry(entries, featureType, Target.DIMENSION, DIMENSION, engine.getDimension()); + addEntry(entries, featureType, Target.REGION, REGION, engine.getRegion(worldX, worldZ)); + addEntry(entries, featureType, Target.BIOME, BIOME, engine.getSurfaceBiome(worldX, worldZ)); + return entries.isEmpty() ? List.of() : List.copyOf(entries); } - private List> entries(Class featureType, String kind, IrisRegistrant owner) { + private void addEntry(List> entries, Class featureType, Target level, String kind, + IrisRegistrant owner) { if (owner == null) { - return List.of(); + return; } - ResourceId source = ids.of(kind, owner.getLoadKey()); - return owner.getModuleSettings().find(featureType) - .map(value -> List.of(new Entry<>(source, source, value))) - .orElse(List.of()); - } - - private static ModuleSettings settingsOf(IrisRegistrant owner) { - return owner == null ? ModuleSettings.NONE : owner.getModuleSettings(); + owner.getModuleSettings().find(featureType) + .ifPresent(value -> entries.add(new Entry<>(level, ids.of(kind, owner.getLoadKey()), value))); } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java b/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java index b75987152..d308a2952 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java @@ -34,6 +34,8 @@ import com.volmit.world.TerrainSampler; */ final class IrisGenerationContext implements GenerationContext { private static final String NOT_BRIDGED = " is not bridged to Iris yet; modules cannot use it until a built-in port needs it"; + /** Chunk stages write only their own chunk. */ + private static final int CHUNK_STAGE_REACH = 0; private final Engine engine; private final int originX; @@ -42,13 +44,13 @@ final class IrisGenerationContext implements GenerationContext { private final IrisTerrainSampler terrain; private final ChunkModuleSettings settings; - IrisGenerationContext(Engine engine, int originX, int originZ, BlockStateHunk blocks, int reachBlocks) { + IrisGenerationContext(Engine engine, int originX, int originZ, BlockStateHunk blocks) { PackResourceIds ids = new PackResourceIds(engine.getData().getDataFolder()); this.engine = engine; this.originX = originX; this.originZ = originZ; this.blocks = blocks; - this.terrain = new IrisTerrainSampler(engine, ids, originX, originZ, reachBlocks); + this.terrain = new IrisTerrainSampler(engine, ids, originX, originZ, CHUNK_STAGE_REACH); this.settings = new ChunkModuleSettings(engine, ids); } 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 index a114ebbcf..e40666d37 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java @@ -31,12 +31,14 @@ 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, a jar copy - * directory under the plugin's cache, and Iris's log. + * 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. */ 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"; + /** Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. */ + public static final String HOST_TYPE_PACKAGE = "art.arcane.iris.engine.object"; 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"; @@ -53,11 +55,17 @@ public final class IrisModuleHost { return Stream.concat(PlacementModules.all().stream(), Stream.of(new PerfectionModule())).toList(); } + /** Whether {@code type} is one of Iris's own classes that built-in settings may hold. */ + public static boolean isHostType(Class type) { + return type.getName().startsWith(HOST_TYPE_PACKAGE + "."); + } + private static ModuleHost build() { return ModuleHost.of(builtInModules()) .exposing(BUILT_IN_API_PACKAGE) .reservingNamespaces(RESERVED_NAMESPACE) .reservingFields(ModuleTargets.reservedFields()) + .describingHostTypesIn(HOST_TYPE_PACKAGE) .copyingJarsTo(jarCopyRoot()) .loggingTo(new IrisApiLogger(PackModules.class.getName())); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleChunkGeneration.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleChunkGeneration.java index c99dda336..a6ecde362 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleChunkGeneration.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleChunkGeneration.java @@ -19,29 +19,25 @@ package art.arcane.iris.core.modules; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.project.hunk.Hunk; import com.volmit.host.ChunkRunner; -import com.volmit.host.ConfiguredSettings; import com.volmit.host.LoadedPack; import com.volmit.host.ResolvedGraph; import java.util.function.Function; /** - * Runs the pack's resolved chunk graph on a chunk Iris has generated. Its stages are active where the - * chunk's dimension, region or biome configures their settings (see {@link ChunkModuleSettings}). A - * failing stage fails the chunk. + * Runs the pack's resolved chunk graph on a chunk. A stage is active where any column of the chunk has its + * settings at the dimension, the column's region or its biome (see {@link ChunkModuleSettings}). A failing + * stage fails the chunk. *

* Stages write the chunk's own block hunk, so a block written beyond the chunk fails instead of being - * clipped. The pipeline's reach widens the terrain they may sample; mantle access is not bridged yet. + * clipped, and read the mantle the mantle pipeline prepared. */ public final class ModuleChunkGeneration { - private static final int CHUNK_CENTER = 7; private static final int CHUNK_SHIFT = 4; private ModuleChunkGeneration() { @@ -49,20 +45,17 @@ public final class ModuleChunkGeneration { /** {@code x} and {@code z} are the chunk's first block, as engine stages receive them. */ public static void generate(Engine engine, int x, int z, Hunk blocks, ChunkContext context) { - generate(engine.getData().getModules().pack(), engine, x, z, blocks, context, - context.getRegion().get(CHUNK_CENTER, CHUNK_CENTER), context.getBiome().get(CHUNK_CENTER, CHUNK_CENTER), B::getState); + generate(engine.getData().getModules().pack(), engine, x, z, blocks, context, B::getState); } static void generate(LoadedPack pack, Engine engine, int x, int z, Hunk blocks, ChunkContext context, - IrisRegion centerRegion, IrisBiome centerBiome, Function platformStates) { + Function platformStates) { ResolvedGraph chunk = pack.chunk(); if (chunk.stages().isEmpty()) { return; } - ConfiguredSettings settings = ChunkModuleSettings.configured(engine.getDimension(), centerRegion, centerBiome); - IrisGenerationContext inputs = new IrisGenerationContext(engine, x, z, - new BlockStateHunk(blocks, platformStates), chunk.reach().blocks()); + IrisGenerationContext inputs = new IrisGenerationContext(engine, x, z, new BlockStateHunk(blocks, platformStates)); long seed = ModuleSeeds.chunk(engine.getSeedManager().getSeed(), x >> CHUNK_SHIFT, z >> CHUNK_SHIFT); - new IrisChunk(engine, x, z, blocks, context).runBound(() -> new ChunkRunner(chunk).generate(inputs, seed, settings)); + new IrisChunk(engine, x, z, blocks, context).runBound(() -> new ChunkRunner(chunk).generate(inputs, seed)); } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java index 888af1cd0..b00989340 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java @@ -88,7 +88,7 @@ public final class ModuleObjectPlacement { new PlacerBlockView(placer, area, states)); long seed = ModuleSeeds.placement(worldSeed, objectKey, x, requestedY, z); PlacementOutcome outcome = placement.runBound(() -> new PlacementRunner(graph) - .place(request, edit, inputs, seed, config.getModuleSettings().configured())); + .place(request, edit, inputs, seed, config.getModuleSettings().placement(source))); return outcome.isPlaced() ? ObjectPlacementResult.placed(placement.anchorY()) : ObjectPlacementResult.rejected(outcome.rejection().orElseThrow()); 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 index 3e1477f1d..1f99ad251 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java @@ -20,14 +20,15 @@ package art.arcane.iris.core.modules; import com.volmit.IrisFeature; import com.volmit.host.ConfiguredSettings; +import com.volmit.resource.ResourceId; 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. + * Module settings one dimension, region, biome or object placement declares, at most one value per settings + * type. Each is one level's entry: levels stack and are never merged (see {@link ChunkModuleSettings}). */ public final class ModuleSettings { public static final ModuleSettings NONE = new ModuleSettings(Map.of()); @@ -54,20 +55,8 @@ public final class ModuleSettings { 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)); + /** These settings as one placement's own, declared by {@code source}. */ + public ConfiguredSettings placement(ResourceId source) { + return isEmpty() ? ConfiguredSettings.none() : ConfiguredSettings.placement(source, 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 index 17bc64aee..569cd7f90 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java @@ -31,6 +31,7 @@ import com.google.gson.stream.JsonWriter; import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; import com.volmit.block.BlockState; +import com.volmit.config.OptionsMetadata; import com.volmit.config.Snippet; import com.volmit.host.FeatureCatalog; import com.volmit.host.FeatureDescriptor; @@ -49,6 +50,7 @@ import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.function.Function; +import java.util.function.Supplier; import java.util.stream.Stream; /** @@ -56,6 +58,10 @@ import java.util.stream.Stream; * 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}. + *

+ * Settings with exactly one option may be written as that option's value: {@code "snow": 0.5} reads as + * {@code "snow": {"amount": 0.5}}. Iris's own classes that built-in settings hold (see + * {@link IrisModuleHost#isHostType}) are read by Iris's pack Gson, exactly as Iris reads them elsewhere. */ public final class ModuleSettingsDecoder { private static final String SNIPPET_PREFIX = "snippet/"; @@ -66,12 +72,16 @@ public final class ModuleSettingsDecoder { private final Map> keys = new EnumMap<>(Target.class); private final Path packFolder; private final Gson gson; + private final Supplier irisGson; - ModuleSettingsDecoder(FeatureCatalog catalog, Path packFolder) { + /** @param irisGson the pack's own Gson, which reads Iris's classes */ + ModuleSettingsDecoder(FeatureCatalog catalog, Path packFolder, Supplier irisGson) { this.packFolder = packFolder; + this.irisGson = irisGson; this.gson = new GsonBuilder() .registerTypeAdapter(BlockState.class, textAdapter(BlockState::parse, BlockState::key)) .registerTypeAdapter(ResourceId.class, textAdapter(ResourceId::parse, ResourceId::toString)) + .registerTypeAdapterFactory(new HostTypes()) .registerTypeAdapterFactory(new SnippetReferences()) .create(); for (Target target : Target.values()) { @@ -112,7 +122,7 @@ public final class ModuleSettingsDecoder { private IrisFeature read(FeatureDescriptor feature, Object value, String key, String resource) { try { - IrisFeature decoded = gson.fromJson(JSONObject.valueToString(value), feature.type()); + IrisFeature decoded = gson.fromJson(JSONObject.valueToString(asObject(feature, value)), feature.type()); if (decoded == null) { throw new JsonParseException("the value is null"); } @@ -123,6 +133,23 @@ public final class ModuleSettingsDecoder { } } + /** A bare value of settings with exactly one option, as the object holding it; anything else unchanged. */ + private static Object asObject(FeatureDescriptor feature, Object value) { + if (value instanceof JSONObject || isSnippetReference(feature, value)) { + return value; + } + List options = feature.options().options(); + if (options.size() != 1) { + throw new JsonParseException("write an object; only settings with exactly one option may be written as that" + + " option's value, and these have " + options.size()); + } + return new JSONObject().put(options.getFirst().name(), value); + } + + private static boolean isSnippetReference(FeatureDescriptor feature, Object value) { + return feature.type().isAnnotationPresent(Snippet.class) && value instanceof String text && text.startsWith(SNIPPET_PREFIX); + } + private static List> settingsAt(FeatureCatalog catalog, Target target) { return catalog.settings().stream() .filter(feature -> feature.attachment().targets().contains(target)) @@ -155,6 +182,27 @@ public final class ModuleSettingsDecoder { }.nullSafe(); } + /** Reads and writes Iris's own classes with the pack's Gson, asked at each use so a hotloaded pack's applies. */ + private final class HostTypes implements TypeAdapterFactory { + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!IrisModuleHost.isHostType(type.getRawType())) { + return null; + } + return new TypeAdapter() { + @Override + public void write(JsonWriter out, T value) throws IOException { + irisGson.get().getAdapter(type).write(out, value); + } + + @Override + public T read(JsonReader in) throws IOException { + return irisGson.get().getAdapter(type).read(in); + } + }; + } + } + /** Lets a {@link Snippet} type be written as a reference to a snippet file. */ private final class SnippetReferences implements TypeAdapterFactory { @Override 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 index 312486fb6..1ba63cf99 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/PackModuleSet.java +++ b/core/src/main/java/art/arcane/iris/core/modules/PackModuleSet.java @@ -19,12 +19,14 @@ package art.arcane.iris.core.modules; import art.arcane.iris.spi.IrisLogging; +import com.google.gson.Gson; import com.volmit.host.LoadedPack; import java.io.File; import java.util.Arrays; import java.util.Comparator; import java.util.List; +import java.util.function.Supplier; /** * The modules of one pack folder, loaded with {@link IrisModuleHost} the first time something needs @@ -39,14 +41,17 @@ public final class PackModuleSet implements AutoCloseable { private static final String JAR_EXTENSION = ".jar"; private final File packFolder; + private final Supplier irisGson; private State state = State.NOT_LOADED; private LoadedPack pack; private ModuleSettingsDecoder settings; private PackModulesException failure; private List loadedJars = List.of(); - public PackModuleSet(File packFolder) { + /** @param irisGson the pack's own Gson, which reads the Iris classes built-in settings hold */ + public PackModuleSet(File packFolder, Supplier irisGson) { this.packFolder = packFolder; + this.irisGson = irisGson; } /** The loaded pack, its built-in modules included. */ @@ -106,7 +111,7 @@ public final class PackModuleSet implements AutoCloseable { try { LoadedPack loaded = LoadedPack.load(packFolder.toPath(), IrisModuleHost.get()); pack = loaded; - settings = new ModuleSettingsDecoder(loaded.catalog(), packFolder.toPath()); + settings = new ModuleSettingsDecoder(loaded.catalog(), packFolder.toPath(), irisGson); state = State.LOADED; } catch (RuntimeException loadFailure) { failure = new PackModulesException(packFolder, loadFailure); diff --git a/core/src/main/java/art/arcane/iris/core/modules/PlacementModuleSettings.java b/core/src/main/java/art/arcane/iris/core/modules/PlacementModuleSettings.java index 91dc30a56..35c7ef286 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/PlacementModuleSettings.java +++ b/core/src/main/java/art/arcane/iris/core/modules/PlacementModuleSettings.java @@ -23,16 +23,18 @@ import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings; import com.volmit.resource.ResourceId; +import java.util.ArrayList; import java.util.List; +import java.util.Optional; /** - * Module settings during one object placement: the placement's own at {@link Target#OBJECT_PLACEMENT}, - * the world's at every other target. A placement without an engine sees no world settings. + * Module settings during one object placement: the world's levels at the column, followed by the placement's + * own entry. A placement without an engine sees no world settings. */ final class PlacementModuleSettings implements FeatureSettings { private static final FeatureSettings NO_WORLD = new FeatureSettings() { @Override - public List> at(Class featureType, Target target, int worldX, int worldY, int worldZ) { + public List> at(Class featureType, int worldX, int worldZ) { return List.of(); } }; @@ -53,12 +55,14 @@ final class PlacementModuleSettings implements FeatureSettings { } @Override - public List> at(Class featureType, Target target, int worldX, int worldY, int worldZ) { - if (target != Target.OBJECT_PLACEMENT) { - return world.at(featureType, target, worldX, worldY, worldZ); + public List> at(Class featureType, int worldX, int worldZ) { + List> worldEntries = world.at(featureType, worldX, worldZ); + Optional own = placement.find(featureType); + if (own.isEmpty()) { + return worldEntries; } - return placement.find(featureType) - .map(value -> List.of(new Entry<>(source, source, value))) - .orElse(List.of()); + List> entries = new ArrayList<>(worldEntries); + entries.add(new Entry<>(Target.OBJECT_PLACEMENT, source, own.get())); + return List.copyOf(entries); } } diff --git a/core/src/main/java/art/arcane/iris/core/project/ModuleSchemaRenderer.java b/core/src/main/java/art/arcane/iris/core/project/ModuleSchemaRenderer.java index 0f404b94d..e95697df2 100644 --- a/core/src/main/java/art/arcane/iris/core/project/ModuleSchemaRenderer.java +++ b/core/src/main/java/art/arcane/iris/core/project/ModuleSchemaRenderer.java @@ -38,7 +38,8 @@ 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. + * 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. */ final class ModuleSchemaRenderer { private static final String DEFINITION_PREFIX = "module-"; @@ -52,17 +53,24 @@ final class ModuleSchemaRenderer { void complete(JSONObject property, Reference reference, TextFormat format); } + /** 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); + } + private final PackSchema schema; private final Map definitions; private final ReferenceCompletions references; + private final HostDefinitions hostDefinitions; private final Function> snippetFiles; /** {@code snippetFiles} lists the snippet references a pack has for a snippet folder, such as {@code snippet/thick}. */ ModuleSchemaRenderer(PackSchema schema, Map definitions, ReferenceCompletions references, - Function> snippetFiles) { + HostDefinitions hostDefinitions, Function> snippetFiles) { this.schema = schema; this.definitions = definitions; this.references = references; + this.hostDefinitions = hostDefinitions; this.snippetFiles = snippetFiles; } @@ -91,9 +99,13 @@ final class ModuleSchemaRenderer { return file; } + /** The settings object, or with exactly one option also that option's bare value. */ private JSONObject featureProperty(FeatureSchema feature) { - JSONObject property = new JSONObject(); - property.put("$ref", DEFINITION_REF + definition(feature.settings().name())); + JSONObject object = new JSONObject(); + object.put("$ref", DEFINITION_REF + definition(feature.settings().name())); + JSONObject property = feature.shorthand() + .map(option -> new JSONObject().put("anyOf", new JSONArray(List.of(object, optionSchema(option))))) + .orElse(object); String description = feature.name() + " (" + feature.id() + "), from module " + feature.module().name() + " (" + feature.module().id() + ")" + (feature.settings().description().isEmpty() ? "" : ". " + feature.settings().description()); property.put("description", description); @@ -197,6 +209,7 @@ final class ModuleSchemaRenderer { value.put("additionalProperties", valueSchema(map.value())); } case ValueKind.ObjectKind object -> value.put("$ref", DEFINITION_REF + definition(object.type())); + case ValueKind.HostKind host -> value.put("$ref", DEFINITION_REF + hostDefinitions.definition(host.type())); } return value; } diff --git a/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java b/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java index a2ca557fc..3edef3594 100644 --- a/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java +++ b/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java @@ -372,11 +372,34 @@ public class SchemaBuilder { private ModuleSchemaRenderer moduleSchemas() { if (moduleSchemas == null) { moduleSchemas = new ModuleSchemaRenderer(data.getModules().pack().schema(), definitions, - this::completeReference, data::getPossibleSnippets); + this::completeReference, this::hostDefinition, data::getPossibleSnippets); } return moduleSchemas; } + /** Iris's own definition of one of its classes that a built-in module's settings hold, as Iris's fields describe it. */ + private String hostDefinition(String typeName) { + Class type = hostType(typeName); + String key = objectDefinitionKey(type); + if (!definitions.containsKey(key)) { + definitions.put(key, new JSONObject()); + definitions.put(key, buildProperties(type)); + } + return key; + } + + private static Class hostType(String typeName) { + try { + return Class.forName(typeName, false, SchemaBuilder.class.getClassLoader()); + } catch (ClassNotFoundException missing) { + throw new IllegalStateException("Built-in settings name Iris class " + typeName + ", which Iris does not have", missing); + } + } + + private static String objectDefinitionKey(Class type) { + return "obj-" + type.getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); + } + /** Completion for a module option that names something, from the same lists Iris's own fields use. */ private void completeReference(JSONObject property, Reference reference, TextFormat format) { switch (reference) { @@ -653,7 +676,7 @@ public class SchemaBuilder { } } else { fancyType = k.getType().getSimpleName().replaceAll("\\QIris\\E", "") + " (Object)"; - String key = "obj-" + k.getType().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); + String key = objectDefinitionKey(k.getType()); if (!definitions.containsKey(key)) { definitions.put(key, new JSONObject()); definitions.put(key, buildProperties(k.getType())); @@ -681,7 +704,7 @@ public class SchemaBuilder { case "number" -> fancyType = "List of Numbers"; case "object" -> { fancyType = "List of " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + "s (Objects)"; - String key = "obj-" + t.type().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); + String key = objectDefinitionKey(t.type()); if (!definitions.containsKey(key)) { definitions.put(key, new JSONObject()); definitions.put(key, buildProperties(t.type())); diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleChunkGenerationTest.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleChunkGenerationTest.java index 3d590ca57..d06b3480d 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleChunkGenerationTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleChunkGenerationTest.java @@ -43,12 +43,14 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; +import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -78,7 +80,8 @@ public class ModuleChunkGenerationTest { @Override public void install(StageGraph graph) { - graph.define(Stage.chunk("iris:pillar/raise")).when(PillarSettings.class).run((context, pillar) -> { + graph.define(Stage.chunk("iris:pillar/raise")).when(PillarSettings.class).run((context, pillars) -> { + PillarSettings pillar = pillars.getLast().value(); com.volmit.hunk.Hunk chunk = context.hunk(BlockState.class); chunk.set(0, 1, 0, chunk.get(0, 0, 0)); chunk.set(pillar.x, 2, 0, pillar.block); @@ -106,6 +109,37 @@ public class ModuleChunkGenerationTest { pack.close(); } + @Test + public void everyLevelThatConfiguresTheSettingsIsItsOwnEntryInLevelOrder() { + List> seen = new ArrayList<>(); + ChunkModuleSettings settings = new ChunkModuleSettings(engine, new PackResourceIds(folder.getRoot())); + IrisRegion region = configured(new IrisRegion(), pillar(1)); + region.setLoadKey("hot"); + IrisBiome biome = configured(new IrisBiome(), pillar(2)); + biome.setLoadKey("desert/dunes"); + when(engine.getRegion(5, 6)).thenReturn(region); + when(engine.getSurfaceBiome(5, 6)).thenReturn(biome); + when(engine.getDimension()).thenReturn(configured(new IrisDimension(), pillar(0))); + + settings.at(PillarSettings.class, 5, 6).forEach(entry -> seen.add(List.of(entry.level().name(), entry.source().toString()))); + + String pack = folder.getRoot().getName().toLowerCase(java.util.Locale.ROOT).replaceAll("[^a-z0-9_.-]", "_"); + assertEquals(List.of(List.of("DIMENSION", pack + ":dimension/null"), List.of("REGION", pack + ":region/hot"), + List.of("BIOME", pack + ":biome/desert/dunes")), seen); + } + + @Test + public void stagesRunWhereAnyColumnOfTheChunkConfiguresThem() { + when(engine.getRegion(anyInt(), anyInt())).thenReturn(new IrisRegion()); + IrisBiome plain = new IrisBiome(); + IrisBiome pillared = configured(new IrisBiome(), pillar(3)); + when(engine.getSurfaceBiome(anyInt(), anyInt())).thenAnswer(call -> call.getArgument(0, Integer.class) == 15 ? pillared : plain); + + ModuleChunkGeneration.generate(pack, engine, 0, 0, blocks, null, ModuleChunkGenerationTest::platformState); + + assertEquals("minecraft:oak_log[axis=y]", blocks.get(3, 2, 0).key()); + } + @Test public void stagesRunWhereTheChunksBiomeConfiguresThemAndWriteIrisBlocks() { blocks.set(0, 0, 0, platformState("minecraft:dirt")); @@ -139,7 +173,9 @@ public class ModuleChunkGenerationTest { } private void generate(IrisBiome biome) { - ModuleChunkGeneration.generate(pack, engine, 0, 0, blocks, null, new IrisRegion(), biome, ModuleChunkGenerationTest::platformState); + when(engine.getRegion(anyInt(), anyInt())).thenReturn(new IrisRegion()); + when(engine.getSurfaceBiome(anyInt(), anyInt())).thenReturn(biome); + ModuleChunkGeneration.generate(pack, engine, 0, 0, blocks, null, ModuleChunkGenerationTest::platformState); } private static PillarSettings pillar(int x) { 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 index f8484f004..60c212cb6 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleSettingsDecoderTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleSettingsDecoderTest.java @@ -18,7 +18,14 @@ package art.arcane.iris.core.modules; +import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.volmlib.util.json.JSONObject; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.volmit.FeatureRegistry; import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; import com.volmit.IrisModule; @@ -69,6 +76,16 @@ public class ModuleSettingsDecoderTest { private int size = 1; } + @Feature(id = "iris:moss/cover", name = "Cover", alias = "cover", targets = Target.BIOME) + public static final class CoverSettings implements IrisFeature { + private double amount = 1; + } + + @Feature(id = "iris:moss/marks", name = "Marks", alias = "marks", targets = Target.BIOME) + public static final class MarksSettings implements IrisFeature { + private List marks = List.of(); + } + public static final class MossModule implements IrisModule { @Override public ModuleInfo info() { @@ -80,13 +97,20 @@ public class ModuleSettingsDecoderTest { graph.define(Stage.chunk("iris:moss/spread")).when(MossSettings.class).run((context, moss) -> { }); } + + @Override + public void register(FeatureRegistry registry) { + registry.registerSettings(CoverSettings.class); + registry.registerSettings(MarksSettings.class); + } } @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); + pack = LoadedPack.load(packFolder, ModuleHost.of(List.of(new MossModule())) + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } @After @@ -148,17 +172,42 @@ public class ModuleSettingsDecoderTest { @Test public void listsTheKeysModulesReadPerTarget() { - assertEquals(Set.of("iris:moss", "moss"), decoder.keys(Target.BIOME)); + assertEquals(Set.of("iris:moss", "moss", "iris:moss/cover", "cover", "iris:moss/marks", "marks"), 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"); + public void settingsWithOneOptionReadABareValueAsThatOption() { + assertEquals(0.5, decoder.decode(Target.BIOME, new JSONObject("{\"cover\": 0.5}"), "biome desert/dunes") + .find(CoverSettings.class).orElseThrow().amount, 0); + assertEquals(0.25, decoder.decode(Target.BIOME, new JSONObject("{\"cover\": {\"amount\": 0.25}}"), "biome desert/dunes") + .find(CoverSettings.class).orElseThrow().amount, 0); - 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); + IllegalArgumentException several = assertThrows(IllegalArgumentException.class, () -> moss("{\"moss\": 4}")); + assertEquals("Cannot read settings iris:moss under \"moss\" in biome desert/dunes: write an object; only settings with exactly" + + " one option may be written as that option's value, and these have 4", several.getMessage()); + } + + @Test + public void irisClassesInBuiltInSettingsAreReadByThePacksGson() { + IrisPosition marked = new IrisPosition(1, 2, 3); + Gson iris = new GsonBuilder().registerTypeAdapter(IrisPosition.class, new TypeAdapter() { + @Override + public void write(JsonWriter out, IrisPosition value) throws IOException { + out.value("marked"); + } + + @Override + public IrisPosition read(JsonReader in) throws IOException { + in.nextString(); + return marked; + } + }).create(); + ModuleSettingsDecoder withIrisGson = new ModuleSettingsDecoder(pack.catalog(), packFolder, () -> iris); + + List marks = withIrisGson.decode(Target.BIOME, new JSONObject("{\"marks\": [\"a\", \"b\"]}"), "biome desert/dunes") + .find(MarksSettings.class).orElseThrow().marks; + + assertEquals(List.of(marked, marked), marks); } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/ObjectPlacementModuleSettingsTest.java b/core/src/test/java/art/arcane/iris/core/modules/ObjectPlacementModuleSettingsTest.java index 52907ab7d..19dd51cac 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ObjectPlacementModuleSettingsTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ObjectPlacementModuleSettingsTest.java @@ -96,7 +96,7 @@ public class ObjectPlacementModuleSettingsTest { public void install(StageGraph graph) { graph.define(TOP).when(GlowSettings.class).requires(BlocksStages.COMPLETE, AnchorStages.FINAL).run((context, glow) -> { int y = context.output(AnchorStages.FINAL).y() + 1; - context.access().set(new PlacedBlock(new BlockPosition(0, y, 0), com.volmit.block.BlockState.parse(glow.block), Optional.empty())); + context.access().set(new PlacedBlock(new BlockPosition(0, y, 0), com.volmit.block.BlockState.parse(glow.getFirst().value().block), Optional.empty())); }); } } @@ -119,7 +119,7 @@ public class ObjectPlacementModuleSettingsTest { data = mock(IrisData.class); pack = BuiltInPlacementPack.serve(data, folder, List.of(new GlowModule())); - ModuleSettingsDecoder decoder = new ModuleSettingsDecoder(pack.catalog(), folder.getRoot().toPath()); + ModuleSettingsDecoder decoder = new ModuleSettingsDecoder(pack.catalog(), folder.getRoot().toPath(), Gson::new); gson = new GsonBuilder().registerTypeAdapterFactory(new ObjectPlacementSettingsReader(() -> decoder)).create(); } 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 index 8d9be5ed8..f8785e820 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PackModuleSetTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PackModuleSetTest.java @@ -18,6 +18,7 @@ package art.arcane.iris.core.modules; +import com.google.gson.Gson; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -37,7 +38,7 @@ public class PackModuleSetTest { @Test public void loadsOnFirstUseAndClosesWithItsOwner() throws IOException { - PackModuleSet modules = new PackModuleSet(folder.newFolder("plain")); + PackModuleSet modules = new PackModuleSet(folder.newFolder("plain"), Gson::new); assertSame(modules.pack(), modules.pack()); assertTrue(modules.pack().packModules().isEmpty()); @@ -50,7 +51,7 @@ public class PackModuleSetTest { 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); + PackModuleSet modules = new PackModuleSet(pack, Gson::new); PackModulesException first = assertThrows(PackModulesException.class, modules::pack); PackModulesException second = assertThrows(PackModulesException.class, modules::settings); diff --git a/core/src/test/java/art/arcane/iris/core/modules/PerfectionModuleTest.java b/core/src/test/java/art/arcane/iris/core/modules/PerfectionModuleTest.java index a7eea117b..3e9d3d84d 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PerfectionModuleTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PerfectionModuleTest.java @@ -22,10 +22,8 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineMetrics; import art.arcane.iris.engine.framework.SeedManager; -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.dimension.IrisDimensionModeType; -import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; @@ -119,7 +117,7 @@ public class PerfectionModuleTest { } private void generate() { - ModuleChunkGeneration.generate(pack, engine, 0, 0, blocks, null, new IrisRegion(), new IrisBiome(), key -> block(key, false)); + ModuleChunkGeneration.generate(pack, engine, 0, 0, blocks, null, key -> block(key, false)); } private static PlatformBlockState decorant(boolean held) { diff --git a/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java b/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java index 94cbba93b..16366898a 100644 --- a/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java +++ b/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java @@ -255,14 +255,16 @@ public class SchemaBuilderParityTest { } @Test - public void objectPlacementSchemaRendersModuleSettingsUnderTheirIdAndAlias() throws IOException { + public void objectPlacementSchemaRendersModuleSettingsUnderTheirIdAndAliasWithTheirShorthand() throws IOException { JSONObject schema = new SchemaBuilder(IrisObjectPlacement.class, structureSchemaData(glowModuleSchema())).construct(); JSONObject properties = rootProperties(schema); - String definition = definitionKey(properties.getJSONObject("example:glow")); + JSONArray forms = properties.getJSONObject("example:glow").getJSONArray("anyOf"); + String definition = definitionKey(forms.getJSONObject(0)); JSONObject level = schema.getJSONObject("definitions").getJSONObject(definition) .getJSONObject("properties").getJSONObject("level"); - assertEquals(definition, definitionKey(properties.getJSONObject("glow"))); + assertEquals(definition, definitionKey(properties.getJSONObject("glow").getJSONArray("anyOf").getJSONObject(0))); + assertEquals("settings with one option also take its bare value", "integer", forms.getJSONObject(1).getString("type")); assertEquals("integer", level.getString("type")); assertEquals(1, level.getInt("minimum")); assertEquals(15, level.getInt("maximum"));