diff --git a/core/src/main/java/art/arcane/iris/core/modules/EngineSpawnCooldowns.java b/core/src/main/java/art/arcane/iris/core/modules/EngineSpawnCooldowns.java
deleted file mode 100644
index a9516fba5..000000000
--- a/core/src/main/java/art/arcane/iris/core/modules/EngineSpawnCooldowns.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Iris is a World Generator for Minecraft Servers
- * Copyright (c) 2026 Arcane Arts (Volmit Software)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-
-package art.arcane.iris.core.modules;
-
-import art.arcane.iris.builtin.spawn.SpawnCooldowns;
-import art.arcane.iris.engine.framework.Engine;
-
-import java.util.function.ToLongFunction;
-
-/** The cooldowns of an engine's spawners, in the data the engine saves with its world. */
-final class EngineSpawnCooldowns implements SpawnCooldowns {
- private final Engine engine;
-
- EngineSpawnCooldowns(Engine engine) {
- this.engine = engine;
- }
-
- @Override
- public boolean canSpawn(String spawner, long intervalMilliseconds) {
- return engine.getEngineData().getCooldown(spawner).canSpawn(intervalMilliseconds);
- }
-
- @Override
- public void spawned(String spawner) {
- engine.getEngineData().getCooldown(spawner).spawn();
- }
-
- @Override
- public boolean canSpawnInChunk(int chunkX, int chunkZ, String spawner, long intervalMilliseconds) {
- return engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(spawner).canSpawn(intervalMilliseconds);
- }
-
- @Override
- public void spawnedInChunk(int chunkX, int chunkZ, String spawner) {
- engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(spawner).spawn();
- }
-
- @Override
- public void forgetExpired(ToLongFunction intervalMilliseconds) {
- engine.getEngineData().cleanup(intervalMilliseconds);
- }
-}
diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java
index 27a766110..9786147c1 100644
--- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java
+++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java
@@ -18,8 +18,6 @@
package art.arcane.iris.core.modules;
-import art.arcane.iris.builtin.LegacyStreams;
-import art.arcane.iris.builtin.spawn.SpawnCooldowns;
import art.arcane.iris.builtin.structure.StructureHost;
import art.arcane.iris.engine.framework.Engine;
import com.volmit.ModuleLog;
@@ -35,17 +33,14 @@ import java.util.function.Function;
* One Iris world as modules see it: an engine runtime generating with one snapshot of its pack's resources, and the
* state modules keep for it. {@link ModuleWorlds} makes one when the runtime is built and a new one whenever the
* pack's resources reload under it. Iris's built-in modules reach what they need of Iris through its
- * {@linkplain #extension extensions}: the spawners' cooldowns Iris saves with the world, Iris's legacy random streams,
- * and the structure host.
+ * {@linkplain #extension extensions}: the structure host.
*/
public final class IrisPackWorld implements PackWorld {
private final Engine engine;
private final IrisPackResources resources;
private final WorldStates states;
private final ModuleLog log;
- private final SpawnCooldowns spawnCooldowns;
- private volatile RunningWorld running;
- private final LegacyStreams legacyStreams;
+ private volatile IrisRunningWorld running;
private final Placements placements;
private volatile IrisStructureHost structureHost;
@@ -54,8 +49,6 @@ public final class IrisPackWorld implements PackWorld {
this.resources = engine.getData().getPackResources();
this.states = new WorldStates();
this.log = IrisApiLogger.hostLog();
- this.spawnCooldowns = new EngineSpawnCooldowns(engine);
- this.legacyStreams = new IrisLegacyStreams(engine.getData(), engine.getSeedManager());
this.placements = new IrisPlacements(engine.getData(), engine, () -> this);
}
@@ -92,14 +85,22 @@ public final class IrisPackWorld implements PackWorld {
@Override
public Optional running() {
- RunningWorld known = running;
+ IrisRunningWorld known = running;
if (known == null) {
- known = new IrisRunningWorld(engine);
+ known = new IrisRunningWorld(engine, log);
running = known;
}
return Optional.of(known);
}
+ /** Writes what modules saved with this world, if any asked for it. */
+ void saveState() {
+ IrisRunningWorld known = running;
+ if (known != null) {
+ known.saveState();
+ }
+ }
+
@Override
public T state(Class type, Function super PackWorld, ? extends T> create) {
return states.state(type, () -> create.apply(this));
@@ -120,12 +121,6 @@ public final class IrisPackWorld implements PackWorld {
if (type == Engine.class) {
return engine;
}
- if (type == SpawnCooldowns.class) {
- return spawnCooldowns;
- }
- if (type == LegacyStreams.class) {
- return legacyStreams;
- }
if (type == StructureHost.class) {
return structures();
}
diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java b/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java
index c34e352a7..7c19723c6 100644
--- a/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java
+++ b/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java
@@ -25,11 +25,13 @@ import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.slices.MarkerMatter;
+import com.volmit.ModuleLog;
import com.volmit.config.FeatureSettings;
import com.volmit.geometry.BlockPosition;
import com.volmit.placement.PlacementRecord;
import com.volmit.resource.ResourceId;
import com.volmit.world.RunningWorld;
+import com.volmit.world.SavedKey;
import com.volmit.world.TerrainSampler;
import java.util.List;
@@ -49,9 +51,21 @@ final class IrisRunningWorld implements RunningWorld {
private volatile TerrainSampler layout;
private volatile FeatureSettings settings;
private volatile Set platformLootTables;
+ private final SavedWorldState savedState;
- IrisRunningWorld(Engine engine) {
+ IrisRunningWorld(Engine engine, ModuleLog log) {
this.engine = engine;
+ this.savedState = new SavedWorldState(() -> engine.getWorld().worldFolder(), log);
+ }
+
+ @Override
+ public T saved(SavedKey key) {
+ return savedState.saved(key);
+ }
+
+ /** Writes the values modules keep with this world; the world calls it when it saves and when it stops. */
+ void saveState() {
+ savedState.saveAll();
}
@Override
diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleWorlds.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleWorlds.java
index 21c3dc545..7a40e4da1 100644
--- a/core/src/main/java/art/arcane/iris/core/modules/ModuleWorlds.java
+++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleWorlds.java
@@ -157,8 +157,20 @@ public final class ModuleWorlds {
private void stopCurrentWorld() {
LifecycleRunner lifecycles = startedWith;
startedWith = null;
- if (lifecycles != null) {
- lifecycles.worldStopped(current());
+ try {
+ if (lifecycles != null) {
+ lifecycles.worldStopped(current());
+ }
+ } finally {
+ saveCurrentWorldState();
+ }
+ }
+
+ /** Writes what modules saved with the current world; does nothing when no world was made or none was asked for. */
+ public void saveCurrentWorldState() {
+ IrisPackWorld world = current;
+ if (world != null) {
+ world.saveState();
}
}
diff --git a/core/src/main/java/art/arcane/iris/core/modules/SavedWorldState.java b/core/src/main/java/art/arcane/iris/core/modules/SavedWorldState.java
new file mode 100644
index 000000000..707666b5a
--- /dev/null
+++ b/core/src/main/java/art/arcane/iris/core/modules/SavedWorldState.java
@@ -0,0 +1,161 @@
+/*
+ * Iris is a World Generator for Minecraft Servers
+ * Copyright (c) 2026 Arcane Arts (Volmit Software)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+package art.arcane.iris.core.modules;
+
+import art.arcane.iris.core.lifecycle.VanishedWorldStorage;
+import com.volmit.ModuleLog;
+import com.volmit.world.SavedKey;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Supplier;
+
+/**
+ * What modules keep with one running world ({@link com.volmit.world.RunningWorld#saved}): the world's one instance per
+ * key, read from {@code /iris/module-data//.bin} when first asked for and written back by
+ * {@link #saveAll()}. A file is the codec's version followed by the codec's payload.
+ */
+final class SavedWorldState {
+ private static final String STORAGE_DIRECTORY = "iris/module-data";
+ private static final String FILE_EXTENSION = ".bin";
+ private static final String TEMPORARY_EXTENSION = ".tmp";
+
+ private final Supplier worldFolder;
+ private final ModuleLog log;
+ private final Map> values = new ConcurrentHashMap<>();
+ private final Object loading = new Object();
+
+ SavedWorldState(Supplier worldFolder, ModuleLog log) {
+ this.worldFolder = worldFolder;
+ this.log = log;
+ }
+
+ T saved(SavedKey key) {
+ Saved> known = values.get(key.id());
+ if (known == null) {
+ known = loadOnce(key);
+ }
+ if (known.key().type() != key.type()) {
+ throw new IllegalArgumentException("Saved state " + key.id() + " is kept as " + known.key().type().getName()
+ + ", not " + key.type().getName());
+ }
+ return key.type().cast(known.value());
+ }
+
+ /** Writes every value asked for so far; a value that cannot be written is reported and does not stop the others. */
+ void saveAll() {
+ List> asked = List.copyOf(values.values());
+ if (asked.isEmpty() || VanishedWorldStorage.vanished(worldFolder.get())) {
+ return;
+ }
+ for (Saved> saved : asked) {
+ save(saved);
+ }
+ }
+
+ private Saved> loadOnce(SavedKey key) {
+ synchronized (loading) {
+ Saved> known = values.get(key.id());
+ if (known != null) {
+ return known;
+ }
+ Saved loaded = new Saved<>(key, load(key));
+ values.put(key.id(), loaded);
+ return loaded;
+ }
+ }
+
+ private T load(SavedKey key) {
+ Path file = fileOf(key);
+ byte[] stored;
+ try {
+ stored = Files.readAllBytes(file);
+ } catch (NoSuchFileException none) {
+ return key.initial().get();
+ } catch (IOException unreadable) {
+ log.warn("Saved state " + key.id() + " could not be read from " + file + " and starts over: " + unreadable);
+ return key.initial().get();
+ }
+ try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(stored))) {
+ T value = key.codec().read(input, input.readInt());
+ if (value == null) {
+ throw new IOException("The codec read no value");
+ }
+ return value;
+ } catch (IOException | RuntimeException rejected) {
+ log.warn("Saved state " + key.id() + " in " + file + " was rejected and starts over: " + rejected);
+ return key.initial().get();
+ }
+ }
+
+ private void save(Saved> saved) {
+ Path file = fileOf(saved.key());
+ try {
+ writeAtomically(file, saved.encode());
+ } catch (IOException | RuntimeException failure) {
+ log.error("Saved state " + saved.key().id() + " could not be written to " + file, failure);
+ }
+ }
+
+ private Path fileOf(SavedKey> key) {
+ String id = key.id();
+ String namespace = id.substring(0, id.indexOf(':'));
+ String path = id.substring(id.indexOf(':') + 1);
+ return worldFolder.get().toPath().resolve(STORAGE_DIRECTORY).resolve(namespace).resolve(path + FILE_EXTENSION);
+ }
+
+ private static void writeAtomically(Path file, byte[] content) throws IOException {
+ Path parent = file.getParent();
+ Files.createDirectories(parent);
+ Path temporary = Files.createTempFile(parent, file.getFileName().toString(), TEMPORARY_EXTENSION);
+ try {
+ Files.write(temporary, content);
+ try {
+ Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+ } catch (AtomicMoveNotSupportedException unsupported) {
+ Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING);
+ }
+ } finally {
+ Files.deleteIfExists(temporary);
+ }
+ }
+
+ private record Saved(SavedKey key, T value) {
+ byte[] encode() throws IOException {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (DataOutputStream output = new DataOutputStream(bytes)) {
+ output.writeInt(key.codec().version());
+ key.codec().write(output, value);
+ }
+ return bytes.toByteArray();
+ }
+ }
+}
diff --git a/core/src/main/java/art/arcane/iris/engine/EngineDataStore.java b/core/src/main/java/art/arcane/iris/engine/EngineDataStore.java
index 6fa3d43d0..d489496d1 100644
--- a/core/src/main/java/art/arcane/iris/engine/EngineDataStore.java
+++ b/core/src/main/java/art/arcane/iris/engine/EngineDataStore.java
@@ -127,6 +127,7 @@ final class EngineDataStore {
}
void saveEngineData() {
+ saveModuleData();
synchronized (engineDataLock) {
if (storageVanished()) {
return;
@@ -144,6 +145,14 @@ final class EngineDataStore {
}
}
+ /** What modules keep with the world is saved wherever the engine saves its own data. */
+ private void saveModuleData() {
+ EngineRuntime runtime = engine.runtime;
+ if (runtime != null) {
+ runtime.generation().saveModuleData();
+ }
+ }
+
void releaseEngineData() {
IrisData data = engine.getData();
data.unregisterEngine(engine);
diff --git a/core/src/main/java/art/arcane/iris/engine/framework/EngineGeneration.java b/core/src/main/java/art/arcane/iris/engine/framework/EngineGeneration.java
index 3120c0f4e..7fd767e16 100644
--- a/core/src/main/java/art/arcane/iris/engine/framework/EngineGeneration.java
+++ b/core/src/main/java/art/arcane/iris/engine/framework/EngineGeneration.java
@@ -103,6 +103,11 @@ public final class EngineGeneration {
return bypass;
}
+ /** Writes what modules saved with the world, as the engine saves its data; see {@link com.volmit.world.RunningWorld#saved}. */
+ public void saveModuleData() {
+ modules.saveCurrentWorldState();
+ }
+
/** Stops the modules' world and closes the state stages kept, such as actuators that hold engine resources. */
public void close() {
modules.close();
diff --git a/core/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java b/core/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java
deleted file mode 100644
index 0a1db5c1b..000000000
--- a/core/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Iris is a World Generator for Minecraft Bukkit Servers
- * Copyright (c) 2022 Arcane Arts (Volmit Software)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-
-package art.arcane.iris.engine.object.entity.spawn;
-
-import art.arcane.volmlib.util.math.M;
-import lombok.Data;
-
-@Data
-public class IrisEngineSpawnerCooldown {
- private long lastSpawn = 0;
- private String spawner;
-
- public void spawn() {
- lastSpawn = M.ms();
- }
-
- public boolean canSpawn(long intervalMilliseconds) {
- return M.ms() - lastSpawn > intervalMilliseconds;
- }
-}
diff --git a/core/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java b/core/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java
deleted file mode 100644
index 1f0965cec..000000000
--- a/core/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package art.arcane.iris.engine.object.entity.spawn;
-
-import art.arcane.volmlib.util.collection.KMap;
-import lombok.EqualsAndHashCode;
-import lombok.NonNull;
-
-import java.util.function.ToLongFunction;
-
-@EqualsAndHashCode
-public class IrisSpawnerCooldowns {
- private final KMap cooldowns = new KMap<>();
-
- public IrisEngineSpawnerCooldown getCooldown(@NonNull String loadKey) {
- return cooldowns.computeIfAbsent(loadKey, k -> {
- IrisEngineSpawnerCooldown cd = new IrisEngineSpawnerCooldown();
- cd.setSpawner(loadKey);
- return cd;
- });
- }
-
- /** Forgets the cooldowns that ran out and those of spawners {@code intervalMilliseconds} does not know (a negative interval). */
- public void cleanup(ToLongFunction intervalMilliseconds) {
- cooldowns.values().removeIf(cd -> {
- long interval = intervalMilliseconds.applyAsLong(cd.getSpawner());
- return interval < 0 || cd.canSpawn(interval);
- });
- }
-
- public boolean isEmpty() {
- return cooldowns.isEmpty();
- }
-}
diff --git a/core/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java b/core/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java
index 2db085788..ae74b019f 100644
--- a/core/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java
+++ b/core/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java
@@ -18,36 +18,10 @@
package art.arcane.iris.engine.object.runtime;
-import art.arcane.iris.engine.object.entity.spawn.IrisSpawnerCooldowns;
-import art.arcane.volmlib.util.cache.CacheKey;
-import art.arcane.volmlib.util.collection.KMap;
import lombok.Data;
-import lombok.EqualsAndHashCode;
-
-import java.util.function.ToLongFunction;
@Data
-@EqualsAndHashCode(callSuper = true)
-public class IrisEngineData extends IrisSpawnerCooldowns {
+public class IrisEngineData {
private IrisEngineStatistics statistics = new IrisEngineStatistics();
- private KMap chunks = new KMap<>();
private Long seed = null;
-
- public void removeChunk(int x, int z) {
- chunks.remove(CacheKey.key(x, z));
- }
-
- public IrisSpawnerCooldowns getChunk(int x, int z) {
- return chunks.computeIfAbsent(CacheKey.key(x, z), k -> new IrisSpawnerCooldowns());
- }
-
- @Override
- public void cleanup(ToLongFunction intervalMilliseconds) {
- super.cleanup(intervalMilliseconds);
-
- chunks.values().removeIf(chunk -> {
- chunk.cleanup(intervalMilliseconds);
- return chunk.isEmpty();
- });
- }
}
diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisRunningWorldTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisRunningWorldTest.java
index 170752e09..92cdcd4e2 100644
--- a/core/src/test/java/art/arcane/iris/core/modules/IrisRunningWorldTest.java
+++ b/core/src/test/java/art/arcane/iris/core/modules/IrisRunningWorldTest.java
@@ -23,7 +23,6 @@ import art.arcane.iris.builtin.loot.ObjectLoot;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
-import art.arcane.iris.builtin.spawn.SpawnCooldowns;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.engine.UsableBlockPlatform;
@@ -33,7 +32,6 @@ import art.arcane.iris.engine.framework.PlacedObject;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.builtin.objects.ObjectPlacement;
-import art.arcane.iris.engine.object.runtime.IrisEngineData;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.engine.object.world.biome.InferredType;
@@ -59,12 +57,11 @@ import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-/** What services ask a running Iris world: the engine's layout, settings and platform state, its spawners' cooldowns and the loot of its objects. */
+/** What services ask a running Iris world: the engine's layout, settings and platform state and the loot of its objects. */
public class IrisRunningWorldTest {
private static final int X = 10;
private static final int Y = 70;
@@ -188,28 +185,6 @@ public class IrisRunningWorldTest {
assertTrue(running.placementAt(X + 2, Y, Z).isEmpty());
}
- @Test
- public void spawnCooldownsCountPerWorldAndPerChunkAndForgetWhatRanOut() {
- IrisEngineData saved = new IrisEngineData();
- when(engine.getEngineData()).thenReturn(saved);
- SpawnCooldowns cooldowns = world.extension(SpawnCooldowns.class).orElseThrow();
-
- assertTrue(cooldowns.canSpawn("wolves", 600_000L));
- cooldowns.spawned("wolves");
- cooldowns.spawnedInChunk(3, 4, "wolves");
- cooldowns.spawned("gone");
-
- assertFalse(cooldowns.canSpawn("wolves", 600_000L));
- assertFalse(cooldowns.canSpawnInChunk(3, 4, "wolves", 600_000L));
- assertTrue(cooldowns.canSpawnInChunk(3, 5, "wolves", 600_000L));
-
- cooldowns.forgetExpired(spawner -> spawner.equals("wolves") ? 600_000L : -1L);
-
- assertFalse("a cooldown still running stays", cooldowns.canSpawn("wolves", 600_000L));
- assertFalse(cooldowns.canSpawnInChunk(3, 4, "wolves", 600_000L));
- assertTrue("a spawner the pack lacks is forgotten", cooldowns.canSpawn("gone", 600_000L));
- }
-
private T owner(Class type, String table) {
T owner = mock(type);
LootSettings loot = TestSettings.of(LootSettings.class, "{\"tables\": [\"" + table + "\"]}");
diff --git a/core/src/test/java/art/arcane/iris/core/modules/SavedWorldStateTest.java b/core/src/test/java/art/arcane/iris/core/modules/SavedWorldStateTest.java
new file mode 100644
index 000000000..07ac661cf
--- /dev/null
+++ b/core/src/test/java/art/arcane/iris/core/modules/SavedWorldStateTest.java
@@ -0,0 +1,248 @@
+package art.arcane.iris.core.modules;
+
+import art.arcane.iris.core.lifecycle.VanishedWorldStorage;
+import com.volmit.ModuleLog;
+import com.volmit.data.Codec;
+import com.volmit.world.SavedKey;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.contains;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+/** What modules keep with a running world: read when first asked for, written on save, and never blocking the world when the stored data is bad. */
+public class SavedWorldStateTest {
+ private static final int CODEC_VERSION = 2;
+ private static final int INITIAL_COUNT = 5;
+
+ @Rule
+ public TemporaryFolder worldFolder = new TemporaryFolder();
+
+ private ModuleLog log;
+ private SavedWorldState state;
+
+ @Before
+ public void startWorld() {
+ VanishedWorldStorage.reset();
+ log = mock(ModuleLog.class);
+ state = new SavedWorldState(worldFolder::getRoot, log);
+ }
+
+ @After
+ public void forgetVanishedWorlds() {
+ VanishedWorldStorage.reset();
+ }
+
+ /** The count a module keeps, stored as one int and rejecting every other version. */
+ private static final class Count {
+ private final AtomicInteger value;
+
+ private Count(int value) {
+ this.value = new AtomicInteger(value);
+ }
+ }
+
+ private static final Codec COUNT_CODEC = new Codec<>() {
+ @Override
+ public int version() {
+ return CODEC_VERSION;
+ }
+
+ @Override
+ public void write(DataOutput output, Count count) throws IOException {
+ output.writeInt(count.value.get());
+ }
+
+ @Override
+ public Count read(DataInput input, int storedVersion) throws IOException {
+ if (storedVersion != CODEC_VERSION) {
+ throw new IOException("Unsupported version " + storedVersion);
+ }
+ return new Count(input.readInt());
+ }
+ };
+
+ private static final SavedKey COUNT = new SavedKey<>("test:counts/waves", Count.class, COUNT_CODEC,
+ () -> new Count(INITIAL_COUNT));
+
+ @Test
+ public void aWorldWithNothingStoredStartsWithTheInitialValueAndKeepsOneInstance() {
+ Count first = state.saved(COUNT);
+
+ assertEquals(INITIAL_COUNT, first.value.get());
+ assertSame(first, state.saved(COUNT));
+ }
+
+ @Test
+ public void whatTheModuleChangedIsReadBackByTheWorldStartedAfterAStop() {
+ state.saved(COUNT).value.set(42);
+ state.saveAll();
+
+ SavedWorldState restarted = new SavedWorldState(worldFolder::getRoot, log);
+
+ assertEquals(42, restarted.saved(COUNT).value.get());
+ }
+
+ @Test
+ public void aValueIsStoredBelowTheWorldsModuleDataByNamespaceAndPath() throws IOException {
+ state.saved(COUNT);
+ state.saveAll();
+
+ File stored = new File(worldFolder.getRoot(), "iris/module-data/test/counts/waves.bin");
+ byte[] codecVersionThenPayload = {0, 0, 0, CODEC_VERSION, 0, 0, 0, INITIAL_COUNT};
+ assertArrayEquals(codecVersionThenPayload, Files.readAllBytes(stored.toPath()));
+ }
+
+ @Test
+ public void aPayloadTheCodecRejectsIsLoggedAndReplacedByTheInitialValue() throws IOException {
+ store(new byte[]{0, 0, 0, 1, 0, 0, 0, 9});
+
+ Count loaded = state.saved(COUNT);
+
+ assertEquals(INITIAL_COUNT, loaded.value.get());
+ verify(log).warn(contains("test:counts/waves"));
+ }
+
+ @Test
+ public void aTruncatedOrEmptyFileIsRejectedLikeAnyOtherBadPayload() throws IOException {
+ store(new byte[]{0, 0, 0, CODEC_VERSION, 0, 0});
+ assertEquals(INITIAL_COUNT, state.saved(COUNT).value.get());
+
+ SavedKey other = new SavedKey<>("test:counts/other", Count.class, COUNT_CODEC, () -> new Count(INITIAL_COUNT));
+ store("other", new byte[0]);
+ assertEquals(INITIAL_COUNT, state.saved(other).value.get());
+ }
+
+ @Test
+ public void aRejectedPayloadIsOverwrittenByTheNextSave() throws IOException {
+ store(new byte[]{1, 2, 3});
+ state.saved(COUNT).value.set(7);
+
+ state.saveAll();
+
+ assertEquals(7, new SavedWorldState(worldFolder::getRoot, log).saved(COUNT).value.get());
+ }
+
+ @Test
+ public void aCodecThatReadsNothingIsRejected() throws IOException {
+ Codec nothing = new Codec<>() {
+ @Override
+ public int version() {
+ return 1;
+ }
+
+ @Override
+ public void write(DataOutput output, Count count) {
+ }
+
+ @Override
+ public Count read(DataInput input, int storedVersion) {
+ return null;
+ }
+ };
+ SavedKey key = new SavedKey<>("test:counts/nothing", Count.class, nothing, () -> new Count(INITIAL_COUNT));
+ store("nothing", new byte[]{0, 0, 0, 1});
+
+ assertEquals(INITIAL_COUNT, state.saved(key).value.get());
+ verify(log).warn(contains("test:counts/nothing"));
+ }
+
+ @Test
+ public void theSameIdAskedForAnotherTypeIsRefused() {
+ state.saved(COUNT);
+ Codec text = new Codec<>() {
+ @Override
+ public int version() {
+ return 1;
+ }
+
+ @Override
+ public void write(DataOutput output, String value) throws IOException {
+ output.writeUTF(value);
+ }
+
+ @Override
+ public String read(DataInput input, int storedVersion) throws IOException {
+ return input.readUTF();
+ }
+ };
+
+ assertThrows(IllegalArgumentException.class,
+ () -> state.saved(new SavedKey<>("test:counts/waves", String.class, text, () -> "")));
+ }
+
+ @Test
+ public void savingWritesNothingWhenNoValueWasAskedFor() {
+ state.saveAll();
+
+ assertFalse(new File(worldFolder.getRoot(), "iris").exists());
+ }
+
+ @Test
+ public void aFailingCodecIsReportedAndDoesNotStopTheOtherValuesFromBeingSaved() {
+ Codec failing = new Codec<>() {
+ @Override
+ public int version() {
+ return 1;
+ }
+
+ @Override
+ public void write(DataOutput output, Count count) throws IOException {
+ throw new IOException("cannot write");
+ }
+
+ @Override
+ public Count read(DataInput input, int storedVersion) {
+ return new Count(0);
+ }
+ };
+ state.saved(new SavedKey<>("test:counts/broken", Count.class, failing, () -> new Count(0)));
+ state.saved(COUNT).value.set(9);
+
+ state.saveAll();
+
+ verify(log).error(contains("test:counts/broken"), any(IOException.class));
+ assertEquals(9, new SavedWorldState(worldFolder::getRoot, log).saved(COUNT).value.get());
+ assertFalse(new File(worldFolder.getRoot(), "iris/module-data/test/counts/broken.bin").exists());
+ }
+
+ @Test
+ public void aWorldWhoseFolderIsGoneIsNotRebuiltBySaving() {
+ File vanishedFolder = new File(worldFolder.getRoot(), "gone");
+ SavedWorldState inVanishedWorld = new SavedWorldState(() -> vanishedFolder, log);
+ inVanishedWorld.saved(COUNT);
+
+ inVanishedWorld.saveAll();
+
+ assertFalse(vanishedFolder.exists());
+ verify(log, never()).error(any(), any());
+ }
+
+ private void store(byte[] payload) throws IOException {
+ store("waves", payload);
+ }
+
+ private void store(String name, byte[] payload) throws IOException {
+ File file = new File(worldFolder.getRoot(), "iris/module-data/test/counts/" + name + ".bin");
+ Files.createDirectories(file.getParentFile().toPath());
+ Files.write(file.toPath(), payload);
+ }
+}
diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java
index 36c29148c..68c321eb7 100644
--- a/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java
+++ b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java
@@ -28,7 +28,6 @@ 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.engine.object.TestSettings;
-import art.arcane.iris.engine.object.runtime.IrisEngineData;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.PlatformWorld;
import com.volmit.entity.EntitySpec;
@@ -42,7 +41,9 @@ import com.volmit.world.RunningWorld;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import java.util.List;
import java.util.Optional;
@@ -58,6 +59,9 @@ import static org.mockito.Mockito.when;
public class EntitySpawningTest {
private static final BlockPosition MARKER_BLOCK = new BlockPosition(40, 70, -12);
+ @Rule
+ public TemporaryFolder worldFolder = new TemporaryFolder();
+
private Engine engine;
private ModuleResourceFixture fixture;
private PackWorld world;
@@ -82,7 +86,7 @@ public class EntitySpawningTest {
IrisWorld engineWorld = mock(IrisWorld.class);
when(engineWorld.platformWorld()).thenReturn(mock(PlatformWorld.class));
when(engine.getWorld()).thenReturn(engineWorld);
- when(engine.getEngineData()).thenReturn(new IrisEngineData());
+ when(engineWorld.worldFolder()).thenReturn(worldFolder.getRoot());
SeedManager seeds = mock(SeedManager.class);
when(seeds.getEntity()).thenReturn(11L);
when(engine.getSeedManager()).thenReturn(seeds);
diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnCooldownBookTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnCooldownBookTest.java
new file mode 100644
index 000000000..0959dd79f
--- /dev/null
+++ b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnCooldownBookTest.java
@@ -0,0 +1,158 @@
+package art.arcane.iris.engine.spawn;
+
+import com.volmit.data.Codec;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+/** When spawners last fired: counted per spawner in the world and in each chunk, forgotten once spent, and kept across saves. */
+public class SpawnCooldownBookTest {
+ private static final long TEN_MINUTES = 600_000L;
+ private static final long START = 1_000_000L;
+
+ private AtomicLong now;
+ private SpawnCooldownBook book;
+
+ @Before
+ public void openBook() {
+ now = new AtomicLong(START);
+ book = new SpawnCooldownBook(now::get);
+ }
+
+ @Test
+ public void aSpawnerThatNeverFiredMayFire() {
+ assertTrue(book.canSpawn("wolves", TEN_MINUTES));
+ assertTrue(book.canSpawnInChunk(3, 4, "wolves", TEN_MINUTES));
+ }
+
+ @Test
+ public void aSpawnerMayFireAgainOnceItsIntervalHasPassed() {
+ book.spawned("wolves");
+
+ assertFalse(book.canSpawn("wolves", TEN_MINUTES));
+ now.addAndGet(TEN_MINUTES);
+ assertFalse("the interval must pass, not just be reached", book.canSpawn("wolves", TEN_MINUTES));
+ now.addAndGet(1);
+ assertTrue(book.canSpawn("wolves", TEN_MINUTES));
+ }
+
+ @Test
+ public void theWorldAndEveryChunkCountSeparatelyPerSpawner() {
+ book.spawnedInChunk(3, 4, "wolves");
+
+ assertFalse(book.canSpawnInChunk(3, 4, "wolves", TEN_MINUTES));
+ assertTrue(book.canSpawnInChunk(3, 5, "wolves", TEN_MINUTES));
+ assertTrue(book.canSpawnInChunk(3, 4, "bats", TEN_MINUTES));
+ assertTrue("a chunk's spawn is not the world's", book.canSpawn("wolves", TEN_MINUTES));
+ }
+
+ @Test
+ public void forgettingKeepsCooldownsStillRunningAndDropsSpentOnesAndSpawnersThePackLacks() {
+ book.spawned("wolves");
+ book.spawnedInChunk(3, 4, "wolves");
+ book.spawned("gone");
+ book.spawnedInChunk(3, 4, "gone");
+ book.spawned("quick");
+ now.addAndGet(1_000L);
+
+ book.forgetExpired(spawner -> switch (spawner) {
+ case "wolves" -> TEN_MINUTES;
+ case "quick" -> 500L;
+ default -> -1L;
+ });
+
+ assertFalse(book.canSpawn("wolves", TEN_MINUTES));
+ assertFalse(book.canSpawnInChunk(3, 4, "wolves", TEN_MINUTES));
+ assertTrue(book.canSpawn("gone", TEN_MINUTES));
+ assertTrue(book.canSpawnInChunk(3, 4, "gone", TEN_MINUTES));
+ assertTrue(book.canSpawn("quick", 500L));
+ }
+
+ @Test
+ public void aSavedBookKeepsWhatFiredInTheWorldAndInChunks() throws IOException {
+ book.spawned("wolves");
+ book.spawnedInChunk(-3, 4, "wolves");
+ book.spawnedInChunk(-3, 4, "bats");
+
+ SpawnCooldownBook restored = roundTrip(book);
+
+ assertFalse(restored.canSpawn("wolves", TEN_MINUTES));
+ assertFalse(restored.canSpawnInChunk(-3, 4, "wolves", TEN_MINUTES));
+ assertFalse(restored.canSpawnInChunk(-3, 4, "bats", TEN_MINUTES));
+ assertTrue(restored.canSpawn("bats", TEN_MINUTES));
+ assertTrue(restored.canSpawnInChunk(3, 4, "wolves", TEN_MINUTES));
+ }
+
+ @Test
+ public void aSavedBookCountsTheTimeThatPassedWhileTheWorldWasStopped() throws IOException {
+ book.spawned("wolves");
+ SpawnCooldownBook restored = roundTrip(book);
+
+ now.addAndGet(TEN_MINUTES + 1);
+
+ assertTrue(restored.canSpawn("wolves", TEN_MINUTES));
+ }
+
+ @Test
+ public void anEmptyBookIsSavedAndRestoredEmpty() throws IOException {
+ assertTrue(roundTrip(book).canSpawn("wolves", TEN_MINUTES));
+ }
+
+ @Test
+ public void aBookOfAnotherFormatVersionIsRejected() {
+ byte[] stored = write(book);
+
+ assertThrows(IOException.class, () -> codec().read(new DataInputStream(new ByteArrayInputStream(stored)), codec().version() + 1));
+ }
+
+ @Test
+ public void aTruncatedBookIsRejected() {
+ book.spawned("wolves");
+ byte[] stored = write(book);
+ byte[] truncated = java.util.Arrays.copyOf(stored, stored.length - 1);
+
+ assertThrows(EOFException.class, () -> codec().read(new DataInputStream(new ByteArrayInputStream(truncated)), codec().version()));
+ }
+
+ @Test
+ public void aNegativeEntryCountIsRejected() {
+ byte[] negativeCount = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
+
+ assertThrows(IOException.class, () -> codec().read(new DataInputStream(new ByteArrayInputStream(negativeCount)), codec().version()));
+ }
+
+ @Test
+ public void theBookTheWorldKeepsIsSavedWithTheSavedKey() {
+ assertTrue(SpawnCooldownBook.SAVED.id().startsWith("iris:spawn/"));
+ assertTrue(SpawnCooldownBook.SAVED.initial().get().canSpawn("wolves", TEN_MINUTES));
+ }
+
+ private Codec codec() {
+ return SpawnCooldownBook.codec(now::get);
+ }
+
+ private SpawnCooldownBook roundTrip(SpawnCooldownBook source) throws IOException {
+ return codec().read(new DataInputStream(new ByteArrayInputStream(write(source))), codec().version());
+ }
+
+ private byte[] write(SpawnCooldownBook source) {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (DataOutputStream output = new DataOutputStream(bytes)) {
+ codec().write(output, source);
+ } catch (IOException impossible) {
+ throw new IllegalStateException(impossible);
+ }
+ return bytes.toByteArray();
+ }
+}
diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java
index bf2916ffb..62644fc7d 100644
--- a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java
+++ b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java
@@ -23,33 +23,38 @@ import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineGeneration;
import art.arcane.iris.engine.object.TestSettings;
-import art.arcane.iris.engine.object.runtime.IrisEngineData;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.PlatformWorld;
import com.volmit.world.BiomeKind;
import com.volmit.world.RunningWorld.Sky;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-/** Whether a spawner may fire: the biome kind its group wants, the world's time and weather, and its rates in the engine's data. */
+/** Whether a spawner may fire: the biome kind its group wants, the world's time and weather, and its rates in the world's saved cooldowns. */
public class SpawnerGateTest {
+ @Rule
+ public TemporaryFolder worldFolder = new TemporaryFolder();
+
+ private Engine engine;
private SpawnerGate gate;
@Before
public void buildEngine() {
- Engine engine = mock(Engine.class);
+ engine = mock(Engine.class);
IrisWorld engineWorld = mock(IrisWorld.class);
PlatformWorld platformWorld = mock(PlatformWorld.class);
when(platformWorld.getTime()).thenReturn(6000L);
when(engineWorld.platformWorld()).thenReturn(platformWorld);
+ when(engineWorld.worldFolder()).thenReturn(worldFolder.getRoot());
when(engine.getWorld()).thenReturn(engineWorld);
when(engine.getData()).thenReturn(mock(IrisData.class));
- when(engine.getEngineData()).thenReturn(new IrisEngineData());
gate = SpawnerGate.of(new EngineGeneration(engine).world());
}
@@ -98,11 +103,27 @@ public class SpawnerGateTest {
assertTrue(gate.canSpawn("other", limited, 9, 9));
}
+ @Test
+ public void aRateHoldsAfterTheWorldWasStoppedAndStartedAgain() {
+ Spawner limited = spawner("{\"maximumRate\": {\"amount\": 1, \"per\": {\"minutes\": 10}}, \"maximumRatePerChunk\": {\"amount\": 1, \"per\": {\"minutes\": 10}}}");
+ EngineGeneration firstRun = new EngineGeneration(engine);
+ SpawnerGate.of(firstRun.world()).spawned("limited", limited, 3, 4);
+
+ firstRun.close();
+ SpawnerGate restarted = SpawnerGate.of(new EngineGeneration(engine).world());
+
+ assertFalse(restarted.canSpawn("limited", limited, 3, 4));
+ assertFalse(restarted.canSpawn("limited", limited, 9, 9));
+ assertTrue(restarted.canSpawn("other", limited, 3, 4));
+ }
+
@Test
public void aWorldWithoutAPlatformWorldLetsNothingFire() {
Engine engine = mock(Engine.class);
+ IrisWorld engineWorld = mock(IrisWorld.class);
+ when(engineWorld.worldFolder()).thenReturn(worldFolder.getRoot());
when(engine.getData()).thenReturn(mock(IrisData.class));
- when(engine.getWorld()).thenReturn(mock(IrisWorld.class));
+ when(engine.getWorld()).thenReturn(engineWorld);
assertFalse(SpawnerGate.of(new EngineGeneration(engine).world()).canSpawn("any", spawner("{}"), 0, 0));
}