From f501e3baf77eb32e3600c882adb57c9d1193817b Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 14:35:32 +0200 Subject: [PATCH] Give modules a world per engine runtime and pack snapshot with lifecycle hooks, and ask them through services: IrisPackWorld and ModuleWorlds (start on publish, restart when the pack's resources reload, stop on retire), contexts' world(), ModuleServices, Engine.getObjectsAt through ObjectsAt and the Iris structure find path and structure index through StructureLocator --- .../iris/core/commands/CommandFind.java | 18 +- ...risStructureLocateCommandContractTest.java | 8 +- .../command/ModdedCommandSuggestions.java | 5 +- .../modded/command/ModdedLocateCommands.java | 16 +- .../command/ModdedUnregisteredStructures.java | 8 +- .../IrisModdedStructureCommandTest.java | 22 +- .../art/arcane/iris/core/loader/IrisData.java | 14 +- .../core/modules/IrisGenerationContext.java | 11 + .../modules/IrisMantleGenerationContext.java | 11 + .../iris/core/modules/IrisPackResources.java | 13 + .../iris/core/modules/IrisPackWorld.java | 85 ++++++ .../core/modules/IrisPlacementInputs.java | 21 +- .../core/modules/ModuleObjectPlacement.java | 2 +- .../iris/core/modules/ModuleServices.java | 132 +++++++++ .../iris/core/modules/ModuleWorlds.java | 182 ++++++++++++ .../core/structure/StructureIndexService.java | 4 +- .../iris/engine/EngineRuntimeBuilder.java | 3 +- .../art/arcane/iris/engine/IrisEngine.java | 13 +- .../arcane/iris/engine/framework/Engine.java | 7 + .../engine/framework/EngineComponent.java | 3 +- .../engine/framework/EngineGeneration.java | 43 ++- .../arcane/iris/engine/framework/Locator.java | 5 - .../iris/engine/platform/EngineBukkitOps.java | 4 - .../specialhandlers/StructureHandler.java | 5 +- .../core/modules/BuiltInServicesTest.java | 57 ++++ .../modules/ChunkSettingsScanTimingTest.java | 2 + .../core/modules/ModuleResourceFixture.java | 10 + .../iris/core/modules/ModuleServicesTest.java | 168 +++++++++++ .../iris/core/modules/ModuleWorldsTest.java | 260 ++++++++++++++++++ .../structure/StructureIndexServiceTest.java | 2 + .../engine/actuator/DecorantModuleTest.java | 26 +- .../structure/StructureResourcesTest.java | 13 + .../specialhandlers/StructureHandlerTest.java | 8 +- 33 files changed, 1101 insertions(+), 80 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java create mode 100644 core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java create mode 100644 core/src/main/java/art/arcane/iris/core/modules/ModuleWorlds.java create mode 100644 core/src/test/java/art/arcane/iris/core/modules/BuiltInServicesTest.java create mode 100644 core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java create mode 100644 core/src/test/java/art/arcane/iris/core/modules/ModuleWorldsTest.java diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandFind.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandFind.java index 622a092b1..f5e506ee6 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandFind.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandFind.java @@ -18,7 +18,7 @@ package art.arcane.iris.core.commands; -import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.Iris; import art.arcane.iris.core.localization.BukkitCommandMessages; import art.arcane.iris.core.localization.BukkitCommandMessagesExtended; @@ -149,7 +149,7 @@ public class CommandFind implements DirectorExecutor { : null; boolean nativePlacement = IrisStructureLocator.hasNativePlacement(e, structureKey); boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(e, structureKey); - boolean locatableEditablePlacement = IrisStructureLocator.hasLocatableEditablePlacement(e, structureKey); + boolean locatableEditablePlacement = ModuleServices.canLocateStructure(e, structureKey); World targetWorld = target.getWorld(); boolean nativeGenerationEnabled = targetWorld.canGenerateStructures(); boolean requiresReachability = registered && decision.generate() @@ -276,7 +276,7 @@ public class CommandFind implements DirectorExecutor { IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false); boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(engine, key); - boolean locatableEditablePlacement = IrisStructureLocator.hasLocatableEditablePlacement(engine, key); + boolean locatableEditablePlacement = ModuleServices.canLocateStructure(engine, key); StructureLookupRoute route = selectStructureLookupRoute( true, decision, nativePlacement, locatableNativePlacement, locatableEditablePlacement, nativeGenerationEnabled, @@ -315,8 +315,8 @@ public class CommandFind implements DirectorExecutor { int editableUnplaced = 0; Set unplacedEditableKeys = new LinkedHashSet<>(); Set locatableEditableKeys = normalizedStructureKeys( - IrisStructureLocator.locatableEditableKeys(engine)); - for (String editableKey : StructureResources.structureKeys(engine.getData())) { + ModuleServices.locatableStructures(engine)); + for (String editableKey : ModuleServices.structureKeys(engine.getData())) { String normalizedKey = normalizeStructureKey(editableKey); if (!isUnplacedEditableCandidate( normalizedKey, registeredKeys.keySet(), locatableEditableKeys, @@ -598,9 +598,8 @@ public class CommandFind implements DirectorExecutor { commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_FIND_LOCATING_2, MessageArgument.untrusted("structure", structure))); J.a(() -> { try { - IrisStructureLocator.LocateResult result = - IrisStructureLocator.locate(engine, structure, blockX, blockZ, 1024); - if (result.status() == IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED) { + ModuleServices.StructureSearch result = ModuleServices.locateStructure(engine, structure, blockX, blockZ, 1024); + if (result.outcome() == ModuleServices.StructureSearch.Outcome.SEARCH_LIMIT_REACHED) { sendStructureMessage(target, commandSender, C.YELLOW + "Unable to locate " + structure + ": the density search safety limit was reached before the full 1024-chunk radius was searched."); @@ -611,8 +610,7 @@ public class CommandFind implements DirectorExecutor { C.YELLOW + "No " + structure + " found within 1024 chunks of you."); return; } - Location destination = new Location( - targetWorld, result.originX(), result.baseY(), result.originZ()); + Location destination = new Location(targetWorld, result.x(), result.y(), result.z()); prepareStructureTeleport(target, targetWorld, commandSender, structure, destination, true); } catch (Throwable t) { sendStructureMessage(target, commandSender, diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java index a2e46a89b..2be4d87f1 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java @@ -20,9 +20,9 @@ public class IrisStructureLocateCommandContractTest { public void findReportsDensityLimitAndUsesExactLocatedOrigin() throws IOException { String source = Files.readString(Path.of(System.getProperty("iris.commandFindSource"))); - assertTrue(source.contains("LocateStatus.SEARCH_LIMIT_REACHED")); + assertTrue(source.contains("StructureSearch.Outcome.SEARCH_LIMIT_REACHED")); assertTrue(source.contains("the density search safety limit was reached")); - assertTrue(source.contains("result.originX(), result.baseY(), result.originZ()")); + assertTrue(source.contains("new Location(targetWorld, result.x(), result.y(), result.z())")); assertFalse(source.contains("at[0] + 8")); assertFalse(source.contains("at[2] + 8")); } @@ -38,7 +38,7 @@ public class IrisStructureLocateCommandContractTest { int nativeLocatableCheck = method.indexOf( "IrisStructureLocator.hasLocatableNativePlacement(e, structureKey)", policyResolution); int editableLocatableCheck = method.indexOf( - "IrisStructureLocator.hasLocatableEditablePlacement(e, structureKey)", nativeLocatableCheck); + "ModuleServices.canLocateStructure(e, structureKey)", nativeLocatableCheck); int worldGenerationCheck = method.indexOf("targetWorld.canGenerateStructures()", editableLocatableCheck); int routeResolution = method.indexOf("selectStructureLookupRoute(", editableLocatableCheck); int nativeLocate = method.indexOf("targetWorld.locateNearestStructure(", routeResolution); @@ -207,7 +207,7 @@ public class IrisStructureLocateCommandContractTest { assertTrue(method.indexOf("DatapackIngestService.installed()") > method.indexOf("J.a(() ->")); assertTrue(source.contains("engine.getDimension().getDatapackImports()")); assertTrue(source.contains("snapshot.configuredImportUrls().contains(importUrl)")); - assertTrue(source.contains("StructureResources.structureKeys(engine.getData())")); + assertTrue(source.contains("ModuleServices.structureKeys(engine.getData())")); assertFalse(method.contains("commandSender.sendMessage(exclusion")); } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java index fd49f7b87..c1043634d 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java @@ -18,6 +18,7 @@ package art.arcane.iris.modded.command; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.modded.ModdedIrisLog; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.core.pack.PackDirectoryResolver; @@ -124,7 +125,7 @@ final class ModdedCommandSuggestions { } boolean nativeGenerationEnabled = source.getServer().getWorldGenSettings().options().generateStructures(); - Collection irisKeys = IrisStructureLocator.locatableEditableKeys(engine); + Collection irisKeys = ModuleServices.locatableStructures(engine); Set reachableNativeKeys = StructureReachability.reachableKeys(engine); Registry registry = source.getServer().registryAccess().lookupOrThrow(Registries.STRUCTURE); List nativeKeys = new ArrayList<>(registry.keySet().size()); @@ -138,7 +139,7 @@ final class ModdedCommandSuggestions { && IrisStructureLocator.hasLocatableNativePlacement(engine, key); boolean locatableEditableReplacement = !nativePlacement && decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS - && IrisStructureLocator.hasLocatableEditablePlacement(engine, key); + && ModuleServices.canLocateStructure(engine, key); if (isEligibleRegisteredStructure(decision, nativePlacement, locatableNativePlacement, locatableEditableReplacement, reachableNativeKeys.contains(normalizeKey(key)), nativeGenerationEnabled)) { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java index adcae8509..0c54ecbc0 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java @@ -18,6 +18,7 @@ package art.arcane.iris.modded.command; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.modded.ModdedIrisLog; import art.arcane.iris.core.localization.IrisLanguage; import art.arcane.iris.core.localization.ModdedCommandMessages; @@ -157,7 +158,7 @@ final class ModdedLocateCommands { Optional resolved = resolveNativeStructure(source, level, engine, key); if (resolved.isEmpty()) { if (!IrisStructureLocator.hasNativePlacement(engine, key) - && IrisStructureLocator.hasLocatableEditablePlacement(engine, key)) { + && ModuleServices.canLocateStructure(engine, key)) { locateIrisStructure(source, level, engine, player, key); return 1; } @@ -173,7 +174,7 @@ final class ModdedLocateCommands { && IrisStructureLocator.hasLocatableNativePlacement(engine, target.key()); boolean locatableEditableReplacement = !nativePlacement && decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS - && IrisStructureLocator.hasLocatableEditablePlacement(engine, target.key()); + && ModuleServices.canLocateStructure(engine, target.key()); boolean reachable = StructureReachability.isReachable(engine, target.key()); if (!ModdedCommandSuggestions.isEligibleRegisteredStructure( decision, nativePlacement, locatableNativePlacement, locatableEditableReplacement, @@ -242,9 +243,8 @@ final class ModdedLocateCommands { IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_SEARCHING_IRIS_PLACED_STRUCTURE, MessageArgument.untrusted("key", key))); Thread thread = new Thread(() -> { try { - IrisStructureLocator.LocateResult result = - IrisStructureLocator.locate(engine, key, blockX, blockZ, 1024); - if (result.status() == IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED) { + ModuleServices.StructureSearch result = ModuleServices.locateStructure(engine, key, blockX, blockZ, 1024); + if (result.outcome() == ModuleServices.StructureSearch.Outcome.SEARCH_LIMIT_REACHED) { server.execute(() -> IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_UNABLE_LOCATE_IRIS_PLACED_STRUCTURE_DENSITY_SEARCH_SAFETY_LIMIT_WAS, MessageArgument.untrusted("key", key)))); return; } @@ -252,9 +252,9 @@ final class ModdedLocateCommands { server.execute(() -> IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_COULD_NOT_FIND_IRIS_PLACED_STRUCTURE_WITHIN_1024_CHUNKS, MessageArgument.untrusted("key", key)))); return; } - int targetX = result.originX(); - int targetY = result.baseY() + 2; - int targetZ = result.originZ(); + int targetX = result.x(); + int targetY = result.y() + 2; + int targetZ = result.z(); server.execute(() -> teleportToStructure(source, level, player, targetX, targetY, targetZ, "Iris-placed structure " + key)); } catch (Throwable e) { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedUnregisteredStructures.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedUnregisteredStructures.java index 3fbeeb906..42ccf8c52 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedUnregisteredStructures.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedUnregisteredStructures.java @@ -18,7 +18,7 @@ package art.arcane.iris.modded.command; -import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.modded.ModdedIrisLog; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; @@ -113,7 +113,7 @@ final class ModdedUnregisteredStructures { && IrisStructureLocator.hasLocatableNativePlacement(engine, key); boolean locatableEditableReplacement = !nativePlacement && decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS - && IrisStructureLocator.hasLocatableEditablePlacement(engine, key); + && ModuleServices.canLocateStructure(engine, key); boolean reachable = reachableNativeKeys.contains(normalizedKey); if (ModdedCommandSuggestions.isEligibleRegisteredStructure( decision, nativePlacement, locatableNativePlacement, @@ -137,7 +137,7 @@ final class ModdedUnregisteredStructures { "Configured by an Iris nativeStructures placement, but absent from the live structure registry; " + "install or enable the datapack or mod that provides this key.")); } - for (String key : StructureResources.structureKeys(engine.getData())) { + for (String key : ModuleServices.structureKeys(engine.getData())) { String normalizedKey = ModdedCommandSuggestions.normalizeKey(key); if (normalizedKey.isEmpty() || eligibleRegisteredKeys.contains(normalizedKey) || excluded.containsKey(normalizedKey)) { @@ -145,7 +145,7 @@ final class ModdedUnregisteredStructures { } boolean registered = registeredKeys.contains(normalizedKey); boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); - boolean locatableEditable = IrisStructureLocator.hasLocatableEditablePlacement(engine, key); + boolean locatableEditable = ModuleServices.canLocateStructure(engine, key); if (!registered && !nativePlacement && locatableEditable) { continue; } diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java index e0775ce56..d1befc6f1 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java @@ -53,7 +53,7 @@ public class IrisModdedStructureCommandTest { String source = source("ModdedLocateCommands.java"); String suggestions = source("ModdedCommandSuggestions.java"); - assertTrue(source.contains("IrisStructureLocator.hasLocatableEditablePlacement(engine, key)")); + assertTrue(source.contains("ModuleServices.canLocateStructure(engine, key)")); assertTrue(source.contains("registry.get(identifier)")); assertTrue(source.contains("getPlacementsForStructure(holder)")); assertTrue(source.contains("generator.findNearestMapStructure(")); @@ -63,11 +63,11 @@ public class IrisModdedStructureCommandTest { assertTrue(source.contains("boolean teleported = player.teleportTo(")); assertTrue(suggestions.contains("combineStructureKeys(unregisteredIrisKeys, nativeKeys)")); assertTrue(source.contains("irisGenerator.isNativeStructureReachable(holder)")); - assertTrue(source.contains("LocateStatus.SEARCH_LIMIT_REACHED")); + assertTrue(source.contains("StructureSearch.Outcome.SEARCH_LIMIT_REACHED")); assertTrue(source.contains("IRIS_MODDED_COMMANDS_UNABLE_LOCATE_IRIS_PLACED_STRUCTURE_DENSITY_SEARCH_SAFETY_LIMIT_WAS")); - assertTrue(source.contains("int targetX = result.originX()")); - assertTrue(source.contains("int targetY = result.baseY() + 2")); - assertTrue(source.contains("int targetZ = result.originZ()")); + assertTrue(source.contains("int targetX = result.x()")); + assertTrue(source.contains("int targetY = result.y() + 2")); + assertTrue(source.contains("int targetZ = result.z()")); assertFalse(source.contains("at[0] + 8")); assertFalse(source.contains("at[2] + 8")); } @@ -184,8 +184,8 @@ public class IrisModdedStructureCommandTest { assertTrue(tree.contains("ModdedUnregisteredStructures.print(context.getSource())")); assertTrue(command.contains("ModdedCommandSuggestions.isEligibleRegisteredStructure(")); assertTrue(command.contains("ModdedLocateCommands.registeredStructureUnavailableMessage(")); - assertTrue(command.contains("StructureResources.structureKeys(engine.getData())")); - assertTrue(command.contains("IrisStructureLocator.hasLocatableEditablePlacement(engine, key)")); + assertTrue(command.contains("ModuleServices.structureKeys(engine.getData())")); + assertTrue(command.contains("ModuleServices.canLocateStructure(engine, key)")); assertTrue(command.contains("ModdedIrisLog.info(\"[Iris goto unregistered] [{}] {} - {}\"")); assertTrue(command.contains("UNREGISTERED(\"unregistered\")")); assertFalse(command.contains("DatapackIngestService")); @@ -201,11 +201,11 @@ public class IrisModdedStructureCommandTest { assertTrue(method.contains("ServerLevel level = source.getLevel()")); assertTrue(method.contains("Engine engine = IrisModdedCommands.engineFor(level)")); assertFalse(method.contains("IrisStructureLocator.locatableKeys(engine)")); - assertTrue(method.contains("IrisStructureLocator.locatableEditableKeys(engine)")); + assertTrue(method.contains("ModuleServices.locatableStructures(engine)")); assertTrue(method.contains("StructureReachability.reachableKeys(engine)")); assertTrue(method.contains("NativeStructureGenerationPolicy.resolve(engine, key, false)")); assertTrue(method.contains("IrisStructureLocator.hasLocatableNativePlacement(engine, key)")); - assertTrue(method.contains("IrisStructureLocator.hasLocatableEditablePlacement(engine, key)")); + assertTrue(method.contains("ModuleServices.canLocateStructure(engine, key)")); assertTrue(method.contains("reachableNativeKeys.contains(normalizeKey(key))")); assertTrue(method.contains("nativeGenerationEnabled")); assertTrue(method.contains("eligibleUnregisteredEditableKeys(")); @@ -258,7 +258,7 @@ public class IrisModdedStructureCommandTest { String method = source.substring(methodStart, methodEnd); int nativeResolution = method.indexOf("resolveNativeStructure(source, level, engine, key)"); int editableIrisLookup = method.indexOf( - "IrisStructureLocator.hasLocatableEditablePlacement(engine, key)", nativeResolution); + "ModuleServices.canLocateStructure(engine, key)", nativeResolution); int policyResolution = method.indexOf( "NativeStructureGenerationPolicy.resolve(engine, target.key(), false)", editableIrisLookup); int eligibilityCheck = method.indexOf( @@ -275,7 +275,7 @@ public class IrisModdedStructureCommandTest { assertTrue(replacementLocate > eligibilityCheck); assertTrue(nativeLocate > replacementLocate); assertTrue(method.contains("IrisStructureLocator.hasLocatableNativePlacement(engine, target.key())")); - assertTrue(method.contains("IrisStructureLocator.hasLocatableEditablePlacement(engine, target.key())")); + assertTrue(method.contains("ModuleServices.canLocateStructure(engine, target.key())")); assertTrue(method.contains("!IrisStructureLocator.hasNativePlacement(engine, key)")); assertTrue(method.contains("StructureReachability.isReachable(engine, target.key())")); assertTrue(method.contains("getWorldGenSettings().options().generateStructures()")); diff --git a/core/src/main/java/art/arcane/iris/core/loader/IrisData.java b/core/src/main/java/art/arcane/iris/core/loader/IrisData.java index 801c2c968..28822f017 100644 --- a/core/src/main/java/art/arcane/iris/core/loader/IrisData.java +++ b/core/src/main/java/art/arcane/iris/core/loader/IrisData.java @@ -37,7 +37,6 @@ import art.arcane.iris.core.modules.PackModuleSet; import art.arcane.iris.core.pack.PackDirectoryResolver; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.structure.StructureGraphCatalog; import art.arcane.iris.core.structure.authoring.StructureRecoveryResult; import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; @@ -592,17 +591,22 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { StructureGraphCatalog.invalidate(this); invalidateLoader(objectLoader); reloadModuleResources(); - for (Engine engine : getEngines()) { - IrisStructureLocator.invalidate(engine); - } } /** * Starts a new snapshot of the pack's resources, so the files of every module resource kind are listed and read - * again, after a tool added, rewrote or deleted some. Iris's own loaders keep their caches. + * again, after a tool added, rewrote or deleted some. Iris's own loaders keep their caches. The engines running + * with this pack restart their modules' worlds with the new snapshot, so no module keeps state built from the old + * files. */ public void reloadModuleResources() { packResources = new IrisPackResources(this); + if (closed) { + return; + } + for (Engine engine : getEngines()) { + engine.packResourcesReloaded(); + } } /** The folders below the pack root that hold its resources: Iris's loaders' and its modules' resource kinds'. */ diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java b/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java index 4f94d0bc0..5a6a8a564 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java @@ -26,6 +26,7 @@ import com.volmit.host.MantleRegistration; import com.volmit.mantle.BlockBox; import com.volmit.mantle.Mantle; import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; import java.util.Collection; @@ -47,6 +48,7 @@ final class IrisGenerationContext implements GenerationContext { private final IrisTerrainSampler terrain; private final ChunkModuleSettings settings; private final IrisModuleMantle mantle; + private PackWorld world; IrisGenerationContext(Engine engine, int originX, int originZ, BlockStateHunk blocks, IrisModuleMantle.Chunks mantleChunks, Collection> mantleLayers) { @@ -104,4 +106,13 @@ final class IrisGenerationContext implements GenerationContext { public PackResources resources() { return engine.getData().getPackResources(); } + + /** The world this invocation first asked for; it keeps it if the world restarts meanwhile. */ + @Override + public PackWorld world() { + if (world == null) { + world = engine.getGeneration().world(); + } + return world; + } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java b/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java index a9151032b..0a9bf1293 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java @@ -25,6 +25,7 @@ import com.volmit.host.MantleRegistration; import com.volmit.mantle.BlockBox; import com.volmit.mantle.Mantle; import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; import java.util.Collection; @@ -44,6 +45,7 @@ final class IrisMantleGenerationContext implements MantleGenerationContext { private final IrisTerrainSampler terrain; private final ChunkModuleSettings settings; private final IrisModuleMantle mantle; + private PackWorld world; IrisMantleGenerationContext(Engine engine, int chunkX, int chunkZ, int reachBlocks, IrisModuleMantle.Chunks chunks, Collection> layers) { @@ -92,4 +94,13 @@ final class IrisMantleGenerationContext implements MantleGenerationContext { public PackResources resources() { return engine.getData().getPackResources(); } + + /** The world this invocation first asked for; it keeps it if the world restarts meanwhile. */ + @Override + public PackWorld world() { + if (world == null) { + world = engine.getGeneration().world(); + } + return world; + } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java index 861b037c9..cddb38dd9 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java @@ -69,6 +69,7 @@ public final class IrisPackResources implements PackResources { private final Supplier>> moduleKindList; private volatile Map, Kind> moduleKinds; private volatile List moduleFolders; + private boolean announcedToModules; public IrisPackResources(IrisData data) { this(data, () -> data.getModules().pack().catalog().resourceKinds().stream() @@ -97,6 +98,18 @@ public final class IrisPackResources implements PackResources { return snapshotId; } + /** + * Runs {@code announce}, which tells the pack's modules that this snapshot loaded, unless it ran successfully for + * this snapshot before: modules hear of each snapshot once, however many worlds start with it. + */ + synchronized void loadOnce(Runnable announce) { + if (announcedToModules) { + return; + } + announce.run(); + announcedToModules = true; + } + @Override public BlockRegistry blocks() { return blocks; 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 new file mode 100644 index 000000000..c235225c5 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java @@ -0,0 +1,85 @@ +/* + * 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.engine.framework.Engine; +import com.volmit.config.PackSettings; +import com.volmit.host.WorldStates; +import com.volmit.world.PackWorld; +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 the engine through {@link #of(PackWorld)}, as built-in + * reaches do through {@link IrisPackSettings#of}. + */ +public final class IrisPackWorld implements PackWorld { + private final Engine engine; + private final IrisPackResources resources; + private final WorldStates states = new WorldStates(); + + IrisPackWorld(Engine engine) { + this.engine = engine; + this.resources = engine.getData().getPackResources(); + } + + /** Iris's own view of {@code world}, which Iris hands to every stage, service and lifecycle hook. */ + public static IrisPackWorld of(PackWorld world) { + if (!(world instanceof IrisPackWorld irisWorld)) { + throw new IllegalArgumentException("Built-in modules work in worlds Iris generates, not " + world); + } + return irisWorld; + } + + /** The engine generating this world. */ + public Engine engine() { + return engine; + } + + @Override + public long seed() { + return engine.getSeedManager().getSeed(); + } + + @Override + public IrisPackResources resources() { + return resources; + } + + @Override + public PackSettings settings() { + return new IrisPackSettings(engine); + } + + @Override + public T state(Class type, Function create) { + return states.state(type, () -> create.apply(this)); + } + + /** Whether the pack's resources were reloaded since this world was made, so it generates with an old snapshot. */ + boolean isStale() { + return engine.getData().getPackResources() != resources; + } + + /** Closes the state modules kept, such as workers that hold engine resources. */ + void closeStates() { + states.close(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPlacementInputs.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPlacementInputs.java index 4305b0b11..26723d757 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPlacementInputs.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPlacementInputs.java @@ -18,6 +18,7 @@ package art.arcane.iris.core.modules; +import art.arcane.iris.engine.framework.Engine; import com.volmit.config.FeatureSettings; import com.volmit.mantle.BlockBox; import com.volmit.object.ObjectTransformer; @@ -26,6 +27,7 @@ import com.volmit.resource.PackResources; import com.volmit.world.BiomeSample; import com.volmit.world.BlockView; import com.volmit.world.TerrainSample; +import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; /** The read-only IrisApi inputs of one Iris object placement. */ @@ -36,9 +38,14 @@ final class IrisPlacementInputs implements PlacementContext { private final FeatureSettings settings; private final BlockView blocks; private final PackResources resources; + private final Engine engine; + private PackWorld world; - IrisPlacementInputs(long worldSeed, TerrainSampler terrain, FeatureSettings settings, BlockView blocks, PackResources resources) { + /** @param engine the engine whose world the placement generates in, or null for a placement without one */ + IrisPlacementInputs(long worldSeed, TerrainSampler terrain, FeatureSettings settings, BlockView blocks, PackResources resources, + Engine engine) { this.resources = resources; + this.engine = engine; this.worldSeed = worldSeed; this.terrain = terrain; this.settings = settings; @@ -98,4 +105,16 @@ final class IrisPlacementInputs implements PlacementContext { public PackResources resources() { return resources; } + + /** The world this placement first asked for; it keeps it if the world restarts meanwhile. */ + @Override + public PackWorld world() { + if (engine == null) { + throw new IllegalStateException("This placement runs without an Iris engine, so it is not part of a world"); + } + if (world == null) { + world = engine.getGeneration().world(); + } + return world; + } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java index fb2995c78..bb42acc19 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java @@ -87,7 +87,7 @@ public final class ModuleObjectPlacement { geometry, new BlockPosition(x, requestedY, z)); IrisPlacementInputs inputs = new IrisPlacementInputs(worldSeed, terrain(engine, ids, area), new PlacementModuleSettings(worldSettings(engine, ids), config.getModuleSettings(), source), - new PlacerBlockView(placer, area, states), data.getPackResources()); + new PlacerBlockView(placer, area, states), data.getPackResources(), engine); long seed = ModuleSeeds.placement(worldSeed, objectKey, x, requestedY, z); PlacementOutcome outcome = placement.runBound(() -> new PlacementRunner(graph) .place(request, edit, inputs, seed, config.getModuleSettings().placement(source))); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java new file mode 100644 index 000000000..44a94b2c3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java @@ -0,0 +1,132 @@ +/* + * 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.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; +import com.volmit.host.FeatureCatalog; +import com.volmit.service.LocateResult; +import com.volmit.service.ObjectsAt; +import com.volmit.service.StructureLocator; +import com.volmit.world.PackWorld; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Optional; +import java.util.Set; + +/** + * What Iris core asks the pack's modules through their services ({@link com.volmit.service.Service}) instead of reading + * their features itself. Each method combines the providers the way their service says. Asking a pack whose modules + * fail to load throws its {@link PackModulesException}. + */ +public final class ModuleServices { + private ModuleServices() { + } + + /** The objects every module would place in the chunk at {@code chunkX}, {@code chunkZ}, guessed without generating it. */ + public static Set objectsAt(Engine engine, int chunkX, int chunkZ) { + PackWorld world = engine.getGeneration().world(); + Set keys = new LinkedHashSet<>(); + for (ObjectsAt provider : catalog(engine.getData()).services(ObjectsAt.class)) { + keys.addAll(provider.objectsAt(world, chunkX, chunkZ)); + } + return keys; + } + + /** Every structure key the pack's modules know, placed or not. */ + public static Set structureKeys(IrisData data) { + Set keys = new LinkedHashSet<>(); + for (StructureLocator provider : catalog(data).services(StructureLocator.class)) { + keys.addAll(provider.structures(data.getPackResources())); + } + return keys; + } + + /** The keys of the structures the world's modules place and can locate. */ + public static Set locatableStructures(Engine engine) { + PackWorld world = engine.getGeneration().world(); + Set keys = new LinkedHashSet<>(); + for (StructureLocator provider : catalog(engine.getData()).services(StructureLocator.class)) { + keys.addAll(provider.locatable(world)); + } + return keys; + } + + /** Whether a module of the world can locate structure {@code key}, matched without regard to case. */ + public static boolean canLocateStructure(Engine engine, String key) { + return structureLocatorOf(engine, key).isPresent(); + } + + /** + * Searches for the start of structure {@code key} nearest to {@code fromX}, {@code fromZ} with the first module that + * can locate it, in the world's own coordinates; not found when none can. + */ + public static StructureSearch locateStructure(Engine engine, String key, int fromX, int fromZ, int maxRadiusChunks) { + PackWorld world = engine.getGeneration().world(); + LocateResult result = structureLocatorOf(engine, key) + .map(provider -> provider.locate(world, key, fromX, fromZ, maxRadiusChunks)) + .orElse(LocateResult.NOT_FOUND); + return StructureSearch.of(result, engine); + } + + /** How a structure search ended. A found start is at {@code x}, {@code y}, {@code z}: world coordinates, Y the world's own. */ + public record StructureSearch(Outcome outcome, int x, int y, int z) { + public enum Outcome { FOUND, NOT_FOUND, SEARCH_LIMIT_REACHED } + + private static final StructureSearch NOT_FOUND = new StructureSearch(Outcome.NOT_FOUND, 0, 0, 0); + private static final StructureSearch SEARCH_LIMIT_REACHED = new StructureSearch(Outcome.SEARCH_LIMIT_REACHED, 0, 0, 0); + + public boolean found() { + return outcome == Outcome.FOUND; + } + + /** {@code result} with its height above the dimension's bottom turned into the world's Y. */ + static StructureSearch of(LocateResult result, Engine engine) { + return switch (result) { + case LocateResult.Found found -> new StructureSearch(Outcome.FOUND, found.position().x(), + found.position().y() + engine.getMinHeight(), found.position().z()); + case LocateResult.NotFound ignored -> NOT_FOUND; + case LocateResult.SearchLimitReached ignored -> SEARCH_LIMIT_REACHED; + }; + } + } + + /** The first provider, in the catalog's order, whose locatable structures hold {@code key}. */ + private static Optional structureLocatorOf(Engine engine, String key) { + if (key == null || key.isBlank()) { + return Optional.empty(); + } + PackWorld world = engine.getGeneration().world(); + String wanted = normalized(key); + for (StructureLocator provider : catalog(engine.getData()).services(StructureLocator.class)) { + if (provider.locatable(world).stream().map(ModuleServices::normalized).anyMatch(wanted::equals)) { + return Optional.of(provider); + } + } + return Optional.empty(); + } + + private static String normalized(String key) { + return key.toLowerCase(Locale.ROOT); + } + + private static FeatureCatalog catalog(IrisData data) { + return data.getModules().pack().catalog(); + } +} 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 new file mode 100644 index 000000000..aad38ec9c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleWorlds.java @@ -0,0 +1,182 @@ +/* + * 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.engine.framework.Engine; +import com.volmit.host.LifecycleRunner; + +/** + * The worlds modules see for one engine runtime, and their lifecycle ({@link com.volmit.ModuleLifecycle}). The runtime + * starts its world once it is published, and closes it when it retires: on a hotload, which builds a new runtime with a + * new world, and when the engine closes. When the pack's resources reload while the runtime runs, such as after a tool + * rewrote structure files, the world restarts in place: modules stop the old world, load the new snapshot and start a + * new world with empty state. + *

+ * An invocation keeps the world it first asked for. Iris does not wait for running invocations on an in-place restart, + * so it closes the old world's state only at the next restart or when the runtime closes, and an invocation that began + * before the restart can finish with it. + * When the pack's modules fail to load, worlds run without hooks: the failure is reported where the modules load, and + * generation reports it again. + */ +public final class ModuleWorlds { + private enum Phase { NOT_STARTED, STARTED, CLOSED } + + private final Engine engine; + private volatile IrisPackWorld current; + private IrisPackWorld retired; + private LifecycleRunner startedWith; + private Phase phase = Phase.NOT_STARTED; + + public ModuleWorlds(Engine engine) { + this.engine = engine; + } + + /** The world the runtime generates now, made the first time anyone asks. */ + public IrisPackWorld current() { + IrisPackWorld world = current; + if (world != null) { + return world; + } + synchronized (this) { + if (current == null) { + current = new IrisPackWorld(engine); + } + return current; + } + } + + /** Starts the world: tells modules about the pack snapshot if no world started with it yet, then starts the world. */ + public synchronized void start() { + if (phase != Phase.NOT_STARTED) { + throw new IllegalStateException("The modules of this Iris runtime were started already"); + } + if (current().isStale()) { + replaceUnstartedWorld(); + } + startCurrentWorld(); + phase = Phase.STARTED; + } + + /** + * The pack's resources were reloaded under the running runtime: stops the world and starts a new one with the new + * snapshot. A runtime that has not started yet only swaps its world, which then starts with the new snapshot. + */ + public synchronized void restart() { + switch (phase) { + case NOT_STARTED -> replaceUnstartedWorld(); + case STARTED -> restartStartedWorld(); + case CLOSED -> { + } + } + } + + /** Stops the world, if it started, and closes the state of the current and the previously retired world. */ + public synchronized void close() { + if (phase == Phase.CLOSED) { + return; + } + phase = Phase.CLOSED; + RuntimeException failure = attempt(this::stopCurrentWorld, null); + failure = attempt(this::closeRetiredWorld, failure); + failure = attempt(this::closeCurrentWorld, failure); + throwIfFailed(failure); + } + + /** Stops the world and starts a new one even when stopping fails, so the runtime never keeps generating unstarted. */ + private void restartStartedWorld() { + RuntimeException failure = attempt(this::stopCurrentWorld, null); + failure = attempt(this::closeRetiredWorld, failure); + retired = current; + current = null; + failure = attempt(this::startCurrentWorld, failure); + throwIfFailed(failure); + } + + /** Drops the world nothing started yet, if one was made, so the next one is made with the current snapshot. */ + private void replaceUnstartedWorld() { + IrisPackWorld unstarted = current; + current = null; + if (unstarted != null) { + unstarted.closeStates(); + } + } + + private void closeCurrentWorld() { + if (current != null) { + current.closeStates(); + } + } + + private void startCurrentWorld() { + LifecycleRunner lifecycles = lifecyclesOfPack(); + if (lifecycles == null) { + return; + } + IrisPackWorld world = current(); + world.resources().loadOnce(() -> lifecycles.packLoaded(world.resources(), new PackDeclaredSettings(engine.getData()))); + lifecycles.worldStarted(world); + startedWith = lifecycles; + } + + private void stopCurrentWorld() { + LifecycleRunner lifecycles = startedWith; + startedWith = null; + if (lifecycles != null) { + lifecycles.worldStopped(current()); + } + } + + private void closeRetiredWorld() { + if (retired == null) { + return; + } + IrisPackWorld closing = retired; + retired = null; + closing.closeStates(); + } + + /** Runs {@code step}, adding what it throws to {@code failure}, the first failure of a sequence that must not stop. */ + private static RuntimeException attempt(Runnable step, RuntimeException failure) { + try { + step.run(); + return failure; + } catch (RuntimeException stepFailure) { + if (failure == null) { + return stepFailure; + } + failure.addSuppressed(stepFailure); + return failure; + } + } + + private static void throwIfFailed(RuntimeException failure) { + if (failure != null) { + throw failure; + } + } + + /** The hooks of the modules the engine's pack loads, or null when they fail to load. */ + private LifecycleRunner lifecyclesOfPack() { + try { + return new LifecycleRunner(engine.getData().getModules().pack().catalog()); + } catch (PackModulesException failure) { + return null; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java b/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java index 42a9b863d..2ede38362 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java +++ b/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java @@ -18,7 +18,7 @@ package art.arcane.iris.core.structure; -import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.core.loader.IrisData; @@ -89,7 +89,7 @@ public final class StructureIndexService { } } - List iris = new ArrayList<>(StructureResources.structureKeys(data)); + List iris = new ArrayList<>(ModuleServices.structureKeys(data)); iris.removeIf(LEGACY_INDEX_KEY::equals); Collections.sort(vanilla); diff --git a/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java b/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java index 14c8b2606..ae2568c2d 100644 --- a/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java +++ b/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java @@ -121,6 +121,7 @@ final class EngineRuntimeBuilder { engine.getClosing().set(false); engine.backgroundTasks.openBackgroundTaskAdmission(); try { + next.generation().startModules(); next.worldManager().start(); } catch (Throwable e) { engine.getClosing().set(true); @@ -139,7 +140,7 @@ final class EngineRuntimeBuilder { if (engine.runtime == next) { engine.runtime = null; } - throw new IllegalStateException("Failed to start the Iris world manager.", e); + throw new IllegalStateException("Failed to start the Iris world's modules or its world manager.", e); } scheduleRuntimeTasks(next); IrisLogging.debug("Engine Setup Complete " + next.cacheId()); diff --git a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java index 4d5d3a892..8e26ab3bf 100644 --- a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java +++ b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine; import art.arcane.iris.engine.EngineBackgroundTasks.BackgroundTaskDrain; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.engine.EngineRuntimeBuilder.RuntimeAssembly; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineEffects; @@ -47,7 +48,6 @@ import art.arcane.iris.core.nms.container.BlockPos; import art.arcane.iris.core.nms.container.Pair; import art.arcane.iris.core.structure.StructureIndexService; import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.mantle.components.ObjectModule; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.common.plugin.VolmitSender; import art.arcane.iris.spi.PlatformBiome; @@ -387,7 +387,7 @@ public class IrisEngine implements Engine { @Override public Set getObjectsAt(int x, int z) { - return ObjectModule.placing(this).guess(x, z); + return ModuleServices.objectsAt(this, x, z); } @Override @@ -509,6 +509,15 @@ public class IrisEngine implements Engine { return current == null ? publishedTarget : current.target(); } + @Override + public void packResourcesReloaded() { + EngineRuntime current = runtime; + if (current == null) { + return; + } + current.generation().restartModules(); + } + @Override public EngineGeneration getGeneration() { RuntimeAssembly assembly = runtimeAssembly.get(); diff --git a/core/src/main/java/art/arcane/iris/engine/framework/Engine.java b/core/src/main/java/art/arcane/iris/engine/framework/Engine.java index d6b0893ec..bbc0a3d34 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/Engine.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/Engine.java @@ -91,6 +91,13 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, EngineGeneration getGeneration(); + /** + * The pack's resources were read again while this engine runs, such as after a tool rewrote some of its files: + * modules restart their world with the new snapshot (see {@link EngineGeneration#restartModules()}). Does nothing + * before the engine has a runtime, which starts with the new snapshot anyway. + */ + void packResourcesReloaded(); + EnginePlatformHooks getPlatformHooks(); /** diff --git a/core/src/main/java/art/arcane/iris/engine/framework/EngineComponent.java b/core/src/main/java/art/arcane/iris/engine/framework/EngineComponent.java index a762cdc17..22639e6cd 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/EngineComponent.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/EngineComponent.java @@ -26,7 +26,7 @@ import art.arcane.iris.spi.IrisServices; import art.arcane.volmlib.util.math.RollingSequence; import art.arcane.iris.util.common.parallel.MultiBurst; -public interface EngineComponent { +public interface EngineComponent extends AutoCloseable { Engine getEngine(); RollingSequence getMetrics(); @@ -37,6 +37,7 @@ public interface EngineComponent { return getEngine().burst(); } + @Override default void close() { try { EngineComponentCleanup cleanup = IrisServices.getOrNull(EngineComponentCleanup.class); 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 531fe624b..6e4fdaf07 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 @@ -18,7 +18,9 @@ package art.arcane.iris.engine.framework; +import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.core.modules.ModuleChunkGeneration; +import art.arcane.iris.core.modules.ModuleWorlds; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBiome; import art.arcane.iris.spi.PlatformBlockState; @@ -27,15 +29,14 @@ import art.arcane.iris.util.project.context.IrisContext; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.documentation.BlockCoordinates; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; /** * How every Iris world generates a chunk: the mantle around it first, then the pack's chunk pipeline, Iris's - * built-in stages included. It also keeps the state built-in stages hold per engine runtime, such as an - * actuator's caches, so a hotload, which builds a new runtime, starts them fresh. + * built-in stages included. It also owns the world modules see for this engine runtime ({@link ModuleWorlds}), whose + * state store keeps what stages and services hold per world, such as an actuator's caches, so a hotload, which builds + * a new runtime, starts them fresh. */ public final class EngineGeneration { private static final int CHUNK_SHIFT = 4; @@ -43,18 +44,35 @@ public final class EngineGeneration { private static final AtomicLong lastMaintenanceBypassLog = new AtomicLong(0L); private final Engine engine; - private final Map, Object> states = new ConcurrentHashMap<>(); + private final ModuleWorlds modules; public EngineGeneration(Engine engine) { this.engine = engine; + this.modules = new ModuleWorlds(engine); } /** - * The one {@code type} instance of this runtime, created by {@code create} the first time a stage asks. - * {@code create} must not ask for other state. + * The one {@code type} instance of the world this runtime generates, created by {@code create} the first time a + * stage asks; the same store as {@link IrisPackWorld#state}. See {@link com.volmit.world.PackWorld#state} for + * what {@code create} may do. */ public T state(Class type, Function create) { - return type.cast(states.computeIfAbsent(type, ignored -> create.apply(engine))); + return modules.current().state(type, ignored -> create.apply(engine)); + } + + /** The world modules see now: stage contexts, services and lifecycle hooks get it. */ + public IrisPackWorld world() { + return modules.current(); + } + + /** Starts the modules' world once the runtime is published; a module whose hook fails stops the runtime from starting. */ + public void startModules() { + modules.start(); + } + + /** Restarts the modules' world with the pack's reloaded resources; see {@link ModuleWorlds#restart()}. */ + public void restartModules() { + modules.restart(); } @BlockCoordinates @@ -80,14 +98,9 @@ public final class EngineGeneration { return bypass; } - /** Closes the state stages kept, such as actuators that hold engine resources. */ + /** Stops the modules' world and closes the state stages kept, such as actuators that hold engine resources. */ public void close() { - states.values().forEach(state -> { - if (state instanceof EngineComponent component) { - component.close(); - } - }); - states.clear(); + modules.close(); } public static boolean shouldDisableContextCacheForMaintenance(boolean maintenanceActive, boolean pregeneratorTargetsWorld) { diff --git a/core/src/main/java/art/arcane/iris/engine/framework/Locator.java b/core/src/main/java/art/arcane/iris/engine/framework/Locator.java index 74c6c309b..81fc0298e 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/Locator.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/Locator.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.nms.container.BlockPos; import art.arcane.iris.core.nms.container.Pair; @@ -58,10 +57,6 @@ public interface Locator { return new HintedLocator<>(exact, (engine) -> HintedLocator.biomePlan(engine, loadKey)); } - static Locator structure(String key) { - return (e, c) -> IrisStructureLocator.startsInChunk(e, key, c.getX(), c.getZ()); - } - static Locator poi(String type) { return (e, c) -> { Set> pos = e.getPOIsAt(c.getX(), c.getZ()); diff --git a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java index 828b1cd13..2de919e08 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java +++ b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java @@ -563,10 +563,6 @@ public final class EngineBukkitOps { find(engine, Locator.poi(type), p, teleport, "POI " + type); } - public static void gotoStructure(Engine engine, String key, Player player, boolean teleport) { - find(engine, Locator.structure(key), player, teleport, "Structure " + key); - } - private static void find(Engine engine, Locator locator, Player player, boolean teleport, String message) { find(engine, locator, player, 120_000, location -> { if (location == null) { diff --git a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandler.java b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandler.java index 9672b8053..29ef5ebab 100644 --- a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandler.java +++ b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandler.java @@ -18,6 +18,7 @@ package art.arcane.iris.util.common.director.specialhandlers; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; @@ -57,7 +58,7 @@ public class StructureHandler implements DirectorParameterHandler { } } - Set locatableKeys = IrisStructureLocator.locatableEditableKeys(activeEngine); + Set locatableKeys = ModuleServices.locatableStructures(activeEngine); for (String key : locatableKeys) { String normalizedKey = normalizeKey(key); if (!normalizedKey.isEmpty() @@ -121,7 +122,7 @@ public class StructureHandler implements DirectorParameterHandler { && IrisStructureLocator.hasLocatableNativePlacement(engine, key); boolean locatableEditableReplacement = !nativePlacement && decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS - && IrisStructureLocator.hasLocatableEditablePlacement(engine, key); + && ModuleServices.canLocateStructure(engine, key); return isEligibleRegisteredKey( decision, nativePlacement, locatableNativePlacement, locatableEditableReplacement, reachableKeys.contains(normalizedKey), nativeGenerationEnabled); diff --git a/core/src/test/java/art/arcane/iris/core/modules/BuiltInServicesTest.java b/core/src/test/java/art/arcane/iris/core/modules/BuiltInServicesTest.java new file mode 100644 index 000000000..8c95aa41b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/BuiltInServicesTest.java @@ -0,0 +1,57 @@ +/* + * 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.engine.framework.structure.StructureLocating; +import art.arcane.iris.engine.mantle.components.StructureModule; +import com.volmit.IrisModule; +import com.volmit.host.FeatureCatalog; +import com.volmit.host.LifecycleRegistration; +import com.volmit.service.ObjectsAt; +import com.volmit.service.StructureLocator; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** The services and hooks Iris's built-in modules provide, which Iris core asks instead of their features. */ +public class BuiltInServicesTest { + private static final FeatureCatalog BUILT_INS = ModuleResourceFixture.catalogOf(IrisModuleHost.builtInModules().toArray(IrisModule[]::new)); + + @Test + public void objectsTellWhichObjectsAChunkGets() { + assertEquals(1, BUILT_INS.services(ObjectsAt.class).size()); + } + + @Test + public void structuresAreFoundThroughTheStructureModule() { + List locators = BUILT_INS.services(StructureLocator.class); + assertEquals(1, locators.size()); + assertTrue(locators.getFirst() instanceof StructureLocating); + } + + @Test + public void theStructureModuleHearsWhenWorldsStop() { + assertEquals(List.of("iris:structure"), BUILT_INS.lifecycles().stream() + .map(LifecycleRegistration::module).map(module -> module.info().id().toString()).toList()); + assertTrue(BUILT_INS.lifecycles().getFirst().lifecycle() instanceof StructureModule); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/ChunkSettingsScanTimingTest.java b/core/src/test/java/art/arcane/iris/core/modules/ChunkSettingsScanTimingTest.java index cf2b38fad..578d79484 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ChunkSettingsScanTimingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ChunkSettingsScanTimingTest.java @@ -37,6 +37,7 @@ import com.volmit.resource.PackResources; import com.volmit.stage.MantleStage; import com.volmit.stage.Stage; import com.volmit.stage.StageGraph; +import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; import org.junit.Rule; import org.junit.Test; @@ -134,6 +135,7 @@ public class ChunkSettingsScanTimingTest { public FeatureSettings settings() { return settings; } public Mantle mantle() { throw new UnsupportedOperationException(); } public PackResources resources() { throw new UnsupportedOperationException(); } + public PackWorld world() { throw new UnsupportedOperationException(); } }; } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java index 40078e94e..e90d197be 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java @@ -4,6 +4,7 @@ import art.arcane.iris.core.loader.IrisData; import com.volmit.IrisModule; import com.volmit.host.DiscoveredModule; import com.volmit.host.FeatureCatalog; +import com.volmit.host.LoadedPack; import com.volmit.host.ModuleRegistry; import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; @@ -61,6 +62,15 @@ public final class ModuleResourceFixture { return registry.freeze(); } + /** Makes {@code data} (a mock) load {@code modules} as its pack's modules, so services and hooks of theirs answer. */ + public static void serveModules(IrisData data, IrisModule... modules) { + LoadedPack pack = mock(LoadedPack.class); + when(pack.catalog()).thenReturn(catalogOf(modules)); + PackModuleSet moduleSet = mock(PackModuleSet.class); + when(moduleSet.pack()).thenReturn(pack); + when(data.getModules()).thenReturn(moduleSet); + } + /** Serves {@code resource} as the resource of {@code kind} the pack names by {@code key}. */ public ModuleResourceFixture resource(ResourceKind kind, String key, T resource) { ResourceId id = idOf(key); diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java new file mode 100644 index 000000000..a66468a83 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java @@ -0,0 +1,168 @@ +/* + * 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.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineGeneration; +import art.arcane.iris.engine.framework.SeedManager; +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleHost; +import com.volmit.resource.PackResources; +import com.volmit.service.LocateResult; +import com.volmit.service.ObjectsAt; +import com.volmit.service.StructureLocator; +import com.volmit.stage.StageGraph; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +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 Iris core asks modules through services: every module's objects, and structures through the module that knows + * them, whose heights above the dimension's bottom come back as the world's Y. + */ +public class ModuleServicesTest { + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private final List searches = new ArrayList<>(); + private LoadedPack pack; + private IrisData data; + private Engine engine; + + /** Places {@code object} in every chunk and finds structure {@code structure} at a fixed spot. */ + public final class ServingModule implements IrisModule { + private final String id; + private final String object; + private final String structure; + + ServingModule(String id, String object, String structure) { + this.id = id; + this.object = object; + this.structure = structure; + } + + @Override + public ModuleInfo info() { + return ModuleInfo.of(id, "Serving " + id, "1"); + } + + @Override + public void install(StageGraph graph) { + } + + @Override + public void register(FeatureRegistry registry) { + registry.registerService(ObjectsAt.class, (world, chunkX, chunkZ) -> Set.of(object + "@" + chunkX + "," + chunkZ)); + registry.registerService(StructureLocator.class, new StructureLocator() { + @Override + public Set structures(PackResources resources) { + return Set.of(structure, structure + "/unplaced"); + } + + @Override + public Set locatable(PackWorld world) { + return Set.of(structure); + } + + @Override + public LocateResult locate(PackWorld world, String key, int fromX, int fromZ, int maxRadiusChunks) { + searches.add(id + " " + key + " " + fromX + " " + fromZ + " " + maxRadiusChunks); + return LocateResult.found(new BlockPosition(fromX + 16, 70, fromZ)); + } + }); + } + } + + @Before + public void servePack() throws IOException { + pack = LoadedPack.load(folder.newFolder("pack").toPath(), ModuleHost.of(List.of( + new ServingModule("test:zeta", "rock", "castle"), + new ServingModule("test:alpha", "tree", "tower"), + new ServingModule("test:beta", "bush", "castle"))) + .copyingJarsTo(folder.newFolder("copies").toPath())); + data = mock(IrisData.class); + PackModuleSet modules = mock(PackModuleSet.class); + when(modules.pack()).thenReturn(pack); + when(data.getModules()).thenReturn(modules); + when(data.getDataFolder()).thenReturn(folder.getRoot()); + IrisPackResources resources = new IrisPackResources(data, List::of); + when(data.getPackResources()).thenReturn(resources); + engine = mock(Engine.class); + SeedManager seeds = mock(SeedManager.class); + when(engine.getData()).thenReturn(data); + when(engine.getSeedManager()).thenReturn(seeds); + when(engine.getMinHeight()).thenReturn(-64); + EngineGeneration generation = new EngineGeneration(engine); + when(engine.getGeneration()).thenReturn(generation); + } + + @After + public void closePack() { + pack.close(); + } + + @Test + public void objectsAtCombinesEveryModulesObjectsInModuleOrder() { + assertEquals(List.of("tree@3,-4", "bush@3,-4", "rock@3,-4"), List.copyOf(ModuleServices.objectsAt(engine, 3, -4))); + } + + @Test + public void structureListsCombineEveryModule() { + assertEquals(Set.of("tower", "castle"), ModuleServices.locatableStructures(engine)); + assertEquals(Set.of("tower", "tower/unplaced", "castle", "castle/unplaced"), ModuleServices.structureKeys(data)); + } + + @Test + public void aStructureIsLocatedByTheFirstModuleThatCanLocateItIgnoringCase() { + assertTrue(ModuleServices.canLocateStructure(engine, "CASTLE")); + assertFalse(ModuleServices.canLocateStructure(engine, "castle/unplaced")); + assertFalse(ModuleServices.canLocateStructure(engine, " ")); + + ModuleServices.StructureSearch result = ModuleServices.locateStructure(engine, "Castle", 100, -200, 64); + + assertEquals(new ModuleServices.StructureSearch(ModuleServices.StructureSearch.Outcome.FOUND, 116, 70 - 64, -200), result); + assertEquals(List.of("test:beta Castle 100 -200 64"), searches); + } + + @Test + public void aStructureNoModuleCanLocateIsNotFoundWithoutSearching() { + assertEquals(ModuleServices.StructureSearch.Outcome.NOT_FOUND, + ModuleServices.locateStructure(engine, "castle/unplaced", 0, 0, 64).outcome()); + assertEquals(List.of(), searches); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleWorldsTest.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleWorldsTest.java new file mode 100644 index 000000000..9a0268d49 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleWorldsTest.java @@ -0,0 +1,260 @@ +/* + * 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.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineGeneration; +import art.arcane.iris.engine.framework.SeedManager; +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleLifecycle; +import com.volmit.config.PackSettings; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleHost; +import com.volmit.resource.PackResources; +import com.volmit.stage.StageGraph; +import com.volmit.world.PackWorld; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The world modules see for an engine runtime: it starts once the runtime is published, its state is the store built-in + * stages share, it restarts with a fresh store when the pack's resources reload, and it stops with the runtime. + */ +public class ModuleWorldsTest { + private static final long SEED = 1337L; + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private final List calls = new ArrayList<>(); + private LoadedPack pack; + private IrisData data; + private Engine engine; + private String failingHook; + + /** What a world keeps for the recording module; closing it is recorded too. */ + public static final class Remembered implements AutoCloseable { + private final List calls; + + Remembered(List calls) { + this.calls = calls; + } + + @Override + public void close() { + calls.add("closed state"); + } + } + + /** Records its hooks and builds its state when a world starts. */ + public final class RecordingModule implements IrisModule, ModuleLifecycle { + @Override + public ModuleInfo info() { + return ModuleInfo.of("test:recording", "Recording", "1"); + } + + @Override + public void install(StageGraph graph) { + } + + @Override + public void register(FeatureRegistry registry) { + registry.registerLifecycle(this); + } + + @Override + public void packLoaded(PackResources resources, PackSettings settings) { + record("loaded"); + } + + @Override + public void worldStarted(PackWorld world) { + record("started"); + world.state(Remembered.class, ignored -> new Remembered(calls)); + } + + @Override + public void worldStopped(PackWorld world) { + record("stopped"); + } + + private void record(String hook) { + calls.add(hook); + if (hook.equals(failingHook)) { + throw new IllegalStateException("cannot be " + hook); + } + } + } + + @Before + public void servePack() throws IOException { + pack = LoadedPack.load(folder.newFolder("pack").toPath(), + ModuleHost.of(List.of(new RecordingModule())).copyingJarsTo(folder.newFolder("copies").toPath())); + data = mock(IrisData.class); + PackModuleSet modules = mock(PackModuleSet.class); + when(modules.pack()).thenReturn(pack); + when(data.getModules()).thenReturn(modules); + File root = folder.getRoot(); + when(data.getDataFolder()).thenReturn(root); + reloadResources(); + engine = mock(Engine.class); + when(engine.getData()).thenReturn(data); + SeedManager seeds = mock(SeedManager.class); + when(seeds.getSeed()).thenReturn(SEED); + when(engine.getSeedManager()).thenReturn(seeds); + } + + @After + public void closePack() { + pack.close(); + } + + @Test + public void theWorldStartsWithThePackSnapshotAndTheEngineSeedAndSharesItsStoreWithBuiltInStages() { + EngineGeneration generation = generation(); + + generation.startModules(); + + IrisPackWorld world = generation.world(); + assertEquals(List.of("loaded", "started"), calls); + assertEquals(SEED, world.seed()); + assertSame(data.getPackResources(), world.resources()); + assertSame(engine, IrisPackWorld.of(world).engine()); + Remembered built = world.state(Remembered.class, ignored -> new Remembered(calls)); + assertSame(built, generation.state(Remembered.class, ignored -> new Remembered(calls))); + } + + @Test + public void reloadedResourcesRestartTheWorldWithAnEmptyStoreAndCloseTheOldStateLater() { + EngineGeneration generation = generation(); + generation.startModules(); + IrisPackWorld first = generation.world(); + Remembered firstState = first.state(Remembered.class, ignored -> new Remembered(calls)); + calls.clear(); + + reloadResources(); + generation.restartModules(); + + IrisPackWorld second = generation.world(); + assertNotSame(first, second); + assertSame(data.getPackResources(), second.resources()); + assertEquals(List.of("stopped", "loaded", "started"), calls); + assertNotSame(firstState, second.state(Remembered.class, ignored -> new Remembered(calls))); + assertSame("a running invocation may still use the old world", firstState, first.state(Remembered.class, ignored -> null)); + + calls.clear(); + reloadResources(); + generation.restartModules(); + assertEquals(List.of("stopped", "closed state", "loaded", "started"), calls); + assertThrows(IllegalStateException.class, () -> first.state(Remembered.class, ignored -> null)); + } + + @Test + public void closingTheRuntimeStopsTheWorldAndClosesItsState() { + EngineGeneration generation = generation(); + generation.startModules(); + IrisPackWorld world = generation.world(); + calls.clear(); + + generation.close(); + generation.close(); + + assertEquals(List.of("stopped", "closed state"), calls); + assertThrows(IllegalStateException.class, () -> world.state(Remembered.class, ignored -> null)); + } + + @Test + public void everyWorldOfOneSnapshotStartsButThePackLoadsOnce() { + EngineGeneration first = generation(); + EngineGeneration second = generation(); + + first.startModules(); + second.startModules(); + + assertEquals(List.of("loaded", "started", "started"), calls); + } + + @Test + public void aRuntimeThatStartsAfterAReloadStartsWithTheNewSnapshot() { + EngineGeneration generation = generation(); + IrisPackWorld madeEarly = generation.world(); + + reloadResources(); + generation.startModules(); + + assertNotSame(madeEarly, generation.world()); + assertSame(data.getPackResources(), generation.world().resources()); + } + + @Test + public void aModuleThatFailsToStartStopsTheRuntimeFromStartingAndIsNotStoppedLater() { + failingHook = "started"; + EngineGeneration generation = generation(); + + IllegalStateException failure = assertThrows(IllegalStateException.class, generation::startModules); + assertTrue(failure.getMessage(), failure.getMessage().contains("test:recording")); + + calls.clear(); + generation.close(); + assertEquals(List.of(), calls); + } + + @Test + public void aPackWhoseModulesFailToLoadRunsItsWorldWithoutHooks() { + PackModuleSet broken = mock(PackModuleSet.class); + when(broken.pack()).thenThrow(new PackModulesException(folder.getRoot(), new IllegalArgumentException("broken jar"))); + when(data.getModules()).thenReturn(broken); + EngineGeneration generation = generation(); + + generation.startModules(); + generation.world().state(Remembered.class, ignored -> new Remembered(calls)); + generation.close(); + + assertEquals(List.of("closed state"), calls); + } + + private EngineGeneration generation() { + return new EngineGeneration(engine); + } + + /** A new snapshot of the pack's resources, as {@link IrisData#reloadModuleResources()} makes. */ + private void reloadResources() { + IrisPackResources resources = new IrisPackResources(data, List::of); + when(data.getPackResources()).thenReturn(resources); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java b/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java index d63ba98a7..5397dfced 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java @@ -3,6 +3,7 @@ package art.arcane.iris.core.structure; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; @@ -105,6 +106,7 @@ public class StructureIndexServiceTest { IrisPlatform platform = mock(IrisPlatform.class); PlatformStructureHooks structureHooks = mock(PlatformStructureHooks.class); when(data.getDataFolder()).thenReturn(pack); + ModuleResourceFixture.serveModules(data, new StructureModule()); ModuleResourceFixture.serve(data) .resource(StructureResources.STRUCTURES, "castle", new IrisStructure()) .resource(StructureResources.STRUCTURES, "structure-index", new IrisStructure()); diff --git a/core/src/test/java/art/arcane/iris/engine/actuator/DecorantModuleTest.java b/core/src/test/java/art/arcane/iris/engine/actuator/DecorantModuleTest.java index e9558a04a..343e14f78 100644 --- a/core/src/test/java/art/arcane/iris/engine/actuator/DecorantModuleTest.java +++ b/core/src/test/java/art/arcane/iris/engine/actuator/DecorantModuleTest.java @@ -1,6 +1,8 @@ package art.arcane.iris.engine.actuator; +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.framework.EngineMetrics; import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.object.world.biome.IrisBiome; @@ -10,8 +12,12 @@ import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.project.context.ChunkedDataCache; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.collection.KList; +import com.volmit.world.PackWorld; import org.junit.Test; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -19,8 +25,26 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -/** Decorating reads nothing of the chunk when the dimension does not decorate, and skips biomes without decorators. */ +/** + * Decorating reads nothing of the chunk when the dimension does not decorate, skips biomes without decorators, and is + * kept per world in the world's state store. + */ public class DecorantModuleTest { + @Test + public void eachWorldKeepsOneDecoratingInItsStateStore() { + Engine engine = engine(true); + when(engine.getData()).thenReturn(mock(IrisData.class)); + EngineGeneration generation = new EngineGeneration(engine); + PackWorld world = generation.world(); + + DecorantModule.Decorating decorating = DecorantModule.decorating(world); + + assertSame(decorating, DecorantModule.decorating(world)); + assertSame("built-in stages share the store", decorating, + generation.state(DecorantModule.Decorating.class, DecorantModule.Decorating::new)); + assertNotSame(decorating, DecorantModule.decorating(new EngineGeneration(engine).world())); + } + @Test public void aDimensionThatDoesNotDecorateIsLeftAlone() { DecorantModule.Decorating decorating = new DecorantModule.Decorating(engine(false)); diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java index a9ed7bb2a..2c6a07efb 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.core.modules.IrisModuleHost; import art.arcane.iris.core.project.ModuleResourceSchemas; import art.arcane.iris.core.project.SchemaTestPlatform; @@ -20,6 +21,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -55,6 +57,17 @@ public class StructureResourcesTest { } } + @Test + public void theStructureModuleListsThePacksStructuresForIrissIndexThroughItsLocator() throws Exception { + IrisData data = IrisData.openValidation(castlePack("listed").toFile()); + try { + assertEquals(Set.of("castle"), new StructureLocating().structures(data.getPackResources())); + assertEquals(Set.of("castle"), ModuleServices.structureKeys(data)); + } finally { + data.close(); + } + } + @Test public void structuresPoolsAndPiecesAreReadThroughPackResources() throws Exception { Path pack = castlePack("castles"); diff --git a/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java b/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java index d53863da5..06a69e7bc 100644 --- a/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java +++ b/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java @@ -4,7 +4,9 @@ import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.modules.ModuleResourceFixture; 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.framework.IrisStructureLocator; +import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl; @@ -107,6 +109,8 @@ public class StructureHandlerTest { ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:custom_definition", custom); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:collision_definition", collision); when(engine.getData()).thenReturn(data); + ModuleResourceFixture.serveModules(data, new StructureModule()); + when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); when(engine.getDimension()).thenReturn(dimension); when(engine.getWorld()).thenReturn(world); when(engine.getMinHeight()).thenReturn(-64); @@ -178,6 +182,8 @@ public class StructureHandlerTest { ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:editable_definition", editable); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:replacement_definition", replacement); when(engine.getData()).thenReturn(data); + ModuleResourceFixture.serveModules(data, new StructureModule()); + when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); when(engine.getDimension()).thenReturn(dimension); when(engine.getWorld()).thenReturn(world); when(engine.getMinHeight()).thenReturn(-64); @@ -244,7 +250,7 @@ public class StructureHandlerTest { assertEquals(1, occurrences(method, "StructureReachability.reachableKeys(activeEngine)")); assertEquals(0, occurrences(method, "IrisStructureLocator.locatableKeys(activeEngine)")); - assertEquals(1, occurrences(method, "IrisStructureLocator.locatableEditableKeys(activeEngine)")); + assertEquals(1, occurrences(method, "ModuleServices.locatableStructures(activeEngine)")); assertTrue(method.indexOf("if (activeEngine == null)") < method.indexOf("IrisPlatforms.get().structureHooks()")); assertFalse(method.contains("INMS"));