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
This commit is contained in:
Brian Neumann-Fopiano committed 2026-11-01 21:27:50 -05:00
1 parent 75d28d16b2
commit 474b1e873a
12 files changed
+826 -167

No files matched your search

@@ -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)
@@ -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<HydrologyFeatureType> 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<HydrologyFeatureType> types;
private final Predicate<HydrologyFeatureRef> 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<HydrologyFeatureRef> nearest() {
Optional<HydrologyFeatureRef> 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<String> 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<HydrologyFeatureType> enabledTypes(HydrologySettings settings, HydrologyFeatureQuery query) {
Set<HydrologyFeatureType> 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<HydrologyTier> 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<RegionPlan> 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<IndexedWindow> plan : plans) {
window(cache.awaitPlan(plan).plan());
window(await(plan, budget).plan());
}
}
}
private <T> T await(CompletableFuture<T> 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<WindowKey> 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);
}
}
}
@@ -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<HydrologyFeatureRef> nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius) {
return nearestFeature(blockX, blockZ, query, radius, feature -> true);
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,
Predicate<HydrologyFeatureRef> eligible) {
Predicate<HydrologyFeatureRef> 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<String> 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) {
@@ -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<UUID, CompletableFuture<RiverSearch>> 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<RiverResult> nearestRiver(
public static CompletableFuture<RiverSearch> 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<RiverSearch> search = new CompletableFuture<>();
CompletableFuture<RiverSearch> 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<String> 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<RiverSearch> 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<Long, Boolean> eligibleChunks = new HashMap<>();
TransitionDisplacementField displacement = engine.getComplex().getTransitionDisplacement();
Predicate<HydrologyFeatureRef> 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");
}
}
}
}