Report stopped river searches

- A timed-out hydrology search throws HydrologySearchTimeoutException carrying the nearest feature found so far
- nearestRiver answers RiverSearch.Stopped with the nearer of that feature and recorded water, and a message saying a nearer one may exist
- Bukkit and modded find river print the stopped message and never teleport on a stopped search
- Both commands catch every throwable while delivering a result and log it before telling the player
- Modded logs a result that cannot reach the server thread instead of dropping it
- The four-argument nearestFeature is removed; tests call the six-argument form
This commit is contained in:
Brian Neumann-Fopiano committed 2026-11-01 21:48:10 -05:00
1 parent 474b1e873a
commit 9afd70e69f
11 files changed
+247 -76

No files matched your search

@@ -240,9 +240,11 @@ public class CommandFind implements DirectorExecutor {
switch (search) { switch (search) {
case GenerationSemanticQueries.RiverSearch.Missing missing -> case GenerationSemanticQueries.RiverSearch.Missing missing ->
sendStructureMessage(request.target(), request.sender(), C.YELLOW + missing.message()); sendStructureMessage(request.target(), request.sender(), C.YELLOW + missing.message());
case GenerationSemanticQueries.RiverSearch.Stopped stopped ->
sendStructureMessage(request.target(), request.sender(), C.YELLOW + stopped.message());
case GenerationSemanticQueries.RiverSearch.Found found -> arriveAtRiver(request, found.feature()); case GenerationSemanticQueries.RiverSearch.Found found -> arriveAtRiver(request, found.feature());
} }
} catch (RuntimeException error) { } catch (Throwable error) {
reportRiverFailure(request, error); reportRiverFailure(request, error);
} }
} }
@@ -258,10 +260,10 @@ public class CommandFind implements DirectorExecutor {
} }
private void reportRiverFailure(RiverRequest request, Throwable failure) { private void reportRiverFailure(RiverRequest request, Throwable failure) {
Iris.reportError("Could not locate hydrology feature '" + request.type().key() + "'.", failure);
sendStructureMessage(request.target(), request.sender(), sendStructureMessage(request.target(), request.sender(),
C.RED + "Could not search for " + request.label() + ": " + failure.getClass().getSimpleName() C.RED + "Could not search for " + request.label() + ": " + failure.getClass().getSimpleName()
+ (failure.getMessage() == null ? "" : " - " + failure.getMessage())); + (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) @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)
@@ -2,6 +2,9 @@ package art.arcane.iris.command;
import art.arcane.iris.Iris; import art.arcane.iris.Iris;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.IrisComplex;
@@ -18,6 +21,7 @@ import org.bukkit.entity.Player;
import org.junit.Test; import org.junit.Test;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import java.time.Duration;
import java.util.Optional; import java.util.Optional;
import java.util.OptionalLong; import java.util.OptionalLong;
import java.util.UUID; import java.util.UUID;
@@ -31,6 +35,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
@@ -179,6 +184,38 @@ public class CommandFindHydrologyTest {
} }
} }
@Test
public void stoppedSearchReportsTheNearestWaterWithoutTeleporting() throws Exception {
try (Fixture fixture = new Fixture()) {
fixture.searchForReal();
IrisDimension dimension = mock(IrisDimension.class);
when(fixture.engine.getDimension()).thenReturn(dimension);
when(dimension.getMinHeight()).thenReturn(-64);
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenThrow(
new HydrologySearchTimeoutException(Duration.ofSeconds(30L), new HydrologyFeatureRef(1L, HydrologyFeatureType.RIVER, 32, 127, 32)));
fixture.command.river("river", true);
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("Stopped searching for the nearest river after 30 seconds. The nearest river found so "
+ "far is at 32, 63, 32; a nearer one may exist."));
fixture.platform.verify(() -> BukkitPlatform.chunkAtAsync(any(World.class), anyInt(), anyInt(), eq(true)), never());
fixture.platform.verify(() -> BukkitPlatform.teleportAsync(any(Player.class), any(Location.class)), never());
}
}
@Test
public void deliveryFailureIsReportedInsteadOfLost() {
try (Fixture fixture = new Fixture()) {
LinkageError failure = new LinkageError("sender gone");
doThrow(failure).when(fixture.sender).sendMessage(contains("Found river"));
fixture.command.river("river", false);
fixture.search.get().run();
fixture.logging.verify(() -> Iris.reportError(any(String.class), eq(failure)));
verify(fixture.sender).sendMessage(contains("Could not search for river: LinkageError - sender gone"));
}
}
@Test @Test
public void missingCavePoolIsReportedAsNotFoundInGeneratedChunks() { public void missingCavePoolIsReportedAsNotFoundInGeneratedChunks() {
try (Fixture fixture = new Fixture()) { try (Fixture fixture = new Fixture()) {
@@ -153,28 +153,46 @@ final class ModdedLocateCommands {
RiverRequest request = new RiverRequest(source, level, player, featureType); RiverRequest request = new RiverRequest(source, level, player, featureType);
IrisModdedCommands.ok(source, GenerationSemanticQueries.riverSearchMessage(featureType, GenerationSemanticQueries.RIVER_SEARCH_DISTANCE)); IrisModdedCommands.ok(source, GenerationSemanticQueries.riverSearchMessage(featureType, GenerationSemanticQueries.RIVER_SEARCH_DISTANCE));
GenerationSemanticQueries.startRiverSearch(player.id(), MultiBurst.burst, engine, featureType, player.blockX(), player.blockZ()) GenerationSemanticQueries.startRiverSearch(player.id(), MultiBurst.burst, engine, featureType, player.blockX(), player.blockZ())
.whenComplete((GenerationSemanticQueries.RiverSearch search, Throwable error) -> { .whenComplete((GenerationSemanticQueries.RiverSearch search, Throwable error) ->
if (!(error instanceof CancellationException)) { deliverRiverSearch(server, request, search, error));
server.execute(() -> finishRiverSearch(request, search, error));
}
});
return 1; return 1;
} }
private static void deliverRiverSearch(NativeModdedServer server, RiverRequest request, GenerationSemanticQueries.RiverSearch search,
Throwable error) {
if (error instanceof CancellationException) {
return;
}
try {
server.execute(() -> finishRiverSearch(request, search, error));
} catch (Throwable rejected) {
ModdedIrisLog.error("Hydrology locate result for {} could not reach the server thread", request.type().key(), rejected);
}
}
private static void finishRiverSearch(RiverRequest request, GenerationSemanticQueries.RiverSearch search, Throwable error) { private static void finishRiverSearch(RiverRequest request, GenerationSemanticQueries.RiverSearch search, Throwable error) {
if (error != null) { if (error != null) {
ModdedIrisLog.error("Hydrology locate failed for {}", request.type().key(), error); reportRiverFailure(request, error);
IrisModdedCommands.fail(request.source(), "Could not search for " + request.label() + ": " + error.getClass().getSimpleName()
+ (error.getMessage() == null ? "" : " - " + error.getMessage()));
return; return;
} }
switch (search) { try {
case GenerationSemanticQueries.RiverSearch.Missing missing -> IrisModdedCommands.fail(request.source(), missing.message()); switch (search) {
case GenerationSemanticQueries.RiverSearch.Found found -> teleportToStructure(request.source(), request.level(), case GenerationSemanticQueries.RiverSearch.Missing missing -> IrisModdedCommands.fail(request.source(), missing.message());
request.player(), found.feature().x(), found.feature().y() + 2, found.feature().z(), request.label()); case GenerationSemanticQueries.RiverSearch.Stopped stopped -> IrisModdedCommands.fail(request.source(), stopped.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());
}
} catch (Throwable failure) {
reportRiverFailure(request, failure);
} }
} }
private static void reportRiverFailure(RiverRequest request, Throwable error) {
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()));
}
static int gotoStructure(NativeCommandSource source, String keyRaw) { static int gotoStructure(NativeCommandSource source, String keyRaw) {
NativeWorld level = source.world(); NativeWorld level = source.world();
Engine engine = IrisModdedCommands.engineFor(level); Engine engine = IrisModdedCommands.engineFor(level);
@@ -4,6 +4,7 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisDimension;
@@ -18,6 +19,7 @@ import org.mockito.ArgumentCaptor;
import org.mockito.MockedConstruction; import org.mockito.MockedConstruction;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import java.time.Duration;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@@ -81,6 +83,35 @@ public class ModdedLocateRiverTest {
} }
} }
@Test
public void stoppedSearchReportsTheNearestWaterWithoutTeleporting() throws Exception {
Fixture fixture = new Fixture();
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenThrow(new HydrologySearchTimeoutException(
Duration.ofSeconds(30L), new HydrologyFeatureRef(9L, HydrologyFeatureType.WATERFALL, 400, 130, -250)));
try (MockedStatic<IrisModdedCommands> commands = fixture.commands()) {
assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "waterfall"));
fixture.finishOnServerThread();
commands.verify(() -> IrisModdedCommands.fail(fixture.source, "Stopped searching for the nearest waterfall after 30 seconds. "
+ "The nearest waterfall found so far is at 400, 66, -250; a nearer one may exist."));
verify(fixture.player, never()).teleport(any(), anyDouble(), anyDouble(), anyDouble());
}
}
@Test
public void deliveryFailureIsReportedInsteadOfLost() throws Exception {
Fixture fixture = new Fixture();
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenReturn(Optional.empty());
try (MockedStatic<IrisModdedCommands> commands = fixture.commands()) {
commands.when(() -> IrisModdedCommands.fail(fixture.source, "No river found within " + DISTANCE + " blocks."))
.thenThrow(new LinkageError("source gone"));
assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "river"));
fixture.finishOnServerThread();
commands.verify(() -> IrisModdedCommands.fail(fixture.source, "Could not search for river: LinkageError - source gone"));
}
}
@Test @Test
public void plannerFailureIsReportedAsAnErrorNotAsNotFound() throws Exception { public void plannerFailureIsReportedAsAnErrorNotAsNotFound() throws Exception {
Fixture fixture = new Fixture(); Fixture fixture = new Fixture();
@@ -10,6 +10,7 @@ import art.arcane.iris.generation.hydrology.plan.WindowPlan;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.hydrology.underground.SeaInlet; import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.Pond;
@@ -32,7 +33,6 @@ import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BooleanSupplier; import java.util.function.BooleanSupplier;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -68,7 +68,7 @@ final class HydrologyFeatureSearch {
this.radiusSquared = (long) radius * radius; this.radiusSquared = (long) radius * radius;
} }
Optional<HydrologyFeatureRef> nearest(Duration timeout, BooleanSupplier running) throws TimeoutException { Optional<HydrologyFeatureRef> nearest(Duration timeout, BooleanSupplier running) throws HydrologySearchTimeoutException {
Objects.requireNonNull(timeout, "timeout"); Objects.requireNonNull(timeout, "timeout");
Objects.requireNonNull(running, "running"); Objects.requireNonNull(running, "running");
int rings = Math.ceilDiv(radius, WindowKey.SIZE) + 1; int rings = Math.ceilDiv(radius, WindowKey.SIZE) + 1;
@@ -125,7 +125,7 @@ final class HydrologyFeatureSearch {
return false; return false;
} }
private void searchLakes(Budget budget) throws TimeoutException { private void searchLakes(Budget budget) throws HydrologySearchTimeoutException {
long minX = (long) originX - radius; long minX = (long) originX - radius;
long minZ = (long) originZ - radius; long minZ = (long) originZ - radius;
long maxX = (long) originX + radius; long maxX = (long) originX + radius;
@@ -145,7 +145,7 @@ final class HydrologyFeatureSearch {
} }
} }
private void searchWindows(int rings, Budget budget) throws TimeoutException { private void searchWindows(int rings, Budget budget) throws HydrologySearchTimeoutException {
WindowKey origin = WindowKey.containing(originX, originZ); WindowKey origin = WindowKey.containing(originX, originZ);
for (int ring = 0; ring <= rings; ring++) { for (int ring = 0; ring <= rings; ring++) {
long bound = Math.max(0L, (long) (ring - 2) * WindowKey.SIZE); long bound = Math.max(0L, (long) (ring - 2) * WindowKey.SIZE);
@@ -162,16 +162,27 @@ final class HydrologyFeatureSearch {
} }
} }
private <T> T await(CompletableFuture<T> plan, Budget budget) throws TimeoutException { private <T> T await(CompletableFuture<T> plan, Budget budget) throws HydrologySearchTimeoutException {
CountDownLatch settled = new CountDownLatch(1); CountDownLatch settled = new CountDownLatch(1);
plan.whenComplete((value, failure) -> settled.countDown()); plan.whenComplete((value, failure) -> settled.countDown());
boolean ready = false; boolean ready = false;
while (!ready) { while (!ready) {
ready = settle(settled, budget.slice()); ready = settle(settled, slice(budget));
} }
return cache.awaitPlan(plan); return cache.awaitPlan(plan);
} }
private long slice(Budget budget) throws HydrologySearchTimeoutException {
if (!budget.running().getAsBoolean()) {
throw new CancellationException("The hydrology feature search was cancelled.");
}
long remaining = budget.deadline() - System.nanoTime();
if (remaining <= 0L) {
throw new HydrologySearchTimeoutException(budget.timeout(), best);
}
return Math.min(remaining, POLL_NANOS);
}
private static boolean settle(CountDownLatch settled, long nanos) { private static boolean settle(CountDownLatch settled, long nanos) {
try { try {
return settled.await(nanos, TimeUnit.NANOSECONDS); return settled.await(nanos, TimeUnit.NANOSECONDS);
@@ -328,15 +339,5 @@ final class HydrologyFeatureSearch {
} }
private record Budget(long deadline, Duration timeout, BooleanSupplier running) { 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);
}
} }
} }
@@ -14,6 +14,7 @@ import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.hydrology.raster.ChannelFluids; import art.arcane.iris.generation.hydrology.raster.ChannelFluids;
import art.arcane.iris.generation.hydrology.raster.ChunkRasterizer; import art.arcane.iris.generation.hydrology.raster.ChunkRasterizer;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
@@ -52,7 +53,6 @@ import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BooleanSupplier; import java.util.function.BooleanSupplier;
import java.util.function.Function; import java.util.function.Function;
@@ -405,14 +405,9 @@ public final class HydrologyRuntime {
} }
} }
public Optional<HydrologyFeatureRef> nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius)
throws TimeoutException {
return nearestFeature(blockX, blockZ, query, radius, feature -> true, () -> true);
}
public Optional<HydrologyFeatureRef> nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius, public Optional<HydrologyFeatureRef> nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius,
Predicate<HydrologyFeatureRef> eligible, BooleanSupplier running) Predicate<HydrologyFeatureRef> eligible, BooleanSupplier running)
throws TimeoutException { throws HydrologySearchTimeoutException {
Objects.requireNonNull(query, "query"); Objects.requireNonNull(query, "query");
Objects.requireNonNull(eligible, "eligible"); Objects.requireNonNull(eligible, "eligible");
Objects.requireNonNull(running, "running"); Objects.requireNonNull(running, "running");
@@ -0,0 +1,18 @@
package art.arcane.iris.generation.hydrology.query;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeoutException;
public final class HydrologySearchTimeoutException extends TimeoutException {
private final HydrologyFeatureRef nearestSoFar;
public HydrologySearchTimeoutException(Duration timeout, HydrologyFeatureRef nearestSoFar) {
super("The hydrology feature search ran past its " + timeout.toMillis() + " ms limit.");
this.nearestSoFar = nearestSoFar;
}
public Optional<HydrologyFeatureRef> nearestSoFar() {
return Optional.ofNullable(nearestSoFar);
}
}
@@ -9,6 +9,7 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import java.math.BigInteger; import java.math.BigInteger;
import java.io.IOException; import java.io.IOException;
@@ -27,7 +28,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.function.BooleanSupplier; import java.util.function.BooleanSupplier;
@@ -218,8 +218,9 @@ public final class GenerationSemanticQueries {
RiverResult active; RiverResult active;
try { try {
active = activeRiver(requiredEngine, history, requiredType, blockX, blockZ, maximumDistance, running); active = activeRiver(requiredEngine, history, requiredType, blockX, blockZ, maximumDistance, running);
} catch (TimeoutException timedOut) { } catch (HydrologySearchTimeoutException timedOut) {
return recorded != null ? new RiverSearch.Found(recorded) : new RiverSearch.Missing(riverTimeoutMessage(requiredType)); RiverResult planned = timedOut.nearestSoFar().map(feature -> activeResult(requiredEngine, history, feature)).orElse(null);
return stoppedSearch(requiredType, nearer(blockX, blockZ, recorded, planned));
} }
RiverResult nearest = nearer(blockX, blockZ, recorded, active); RiverResult nearest = nearer(blockX, blockZ, recorded, active);
return nearest == null return nearest == null
@@ -273,9 +274,14 @@ public final class GenerationSemanticQueries {
return "No " + label(type) + " forms in this dimension: " + reason + "."; return "No " + label(type) + " forms in this dimension: " + reason + ".";
} }
private static String riverTimeoutMessage(HydrologyFeatureType type) { private static RiverSearch stoppedSearch(HydrologyFeatureType type, RiverResult nearestSoFar) {
return "Stopped searching for the nearest " + label(type) + " after " String stopped = "Stopped searching for the nearest " + label(type) + " after "
+ HydrologyRuntime.FEATURE_SEARCH_TIMEOUT.toSeconds() + " seconds."; + HydrologyRuntime.FEATURE_SEARCH_TIMEOUT.toSeconds() + " seconds";
if (nearestSoFar == null) {
return new RiverSearch.Stopped(Optional.empty(), stopped + " without finding one.");
}
return new RiverSearch.Stopped(Optional.of(nearestSoFar), stopped + ". The nearest " + label(type) + " found so far is at "
+ nearestSoFar.x() + ", " + nearestSoFar.y() + ", " + nearestSoFar.z() + "; a nearer one may exist.");
} }
private static String label(HydrologyFeatureType type) { private static String label(HydrologyFeatureType type) {
@@ -381,7 +387,7 @@ public final class GenerationSemanticQueries {
int blockZ, int blockZ,
int maximumDistance, int maximumDistance,
BooleanSupplier running BooleanSupplier running
) throws TimeoutException { ) throws HydrologySearchTimeoutException {
HydrologyRuntime runtime = engine.getComplex().getHydrologyRuntime(); HydrologyRuntime runtime = engine.getComplex().getHydrologyRuntime();
Map<Long, Boolean> eligibleChunks = new HashMap<>(); Map<Long, Boolean> eligibleChunks = new HashMap<>();
TransitionDisplacementField displacement = engine.getComplex().getTransitionDisplacement(); TransitionDisplacementField displacement = engine.getComplex().getTransitionDisplacement();
@@ -397,9 +403,10 @@ public final class GenerationSemanticQueries {
eligibility, eligibility,
running running
).orElse(null); ).orElse(null);
if (feature == null) { return feature == null ? null : activeResult(engine, history, feature);
return null; }
}
private static RiverResult activeResult(Engine engine, GenerationHistory history, HydrologyFeatureRef feature) {
OptionalLong activationId = history == null OptionalLong activationId = history == null
? OptionalLong.empty() ? OptionalLong.empty()
: OptionalLong.of(history.activeActivation().activationId()); : OptionalLong.of(history.activeActivation().activationId());
@@ -470,5 +477,12 @@ public final class GenerationSemanticQueries {
Objects.requireNonNull(message, "message"); Objects.requireNonNull(message, "message");
} }
} }
record Stopped(Optional<RiverResult> nearestSoFar, String message) implements RiverSearch {
public Stopped {
Objects.requireNonNull(nearestSoFar, "nearestSoFar");
Objects.requireNonNull(message, "message");
}
}
} }
} }
@@ -11,6 +11,7 @@ import art.arcane.iris.generation.hydrology.plan.WindowPlan;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Reach; import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle; import art.arcane.iris.generation.hydrology.water.ReachStyle;
@@ -28,7 +29,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -100,10 +100,26 @@ public class HydrologyFeatureSearchTest {
HydrologyFeatureSearch search = search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.POND)); HydrologyFeatureSearch search = search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.POND));
long started = System.nanoTime(); long started = System.nanoTime();
assertThrows(TimeoutException.class, () -> search.nearest(timeout, () -> true)); HydrologySearchTimeoutException stopped = assertThrows(HydrologySearchTimeoutException.class,
() -> search.nearest(timeout, () -> true));
assertTrue(System.nanoTime() - started >= timeout.toNanos()); assertTrue(System.nanoTime() - started >= timeout.toNanos());
assertTrue(planners.calls.get() > 0); assertTrue(planners.calls.get() > 0);
assertEquals(Optional.empty(), stopped.nearestSoFar());
}
@Test(timeout = 20_000L)
public void timedOutSearchKeepsTheNearestFeatureFoundSoFar() {
HydrologySettings settings = settings(config -> {
});
Planners planners = new Planners(gate);
planners.channelTier = settings.tiers().getFirst();
HydrologyPlanCache cache = cache(settings, planners);
HydrologySearchTimeoutException stopped = assertThrows(HydrologySearchTimeoutException.class,
() -> search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM)).nearest(Duration.ofMillis(200L), () -> true));
assertEquals(Optional.of(new HydrologyFeatureRef(CHANNEL, HydrologyFeatureType.STREAM, 100, 70, 100)), stopped.nearestSoFar());
} }
@Test(timeout = 20_000L) @Test(timeout = 20_000L)
@@ -183,16 +199,15 @@ public class HydrologyFeatureSearchTest {
RegionPlan region(RegionKey key) { RegionPlan region(RegionKey key) {
calls.incrementAndGet(); calls.incrementAndGet();
hold();
return new RegionPlan(key, List.of(), List.of()); return new RegionPlan(key, List.of(), List.of());
} }
WindowPlan window(WindowKey key, List<RegionPlan> plans) { WindowPlan window(WindowKey key, List<RegionPlan> plans) {
calls.incrementAndGet(); calls.incrementAndGet();
hold();
if (channelTier != null && key.equals(new WindowKey(0, 0))) { 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(channel(channelTier)), List.of(), List.of());
} }
hold();
return new WindowPlan(key, List.of(), List.of(), List.of()); return new WindowPlan(key, List.of(), List.of(), List.of());
} }
@@ -71,6 +71,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier; import java.util.function.BooleanSupplier;
import java.util.function.Predicate;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
@@ -107,6 +108,8 @@ public class HydrologyRuntimeTest {
private static final long LAKE = 0x4c414b45L; private static final long LAKE = 0x4c414b45L;
private static final long RIVER = 0x52495645L; private static final long RIVER = 0x52495645L;
private static final long INLET = 0x494e4c4554L; private static final long INLET = 0x494e4c4554L;
private static final Predicate<HydrologyFeatureRef> ANY = feature -> true;
private static final BooleanSupplier RUNNING = () -> true;
@ClassRule @ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@@ -301,24 +304,29 @@ public class HydrologyRuntimeTest {
FakePlanners planners = new FakePlanners(settings()); FakePlanners planners = new FakePlanners(settings());
HydrologyRuntime runtime = runtime(planners, () -> false); HydrologyRuntime runtime = runtime(planners, () -> false);
HydrologyFeatureRef pond = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048).orElseThrow(); HydrologyFeatureRef pond = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048, ANY, RUNNING)
.orElseThrow();
assertEquals(new HydrologyFeatureRef(POND, HydrologyFeatureType.POND, 2, 70, 2), pond); assertEquals(new HydrologyFeatureRef(POND, HydrologyFeatureType.POND, 2, 70, 2), pond);
assertEquals(0, planners.windowCalls(new WindowKey(3, 3))); assertEquals(0, planners.windowCalls(new WindowKey(3, 3)));
assertEquals(new HydrologyFeatureRef(POND + 1, HydrologyFeatureType.POND, 300, 70, 300), assertEquals(new HydrologyFeatureRef(POND + 1, HydrologyFeatureType.POND, 300, 70, 300),
runtime.nearestFeature(301, 299, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64).orElseThrow()); runtime.nearestFeature(301, 299, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64, ANY, RUNNING).orElseThrow());
HydrologyFeatureRef river = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER), 2048).orElseThrow(); HydrologyFeatureRef river = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER), 2048, ANY, RUNNING)
.orElseThrow();
assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.RIVER, 1000, 80, 200), river); assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.RIVER, 1000, 80, 200), river);
HydrologyFeatureRef fall = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.WATERFALL), 2048).orElseThrow(); HydrologyFeatureRef fall = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.WATERFALL), 2048, ANY,
RUNNING).orElseThrow();
assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.WATERFALL, 1050, 75, 200), fall); assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.WATERFALL, 1050, 75, 200), fall);
HydrologyFeatureQuery water = HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER, HydrologyFeatureType.POND); HydrologyFeatureQuery water = HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER, HydrologyFeatureType.POND);
assertEquals(pond, runtime.nearestFeature(0, 0, water, 2048).orElseThrow()); assertEquals(pond, runtime.nearestFeature(0, 0, water, 2048, ANY, RUNNING).orElseThrow());
assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.RIVER, 1100, 70, 200), runtime.nearestFeature(1100, 100, water, 2048) assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.RIVER, 1100, 70, 200),
.orElseThrow()); runtime.nearestFeature(1100, 100, water, 2048, ANY, RUNNING).orElseThrow());
assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2)); assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2, ANY, RUNNING));
assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, assertEquals(Optional.empty(), runtime.nearestFeature(0, 0,
HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM, HydrologyFeatureType.MAJOR_RIVER), 2048)); HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM, HydrologyFeatureType.MAJOR_RIVER), 2048, ANY, RUNNING));
assertEquals(FAR_POND, runtime.nearestFeature(1700, 150, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 512).orElseThrow().id()); assertEquals(FAR_POND, runtime.nearestFeature(1700, 150, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 512, ANY, RUNNING)
HydrologyFeatureRef lake = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 4096).orElseThrow(); .orElseThrow().id());
HydrologyFeatureRef lake = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 4096, ANY, RUNNING)
.orElseThrow();
assertEquals(new HydrologyFeatureRef(LAKE, HydrologyFeatureType.LAKE, 2500, 90, 2500), lake); assertEquals(new HydrologyFeatureRef(LAKE, HydrologyFeatureType.LAKE, 2500, 90, 2500), lake);
} }
@@ -358,9 +366,11 @@ public class HydrologyRuntimeTest {
assertTrue("the chunk past the owner window writes inlet water", assertTrue("the chunk past the owner window writes inlet water",
written.values().stream().anyMatch(cell -> cell.action() == HydrologyCaveAction.WET_SOURCE)); written.values().stream().anyMatch(cell -> cell.action() == HydrologyCaveAction.WET_SOURCE));
HydrologyFeatureRef nearest = runtime.nearestFeature(1050, 405, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 512).orElseThrow(); HydrologyFeatureRef nearest = runtime.nearestFeature(1050, 405, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 512, ANY,
RUNNING).orElseThrow();
assertEquals(new HydrologyFeatureRef(INLET, HydrologyFeatureType.SEA_INLET, 1048, 40, 400), nearest); assertEquals(new HydrologyFeatureRef(INLET, HydrologyFeatureType.SEA_INLET, 1048, 40, 400), nearest);
assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 64)); assertEquals(Optional.empty(),
runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 64, ANY, RUNNING));
assertEquals(List.of(FakePlanners.inlet()), runtime.planPreview(900, 300, 1100, 500).inlets()); assertEquals(List.of(FakePlanners.inlet()), runtime.planPreview(900, 300, 1100, 500).inlets());
assertEquals(List.of(), FakeHydrology.disabled().inlets(0, 0)); assertEquals(List.of(), FakeHydrology.disabled().inlets(0, 0));
} }
@@ -371,11 +381,11 @@ public class HydrologyRuntimeTest {
HydrologyRuntime runtime = runtime(planners, () -> false); HydrologyRuntime runtime = runtime(planners, () -> false);
HydrologyFeatureRef seeded = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048, HydrologyFeatureRef seeded = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048,
feature -> feature.id() != POND, () -> true).orElseThrow(); feature -> feature.id() != POND, RUNNING).orElseThrow();
assertEquals(POND + 1, seeded.id()); assertEquals(POND + 1, seeded.id());
assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048, assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048,
feature -> false, () -> true)); feature -> false, RUNNING));
} }
@Test(timeout = 180_000L) @Test(timeout = 180_000L)
@@ -808,7 +818,7 @@ public class HydrologyRuntimeTest {
AtomicBoolean main = new AtomicBoolean(true); AtomicBoolean main = new AtomicBoolean(true);
HydrologyRuntime runtime = runtime(planners, pool, main::get); HydrologyRuntime runtime = runtime(planners, pool, main::get);
try { try {
runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64); runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64, ANY, RUNNING);
fail("A feature search on the main thread must refuse"); fail("A feature search on the main thread must refuse");
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
assertTrue(expected.getMessage(), expected.getMessage().contains("main thread")); assertTrue(expected.getMessage(), expected.getMessage().contains("main thread"));
@@ -818,14 +828,15 @@ public class HydrologyRuntimeTest {
assertEquals(0, planners.windowOrder().size()); assertEquals(0, planners.windowOrder().size());
assertEquals(0, planners.regionArrivals.get()); assertEquals(0, planners.regionArrivals.get());
assertEquals(Optional.empty(), runtime.nearestFeature(10_000, 10_000, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64)); assertEquals(Optional.empty(),
runtime.nearestFeature(10_000, 10_000, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64, ANY, RUNNING));
assertEquals(25, planners.windowOrder().size()); assertEquals(25, planners.windowOrder().size());
CountDownLatch regions = new CountDownLatch(1); CountDownLatch regions = new CountDownLatch(1);
planners.regionGate = regions; planners.regionGate = regions;
int before = planners.regionArrivals.get(); int before = planners.regionArrivals.get();
FutureTask<Optional<HydrologyFeatureRef>> lake = new FutureTask<>(() -> runtime.nearestFeature(-20_000, -20_000, FutureTask<Optional<HydrologyFeatureRef>> lake = new FutureTask<>(() -> runtime.nearestFeature(-20_000, -20_000,
HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 64)); HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 64, ANY, RUNNING));
Thread search = new Thread(lake); Thread search = new Thread(lake);
search.start(); search.start();
await(() -> planners.regionArrivals.get() - before >= 4, "every lake region to plan at once"); await(() -> planners.regionArrivals.get() - before >= 4, "every lake region to plan at once");
@@ -1067,7 +1078,7 @@ public class HydrologyRuntimeTest {
assertSame(ChunkWaterRaster.EMPTY, runtime.raster(0, 0)); assertSame(ChunkWaterRaster.EMPTY, runtime.raster(0, 0));
assertSame(ChunkWaterRaster.EMPTY, runtime.rasterSnapshot(0, 0)); assertSame(ChunkWaterRaster.EMPTY, runtime.rasterSnapshot(0, 0));
assertSame(ChunkWaterRaster.EMPTY, runtime.rasterAt(0, 0)); assertSame(ChunkWaterRaster.EMPTY, runtime.rasterAt(0, 0));
assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64)); assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64, ANY, RUNNING));
assertTrue(runtime.prepareWindowsAround(0, 0, 0, 0, 1).isDone()); assertTrue(runtime.prepareWindowsAround(0, 0, 0, 0, 1).isDone());
try (HydrologyPregeneration pregeneration = runtime.openPregeneration()) { try (HydrologyPregeneration pregeneration = runtime.openPregeneration()) {
pregeneration.prepare(List.of(new long[]{0L, 0L})); pregeneration.prepare(List.of(new long[]{0L, 0L}));
@@ -8,10 +8,12 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisDimension;
import org.junit.Test; import org.junit.Test;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@@ -19,7 +21,6 @@ import java.util.UUID;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier; import java.util.function.BooleanSupplier;
@@ -323,31 +324,52 @@ public final class GenerationSemanticQueriesTest {
} }
@Test @Test
public void timedOutSearchUsesRecordedWaterOrSaysItStopped() throws Exception { public void stoppedSearchReportsTheNearestWaterFoundSoFar() throws Exception {
IrisEngine engine = mock(IrisEngine.class); IrisEngine engine = mock(IrisEngine.class);
IrisComplex complex = mock(IrisComplex.class); IrisComplex complex = mock(IrisComplex.class);
HydrologyRuntime runtime = mock(HydrologyRuntime.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class);
IrisDimension dimension = mock(IrisDimension.class);
GenerationHistory history = mock(GenerationHistory.class); GenerationHistory history = mock(GenerationHistory.class);
GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class); GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class);
GenerationActivation activation = mock(GenerationActivation.class);
when(engine.getComplex()).thenReturn(complex); when(engine.getComplex()).thenReturn(complex);
when(engine.getDimension()).thenReturn(dimension);
when(dimension.getMinHeight()).thenReturn(-64);
when(complex.getHydrologyRuntime()).thenReturn(runtime); when(complex.getHydrologyRuntime()).thenReturn(runtime);
when(runtime.enabled()).thenReturn(true); when(runtime.enabled()).thenReturn(true);
when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())) when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()))
.thenThrow(new TimeoutException("The hydrology feature search ran past its 30000 ms limit.")); .thenThrow(new HydrologySearchTimeoutException(Duration.ofSeconds(30L), null));
when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty()); when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty());
assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("Stopped searching for the nearest river after 30 seconds."), assertEquals(new GenerationSemanticQueries.RiverSearch.Stopped(Optional.empty(),
"Stopped searching for the nearest river after 30 seconds without finding one."),
GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true)); GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true));
ChunkGenerationSemantics.RiverFeatureOccurrence occurrence = new ChunkGenerationSemantics.RiverFeatureOccurrence( ChunkGenerationSemantics.RiverFeatureOccurrence occurrence = new ChunkGenerationSemantics.RiverFeatureOccurrence(
"water", HydrologyFeatureType.RIVER, 8L, new ChunkGenerationSemantics.BlockPosition(60, 70, 0)); "water", HydrologyFeatureType.RIVER, 8L, new ChunkGenerationSemantics.BlockPosition(60, 70, 0));
when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router));
when(router.history()).thenReturn(history); when(router.history()).thenReturn(history);
when(history.activeActivation()).thenReturn(activation);
when(activation.activationId()).thenReturn(2L);
when(history.findRecordedRiver(any())).thenReturn(Optional.of( when(history.findRecordedRiver(any())).thenReturn(Optional.of(
new GenerationSemanticIndex.RiverMatch(occurrence, new GenerationSemanticIndex.ChunkReference(3, 0, 1L)))); new GenerationSemanticIndex.RiverMatch(occurrence, new GenerationSemanticIndex.ChunkReference(3, 0, 1L))));
GenerationSemanticQueries.RiverSearch.Stopped recorded = stopped(
GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true));
assertEquals(8L, found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true)) assertEquals(8L, recorded.nearestSoFar().orElseThrow().featureId());
.featureId()); assertEquals("Stopped searching for the nearest river after 30 seconds. The nearest river found so far is at 60, 70, 0; "
+ "a nearer one may exist.", recorded.message());
doThrow(new HydrologySearchTimeoutException(Duration.ofSeconds(30L), feature(4L, 20, 20, 0)))
.when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any());
GenerationSemanticQueries.RiverSearch.Stopped planned = stopped(
GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true));
GenerationSemanticQueries.RiverResult nearer = planned.nearestSoFar().orElseThrow();
assertEquals(GenerationSemanticQueries.RiverSource.ACTIVE_PREDICTION, nearer.source());
assertEquals(4L, nearer.featureId());
assertEquals(-44, nearer.y());
assertTrue(planned.message(), planned.message().contains("at 20, -44, 0;"));
} }
@Test @Test
@@ -509,6 +531,13 @@ public final class GenerationSemanticQueriesTest {
throw new AssertionError("Expected a river, the search said: " + search); throw new AssertionError("Expected a river, the search said: " + search);
} }
private static GenerationSemanticQueries.RiverSearch.Stopped stopped(GenerationSemanticQueries.RiverSearch search) {
if (search instanceof GenerationSemanticQueries.RiverSearch.Stopped stopped) {
return stopped;
}
throw new AssertionError("Expected a stopped search, the search said: " + search);
}
private static HydrologyFeatureRef feature(long id, int x, int y, int z) { private static HydrologyFeatureRef feature(long id, int x, int y, int z) {
return new HydrologyFeatureRef(id, HydrologyFeatureType.RIVER, x, y, z); return new HydrologyFeatureRef(id, HydrologyFeatureType.RIVER, x, y, z);
} }