diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDeveloper.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDeveloper.java index 9e6ac7ec9..a22d29625 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDeveloper.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDeveloper.java @@ -24,7 +24,6 @@ import art.arcane.iris.pack.datapack.ServerConfigurator; import art.arcane.iris.pack.datapack.DataVersion; import art.arcane.iris.world.runtime.ChunkClearer; import art.arcane.iris.generation.validation.GoldenHashScanner; -import art.arcane.iris.world.runtime.InPlaceChunkRegenerator; import art.arcane.iris.generation.runtime.IrisEngineSVC; import art.arcane.iris.pack.IrisPackBenchmarking; import art.arcane.iris.world.IrisToolbelt; @@ -305,51 +304,6 @@ public class CommandDeveloper implements DirectorExecutor { } } - // --- Regen --- - - @Director(name = "regen", aliases = {"rg"}, description = "Delete and regenerate nearby chunks in place using Iris generation", descriptionKey = "iris.director.commanddeveloper.director.delete_regenerate_nearby_chunks_place_using_iris_generation", origin = DirectorOrigin.PLAYER) - public void regen( - @Param(name = "radius", description = "The radius of nearby chunks", descriptionKey = "iris.director.commanddeveloper.param.radius_nearby_chunks", defaultValue = "5") - int radius - ) { - if (radius < 0) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_RADIUS_MUST_BE_0_GREATER_2)); - return; - } - - Player player = player(); - VolmitSender commandSender = sender(); - World world = player.getWorld(); - if (!IrisToolbelt.isIrisWorld(world)) { - commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_YOU_MUST_BE_IRIS_WORLD_USE_REGEN)); - return; - } - - Engine engine = IrisToolbelt.access(world).getEngine(); - if (engine == null) { - commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_ENGINE_ACCESS_THIS_WORLD_IS_NULL_GENERATE_NEARBY_CHUNKS_FIRST)); - return; - } - - int chunks = (radius * 2 + 1) * (radius * 2 + 1); - - // The player position must be read on the thread owning the player; the regenerator hops per chunk itself. - if (!J.runEntity(player, () -> { - int centerX = player.getLocation().getBlockX() >> 4; - int centerZ = player.getLocation().getBlockZ() >> 4; - - commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_REGEN_STARTED_CHUNK_S_AROUND_DELETING_REGENERATING_PLACE, MessageArgument.untrusted("chunks", chunks), MessageArgument.untrusted("centerX", centerX), MessageArgument.untrusted("centerZ", centerZ))); - Iris.info("Regen run start: world=" + world.getName() - + " center=" + centerX + "," + centerZ - + " radius=" + radius - + " chunks=" + chunks); - - new InPlaceChunkRegenerator(world, engine, commandSender, centerX, centerZ, radius).start(); - })) { - Iris.warn("Could not schedule regen on the thread owning " + player.getName() + "."); - } - } - @Director(name = "goldenhash", aliases = {"gold"}, description = "Generate chunks into buffers (no world writes) and hash blocks+biomes; captures a golden file or verifies against an existing one. Deletes the world's entire mantle - use on disposable test worlds.", descriptionKey = "iris.director.commanddeveloper.director.generate_chunks_into_buffers_no_world_writes_hash_blocks_biomes_captures_golden", origin = DirectorOrigin.BOTH) public void goldenhash( @Param(description = "The world to scan", descriptionKey = "iris.director.commanddeveloper.param.world_scan", contextual = true, contextualOverride = true) diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java index 7bc889a94..bbeb9a730 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java @@ -34,6 +34,7 @@ import art.arcane.iris.structure.BulkStructureImporter; import art.arcane.iris.structure.FeatureImporter; import art.arcane.iris.structure.StructureImporter; import art.arcane.iris.world.IrisToolbelt; +import art.arcane.iris.world.runtime.InPlaceChunkRegenerator; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.world.loot.InventorySlotType; import art.arcane.iris.generation.biome.IrisBiome; @@ -220,6 +221,49 @@ public class CommandStudio implements DirectorExecutor { LanguageAudience.run(audience, () -> sendHotloadResult(commandSender, failure))); } + @Director(name = "regen", aliases = {"rg"}, description = "Delete and regenerate nearby chunks in place using Iris generation", descriptionKey = "iris.director.commanddeveloper.director.delete_regenerate_nearby_chunks_place_using_iris_generation", origin = DirectorOrigin.PLAYER) + public void regen( + @Param(name = "radius", description = "The radius of nearby chunks", descriptionKey = "iris.director.commanddeveloper.param.radius_nearby_chunks", defaultValue = "5") + int radius + ) { + if (radius < 0) { + sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_RADIUS_MUST_BE_0_GREATER_2)); + return; + } + + Player player = player(); + VolmitSender commandSender = sender(); + World world = player.getWorld(); + if (!IrisToolbelt.isIrisWorld(world)) { + commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_YOU_MUST_BE_IRIS_WORLD_USE_REGEN)); + return; + } + + Engine engine = IrisToolbelt.access(world).getEngine(); + if (engine == null) { + commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_ENGINE_ACCESS_THIS_WORLD_IS_NULL_GENERATE_NEARBY_CHUNKS_FIRST)); + return; + } + + int chunks = (radius * 2 + 1) * (radius * 2 + 1); + + // The player position must be read on the thread owning the player; the regenerator hops per chunk itself. + if (!J.runEntity(player, () -> { + int centerX = player.getLocation().getBlockX() >> 4; + int centerZ = player.getLocation().getBlockZ() >> 4; + + commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_REGEN_STARTED_CHUNK_S_AROUND_DELETING_REGENERATING_PLACE, MessageArgument.untrusted("chunks", chunks), MessageArgument.untrusted("centerX", centerX), MessageArgument.untrusted("centerZ", centerZ))); + Iris.info("Regen run start: world=" + world.getName() + + " center=" + centerX + "," + centerZ + + " radius=" + radius + + " chunks=" + chunks); + + new InPlaceChunkRegenerator(world, engine, commandSender, centerX, centerZ, radius).start(); + })) { + Iris.warn("Could not schedule regen on the thread owning " + player.getName() + "."); + } + } + @Director(description = "Toggle your Studio debug scoreboard", descriptionKey = "iris.director.commandstudio.director.toggle_your_studio_debug_scoreboard", aliases = {"board", "sidebar", "sb"}, origin = DirectorOrigin.PLAYER) public void scoreboard() { Player target = player(); diff --git a/adapters/bukkit/plugin/src/test/gameplay/ce-native.mjs b/adapters/bukkit/plugin/src/test/gameplay/ce-native.mjs index 33e2bd6fd..57e017ee7 100644 --- a/adapters/bukkit/plugin/src/test/gameplay/ce-native.mjs +++ b/adapters/bukkit/plugin/src/test/gameplay/ce-native.mjs @@ -27,7 +27,7 @@ export default { await context.step('regeneration removes target furniture and preserves neighbor ownership', async () => { const ready = await context.command('/iriscenative neighbor', /CE_NEIGHBOR_READY|CE_FAILED/, 30000) context.expect(ready.includes('CE_NEIGHBOR_READY chunk=2,0 furniture=3 target=1'), ready) - const regenerated = await context.command('/iris developer regen radius=0', /Regen complete:|Regen failed:/, 90000) + const regenerated = await context.command('/iris studio regen radius=0', /Regen complete:|Regen failed:/, 90000) context.expect(regenerated.includes('Regen complete:'), regenerated) const response = await context.command('/iriscenative loaded', /CE_LOADED|CE_FAILED/, 30000) context.expect(response.includes('CE_LOADED removed=1 untouched=1 replacement=1 wall=1 target=1'), response) diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java index 7b639f441..b87c7383c 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java @@ -73,7 +73,6 @@ final class ModdedCommandHelp { Entry.command("catalog", "[namespace|refresh]", ModdedCatalogMessages.HELP_CATALOG), Entry.group("ingest", ModdedCatalogMessages.HELP_INGEST), Entry.command("metrics", "", ModdedHelpMessages.COMMAND_METRICS_PRINT_GENERATION_METRICS_FOR_YOUR_CURRENT_IRIS_DIMENSION, "measure"), - Entry.command("regen", "[radius]", ModdedHelpMessages.COMMAND_REGEN_DELETE_AND_REGENERATE_NEARBY_CHUNKS_IN_PLACE, "rg"), Entry.group("pregen", ModdedHelpMessages.GROUP_PREGEN_PREGENERATE_AN_IRIS_DIMENSION, "pregenerate"), Entry.command("wand", "", ModdedHelpMessages.COMMAND_WAND_GET_AN_IRIS_OBJECT_WAND), Entry.command("dust", "", ModdedHelpMessages.COMMAND_DUST_GET_DUST_THAT_REVEALS_OBJECT_PLACEMENTS, "d"), @@ -151,6 +150,7 @@ final class ModdedCommandHelp { Entry.command("tpstudio", "", ModdedHelpMessages.COMMAND_TPSTUDIO_TELEPORT_INTO_THE_OPEN_STUDIO_DIMENSION, "stp"), Entry.command("status", "", ModdedHelpMessages.COMMAND_STATUS_SHOW_THE_OPEN_STUDIO_DIMENSION_AND_ITS_PACK), Entry.command("hotload", "", ModdedHelpMessages.COMMAND_HOTLOAD_REFRESH_THE_OPEN_STUDIO, "refresh"), + Entry.command("regen", "[radius]", ModdedHelpMessages.COMMAND_REGEN_DELETE_AND_REGENERATE_NEARBY_CHUNKS_IN_PLACE, "rg"), Entry.command("noise", "[generator] [seed]", ModdedHelpMessages.COMMAND_NOISE_OPEN_THE_NOISE_EXPLORER_GUI_ON_THE_SERVER_DISPLAY, "nmap"), Entry.command("map", "", ModdedHelpMessages.COMMAND_MAP_OPEN_THE_VISION_MAP_GUI_ON_THE_SERVER_DISPLAY, "render"), Entry.command("vscode", "[pack]", ModdedHelpMessages.COMMAND_VSCODE_REGENERATE_THE_CODE_WORKSPACE_FOR_A_PACK_AND_OPEN_IT_IN_YOUR, "vsc"), diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java index 6cb25508e..f6133a1e0 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java @@ -120,9 +120,6 @@ final class ModdedCommandTree { root.then(metricsTree("metrics")); root.then(metricsTree("measure")); - root.then(regenTree("regen")); - root.then(regenTree("rg")); - root.then(pregenTree("pregen")); root.then(pregenTree("pregenerate")); @@ -222,13 +219,6 @@ final class ModdedCommandTree { .executes(ModdedCommandTree.localized((CommandContext context) -> IrisModdedCommands.metrics(context.getSource()))); } - private static LiteralArgumentBuilder regenTree(String name) { - return NativeCommandRegistration.literal(name).requires(GATE) - .executes(ModdedCommandTree.localized((CommandContext context) -> IrisModdedCommands.regen(context.getSource(), 0))) - .then(NativeCommandRegistration.argument("radius", IntegerArgumentType.integer(0, 64)) - .executes(ModdedCommandTree.localized((CommandContext context) -> IrisModdedCommands.regen(context.getSource(), IntegerArgumentType.getInteger(context, "radius"))))); - } - private static LiteralArgumentBuilder gotoTree(String name) { return NativeCommandRegistration.literal(name).requires(GATE) .executes(ModdedCommandTree.localized((CommandContext context) -> ModdedCommandHelp.send(context.getSource(), name))) diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java index ea415b719..76f4b45e8 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java @@ -159,6 +159,8 @@ public final class ModdedStudioCommands { .executes(ModdedCommandTree.localized((CommandContext context) -> hotload(context.getSource())))); root.then(NativeCommandRegistration.literal("refresh") .executes(ModdedCommandTree.localized((CommandContext context) -> hotload(context.getSource())))); + root.then(regenTree("regen")); + root.then(regenTree("rg")); root.then(workspaceTree("vscode", true)); root.then(workspaceTree("vsc", true)); root.then(workspaceTree("update", false)); @@ -210,6 +212,13 @@ public final class ModdedStudioCommands { STUDIOS.clear(); } + private static LiteralArgumentBuilder regenTree(String name) { + return NativeCommandRegistration.literal(name) + .executes(ModdedCommandTree.localized((CommandContext context) -> IrisModdedCommands.regen(context.getSource(), 0))) + .then(NativeCommandRegistration.argument("radius", IntegerArgumentType.integer(0, 64)) + .executes(ModdedCommandTree.localized((CommandContext context) -> IrisModdedCommands.regen(context.getSource(), IntegerArgumentType.getInteger(context, "radius"))))); + } + private static LiteralArgumentBuilder openTree(String name) { return NativeCommandRegistration.literal(name) .executes(ModdedCommandTree.localized((CommandContext context) -> openHelp(context.getSource()))) diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java index 9b881691b..dd3225b2e 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java @@ -206,6 +206,23 @@ public class IrisModdedCommandParityTest { assertNotNull("pack cp", child(child(iris, "pk"), "cp").getCommand()); } + @Test + public void regenLivesUnderStudio() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + CommandDispatcher dispatcher = new CommandDispatcher<>(); + + IrisModdedCommands.register(new NativeCommandRegistration(dispatcher)); + + CommandNode iris = child(dispatcher.getRoot(), "iris"); + assertNotNull("std regen", child(child(iris, "std"), "regen").getCommand()); + assertNotNull("studio rg radius", child(child(child(iris, "studio"), "rg"), "radius").getCommand()); + assertNull("top-level regen", iris.getChild("regen")); + assertNull("top-level rg", iris.getChild("rg")); + assertTrue(ModdedCommandHelp.consoleLines("studio").stream().anyMatch((String line) -> + line.startsWith("/iris studio regen [radius] (rg) - "))); + } + @Test public void consoleHelpListsEveryEntryWithInlineUsageAndDescription() { List root = ModdedCommandHelp.consoleLines(""); diff --git a/core/src/main/java/art/arcane/iris/platform/generation/BukkitChunkGenerator.java b/core/src/main/java/art/arcane/iris/platform/generation/BukkitChunkGenerator.java index 668a2c7df..7a9a76536 100644 --- a/core/src/main/java/art/arcane/iris/platform/generation/BukkitChunkGenerator.java +++ b/core/src/main/java/art/arcane/iris/platform/generation/BukkitChunkGenerator.java @@ -1086,11 +1086,23 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun withExclusiveControl(() -> { if (!studioUpdatesPaused && !closing) { - getEngine().hotload(); + hotloadEngine(); } }); } + private void hotloadEngine() { + Engine activeEngine = getEngine(); + long started = M.ms(); + activeEngine.hotload(); + IrisLogging.info("Hotloaded " + packKeyOf(activeEngine) + " in " + (M.ms() - started) + "ms"); + } + + private static String packKeyOf(Engine activeEngine) { + IrisDimension dimension = activeEngine.getDimension(); + return dimension == null ? "unknown pack" : dimension.getLoadKey(); + } + @Override public CompletableFuture hotloadAsync() { if (!canHotloadStudio()) { @@ -1100,7 +1112,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun if (!canHotloadStudio()) { throw new IllegalStateException("Studio is not ready for hotload."); } - getEngine().hotload(); + hotloadEngine(); }); } @@ -1125,7 +1137,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun if (!initialEntryPending && !studioUpdatesPaused && shouldRunStudioHotload(isStudio(), closing, jigsawStudioActive)) { IrisLogging.debug("Studio update admission: world=%s wait=%dms", getTarget().getWorld().name(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - queuedAt)); - getEngine().hotload(); + hotloadEngine(); } }, pending)); } diff --git a/core/src/main/java/art/arcane/iris/world/runtime/ChunkJobReporter.java b/core/src/main/java/art/arcane/iris/world/runtime/ChunkJobReporter.java index e51454837..3ff8b2acc 100644 --- a/core/src/main/java/art/arcane/iris/world/runtime/ChunkJobReporter.java +++ b/core/src/main/java/art/arcane/iris/world/runtime/ChunkJobReporter.java @@ -56,6 +56,7 @@ public final class ChunkJobReporter { private final AtomicBoolean failed = new AtomicBoolean(false); private final AtomicInteger applied = new AtomicInteger(0); private final AtomicInteger failures = new AtomicInteger(0); + private final AtomicInteger skipped = new AtomicInteger(0); private volatile int total = 0; private volatile long startMs = 0L; @@ -89,7 +90,17 @@ public final class ChunkJobReporter { failures.incrementAndGet(); } - int finished = applied.get() + failures.get(); + updateProgress(); + } + + /** A chunk the job had nothing to do for. It leaves the total, so the summary only counts chunks the job worked on. */ + public void countSkipped() { + skipped.incrementAndGet(); + updateProgress(); + } + + private void updateProgress() { + int finished = applied.get() + failures.get() + skipped.get(); if (total > 0) { progress.set(Math.min(0.999D, (double) finished / total)); } @@ -97,10 +108,18 @@ public final class ChunkJobReporter { public void finish(boolean error) { progress.set(1.0D); - failed.set(error || (applied.get() == 0 && total > 0)); + failed.set(error || (applied.get() == 0 && workedTotal() > 0)); complete.set(true); } + public int skipped() { + return skipped.get(); + } + + private int workedTotal() { + return total - skipped.get(); + } + public int applied() { return applied.get(); } @@ -151,7 +170,7 @@ public final class ChunkJobReporter { MessageArgument.trusted("percent", percent), MessageArgument.trusted("stage", stage.get()), MessageArgument.trusted("applied", applied.get()), - MessageArgument.trusted("total", total <= 0 ? "?" : total) + MessageArgument.trusted("total", total <= 0 ? "?" : workedTotal()) )); } }, REPORT_INTERVAL_TICKS)); @@ -166,14 +185,14 @@ public final class ChunkJobReporter { ? IrisLanguage.text( RuntimeProgressMessages.CHUNK_SUMMARY_FAILED, MessageArgument.trusted("applied", applied.get()), - MessageArgument.trusted("total", total), + MessageArgument.trusted("total", workedTotal()), MessageArgument.trusted("elapsed", Form.duration(elapsed, 1)), MessageArgument.trusted("failures", failures.get()) ) : IrisLanguage.text( RuntimeProgressMessages.CHUNK_SUMMARY, MessageArgument.trusted("applied", applied.get()), - MessageArgument.trusted("total", total), + MessageArgument.trusted("total", workedTotal()), MessageArgument.trusted("elapsed", Form.duration(elapsed, 1)) ); diff --git a/core/src/main/java/art/arcane/iris/world/runtime/InPlaceChunkRegenerator.java b/core/src/main/java/art/arcane/iris/world/runtime/InPlaceChunkRegenerator.java index 319536a6f..b8b3b0f17 100644 --- a/core/src/main/java/art/arcane/iris/world/runtime/InPlaceChunkRegenerator.java +++ b/core/src/main/java/art/arcane/iris/world/runtime/InPlaceChunkRegenerator.java @@ -25,8 +25,13 @@ import art.arcane.iris.platform.bukkit.nms.INMS; import art.arcane.iris.generation.chunk.TerrainChunk; import art.arcane.iris.generation.chunk.ChunkDataHunkView; import art.arcane.iris.generation.chunk.TerrainChunkBiomeHunkView; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.platform.generation.BukkitChunkGenerator; +import art.arcane.iris.platform.generation.BukkitChunkGenerator.GenerationStagePermit; import art.arcane.iris.platform.generation.EngineBukkitOps; import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.WrongEngineBroException; +import art.arcane.iris.world.IrisToolbelt; import art.arcane.iris.generation.mantle.EngineMantle; import art.arcane.iris.generation.mantle.DeferredPlacementRecords; import art.arcane.volmlib.nativelib.terrain.NativeBiome; @@ -46,8 +51,11 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator.ChunkData; +import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; @@ -55,6 +63,8 @@ import java.util.function.Consumer; public final class InPlaceChunkRegenerator { private static final int BIOME_STEP = 4; private static final int APPLY_AHEAD = 8; + private static final int PROBE_BATCH_CHUNKS = 256; + private static final String GENERATION_STAGE = "regen"; private final World world; private final Engine engine; @@ -89,6 +99,7 @@ public final class InPlaceChunkRegenerator { reporter.setTotal(targets.size()); reporter.setStage(IrisLanguage.text(RuntimeProgressMessages.CHUNK_STAGE_REGENERATING)); regenerate(targets); + logSkippedChunks(); } catch (Throwable e) { IrisLogging.reportError(e); error = true; @@ -97,6 +108,14 @@ public final class InPlaceChunkRegenerator { } } + private void logSkippedChunks() { + if (reporter.skipped() == 0) { + return; + } + IrisLogging.info("Regen skipped " + reporter.skipped() + " chunks in " + world.getName() + + " that were never generated; they generate fresh when visited."); + } + private void resetMantleMargin() { EngineMantle engineMantle = engine.getMantle(); Mantle mantle = engineMantle.getMantle(); @@ -111,59 +130,133 @@ public final class InPlaceChunkRegenerator { private void regenerate(List targets) throws InterruptedException { Semaphore inFlight = new Semaphore(APPLY_AHEAD); - CountDownLatch allApplied = new CountDownLatch(targets.size()); - for (int[] target : targets) { - int chunkX = target[0]; - int chunkZ = target[1]; + for (int from = 0; from < targets.size(); from += PROBE_BATCH_CHUNKS) { + List batch = targets.subList(from, Math.min(targets.size(), from + PROBE_BATCH_CHUNKS)); + for (int[] generated : generatedChunksOf(batch)) { + inFlight.acquire(); + MultiBurst.burst.lazy(() -> regenerateChunk(generated[0], generated[1], inFlight::release)); + } + } - inFlight.acquire(); - MultiBurst.burst.lazy(() -> { - // Settle exactly once no matter which path fails: an unguarded throw here - // (TerrainChunk.create, runRegion) parked the regen thread on the latch - // forever and stranded the player's boss bar. CAS is required — on Folia's - // owned-region path runRegion runs the apply inline before returning. - AtomicBoolean settled = new AtomicBoolean(); - Consumer settle = ok -> { - if (settled.compareAndSet(false, true)) { - reporter.countApplied(ok); - inFlight.release(); - allApplied.countDown(); - } - }; - try { - TerrainChunk buffer = TerrainChunk.create(world); - engine.generate(chunkX << 4, chunkZ << 4, new ChunkDataHunkView(buffer.getChunkData()), - new TerrainChunkBiomeHunkView(buffer), false); + inFlight.acquire(APPLY_AHEAD); + } - boolean scheduled = J.runRegion(world, chunkX, chunkZ, () -> { - boolean ok = false; - try { - applyToLiveChunk(chunkX, chunkZ, buffer); - ok = true; - } catch (Throwable e) { - IrisLogging.reportError(e); - } finally { - settle.accept(ok); - } - }); + /** + * Chunks that were never generated are skipped: their mantle is reset, so they generate fresh when first visited. + * Regenerating them here would generate each one twice, and loading them on the server thread stalls it. + */ + private List generatedChunksOf(List batch) { + List> loads = new ArrayList<>(batch.size()); + for (int[] target : batch) { + loads.add(loadIfGenerated(target[0], target[1])); + } - if (!scheduled) { - IrisLogging.warn("Regen could not schedule chunk apply at " + chunkX + "," + chunkZ + " in " + world.getName() + "."); - settle.accept(false); - } - } catch (Throwable e) { - IrisLogging.reportError(e); + List generated = new ArrayList<>(batch.size()); + for (int index = 0; index < batch.size(); index++) { + try { + if (loads.get(index).join() == null) { + reporter.countSkipped(); + continue; + } + generated.add(batch.get(index)); + } catch (CompletionException | CancellationException e) { + IrisLogging.reportError(e); + reporter.countApplied(false); + } + } + return generated; + } + + /** Spigot has no async chunk loading, so its fallback loads in place; that must happen on the server thread. */ + private CompletableFuture loadIfGenerated(int chunkX, int chunkZ) { + if (BukkitPlatform.isPaperServer()) { + return BukkitPlatform.chunkAtAsync(world, chunkX, chunkZ, false); + } + return J.sfut(() -> BukkitPlatform.chunkAtAsync(world, chunkX, chunkZ, false)).thenCompose(load -> load); + } + + private void regenerateChunk(int chunkX, int chunkZ, Runnable release) { + // Settle exactly once no matter which path fails: an unguarded throw stranded the regen thread and the + // player's boss bar. CAS is required because the apply can run inline, before the scheduling call returns. + AtomicBoolean settled = new AtomicBoolean(); + Consumer settle = ok -> { + if (settled.compareAndSet(false, true)) { + reporter.countApplied(ok); + release.run(); + } + }; + try { + TerrainChunk buffer = generate(chunkX, chunkZ); + loadIfGenerated(chunkX, chunkZ).whenComplete((chunk, loadFailure) -> { + if (loadFailure != null) { + IrisLogging.reportError(loadFailure); + } + if (!scheduledApply(chunk, buffer, settle)) { settle.accept(false); } }); + } catch (Throwable e) { + IrisLogging.reportError(e); + settle.accept(false); } - - allApplied.await(); } - private void applyToLiveChunk(int chunkX, int chunkZ, TerrainChunk buffer) { - Chunk chunk = world.getChunkAt(chunkX, chunkZ); + /** + * @return false when the apply could not be handed to the thread owning the chunk, so the caller settles the chunk + * as failed; true leaves settling to the apply. + */ + private boolean scheduledApply(Chunk chunk, TerrainChunk buffer, Consumer settle) { + if (chunk == null) { + IrisLogging.warn("Regen could not load a chunk it found generated in " + world.getName() + "."); + return false; + } + try { + return runOnThreadOwning(chunk, () -> settle.accept(applied(chunk, buffer))); + } catch (Throwable e) { + IrisLogging.reportError(e); + return false; + } + } + + /** Holds a generation stage like any chunk the server generates, so a hotload waits for it instead of rejecting it. */ + private TerrainChunk generate(int chunkX, int chunkZ) throws WrongEngineBroException { + TerrainChunk buffer = TerrainChunk.create(world); + try (GenerationStagePermit ignored = acquireGenerationStage()) { + engine.generate(chunkX << 4, chunkZ << 4, new ChunkDataHunkView(buffer.getChunkData()), + new TerrainChunkBiomeHunkView(buffer), false); + } + return buffer; + } + + private GenerationStagePermit acquireGenerationStage() { + if (IrisToolbelt.access(world) instanceof BukkitChunkGenerator generator) { + return generator.acquireGenerationStage(GENERATION_STAGE); + } + return GenerationStagePermit.noop(); + } + + private boolean runOnThreadOwning(Chunk chunk, Runnable task) { + if (!J.isFolia() && J.isPrimaryThread()) { + task.run(); + return true; + } + return J.runRegion(world, chunk.getX(), chunk.getZ(), task); + } + + private boolean applied(Chunk chunk, TerrainChunk buffer) { + try { + applyToLiveChunk(chunk, buffer); + return true; + } catch (Throwable e) { + IrisLogging.reportError(e); + return false; + } + } + + private void applyToLiveChunk(Chunk chunk, TerrainChunk buffer) { + int chunkX = chunk.getX(); + int chunkZ = chunk.getZ(); for (Entity entity : chunk.getEntities()) { if (!(entity instanceof Player)) { entity.remove();