iris:loot and iris:spawn onto the module surface and into iris-builtins.jar: no engine, IrisData, IrisPlatforms or Bukkit types; the validator checks the decoded tables and references

This commit is contained in:
piexel committed 2026-10-10 18:21:31 +02:00
1 parent 347c69b0a2
commit 48ff0908e2
19 files changed
+445 -510

No files matched your search

@@ -18,16 +18,12 @@
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.Level;
import art.arcane.iris.builtin.loot.BlockDrop;
import art.arcane.iris.builtin.loot.BlockDropSettings;
import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.item.ItemDrop;
import com.volmit.service.BlockDrops;
@@ -45,19 +41,17 @@ import java.util.concurrent.ConcurrentMap;
public final class BlockDropping implements BlockDrops {
@Override
public Result drops(PackWorld world, Broken broken) {
Engine engine = IrisPackWorld.of(world).engine();
LiveWorld live = LiveWorld.of(world);
int x = broken.position().x();
int y = broken.position().y();
int z = broken.position().z();
String brokenKey = IrisPlatforms.get().registries().block(broken.block().key()).key();
String brokenKey = world.resources().blocks().resolve(broken.block()).key();
ResolvedDrops resolved = world.state(ResolvedDrops.class, ignored -> new ResolvedDrops());
IrisBiome biome = engine.getBiome(x, y, z);
List<ResolvedBlockDrop> providers = dropsFor(biome, brokenKey, resolved, world);
List<ResolvedBlockDrop> providers = dropsFor(live, Level.BIOME, x, y, z, brokenKey, resolved, world);
if (providers.stream().noneMatch(provider -> provider.drop().skipParents())) {
IrisRegion region = engine.getRegion(x, z);
providers.addAll(dropsFor(region, brokenKey, resolved, world));
providers.addAll(dropsFor(engine.getDimension(), brokenKey, resolved, world));
providers.addAll(dropsFor(live, Level.REGION, x, y, z, brokenKey, resolved, world));
providers.addAll(dropsFor(live, Level.DIMENSION, x, y, z, brokenKey, resolved, world));
}
LootItems items = new LootItems(world.resources().items(), false);
@@ -79,9 +73,10 @@ public final class BlockDropping implements BlockDrops {
}
}
private static List<ResolvedBlockDrop> dropsFor(IrisRegistrant owner, String brokenKey, ResolvedDrops resolved, PackWorld world) {
private static List<ResolvedBlockDrop> dropsFor(LiveWorld live, Level level, int x, int y, int z, String brokenKey,
ResolvedDrops resolved, PackWorld world) {
List<ResolvedBlockDrop> matching = new ArrayList<>();
for (BlockDrop drop : owner.getModuleSettings().find(BlockDropSettings.class).map(BlockDropSettings::drops).orElse(List.of())) {
for (BlockDrop drop : live.settings(BlockDropSettings.class, level, x, y, z).map(BlockDropSettings::drops).orElse(List.of())) {
ResolvedBlockDrop candidate = resolved.of(drop, world);
if (candidate.dropsFor(brokenKey)) {
matching.add(candidate);
@@ -18,14 +18,11 @@
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.builtin.IrisSeed;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.ObjectLoots;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.framework.PlacedObject;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.item.ItemDrop;
import com.volmit.service.Loot;
@@ -33,7 +30,7 @@ import com.volmit.world.PackWorld;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Optional;
/**
* How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the
@@ -43,76 +40,48 @@ import java.util.Set;
public final class LootGiving implements Loot {
@Override
public List<Source> tables(PackWorld world, Site site) {
Engine engine = engine(world);
LiveWorld live = LiveWorld.of(world);
int x = site.position().x();
int z = site.position().z();
int relativeY = site.position().y();
int worldY = relativeY + engine.getMinHeight();
RNG rng = LootResolver.containerRng(lootSeed(engine), x, worldY, z);
int worldY = relativeY + live.bottomY();
RNG rng = LootResolver.containerRng(lootSeed(world), x, worldY, z);
List<Source> sources = new ArrayList<>();
boolean objectLootDefined = site.nativeLootDefined();
IrisObjectPlacement placement = site.container() == null ? null : placementAt(engine, x, relativeY, z);
if (placement != null) {
objectLootDefined = objectLootDefined || placement.getLoot().isNotEmpty() || placement.getVanillaLoot().isNotEmpty();
Source picked = placementLoot(world, engine).pick(placement.getVanillaLoot(), placement.getLoot(), platformState(site), rng, x, worldY, z);
Optional<ObjectLoots> objectLoots = site.container() == null ? Optional.empty() : live.objectLoots(x, relativeY, z);
if (objectLoots.isPresent()) {
objectLootDefined = objectLootDefined || objectLoots.get().defined();
Source picked = placementLoot(world, live).pick(objectLoots.get().platformTables(), objectLoots.get().packTables(),
site.container(), rng, x, worldY, z);
if (picked != null) {
sources.add(picked);
if (placement.isOverrideGlobalLoot()) {
if (objectLoots.get().overridesGlobalLoot()) {
return sources;
}
}
}
LootTables.resolveEnvironmentSources(sources, engine, rng, x, relativeY, z, objectLootDefined, Table::new);
LootTables.resolveEnvironmentSources(sources, world, rng, x, relativeY, z, objectLootDefined, Table::new);
return sources;
}
@Override
public List<ItemDrop> items(PackWorld world, Site site, String key) {
Engine engine = engine(world);
LootTable table = LootResources.table(engine.getData(), key);
LootTable table = LootResources.table(world.resources(), key);
if (table == null) {
return List.of();
}
int worldY = site.position().y() + engine.getMinHeight();
int worldY = site.position().y() + LiveWorld.of(world).bottomY();
return new LootItems(world.resources().items(), site.debug())
.draw(key, table, lootSeed(engine), site.position().x(), worldY, site.position().z());
.draw(key, table, lootSeed(world), site.position().x(), worldY, site.position().z());
}
private static PlacementLoot placementLoot(PackWorld world, Engine engine) {
PlatformLootTables platformTables = world.state(PlatformLootTables.class, ignored -> new PlatformLootTables());
return new PlacementLoot(engine.getData(), platformTables::keys, lootSeed(engine), world.log());
private static PlacementLoot placementLoot(PackWorld world, LiveWorld live) {
return new PlacementLoot(world.resources(), live::platformLootTables, lootSeed(world), world.log());
}
private static IrisObjectPlacement placementAt(Engine engine, int x, int relativeY, int z) {
PlacedObject placed = engine.getObjectPlacement(x, relativeY, z);
return placed == null ? null : placed.getPlacement();
}
private static PlatformBlockState platformState(Site site) {
return IrisPlatforms.get().registries().block(site.container().key());
}
private static long lootSeed(Engine engine) {
return engine.getSeedManager().getLoot();
}
private static Engine engine(PackWorld world) {
return IrisPackWorld.of(world).engine();
}
/** The loot table keys of the platform, which do not change while a world runs. */
private static final class PlatformLootTables {
private volatile Set<String> keys;
private Set<String> keys() {
Set<String> known = keys;
if (known == null) {
known = PlacementLoot.platformTableKeys();
keys = known;
}
return known;
}
private static long lootSeed(PackWorld world) {
return IrisSeed.LOOT.of(world);
}
}
@@ -20,6 +20,8 @@ package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.BlockDropSettings;
import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.iris.builtin.loot.ObjectLoot;
import art.arcane.iris.builtin.loot.ObjectVanillaLoot;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
@@ -49,6 +51,8 @@ public final class LootModule implements IrisModule {
public void register(FeatureRegistry registry) {
registry.registerSettings(LootSettings.class);
registry.registerSettings(BlockDropSettings.class);
registry.registerHeldType(ObjectLoot.class);
registry.registerHeldType(ObjectVanillaLoot.class);
LootResources.kinds().forEach(registry::registerResourceKind);
registry.registerValidator(new LootValidator());
registry.registerService(Loot.class, new LootGiving());
@@ -19,8 +19,7 @@
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.IrisPackResources;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
@@ -46,11 +45,10 @@ public final class LootResources {
return List.of(TABLES);
}
public static LootTable table(IrisData data, String key) {
public static LootTable table(PackResources resources, 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) {
@@ -59,7 +57,7 @@ public final class LootResources {
}
/** 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();
public static List<String> tableKeys(PackResources resources) {
return resources.ids(TABLES.type()).stream().map(ResourceId::path).toList();
}
}
@@ -18,14 +18,13 @@
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.Level;
import art.arcane.iris.builtin.loot.LootMode;
import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
@@ -64,9 +63,9 @@ public final class LootTables {
return LootResolver.spatialOneIn(lootSeed, identity, entryIndex, x, y, z, rarity);
}
/** The loot settings a dimension, region or biome declares; the defaults, which add nothing, when it declares none. */
public static LootSettings settingsOf(IrisRegistrant owner) {
return owner.getModuleSettings().find(LootSettings.class).orElseGet(LootSettings::new);
/** The loot settings the level declares at the block; the defaults, which add nothing, when it declares none. */
private static LootSettings settingsAt(LiveWorld live, Level level, int x, int relativeY, int z) {
return live.settings(LootSettings.class, level, x, relativeY, z).orElseGet(LootSettings::new);
}
/**
@@ -76,7 +75,7 @@ public final class LootTables {
*/
public static <T> void resolveEnvironmentSources(
List<T> sources,
Engine engine,
PackWorld world,
RNG rng,
int x,
int relativeY,
@@ -84,31 +83,25 @@ public final class LootTables {
boolean objectLootDefined,
Function<String, T> mapper
) {
IrisRegion region = engine.getComplex().getRegionStream().get(x, z);
IrisBiome surfaceBiome = engine.getComplex().getTrueBiomeStream().get(x, z);
double terrainHeight = engine.getComplex().getHeightStream().get(x, z);
IrisBiome contextualBiome = relativeY < terrainHeight
? engine.getCaveBiome(x, relativeY, z)
: surfaceBiome;
if (contextualBiome == null) {
contextualBiome = surfaceBiome;
}
LiveWorld live = LiveWorld.of(world);
boolean belowSurface = relativeY < live.terrainHeight(x, z);
boolean distinctContextualBiome = belowSurface && !live.caveBiome(x, relativeY, z).equals(live.surfaceBiome(x, z));
LootSettings dimensionLoot = settingsOf(engine.getDimension());
LootSettings regionLoot = settingsOf(region);
LootSettings surfaceLoot = settingsOf(surfaceBiome);
boolean distinctContextualBiome = !sameBiome(surfaceBiome, contextualBiome);
LootSettings dimensionLoot = settingsAt(live, Level.DIMENSION, x, relativeY, z);
LootSettings regionLoot = settingsAt(live, Level.REGION, x, relativeY, z);
LootSettings surfaceLoot = settingsAt(live, Level.SURFACE_BIOME, x, relativeY, z);
double multiplier = dimensionLoot.multiplier() * regionLoot.multiplier() * surfaceLoot.multiplier();
if (distinctContextualBiome) {
multiplier *= settingsOf(contextualBiome).multiplier();
LootSettings contextualLoot = distinctContextualBiome ? settingsAt(live, Level.CAVE_BIOME, x, relativeY, z) : null;
if (contextualLoot != null) {
multiplier *= contextualLoot.multiplier();
}
boolean fallback = !objectLootDefined;
injectReference(sources, dimensionLoot, engine, mapper, fallback);
injectReference(sources, regionLoot, engine, mapper, fallback);
injectReference(sources, surfaceLoot, engine, mapper, fallback);
if (distinctContextualBiome) {
injectReference(sources, settingsOf(contextualBiome), engine, mapper, fallback);
injectReference(sources, dimensionLoot, world, mapper, fallback);
injectReference(sources, regionLoot, world, mapper, fallback);
injectReference(sources, surfaceLoot, world, mapper, fallback);
if (contextualLoot != null) {
injectReference(sources, contextualLoot, world, mapper, fallback);
}
LootResolver.scaleSources(sources, multiplier, rng);
}
@@ -133,25 +126,15 @@ public final class LootTables {
sources.addAll(additions);
}
static boolean sameBiome(IrisBiome first, IrisBiome second) {
if (first == second) {
return true;
}
if (first == null || second == null) {
return false;
}
return Objects.equals(first.getLoadKey(), second.getLoadKey());
}
private static <T> void injectReference(
List<T> sources,
LootSettings loot,
Engine engine,
PackWorld world,
Function<String, T> mapper,
boolean fallback
) {
List<T> additions = loot.tables().stream()
.filter(key -> LootResources.table(engine.getData(), key) != null)
.filter(key -> LootResources.table(world.resources(), key) != null)
.map(mapper)
.filter(Objects::nonNull)
.toList();
@@ -18,269 +18,210 @@
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.builtin.loot.LootEnchantment;
import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.builtin.loot.LootMode;
import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import com.volmit.FeatureAttachment.Target;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
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;
import java.util.function.BiFunction;
/**
* 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.
* reference of a dimension, region or biome names a table the pack has. It checks the tables and settings as they
* decoded; a file that is not valid JSON, or holds a value of the wrong type, is reported by the load that reads it.
*/
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";
private static final String LEVEL_FOLDER_SEPARATOR = "/";
@Override
public void validate(ValidationContext pack) {
check(IrisValidationContext.of(pack).data().getDataFolder()).forEach(pack::report);
checkTables(pack.resources()).forEach(pack::report);
checkReferences(pack).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) {
private static List<Problem> checkTables(PackResources resources) {
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);
for (ResourceId id : resources.ids(LootTable.class)) {
String lootKey = id.path();
List<String> errors = new ArrayList<>();
JSONObject table = readTable(lootFile, lootKey, errors);
LootTable table = readTable(resources, id, lootKey, errors);
if (table != null) {
validateLootTable(lootKey, table, errors);
}
report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors);
}
return problems;
}
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);
private static List<Problem> checkReferences(ValidationContext pack) {
Set<ResourceId> lootIds = Set.copyOf(pack.resources().ids(LootTable.class));
List<Problem> problems = new ArrayList<>();
List<Entry<LootSettings>> declared = new ArrayList<>(pack.settings().declared(LootSettings.class));
declared.sort(Comparator.comparing(Entry<LootSettings>::level).thenComparing(Entry::source));
for (Entry<LootSettings> entry : declared) {
String resourceKey = keyOf(entry);
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);
validateLootReference(pack.resources(), hostType(entry.level()), resourceKey, entry.value(), lootIds, errors, warnings);
Subject subject = Subject.file(folderOf(entry.level()) + "/" + resourceKey + JSON_EXTENSION);
report(problems, Problem::error, subject, errors);
report(problems, Problem::warning, subject, warnings);
}
return problems;
}
private static void report(List<Problem> problems, java.util.function.BiFunction<Subject, String, Problem> severity,
private static void report(List<Problem> problems, 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) {
private static LootTable readTable(PackResources resources, ResourceId id, 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 resources.find(LootResources.TABLES.key(id)).orElse(null);
} catch (IllegalStateException failedToLoad) {
errors.add("Loot table '" + key + "' cannot be read; the log says what is wrong with the file.");
return null;
}
}
private static String hostType(String folderName) {
return switch (folderName) {
case "dimensions" -> "Dimension";
case "regions" -> "Region";
case "biomes" -> "Biome";
default -> "Resource";
/** The key of the dimension, region or biome that declared {@code entry}: its source id is {@code <pack>:<level>/<key>}. */
private static String keyOf(Entry<LootSettings> entry) {
String path = entry.source().path();
return path.substring(path.indexOf(LEVEL_FOLDER_SEPARATOR) + 1);
}
private static String hostType(Target level) {
return switch (level) {
case DIMENSION -> "Dimension";
case REGION -> "Region";
case BIOME -> "Biome";
case OBJECT_PLACEMENT -> "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, LootTable.MAX_PICKED, blockingErrors);
PackIntegerChecks.requireMaximum(path + ".maxPicked", maximumPicked, LootTable.MAX_PICKED, blockingErrors);
PackIntegerChecks.requireMaximum(path + ".maxTries", maximumTries, LootTable.MAX_TRIES, blockingErrors);
PackIntegerChecks.requireOrdered(path + ".minPicked", minimumPicked, path + ".maxPicked", maximumPicked, blockingErrors);
private static String folderOf(Target level) {
return switch (level) {
case DIMENSION -> "dimensions";
case REGION -> "regions";
case BIOME -> "biomes";
case OBJECT_PLACEMENT -> "placements";
};
}
JSONArray entries = table.optJSONArray("loot");
if (entries == null || entries.length() == 0) {
private static void validateLootTable(String lootKey, LootTable table, List<String> blockingErrors) {
String path = "Loot table '" + lootKey + "'";
requireMinimum(path + ".rarity", table.rarity(), 1, blockingErrors);
requireMinimum(path + ".minPicked", table.minPicked(), 0, blockingErrors);
requireMinimum(path + ".maxPicked", table.maxPicked(), 1, blockingErrors);
requireMinimum(path + ".maxTries", table.maxTries(), 1, blockingErrors);
requireMaximum(path + ".minPicked", table.minPicked(), LootTable.MAX_PICKED, blockingErrors);
requireMaximum(path + ".maxPicked", table.maxPicked(), LootTable.MAX_PICKED, blockingErrors);
requireMaximum(path + ".maxTries", table.maxTries(), LootTable.MAX_TRIES, blockingErrors);
requireOrdered(path + ".minPicked", table.minPicked(), path + ".maxPicked", table.maxPicked(), blockingErrors);
List<LootEntry> entries = table.loot();
if (entries.isEmpty()) {
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, LootEntry.MAX_AMOUNT, blockingErrors);
PackIntegerChecks.requireMaximum(entryPath + ".maxAmount", maximumAmount, LootEntry.MAX_AMOUNT, blockingErrors);
PackIntegerChecks.requireOrdered(entryPath + ".minAmount", minimumAmount,
entryPath + ".maxAmount", maximumAmount, blockingErrors);
validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors);
for (int entryIndex = 0; entryIndex < entries.size(); entryIndex++) {
validateLootEntry(path + ".loot[" + entryIndex + "]", entries.get(entryIndex), blockingErrors);
}
}
private static void validateLootEnchantments(String entryPath, Object rawEnchantments,
List<String> blockingErrors) {
if (rawEnchantments == null || rawEnchantments == JSONObject.NULL) {
private static void validateLootEntry(String entryPath, LootEntry entry, List<String> blockingErrors) {
if (entry == null) {
blockingErrors.add(entryPath + " must be an object.");
return;
}
if (!(rawEnchantments instanceof JSONArray enchantments)) {
blockingErrors.add(entryPath + ".enchantments must be an array.");
return;
if (entry.type().trim().isEmpty()) {
blockingErrors.add(entryPath + ".type must not be blank.");
}
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.");
}
}
requireMinimum(entryPath + ".rarity", entry.rarity(), 1, blockingErrors);
requireMinimum(entryPath + ".minAmount", entry.minAmount(), 1, blockingErrors);
requireMinimum(entryPath + ".maxAmount", entry.maxAmount(), 1, blockingErrors);
requireMaximum(entryPath + ".minAmount", entry.minAmount(), LootEntry.MAX_AMOUNT, blockingErrors);
requireMaximum(entryPath + ".maxAmount", entry.maxAmount(), LootEntry.MAX_AMOUNT, blockingErrors);
requireOrdered(entryPath + ".minAmount", entry.minAmount(), entryPath + ".maxAmount", entry.maxAmount(), blockingErrors);
List<LootEnchantment> enchantments = entry.enchantments();
for (int enchantmentIndex = 0; enchantmentIndex < enchantments.size(); enchantmentIndex++) {
validateEnchantment(entryPath + ".enchantments[" + enchantmentIndex + "]", enchantments.get(enchantmentIndex), blockingErrors);
}
}
private static void validateLootReference(String resourceType, String resourceKey, Object rawLoot,
Set<String> lootKeys, List<String> blockingErrors, List<String> warnings) {
private static void validateEnchantment(String enchantmentPath, LootEnchantment enchantment, List<String> blockingErrors) {
if (enchantment == null) {
blockingErrors.add(enchantmentPath + " must be an object.");
return;
}
String name = enchantment.enchantment();
if (name == null || name.isBlank()) {
blockingErrors.add(enchantmentPath + ".enchantment must not be blank.");
}
requireMinimum(enchantmentPath + ".minLevel", enchantment.minLevel(), 1, blockingErrors);
requireMinimum(enchantmentPath + ".maxLevel", enchantment.maxLevel(), 1, blockingErrors);
requireOrdered(enchantmentPath + ".minLevel", enchantment.minLevel(),
enchantmentPath + ".maxLevel", enchantment.maxLevel(), blockingErrors);
double chance = enchantment.chance();
if (!Double.isFinite(chance) || chance < 0D || chance > 1D) {
blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1.");
}
}
private static void validateLootReference(PackResources resources, String resourceType, String resourceKey, LootSettings reference,
Set<ResourceId> lootIds, List<String> blockingErrors, List<String> warnings) {
String path = resourceType + " '" + resourceKey + "'.loot";
if (!(rawLoot instanceof JSONObject reference)) {
blockingErrors.add(path + " must be an object.");
return;
double multiplier = reference.multiplier();
if (!Double.isFinite(multiplier) || multiplier < 0D || multiplier > LootSettings.MAX_MULTIPLIER) {
blockingErrors.add(path + ".multiplier must be a finite number from 0 to " + (int) LootSettings.MAX_MULTIPLIER + ".");
}
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() > LootSettings.MAX_MULTIPLIER) {
blockingErrors.add(path + ".multiplier must be a finite number from 0 to "
+ (int) LootSettings.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()
List<String> tables = reference.tables();
if (reference.mode() == LootMode.CLEAR && !tables.isEmpty()) {
warnings.add(path + " uses mode CLEAR and lists " + tables.size()
+ " 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()) {
for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) {
String tableKey = tables.get(tableIndex);
if (tableKey == null || 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 + "'.");
} else if (!lootIds.contains(resources.idOf(tableKey))) {
blockingErrors.add(path + ".tables[" + tableIndex + "] references missing loot table '" + tableKey + "'.");
}
}
}
private static void requireMinimum(String fieldPath, int value, int minimum, List<String> blockingErrors) {
if (value < minimum) {
blockingErrors.add(fieldPath + " must be at least " + minimum + ".");
}
}
private static void requireMaximum(String fieldPath, int value, int maximum, List<String> blockingErrors) {
if (value > maximum) {
blockingErrors.add(fieldPath + " must be at most " + maximum + ".");
}
}
private static void requireOrdered(String minimumPath, int minimum, String maximumPath, int maximum, List<String> blockingErrors) {
if (minimum > maximum) {
blockingErrors.add(minimumPath + " must not exceed " + maximumPath + ".");
}
}
}
@@ -18,13 +18,13 @@
package art.arcane.iris.engine.loot;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.object.loot.IObjectLoot;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.builtin.loot.ObjectLootEntry;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.block.BlockSpec;
import com.volmit.block.BlockState;
import com.volmit.resource.PackResources;
import com.volmit.service.Loot;
import java.util.ArrayList;
@@ -43,32 +43,27 @@ final class PlacementLoot {
private static final char NAMESPACE_SEPARATOR = ':';
private static final char PROPERTIES_START = '[';
private final IrisData data;
private final PackResources resources;
private final Supplier<Set<String>> platformTables;
private final long lootSeed;
private final ModuleLog log;
/** @param platformTables the keys of the loot tables the platform has, asked for only when a placement names one */
PlacementLoot(IrisData data, Supplier<Set<String>> platformTables, long lootSeed, ModuleLog log) {
this.data = data;
PlacementLoot(PackResources resources, Supplier<Set<String>> platformTables, long lootSeed, ModuleLog log) {
this.resources = resources;
this.platformTables = platformTables;
this.lootSeed = lootSeed;
this.log = log;
}
/** The platform's loot table keys, which a placement may name, in the form a placement names them. */
static Set<String> platformTableKeys() {
return Set.copyOf(IrisPlatforms.get().registries().lootTableKeys());
}
/**
* The table a placement, whose platform tables are {@code platformLoot} and whose pack tables are {@code packLoot},
* gives {@code container}, a storage chest, at the spot {@code x}, {@code worldY}, {@code z}; null when it gives
* it none.
*/
Loot.Source pick(List<? extends IObjectLoot> platformLoot, List<? extends IObjectLoot> packLoot, PlatformBlockState container,
Loot.Source pick(List<? extends ObjectLootEntry> platformLoot, List<? extends ObjectLootEntry> packLoot, BlockState container,
RNG rng, int x, int worldY, int z) {
Candidates candidates = new Candidates(container);
Candidates candidates = new Candidates(resources.blocks().resolve(container));
add(candidates, platformLoot, name -> platformSource(name, x, worldY, z));
add(candidates, packLoot, this::packSource);
List<Candidate> pool = candidates.pool();
@@ -76,22 +71,22 @@ final class PlacementLoot {
return picked == null ? null : picked.source();
}
private void add(Candidates candidates, List<? extends IObjectLoot> entries, Function<String, Loot.Source> sourceOf) {
for (IObjectLoot entry : entries) {
if (entry == null || entry.getWeight() <= 0) {
private void add(Candidates candidates, List<? extends ObjectLootEntry> entries, Function<String, Loot.Source> sourceOf) {
for (ObjectLootEntry entry : entries) {
if (entry == null || entry.weight() <= 0) {
continue;
}
Loot.Source source = sourceOf.apply(entry.getName());
Loot.Source source = sourceOf.apply(entry.name());
if (source == null) {
log.warn("Couldn't find loot table " + entry.getName());
log.warn("Couldn't find loot table " + entry.name());
continue;
}
candidates.add(entry, data, new Candidate(source, entry.getWeight()));
candidates.add(entry, resources, new Candidate(source, entry.weight()));
}
}
private Loot.Source packSource(String key) {
return LootResources.table(data, key) == null ? null : new Loot.Table(key);
return LootResources.table(resources, key) == null ? null : new Loot.Table(key);
}
private Loot.Source platformSource(String name, int x, int worldY, int z) {
@@ -121,21 +116,22 @@ final class PlacementLoot {
private final List<Candidate> basic = new ArrayList<>();
private final List<Candidate> global = new ArrayList<>();
private Candidates(PlatformBlockState container) {
private Candidates(BlockState container) {
this.containerKey = container.key();
this.containerMaterial = materialOf(containerKey);
}
void add(IObjectLoot entry, IrisData data, Candidate candidate) {
List<PlatformBlockState> filter = entry.getFilter(data);
void add(ObjectLootEntry entry, PackResources resources, Candidate candidate) {
List<BlockSpec> filter = entry.filter();
if (filter.isEmpty()) {
global.add(candidate);
return;
}
for (PlatformBlockState filterState : filter) {
if (entry.isExact() && filterState.key().equals(containerKey)) {
for (BlockSpec filterSpec : filter) {
String filterKey = resources.blocks().resolve(filterSpec).key();
if (entry.exact() && filterKey.equals(containerKey)) {
exact.add(candidate);
} else if (!entry.isExact() && materialOf(filterState.key()).equals(containerMaterial)) {
} else if (!entry.exact() && materialOf(filterKey).equals(containerMaterial)) {
basic.add(candidate);
}
}
@@ -19,8 +19,6 @@
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.BlockDrop;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockSpec;
@@ -45,10 +43,7 @@ final class ResolvedBlockDrop {
static ResolvedBlockDrop of(BlockDrop drop, BlockRegistry blocks) {
Set<String> keys = new LinkedHashSet<>();
for (BlockSpec spec : drop.blocks()) {
PlatformBlockState state = IrisPlatforms.get().registries().block(blocks.resolve(spec).key());
if (state != null) {
keys.add(comparable(state.key(), drop.exactBlocks()));
}
keys.add(comparable(blocks.resolve(spec).key(), drop.exactBlocks()));
}
return new ResolvedBlockDrop(drop, keys);
}
@@ -93,23 +93,5 @@ public interface IRare {
return v instanceof IRare ? Math.max(1, ((IRare) v).getRarity()) : 1;
}
/**
* Expands a candidate list into a rarity-weighted list: each entry appears totalRarity/rarity
* times, so picking uniformly from the result applies rarity exactly once. Both the Bukkit and
* modded entity spawners select through this expansion; rarity must never be applied a second
* time per spawn position.
*/
static <T> KList<T> expandWeighted(List<T> possibilities) {
KList<T> rarityTypes = new KList<>();
int totalRarity = 0;
for (T i : possibilities) {
totalRarity += get(i);
}
for (T i : possibilities) {
rarityTypes.addMultiple(i, totalRarity / get(i));
}
return rarityTypes;
}
int getRarity();
}
@@ -18,14 +18,13 @@
package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.Level;
import art.arcane.iris.builtin.LiveWorld.Sky;
import art.arcane.iris.builtin.spawn.AmbientEffect;
import art.arcane.iris.builtin.spawn.EffectCommands;
import art.arcane.iris.builtin.spawn.EffectSettings;
import art.arcane.iris.builtin.spawn.SpawnCommand;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.spi.PlatformWorld;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.entity.EntitySpec;
import com.volmit.service.AmbientEffects;
@@ -34,6 +33,7 @@ import com.volmit.world.PackWorld;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* How {@code iris:spawn} plays the ambient effects of regions and biomes: the region's effects, then the biome's, each
@@ -42,32 +42,32 @@ import java.util.List;
public final class AmbientEffecting implements AmbientEffects {
@Override
public List<Effect> due(PackWorld world, BlockPosition at) {
Engine engine = IrisPackWorld.of(world).engine();
LiveWorld live = LiveWorld.of(world);
EffectTimers timers = world.state(EffectTimers.class, ignored -> new EffectTimers());
PlatformWorld platformWorld = engine.getWorld().platformWorld();
Optional<Sky> sky = live.sky();
List<Effect> due = new ArrayList<>();
addDue(due, effectsOf(engine.getRegion(at.x(), at.z())), timers, platformWorld);
addDue(due, effectsOf(engine.getBiome(at.x(), at.y(), at.z())), timers, platformWorld);
addDue(due, effectsOf(live, Level.REGION, at), timers, sky);
addDue(due, effectsOf(live, Level.BIOME, at), timers, sky);
return due;
}
private static List<AmbientEffect> effectsOf(IrisRegistrant owner) {
return owner.getModuleSettings().find(EffectSettings.class).map(EffectSettings::effects).orElse(List.of());
private static List<AmbientEffect> effectsOf(LiveWorld live, Level level, BlockPosition at) {
return live.settings(EffectSettings.class, level, at.x(), at.y(), at.z()).map(EffectSettings::effects).orElse(List.of());
}
private static void addDue(List<Effect> due, List<AmbientEffect> effects, EffectTimers timers, PlatformWorld world) {
private static void addDue(List<Effect> due, List<AmbientEffect> effects, EffectTimers timers, Optional<Sky> sky) {
for (AmbientEffect effect : effects) {
if (timers.shouldPlayNow(effect)) {
due.add(play(effect, world));
due.add(play(effect, sky));
}
}
}
private static Effect play(AmbientEffect effect, PlatformWorld world) {
private static Effect play(AmbientEffect effect, Optional<Sky> sky) {
Sound sound = effect.sound() == null ? null : soundOf(effect);
Particles particles = effect.particleEffect() == null ? null : particlesOf(effect);
return new Effect(sound, particles, commandsOf(effect.commandRegistry(), world), potionOf(effect));
return new Effect(sound, particles, commandsOf(effect.commandRegistry(), sky), potionOf(effect));
}
private static Sound soundOf(AmbientEffect effect) {
@@ -92,7 +92,7 @@ public final class AmbientEffecting implements AmbientEffects {
altX, altY, altZ, effect.extra());
}
private static List<Command> commandsOf(EffectCommands registry, PlatformWorld world) {
private static List<Command> commandsOf(EffectCommands registry, Optional<Sky> sky) {
List<Command> commands = new ArrayList<>();
if (registry == null) {
return commands;
@@ -102,7 +102,7 @@ public final class AmbientEffecting implements AmbientEffects {
double offsetY = commandOffset(registry.commandOffsetY(), registry.commandRandomAltY());
double offsetZ = commandOffset(registry.commandOffsetZ(), registry.commandRandomAltZ());
for (SpawnCommand command : registry.rawCommands()) {
if (SpawnConditions.allow(command.timeBlock(), command.weather(), world)) {
if (sky.isPresent() && SpawnConditions.allow(command.timeBlock(), command.weather(), sky.get())) {
commands.add(new Command(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(),
command.repeatDelay()), offsetX, offsetY, offsetZ));
}
@@ -18,6 +18,7 @@
package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.LiveWorld.Sky;
import art.arcane.iris.builtin.loot.ItemAttributeModifier;
import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.builtin.spawn.AmbientEffect;
@@ -25,7 +26,6 @@ import art.arcane.iris.builtin.spawn.EntityDefinition;
import art.arcane.iris.builtin.spawn.SpawnCommand;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.loot.LootItems;
import art.arcane.iris.spi.PlatformWorld;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemAttribute;
@@ -33,6 +33,7 @@ import com.volmit.item.ItemDrop;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Turns an entity of the pack into the {@link EntitySpec} the host spawns, making every random choice in the order Iris
@@ -43,13 +44,13 @@ final class EntityResolution {
private static final long LEASH_HOLDER_STREAM = 234548L;
private final LootItems items;
private final PlatformWorld world;
private final Optional<Sky> sky;
private final EffectTimers timers;
/** @param world the world the entity appears in, whose time and weather decide which of its commands run */
EntityResolution(LootItems items, PlatformWorld world, EffectTimers timers) {
/** @param sky the sky of the world the entity appears in, whose time and weather decide which of its commands run; none while the world has no platform world */
EntityResolution(LootItems items, Optional<Sky> sky, EffectTimers timers) {
this.items = items;
this.world = world;
this.sky = sky;
this.timers = timers;
}
@@ -121,7 +122,7 @@ final class EntityResolution {
private List<EntitySpec.Command> commandsOf(EntityDefinition entity) {
List<EntitySpec.Command> commands = new ArrayList<>();
for (SpawnCommand command : entity.rawCommands()) {
if (SpawnConditions.allow(command.timeBlock(), command.weather(), world)) {
if (sky.isPresent() && SpawnConditions.allow(command.timeBlock(), command.weather(), sky.get())) {
commands.add(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), command.repeatDelay()));
}
}
@@ -18,29 +18,25 @@
package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.IrisSeed;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.Level;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.builtin.spawn.EntityDefinition;
import art.arcane.iris.builtin.spawn.EntitySpawn;
import art.arcane.iris.builtin.spawn.SpawnMarker;
import art.arcane.iris.builtin.spawn.SpawnSurface;
import art.arcane.iris.builtin.spawn.Spawner;
import art.arcane.iris.builtin.spawn.SpawnerSettings;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.loot.LootItems;
import art.arcane.iris.engine.object.value.IRare;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.spawn.SpawnResources.KeyedSpawner;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.slices.MarkerMatter;
import art.arcane.volmlib.util.scheduling.ChronoLatch;
import com.volmit.config.Range;
import com.volmit.entity.EntitySpec;
import com.volmit.resource.PackResources;
import com.volmit.service.EntitySpawns;
import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld;
@@ -63,13 +59,15 @@ public final class EntitySpawning implements EntitySpawns {
private static final String CAVE_FLOOR_MARKER = "cave_floor";
private static final String CAVE_CEILING_MARKER = "cave_ceiling";
private static final int AIR_ABOVE_MARKER = 1;
private static final long COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS = 60_000L;
private static final int LAYOUT_QUESTION_HEIGHT = 0;
@Override
public Optional<Plan> plan(PackWorld world, Site site) {
Engine engine = engine(world);
forgetExpiredCooldowns(world);
return switch (site) {
case Chunk chunk -> planChunk(world, engine, chunk);
case Marker marker -> planMarker(world, engine, marker);
case Chunk chunk -> planChunk(world, chunk);
case Marker marker -> planMarker(world, marker);
};
}
@@ -78,19 +76,19 @@ public final class EntitySpawning implements EntitySpawns {
if (count <= 0) {
return;
}
Spawner spawner = SpawnResources.spawner(engine(world).getData(), plan.spawner());
Spawner spawner = SpawnResources.spawner(world.resources(), plan.spawner());
if (spawner != null) {
SpawnerGate.spawned(plan.spawner(), spawner, engine(world), plan.chunkX(), plan.chunkZ());
SpawnerGate.spawned(plan.spawner(), spawner, LiveWorld.of(world), plan.chunkX(), plan.chunkZ());
}
}
@Override
public Optional<EntitySpec> entity(PackWorld world, String key) {
EntityDefinition entity = SpawnResources.entity(engine(world).getData(), key);
EntityDefinition entity = SpawnResources.entity(world.resources(), key);
if (entity == null) {
return Optional.empty();
}
return Optional.of(resolution(world, engine(world)).resolve(entity, entityRandom(world).rng()));
return Optional.of(resolution(world).resolve(entity, entityRandom(world).rng()));
}
@Override
@@ -98,15 +96,14 @@ public final class EntitySpawning implements EntitySpawns {
if (tag.equals(CAVE_FLOOR_MARKER) || tag.equals(CAVE_CEILING_MARKER)) {
return Optional.empty();
}
Engine engine = engine(world);
SpawnMarker marker = SpawnResources.marker(engine.getData(), tag);
SpawnMarker marker = SpawnResources.marker(world.resources(), tag);
if (marker == null) {
return Optional.empty();
}
List<String> spawners = new ArrayList<>();
for (String key : marker.spawners()) {
if (SpawnResources.spawner(engine.getData(), key) == null) {
if (SpawnResources.spawner(world.resources(), key) == null) {
world.log().error("Cannot load spawner: " + key + " for marker " + tag, null);
continue;
}
@@ -115,69 +112,78 @@ public final class EntitySpawning implements EntitySpawns {
return Optional.of(new MarkerRule(spawners, marker.emptyAbove(), marker.removeOnChange()));
}
private Optional<Plan> planChunk(PackWorld world, Engine engine, Chunk chunk) {
Predicate<KeyedSpawner> canSpawn = keyed -> SpawnerGate.canSpawn(keyed.key(), keyed.spawner(), engine, chunk.chunkX(), chunk.chunkZ());
/** Drops the cooldowns that ran out, now and then: the world's data keeps them across restarts. */
private static void forgetExpiredCooldowns(PackWorld world) {
CooldownCleanup cleanup = world.state(CooldownCleanup.class, ignored -> new CooldownCleanup());
if (!cleanup.due()) {
return;
}
PackResources resources = world.resources();
LiveWorld.of(world).spawnCooldowns().forgetExpired(key -> {
Spawner spawner = SpawnResources.spawner(resources, key);
return spawner == null ? -1L : spawner.maximumRate().interval();
});
}
private Optional<Plan> planChunk(PackWorld world, Chunk chunk) {
LiveWorld live = LiveWorld.of(world);
Predicate<KeyedSpawner> canSpawn = keyed -> SpawnerGate.canSpawn(keyed.key(), keyed.spawner(), live, chunk.chunkX(), chunk.chunkZ());
int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX());
int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ());
IrisBiome centreBiome = engine.getSurfaceBiome(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE);
IrisRegion region = engine.getRegion(blockX, blockZ);
IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ);
LiveWorld.BiomeKind centreKind = live.surfaceKind(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE);
List<KeyedSpawner> candidates = Stream.concat(
shuffled(engine, engine.getDimension()).stream()
.filter(canSpawn).filter(keyed -> SpawnerGate.suits(keyed.spawner(), centreBiome)),
shuffled(world, live, Level.DIMENSION, blockX, blockZ).stream()
.filter(canSpawn).filter(keyed -> SpawnerGate.suits(keyed.spawner(), centreKind)),
Stream.concat(
shuffled(engine, region).stream().filter(canSpawn),
shuffled(engine, biome).stream().filter(canSpawn)))
shuffled(world, live, Level.REGION, blockX, blockZ).stream().filter(canSpawn),
shuffled(world, live, Level.SURFACE_BIOME, blockX, blockZ).stream().filter(canSpawn)))
.filter(keyed -> chunk.livingEntities() < keyed.spawner().maxEntitiesPerChunk())
.toList();
List<Candidate> spawns = candidates.stream().flatMap(keyed -> spawnsOf(keyed, chunk.initial())).collect(Collectors.toList());
Candidate chosen = IRare.expandWeighted(spawns).getRandom();
Candidate chosen = RarityWeighting.expand(spawns, Candidate::rarity).getRandom();
if (chosen == null) {
return Optional.empty();
}
return planChunkSpawn(world, engine, chunk, chosen);
return planChunkSpawn(world, live, chunk, chosen);
}
private Optional<Plan> planChunkSpawn(PackWorld world, Engine engine, Chunk chunk, Candidate chosen) {
private Optional<Plan> planChunkSpawn(PackWorld world, LiveWorld live, Chunk chunk, Candidate chosen) {
EntitySpawn spawn = chosen.spawn();
int count = LootResolver.inclusive(RNG.r, spawn.minSpawns(), spawn.maxSpawns());
List<Attempt> attempts = new ArrayList<>();
for (int i = 0; i < count; i++) {
int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE);
int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE);
BlockPosition at = spawnPosition(engine, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z);
BlockPosition at = spawnPosition(live, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z);
if (at != null) {
addAttempt(attempts, world, engine, chosen, at, true);
addAttempt(attempts, world, chosen, at, true);
}
}
return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(chosen.key(), chunk.chunkX(), chunk.chunkZ(), false, attempts));
}
/** Where a spawner of its group puts an entity at the column; null when it has no place for one. */
private static BlockPosition spawnPosition(Engine engine, Spawner spawner, int chunkX, int chunkZ, int x, int z) {
int height = engine.getHeight(x, z, true);
int heightWithFluid = engine.getHeight(x, z, false);
private static BlockPosition spawnPosition(LiveWorld live, Spawner spawner, int chunkX, int chunkZ, int x, int z) {
int height = live.highestBlock(x, z, true);
int heightWithFluid = live.highestBlock(x, z, false);
return switch (spawner.group()) {
case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z);
case CAVE -> caveSpawnPosition(engine, chunkX, chunkZ);
case CAVE -> caveSpawnPosition(live, chunkX, chunkZ);
case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z);
};
}
static BlockPosition caveSpawnPosition(Engine engine, int chunkX, int chunkZ) {
if (J.isFolia()) {
return null;
}
KList<IrisPosition> floors = engine.getMantle().findMarkers(chunkX, chunkZ, MarkerMatter.CAVE_FLOOR);
IrisPosition floor = floors.getRandom(RNG.r);
return floor == null ? null : new BlockPosition(floor.getX(), floor.getY() - engine.getMinHeight() + AIR_ABOVE_MARKER, floor.getZ());
static BlockPosition caveSpawnPosition(LiveWorld live, int chunkX, int chunkZ) {
KList<BlockPosition> floors = new KList<>(live.caveFloors(chunkX, chunkZ));
BlockPosition floor = floors.getRandom(RNG.r);
return floor == null ? null : new BlockPosition(floor.x(), floor.y() + AIR_ABOVE_MARKER, floor.z());
}
private Optional<Plan> planMarker(PackWorld world, Engine engine, Marker marker) {
Spawner spawner = SpawnResources.spawner(engine.getData(), marker.spawner());
SpawnMarker spawnMarker = SpawnResources.marker(engine.getData(), marker.marker());
private Optional<Plan> planMarker(PackWorld world, Marker marker) {
Spawner spawner = SpawnResources.spawner(world.resources(), marker.spawner());
SpawnMarker spawnMarker = SpawnResources.marker(world.resources(), marker.marker());
if (spawner == null) {
return Optional.empty();
}
@@ -186,12 +192,13 @@ public final class EntitySpawning implements EntitySpawns {
if (candidates.isEmpty()) {
return Optional.empty();
}
EntitySpawn spawn = IRare.expandWeighted(candidates.stream().map(RareSpawn::new).toList()).getRandom().spawn();
EntitySpawn spawn = RarityWeighting.expand(candidates, EntitySpawn::rarity).getRandom();
BlockPosition position = marker.position();
int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x());
int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z());
if (!SpawnerGate.canSpawn(marker.spawner(), spawner, engine, chunkX, chunkZ)) {
LiveWorld live = LiveWorld.of(world);
if (!SpawnerGate.canSpawn(marker.spawner(), spawner, live, chunkX, chunkZ)) {
return Optional.empty();
}
@@ -203,7 +210,7 @@ public final class EntitySpawning implements EntitySpawns {
List<Attempt> attempts = new ArrayList<>();
BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z());
for (int i = 0; i < count; i++) {
addAttempt(attempts, world, engine, new Candidate(marker.spawner(), spawner, spawn), above, false);
addAttempt(attempts, world, new Candidate(marker.spawner(), spawner, spawn), above, false);
}
return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(marker.spawner(), chunkX, chunkZ, exhaustsMarker, attempts));
}
@@ -212,22 +219,23 @@ public final class EntitySpawning implements EntitySpawns {
return marker.exhaustionChance() > RNG.r.nextDouble();
}
private void addAttempt(List<Attempt> attempts, PackWorld world, Engine engine, Candidate candidate, BlockPosition at, boolean checkSurface) {
EntityDefinition entity = SpawnResources.entity(engine.getData(), candidate.spawn().entity());
private void addAttempt(List<Attempt> attempts, PackWorld world, Candidate candidate, BlockPosition at, boolean checkSurface) {
EntityDefinition entity = SpawnResources.entity(world.resources(), candidate.spawn().entity());
if (entity == null) {
world.log().debug(" You are trying to spawn an entity that does not exist!");
return;
}
Range light = candidate.spawner().allowedLightLevels();
EntitySpec spec = resolution(world, engine).resolve(entity, entityRandom(world).rng());
EntitySpec spec = resolution(world).resolve(entity, entityRandom(world).rng());
attempts.add(new Attempt(at, spec, surfaceOf(entity.surface()),
(int) Math.ceil(light.min()), (int) Math.floor(light.max()), checkSurface));
}
private static EntityResolution resolution(PackWorld world, Engine engine) {
LootItems items = new LootItems(world.resources().items(), engine.isStudio());
return new EntityResolution(items, engine.getWorld().platformWorld(), world.state(EffectTimers.class, ignored -> new EffectTimers()));
private static EntityResolution resolution(PackWorld world) {
LiveWorld live = LiveWorld.of(world);
LootItems items = new LootItems(world.resources().items(), live.studio());
return new EntityResolution(items, live.sky(), world.state(EffectTimers.class, ignored -> new EffectTimers()));
}
private static EntityRandom entityRandom(PackWorld world) {
@@ -238,10 +246,11 @@ public final class EntitySpawning implements EntitySpawns {
return Surface.valueOf(surface.name());
}
/** The spawners an area lists, in a random order. */
private static List<KeyedSpawner> shuffled(Engine engine, IrisRegistrant owner) {
List<String> keys = owner.getModuleSettings().find(SpawnerSettings.class).map(SpawnerSettings::spawners).orElse(List.of());
return new KList<>(SpawnResources.spawners(engine.getData(), keys)).shuffleCopy(RNG.r);
/** The spawners the dimension, region or surface biome at the column lists, in a random order. */
private static List<KeyedSpawner> shuffled(PackWorld world, LiveWorld live, Level level, int x, int z) {
List<String> keys = live.settings(SpawnerSettings.class, level, x, LAYOUT_QUESTION_HEIGHT, z)
.map(SpawnerSettings::spawners).orElse(List.of());
return new KList<>(SpawnResources.spawners(world.resources(), keys)).shuffleCopy(RNG.r);
}
private static Stream<Candidate> spawnsOf(KeyedSpawner keyed, boolean initial) {
@@ -250,35 +259,31 @@ public final class EntitySpawning implements EntitySpawns {
}
/** A spawn of a spawner, which picks as often as the spawn's rarity says. */
private record Candidate(String key, Spawner spawner, EntitySpawn spawn) implements IRare {
@Override
public int getRarity() {
private record Candidate(String key, Spawner spawner, EntitySpawn spawn) {
int rarity() {
return spawn.rarity();
}
}
/** A spawn that picks as often as its rarity says. */
private record RareSpawn(EntitySpawn spawn) implements IRare {
@Override
public int getRarity() {
return spawn.rarity();
}
}
private static Engine engine(PackWorld world) {
return IrisPackWorld.of(world).engine();
}
/** The random stream entities are made from, seeded from the world like Iris always seeded it; one per world. */
private static final class EntityRandom {
private final RNG rng;
private EntityRandom(PackWorld world) {
this.rng = new RNG(IrisPackWorld.of(world).engine().getSeedManager().getEntity());
this.rng = new RNG(IrisSeed.ENTITY.of(world));
}
private RNG rng() {
return rng;
}
}
/** When the world's spawner cooldowns were last tidied. */
private static final class CooldownCleanup {
private final ChronoLatch latch = new ChronoLatch(COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS);
private boolean due() {
return latch.flip();
}
}
}
@@ -0,0 +1,53 @@
/*
* 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.volmlib.util.collection.KList;
import java.util.List;
import java.util.function.ToIntFunction;
/**
* Applies rarity to a pick: each possibility appears in the expansion as often as its rarity says, so picking one at
* random from the expansion picks the rarer ones less often. Spawner choices go through this once; rarity must never be
* applied a second time per spawn position.
*/
final class RarityWeighting {
private static final int MINIMUM_RARITY = 1;
private RarityWeighting() {
}
/** Each of {@code possibilities} repeated total/rarity times, where a rarity below 1 counts as 1. */
static <T> KList<T> expand(List<T> possibilities, ToIntFunction<T> rarity) {
KList<T> expanded = new KList<>();
int totalRarity = 0;
for (T possibility : possibilities) {
totalRarity += rarityOf(possibility, rarity);
}
for (T possibility : possibilities) {
expanded.addMultiple(possibility, totalRarity / rarityOf(possibility, rarity));
}
return expanded;
}
private static <T> int rarityOf(T possibility, ToIntFunction<T> rarity) {
return Math.max(MINIMUM_RARITY, rarity.applyAsInt(possibility));
}
}
@@ -18,11 +18,11 @@
package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.LiveWorld.Sky;
import art.arcane.iris.builtin.spawn.SpawnTimeBlock;
import art.arcane.iris.builtin.spawn.SpawnWeather;
import art.arcane.iris.spi.PlatformWorld;
/** The time of day and the weather a command or spawner of the pack asks for, checked against a world. */
/** The time of day and the weather a command or spawner of the pack asks for, checked against a world's sky. */
final class SpawnConditions {
private static final double TICKS_PER_HOUR = 1000D;
private static final double HOURS_AT_TIME_ZERO = 6;
@@ -31,12 +31,12 @@ final class SpawnConditions {
private SpawnConditions() {
}
static boolean allow(SpawnTimeBlock time, SpawnWeather weather, PlatformWorld world) {
return time.contains(hourOf(world)) && weather.matches(world.isStorming(), world.isThundering());
static boolean allow(SpawnTimeBlock time, SpawnWeather weather, Sky sky) {
return time.contains(hourOf(sky)) && weather.matches(sky.storming(), sky.thundering());
}
/** The world's time of day as a clock hour: tick 0 is 6 in the morning. */
static double hourOf(PlatformWorld world) {
return ((world.getTime() / TICKS_PER_HOUR) + HOURS_AT_TIME_ZERO) % HOURS_PER_DAY;
static double hourOf(Sky sky) {
return ((sky.time() / TICKS_PER_HOUR) + HOURS_AT_TIME_ZERO) % HOURS_PER_DAY;
}
}
@@ -19,6 +19,7 @@
package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.spawn.EffectSettings;
import art.arcane.iris.builtin.spawn.PlacementMarker;
import art.arcane.iris.builtin.spawn.SpawnerSettings;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule;
@@ -50,6 +51,7 @@ public final class SpawnModule implements IrisModule {
public void register(FeatureRegistry registry) {
registry.registerSettings(SpawnerSettings.class);
registry.registerSettings(EffectSettings.class);
registry.registerHeldType(PlacementMarker.class);
SpawnResources.kinds().forEach(registry::registerResourceKind);
registry.registerService(EntitySpawns.class, new EntitySpawning());
registry.registerService(AmbientEffects.class, new AmbientEffecting());
@@ -21,8 +21,7 @@ package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.spawn.EntityDefinition;
import art.arcane.iris.builtin.spawn.SpawnMarker;
import art.arcane.iris.builtin.spawn.Spawner;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.IrisPackResources;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
@@ -57,23 +56,23 @@ public final class SpawnResources {
return List.of(SPAWNERS, ENTITIES, MARKERS);
}
public static Spawner spawner(IrisData data, String key) {
return find(data, SPAWNERS, key);
public static Spawner spawner(PackResources resources, String key) {
return find(resources, SPAWNERS, key);
}
public static EntityDefinition entity(IrisData data, String key) {
return find(data, ENTITIES, key);
public static EntityDefinition entity(PackResources resources, String key) {
return find(resources, ENTITIES, key);
}
public static SpawnMarker marker(IrisData data, String key) {
return find(data, MARKERS, key);
public static SpawnMarker marker(PackResources resources, String key) {
return find(resources, MARKERS, key);
}
/** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */
public static List<KeyedSpawner> spawners(IrisData data, List<String> keys) {
public static List<KeyedSpawner> spawners(PackResources resources, List<String> keys) {
List<KeyedSpawner> spawners = new ArrayList<>();
for (String key : keys) {
Spawner spawner = spawner(data, key);
Spawner spawner = spawner(resources, key);
if (spawner != null) {
spawners.add(new KeyedSpawner(key, spawner));
}
@@ -82,25 +81,24 @@ public final class SpawnResources {
}
/** The key of every entity of the pack, in key order. */
public static List<String> entityKeys(IrisData data) {
return keys(data, ENTITIES);
public static List<String> entityKeys(PackResources resources) {
return keys(resources, ENTITIES);
}
/** The key of every spawner of the pack, in key order. */
public static List<String> spawnerKeys(IrisData data) {
return keys(data, SPAWNERS);
public static List<String> spawnerKeys(PackResources resources) {
return keys(resources, SPAWNERS);
}
/** The key of every marker of the pack, in key order. */
public static List<String> markerKeys(IrisData data) {
return keys(data, MARKERS);
public static List<String> markerKeys(PackResources resources) {
return keys(resources, MARKERS);
}
private static <T> T find(IrisData data, ResourceKind<T> kind, String key) {
private static <T> T find(PackResources resources, 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) {
@@ -109,7 +107,7 @@ public final class SpawnResources {
}
/** 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();
private static List<String> keys(PackResources resources, ResourceKind<?> kind) {
return resources.ids(kind.type()).stream().map(ResourceId::path).toList();
}
}
@@ -18,34 +18,36 @@
package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.BiomeKind;
import art.arcane.iris.builtin.LiveWorld.Sky;
import art.arcane.iris.builtin.spawn.SpawnRate;
import art.arcane.iris.builtin.spawn.SpawnCooldowns;
import art.arcane.iris.builtin.spawn.Spawner;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.spi.PlatformWorld;
import java.util.Optional;
/**
* Whether a spawner may fire: in a biome of the kind its group wants, in the time and weather it asks for, and not
* more often than its rates allow. The rates count in the engine's persisted data, by the key the pack names the
* spawner by.
* more often than its rates allow. The rates count in the world's data, by the key the pack names the spawner by.
*/
final class SpawnerGate {
private SpawnerGate() {
}
/** Whether a spawner of this group fires in {@code biome}. */
static boolean suits(Spawner spawner, IrisBiome biome) {
/** Whether a spawner of this group fires in a biome of {@code kind}. */
static boolean suits(Spawner spawner, BiomeKind kind) {
return switch (spawner.group()) {
case NORMAL -> switch (biome.getInferredType()) {
case NORMAL -> switch (kind) {
case SHORE, SEA, CAVE -> false;
case LAND -> true;
};
case CAVE -> true;
case UNDERWATER -> switch (biome.getInferredType()) {
case UNDERWATER -> switch (kind) {
case SHORE, LAND, CAVE -> false;
case SEA -> true;
};
case BEACH -> switch (biome.getInferredType()) {
case BEACH -> switch (kind) {
case SHORE -> true;
case LAND, CAVE, SEA -> false;
};
@@ -53,45 +55,45 @@ final class SpawnerGate {
}
/** Whether the world is in the time and weather the spawner asks for. */
static boolean suits(Spawner spawner, PlatformWorld world) {
return SpawnConditions.allow(spawner.timeBlock(), spawner.weather(), world);
static boolean suits(Spawner spawner, Sky sky) {
return SpawnConditions.allow(spawner.timeBlock(), spawner.weather(), sky);
}
/** Whether the spawner may fire in the chunk now. */
static boolean canSpawn(String key, Spawner spawner, Engine engine, int chunkX, int chunkZ) {
if (!canSpawn(key, spawner, engine)) {
static boolean canSpawn(String key, Spawner spawner, LiveWorld live, int chunkX, int chunkZ) {
if (!canSpawn(key, spawner, live)) {
return false;
}
SpawnRate rate = spawner.maximumRatePerChunk();
return rate.isInfinite() || engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(key).canSpawn(rate.interval());
return rate.isInfinite() || live.spawnCooldowns().canSpawnInChunk(chunkX, chunkZ, key, rate.interval());
}
/** Counts a spawn of the spawner in the chunk against its rates. */
static void spawned(String key, Spawner spawner, Engine engine, int chunkX, int chunkZ) {
spawned(key, spawner, engine);
static void spawned(String key, Spawner spawner, LiveWorld live, int chunkX, int chunkZ) {
spawned(key, spawner, live);
if (spawner.maximumRatePerChunk().isInfinite()) {
return;
}
engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(key).spawn();
live.spawnCooldowns().spawnedInChunk(chunkX, chunkZ, key);
}
private static boolean canSpawn(String key, Spawner spawner, Engine engine) {
PlatformWorld world = engine.getWorld().platformWorld();
if (world == null || !suits(spawner, world)) {
private static boolean canSpawn(String key, Spawner spawner, LiveWorld live) {
Optional<Sky> sky = live.sky();
if (sky.isEmpty() || !suits(spawner, sky.get())) {
return false;
}
SpawnRate rate = spawner.maximumRate();
return rate.isInfinite() || engine.getEngineData().getCooldown(key).canSpawn(rate.interval());
return rate.isInfinite() || live.spawnCooldowns().canSpawn(key, rate.interval());
}
private static void spawned(String key, Spawner spawner, Engine engine) {
private static void spawned(String key, Spawner spawner, LiveWorld live) {
if (spawner.maximumRate().isInfinite()) {
return;
}
engine.getEngineData().getCooldown(key).spawn();
live.spawnCooldowns().spawned(key);
}
}