Loot tables, spawners, entities and markers are resource kinds of iris:loot and iris:spawn

LootResources and SpawnResources keep the folders and lookups by key; LootValidator is the loot check that was Iris's
PackLootValidator.
This commit is contained in:
piexel committed 2026-10-09 22:24:20 +02:00
1 parent 910eab1f79
commit 8428da4f50
12 files changed
+499 -16

No files matched your search

@@ -70,7 +70,7 @@ public final class LootGiving implements Loot {
@Override
public List<ItemDrop> items(PackWorld world, Site site, String key) {
Engine engine = engine(world);
IrisLootTable table = engine.getData().getLootLoader().load(key);
IrisLootTable table = LootResources.table(engine.getData(), key);
if (table == null) {
return List.of();
}
@@ -26,8 +26,8 @@ import com.volmit.service.Loot;
import com.volmit.stage.StageGraph;
/**
* Module {@code iris:loot}: the loot tables of the pack and the items they and the block drops of the dimension, regions
* and biomes give. It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through
* Module {@code iris:loot}: the loot tables of the pack ({@link LootResources}) and the items they and the block drops
* of the dimension, regions and biomes give. It checks the tables and the references to them ({@link LootValidator}). It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through
* {@link BlockDrops} when a player breaks a block.
*/
public final class LootModule implements IrisModule {
@@ -44,6 +44,8 @@ public final class LootModule implements IrisModule {
@Override
public void register(FeatureRegistry registry) {
LootResources.kinds().forEach(registry::registerResourceKind);
registry.registerValidator(new LootValidator());
registry.registerService(Loot.class, new LootGiving());
registry.registerService(BlockDrops.class, new BlockDropping());
}
@@ -0,0 +1,78 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.IrisPackResources;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.volmlib.util.collection.KList;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import java.util.List;
/**
* The resource kind of module {@code iris:loot}, which keeps the folder and files Iris packs have always used, and
* lookups by pack key for code that still names loot tables by key. Every lookup goes through the pack's
* {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot.
* <p>
* Lookups answer null where Iris's loader did: for a blank key, a key the pack has no file for, and a file that fails
* to load, which was reported when it was read.
*/
public final class LootResources {
/** Loot tables, in {@code loot/}. */
public static final ResourceKind<IrisLootTable> TABLES = ResourceKind.of("iris:loot/table", "loot", IrisLootTable.class);
private LootResources() {
}
/** Every resource kind of the loot module. */
public static List<ResourceKind<?>> kinds() {
return List.of(TABLES);
}
public static IrisLootTable table(IrisData data, String key) {
if (key == null || key.isBlank()) {
return null;
}
IrisPackResources resources = data.getPackResources();
try {
return resources.find(TABLES.key(resources.idOf(key))).orElse(null);
} catch (IllegalStateException failedToLoad) {
return null;
}
}
/** The tables of the pack named by {@code keys}, in order, without the ones the pack lacks. */
public static KList<IrisLootTable> tables(IrisData data, List<String> keys) {
KList<IrisLootTable> tables = new KList<>();
for (String key : keys) {
IrisLootTable table = table(data, key);
if (table != null) {
tables.add(table);
}
}
return tables;
}
/** The key of every loot table of the pack, in key order. */
public static List<String> tableKeys(IrisData data) {
return data.getPackResources().ids(TABLES.type()).stream().map(ResourceId::path).toList();
}
}
@@ -0,0 +1,286 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.core.modules.IrisValidationContext;
import art.arcane.iris.core.pack.PackIntegerChecks;
import art.arcane.iris.core.pack.PackValidationIo;
import art.arcane.iris.engine.object.loot.IrisLoot;
import art.arcane.iris.engine.object.loot.IrisLootReference;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import com.volmit.validation.Problem;
import com.volmit.validation.Subject;
import com.volmit.validation.ValidationContext;
import com.volmit.validation.Validator;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot
* reference of a dimension, region or biome names a table the pack has. The files are read as written, like the pack
* validator's other file checks, so a malformed table is reported rather than failing the load.
*/
public final class LootValidator implements Validator {
private static final List<String> LOOT_HOST_FOLDERS = List.of("dimensions", "regions", "biomes");
private static final String JSON_EXTENSION = ".json";
@Override
public void validate(ValidationContext pack) {
check(IrisValidationContext.of(pack).data().getDataFolder()).forEach(pack::report);
}
/** What is wrong with the loot tables and loot references of the pack in {@code packFolder}. */
public static List<Problem> check(File packFolder) {
List<Problem> problems = new ArrayList<>();
if (packFolder == null || !packFolder.isDirectory()) {
return problems;
}
File lootFolder = new File(packFolder, LootResources.TABLES.folder());
Set<String> lootKeys = keysOf(lootFolder);
checkTables(lootFolder, problems);
for (String folderName : LOOT_HOST_FOLDERS) {
checkReferences(new File(packFolder, folderName), folderName, lootKeys, problems);
}
return problems;
}
private static void checkTables(File lootFolder, List<Problem> problems) {
if (!lootFolder.isDirectory()) {
return;
}
List<File> lootFiles = PackValidationIo.listJsonRecursive(lootFolder);
lootFiles.sort(Comparator.comparing(File::getPath));
for (File lootFile : lootFiles) {
String lootKey = PackValidationIo.deriveKey(lootFolder, lootFile);
List<String> errors = new ArrayList<>();
JSONObject table = readTable(lootFile, lootKey, errors);
if (table != null) {
validateLootTable(lootKey, table, errors);
}
report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors);
}
}
private static void checkReferences(File resourceFolder, String folderName, Set<String> lootKeys, List<Problem> problems) {
if (!resourceFolder.isDirectory()) {
return;
}
List<File> resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder);
resourceFiles.sort(Comparator.comparing(File::getPath));
for (File resourceFile : resourceFiles) {
JSONObject resource = PackValidationIo.readJson(resourceFile);
if (resource == null || !resource.has("loot")) {
continue;
}
String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile);
List<String> errors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
validateLootReference(hostType(folderName), resourceKey, resource.opt("loot"), lootKeys, errors, warnings);
Subject subject = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION);
report(problems, Problem::error, subject, errors);
report(problems, Problem::warning, subject, warnings);
}
}
private static void report(List<Problem> problems, java.util.function.BiFunction<Subject, String, Problem> severity,
Subject subject, List<String> messages) {
for (String message : messages) {
problems.add(severity.apply(subject, message));
}
}
private static Set<String> keysOf(File folder) {
Set<String> keys = new HashSet<>();
if (!folder.isDirectory()) {
return keys;
}
for (File file : PackValidationIo.listJsonRecursive(folder)) {
String key = PackValidationIo.deriveKey(folder, file);
if (key != null && !key.isBlank()) {
keys.add(key);
}
}
return keys;
}
private static JSONObject readTable(File file, String key, List<String> errors) {
try {
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8));
} catch (IOException | RuntimeException e) {
String reason = e.getMessage();
if (reason == null || reason.isBlank()) {
reason = e.getClass().getSimpleName();
}
errors.add("Loot table '" + key + "' has invalid JSON: " + reason);
return null;
}
}
private static String hostType(String folderName) {
return switch (folderName) {
case "dimensions" -> "Dimension";
case "regions" -> "Region";
case "biomes" -> "Biome";
default -> "Resource";
};
}
private static void validateLootTable(String lootKey, JSONObject table, List<String> blockingErrors) {
String path = "Loot table '" + lootKey + "'";
Integer rarity = PackIntegerChecks.integerField(table, "rarity", 1, path, blockingErrors);
Integer minimumPicked = PackIntegerChecks.integerField(table, "minPicked", 1, path, blockingErrors);
Integer maximumPicked = PackIntegerChecks.integerField(table, "maxPicked", 5, path, blockingErrors);
Integer maximumTries = PackIntegerChecks.integerField(table, "maxTries", 10, path, blockingErrors);
PackIntegerChecks.requireMinimum(path + ".rarity", rarity, 1, blockingErrors);
PackIntegerChecks.requireMinimum(path + ".minPicked", minimumPicked, 0, blockingErrors);
PackIntegerChecks.requireMinimum(path + ".maxPicked", maximumPicked, 1, blockingErrors);
PackIntegerChecks.requireMinimum(path + ".maxTries", maximumTries, 1, blockingErrors);
PackIntegerChecks.requireMaximum(path + ".minPicked", minimumPicked, IrisLootTable.MAX_PICKED, blockingErrors);
PackIntegerChecks.requireMaximum(path + ".maxPicked", maximumPicked, IrisLootTable.MAX_PICKED, blockingErrors);
PackIntegerChecks.requireMaximum(path + ".maxTries", maximumTries, IrisLootTable.MAX_TRIES, blockingErrors);
PackIntegerChecks.requireOrdered(path + ".minPicked", minimumPicked, path + ".maxPicked", maximumPicked, blockingErrors);
JSONArray entries = table.optJSONArray("loot");
if (entries == null || entries.length() == 0) {
blockingErrors.add(path + ".loot must be a non-empty array.");
return;
}
for (int entryIndex = 0; entryIndex < entries.length(); entryIndex++) {
JSONObject entry = entries.optJSONObject(entryIndex);
String entryPath = path + ".loot[" + entryIndex + "]";
if (entry == null) {
blockingErrors.add(entryPath + " must be an object.");
continue;
}
String type = entry.optString("type", "").trim();
if (type.isEmpty()) {
blockingErrors.add(entryPath + ".type must not be blank.");
}
Integer entryRarity = PackIntegerChecks.integerField(entry, "rarity", 1, entryPath, blockingErrors);
Integer minimumAmount = PackIntegerChecks.integerField(entry, "minAmount", 1, entryPath, blockingErrors);
Integer maximumAmount = PackIntegerChecks.integerField(entry, "maxAmount", 1, entryPath, blockingErrors);
PackIntegerChecks.requireMinimum(entryPath + ".rarity", entryRarity, 1, blockingErrors);
PackIntegerChecks.requireMinimum(entryPath + ".minAmount", minimumAmount, 1, blockingErrors);
PackIntegerChecks.requireMinimum(entryPath + ".maxAmount", maximumAmount, 1, blockingErrors);
PackIntegerChecks.requireMaximum(entryPath + ".minAmount", minimumAmount, IrisLoot.MAX_AMOUNT, blockingErrors);
PackIntegerChecks.requireMaximum(entryPath + ".maxAmount", maximumAmount, IrisLoot.MAX_AMOUNT, blockingErrors);
PackIntegerChecks.requireOrdered(entryPath + ".minAmount", minimumAmount,
entryPath + ".maxAmount", maximumAmount, blockingErrors);
validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors);
}
}
private static void validateLootEnchantments(String entryPath, Object rawEnchantments,
List<String> blockingErrors) {
if (rawEnchantments == null || rawEnchantments == JSONObject.NULL) {
return;
}
if (!(rawEnchantments instanceof JSONArray enchantments)) {
blockingErrors.add(entryPath + ".enchantments must be an array.");
return;
}
for (int enchantmentIndex = 0; enchantmentIndex < enchantments.length(); enchantmentIndex++) {
JSONObject enchantment = enchantments.optJSONObject(enchantmentIndex);
String enchantmentPath = entryPath + ".enchantments[" + enchantmentIndex + "]";
if (enchantment == null) {
blockingErrors.add(enchantmentPath + " must be an object.");
continue;
}
if (enchantment.optString("enchantment", "").isBlank()) {
blockingErrors.add(enchantmentPath + ".enchantment must not be blank.");
}
Integer minimumLevel = PackIntegerChecks.integerField(enchantment, "minLevel", 1, enchantmentPath, blockingErrors);
Integer maximumLevel = PackIntegerChecks.integerField(enchantment, "maxLevel", 1, enchantmentPath, blockingErrors);
PackIntegerChecks.requireMinimum(enchantmentPath + ".minLevel", minimumLevel, 1, blockingErrors);
PackIntegerChecks.requireMinimum(enchantmentPath + ".maxLevel", maximumLevel, 1, blockingErrors);
PackIntegerChecks.requireOrdered(enchantmentPath + ".minLevel", minimumLevel,
enchantmentPath + ".maxLevel", maximumLevel, blockingErrors);
if (enchantment.has("chance")) {
Object rawChance = enchantment.opt("chance");
if (!(rawChance instanceof Number number)
|| !Double.isFinite(number.doubleValue())
|| number.doubleValue() < 0D
|| number.doubleValue() > 1D) {
blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1.");
}
}
}
}
private static void validateLootReference(String resourceType, String resourceKey, Object rawLoot,
Set<String> lootKeys, List<String> blockingErrors, List<String> warnings) {
String path = resourceType + " '" + resourceKey + "'.loot";
if (!(rawLoot instanceof JSONObject reference)) {
blockingErrors.add(path + " must be an object.");
return;
}
boolean clearMode = false;
if (reference.has("mode")) {
Object rawMode = reference.opt("mode");
if (!(rawMode instanceof String mode)
|| !Set.of("ADD", "CLEAR", "REPLACE", "FALLBACK").contains(mode)) {
blockingErrors.add(path + ".mode must be ADD, CLEAR, REPLACE, or FALLBACK.");
} else {
clearMode = "CLEAR".equals(mode);
}
}
if (reference.has("multiplier")) {
Object rawMultiplier = reference.opt("multiplier");
if (!(rawMultiplier instanceof Number multiplier)
|| !Double.isFinite(multiplier.doubleValue())
|| multiplier.doubleValue() < 0D
|| multiplier.doubleValue() > IrisLootReference.MAX_MULTIPLIER) {
blockingErrors.add(path + ".multiplier must be a finite number from 0 to "
+ (int) IrisLootReference.MAX_MULTIPLIER + ".");
}
}
if (!reference.has("tables")) {
return;
}
JSONArray tables = reference.optJSONArray("tables");
if (tables == null) {
blockingErrors.add(path + ".tables must be an array.");
return;
}
if (clearMode && tables.length() > 0) {
warnings.add(path + " uses mode CLEAR and lists " + tables.length()
+ " table(s); CLEAR clears parent tables and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them.");
}
for (int tableIndex = 0; tableIndex < tables.length(); tableIndex++) {
Object rawTableKey = tables.opt(tableIndex);
if (!(rawTableKey instanceof String tableKey) || tableKey.isBlank()) {
blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table.");
} else if (!lootKeys.contains(tableKey)) {
blockingErrors.add(path + ".tables[" + tableIndex
+ "] references missing loot table '" + tableKey + "'.");
}
}
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.engine.object.entity;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.iris.engine.object.value.IRare;
@@ -60,6 +61,6 @@ public class IrisEntitySpawn implements IRare {
private transient IrisMarker referenceMarker;
public IrisEntity getRealEntity(Engine g) {
return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity()));
return ent.aquire(() -> SpawnResources.entity(g.getData(), getEntity()));
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.engine.object.entity.spawn;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.volmlib.util.collection.KMap;
import lombok.EqualsAndHashCode;
@@ -23,7 +24,7 @@ public class IrisSpawnerCooldowns {
public void cleanup(Engine engine) {
cooldowns.values().removeIf(cd -> {
IrisSpawner sp = engine.getData().getSpawnerLoader().load(cd.getSpawner());
IrisSpawner sp = SpawnResources.spawner(engine.getData(), cd.getSpawner());
return sp == null || cd.canSpawn(sp.getMaximumRate());
});
}
@@ -18,6 +18,7 @@
package art.arcane.iris.engine.object.loot;
import art.arcane.iris.engine.loot.LootResources;
import art.arcane.iris.engine.data.cache.AtomicCache;
import art.arcane.iris.engine.object.annotations.ArrayType;
import art.arcane.iris.engine.object.annotations.Desc;
@@ -59,7 +60,7 @@ public class IrisLootReference {
KList<IrisLootTable> t = new KList<>();
for (String i : tables) {
t.add(g.getData().getLootLoader().load(i));
t.add(LootResources.table(g.getData(), i));
}
return t;
@@ -18,6 +18,7 @@
package art.arcane.iris.engine.object.placement;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.builtin.blocks.ObjectMarkers;
import art.arcane.iris.builtin.blocks.WrittenBlocks;
@@ -196,7 +197,7 @@ public final class BlocksModule implements IrisModule {
RNG markerRandom = new RNG(context.random().nextLong());
int salt = 0;
for (IrisObjectMarker markerConfig : config.getMarkers()) {
IrisMarker marker = placement.object().getLoader().getMarkerLoader().load(markerConfig.getMarker());
IrisMarker marker = SpawnResources.marker(placement.object().getLoader(), markerConfig.getMarker());
int markerSalt = salt++;
if (marker == null) {
continue;
@@ -18,6 +18,7 @@
package art.arcane.iris.engine.object.placement;
import art.arcane.iris.engine.loot.LootResources;
import art.arcane.iris.core.modules.ModuleSettings;
import art.arcane.iris.engine.object.loot.IObjectLoot;
import art.arcane.iris.engine.object.loot.IrisLootTable;
@@ -301,7 +302,7 @@ public class IrisObjectPlacement {
TableCache cache = new TableCache();
cache.merge(getCache(manager, getVanillaLoot(), IrisObjectPlacement::getVanillaTable));
cache.merge(getCache(manager, getLoot(), manager.getLootLoader()::load));
cache.merge(getCache(manager, getLoot(), key -> LootResources.table(manager, key)));
return cache;
});
@@ -76,7 +76,7 @@ public final class EntitySpawning implements EntitySpawns {
if (count <= 0) {
return;
}
IrisSpawner spawner = engine(world).getData().getSpawnerLoader().load(plan.spawner());
IrisSpawner spawner = SpawnResources.spawner(engine(world).getData(), plan.spawner());
if (spawner != null) {
spawner.spawn(engine(world), plan.chunkX(), plan.chunkZ());
}
@@ -84,7 +84,7 @@ public final class EntitySpawning implements EntitySpawns {
@Override
public Optional<EntitySpec> entity(PackWorld world, String key) {
IrisEntity entity = engine(world).getData().getEntityLoader().load(key);
IrisEntity entity = SpawnResources.entity(engine(world).getData(), key);
if (entity == null) {
return Optional.empty();
}
@@ -97,14 +97,14 @@ public final class EntitySpawning implements EntitySpawns {
return Optional.empty();
}
Engine engine = engine(world);
IrisMarker marker = engine.getData().getMarkerLoader().load(tag);
IrisMarker marker = SpawnResources.marker(engine.getData(), tag);
if (marker == null) {
return Optional.empty();
}
List<String> spawners = new ArrayList<>();
for (String key : marker.getSpawners()) {
if (engine.getData().getSpawnerLoader().load(key) == null) {
if (SpawnResources.spawner(engine.getData(), key) == null) {
IrisLogging.error("Cannot load spawner: " + key + " for marker " + tag);
continue;
}
@@ -175,8 +175,8 @@ public final class EntitySpawning implements EntitySpawns {
}
private Optional<Plan> planMarker(PackWorld world, Engine engine, Marker marker) {
IrisSpawner spawner = engine.getData().getSpawnerLoader().load(marker.spawner());
IrisMarker irisMarker = engine.getData().getMarkerLoader().load(marker.marker());
IrisSpawner spawner = SpawnResources.spawner(engine.getData(), marker.spawner());
IrisMarker irisMarker = SpawnResources.marker(engine.getData(), marker.marker());
if (spawner == null) {
return Optional.empty();
}
@@ -234,7 +234,7 @@ public final class EntitySpawning implements EntitySpawns {
}
private static KList<IrisSpawner> shuffled(Engine engine, KList<String> keys) {
return engine.getData().getSpawnerLoader().loadAll(keys).shuffleCopy(RNG.r);
return SpawnResources.spawners(engine.getData(), keys).shuffleCopy(RNG.r);
}
private static Stream<Candidate> spawnsOf(IrisSpawner spawner, boolean initial) {
@@ -25,7 +25,7 @@ import com.volmit.service.EntitySpawns;
import com.volmit.stage.StageGraph;
/**
* Module {@code iris:spawn}: the spawners, entities and markers of the pack, and the entities that appear in the world
* Module {@code iris:spawn}: the spawners, entities and markers of the pack ({@link SpawnResources}), and the entities that appear in the world
* over time because of them. It has no generation stage; Iris asks it through {@link EntitySpawns} when it looks for
* something to spawn in a chunk or at a marker.
*/
@@ -43,6 +43,7 @@ public final class SpawnModule implements IrisModule {
@Override
public void register(FeatureRegistry registry) {
SpawnResources.kinds().forEach(registry::registerResourceKind);
registry.registerService(EntitySpawns.class, new EntitySpawning());
}
}
@@ -0,0 +1,111 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.spawn;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.IrisPackResources;
import art.arcane.iris.engine.object.entity.IrisEntity;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.volmlib.util.collection.KList;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import java.util.List;
/**
* The resource kinds of module {@code iris:spawn}, which keep the folders and files Iris packs have always used, and
* lookups by pack key for code that still names spawners, entities and markers by key. Every lookup goes through the
* pack's {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot.
* <p>
* Lookups answer null where Iris's loaders did: for a blank key, a key the pack has no file for, and a file that fails
* to load, which was reported when it was read.
*/
public final class SpawnResources {
/** Spawners, in {@code spawners/}. */
public static final ResourceKind<IrisSpawner> SPAWNERS = ResourceKind.of("iris:spawn/spawner", "spawners", IrisSpawner.class);
/** Entities, in {@code entities/}. */
public static final ResourceKind<IrisEntity> ENTITIES = ResourceKind.of("iris:spawn/entity", "entities", IrisEntity.class);
/** Markers, in {@code markers/}. */
public static final ResourceKind<IrisMarker> MARKERS = ResourceKind.of("iris:spawn/marker", "markers", IrisMarker.class);
private SpawnResources() {
}
/** Every resource kind of the spawn module. */
public static List<ResourceKind<?>> kinds() {
return List.of(SPAWNERS, ENTITIES, MARKERS);
}
public static IrisSpawner spawner(IrisData data, String key) {
return find(data, SPAWNERS, key);
}
public static IrisEntity entity(IrisData data, String key) {
return find(data, ENTITIES, key);
}
public static IrisMarker marker(IrisData data, String key) {
return find(data, MARKERS, key);
}
/** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */
public static KList<IrisSpawner> spawners(IrisData data, List<String> keys) {
KList<IrisSpawner> spawners = new KList<>();
for (String key : keys) {
IrisSpawner spawner = spawner(data, key);
if (spawner != null) {
spawners.add(spawner);
}
}
return spawners;
}
/** The key of every entity of the pack, in key order. */
public static List<String> entityKeys(IrisData data) {
return keys(data, ENTITIES);
}
/** The key of every spawner of the pack, in key order. */
public static List<String> spawnerKeys(IrisData data) {
return keys(data, SPAWNERS);
}
/** The key of every marker of the pack, in key order. */
public static List<String> markerKeys(IrisData data) {
return keys(data, MARKERS);
}
private static <T> T find(IrisData data, ResourceKind<T> kind, String key) {
if (key == null || key.isBlank()) {
return null;
}
IrisPackResources resources = data.getPackResources();
try {
return resources.find(kind.key(resources.idOf(key))).orElse(null);
} catch (IllegalStateException failedToLoad) {
return null;
}
}
/** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */
private static List<String> keys(IrisData data, ResourceKind<?> kind) {
return data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList();
}
}