From 474b1e873a6cce6ad2ae433d6354aad85e550145 Mon Sep 17 00:00:00 2001 From: Brian Neumann-Fopiano Date: Sun, 1 Nov 2026 21:27:50 -0500 Subject: [PATCH] Bound find river search - HydrologyFeatureSearch stops after its timeout or when the caller cancels, waiting on plans in 50 ms slices - Types the dimension cannot form answer at once without planning, naming the setting that turns them off - channelType reads the tier name (stream, river, major or major_river) and falls back to rank, so one-tier packs match stream - HydrologyRuntime adds unavailable(type) and passes FEATURE_SEARCH_TIMEOUT (30 s) and a running check to the search - nearestRiver returns a RiverSearch outcome, reports disabled and timed-out searches, and keeps recorded water on timeout - startRiverSearch keeps one search per player; a new search cancels the previous one without a message - Bukkit and modded find river run through the shared per-player search - Tier name description and schema digest follow the new tier naming - HydrologyFeatureSearchTest plus new query, Bukkit and modded cases cover the bounds --- .../art/arcane/iris/command/CommandFind.java | 81 +++--- .../command/CommandFindHydrologyTest.java | 59 ++++- .../modded/command/ModdedLocateCommands.java | 55 ++--- .../modded/command/ModdedLocateRiverTest.java | 28 ++- .../hydrology/config/IrisHydrologyTier.java | 2 +- .../engine/HydrologyFeatureSearch.java | 140 +++++++++-- .../hydrology/engine/HydrologyRuntime.java | 22 +- .../history/GenerationSemanticQueries.java | 136 +++++++++-- .../engine/HydrologyFeatureSearchTest.java | 230 ++++++++++++++++++ .../engine/HydrologyRuntimeTest.java | 24 +- .../schema/SchemaBuilderIdentityTest.java | 2 +- .../GenerationSemanticQueriesTest.java | 214 +++++++++++++--- 12 files changed, 826 insertions(+), 167 deletions(-) create mode 100644 core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearchTest.java diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandFind.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandFind.java index 54c03e8ea..23bec5347 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandFind.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandFind.java @@ -70,6 +70,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.concurrent.CancellationException; @Director(name = "find", origin = DirectorOrigin.PLAYER, description = "Iris Find commands", descriptionKey = "iris.director.commandfind.director.iris_find_commands", aliases = "goto") public class CommandFind implements DirectorExecutor { @@ -218,41 +219,49 @@ public class CommandFind implements DirectorExecutor { commandSender.sendMessage(C.RED + error.getMessage()); return; } - String label = featureType.key().replace('_', ' '); Location origin = target.getLocation(); - World originWorld = origin.getWorld(); - int maximumDistance = GenerationSemanticQueries.RIVER_SEARCH_DISTANCE; - commandSender.sendMessage(C.GRAY + GenerationSemanticQueries.riverSearchMessage(featureType, maximumDistance)); - J.a(() -> { - try { - GenerationSemanticQueries.RiverResult feature = GenerationSemanticQueries.nearestRiver( - activeEngine, - featureType, - origin.getBlockX(), - origin.getBlockZ(), - maximumDistance - ).orElse(null); - if (feature == null) { - sendStructureMessage(target, commandSender, - C.YELLOW + GenerationSemanticQueries.riverNotFoundMessage(featureType, maximumDistance)); - return; - } - if (!teleport) { - sendStructureMessage(target, commandSender, - C.GREEN + "Found " + label + " at " + feature.x() + ", " + feature.y() + ", " + feature.z() + "."); - return; - } - Location destination = new Location( - originWorld, feature.x(), feature.y(), feature.z()); - prepareStructureTeleport( - target, originWorld, commandSender, label, destination, true); - } catch (Throwable error) { - sendStructureMessage(target, commandSender, - C.RED + "Could not search for " + label + ": " + error.getClass().getSimpleName() - + (error.getMessage() == null ? "" : " - " + error.getMessage())); - Iris.reportError("Could not locate hydrology feature '" + featureType.key() + "'.", error); + RiverRequest request = new RiverRequest(target, origin.getWorld(), commandSender, featureType, teleport); + commandSender.sendMessage(C.GRAY + GenerationSemanticQueries.riverSearchMessage(featureType, + GenerationSemanticQueries.RIVER_SEARCH_DISTANCE)); + GenerationSemanticQueries.startRiverSearch(target.getUniqueId(), J::a, activeEngine, featureType, origin.getBlockX(), + origin.getBlockZ()) + .whenComplete((search, failure) -> finishRiverSearch(request, search, failure)); + } + + private void finishRiverSearch(RiverRequest request, GenerationSemanticQueries.RiverSearch search, Throwable failure) { + if (failure instanceof CancellationException) { + return; + } + if (failure != null) { + reportRiverFailure(request, failure); + return; + } + try { + switch (search) { + case GenerationSemanticQueries.RiverSearch.Missing missing -> + sendStructureMessage(request.target(), request.sender(), C.YELLOW + missing.message()); + case GenerationSemanticQueries.RiverSearch.Found found -> arriveAtRiver(request, found.feature()); } - }); + } catch (RuntimeException error) { + reportRiverFailure(request, error); + } + } + + private void arriveAtRiver(RiverRequest request, GenerationSemanticQueries.RiverResult feature) { + if (!request.teleport()) { + sendStructureMessage(request.target(), request.sender(), + C.GREEN + "Found " + request.label() + " at " + feature.x() + ", " + feature.y() + ", " + feature.z() + "."); + return; + } + Location destination = new Location(request.world(), feature.x(), feature.y(), feature.z()); + prepareStructureTeleport(request.target(), request.world(), request.sender(), request.label(), destination, true); + } + + private void reportRiverFailure(RiverRequest request, Throwable failure) { + sendStructureMessage(request.target(), request.sender(), + C.RED + "Could not search for " + request.label() + ": " + failure.getClass().getSimpleName() + + (failure.getMessage() == null ? "" : " - " + failure.getMessage())); + Iris.reportError("Could not locate hydrology feature '" + request.type().key() + "'.", failure); } @Director(description = "Find a structure (a vanilla key like minecraft:village_plains or minecraft:stronghold, or an imported iris structure key)", descriptionKey = "iris.director.commandfind.director.find_structure_vanilla_key_like_minecraft_village_plains_minecraft_stronghold_imported_iris", sync = true) @@ -919,6 +928,12 @@ public class CommandFind implements DirectorExecutor { int configuredUnregistered, int editableUnplaced, int managedUnregistered) { } + private record RiverRequest(Player target, World world, VolmitSender sender, HydrologyFeatureType type, boolean teleport) { + private String label() { + return type.key().replace('_', ' '); + } + } + private record ManagedDatapackStructure(String key, Set sourceIds) { private ManagedDatapackStructure(String key) { this(key, new LinkedHashSet<>()); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandFindHydrologyTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandFindHydrologyTest.java index 1c507db10..ef079889c 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandFindHydrologyTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandFindHydrologyTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.command; import art.arcane.iris.Iris; +import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; @@ -19,6 +20,7 @@ import org.mockito.MockedStatic; import java.util.Optional; import java.util.OptionalLong; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; @@ -126,11 +128,12 @@ public class CommandFindHydrologyTest { for (HydrologyFeatureType type : HydrologyFeatureType.values()) { try (Fixture fixture = new Fixture()) { fixture.command.river(type.key(), false); - fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), any(), anyInt(), anyInt(), anyInt()), never()); + fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), any(), anyInt(), anyInt(), anyInt(), any()), + never()); fixture.search.get().run(); - fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(fixture.engine, type, 0, 0, - GenerationSemanticQueries.RIVER_SEARCH_DISTANCE)); + fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), eq(type), eq(0), eq(0), + eq(GenerationSemanticQueries.RIVER_SEARCH_DISTANCE), any())); verify(fixture.sender).sendMessage(contains("Found " + type.key().replace('_', ' ') + " at 32, 63, 32.")); } } @@ -146,11 +149,40 @@ public class CommandFindHydrologyTest { } } + @Test + public void aNewSearchSilentlyReplacesThePlayersRunningSearch() { + try (Fixture fixture = new Fixture()) { + fixture.command.river("pond", false); + Runnable replaced = fixture.search.get(); + fixture.command.river("river", false); + replaced.run(); + + fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), eq(HydrologyFeatureType.POND), anyInt(), anyInt(), + anyInt(), any()), never()); + fixture.search.get().run(); + verify(fixture.sender).sendMessage(contains("Found river at 32, 63, 32.")); + verify(fixture.sender, never()).sendMessage(contains("Found pond")); + verify(fixture.sender, never()).sendMessage(contains("Could not search")); + } + } + + @Test + public void disabledTypeIsReportedWithItsReason() throws Exception { + try (Fixture fixture = new Fixture()) { + fixture.searchForReal(); + when(fixture.runtime.unavailable(HydrologyFeatureType.LAKE)).thenReturn(Optional.of("hydrology.lakes is disabled")); + fixture.command.river("lake", true); + fixture.search.get().run(); + + verify(fixture.sender).sendMessage(contains("No lake forms in this dimension: hydrology.lakes is disabled.")); + verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + } + } + @Test public void missingCavePoolIsReportedAsNotFoundInGeneratedChunks() { try (Fixture fixture = new Fixture()) { - fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt())) - .thenReturn(Optional.empty()); + fixture.searchForReal(); fixture.command.river("cave_pool", true); fixture.search.get().run(); @@ -162,8 +194,7 @@ public class CommandFindHydrologyTest { @Test public void missingFeatureIsReportedAsNotFound() { try (Fixture fixture = new Fixture()) { - fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt())) - .thenReturn(Optional.empty()); + fixture.searchForReal(); fixture.command.river("sea_inlet", true); fixture.search.get().run(); @@ -176,7 +207,7 @@ public class CommandFindHydrologyTest { public void plannerFailureIsReportedAsAnErrorNotAsNotFound() { try (Fixture fixture = new Fixture()) { IllegalStateException failure = new IllegalStateException("window planner exploded"); - fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt())) + fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt(), any())) .thenThrow(failure); fixture.command.river("lake", true); fixture.search.get().run(); @@ -191,6 +222,7 @@ public class CommandFindHydrologyTest { private final CommandFind command = mock(CommandFind.class, CALLS_REAL_METHODS); private final Engine engine = mock(Engine.class); private final IrisComplex complex = mock(IrisComplex.class); + private final HydrologyRuntime runtime = mock(HydrologyRuntime.class); private final Player player = mock(Player.class); private final World world = mock(World.class); private final VolmitSender sender = mock(VolmitSender.class); @@ -208,6 +240,8 @@ public class CommandFindHydrologyTest { doReturn(player).when(command).player(); doReturn(sender).when(command).sender(); when(engine.getComplex()).thenReturn(complex); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(player.getUniqueId()).thenReturn(UUID.randomUUID()); when(player.getWorld()).thenReturn(world); when(player.getLocation()).thenReturn(new Location(world, 0, 70, 0)); when(player.isOnline()).thenReturn(true); @@ -227,12 +261,17 @@ public class CommandFindHydrologyTest { }); platform.when(() -> BukkitPlatform.chunkAtAsync(any(World.class), anyInt(), anyInt(), eq(true))).thenReturn(chunk); platform.when(() -> BukkitPlatform.teleportAsync(eq(player), any(Location.class))).thenReturn(teleport); - queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt())) - .thenReturn(Optional.of(new GenerationSemanticQueries.RiverResult( + queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt(), any())) + .thenReturn(new GenerationSemanticQueries.RiverSearch.Found(new GenerationSemanticQueries.RiverResult( GenerationSemanticQueries.RiverSource.ACTIVE_PREDICTION, HydrologyFeatureType.RIVER, 1L, 32, 63, 32, OptionalLong.empty()))); } + private void searchForReal() { + queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt(), any())) + .thenCallRealMethod(); + } + @Override public void close() { logging.close(); 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 077f9597d..8f3c1c076 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 @@ -149,39 +149,32 @@ final class ModdedLocateCommands { IrisModdedCommands.fail(source, error.getMessage()); return 0; } - String label = featureType.key().replace('_', ' '); - int originX = player.blockX(); - int originZ = player.blockZ(); - int maximumDistance = GenerationSemanticQueries.RIVER_SEARCH_DISTANCE; NativeModdedServer server = source.server(); - IrisModdedCommands.ok(source, GenerationSemanticQueries.riverSearchMessage(featureType, maximumDistance)); - MultiBurst.burst.completeValueAsync(() -> GenerationSemanticQueries.nearestRiver( - engine, featureType, originX, originZ, maximumDistance).orElse(null)) - .whenComplete((GenerationSemanticQueries.RiverResult feature, Throwable error) -> server.execute(() -> { - if (error != null) { - Throwable cause = error instanceof CompletionException && error.getCause() != null ? error.getCause() : error; - ModdedIrisLog.error("Hydrology locate failed for {}", featureType.key(), cause); - IrisModdedCommands.fail(source, "Could not search for " + label + ": " + cause.getClass().getSimpleName() - + (cause.getMessage() == null ? "" : " - " + cause.getMessage())); - return; + RiverRequest request = new RiverRequest(source, level, player, featureType); + IrisModdedCommands.ok(source, GenerationSemanticQueries.riverSearchMessage(featureType, GenerationSemanticQueries.RIVER_SEARCH_DISTANCE)); + GenerationSemanticQueries.startRiverSearch(player.id(), MultiBurst.burst, engine, featureType, player.blockX(), player.blockZ()) + .whenComplete((GenerationSemanticQueries.RiverSearch search, Throwable error) -> { + if (!(error instanceof CancellationException)) { + server.execute(() -> finishRiverSearch(request, search, error)); } - if (feature == null) { - IrisModdedCommands.fail(source, GenerationSemanticQueries.riverNotFoundMessage(featureType, maximumDistance)); - return; - } - teleportToStructure( - source, - level, - player, - feature.x(), - feature.y() + 2, - feature.z(), - label - ); - })); + }); return 1; } + private static void finishRiverSearch(RiverRequest request, GenerationSemanticQueries.RiverSearch search, Throwable error) { + if (error != null) { + ModdedIrisLog.error("Hydrology locate failed for {}", request.type().key(), error); + IrisModdedCommands.fail(request.source(), "Could not search for " + request.label() + ": " + error.getClass().getSimpleName() + + (error.getMessage() == null ? "" : " - " + error.getMessage())); + return; + } + switch (search) { + case GenerationSemanticQueries.RiverSearch.Missing missing -> IrisModdedCommands.fail(request.source(), missing.message()); + case GenerationSemanticQueries.RiverSearch.Found found -> teleportToStructure(request.source(), request.level(), + request.player(), found.feature().x(), found.feature().y() + 2, found.feature().z(), request.label()); + } + } + static int gotoStructure(NativeCommandSource source, String keyRaw) { NativeWorld level = source.world(); Engine engine = IrisModdedCommands.engineFor(level); @@ -706,6 +699,12 @@ final class ModdedLocateCommands { record CaveDestination(SubterrainPosition target, Optional read) { } + private record RiverRequest(NativeCommandSource source, NativeWorld level, NativeProtocolPlayer player, HydrologyFeatureType type) { + private String label() { + return type.key().replace('_', ' '); + } + } + private record CaveLocateRequest(NativeCommandSource source, NativeWorld level, Engine engine, NativeProtocolPlayer player, String label, NativeModdedServer server, UUID playerId, CompletableFuture search, BiomeLocator locator, Position2 at) { diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/ModdedLocateRiverTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/ModdedLocateRiverTest.java index afd149bb0..6ed7fa857 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/ModdedLocateRiverTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/ModdedLocateRiverTest.java @@ -19,6 +19,7 @@ import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @@ -41,7 +42,7 @@ public class ModdedLocateRiverTest { private static final int DISTANCE = GenerationSemanticQueries.RIVER_SEARCH_DISTANCE; @Test - public void unknownTypeFailsBeforeSearching() { + public void unknownTypeFailsBeforeSearching() throws Exception { Fixture fixture = new Fixture(); try (MockedStatic commands = fixture.commands()) { assertEquals(0, ModdedLocateCommands.gotoRiver(fixture.source, "ocean_trench")); @@ -49,14 +50,14 @@ public class ModdedLocateRiverTest { commands.verify(() -> IrisModdedCommands.fail(eq(fixture.source), anyString())); commands.verify(() -> IrisModdedCommands.ok(eq(fixture.source), anyString()), never()); verify(fixture.server, never()).execute(any()); - verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); + verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); } } @Test public void missingFeatureReportsNotFound() throws Exception { Fixture fixture = new Fixture(); - when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())).thenReturn(Optional.empty()); + when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenReturn(Optional.empty()); try (MockedStatic commands = fixture.commands()) { assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "river")); fixture.finishOnServerThread(); @@ -66,10 +67,24 @@ public class ModdedLocateRiverTest { } } + @Test + public void disabledTypeReportsItsReasonWithoutSearching() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.runtime.unavailable(HydrologyFeatureType.DAM)).thenReturn(Optional.of("hydrology.ponds.dams is disabled")); + try (MockedStatic commands = fixture.commands()) { + assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "dam")); + fixture.finishOnServerThread(); + + commands.verify(() -> IrisModdedCommands.fail(fixture.source, "No dam forms in this dimension: hydrology.ponds.dams is disabled.")); + verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + verify(fixture.player, never()).teleport(any(), anyDouble(), anyDouble(), anyDouble()); + } + } + @Test public void plannerFailureIsReportedAsAnErrorNotAsNotFound() throws Exception { Fixture fixture = new Fixture(); - when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())) + when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())) .thenThrow(new IllegalStateException("window planner exploded")); try (MockedStatic commands = fixture.commands()) { assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "major_river")); @@ -86,7 +101,7 @@ public class ModdedLocateRiverTest { @Test public void foundFeatureTeleportsAboveItFromThePlayersPosition() throws Exception { Fixture fixture = new Fixture(); - when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())) + when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())) .thenReturn(Optional.of(new HydrologyFeatureRef(9L, HydrologyFeatureType.WATERFALL, 400, 130, -250))); when(fixture.player.teleport(fixture.world, 400.5D, 68D, -249.5D)).thenReturn(true); try (MockedStatic commands = fixture.commands(); @@ -95,7 +110,7 @@ public class ModdedLocateRiverTest { fixture.finishOnServerThread(); ArgumentCaptor query = ArgumentCaptor.forClass(HydrologyFeatureQuery.class); - verify(fixture.runtime).nearestFeature(eq(120), eq(-75), query.capture(), eq(DISTANCE), any()); + verify(fixture.runtime).nearestFeature(eq(120), eq(-75), query.capture(), eq(DISTANCE), any(), any()); assertEquals(HydrologyFeatureQuery.of(HydrologyFeatureType.WATERFALL), query.getValue()); verify(queries.constructed().getFirst()).loadChunk(400 >> 4, -250 >> 4); verify(fixture.player).teleport(fixture.world, 400.5D, 68D, -249.5D); @@ -119,6 +134,7 @@ public class ModdedLocateRiverTest { when(source.player()).thenReturn(player); when(source.world()).thenReturn(world); when(source.server()).thenReturn(server); + when(player.id()).thenReturn(UUID.randomUUID()); when(player.blockX()).thenReturn(120); when(player.blockZ()).thenReturn(-75); when(player.connected()).thenReturn(true); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java index 78f45b2e1..e0498acfd 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java @@ -17,7 +17,7 @@ import lombok.experimental.Accessors; @Data public class IrisHydrologyTier { @Required - @Description("Label for this tier in configuration error messages. Locate, maps and history do not use it: they rank tiers by minCatchment, so the lowest tier is a stream, the highest a major river and any between are rivers.") + @Description("Channel type of this tier for locate, maps and history: stream, river or major (also major_river). Any other name takes the type of its rank by minCatchment instead: the lowest tier is a stream, the highest a major river and any between are rivers. Configuration error messages also use the name.") private String name = "stream"; @MinNumber(0) diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearch.java b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearch.java index 9c57c6885..7b112edd7 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearch.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearch.java @@ -18,14 +18,22 @@ import art.arcane.iris.generation.hydrology.water.PondMask; import art.arcane.iris.generation.hydrology.water.Reach; import art.arcane.iris.generation.hydrology.water.ReachStyle; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; +import java.util.Locale; +import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.BooleanSupplier; import java.util.function.Predicate; final class HydrologyFeatureSearch { @@ -33,12 +41,15 @@ final class HydrologyFeatureSearch { private static final Set WINDOW_TYPES = EnumSet.of(HydrologyFeatureType.STREAM, HydrologyFeatureType.RIVER, HydrologyFeatureType.MAJOR_RIVER, HydrologyFeatureType.CASCADE, HydrologyFeatureType.WATERFALL, HydrologyFeatureType.MOUTH, HydrologyFeatureType.POND, HydrologyFeatureType.DAM, HydrologyFeatureType.SEA_INLET); + private static final long POLL_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); + static final String OFF = "hydrology is off"; + private static final String PONDS_OFF = "hydrology.ponds.natural and hydrology.ponds.seeded are disabled"; private final HydrologySettings settings; private final HydrologyPlanCache cache; private final int originX; private final int originZ; - private final HydrologyFeatureQuery query; + private final Set types; private final Predicate eligible; private final int radius; private final long radiusSquared; @@ -51,29 +62,70 @@ final class HydrologyFeatureSearch { this.cache = cache; this.originX = originX; this.originZ = originZ; - this.query = query; + this.types = enabledTypes(settings, query); this.eligible = eligible; this.radius = radius; this.radiusSquared = (long) radius * radius; } - Optional nearest() { + Optional nearest(Duration timeout, BooleanSupplier running) throws TimeoutException { + Objects.requireNonNull(timeout, "timeout"); + Objects.requireNonNull(running, "running"); int rings = Math.ceilDiv(radius, WindowKey.SIZE) + 1; long windows = (2L * rings + 1L) * (2L * rings + 1L); if (windows > MAX_WINDOWS) { throw new IllegalArgumentException("Hydrology feature search radius " + radius + " covers " + windows + " windows, above " + MAX_WINDOWS); } - if (query.matches(HydrologyFeatureType.LAKE)) { - searchLakes(); + if (types.isEmpty()) { + return Optional.empty(); } - if (!Collections.disjoint(query.types(), WINDOW_TYPES)) { - searchWindows(rings); + Budget budget = new Budget(System.nanoTime() + timeout.toNanos(), timeout, running); + if (types.contains(HydrologyFeatureType.LAKE)) { + searchLakes(budget); + } + if (!Collections.disjoint(types, WINDOW_TYPES)) { + searchWindows(rings, budget); } return Optional.ofNullable(best); } - private void searchLakes() { + static Optional disabledReason(HydrologySettings settings, HydrologyFeatureType type) { + HydrologySettings.Ponds ponds = settings.ponds(); + boolean anyPonds = ponds.natural().enabled() || ponds.seeded().enabled(); + String reason = switch (type) { + case STREAM, RIVER, MAJOR_RIVER -> hasTier(settings, type) ? null : "it has no " + type.key().replace('_', ' ') + " tier"; + case CASCADE, WATERFALL, MOUTH -> null; + case POND -> anyPonds ? null : PONDS_OFF; + case DAM -> !anyPonds ? PONDS_OFF : ponds.dams().enabled() ? null : "hydrology.ponds.dams is disabled"; + case LAKE -> settings.lakes().enabled() ? null : "hydrology.lakes is disabled"; + case SEA_INLET -> settings.underground().seaInlets().enabled() ? null : "hydrology.underground.seaInlets is disabled"; + case CAVE_POOL -> settings.underground().cavePools().enabled() ? null : "hydrology.underground.cavePools is disabled"; + }; + return Optional.ofNullable(reason); + } + + private static Set enabledTypes(HydrologySettings settings, HydrologyFeatureQuery query) { + Set enabled = EnumSet.noneOf(HydrologyFeatureType.class); + for (HydrologyFeatureType type : query.types()) { + if (disabledReason(settings, type).isEmpty()) { + enabled.add(type); + } + } + return enabled; + } + + private static boolean hasTier(HydrologySettings settings, HydrologyFeatureType type) { + List tiers = settings.tiers(); + for (int index = 0; index < tiers.size(); index++) { + if (channelType(tiers.get(index).name(), index, tiers.size()) == type) { + return true; + } + } + return false; + } + + private void searchLakes(Budget budget) throws TimeoutException { long minX = (long) originX - radius; long minZ = (long) originZ - radius; long maxX = (long) originX + radius; @@ -85,7 +137,7 @@ final class HydrologyFeatureSearch { plans.add(cache.demandRegion(key)); } for (CompletableFuture plan : plans) { - for (Pond lake : cache.awaitPlan(plan).lakes()) { + for (Pond lake : await(plan, budget).lakes()) { if (seen.add(lake.id())) { pond(lake, HydrologyFeatureType.LAKE); } @@ -93,7 +145,7 @@ final class HydrologyFeatureSearch { } } - private void searchWindows(int rings) { + private void searchWindows(int rings, Budget budget) throws TimeoutException { WindowKey origin = WindowKey.containing(originX, originZ); for (int ring = 0; ring <= rings; ring++) { long bound = Math.max(0L, (long) (ring - 2) * WindowKey.SIZE); @@ -105,11 +157,32 @@ final class HydrologyFeatureSearch { plans.add(cache.demandWindow(key)); } for (CompletableFuture plan : plans) { - window(cache.awaitPlan(plan).plan()); + window(await(plan, budget).plan()); } } } + private T await(CompletableFuture plan, Budget budget) throws TimeoutException { + CountDownLatch settled = new CountDownLatch(1); + plan.whenComplete((value, failure) -> settled.countDown()); + boolean ready = false; + while (!ready) { + ready = settle(settled, budget.slice()); + } + return cache.awaitPlan(plan); + } + + private static boolean settle(CountDownLatch settled, long nanos) { + try { + return settled.await(nanos, TimeUnit.NANOSECONDS); + } catch (InterruptedException interruption) { + Thread.currentThread().interrupt(); + CancellationException cancelled = new CancellationException("The hydrology feature search was interrupted."); + cancelled.initCause(interruption); + throw cancelled; + } + } + private static List ring(WindowKey origin, int ring) { if (ring == 0) { return List.of(origin); @@ -135,7 +208,7 @@ final class HydrologyFeatureSearch { pond(pond, type); } } - if (query.matches(HydrologyFeatureType.SEA_INLET)) { + if (types.contains(HydrologyFeatureType.SEA_INLET)) { for (SeaInlet inlet : plan.inlets()) { inlet(inlet); } @@ -151,22 +224,22 @@ final class HydrologyFeatureSearch { private HydrologyFeatureType pondType(Pond pond) { if (pond.kind() == PondKind.LAKE) { - return query.matches(HydrologyFeatureType.LAKE) ? HydrologyFeatureType.LAKE : null; + return types.contains(HydrologyFeatureType.LAKE) ? HydrologyFeatureType.LAKE : null; } - if (pond.damRaise() > 0 && query.matches(HydrologyFeatureType.DAM)) { + if (pond.damRaise() > 0 && types.contains(HydrologyFeatureType.DAM)) { return HydrologyFeatureType.DAM; } - return query.matches(HydrologyFeatureType.POND) ? HydrologyFeatureType.POND : null; + return types.contains(HydrologyFeatureType.POND) ? HydrologyFeatureType.POND : null; } private void reach(Reach reach) { HydrologyFeatureType channel = channelType(settings, reach.tier()); - boolean whole = query.matches(channel); + boolean whole = types.contains(channel); float[] xs = reach.xs(); float[] zs = reach.zs(); for (int index = 0; index < xs.length; index++) { HydrologyFeatureType point = pointType(reach.style()[index]); - HydrologyFeatureType type = point != null && query.matches(point) ? point : whole ? channel : null; + HydrologyFeatureType type = point != null && types.contains(point) ? point : whole ? channel : null; if (type != null) { offer(reach.id(), type, (int) Math.floor(xs[index]), reach.grade()[index], (int) Math.floor(zs[index])); } @@ -197,10 +270,24 @@ final class HydrologyFeatureSearch { if (index < 0) { throw new IllegalStateException("Reach tier '" + tier.name() + "' is not one of the hydrology tiers"); } - if (tier.equals(settings.majorTier())) { - return HydrologyFeatureType.MAJOR_RIVER; + return channelType(tier.name(), index, tiers.size()); + } + + private static HydrologyFeatureType channelType(String name, int index, int count) { + String normalized = name == null ? "" : name.trim().toLowerCase(Locale.ROOT).replace('-', '_').replace(' ', '_'); + return switch (normalized) { + case "stream" -> HydrologyFeatureType.STREAM; + case "river" -> HydrologyFeatureType.RIVER; + case "major", "major_river" -> HydrologyFeatureType.MAJOR_RIVER; + default -> rankType(index, count); + }; + } + + private static HydrologyFeatureType rankType(int index, int count) { + if (index == 0) { + return HydrologyFeatureType.STREAM; } - return index == 0 ? HydrologyFeatureType.STREAM : HydrologyFeatureType.RIVER; + return index == count - 1 ? HydrologyFeatureType.MAJOR_RIVER : HydrologyFeatureType.RIVER; } private static HydrologyFeatureType pointType(ReachStyle style) { @@ -239,4 +326,17 @@ final class HydrologyFeatureSearch { } return x != best.x() ? x < best.x() : z < best.z(); } + + private record Budget(long deadline, Duration timeout, BooleanSupplier running) { + private long slice() throws TimeoutException { + if (!running.getAsBoolean()) { + throw new CancellationException("The hydrology feature search was cancelled."); + } + long remaining = deadline - System.nanoTime(); + if (remaining <= 0L) { + throw new TimeoutException("The hydrology feature search ran past its " + timeout.toMillis() + " ms limit."); + } + return Math.min(remaining, POLL_NANOS); + } + } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java index e1bcc3c45..f15662a80 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java @@ -37,6 +37,7 @@ import art.arcane.iris.world.IrisWorld; import java.io.File; import java.io.UncheckedIOException; import java.nio.file.Path; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -51,6 +52,7 @@ import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BooleanSupplier; import java.util.function.Function; @@ -65,6 +67,7 @@ public final class HydrologyRuntime { public static final int MAX_PREGENERATION_REGIONS = 4096; private static final int MAX_PREVIEW_REQUESTS = 64; private static final int PREFETCH_CAPACITY = 16; + public static final Duration FEATURE_SEARCH_TIMEOUT = Duration.ofSeconds(30L); private static final HydrologyRuntime DISABLED = new HydrologyRuntime(); private final HydrologySettings settings; @@ -402,14 +405,17 @@ public final class HydrologyRuntime { } } - public Optional nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius) { - return nearestFeature(blockX, blockZ, query, radius, feature -> true); + public Optional nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius) + throws TimeoutException { + return nearestFeature(blockX, blockZ, query, radius, feature -> true, () -> true); } public Optional nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius, - Predicate eligible) { + Predicate eligible, BooleanSupplier running) + throws TimeoutException { Objects.requireNonNull(query, "query"); Objects.requireNonNull(eligible, "eligible"); + Objects.requireNonNull(running, "running"); if (radius < 0) { throw new IllegalArgumentException("Hydrology feature search radius must not be negative, got " + radius); } @@ -420,7 +426,15 @@ public final class HydrologyRuntime { throw new IllegalStateException("Hydrology feature search was requested on the main thread."); } requireOpen(); - return new HydrologyFeatureSearch(settings, cache, blockX, blockZ, query, eligible, radius).nearest(); + return new HydrologyFeatureSearch(settings, cache, blockX, blockZ, query, eligible, radius).nearest(FEATURE_SEARCH_TIMEOUT, running); + } + + public Optional unavailable(HydrologyFeatureType type) { + Objects.requireNonNull(type, "type"); + if (settings == null) { + return Optional.of(HydrologyFeatureSearch.OFF); + } + return HydrologyFeatureSearch.disabledReason(settings, type); } public HydrologyFeatureType channelType(HydrologyTier tier) { diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticQueries.java b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticQueries.java index 7d30617ee..2f925e681 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticQueries.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticQueries.java @@ -21,11 +21,19 @@ import java.util.Objects; import java.util.Optional; import java.util.OptionalLong; import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeoutException; import java.util.function.Predicate; import java.util.function.BooleanSupplier; public final class GenerationSemanticQueries { public static final int RIVER_SEARCH_DISTANCE = 7168; + private static final ConcurrentHashMap> RIVER_SEARCHES = new ConcurrentHashMap<>(); private GenerationSemanticQueries() { } @@ -153,15 +161,41 @@ public final class GenerationSemanticQueries { IrisStructureLocator.LocateStatus.FOUND, position.x(), position.y(), position.z()); } - public static Optional nearestRiver( + public static CompletableFuture startRiverSearch( + UUID searcher, + Executor executor, + Engine engine, + HydrologyFeatureType type, + int blockX, + int blockZ + ) { + UUID requiredSearcher = Objects.requireNonNull(searcher, "searcher"); + Executor requiredExecutor = Objects.requireNonNull(executor, "executor"); + CompletableFuture search = new CompletableFuture<>(); + CompletableFuture previous = RIVER_SEARCHES.put(requiredSearcher, search); + if (previous != null) { + previous.cancel(false); + } + search.whenComplete((result, failure) -> RIVER_SEARCHES.remove(requiredSearcher, search)); + try { + requiredExecutor.execute(() -> runRiverSearch(search, engine, type, blockX, blockZ)); + } catch (RejectedExecutionException rejected) { + search.completeExceptionally(rejected); + } + return search; + } + + public static RiverSearch nearestRiver( Engine engine, HydrologyFeatureType type, int blockX, int blockZ, - int maximumDistance + int maximumDistance, + BooleanSupplier running ) { Engine requiredEngine = Objects.requireNonNull(engine, "engine"); HydrologyFeatureType requiredType = Objects.requireNonNull(type, "type"); + Objects.requireNonNull(running, "running"); if (maximumDistance < 0) { throw new IllegalArgumentException("Maximum river search distance cannot be negative."); } @@ -173,23 +207,55 @@ public final class GenerationSemanticQueries { blockZ, maximumDistance ); - RiverResult active = recordedOnly(requiredType) ? null : activeRiver( - requiredEngine, - history, - requiredType, - blockX, - blockZ, - maximumDistance - ); + Optional unavailable = requiredEngine.getComplex().getHydrologyRuntime().unavailable(requiredType); + if (recordedOnly(requiredType) || unavailable.isPresent()) { + if (recorded != null) { + return new RiverSearch.Found(recorded); + } + return new RiverSearch.Missing(unavailable.map(reason -> riverUnavailableMessage(requiredType, reason)) + .orElseGet(() -> riverNotFoundMessage(requiredType, maximumDistance))); + } + RiverResult active; + try { + active = activeRiver(requiredEngine, history, requiredType, blockX, blockZ, maximumDistance, running); + } catch (TimeoutException timedOut) { + return recorded != null ? new RiverSearch.Found(recorded) : new RiverSearch.Missing(riverTimeoutMessage(requiredType)); + } + RiverResult nearest = nearer(blockX, blockZ, recorded, active); + return nearest == null + ? new RiverSearch.Missing(riverNotFoundMessage(requiredType, maximumDistance)) + : new RiverSearch.Found(nearest); + } + + private static void runRiverSearch( + CompletableFuture search, + Engine engine, + HydrologyFeatureType type, + int blockX, + int blockZ + ) { + if (search.isDone()) { + return; + } + try { + search.complete(nearestRiver(engine, type, blockX, blockZ, RIVER_SEARCH_DISTANCE, () -> !search.isDone())); + } catch (CancellationException stopped) { + search.completeExceptionally(new IllegalStateException(stopped.getMessage(), stopped)); + } catch (Throwable failure) { + search.completeExceptionally(failure); + } + } + + private static RiverResult nearer(int blockX, int blockZ, RiverResult recorded, RiverResult active) { if (recorded == null) { - return Optional.ofNullable(active); + return active; } if (active == null) { - return Optional.of(recorded); + return recorded; } int comparison = horizontalDistanceSquared(blockX, blockZ, recorded.x(), recorded.z()) .compareTo(horizontalDistanceSquared(blockX, blockZ, active.x(), active.z())); - return Optional.of(comparison <= 0 ? recorded : active); + return comparison <= 0 ? recorded : active; } private static boolean recordedOnly(HydrologyFeatureType type) { @@ -197,14 +263,27 @@ public final class GenerationSemanticQueries { } public static String riverSearchMessage(HydrologyFeatureType type, int maximumDistance) { - String label = type.key().replace('_', ' '); + String label = label(type); return recordedOnly(type) ? "Searching generated chunks for the nearest " + label + " within " + maximumDistance + " blocks..." : "Searching for the nearest " + label + " within " + maximumDistance + " blocks..."; } - public static String riverNotFoundMessage(HydrologyFeatureType type, int maximumDistance) { - String label = type.key().replace('_', ' '); + private static String riverUnavailableMessage(HydrologyFeatureType type, String reason) { + return "No " + label(type) + " forms in this dimension: " + reason + "."; + } + + private static String riverTimeoutMessage(HydrologyFeatureType type) { + return "Stopped searching for the nearest " + label(type) + " after " + + HydrologyRuntime.FEATURE_SEARCH_TIMEOUT.toSeconds() + " seconds."; + } + + private static String label(HydrologyFeatureType type) { + return type.key().replace('_', ' '); + } + + private static String riverNotFoundMessage(HydrologyFeatureType type, int maximumDistance) { + String label = label(type); return recordedOnly(type) ? "No " + label + " found in generated chunks within " + maximumDistance + " blocks. Cave pools form in carved caves, so " + "only chunks that have already generated can hold one." @@ -300,12 +379,10 @@ public final class GenerationSemanticQueries { HydrologyFeatureType type, int blockX, int blockZ, - int maximumDistance - ) { + int maximumDistance, + BooleanSupplier running + ) throws TimeoutException { HydrologyRuntime runtime = engine.getComplex().getHydrologyRuntime(); - if (runtime == null || !runtime.enabled()) { - return null; - } Map eligibleChunks = new HashMap<>(); TransitionDisplacementField displacement = engine.getComplex().getTransitionDisplacement(); Predicate eligibility = feature -> (displacement == null @@ -317,7 +394,8 @@ public final class GenerationSemanticQueries { blockZ, HydrologyFeatureQuery.of(type), maximumDistance, - eligibility + eligibility, + running ).orElse(null); if (feature == null) { return null; @@ -379,4 +457,18 @@ public final class GenerationSemanticQueries { activationId = Objects.requireNonNull(activationId, "activationId"); } } + + public sealed interface RiverSearch { + record Found(RiverResult feature) implements RiverSearch { + public Found { + Objects.requireNonNull(feature, "feature"); + } + } + + record Missing(String message) implements RiverSearch { + public Missing { + Objects.requireNonNull(message, "message"); + } + } + } } diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearchTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearchTest.java new file mode 100644 index 000000000..56ed8cbcb --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearchTest.java @@ -0,0 +1,230 @@ +package art.arcane.iris.generation.hydrology.engine; + +import art.arcane.iris.generation.hydrology.config.IrisHydrology; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier; +import art.arcane.iris.generation.hydrology.plan.HydrologyPlanCache; +import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.hydrology.plan.RegionKey; +import art.arcane.iris.generation.hydrology.plan.RegionPlan; +import art.arcane.iris.generation.hydrology.plan.WindowKey; +import art.arcane.iris.generation.hydrology.plan.WindowPlan; +import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; +import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; +import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; +import art.arcane.iris.generation.hydrology.water.HydrologyTier; +import art.arcane.iris.generation.hydrology.water.Reach; +import art.arcane.iris.generation.hydrology.water.ReachStyle; +import art.arcane.iris.testsupport.FakeHydrology; +import art.arcane.volmlib.util.collection.KList; +import org.junit.After; +import org.junit.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class HydrologyFeatureSearchTest { + private static final long SEED = 1337L; + private static final long CHANNEL = 0x4348414eL; + private static final Duration LONG_TIMEOUT = Duration.ofSeconds(30L); + + private final List pools = new ArrayList<>(); + private final List caches = new ArrayList<>(); + private final CountDownLatch gate = new CountDownLatch(1); + + @After + public void shutDown() { + gate.countDown(); + for (HydrologyPlanCache cache : caches) { + cache.close(); + } + for (ExecutorService pool : pools) { + pool.shutdownNow(); + } + } + + @Test(timeout = 20_000L) + public void disabledTypeAnswersImmediately() throws Exception { + HydrologySettings settings = settings(config -> config.getLakes().setEnabled(false)); + Planners planners = new Planners(gate); + HydrologyPlanCache cache = cache(settings, planners); + + assertEquals(Optional.empty(), search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE)) + .nearest(LONG_TIMEOUT, () -> true)); + assertEquals(Optional.empty(), search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE, HydrologyFeatureType.DAM)) + .nearest(LONG_TIMEOUT, () -> true)); + assertEquals(0, planners.calls.get()); + assertEquals(Optional.of("hydrology.lakes is disabled"), HydrologyFeatureSearch.disabledReason(settings, HydrologyFeatureType.LAKE)); + assertEquals(Optional.of("hydrology.ponds.dams is disabled"), HydrologyFeatureSearch.disabledReason(settings, HydrologyFeatureType.DAM)); + assertEquals(Optional.empty(), HydrologyFeatureSearch.disabledReason(settings, HydrologyFeatureType.POND)); + assertEquals(Optional.empty(), HydrologyFeatureSearch.disabledReason(settings, HydrologyFeatureType.WATERFALL)); + + HydrologySettings dry = settings(config -> { + config.getPonds().getNatural().setEnabled(false); + config.getPonds().getSeeded().setEnabled(false); + config.getPonds().getDams().setEnabled(true); + config.getUnderground().getSeaInlets().setEnabled(false); + config.getUnderground().getCavePools().setEnabled(false); + }); + String ponds = "hydrology.ponds.natural and hydrology.ponds.seeded are disabled"; + assertEquals(Optional.of(ponds), HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.POND)); + assertEquals(Optional.of(ponds), HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.DAM)); + assertEquals(Optional.of("hydrology.underground.seaInlets is disabled"), + HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.SEA_INLET)); + assertEquals(Optional.of("hydrology.underground.cavePools is disabled"), + HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.CAVE_POOL)); + assertEquals(Optional.empty(), HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.LAKE)); + assertEquals(Optional.of("hydrology is off"), FakeHydrology.disabled().unavailable(HydrologyFeatureType.RIVER)); + } + + @Test(timeout = 20_000L) + public void searchStopsAtTheTimeout() { + HydrologySettings settings = settings(config -> { + }); + Planners planners = new Planners(gate); + HydrologyPlanCache cache = cache(settings, planners); + Duration timeout = Duration.ofMillis(200L); + HydrologyFeatureSearch search = search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.POND)); + + long started = System.nanoTime(); + assertThrows(TimeoutException.class, () -> search.nearest(timeout, () -> true)); + + assertTrue(System.nanoTime() - started >= timeout.toNanos()); + assertTrue(planners.calls.get() > 0); + } + + @Test(timeout = 20_000L) + public void cancelledSearchStopsWaitingForPlans() { + HydrologySettings settings = settings(config -> { + }); + Planners planners = new Planners(gate); + HydrologyPlanCache cache = cache(settings, planners); + AtomicInteger checks = new AtomicInteger(); + + assertThrows(CancellationException.class, () -> search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER)) + .nearest(LONG_TIMEOUT, () -> checks.incrementAndGet() < 3)); + assertTrue(checks.get() >= 3); + } + + @Test(timeout = 20_000L) + public void oneTierPacksMatchStream() throws Exception { + HydrologySettings oneTier = settings(config -> config.setTiers(new KList<>(new IrisHydrologyTier()))); + HydrologyTier only = oneTier.tiers().getFirst(); + Planners planners = new Planners(null); + planners.channelTier = only; + HydrologyPlanCache cache = cache(oneTier, planners); + + assertEquals(HydrologyFeatureType.STREAM, HydrologyFeatureSearch.channelType(oneTier, only)); + assertEquals(new HydrologyFeatureRef(CHANNEL, HydrologyFeatureType.STREAM, 100, 70, 100), + search(oneTier, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM)).nearest(LONG_TIMEOUT, () -> true).orElseThrow()); + assertEquals(Optional.of("it has no river tier"), HydrologyFeatureSearch.disabledReason(oneTier, HydrologyFeatureType.RIVER)); + assertEquals(Optional.of("it has no major river tier"), HydrologyFeatureSearch.disabledReason(oneTier, HydrologyFeatureType.MAJOR_RIVER)); + + HydrologySettings creek = settings(config -> config.setTiers(new KList<>(new IrisHydrologyTier().setName("creek")))); + assertEquals(HydrologyFeatureType.STREAM, HydrologyFeatureSearch.channelType(creek, creek.tiers().getFirst())); + + HydrologySettings twoTier = settings(config -> config.setTiers(new KList<>(new IrisHydrologyTier(), + new IrisHydrologyTier().setName("river").setMinCatchment(20000D)))); + assertEquals(HydrologyFeatureType.STREAM, HydrologyFeatureSearch.channelType(twoTier, twoTier.tiers().getFirst())); + assertEquals(HydrologyFeatureType.RIVER, HydrologyFeatureSearch.channelType(twoTier, twoTier.majorTier())); + assertEquals(Optional.of("it has no major river tier"), HydrologyFeatureSearch.disabledReason(twoTier, HydrologyFeatureType.MAJOR_RIVER)); + + HydrologySettings ranked = settings(config -> config.setTiers(new KList<>(new IrisHydrologyTier().setName("brook"), + new IrisHydrologyTier().setName("channel").setMinCatchment(20000D), + new IrisHydrologyTier().setName("trunk").setMinCatchment(320000D)))); + assertEquals(HydrologyFeatureType.STREAM, HydrologyFeatureSearch.channelType(ranked, ranked.tiers().get(0))); + assertEquals(HydrologyFeatureType.RIVER, HydrologyFeatureSearch.channelType(ranked, ranked.tiers().get(1))); + assertEquals(HydrologyFeatureType.MAJOR_RIVER, HydrologyFeatureSearch.channelType(ranked, ranked.tiers().get(2))); + } + + private HydrologyPlanCache cache(HydrologySettings settings, Planners planners) { + ExecutorService pool = Executors.newFixedThreadPool(2, runnable -> { + Thread thread = new Thread(runnable, "feature-search-planner"); + thread.setDaemon(true); + return thread; + }); + pools.add(pool); + HydrologyPlanCache cache = new HydrologyPlanCache(settings, planners::region, planners::window, pool, () -> false); + caches.add(cache); + return cache; + } + + private static HydrologyFeatureSearch search(HydrologySettings settings, HydrologyPlanCache cache, HydrologyFeatureQuery query) { + return new HydrologyFeatureSearch(settings, cache, 0, 0, query, feature -> true, 2048); + } + + private static HydrologySettings settings(Consumer change) { + IrisHydrology config = new IrisHydrology().setEnabled(true).setPersist(false); + change.accept(config); + return HydrologySettings.compile(config, SEED, 40, 0, 384); + } + + private static final class Planners { + private final CountDownLatch gate; + private final AtomicInteger calls = new AtomicInteger(); + private volatile HydrologyTier channelTier; + + private Planners(CountDownLatch gate) { + this.gate = gate; + } + + RegionPlan region(RegionKey key) { + calls.incrementAndGet(); + hold(); + return new RegionPlan(key, List.of(), List.of()); + } + + WindowPlan window(WindowKey key, List plans) { + calls.incrementAndGet(); + hold(); + if (channelTier != null && key.equals(new WindowKey(0, 0))) { + return new WindowPlan(key, List.of(channel(channelTier)), List.of(), List.of()); + } + return new WindowPlan(key, List.of(), List.of(), List.of()); + } + + private void hold() { + if (gate == null) { + return; + } + try { + gate.await(60L, TimeUnit.SECONDS); + } catch (InterruptedException interruption) { + Thread.currentThread().interrupt(); + throw new CancellationException("Planning interrupted."); + } + } + + private static Reach channel(HydrologyTier tier) { + int points = 3; + float[] xs = new float[points]; + float[] zs = new float[points]; + int[] grade = new int[points]; + float[] halfWidth = new float[points]; + float[] depth = new float[points]; + ReachStyle[] style = new ReachStyle[points]; + for (int index = 0; index < points; index++) { + xs[index] = 100f + index * 50f; + zs[index] = 100f; + grade[index] = 70; + halfWidth[index] = 1f; + depth[index] = 1f; + style[index] = ReachStyle.RUN; + } + return new Reach(CHANNEL, tier, 0L, xs, zs, grade, halfWidth, depth, style, 2000f); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntimeTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntimeTest.java index 3765f73a6..3946dbed7 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntimeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntimeTest.java @@ -62,8 +62,10 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; @@ -369,11 +371,11 @@ public class HydrologyRuntimeTest { HydrologyRuntime runtime = runtime(planners, () -> false); HydrologyFeatureRef seeded = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048, - feature -> feature.id() != POND).orElseThrow(); + feature -> feature.id() != POND, () -> true).orElseThrow(); assertEquals(POND + 1, seeded.id()); assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048, - feature -> false)); + feature -> false, () -> true)); } @Test(timeout = 180_000L) @@ -822,14 +824,13 @@ public class HydrologyRuntimeTest { CountDownLatch regions = new CountDownLatch(1); planners.regionGate = regions; int before = planners.regionArrivals.get(); - AtomicReference> lake = new AtomicReference<>(); - Thread search = new Thread(() -> lake.set(runtime.nearestFeature(-20_000, -20_000, - HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 64))); + FutureTask> lake = new FutureTask<>(() -> runtime.nearestFeature(-20_000, -20_000, + HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 64)); + Thread search = new Thread(lake); search.start(); await(() -> planners.regionArrivals.get() - before >= 4, "every lake region to plan at once"); regions.countDown(); - search.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); - assertEquals(Optional.empty(), lake.get()); + assertEquals(Optional.empty(), lake.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); } @Test(timeout = 180_000L) @@ -878,7 +879,7 @@ public class HydrologyRuntimeTest { } @Test - public void createStaysDisabledWithoutHydrology() { + public void createStaysDisabledWithoutHydrology() throws Exception { Engine engine = mock(Engine.class); IrisComplex complex = mock(IrisComplex.class); IrisDimension dimension = new IrisDimension(); @@ -895,7 +896,7 @@ public class HydrologyRuntimeTest { @Test @SuppressWarnings("unchecked") - public void createChecksEveryReachableBiomeFluidWhileCavePoolsAreEnabled() { + public void createChecksEveryReachableBiomeFluidWhileCavePoolsAreEnabled() throws Exception { IrisDimension dimension = new IrisDimension().setRegions(new KList<>("tropical")); dimension.setHydrology(new IrisHydrology().setEnabled(true).setDensity(0D)); IrisRegion tropical = new IrisRegion().setLandBiomes(new KList<>("volcanoes")); @@ -924,7 +925,7 @@ public class HydrologyRuntimeTest { } @Test - public void zeroDensitySkipsRuntimePlanningAfterValidatingSettings() { + public void zeroDensitySkipsRuntimePlanningAfterValidatingSettings() throws Exception { Engine engine = mock(Engine.class); IrisComplex complex = mock(IrisComplex.class); IrisDimension dimension = new IrisDimension(); @@ -1059,8 +1060,9 @@ public class HydrologyRuntimeTest { } } - private static void assertDisabled(HydrologyRuntime runtime) { + private static void assertDisabled(HydrologyRuntime runtime) throws TimeoutException { assertFalse(runtime.enabled()); + assertEquals(Optional.of("hydrology is off"), runtime.unavailable(HydrologyFeatureType.RIVER)); assertEquals(0L, runtime.previewRevision()); assertSame(ChunkWaterRaster.EMPTY, runtime.raster(0, 0)); assertSame(ChunkWaterRaster.EMPTY, runtime.rasterSnapshot(0, 0)); diff --git a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java index 9dec58dc5..f1460ab42 100644 --- a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java @@ -84,7 +84,7 @@ public class SchemaBuilderIdentityTest { @ClassRule public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); - private static final String EXPECTED_SCHEMA_DIGEST = "87e3f95ad75204881cdcf766e9a318b69ca9fb365fe0249de112edaa8461dd00"; + private static final String EXPECTED_SCHEMA_DIGEST = "cc8006323ee6ce8f8cda87ddb7daf2e73fbb832937c9fce0afe4b71c1f1eae37"; private static final List> SCHEMA_ROOTS = List.of( IrisDimension.class, diff --git a/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticQueriesTest.java b/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticQueriesTest.java index d9757ba06..3c6753b83 100644 --- a/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticQueriesTest.java +++ b/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticQueriesTest.java @@ -12,8 +12,17 @@ import art.arcane.iris.generation.terrain.IrisDimension; import org.junit.Test; import org.mockito.MockedStatic; +import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; import java.util.function.Predicate; import static org.junit.Assert.assertEquals; @@ -25,9 +34,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -135,7 +146,7 @@ public final class GenerationSemanticQueriesTest { } @Test - public void rejectsTaperedPredictionsAndMergesTheNearestEligibleRiver() { + public void rejectsTaperedPredictionsAndMergesTheNearestEligibleRiver() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -178,11 +189,10 @@ public final class GenerationSemanticQueriesTest { when(history.semantics(anyInt(), anyInt())).thenReturn(Optional.empty()); when(history.activeActivation()).thenReturn(activation); when(activation.activationId()).thenReturn(2L); - when(runtime.nearestFeature(eq(0), eq(0), eq(HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER)), eq(200), any())) + when(runtime.nearestFeature(eq(0), eq(0), eq(HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER)), eq(200), any(), any())) .thenAnswer(invocation -> firstEligible(List.of(tapered, eligible), invocation.getArgument(4))); - GenerationSemanticQueries.RiverResult active = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.RIVER, 0, 0, 200).orElseThrow(); + GenerationSemanticQueries.RiverResult active = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); assertEquals(GenerationSemanticQueries.RiverSource.ACTIVE_PREDICTION, active.source()); assertEquals(HydrologyFeatureType.RIVER, active.type()); @@ -191,10 +201,9 @@ public final class GenerationSemanticQueriesTest { HydrologyFeatureRef fartherActive = feature(4L, 120, 20, 0); doAnswer(invocation -> firstEligible(List.of(tapered, fartherActive), invocation.getArgument(4))) - .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); + .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); - GenerationSemanticQueries.RiverResult historical = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.RIVER, 0, 0, 200).orElseThrow(); + GenerationSemanticQueries.RiverResult historical = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); assertEquals(GenerationSemanticQueries.RiverSource.RECORDED, historical.source()); assertEquals(100, historical.x()); @@ -202,7 +211,7 @@ public final class GenerationSemanticQueriesTest { } @Test - public void seamWeightIsJudgedPerCandidateInsideOneTransitionChunk() { + public void seamWeightIsJudgedPerCandidateInsideOneTransitionChunk() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -220,29 +229,28 @@ public final class GenerationSemanticQueriesTest { when(displacement.seamWeight(anyInt(), anyInt())).thenAnswer(invocation -> invocation.getArgument(0) < 8 ? 0.4D : 1D); when(dimension.getMinHeight()).thenReturn(-64); - when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())) + when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())) .thenAnswer(invocation -> firstEligible(List.of(tapered, solid), invocation.getArgument(4))); - GenerationSemanticQueries.RiverResult taperedFirst = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.RIVER, 0, 0, 200).orElseThrow(); + GenerationSemanticQueries.RiverResult taperedFirst = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); doAnswer(invocation -> firstEligible(List.of(solid, tapered), invocation.getArgument(4))) - .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); - GenerationSemanticQueries.RiverResult solidFirst = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.RIVER, 0, 0, 200).orElseThrow(); + .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + GenerationSemanticQueries.RiverResult solidFirst = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); doAnswer(invocation -> { Predicate eligible = invocation.getArgument(4); assertTrue(eligible.test(solid)); assertFalse(eligible.test(tapered)); return Optional.empty(); - }).when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); + }).when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); assertEquals(2L, taperedFirst.featureId()); assertEquals(2L, solidFirst.featureId()); - assertTrue(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200).isEmpty()); + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("No river found within 200 blocks."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); } @Test - public void returnsRecordedRiverWhenTheActivePackHasNoHydrology() { + public void returnsRecordedRiverWhenTheActivePackHasNoHydrology() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -258,6 +266,7 @@ public final class GenerationSemanticQueriesTest { when(engine.getComplex()).thenReturn(complex); when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.unavailable(any())).thenReturn(Optional.of("hydrology is off")); when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); when(router.history()).thenReturn(history); when(history.findRecordedRiver(any())).thenReturn(Optional.of( @@ -267,16 +276,154 @@ public final class GenerationSemanticQueriesTest { ) )); - GenerationSemanticQueries.RiverResult result = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.WATERFALL, 0, 0, 100).orElseThrow(); + GenerationSemanticQueries.RiverResult result = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.WATERFALL, 0, 0, 100, () -> true)); assertEquals(GenerationSemanticQueries.RiverSource.RECORDED, result.source()); assertEquals(HydrologyFeatureType.WATERFALL, result.type()); assertEquals(9L, result.featureId()); + verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + + when(history.findRecordedRiver(any())).thenReturn(Optional.empty()); + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("No waterfall forms in this dimension: hydrology is off."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.WATERFALL, 0, 0, 100, () -> true)); } @Test - public void cavePoolsAreFoundOnlyInRecordedHistory() { + public void disabledTypeAnswersWithItsReasonWithoutPlanning() throws Exception { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + GenerationHistory history = mock(GenerationHistory.class); + GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + when(runtime.unavailable(HydrologyFeatureType.DAM)).thenReturn(Optional.of("hydrology.ponds.dams is disabled")); + when(runtime.unavailable(HydrologyFeatureType.CAVE_POOL)).thenReturn(Optional.of("hydrology.underground.cavePools is disabled")); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); + when(router.history()).thenReturn(history); + when(history.findRecordedRiver(any())).thenReturn(Optional.empty()); + + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("No dam forms in this dimension: hydrology.ponds.dams is disabled."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.DAM, 0, 0, 100, () -> true)); + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing( + "No cave pool forms in this dimension: hydrology.underground.cavePools is disabled."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100, () -> true)); + + ChunkGenerationSemantics.RiverFeatureOccurrence older = new ChunkGenerationSemantics.RiverFeatureOccurrence( + "water", HydrologyFeatureType.DAM, 5L, new ChunkGenerationSemantics.BlockPosition(30, 64, 0)); + when(history.findRecordedRiver(any())).thenReturn(Optional.of( + new GenerationSemanticIndex.RiverMatch(older, new GenerationSemanticIndex.ChunkReference(1, 0, 1L)))); + GenerationSemanticQueries.RiverResult recorded = found( + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.DAM, 0, 0, 100, () -> true)); + + assertEquals(GenerationSemanticQueries.RiverSource.RECORDED, recorded.source()); + assertEquals(5L, recorded.featureId()); + verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + } + + @Test + public void timedOutSearchUsesRecordedWaterOrSaysItStopped() throws Exception { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + GenerationHistory history = mock(GenerationHistory.class); + GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())) + .thenThrow(new TimeoutException("The hydrology feature search ran past its 30000 ms limit.")); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty()); + + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("Stopped searching for the nearest river after 30 seconds."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true)); + + ChunkGenerationSemantics.RiverFeatureOccurrence occurrence = new ChunkGenerationSemantics.RiverFeatureOccurrence( + "water", HydrologyFeatureType.RIVER, 8L, new ChunkGenerationSemantics.BlockPosition(60, 70, 0)); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); + when(router.history()).thenReturn(history); + when(history.findRecordedRiver(any())).thenReturn(Optional.of( + new GenerationSemanticIndex.RiverMatch(occurrence, new GenerationSemanticIndex.ChunkReference(3, 0, 1L)))); + + assertEquals(8L, found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true)) + .featureId()); + } + + @Test + public void aNewSearchCancelsThePlayersPreviousSearch() throws Exception { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + when(engine.getComplex()).thenReturn(complex); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty()); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenReturn(Optional.empty()); + List queued = new ArrayList<>(); + UUID player = UUID.randomUUID(); + UUID other = UUID.randomUUID(); + GenerationSemanticQueries.RiverSearch missing = new GenerationSemanticQueries.RiverSearch.Missing( + "No river found within " + GenerationSemanticQueries.RIVER_SEARCH_DISTANCE + " blocks."); + + CompletableFuture first = GenerationSemanticQueries.startRiverSearch( + player, queued::add, engine, HydrologyFeatureType.RIVER, 0, 0); + CompletableFuture elsewhere = GenerationSemanticQueries.startRiverSearch( + other, queued::add, engine, HydrologyFeatureType.RIVER, 0, 0); + CompletableFuture second = GenerationSemanticQueries.startRiverSearch( + player, queued::add, engine, HydrologyFeatureType.RIVER, 0, 0); + + assertTrue(first.isCancelled()); + assertFalse(elsewhere.isDone()); + for (Runnable search : queued) { + search.run(); + } + assertEquals(missing, second.join()); + assertEquals(missing, elsewhere.join()); + verify(runtime, times(2)).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + } + + @Test + public void supersededSearchStopsAndOtherCancellationsAreFailures() throws Exception { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + when(engine.getComplex()).thenReturn(complex); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty()); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + UUID player = UUID.randomUUID(); + AtomicReference> replacement = new AtomicReference<>(); + AtomicBoolean stillRunning = new AtomicBoolean(true); + doAnswer(invocation -> { + BooleanSupplier running = invocation.getArgument(5); + assertTrue(running.getAsBoolean()); + replacement.set(GenerationSemanticQueries.startRiverSearch(player, ignored -> { + }, engine, HydrologyFeatureType.RIVER, 0, 0)); + stillRunning.set(running.getAsBoolean()); + throw new CancellationException("The hydrology feature search was cancelled."); + }).when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + + CompletableFuture superseded = GenerationSemanticQueries.startRiverSearch( + player, Runnable::run, engine, HydrologyFeatureType.RIVER, 0, 0); + + assertFalse(stillRunning.get()); + assertTrue(superseded.isCancelled()); + replacement.get().cancel(false); + + doThrow(new CancellationException("Hydrology plan cache is closed.")) + .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + CompletableFuture closed = GenerationSemanticQueries.startRiverSearch( + player, Runnable::run, engine, HydrologyFeatureType.RIVER, 0, 0); + + assertFalse(closed.isCancelled()); + ExecutionException failure = assertThrows(ExecutionException.class, closed::get); + assertTrue(String.valueOf(failure.getCause()), failure.getCause() instanceof IllegalStateException); + assertEquals("Hydrology plan cache is closed.", failure.getCause().getMessage()); + } + + @Test + public void cavePoolsAreFoundOnlyInRecordedHistory() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -292,21 +439,19 @@ public final class GenerationSemanticQueriesTest { when(history.findRecordedRiver(any())).thenReturn(Optional.of( new GenerationSemanticIndex.RiverMatch(occurrence, new GenerationSemanticIndex.ChunkReference(2, 0, 1L)))); - GenerationSemanticQueries.RiverResult found = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100).orElseThrow(); + GenerationSemanticQueries.RiverResult found = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100, () -> true)); assertEquals(GenerationSemanticQueries.RiverSource.RECORDED, found.source()); assertEquals(40, found.x()); assertEquals(-20, found.y()); - verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); + verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); when(history.findRecordedRiver(any())).thenReturn(Optional.empty()); - assertTrue(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100).isEmpty()); - verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); - assertTrue(GenerationSemanticQueries.riverNotFoundMessage(HydrologyFeatureType.CAVE_POOL, 100) - .startsWith("No cave pool found in generated chunks within 100 blocks.")); + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("No cave pool found in generated chunks within 100 blocks. Cave pools " + + "form in carved caves, so only chunks that have already generated can hold one."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100, () -> true)); + verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); assertTrue(GenerationSemanticQueries.riverSearchMessage(HydrologyFeatureType.CAVE_POOL, 100).contains("generated chunks")); - assertEquals("No river found within 100 blocks.", GenerationSemanticQueries.riverNotFoundMessage(HydrologyFeatureType.RIVER, 100)); } @Test @@ -328,7 +473,7 @@ public final class GenerationSemanticQueriesTest { } @Test - public void plannerFailureEscapesInsteadOfReportingNothingFound() { + public void plannerFailureEscapesInsteadOfReportingNothingFound() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -337,10 +482,10 @@ public final class GenerationSemanticQueriesTest { when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty()); when(complex.getHydrologyRuntime()).thenReturn(runtime); when(runtime.enabled()).thenReturn(true); - when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())).thenThrow(failure); + when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenThrow(failure); IllegalStateException thrown = assertThrows(IllegalStateException.class, - () -> GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.LAKE, 0, 0, 100)); + () -> GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.LAKE, 0, 0, 100, () -> true)); assertSame(failure, thrown); } @@ -357,6 +502,13 @@ public final class GenerationSemanticQueriesTest { return Optional.empty(); } + private static GenerationSemanticQueries.RiverResult found(GenerationSemanticQueries.RiverSearch search) { + if (search instanceof GenerationSemanticQueries.RiverSearch.Found found) { + return found.feature(); + } + throw new AssertionError("Expected a river, the search said: " + search); + } + private static HydrologyFeatureRef feature(long id, int x, int y, int z) { return new HydrologyFeatureRef(id, HydrologyFeatureType.RIVER, x, y, z); }