Inland lowlands not mouths

- Reach chains end at the sea only where the receiver has ocean intent
- Channels continue across non-ocean lowland below sea level toward the sea
- Fitted ocean flags stay only on the trailing run of chains that drain to the sea
- Ground reads off the sea run ignore sub-cell ocean slivers, so a sliver no longer trenches a reach or drops ponds below it
- Inland hollows below sea level hold an outlet-free pond at sea level; oversized ones sink instead of being breached
- Burned trunks neither descend nor drain through inland hollows
- Sea-head check keys on the trailing mouth run and fails closed on mouths inside a reach or draining into another reach
- Inland water keeps the land biome at any head; mouths and inlets keep the sea biome
- Tests for inland hollows, crater rims, sea slivers, inland pond outlets, coastal delta ownership and the sea-level river biome
This commit is contained in:
Brian Neumann-Fopiano committed 2026-11-02 01:57:09 -05:00
1 parent d61b5c3041
commit 30865031ba
19 files changed
+786 -112

No files matched your search

@@ -1,6 +1,6 @@
package art.arcane.iris.generation.hydrology.grid;
public record Basin(int id, int floorIndex, int spillIndex, float spillHeight, float maxDepth, int[] cells) {
public record Basin(int id, int floorIndex, int spillIndex, float spillHeight, float maxDepth, int[] cells, boolean belowSea) {
public int span(int width) {
int minI = Integer.MAX_VALUE;
int maxI = Integer.MIN_VALUE;
@@ -2,7 +2,9 @@ package art.arcane.iris.generation.hydrology.grid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import java.util.function.IntPredicate;
public final class BasinExtractor {
private BasinExtractor() {
@@ -62,11 +64,139 @@ public final class BasinExtractor {
}
int spill = spill(raw, filled, floor, lowestFilled);
float spillHeight = heights[spill];
basins.add(new Basin(basins.size(), floor, spill, spillHeight, spillHeight - heights[floor], cells));
basins.add(new Basin(basins.size(), floor, spill, spillHeight, spillHeight - heights[floor], cells, false));
}
return basins;
}
public static BitSet inland(DemGrid natural, boolean[] ocean, int seaLevel) {
float[] heights = natural.values();
int count = heights.length;
if (ocean.length < count) {
throw new IllegalArgumentException("Ocean flags cover " + ocean.length + " cells, grid has " + count);
}
BitSet inland = new BitSet(count);
boolean[] visited = new boolean[count];
int[] queue = new int[count];
for (int start = 0; start < count; start++) {
if (visited[start] || !belowSea(heights, ocean, start, seaLevel)) {
continue;
}
int tail = component(natural, cell -> belowSea(heights, ocean, cell, seaLevel), visited, queue, start);
if (enclosed(natural, ocean, queue, tail)) {
for (int index = 0; index < tail; index++) {
inland.set(queue[index]);
}
}
}
return inland;
}
public static BitSet hollow(DemGrid natural, BitSet inland, int cell) {
BitSet hollow = new BitSet(natural.values().length);
if (!inland.get(cell)) {
return hollow;
}
int[] queue = new int[natural.values().length];
int tail = component(natural, inland::get, new boolean[queue.length], queue, cell);
for (int index = 0; index < tail; index++) {
hollow.set(queue[index]);
}
return hollow;
}
public static List<Basin> hollows(DemGrid natural, BitSet inland, float[] filled, int seaLevel, int firstId) {
float[] heights = natural.values();
boolean[] visited = new boolean[heights.length];
int[] queue = new int[heights.length];
List<Basin> hollows = new ArrayList<>();
for (int start = inland.nextSetBit(0); start >= 0; start = inland.nextSetBit(start + 1)) {
if (visited[start]) {
continue;
}
int tail = component(natural, inland::get, visited, queue, start);
if (!drained(filled, queue, tail, seaLevel)) {
continue;
}
int[] cells = Arrays.copyOf(queue, tail);
Arrays.sort(cells);
int floor = cells[0];
for (int cell : cells) {
if (heights[cell] < heights[floor]) {
floor = cell;
}
}
hollows.add(new Basin(firstId + hollows.size(), floor, floor, seaLevel, seaLevel - heights[floor], cells, true));
}
return hollows;
}
private static boolean drained(float[] filled, int[] cells, int count, int seaLevel) {
for (int index = 0; index < count; index++) {
if (filled[cells[index]] > seaLevel) {
return false;
}
}
return true;
}
private static boolean belowSea(float[] heights, boolean[] ocean, int cell, int seaLevel) {
return !ocean[cell] && Math.round(heights[cell]) < seaLevel;
}
private static boolean enclosed(DemGrid grid, boolean[] ocean, int[] cells, int count) {
int width = grid.width();
int depth = grid.depth();
for (int index = 0; index < count; index++) {
int cell = cells[index];
int i = cell % width;
int j = cell / width;
if (i == 0 || j == 0 || i == width - 1 || j == depth - 1) {
return false;
}
for (int dz = -1; dz <= 1; dz++) {
for (int dx = -1; dx <= 1; dx++) {
if (ocean[(j + dz) * width + i + dx]) {
return false;
}
}
}
}
return true;
}
private static int component(DemGrid grid, IntPredicate member, boolean[] visited, int[] queue, int start) {
int width = grid.width();
int depth = grid.depth();
int head = 0;
int tail = 0;
queue[tail++] = start;
visited[start] = true;
while (head < tail) {
int cell = queue[head++];
int i = cell % width;
int j = cell / width;
for (int dz = -1; dz <= 1; dz++) {
int nj = j + dz;
if (nj < 0 || nj >= depth) {
continue;
}
for (int dx = -1; dx <= 1; dx++) {
int ni = i + dx;
if (ni < 0 || ni >= width) {
continue;
}
int neighbour = nj * width + ni;
if (!visited[neighbour] && member.test(neighbour)) {
visited[neighbour] = true;
queue[tail++] = neighbour;
}
}
}
}
return tail;
}
private static boolean flooded(float[] heights, float[] filled, int cell, float minDepth, float seaLevel) {
return filled[cell] - heights[cell] > minDepth && filled[cell] > seaLevel;
}
@@ -13,22 +13,24 @@ import java.util.Map;
final class BurnedTrunks {
private final BitSet cells;
private final BitSet hollows;
private final int[] next;
private final float[] catchment;
private final float epsilon;
private int[] order;
private BitSet entries;
private BurnedTrunks(int count, float epsilon) {
private BurnedTrunks(int count, float epsilon, BitSet hollows) {
this.cells = new BitSet(count);
this.hollows = hollows;
this.next = new int[count];
this.catchment = new float[count];
this.epsilon = epsilon;
Arrays.fill(next, -1);
}
static BurnedTrunks burn(DemGrid raw, List<Reach> reaches, float depth, float epsilon) {
BurnedTrunks trunks = new BurnedTrunks(raw.values().length, epsilon);
static BurnedTrunks burn(DemGrid raw, List<Reach> reaches, float depth, float epsilon, BitSet hollows) {
BurnedTrunks trunks = new BurnedTrunks(raw.values().length, epsilon, hollows);
Map<Long, Reach> byId = new HashMap<>();
for (Reach reach : reaches) {
byId.putIfAbsent(reach.id(), reach);
@@ -57,7 +59,7 @@ final class BurnedTrunks {
void descend(float[] heights) {
for (int cell : order) {
int successor = next[cell];
if (successor >= 0) {
if (successor >= 0 && !hollows.get(cell)) {
heights[successor] = Math.min(heights[successor], Math.min(heights[cell] - epsilon, Math.nextDown(heights[cell])));
}
}
@@ -65,7 +67,7 @@ final class BurnedTrunks {
void route(int[] receivers) {
for (int cell = cells.nextSetBit(0); cell >= 0; cell = cells.nextSetBit(cell + 1)) {
if (next[cell] >= 0) {
if (next[cell] >= 0 && !hollows.get(cell)) {
receivers[cell] = next[cell];
}
}
@@ -130,7 +130,7 @@ public final class RegionPlanner {
BitSet candidates = ChannelHeads.candidates(surface, accumulation, samples.permission(), settings.majorTier().minCatchment(), settings.seaLevel());
BitSet channels = ChannelHeads.keep(surface, samples.height(), receivers, candidates, settings.drainage().headRelief(), cell -> false,
cell -> CellHash.unit(CellHash.mix(settings.seed(), SALT_HEAD, surface.blockX(cell), surface.blockZ(cell))) < settings.density());
return shaper.coarsePaths(surface, receivers, accumulation, channels, settings.seed());
return shaper.coarsePaths(surface, receivers, accumulation, channels, samples.ocean(), settings.seed());
}
private static List<Reach> ownedReaches(RegionKey key, List<Reach> reaches) {
@@ -85,14 +85,19 @@ public final class WindowPlanner {
int cellZ = Math.multiplyExact(key.wz() - 1, WINDOW_CELLS);
HydrologySampleBuffer samples = new HydrologySampleBuffer(SPAN * SPAN);
fine.fill(cellX * FINE_STRIDE, cellZ * FINE_STRIDE, SPAN, SPAN, FINE_STRIDE, samples);
DemGrid raw = new DemGrid(cellX * CELL, cellZ * CELL, CELL, SPAN, SPAN);
System.arraycopy(samples.height(), 0, raw.values(), 0, SPAN * SPAN);
DemGrid natural = new DemGrid(cellX * CELL, cellZ * CELL, CELL, SPAN, SPAN);
System.arraycopy(samples.height(), 0, natural.values(), 0, SPAN * SPAN);
DemGrid raw = new DemGrid(natural.originX(), natural.originZ(), CELL, SPAN, SPAN);
System.arraycopy(natural.values(), 0, raw.values(), 0, SPAN * SPAN);
BitSet inland = BasinExtractor.inland(natural, samples.ocean(), settings.seaLevel());
List<Pond> lakes = regionLakes(plans.values());
BurnedTrunks trunks = BurnedTrunks.burn(raw, majorReaches(key, plans), settings.majorTier().inset(), settings.drainage().fillEpsilon());
BurnedTrunks trunks = BurnedTrunks.burn(raw, majorReaches(key, plans), settings.majorTier().inset(), settings.drainage().fillEpsilon(),
inland);
BitSet seeds = seeds(samples.ocean(), trunks);
DemGrid preliminary = new DemGrid(raw.originX(), raw.originZ(), CELL, SPAN, SPAN);
System.arraycopy(raw.values(), 0, preliminary.values(), 0, SPAN * SPAN);
Drainage initial = drain(preliminary, seeds, samples, trunks, lakes);
DrainContext context = new DrainContext(samples, trunks, inland);
Drainage initial = drain(preliminary, seeds, context, lakes);
BitSet channelHint = (BitSet) initial.channels().clone();
channelHint.andNot(trunks.cells());
CupSet cups = ponds.subtractCups(raw, key, samples, channelHint);
@@ -102,12 +107,14 @@ public final class WindowPlanner {
drainage = initial;
} else {
trunks.descend(raw.values());
drainage = drain(raw, seeds, samples, trunks, lakes);
drainage = drain(raw, seeds, context, lakes);
}
List<Pond> water = new ArrayList<>(ponds.ponds(raw, drainage.filled(), drainage.basins(), lakes, fine, cups));
List<Basin> basins = new ArrayList<>(drainage.basins());
basins.addAll(BasinExtractor.hollows(natural, inland, drainage.filled(), settings.seaLevel(), basins.size()));
List<Pond> water = new ArrayList<>(ponds.ponds(raw, drainage.filled(), basins, lakes, fine, cups));
water.addAll(lakes);
ShapedNetwork network = PondChannelSettlement.settle(key, shaper.shape(key, drainage.surface(), drainage.receivers(),
drainage.accumulation(), drainage.channels(), water, fine, settings.seed()), settings.seaLevel());
drainage.accumulation(), drainage.channels(), samples.ocean(), water, fine, settings.seed()), settings.seaLevel());
long passes = settlementPasses(water);
for (long pass = 1; lowered(water, network.ponds()); pass++) {
if (pass >= passes) {
@@ -115,7 +122,7 @@ public final class WindowPlanner {
}
water = replanned(settled(raw, cups, water, network.ponds()));
network = PondChannelSettlement.settle(key, shaper.shape(key, drainage.surface(), drainage.receivers(),
drainage.accumulation(), drainage.channels(), water, fine, settings.seed()), settings.seaLevel());
drainage.accumulation(), drainage.channels(), samples.ocean(), water, fine, settings.seed()), settings.seaLevel());
}
List<Reach> reaches = network.reaches();
List<Pond> windowPonds = windowPonds(network.ponds());
@@ -174,13 +181,16 @@ public final class WindowPlanner {
return seeds;
}
private Drainage drain(DemGrid raw, BitSet seeds, HydrologySampleBuffer samples, BurnedTrunks trunks, List<Pond> lakes) {
private Drainage drain(DemGrid raw, BitSet seeds, DrainContext context, List<Pond> lakes) {
HydrologySampleBuffer samples = context.samples();
BurnedTrunks trunks = context.trunks();
float epsilon = settings.drainage().fillEpsilon();
float[] filled = PriorityFlood.fill(raw, seeds, epsilon);
BitSet sinks = (BitSet) seeds.clone();
float[] filled = PriorityFlood.fill(raw, sinks, epsilon);
List<Basin> basins = BasinExtractor.basins(raw, filled, BASIN_DEPTH, settings.seaLevel());
for (int pass = 0; pass < BREACH_PASSES && breach(raw, filled, basins, lakes); pass++) {
for (int pass = 0; pass < BREACH_PASSES && breach(raw, filled, basins, lakes, context.inland(), sinks); pass++) {
trunks.descend(raw.values());
filled = PriorityFlood.fill(raw, seeds, epsilon);
filled = PriorityFlood.fill(raw, sinks, epsilon);
basins = BasinExtractor.basins(raw, filled, BASIN_DEPTH, settings.seaLevel());
}
DemGrid surface = new DemGrid(raw.originX(), raw.originZ(), CELL, SPAN, SPAN);
@@ -197,21 +207,36 @@ public final class WindowPlanner {
trunks.inject(weights);
float[] accumulation = FlowAccumulator.accumulate(receivers, filled, weights, settings.drainage().saturationCatchment());
trunks.pin(accumulation);
BitSet channels = channels(surface, receivers, accumulation, samples, trunks);
BitSet channels = channels(surface, receivers, accumulation, context);
return new Drainage(filled, basins, surface, receivers, accumulation, channels);
}
private boolean breach(DemGrid raw, float[] filled, List<Basin> basins, List<Pond> lakes) {
private boolean breach(DemGrid raw, float[] filled, List<Basin> basins, List<Pond> lakes, BitSet inland, BitSet sinks) {
boolean breached = false;
for (Basin basin : basins) {
if (oversized(basin) && !underLake(raw, basin, lakes)) {
Breacher.breach(raw, filled, basin);
BitSet hollow = hollow(raw, basin, inland);
if (hollow.isEmpty()) {
Breacher.breach(raw, filled, basin);
} else {
sinks.or(hollow);
}
breached = true;
}
}
return breached;
}
private static BitSet hollow(DemGrid raw, Basin basin, BitSet inland) {
BitSet hollow = new BitSet(raw.values().length);
for (int cell : basin.cells()) {
if (inland.get(cell) && !hollow.get(cell)) {
hollow.or(BasinExtractor.hollow(raw, inland, cell));
}
}
return hollow;
}
private boolean oversized(Basin basin) {
return basin.maxDepth() > settings.drainage().breachDepth()
|| (long) basin.cells().length * CELL * CELL > settings.ponds().natural().maxArea();
@@ -228,11 +253,35 @@ public final class WindowPlanner {
return false;
}
private BitSet channels(DemGrid surface, int[] receivers, float[] accumulation, HydrologySampleBuffer samples, BurnedTrunks trunks) {
private BitSet channels(DemGrid surface, int[] receivers, float[] accumulation, DrainContext context) {
HydrologySampleBuffer samples = context.samples();
BitSet candidates = ChannelHeads.candidates(surface, accumulation, samples.permission(), settings.tiers().get(0).minCatchment(),
settings.seaLevel());
return ChannelHeads.keep(surface, samples.height(), receivers, candidates, settings.drainage().headRelief(), trunks::contains,
cell -> keepHead(surface, cell, samples.rainfall()[cell]));
BitSet channels = ChannelHeads.keep(surface, samples.height(), receivers, candidates, settings.drainage().headRelief(),
context.trunks()::contains, cell -> keepHead(surface, cell, samples.rainfall()[cell]));
reachTheSea(channels, surface.values(), receivers, context);
return channels;
}
private void reachTheSea(BitSet channels, float[] filled, int[] receivers, DrainContext context) {
BitSet ends = new BitSet(receivers.length);
for (int cell = channels.nextSetBit(0); cell >= 0; cell = channels.nextSetBit(cell + 1)) {
int receiver = receivers[cell];
if (receiver >= 0 && !channels.get(receiver) && crossable(filled, context, receiver)) {
ends.set(cell);
}
}
for (int end = ends.nextSetBit(0); end >= 0; end = ends.nextSetBit(end + 1)) {
for (int cell = receivers[end]; cell >= 0 && !channels.get(cell) && crossable(filled, context, cell); cell = receivers[cell]) {
channels.set(cell);
}
}
}
private boolean crossable(float[] filled, DrainContext context, int cell) {
HydrologySampleBuffer samples = context.samples();
return !samples.ocean()[cell] && filled[cell] <= settings.seaLevel() && !context.inland().get(cell)
&& (samples.permission()[cell] & HydrologySampleBuffer.ALLOW_STREAMS) != 0;
}
private boolean keepHead(DemGrid surface, int cell, float rainfall) {
@@ -329,16 +378,21 @@ public final class WindowPlanner {
}
}
for (Reach reach : plan.reaches()) {
int mouth = reach.grade().length;
while (mouth > 0 && reach.style()[mouth - 1] == ReachStyle.MOUTH) {
mouth--;
}
if (mouth < reach.grade().length && reach.downstreamId() != 0L) {
throw offSea(plan.key(), reach, mouth, ", but its mouth drains into reach " + reach.downstreamId() + " instead of the sea");
}
for (int point = 0; point < reach.grade().length; point++) {
if (reach.grade()[point] < seaLevel) {
throw offSea(plan.key(), reach, point, ", below sea level " + seaLevel);
}
}
if (reach.downstreamId() != 0L) {
continue;
}
for (int point = reach.grade().length - 1; point >= 0 && reach.style()[point] == ReachStyle.MOUTH; point--) {
if (reach.grade()[point] != seaLevel) {
if (point < mouth && reach.style()[point] == ReachStyle.MOUTH) {
throw offSea(plan.key(), reach, point, ", but a mouth lies inside the reach, away from its sea end");
}
if (point >= mouth && reach.grade()[point] != seaLevel) {
throw offSea(plan.key(), reach, point, ", but the mouth must meet the sea at sea level " + seaLevel);
}
}
@@ -358,4 +412,7 @@ public final class WindowPlanner {
private record Drainage(float[] filled, List<Basin> basins, DemGrid surface, int[] receivers, float[] accumulation, BitSet channels) {
}
private record DrainContext(HydrologySampleBuffer samples, BurnedTrunks trunks, BitSet inland) {
}
}
@@ -106,7 +106,8 @@ public final class PondPlanner {
List<Candidate> kept = new ArrayList<>();
List<Pond> measured = new ArrayList<>();
for (Candidate candidate : candidates) {
Pond pond = measure(raw, fine, cups, candidate, Integer.MAX_VALUE);
Pond pond = candidate.basin().belowSea() ? enclosed(measure(raw, fine, cups, candidate, settings.seaLevel()))
: measure(raw, fine, cups, candidate, Integer.MAX_VALUE);
if (pond != null && !overlapsAny(pond, accepted) && !touchesLake(pond, regionLakes)) {
accepted.add(pond);
kept.add(candidate);
@@ -216,7 +217,7 @@ public final class PondPlanner {
private Candidate candidate(DemGrid raw, Basin basin, CupSet cups, HeightLattice fine) {
PondKind kind = cups.kind(raw, basin);
if (!qualifies(raw, basin, kind)) {
if (!basin.belowSea() && !qualifies(raw, basin, kind)) {
return null;
}
int floorX = raw.blockX(basin.floorIndex());
@@ -225,7 +226,7 @@ public final class PondPlanner {
if ((floor.permission()[0] & HydrologySampleBuffer.ALLOW_PONDS) == 0) {
return null;
}
if (kind == PondKind.NATURAL && CellHash.unit(CellHash.mix(settings.seed(), SALT_KEEP, floorX, floorZ))
if (kind == PondKind.NATURAL && !basin.belowSea() && CellHash.unit(CellHash.mix(settings.seed(), SALT_KEEP, floorX, floorZ))
>= Math.clamp(settings.ponds().natural().keep() * floor.pondDensity()[0], 0f, 1f) * settings.density()) {
return null;
}
@@ -410,6 +411,11 @@ public final class PondPlanner {
mask, 0L, damRaise, site.fluid(), site.floorX(), site.floorZ());
}
private static Pond enclosed(Pond pond) {
return pond == null ? null : new Pond(pond.id(), pond.kind(), pond.level(), pond.floor(), pond.floorX(), pond.floorZ(), pond.level(),
pond.mask(), pond.outletReachId(), pond.damRaise(), pond.fluid(), pond.floorX(), pond.floorZ());
}
private static boolean covered(DemGrid raw, Basin basin, List<Pond> lakes) {
int x = raw.blockX(basin.floorIndex());
int z = raw.blockZ(basin.floorIndex());
@@ -36,7 +36,6 @@ final class ReachDraft {
this.zs = fitted.zs();
this.catchments = fitted.catchment();
this.ocean = fitted.ocean();
this.ocean[xs.length - 1] |= chain.end() == ReachTracer.End.OCEAN;
this.target = new int[xs.length];
for (int point = 0; point < xs.length; point++) {
target[point] = (int) Math.floor(fitted.ground()[point]) - tier.inset();
@@ -25,7 +25,7 @@ final class ReachFitter {
this.ponds = ponds;
}
Fitted fit(DemGrid grid, int[] cells, float[] cellCatchment, HydrologyTier tier, long shapeSeed) {
Fitted fit(DemGrid grid, int[] cells, float[] cellCatchment, HydrologyTier tier, long shapeSeed, boolean drainsToTheSea) {
float halfWidth = tier.halfWidth(cellCatchment[cellCatchment.length - 1]);
Line line = resample(grid, cells, cellCatchment);
meander(line, shapeSeed);
@@ -33,6 +33,7 @@ final class ReachFitter {
Tangents tangents = tangents(line.xs(), line.zs());
Reads reads = read(line, tangents, reach);
Fitted fitted = place(line, tangents, reads, viterbi(reads, line.xs().length, reach), tier);
seaEnd(fitted.ocean(), drainsToTheSea);
lowestNearbyGround(fitted);
return fitted;
}
@@ -155,15 +156,28 @@ final class ReachFitter {
fine.fill(nodeX, nodeZ, samples);
for (int point = 0; point < points; point++) {
float lowest = Float.POSITIVE_INFINITY;
float lowestLand = Float.POSITIVE_INFINITY;
for (int node = offsets[point]; node < offsets[point + 1]; node++) {
int pond = ponds.at(nodeX[node] * step, nodeZ[node] * step);
float height = pond < 0 ? samples.height()[node] : Math.max(samples.height()[node], ponds.pond(pond).level());
lowest = Math.min(lowest, height);
if (!samples.ocean()[node]) {
lowestLand = Math.min(lowestLand, height);
}
}
fitted.ground()[point] = lowest;
fitted.ground()[point] = fitted.ocean()[point] || lowestLand == Float.POSITIVE_INFINITY ? lowest : lowestLand;
}
}
private static void seaEnd(boolean[] ocean, boolean drainsToTheSea) {
int start = ocean.length - 1;
ocean[start] = drainsToTheSea;
while (drainsToTheSea && start > 0 && ocean[start - 1]) {
start--;
}
Arrays.fill(ocean, 0, start, false);
}
private static int[] viterbi(Reads reads, int count, int reach) {
int span = reads.span();
float[] cost = new float[count * span];
@@ -35,9 +35,9 @@ public final class ReachShaper {
this.deltas = new DeltaPlanner(settings);
}
public ShapedNetwork shape(WindowKey window, DemGrid filled, int[] receivers, float[] accumulation, BitSet channels, List<Pond> ponds,
HeightLattice fine, long seed) {
requireNetwork(filled, receivers, accumulation, channels);
public ShapedNetwork shape(WindowKey window, DemGrid filled, int[] receivers, float[] accumulation, BitSet channels, boolean[] ocean,
List<Pond> ponds, HeightLattice fine, long seed) {
requireNetwork(filled, receivers, accumulation, channels, ocean);
PondLookup lookup = new PondLookup(ponds);
int[] pondAt = lookup.cells(filled);
int[] outletCells = outletCells(filled, receivers, accumulation, channels, lookup, pondAt);
@@ -47,7 +47,7 @@ public final class ReachShaper {
outlets.set(cell);
}
}
List<ReachTracer.Chain> chains = ReachTracer.trace(filled, receivers, channels, pondAt, outlets, settings.seaLevel());
List<ReachTracer.Chain> chains = ReachTracer.trace(filled, receivers, channels, ocean, pondAt, outlets);
ReachFitter fitter = new ReachFitter(Objects.requireNonNull(fine, "fine"), lookup);
List<ReachDraft> drafts = new ArrayList<>(chains.size());
for (ReachTracer.Chain chain : chains) {
@@ -98,9 +98,9 @@ public final class ReachShaper {
return new ShapedNetwork(reaches, linked);
}
public List<Reach> coarsePaths(DemGrid filled, int[] receivers, float[] accumulation, BitSet channels, long seed) {
requireNetwork(filled, receivers, accumulation, channels);
List<ReachTracer.Chain> chains = ReachTracer.trace(filled, receivers, channels, null, new BitSet(), settings.seaLevel());
public List<Reach> coarsePaths(DemGrid filled, int[] receivers, float[] accumulation, BitSet channels, boolean[] ocean, long seed) {
requireNetwork(filled, receivers, accumulation, channels, ocean);
List<ReachTracer.Chain> chains = ReachTracer.trace(filled, receivers, channels, ocean, null, new BitSet());
int[] downstream = ReachTracer.downstream(chains);
long[] ids = new long[chains.size()];
for (int index = 0; index < ids.length; index++) {
@@ -143,7 +143,7 @@ public final class ReachShaper {
float catchment = cellCatchment[cellCatchment.length - 1];
HydrologyTier tier = settings.tierFor(catchment);
long shapeSeed = CellHash.mix(seed, SALT_SHAPE, grid.blockX(chain.start()), grid.blockZ(chain.start()));
ReachFitter.Fitted fitted = fitter.fit(grid, chain.cells(), cellCatchment, tier, shapeSeed);
ReachFitter.Fitted fitted = fitter.fit(grid, chain.cells(), cellCatchment, tier, shapeSeed, chain.end() == ReachTracer.End.OCEAN);
int endLevel = chain.end() == ReachTracer.End.POND ? ponds.pond(chain.pond()).level() : Integer.MIN_VALUE;
return new ReachDraft(chain, id(seed, SALT_START, SALT_END, grid, chain), tier, catchment, endLevel, fitted);
}
@@ -649,11 +649,11 @@ public final class ReachShaper {
return CellHash.mix(start, endSalt, grid.blockX(chain.last()), grid.blockZ(chain.last()));
}
private static void requireNetwork(DemGrid grid, int[] receivers, float[] accumulation, BitSet channels) {
private static void requireNetwork(DemGrid grid, int[] receivers, float[] accumulation, BitSet channels, boolean[] ocean) {
int count = grid.width() * grid.depth();
if (receivers.length != count || accumulation.length != count || channels.length() > count) {
if (receivers.length != count || accumulation.length != count || channels.length() > count || ocean.length < count) {
throw new IllegalArgumentException("Drainage network does not match the " + count + "-cell grid: receivers=" + receivers.length
+ " accumulation=" + accumulation.length + " channels=" + channels.length());
+ " accumulation=" + accumulation.length + " channels=" + channels.length() + " ocean=" + ocean.length);
}
}
@@ -13,11 +13,11 @@ final class ReachTracer {
private ReachTracer() {
}
static List<Chain> trace(DemGrid grid, int[] receivers, BitSet channels, int[] pondAt, BitSet outlets, int seaLevel) {
static List<Chain> trace(DemGrid grid, int[] receivers, BitSet channels, boolean[] ocean, int[] pondAt, BitSet outlets) {
BitSet starts = starts(grid, receivers, channels, pondAt, outlets);
List<Chain> chains = new ArrayList<>(starts.cardinality());
for (int start = starts.nextSetBit(0); start >= 0; start = starts.nextSetBit(start + 1)) {
Chain chain = walk(grid, receivers, channels, pondAt, starts, seaLevel, start);
Chain chain = walk(receivers, channels, ocean, pondAt, starts, start);
if (chain.cells().length >= 2) {
chains.add(chain);
}
@@ -72,7 +72,7 @@ final class ReachTracer {
return starts;
}
private static Chain walk(DemGrid grid, int[] receivers, BitSet channels, int[] pondAt, BitSet starts, int seaLevel, int start) {
private static Chain walk(int[] receivers, BitSet channels, boolean[] ocean, int[] pondAt, BitSet starts, int start) {
int[] path = new int[16];
int length = 0;
path[length++] = start;
@@ -91,7 +91,7 @@ final class ReachTracer {
return new Chain(Arrays.copyOf(path, length), End.POND, pond);
}
if (!channels.get(receiver)) {
if (grid.values()[receiver] > seaLevel) {
if (!ocean[receiver]) {
return new Chain(Arrays.copyOf(path, length), End.EDGE, -1);
}
path[length++] = receiver;
@@ -1794,8 +1794,7 @@ public class IrisComplex implements DataProvider {
return false;
}
WaterRole role = raster.role(blockX & 15, blockZ & 15);
return role.wet() && role != WaterRole.MOUTH && role != WaterRole.INLET && seamWeight(blockX, blockZ) != 0D
&& raster.waterHead(blockX & 15, blockZ & 15) > transitionFluidHeight(x, z, fluidHeight);
return role.wet() && role != WaterRole.MOUTH && role != WaterRole.INLET && seamWeight(blockX, blockZ) != 0D;
}
private IrisBiome hydrologyShoreBiome(double terrainHeight, double x, double z) {
@@ -2,15 +2,19 @@ package art.arcane.iris.generation.hydrology.grid;
import org.junit.Test;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BasinExtractorTest {
private static final float FLOOR = 10f;
private static final float RIM = 30f;
private static final float RIM_MIN = 24f;
private static final float SEA = 40f;
@Test
public void bowlYieldsOneBasinWithSpillAndDepth() {
@@ -50,6 +54,45 @@ public class BasinExtractorTest {
assertTrue(BasinExtractor.basins(grid, filled, RIM_MIN - FLOOR + 1f, 0f).isEmpty());
}
@Test
public void inlandHollowsAreBelowTheSeaAndRingedByLand() {
DemGrid natural = new DemGrid(0, 0, 8, 17, 17);
Arrays.fill(natural.values(), 60f);
boolean[] ocean = new boolean[natural.values().length];
for (int j = 6; j <= 8; j++) {
for (int i = 6; i <= 8; i++) {
natural.set(i, j, i == 7 && j == 7 ? 20f : 30f);
}
}
natural.set(0, 12, 30f);
natural.set(1, 12, 30f);
natural.set(12, 12, 30f);
natural.set(13, 12, 10f);
ocean[natural.index(13, 12)] = true;
natural.set(12, 2, SEA + 0.4f);
BitSet inland = BasinExtractor.inland(natural, ocean, (int) SEA);
assertEquals("only the ringed hollow is inland " + inland, 9, inland.cardinality());
assertTrue(inland.get(natural.index(7, 7)));
assertFalse("a lowland open to the window edge is not inland", inland.get(natural.index(1, 12)));
assertFalse("a lowland beside the sea is not inland", inland.get(natural.index(12, 12)));
assertFalse("ground that rounds to the sea surface is not below it", inland.get(natural.index(12, 2)));
assertEquals(inland, BasinExtractor.hollow(natural, inland, natural.index(6, 8)));
assertTrue(BasinExtractor.hollow(natural, inland, natural.index(3, 3)).isEmpty());
float[] filled = natural.values().clone();
List<Basin> hollows = BasinExtractor.hollows(natural, inland, filled, (int) SEA, 5);
assertEquals(1, hollows.size());
Basin hollow = hollows.get(0);
assertTrue(hollow.belowSea());
assertEquals(5, hollow.id());
assertEquals(natural.index(7, 7), hollow.floorIndex());
assertEquals(SEA, hollow.spillHeight(), 0f);
assertEquals(SEA - 20f, hollow.maxDepth(), 0f);
assertEquals(9, hollow.cells().length);
filled[natural.index(6, 6)] = SEA + 1f;
assertTrue("a hollow that still fills above the sea is an ordinary basin",
BasinExtractor.hollows(natural, inland, filled, (int) SEA, 0).isEmpty());
}
private static DemGrid bowl() {
DemGrid grid = new DemGrid(0, 0, 8, 17, 17);
for (int j = 0; j < 17; j++) {
@@ -8,6 +8,7 @@ import art.arcane.iris.generation.hydrology.water.ReachStyle;
import org.junit.Test;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import static org.junit.Assert.assertEquals;
@@ -17,6 +18,8 @@ public class BurnedTrunksTest {
private static final int CELL = 8;
private static final int SIZE = 32;
private static final int TRENCH_ROW = 10;
private static final int HOLLOW_FROM = 8;
private static final int HOLLOW_TO = 12;
@Test
public void reachRoutedBackOverItsFeederKeepsTheFeederLinked() {
@@ -28,7 +31,7 @@ public class BurnedTrunksTest {
HydrologyTier major = HydrologySettings.compile(new IrisHydrology(), 1337L, 40, -64, 320).majorTier();
Reach feeder = reach(1L, 2L, major, 2, 20);
Reach backtrack = reach(2L, 0L, major, 20, 12);
BurnedTrunks trunks = BurnedTrunks.burn(raw, List.of(feeder, backtrack), 3f, 0.001f);
BurnedTrunks trunks = BurnedTrunks.burn(raw, List.of(feeder, backtrack), 3f, 0.001f, new BitSet());
int[] receivers = new int[SIZE * SIZE];
Arrays.fill(receivers, -1);
trunks.route(receivers);
@@ -44,6 +47,38 @@ public class BurnedTrunksTest {
assertEquals(-1, receivers[end]);
}
@Test
public void trunkNeitherDescendsNorDrainsThroughAnInlandHollow() {
DemGrid raw = new DemGrid(0, 0, CELL, SIZE, SIZE);
Arrays.fill(raw.values(), 200f);
BitSet hollow = new BitSet(SIZE * SIZE);
for (int i = 0; i < SIZE; i++) {
boolean inside = i >= HOLLOW_FROM && i <= HOLLOW_TO;
raw.set(i, TRENCH_ROW, inside ? 10f : 100f);
if (inside) {
hollow.set(raw.index(i, TRENCH_ROW));
}
}
HydrologyTier major = HydrologySettings.compile(new IrisHydrology(), 1337L, 40, -64, 320).majorTier();
BurnedTrunks trunks = BurnedTrunks.burn(raw, List.of(reach(1L, 0L, major, 2, 24)), 3f, 0.001f, hollow);
int[] receivers = new int[SIZE * SIZE];
Arrays.fill(receivers, -1);
trunks.route(receivers);
for (int i = 2; i < HOLLOW_FROM; i++) {
assertEquals("the trunk above the hollow drains into it at " + i, raw.index(i + 1, TRENCH_ROW), receivers[raw.index(i, TRENCH_ROW)]);
}
for (int i = HOLLOW_FROM; i <= HOLLOW_TO; i++) {
assertEquals("the hollow keeps its own drainage at " + i, -1, receivers[raw.index(i, TRENCH_ROW)]);
}
for (int i = HOLLOW_TO + 1; i <= 24; i++) {
float height = raw.values()[raw.index(i, TRENCH_ROW)];
assertTrue("the trunk beyond the hollow keeps its burned height at " + i + ": " + height, height > 90f);
if (i < 24) {
assertEquals("the trunk beyond the hollow drains on at " + i, raw.index(i + 1, TRENCH_ROW), receivers[raw.index(i, TRENCH_ROW)]);
}
}
}
private static Reach reach(long id, long downstreamId, HydrologyTier tier, int fromI, int toI) {
float[] xs = {fromI * CELL, toI * CELL};
float[] zs = {TRENCH_ROW * CELL, TRENCH_ROW * CELL};
@@ -92,6 +92,10 @@ final class PlannedScene {
}
static HydrologySettings packSettings(long seed) {
return HydrologySettings.compile(packConfig(), seed, SyntheticTerrain.SEA_LEVEL, SyntheticTerrain.MIN_Y, SyntheticTerrain.MAX_Y);
}
static IrisHydrology packConfig() {
IrisHydrology config = new IrisHydrology();
config.setTiers(new KList<>(
new IrisHydrologyTier().setName("stream").setMinCatchment(900D).setHalfWidth(new KList<>(0.5D, 2.5D)).setWidthFactor(1.2D)
@@ -104,7 +108,7 @@ final class PlannedScene {
config.getPonds().setClimateDrawdown(3);
config.getPonds().getSeeded().setDensity(10D).setRadius(new KList<>(6, 22)).setMaxSlope(0.7D).setChannelSpacing(new KList<>(80, 192));
config.getPonds().getShore().setRoundness(0.5D).setShelf(6).setTaper(14).setMaxDepth(8);
return HydrologySettings.compile(config, seed, SyntheticTerrain.SEA_LEVEL, SyntheticTerrain.MIN_Y, SyntheticTerrain.MAX_Y);
return config;
}
HydrologySettings settings() {
@@ -21,32 +21,38 @@ final class SyntheticTerrain implements HydrologyTerrainSource {
private final DoubleBinaryOperator natural;
private final DoubleBinaryOperator rainfall;
private final Area streamsBlocked;
private final Area land;
private final AtomicLong baseSamples;
private final AtomicLong naturalSamples;
private SyntheticTerrain(DoubleBinaryOperator natural) {
this(natural, (x, z) -> 1D, (x, z) -> false);
this(natural, (x, z) -> 1D, (x, z) -> false, (x, z) -> false);
}
private SyntheticTerrain(DoubleBinaryOperator natural, DoubleBinaryOperator rainfall, Area streamsBlocked) {
private SyntheticTerrain(DoubleBinaryOperator natural, DoubleBinaryOperator rainfall, Area streamsBlocked, Area land) {
this.natural = natural;
this.rainfall = rainfall;
this.streamsBlocked = streamsBlocked;
this.land = land;
this.baseSamples = new AtomicLong();
this.naturalSamples = new AtomicLong();
}
SyntheticTerrain withRainfall(DoubleBinaryOperator rainfall) {
return new SyntheticTerrain(natural, rainfall, streamsBlocked);
return new SyntheticTerrain(natural, rainfall, streamsBlocked, land);
}
SyntheticTerrain withStreamsBlocked(Area area) {
return new SyntheticTerrain(natural, rainfall, area);
return new SyntheticTerrain(natural, rainfall, area, land);
}
SyntheticTerrain withLand(Area area) {
return new SyntheticTerrain(natural, rainfall, streamsBlocked, area);
}
SyntheticTerrain lowered(double depth) {
DoubleBinaryOperator inner = natural;
return new SyntheticTerrain((x, z) -> inner.applyAsDouble(x, z) - depth, rainfall, streamsBlocked);
return new SyntheticTerrain((x, z) -> inner.applyAsDouble(x, z) - depth, rainfall, streamsBlocked, land);
}
SyntheticTerrain withPit(double centreX, double centreZ, double radius, double depth) {
@@ -55,7 +61,7 @@ final class SyntheticTerrain implements HydrologyTerrainSource {
double ratio = Math.hypot(x - centreX, z - centreZ) / radius;
double height = inner.applyAsDouble(x, z);
return ratio < 1D ? height - depth * (1D - ratio * ratio) : height;
}, rainfall, streamsBlocked);
}, rainfall, streamsBlocked, land);
}
static SyntheticTerrain valleyLake() {
@@ -261,8 +267,15 @@ final class SyntheticTerrain implements HydrologyTerrainSource {
}
static SyntheticTerrain seaStrip(double stripMinX, double stripWidth) {
return new SyntheticTerrain((x, z) -> x >= stripMinX && x < stripMinX + stripWidth ? SEA_LEVEL - 2D
: 100D - 0.03D * x + 0.05D * Math.abs(z - 512D));
return new SyntheticTerrain((x, z) -> x >= stripMinX && x < stripMinX + stripWidth ? SEA_LEVEL - 2D : valleySlope(x, z));
}
static SyntheticTerrain valleySlope() {
return new SyntheticTerrain(SyntheticTerrain::valleySlope);
}
private static double valleySlope(double x, double z) {
return 100D - 0.03D * x + 0.05D * Math.abs(z - 512D);
}
static SyntheticTerrain openFractal(long seed) {
@@ -303,7 +316,7 @@ final class SyntheticTerrain implements HydrologyTerrainSource {
for (int index = 0; index < xs.length; index++) {
float value = (float) (baseOnly ? base(xs[index], zs[index]) : natural(xs[index], zs[index]));
out.height()[index] = value;
out.ocean()[index] = value <= SEA_LEVEL;
out.ocean()[index] = value <= SEA_LEVEL && !land.contains(xs[index], zs[index]);
out.rainfall()[index] = (float) rainfall.applyAsDouble(xs[index], zs[index]);
out.pondDensity()[index] = 1f;
out.permission()[index] = streamsBlocked.contains(xs[index], zs[index]) ? HydrologySampleBuffer.ALLOW_PONDS : ALLOW_ALL;
@@ -1,6 +1,7 @@
package art.arcane.iris.generation.hydrology.plan;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier;
import art.arcane.iris.generation.hydrology.grid.HeightLattice;
import art.arcane.iris.generation.hydrology.raster.WaterHeads;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
@@ -31,7 +32,9 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -49,6 +52,22 @@ public class WindowPlannerTest {
private static final int SEAM_DISTANCE = 256;
private static final double COAST_DROP = 20D;
private static final double CLIFF_COAST_X = 300D;
private static final double HOLLOW_X = 600D;
private static final double HOLLOW_Z = 512D;
private static final double HOLLOW_RADIUS = 100D;
private static final double HOLLOW_DEPTH = 64D;
private static final double PIT_X = 900D;
private static final double PIT_Z = 512D;
private static final double PIT_RADIUS = 50D;
private static final double PIT_DEPTH = 30D;
private static final int DEEP_CUT = 12;
private static final int SLIVER_REACH = 32;
private static final int RIM_CUT = 24;
private static final double CRATER_X = 512D;
private static final double CRATER_Z = 512D;
private static final int CRATER_SPILL = 75;
private static final double CRATER_RIM = 120D;
private static final long DELTA_SEED = 5L;
@Test
public void zeroDensityRemovesLocalChannelsAndPonds() {
@@ -80,14 +99,14 @@ public class WindowPlannerTest {
ReachShaper shaper = mock(ReachShaper.class);
AtomicInteger passes = new AtomicInteger();
doAnswer(call -> {
List<Pond> water = call.getArgument(5);
List<Pond> water = call.getArgument(6);
Pond pond = single(water);
passes.incrementAndGet();
int head = pond.level() > 96 ? 96 : 94;
Reach outlet = new Reach(20L, settings.tiers().get(0), 0L, new float[]{64f, 64f}, new float[]{32f, 96f},
new int[]{head, head}, new float[]{2f, 2f}, new float[]{2f, 2f}, new ReachStyle[]{ReachStyle.RUN, ReachStyle.RUN}, 1000f);
return new ShapedNetwork(List.of(outlet), List.of(pond.withOutletReachId(outlet.id())));
}).when(shaper).shape(any(), any(), any(), any(), any(), any(), any(), anyLong());
}).when(shaper).shape(any(), any(), any(), any(), any(), any(), any(), any(), anyLong());
WindowPlanner planner = new WindowPlanner(settings,
new HeightLattice(terrain, WindowPlanner.FINE_CELL, false, 1 << 18), ponds, shaper);
@@ -577,7 +596,7 @@ public class WindowPlannerTest {
private static WindowPlanner loweringWatched(HydrologySettings settings, SyntheticTerrain terrain, Set<Long> lowered) {
ReachShaper shaper = spy(new ReachShaper(settings));
doAnswer(call -> {
List<Pond> planned = call.getArgument(5);
List<Pond> planned = call.getArgument(6);
ShapedNetwork network = (ShapedNetwork) call.callRealMethod();
Map<Long, Integer> levels = new HashMap<>();
for (Pond pond : planned) {
@@ -590,7 +609,7 @@ public class WindowPlannerTest {
}
}
return network;
}).when(shaper).shape(any(), any(), any(), any(), any(), any(), any(), anyLong());
}).when(shaper).shape(any(), any(), any(), any(), any(), any(), any(), any(), anyLong());
return new WindowPlanner(settings,
new HeightLattice(terrain, WindowPlanner.FINE_CELL, false, 1 << 21), new PondPlanner(settings), shaper);
}
@@ -854,6 +873,70 @@ public class WindowPlannerTest {
return false;
}
@Test
public void coastalDeltasBelongToOneWindowAndPersist() {
IrisHydrology config = PlannedScene.packConfig();
for (IrisHydrologyTier tier : config.getTiers()) {
tier.getDelta().setChannels(2);
}
HydrologySettings settings = HydrologySettings.compile(config, SEED, SEA_LEVEL, SyntheticTerrain.MIN_Y, SyntheticTerrain.MAX_Y);
SyntheticTerrain coast = SyntheticTerrain.boxedFractal(DELTA_SEED, LAND.wx() * WindowKey.SIZE - 2D, LAND.wz() * WindowKey.SIZE - 2D,
2 * WindowKey.SIZE);
Map<WindowKey, WindowComputation> fanned = coastalWindows(settings, coast);
Set<Long> plain = new HashSet<>();
for (WindowComputation computation : coastalWindows(PlannedScene.packSettings(SEED), coast).values()) {
for (Reach reach : computation.allReaches()) {
plain.add(reach.id());
}
}
Map<Long, WindowKey> owners = new HashMap<>();
int shared = 0;
for (Map.Entry<WindowKey, WindowComputation> entry : fanned.entrySet()) {
WindowPlan owned = entry.getValue().owned();
for (Reach reach : owned.reaches()) {
if (plain.contains(reach.id())) {
continue;
}
assertNull("delta channel " + reach.id() + " has one owner", owners.put(reach.id(), entry.getKey()));
int last = reach.xs().length - 1;
assertEquals(reach + " belongs to the window of its sea end", entry.getKey(),
WindowKey.containing((int) Math.floor(reach.xs()[last]), (int) Math.floor(reach.zs()[last])));
assertEquals(reach + " drains to the sea", 0L, reach.downstreamId());
for (int point = 0; point < reach.grade().length; point++) {
assertEquals(reach + " point " + point, ReachStyle.MOUTH, reach.style()[point]);
assertEquals(reach + " point " + point, SEA_LEVEL, reach.grade()[point]);
}
for (Map.Entry<WindowKey, WindowComputation> other : fanned.entrySet()) {
if (other.getKey().equals(entry.getKey())) {
continue;
}
for (Reach seen : other.getValue().allReaches()) {
if (seen.id() == reach.id()) {
shared++;
assertEquals(reach + " seen from " + other.getKey(), reach, seen);
}
}
}
}
assertEquals(entry.getKey() + " plan round-trips its delta", owned,
HydrologyPlanCodec.decodeWindow(settings, HydrologyPlanCodec.encode(settings, owned)).orElseThrow());
}
assertTrue("delta channels on the bounded coast " + owners.size(), owners.size() >= 8);
assertTrue("delta channels also planned by a neighbouring window " + shared, shared >= 8);
}
private static Map<WindowKey, WindowComputation> coastalWindows(HydrologySettings settings, SyntheticTerrain terrain) {
Map<RegionKey, RegionPlan> regions = new HashMap<>();
Map<WindowKey, WindowComputation> computations = new HashMap<>();
for (int wz = LAND.wz(); wz <= LAND.wz() + 1; wz++) {
for (int wx = LAND.wx(); wx <= LAND.wx() + 1; wx++) {
WindowKey key = new WindowKey(wx, wz);
computations.put(key, planner(settings, terrain).compute(key, regionPlans(settings, terrain, key, regions)));
}
}
return computations;
}
@Test
public void planWithAMouthBelowSeaFailsClosed() {
HydrologySettings settings = settings(new IrisHydrology());
@@ -862,27 +945,134 @@ public class WindowPlannerTest {
}
@Test
public void oceanFlagsInsideAReachDoNotFailClosed() {
public void seaSliversInsideAReachLeaveNoMouthsTrenchesOrLostPonds() {
HydrologySettings settings = settings(new IrisHydrology());
PlannedScene dry = PlannedScene.plan(SyntheticTerrain.valleySlope().withPit(PIT_X, PIT_Z, PIT_RADIUS, PIT_DEPTH), settings, 2, 2);
int dryCuts = deepCuts(dry);
for (double stripX : new double[]{817D, 841D}) {
SyntheticTerrain terrain = SyntheticTerrain.seaStrip(stripX, 4D).withPit(900D, 512D, 50D, 30D);
PlannedScene scene = PlannedScene.plan(terrain, settings, 2, 2);
int inner = 0;
PlannedScene scene = PlannedScene.plan(SyntheticTerrain.seaStrip(stripX, 4D).withPit(PIT_X, PIT_Z, PIT_RADIUS, PIT_DEPTH), settings, 2, 2);
int crossing = 0;
for (Reach reach : scene.reaches()) {
int trailing = reach.grade().length;
while (trailing > 0 && reach.style()[trailing - 1] == ReachStyle.MOUTH) {
trailing--;
}
for (int point = 0; point < trailing; point++) {
inner += reach.style()[point] == ReachStyle.MOUTH && reach.grade()[point] > SEA_LEVEL ? 1 : 0;
for (int point = 0; point < reach.style().length; point++) {
assertNotEquals(reach + " point " + point + " over the sliver at x " + stripX + " is a mouth", ReachStyle.MOUTH, reach.style()[point]);
crossing += reach.xs()[point] >= stripX - 2D && reach.xs()[point] < stripX + 6D ? 1 : 0;
}
}
assertTrue("mouth points above sea inside reaches crossing the sea strip at x " + stripX + ": " + inner, inner > 0);
assertTrue("reach points crossing the sea sliver at x " + stripX + ": " + crossing, crossing > 0);
Map<Long, Pond> ponds = new HashMap<>();
for (Pond pond : scene.ponds()) {
ponds.put(pond.id(), pond);
}
int away = 0;
for (Pond pond : dry.ponds()) {
if (Math.abs(pond.floorX() - stripX) <= SLIVER_REACH) {
continue;
}
away++;
Pond kept = ponds.get(pond.id());
assertNotNull(pond + " away from the sea sliver at x " + stripX + " is kept", kept);
assertEquals(pond + " level with the sea sliver at x " + stripX, pond.level(), kept.level());
}
assertTrue("ponds away from the sea sliver at x " + stripX + ": " + away, away > 10);
int cuts = deepCuts(scene);
assertTrue("reach points cut more than " + DEEP_CUT + " below the ground with the sliver at x " + stripX + ": " + cuts + ", without it "
+ dryCuts, cuts <= dryCuts + dryCuts / 50);
}
Reach crossing = new Reach(4715L, settings.tiers().get(0), 0L, new float[]{64f, 80f, 96f}, new float[]{64f, 64f, 64f},
new int[]{SEA_LEVEL + 6, SEA_LEVEL + 4, SEA_LEVEL + 2}, new float[]{2f, 2f, 2f}, new float[]{1f, 1f, 1f},
new ReachStyle[]{ReachStyle.RUN, ReachStyle.MOUTH, ReachStyle.RUN}, 1000f);
assertEquals(List.of(crossing), plannerReturning(settings, List.of(crossing), List.of()).plan(ORIGIN, noRegions(ORIGIN)).reaches());
}
private static int deepCuts(PlannedScene scene) {
int deep = 0;
for (Reach reach : scene.reaches()) {
for (int point = 0; point < reach.grade().length; point++) {
int x = (int) Math.floor(reach.xs()[point]);
int z = (int) Math.floor(reach.zs()[point]);
if (pondAt(scene.ponds(), x, z) == null && scene.natural(x, z) - reach.grade()[point] > DEEP_CUT) {
deep++;
}
}
}
return deep;
}
@Test
public void inlandBelowSeaHollowsHoldPondsNotMouths() {
HydrologySettings settings = settings(new IrisHydrology());
SyntheticTerrain hollow = SyntheticTerrain.valleySlope().withPit(HOLLOW_X, HOLLOW_Z, HOLLOW_RADIUS, HOLLOW_DEPTH);
assertTrue("the hollow floor lies far below the sea", hollow.natural(HOLLOW_X, HOLLOW_Z) < SEA_LEVEL - 20D);
PlannedScene inland = PlannedScene.plan(hollow.withLand((x, z) -> true), settings, 2, 2);
Pond pond = pondAt(inland.ponds(), HOLLOW_X, HOLLOW_Z);
assertNotNull("a pond holds the inland hollow, ponds " + inland.ponds(), pond);
assertEquals("the inland hollow holds water at the sea surface " + pond, SEA_LEVEL, pond.level());
int inflows = 0;
for (Reach reach : inland.reaches()) {
for (int point = 0; point < reach.style().length; point++) {
assertNotEquals(reach + " point " + point + " is a sea mouth inland", ReachStyle.MOUTH, reach.style()[point]);
}
int last = reach.xs().length - 1;
if (pond.mask().contains((int) Math.floor(reach.xs()[last]), (int) Math.floor(reach.zs()[last]))) {
inflows++;
assertEquals(reach + " ends in the hollow pond", 0L, reach.downstreamId());
assertTrue(reach + " meets the hollow pond at or above its level", reach.grade()[last] >= pond.level());
}
}
assertTrue("streams draining into the hollow end in its pond: " + inflows, inflows > 0);
assertEquals("the inland hollow pond has no outlet", 0L, pond.outletReachId());
assertEquals("the hollow centre is pond water", WaterRole.POND, inland.role((int) HOLLOW_X, (int) HOLLOW_Z));
assertEquals("the hollow pond surface", SEA_LEVEL, inland.head((int) HOLLOW_X, (int) HOLLOW_Z));
for (int z = inland.minZ() + WaterInvariants.EDGE_MARGIN; z <= inland.maxZ() - WaterInvariants.EDGE_MARGIN; z++) {
for (int x = inland.minX() + WaterInvariants.EDGE_MARGIN; x <= inland.maxX() - WaterInvariants.EDGE_MARGIN; x++) {
assertNotEquals("no sea mouth water inland at " + x + "," + z, WaterRole.MOUTH, inland.role(x, z));
}
}
PlannedScene sea = PlannedScene.plan(hollow, settings, 2, 2);
assertNull("the same hollow with sea intent is the sea, not a pond", pondAt(sea.ponds(), HOLLOW_X, HOLLOW_Z));
int mouths = 0;
for (Reach reach : sea.reaches()) {
int last = reach.xs().length - 1;
if (reach.style()[last] == ReachStyle.MOUTH && Math.hypot(reach.xs()[last] - HOLLOW_X, reach.zs()[last] - HOLLOW_Z) < HOLLOW_RADIUS) {
mouths++;
}
}
assertTrue("streams entering the sea-intent hollow keep their mouths: " + mouths, mouths > 0);
}
@Test
public void deepInlandHollowsKeepTheirRim() {
HydrologySettings settings = settings(new IrisHydrology());
SyntheticTerrain crater = SyntheticTerrain.crater(CRATER_X, CRATER_Z, CRATER_SPILL, CRATER_RIM)
.withLand((x, z) -> Math.hypot(x - CRATER_X, z - CRATER_Z) < CRATER_RIM + 50D);
double floor = crater.natural(CRATER_X, CRATER_Z);
assertTrue("the crater floor lies below the sea and deeper than the breach depth under its spill " + floor,
floor < SEA_LEVEL && CRATER_SPILL - floor > settings.drainage().breachDepth());
PlannedScene scene = PlannedScene.plan(crater, settings, 2, 2);
Pond pond = pondAt(scene.ponds(), CRATER_X, CRATER_Z);
assertNotNull("a pond holds the crater floor, ponds " + scene.ponds(), pond);
assertEquals(pond.toString(), SEA_LEVEL, pond.level());
assertEquals("the crater pond has no outlet " + pond, 0L, pond.outletReachId());
int rim = 0;
for (Reach reach : scene.reaches()) {
for (int point = 0; point < reach.grade().length; point++) {
double distance = Math.hypot(reach.xs()[point] - CRATER_X, reach.zs()[point] - CRATER_Z);
if (distance < 0.5D * CRATER_RIM || distance > CRATER_RIM + 100D) {
continue;
}
rim++;
double ground = crater.natural(reach.xs()[point], reach.zs()[point]);
assertNotEquals(reach + " point " + point + " is a sea mouth in the crater", ReachStyle.MOUTH, reach.style()[point]);
assertTrue(reach + " point " + point + " cuts through the crater rim, graded " + reach.grade()[point] + " under ground " + ground,
ground - reach.grade()[point] <= RIM_CUT);
}
}
assertTrue("reach points on the crater walls " + rim, rim > 100);
}
private static Pond pondAt(List<Pond> ponds, double x, double z) {
for (Pond pond : ponds) {
if (pond.mask().contains((int) Math.floor(x), (int) Math.floor(z))) {
return pond;
}
}
return null;
}
@Test
@@ -891,6 +1081,14 @@ public class WindowPlannerTest {
HydrologyTier stream = settings.tiers().get(0);
assertFailsClosed(settings, List.of(coastal(4712L, stream, SEA_LEVEL + 1, ReachStyle.MOUTH)), List.of(), "reach 4712");
assertFailsClosed(settings, List.of(coastal(4713L, stream, SEA_LEVEL - 1, ReachStyle.RUN)), List.of(), "reach 4713");
Reach crossing = new Reach(4715L, stream, 0L, new float[]{64f, 80f, 96f}, new float[]{64f, 64f, 64f},
new int[]{SEA_LEVEL + 6, SEA_LEVEL + 4, SEA_LEVEL + 2}, new float[]{2f, 2f, 2f}, new float[]{1f, 1f, 1f},
new ReachStyle[]{ReachStyle.RUN, ReachStyle.MOUTH, ReachStyle.RUN}, 1000f);
assertFailsClosed(settings, List.of(crossing), List.of(), "reach 4715");
Reach linked = new Reach(4716L, stream, 4717L, new float[]{64f, 80f, 96f}, new float[]{64f, 64f, 64f},
new int[]{SEA_LEVEL + 2, SEA_LEVEL, SEA_LEVEL}, new float[]{2f, 2f, 2f}, new float[]{1f, 1f, 1f},
new ReachStyle[]{ReachStyle.RUN, ReachStyle.MOUTH, ReachStyle.MOUTH}, 1000f);
assertFailsClosed(settings, List.of(linked), List.of(), "reach 4716");
int width = 9;
long[] bits = new long[(width * width + 63) >>> 6];
for (int cell = 0; cell < width * width; cell++) {
@@ -919,7 +1117,7 @@ public class WindowPlannerTest {
doReturn(CupSet.EMPTY).when(ponds).subtractCups(any(), any(), any(), any());
doReturn(water).when(ponds).ponds(any(), any(), any(), any(), any(), any());
ReachShaper shaper = mock(ReachShaper.class);
doReturn(new ShapedNetwork(reaches, water)).when(shaper).shape(any(), any(), any(), any(), any(), any(), any(), anyLong());
doReturn(new ShapedNetwork(reaches, water)).when(shaper).shape(any(), any(), any(), any(), any(), any(), any(), any(), anyLong());
return new WindowPlanner(settings, new HeightLattice(SyntheticTerrain.flat(100D), WindowPlanner.FINE_CELL, false, 1 << 18), ponds, shaper);
}
@@ -51,6 +51,7 @@ public class ReachShaperTest {
private static final int WINDOW_MIN_X = 140;
private static final int WINDOW_MAX_X = 250;
private static final int OUTLET_POND_LEVEL = SEA_LEVEL + 3;
private static final double SLIVER_X = 134D;
private static final byte ALLOW_ALL = HydrologySampleBuffer.ALLOW_STREAMS | HydrologySampleBuffer.ALLOW_PONDS;
@Test
@@ -293,7 +294,7 @@ public class ReachShaperTest {
quadrupled[cell] *= 4f;
}
ShapedNetwork wider = new ReachShaper(settings).shape(WINDOW, network.grid(), network.receivers(), quadrupled, network.channels(),
network.ponds(), network.fine(), SEED);
sea(network.grid()), network.ponds(), network.fine(), SEED);
Map<Long, Reach> widerById = byId(wider.reaches());
Map<Long, Integer> incoming = incoming(shaped.reaches());
int compared = 0;
@@ -401,7 +402,7 @@ public class ReachShaperTest {
Pond pond = new Pond(31L, PondKind.NATURAL, 99, 94, 104, 64, 100f, disk(96, 64, 5), 0L, 0, "water", 96, 64);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> Math.hypot(x - 96D, z - 64D) <= 5D ? 94D
: x <= 104D ? 100D : 100D - 0.5D * (x - 104D)), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, List.of(pond), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), List.of(pond), fine, SEED);
Pond shapedPond = shaped.ponds().get(0);
assertEquals(99, shapedPond.level());
assertOutletLeavesAtThePondLevel("lip outlet", shapedPond, byId(shaped.reaches()).get(shapedPond.outletReachId()));
@@ -433,7 +434,7 @@ public class ReachShaperTest {
PondPlanner planner = new PondPlanner(settings);
ReachShaper shaper = new ReachShaper(settings);
List<Pond> water = List.of(new Pond(41L, PondKind.NATURAL, 99, 93, 104, 64, 100f, disk(96, 64, 5), 0L, 0, "water", 96, 64));
ShapedNetwork network = PondChannelSettlement.settle(WINDOW, shaper.shape(WINDOW, flat, receivers, accumulation, channels, water, fine, SEED), SEA_LEVEL);
ShapedNetwork network = PondChannelSettlement.settle(WINDOW, shaper.shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), water, fine, SEED), SEA_LEVEL);
int lowerings = 0;
while (network.ponds().get(0).level() < water.get(0).level()) {
lowerings++;
@@ -441,7 +442,7 @@ public class ReachShaperTest {
Pond reflooded = planner.reflood(flat, fine, CupSet.EMPTY, network.ponds().get(0));
assertNotNull("reflooded pond at " + network.ponds().get(0).level(), reflooded);
water = List.of(reflooded.withOutletReachId(0L));
network = PondChannelSettlement.settle(WINDOW, shaper.shape(WINDOW, flat, receivers, accumulation, channels, water, fine, SEED), SEA_LEVEL);
network = PondChannelSettlement.settle(WINDOW, shaper.shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), water, fine, SEED), SEA_LEVEL);
}
Pond settled = network.ponds().get(0);
Map<Long, Reach> byId = byId(network.reaches());
@@ -478,7 +479,7 @@ public class ReachShaperTest {
assertFalse("no DEM node inside the pond", mask.contains(32, 40) || mask.contains(32, 48));
Pond pond = new Pond(51L, PondKind.NATURAL, 99, 94, 32, 34, 100f, mask, 0L, 0, "water", 32, 43);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> 100D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, List.of(pond), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), List.of(pond), fine, SEED);
Pond shapedPond = shaped.ponds().get(0);
Reach outlet = byId(shaped.reaches()).get(shapedPond.outletReachId());
assertNotNull(outlet);
@@ -507,7 +508,7 @@ public class ReachShaperTest {
PondMask shore = rectangle(72, 52, 18, 3);
Pond pond = new Pond(81L, PondKind.NATURAL, 99, 94, 72, 64, 100f, shore, 0L, 0, "water", 104, 56);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> shore.contains((int) x, (int) z) ? 94D : 100D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, List.of(pond), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), List.of(pond), fine, SEED);
Reach outlet = byId(shaped.reaches()).get(shaped.ponds().get(0).outletReachId());
assertNotNull("the pond drains through an outlet along its shore", outlet);
float farthestHeld = 0f;
@@ -538,7 +539,7 @@ public class ReachShaperTest {
Pond side = new Pond(62L, PondKind.NATURAL, 99, 94, 104, 60, 100f, disk(104, 56, 3), 0L, 0, "water", 104, 56);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> fed.mask().contains((int) x, (int) z)
|| side.mask().contains((int) x, (int) z) ? 94D : 100D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, List.of(fed, side), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), List.of(fed, side), fine, SEED);
assertEquals("both ponds drain through the same exit", shaped.ponds().get(0).outletReachId(), shaped.ponds().get(1).outletReachId());
Reach outlet = byId(shaped.reaches()).get(shaped.ponds().get(1).outletReachId());
assertNotNull(outlet);
@@ -566,7 +567,7 @@ public class ReachShaperTest {
surface.set(19, 1, 30f);
Pond pond = new Pond(71L, PondKind.NATURAL, 59, 54, 136, 8, 60f, disk(128, 8, 7), 0L, 0, "water", 128, 8);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> x < 138D ? 60D : 35D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, List.of(pond), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, sea(surface), List.of(pond), fine, SEED);
Pond shapedPond = shaped.ponds().get(0);
Reach outlet = byId(shaped.reaches()).get(shapedPond.outletReachId());
assertNotNull(outlet);
@@ -582,6 +583,39 @@ public class ReachShaperTest {
assertTrue("ocean points " + mouths, mouths > 1);
}
@Test
public void inlandPondOutletOverASeaSliverHoldsThePondLevel() {
HydrologySettings settings = settings(config -> {
});
int width = 24;
DemGrid surface = new DemGrid(0, 0, CELL, width, 3);
Arrays.fill(surface.values(), 60f);
int[] receivers = new int[width * 3];
Arrays.fill(receivers, -1);
float[] accumulation = new float[width * 3];
BitSet channels = new BitSet(width * 3);
for (int i = 0; i < 19; i++) {
flow(surface, receivers, accumulation, channels, i, 1, i + 1, 1, 1600f + 10f * i);
}
Pond pond = new Pond(73L, PondKind.NATURAL, 59, 54, 136, 8, 60f, disk(128, 8, 7), 0L, 0, "water", 128, 8);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> x >= SLIVER_X && x < SLIVER_X + 8D ? 35D : 60D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, sea(surface), List.of(pond), fine,
SEED);
Pond shapedPond = shaped.ponds().get(0);
Reach outlet = byId(shaped.reaches()).get(shapedPond.outletReachId());
assertNotNull(outlet);
assertEquals("the inland pond keeps its level", 59, shapedPond.level());
assertTrue("the outlet leads in from the pond", shapedPond.mask().contains(Math.round(outlet.xs()[0]), Math.round(outlet.zs()[0])));
assertTrue("the outlet starts over the sea sliver", outlet.xs()[1] >= SLIVER_X && outlet.xs()[1] < SLIVER_X + 8D);
assertEquals("the lead-in holds the pond level", shapedPond.level(), outlet.grade()[0]);
assertEquals("the lip holds the pond level", shapedPond.level(), outlet.grade()[1]);
for (int point = 0; point < outlet.grade().length; point++) {
assertNotEquals("outlet point " + point + " at " + outlet.xs()[point] + " is a mouth", ReachStyle.MOUTH, outlet.style()[point]);
assertTrue("outlet point " + point + " at " + outlet.xs()[point] + " drops to the sea surface, graded " + outlet.grade()[point],
outlet.grade()[point] > SEA_LEVEL + 10);
}
}
@Test
public void gorgeCutWhenRidgeMissedByGrid() {
HydrologySettings settings = settings(config -> {
@@ -825,7 +859,7 @@ public class ReachShaperTest {
accumulation[flat.index(12, 10)] = 300f;
Pond pond = new Pond(21L, PondKind.NATURAL, 101, 98, 0, 0, 102f, rectangle(80, 48, 9, 9), 0L, 0, "water", 96, 64);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> 100D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, List.of(pond), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), List.of(pond), fine, SEED);
Reach outlet = byId(shaped.reaches()).get(shaped.ponds().get(0).outletReachId());
assertNotNull(outlet);
assertTrue(pond.mask().contains(Math.round(outlet.xs()[0]), Math.round(outlet.zs()[0])));
@@ -854,7 +888,7 @@ public class ReachShaperTest {
}
surface.set(width - 1, 1, 30f);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> 45D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, List.of(), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, sea(surface), List.of(), fine, SEED);
int mouths = 0;
for (Reach reach : shaped.reaches()) {
int last = reach.xs().length - 1;
@@ -891,7 +925,7 @@ public class ReachShaperTest {
Pond sunken = new Pond(77L, PondKind.NATURAL, SEA_LEVEL - 1, SEA_LEVEL - 6, CELL, CELL, SEA_LEVEL + 0.5f,
new PondMask(0, CELL, CELL, 2, 1, new long[]{0b11L}), 0L, 0, "water", 0, CELL);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> 45D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, List.of(sunken), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, sea(surface), List.of(sunken), fine, SEED);
int mouths = 0;
for (Reach reach : shaped.reaches()) {
for (int grade : reach.grade()) {
@@ -1126,23 +1160,42 @@ public class ReachShaperTest {
}
@Test
public void oceanPointsHoldSeaLevel() {
public void seaSliverInsideAReachIsNeitherAMouthNorItsBed() {
HydrologySettings settings = settings(config -> {
});
int inletX = 204;
DoubleBinaryOperator terrain = (x, z) -> 60D - 0.05D * x + 0.1D * Math.abs(z - VALLEY_Z)
- (Math.abs(x - inletX) <= 2D && Math.abs(z - VALLEY_Z) <= 20D ? 10.3D : 0D);
ShapedNetwork shaped = shape(settings, network(settings, terrain, 64, 64, VALLEY_THRESHOLD, false));
int overInlet = 0;
int crossing = 0;
int below = 0;
int mouths = 0;
for (Reach reach : shaped.reaches()) {
int sea = reach.xs().length;
while (sea > 0 && reach.style()[sea - 1] == ReachStyle.MOUTH) {
sea--;
}
for (int index = 0; index < reach.xs().length; index++) {
if (reach.style()[index] == ReachStyle.MOUTH) {
assertEquals(reach + " at " + index, SEA_LEVEL, reach.grade()[index]);
overInlet += Math.abs(reach.xs()[index] - inletX) <= 2f ? 1 : 0;
float x = reach.xs()[index];
if (index >= sea) {
mouths++;
assertEquals(reach + " mouth point " + index, SEA_LEVEL, reach.grade()[index]);
assertTrue(reach + " mouth point " + index + " at " + x + " lies at the sea",
terrain.applyAsDouble(x, reach.zs()[index]) < SEA_LEVEL + 8D);
continue;
}
assertNotEquals(reach + " point " + index + " at " + x + " is a mouth inside the reach", ReachStyle.MOUTH, reach.style()[index]);
crossing += Math.abs(x - inletX) <= 2f ? 1 : 0;
if (x >= inletX + 16f && x <= inletX + 96f) {
below++;
assertTrue(reach + " point " + index + " at " + x + " keeps to the valley below the sliver, graded " + reach.grade()[index],
reach.grade()[index] >= Math.floor(terrain.applyAsDouble(x, reach.zs()[index])) - reach.tier().inset() - 2);
}
}
}
assertTrue("mouth points over the inlet " + overInlet, overInlet > 0);
assertTrue("points crossing the sea sliver " + crossing, crossing > 0);
assertTrue("points below the sea sliver " + below, below > 0);
assertTrue("mouth points where the valley meets the sea " + mouths, mouths > 0);
}
@Test
@@ -1181,7 +1234,7 @@ public class ReachShaperTest {
Pond fed = new Pond(32L, PondKind.NATURAL, 100 + maxFill + 4, 98, 192, 128, 100 + maxFill + 5f, rectangle(160, 112, 9, 9), 0L, 0,
"water", 176, 128);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> 100D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, List.of(looped, fed), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), List.of(looped, fed), fine, SEED);
int inflows = 0;
for (Reach reach : shaped.reaches()) {
if (reach.downstreamId() == 0L && endsIn(reach, fed)) {
@@ -1253,7 +1306,7 @@ public class ReachShaperTest {
channels.set(cell);
}
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> 100D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, List.of(), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), List.of(), fine, SEED);
Map<Long, Reach> byId = byId(shaped.reaches());
int links = 0;
for (Reach reach : shaped.reaches()) {
@@ -1365,7 +1418,7 @@ public class ReachShaperTest {
flow(flat, receivers, accumulation, channels, i, 8, i + 1 < flat.width() ? i + 1 : -1, 8, 6400f);
}
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> 100D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, List.of(), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), List.of(), fine, SEED);
Map<Long, List<Reach>> feeders = feeders(shaped.reaches());
assertEquals("one confluence " + feeders.keySet(), 1, feeders.size());
Map.Entry<Long, List<Reach>> confluence = feeders.entrySet().iterator().next();
@@ -1416,7 +1469,7 @@ public class ReachShaperTest {
Pond pond = new Pond(71L, PondKind.NATURAL, 99, 94, 104, 64, 100f, disk(96, 64, 5), 0L, 0, "water", 96, 64);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> Math.hypot(x - 96D, z - 64D) <= 5D ? 94D
: x <= 104D ? 100D : 100D - 0.5D * (x - 104D)), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, List.of(pond), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, flat, receivers, accumulation, channels, sea(flat), List.of(pond), fine, SEED);
Reach outlet = byId(shaped.reaches()).get(shaped.ponds().get(0).outletReachId());
assertNotNull("the pond drains through an outlet", outlet);
assertEquals("the outlet is a river", "river", outlet.tier().name());
@@ -1532,7 +1585,8 @@ public class ReachShaperTest {
BitSet candidates = ChannelHeads.candidates(network.grid(), network.accumulation(), allowed, minCatchment, SEA_LEVEL);
BitSet channels = ChannelHeads.keep(network.grid(), network.grid().values(), network.receivers(), candidates,
settings.drainage().headRelief(), index -> false, index -> true);
List<Reach> paths = new ReachShaper(settings).coarsePaths(network.grid(), network.receivers(), network.accumulation(), channels, SEED);
List<Reach> paths = new ReachShaper(settings).coarsePaths(network.grid(), network.receivers(), network.accumulation(), channels,
sea(network.grid()), SEED);
assertFalse(paths.isEmpty());
Map<Long, Reach> byId = byId(paths);
int mouths = 0;
@@ -1990,7 +2044,7 @@ public class ReachShaperTest {
Pond pond = new Pond(73L, kind, OUTLET_POND_LEVEL, OUTLET_POND_LEVEL - 4, 136, 8, OUTLET_POND_LEVEL + 0.5f, disk(128, 8, 7), 0L, 0,
"water", 128, 8);
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> x < 160D ? SEA_LEVEL + 4D : SEA_LEVEL - 5D), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, List.of(pond), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, sea(surface), List.of(pond), fine, SEED);
Pond shapedPond = shaped.ponds().get(0);
assertEquals(kind + " level", OUTLET_POND_LEVEL, shapedPond.level());
Reach outlet = byId(shaped.reaches()).get(shapedPond.outletReachId());
@@ -2035,7 +2089,7 @@ public class ReachShaperTest {
}
float mouthX = (width - 1) * CELL;
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> SEA_LEVEL + 1D + rise * Math.max(0D, mouthX - x)), FINE, false, 1 << 16);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, List.of(), fine, SEED);
ShapedNetwork shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, sea(surface), List.of(), fine, SEED);
assertEquals(1, shaped.reaches().size());
return shaped.reaches().get(0);
}
@@ -2247,7 +2301,15 @@ public class ReachShaperTest {
private static ShapedNetwork shape(HydrologySettings settings, Network network) {
return new ReachShaper(settings).shape(WINDOW, network.grid(), network.receivers(), network.accumulation(), network.channels(),
network.ponds(), network.fine(), SEED);
sea(network.grid()), network.ponds(), network.fine(), SEED);
}
private static boolean[] sea(DemGrid filled) {
boolean[] sea = new boolean[filled.values().length];
for (int cell = 0; cell < sea.length; cell++) {
sea[cell] = filled.values()[cell] <= SEA_LEVEL;
}
return sea;
}
private static Network network(HydrologySettings settings, DoubleBinaryOperator height, int width, int depth, float threshold,
@@ -0,0 +1,104 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
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.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.testsupport.FakeHydrology;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.stream.ProceduralStream;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class IrisComplexHydrologyTest {
private static final int SEA_LEVEL = 85;
private static final int GROUND = SEA_LEVEL + 2;
private static final int RIVER_Z = 8;
private static final int MOUTH_Z = 40;
private static final int COLUMN_X = 8;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private IrisSettings previousSettings;
@Before
public void prepareRuntime() {
previousSettings = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
IrisServices.register(PreservationRegistry.class, mock(PreservationRegistry.class));
IrisPlatform platform = mock(IrisPlatform.class);
when(platform.platformName()).thenReturn("bukkit");
IrisPlatforms.bind(platform);
}
@After
public void releaseRuntime() {
IrisPlatforms.unbind();
IrisServices.remove(PreservationRegistry.class);
IrisSettings.settings = previousSettings;
}
@Test(timeout = 120_000L)
public void seaLevelInlandRiversKeepTheLandBiome() throws Exception {
Path pack = HydrologyFixture.pack(temporaryFolder.newFolder().toPath(), null, null);
Files.writeString(pack.resolve("dimensions/main.json"), """
{"regions":["plain"],"landChance":1,"fluidHeight":%d,"carvingEnabled":false}
""".formatted(SEA_LEVEL));
Files.writeString(pack.resolve("regions/plain.json"), "{\"landBiomes\":[\"plain\"],\"seaBiomes\":[\"ocean\"]}");
Files.writeString(pack.resolve("biomes/ocean.json"), "{\"generators\":[{\"generator\":\"flat\",\"min\":10,\"max\":10}]}");
HydrologyTier stream = FakeHydrology.settings(SEA_LEVEL).tiers().get(0);
Reach river = reach(901L, stream, RIVER_Z, ReachStyle.RUN);
Reach mouth = reach(902L, stream, MOUTH_Z, ReachStyle.MOUTH);
try (HydrologyFixture fixture = new HydrologyFixture(pack);
FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> GROUND, SEA_LEVEL, List.of(river, mouth), List.of())) {
IrisComplex complex = fixture.complex(hydrology.runtime);
complex.setNaturalHeightStream(ProceduralStream.ofDouble((x, z) -> GROUND));
ChunkWaterRaster channel = hydrology.runtime.raster(0, RIVER_Z >> 4);
assertEquals("the inland river column is channel water", WaterRole.CHANNEL, channel.role(COLUMN_X, RIVER_Z & 15));
assertEquals("the inland river holds the sea surface", SEA_LEVEL, channel.waterHead(COLUMN_X, RIVER_Z & 15));
assertTrue("the inland river bed lies below the sea surface", channel.terrainHeight(COLUMN_X, RIVER_Z & 15) < SEA_LEVEL);
assertEquals("a sea-level river on land keeps the land biome", "plain",
complex.getTrueBiomeStream().get(COLUMN_X, RIVER_Z).getLoadKey());
ChunkWaterRaster sea = hydrology.runtime.raster(0, MOUTH_Z >> 4);
assertEquals("the mouth column is mouth water", WaterRole.MOUTH, sea.role(COLUMN_X, MOUTH_Z & 15));
assertEquals("a river mouth takes the sea biome", "ocean", complex.getTrueBiomeStream().get(COLUMN_X, MOUTH_Z).getLoadKey());
}
}
private static Reach reach(long id, HydrologyTier tier, int z, ReachStyle style) {
float[] xs = {-32f, 0f, 32f, 64f};
float[] zs = new float[xs.length];
int[] grade = new int[xs.length];
float[] halfWidth = new float[xs.length];
float[] depth = new float[xs.length];
ReachStyle[] styles = new ReachStyle[xs.length];
Arrays.fill(zs, z);
Arrays.fill(grade, SEA_LEVEL);
Arrays.fill(halfWidth, 3f);
Arrays.fill(depth, 2f);
Arrays.fill(styles, style);
return new Reach(id, tier, 0L, xs, zs, grade, halfWidth, depth, styles, 5000f);
}
}
@@ -72,7 +72,7 @@ public final class DeltaCoast {
row(surface, receivers, accumulation, channels, neighbourZ);
}
HeightLattice fine = new HeightLattice(new Terrain(ground), FINE, false, 1 << 16);
return new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, ponds, fine, seed);
return new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels, sea(surface), ponds, fine, seed);
}
public static double ground(double x, double z) {
@@ -106,6 +106,14 @@ public final class DeltaCoast {
return fan;
}
private static boolean[] sea(DemGrid filled) {
boolean[] sea = new boolean[filled.values().length];
for (int cell = 0; cell < sea.length; cell++) {
sea[cell] = filled.values()[cell] <= SEA_LEVEL;
}
return sea;
}
private static void row(DemGrid grid, int[] receivers, float[] accumulation, BitSet channels, int z) {
int j = (z - grid.originZ()) / CELL;
for (int x = 0; x < SEA_X; x += CELL) {