Task 19 WIP

- Add ReachGeometry and the shared curved brink head rule
- Use it in RasterComposer and PondChannelSettlement
- Add T8, T9 and multi-seed brink tests
- Unfinished: see task-19-report.md
This commit is contained in:
Brian Fopiano committed 2026-11-02 21:11:48 -05:00
1 parent 6c0c42cd8c
commit 6458b2331c
12 files changed
+622 -37

No files matched your search

@@ -118,7 +118,7 @@ public final class WindowPlanner {
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(), samples.ocean(), water, fine, settings.seed()), settings.seaLevel());
drainage.accumulation(), drainage.channels(), samples.ocean(), water, fine, settings.seed()), settings.seed(), settings.seaLevel());
long passes = settlementPasses(water);
for (long pass = 1; lowered(water, network.ponds()); pass++) {
if (pass >= passes) {
@@ -126,7 +126,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(), samples.ocean(), water, fine, settings.seed()), settings.seaLevel());
drainage.accumulation(), drainage.channels(), samples.ocean(), water, fine, settings.seed()), settings.seed(), settings.seaLevel());
}
List<Reach> reaches = network.reaches();
List<Pond> windowPonds = windowPonds(network.ponds());
@@ -34,12 +34,14 @@ final class ChunkFeatures {
private final int[] inletBoxes;
private final int[] lakeBoxes;
private final ReachSegments segments = new ReachSegments(SEGMENT_CAPACITY);
private final ReachGeometry.Lookup brinks;
private final MaskEdges pondShores = new MaskEdges(MaskEdges.Kind.WATER);
private final MaskEdges pondBanks = new MaskEdges(MaskEdges.Kind.BANK);
private final MaskEdges lakeReach = new MaskEdges(MaskEdges.Kind.GROWN_WATER);
private boolean inert;
private ChunkFeatures(List<Reach> reaches, List<Pond> ponds, List<Pond> lakes, List<SeaInlet> inlets, int[] inletBoxes) {
private ChunkFeatures(HydrologySettings settings, List<Reach> reaches, List<Pond> ponds, List<Pond> lakes, List<SeaInlet> inlets, int[] inletBoxes) {
this.brinks = new ReachGeometry.Lookup(settings.seed(), settings.seaLevel());
this.reaches = reaches;
this.ponds = ponds;
this.lakes = lakes;
@@ -73,7 +75,7 @@ final class ChunkFeatures {
}
}
List<Pond> lakes = lakes(chunkX, chunkZ, halo, lakeRegionPlans, lakeRegions);
ChunkFeatures features = new ChunkFeatures(reaches, ponds, lakes, inlets, inletBoxes);
ChunkFeatures features = new ChunkFeatures(settings, reaches, ponds, lakes, inlets, inletBoxes);
features.index(settings, chunkX, chunkZ);
return features;
}
@@ -96,6 +98,10 @@ final class ChunkFeatures {
return null;
}
ReachGeometry.Lookup brinks() {
return brinks;
}
ReachSegments segments() {
return segments;
}
@@ -17,12 +17,12 @@ public final class PondChannelSettlement {
private PondChannelSettlement() {
}
public static ShapedNetwork settle(WindowKey window, ShapedNetwork network, int seaLevel) {
public static ShapedNetwork settle(WindowKey window, ShapedNetwork network, long seed, int seaLevel) {
int[] initial = new int[network.ponds().size()];
for (int index = 0; index < initial.length; index++) {
initial[index] = network.ponds().get(index).level();
}
int[] levels = levels(window, network.reaches(), network.ponds(), initial, seaLevel);
int[] levels = levels(window, network.reaches(), network.ponds(), initial, seed, seaLevel);
List<Pond> water = new ArrayList<>(initial.length);
for (int index = 0; index < initial.length; index++) {
Pond pond = network.ponds().get(index);
@@ -32,7 +32,7 @@ public final class PondChannelSettlement {
return new ShapedNetwork(network.reaches(), water);
}
static int[] levels(WindowKey window, List<Reach> reaches, List<Pond> ponds, int[] initial, int seaLevel) {
static int[] levels(WindowKey window, List<Reach> reaches, List<Pond> ponds, int[] initial, long seed, int seaLevel) {
int[] levels = initial.clone();
if (reaches.isEmpty() || ponds.isEmpty()) {
return levels;
@@ -45,6 +45,7 @@ public final class PondChannelSettlement {
return levels;
}
ReachIndex index = ReachIndex.build(window, reaches, List.of());
ReachGeometry.Lookup brinks = new ReachGeometry.Lookup(seed, seaLevel);
List<Reach> nearby = new ArrayList<>();
List<Pond> unused = new ArrayList<>();
for (int pond = 0; pond < ponds.size(); pond++) {
@@ -60,18 +61,18 @@ public final class PondChannelSettlement {
nearby.clear();
index.candidates(chunkX, chunkZ, halo, nearby, unused);
if (!nearby.isEmpty()) {
levels[pond] = lower(nearby, water.mask(), bounds, levels[pond], seaLevel);
levels[pond] = lower(nearby, water.mask(), bounds, levels[pond], brinks, seaLevel);
}
}
return levels;
}
private static int lower(List<Reach> reaches, PondMask mask, Bounds bounds, int level, int seaLevel) {
private static int lower(List<Reach> reaches, PondMask mask, Bounds bounds, int level, ReachGeometry.Lookup brinks, int seaLevel) {
ReachSegments segments = new ReachSegments(64);
for (Reach reach : reaches) {
segments.addNear(reach, bounds.minX() - 1, bounds.minZ() - 1, bounds.maxX() + 1, bounds.maxZ() + 1, 0f);
}
ReachCursor cursor = new ReachCursor();
ReachCursor cursor = new ReachCursor(brinks);
int width = bounds.maxX() - bounds.minX() + 1;
BitSet visited = new BitSet(width * (bounds.maxZ() - bounds.minZ() + 1));
for (Reach reach : reaches) {
@@ -91,12 +92,12 @@ public final class PondChannelSettlement {
continue;
}
visited.set(cell);
level = Math.min(level, touchingHead(segments, cursor, x, z, seaLevel, level));
level = Math.min(level, touchingHead(segments, cursor, brinks, x, z, seaLevel, level));
for (int[] side : SIDES) {
int nx = x + side[0];
int nz = z + side[1];
if (!mask.contains(nx, nz)) {
level = Math.min(level, touchingHead(segments, cursor, nx, nz, seaLevel, level));
level = Math.min(level, touchingHead(segments, cursor, brinks, nx, nz, seaLevel, level));
}
}
}
@@ -106,13 +107,13 @@ public final class PondChannelSettlement {
return level;
}
private static int touchingHead(ReachSegments segments, ReachCursor cursor, int x, int z, int seaLevel, int level) {
private static int touchingHead(ReachSegments segments, ReachCursor cursor, ReachGeometry.Lookup brinks, int x, int z, int seaLevel, int level) {
segments.nearest(x, z, ReachSegments.Scope.CHANNEL, cursor);
ReachCursor.Choice channel = cursor.channel;
if (channel.reach == null) {
return level;
}
int head = WaterHeads.snap(channel.reach.grade()[channel.point()], seaLevel);
int head = brinks.head(channel);
return head < WaterHeads.snap(level, seaLevel) ? head : level;
}
@@ -42,7 +42,8 @@ final class RasterComposer {
private final double[] distance = new double[CELLS];
private final long[] nearFeature = new long[CELLS];
private final HydrologyTier[] nearTier = new HydrologyTier[CELLS];
private final ReachCursor cursor = new ReachCursor();
private final ReachGeometry.Lookup brinks;
private final ReachCursor cursor;
private final int[] inletColumn = new int[2];
private final Map<Long, String> reachFluids = new HashMap<>();
private NaturalHeights naturalHeight;
@@ -51,6 +52,8 @@ final class RasterComposer {
this.settings = settings;
this.features = features;
this.channelFluids = channelFluids;
this.brinks = features.brinks();
this.cursor = new ReachCursor(brinks);
this.originX = chunkX * CHUNK - 1;
this.originZ = chunkZ * CHUNK - 1;
Arrays.fill(head, Integer.MIN_VALUE);
@@ -133,15 +136,15 @@ final class RasterComposer {
if (hit.reach == null) {
return floor;
}
int ownerHead = WaterHeads.snap(hit.grade(), settings.seaLevel());
int ownerHead = brinks.head(hit);
return Math.min(floor, deepestBed(ownerHead, Math.min(level, ownerHead), ground, variation, detail));
}
private void channel(int cell, int x, int z, int ground, double variation) {
ReachCursor.Choice hit = cursor.channel;
Reach reach = hit.reach;
int point = hit.point();
head[cell] = WaterHeads.snap(reach.grade()[point], settings.seaLevel());
int point = brinks.point(hit);
head[cell] = brinks.head(hit);
terrain[cell] = deepestBed(head[cell], head[cell], ground, variation, BedProfile.detail(settings.seed(), x, z));
role[cell] = role(reach.style()[point]);
feature[cell] = reach.id();
@@ -158,7 +161,7 @@ final class RasterComposer {
int deepest = Integer.MAX_VALUE;
for (int entry = 0; entry < waters.size(); entry++) {
ReachCursor.Choice water = waters.get(entry);
if (WaterHeads.snap(water.grade(), settings.seaLevel()) == ownerHead) {
if (brinks.head(water) == ownerHead) {
deepest = Math.min(deepest, bed(water, surface, ground, variation, detail));
}
}
@@ -179,7 +182,7 @@ final class RasterComposer {
ReachCursor.Choice bank = cursor.bank;
if (bank.reach != null) {
HydrologyTier bankTier = bank.reach.tier();
int surface = WaterHeads.snap(bank.reach.grade()[bank.point()], settings.seaLevel());
int surface = brinks.head(bank);
bankEdge = bank.distance - bank.halfWidth();
double u = bankEdge / bankTier.bankBand();
if (bankTier.bankStyle() != IrisBankStyle.CLIFF && bankTier.bankStyle() != IrisBankStyle.TERRACED) {
@@ -349,7 +352,7 @@ final class RasterComposer {
features.segments().nearest(x, z, ReachSegments.Scope.CHANNEL, cursor);
ReachCursor.Choice hit = cursor.channel;
if (hit.reach != null) {
sample.set(WaterHeads.snap(hit.grade(), settings.seaLevel()), hit.reach.id(), role(hit.reach.style()[hit.point()]));
sample.set(brinks.head(hit), hit.reach.id(), role(hit.reach.style()[brinks.point(hit)]));
}
}
@@ -10,6 +10,19 @@ final class ReachCursor {
final Choice nearest = new Choice();
final Choice edge = new Choice();
final Waters waters = new Waters();
private final ReachGeometry.Lookup brinks;
ReachCursor() {
this(null);
}
ReachCursor(ReachGeometry.Lookup brinks) {
this.brinks = brinks;
}
void resolveChannel() {
waters.resolve(channel, brinks);
}
void reset() {
channel.reset();
@@ -118,23 +131,23 @@ final class ReachCursor {
entries[size++].set(reach, segment, index, t, distance);
}
void resolve(Choice channel) {
private void resolve(Choice channel, ReachGeometry.Lookup brinks) {
channel.reset();
if (size == 0) {
return;
}
Choice owner = entries[0];
for (int entry = 1; entry < size; entry++) {
if (owns(entries[entry], owner)) {
if (owns(entries[entry], owner, brinks)) {
owner = entries[entry];
}
}
channel.set(owner.reach, owner.segment, owner.index, owner.t, owner.distance);
}
private static boolean owns(Choice candidate, Choice held) {
int candidateGrade = candidate.grade();
int heldGrade = held.grade();
private static boolean owns(Choice candidate, Choice held, ReachGeometry.Lookup brinks) {
int candidateGrade = brinks == null ? candidate.grade() : candidate.reach.grade()[brinks.point(candidate)];
int heldGrade = brinks == null ? held.grade() : held.reach.grade()[brinks.point(held)];
if (candidateGrade != heldGrade) {
return candidateGrade < heldGrade;
}
@@ -0,0 +1,187 @@
package art.arcane.iris.generation.hydrology.raster;
import art.arcane.iris.generation.hydrology.grid.CellHash;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachShaper;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.Map;
final class ReachGeometry {
static final int BRINK_MIN_DROP = 4;
static final double BRINK_CURVE_MIN = 0.25D;
static final double BRINK_CURVE_MAX = 0.6D;
static final double BRINK_MIN_SHIFT = 1D;
static final double BRINK_MAX_SHIFT = 11D;
static final double EDGE_MARGIN = 1D;
private static final long SALT_BRINK = 0x4252494e4bL;
private static final ReachGeometry STRAIGHT = new ReachGeometry(new double[0], new int[0], new double[0], new double[0], new double[0]);
private final double[] along;
private final int[] segments;
private final double[] middles;
private final double[] shifts;
private final double[] starts;
private ReachGeometry(double[] along, int[] segments, double[] middles, double[] shifts, double[] starts) {
this.along = along;
this.segments = segments;
this.middles = middles;
this.shifts = shifts;
this.starts = starts;
}
static ReachGeometry of(Reach reach, long seed, int seaLevel) {
int[] grade = reach.grade();
int[] steps = new int[grade.length - 1];
int count = 0;
boolean falls = false;
for (int segment = 0; segment + 1 < grade.length; segment++) {
if (WaterHeads.snap(grade[segment], seaLevel) != WaterHeads.snap(grade[segment + 1], seaLevel)) {
steps[count++] = segment;
falls |= grade[segment] - grade[segment + 1] >= BRINK_MIN_DROP;
}
}
if (!falls) {
return STRAIGHT;
}
double[] along = along(reach);
double end = along[along.length - 1];
double held = protectedEnd(reach, along);
double mouth = firstMouth(reach, along);
int[] segments = new int[count];
double[] middles = new double[count];
double[] shifts = new double[count];
double[] starts = new double[count];
int curves = 0;
int start = WaterHeads.snap(grade[0], seaLevel);
boolean outlet = reach.style()[0] == ReachStyle.POND_OUTLET;
boolean feeder = reach.downstreamId() != 0L;
int landing = WaterHeads.snap(grade[grade.length - 1], seaLevel);
for (int step = 0; step < count; step++) {
int segment = steps[step];
double middle = middle(along, segment);
int upper = WaterHeads.snap(grade[segment], seaLevel);
int lower = WaterHeads.snap(grade[segment + 1], seaLevel);
if (grade[segment] - grade[segment + 1] < BRINK_MIN_DROP || middle <= held || outlet && upper == start || feeder && lower == landing
|| reach.style()[segment] == ReachStyle.MOUTH || reach.style()[segment + 1] == ReachStyle.MOUTH) {
continue;
}
double width = (reach.halfWidth()[segment] + reach.halfWidth()[segment + 1]) / 2D;
if (width - EDGE_MARGIN < BRINK_MIN_SHIFT) {
continue;
}
long hash = CellHash.mix(seed, SALT_BRINK, Math.round((reach.xs()[segment] + reach.xs()[segment + 1]) / 2f),
Math.round((reach.zs()[segment] + reach.zs()[segment + 1]) / 2f));
double curve = BRINK_CURVE_MIN + (BRINK_CURVE_MAX - BRINK_CURVE_MIN) * CellHash.unit(hash);
double wanted = Math.min(BRINK_MAX_SHIFT, Math.max(BRINK_MIN_SHIFT, curve * (width - EDGE_MARGIN)));
boolean tongue = (hash & 1L) == 0L;
double room = tongue
? Math.min(step + 1 < count ? (middle(along, steps[step + 1]) - middle) / 2D : end - middle, mouth - middle)
: Math.min(step > 0 ? (middle - middle(along, steps[step - 1])) / 2D : middle, middle - held);
double shift = Math.min(wanted, room);
if (shift > 0D) {
segments[curves] = segment;
middles[curves] = middle;
shifts[curves] = tongue ? shift : -shift;
starts[curves] = tongue ? middle : middle - shift;
curves++;
}
}
if (curves == 0) {
return STRAIGHT;
}
return new ReachGeometry(along, Arrays.copyOf(segments, curves), Arrays.copyOf(middles, curves), Arrays.copyOf(shifts, curves),
Arrays.copyOf(starts, curves));
}
int point(ReachCursor.Choice choice) {
int straight = choice.point();
if (segments.length == 0) {
return straight;
}
double inner = choice.halfWidth() - EDGE_MARGIN;
if (choice.distance >= inner) {
return straight;
}
double at = along[choice.segment] + choice.t * (along[choice.segment + 1] - along[choice.segment]);
int found = Arrays.binarySearch(starts, at);
int curve = found >= 0 ? found : -found - 2;
if (curve < 0 || at > starts[curve] + Math.abs(shifts[curve])) {
return straight;
}
double ratio = choice.distance / inner;
boolean below = at - shifts[curve] * (1D - ratio * ratio) >= middles[curve];
if (shifts[curve] > 0D) {
return below ? straight : segments[curve];
}
return below ? segments[curve] + 1 : straight;
}
private static double[] along(Reach reach) {
float[] xs = reach.xs();
float[] zs = reach.zs();
double[] along = new double[xs.length];
for (int point = 1; point < xs.length; point++) {
double dx = xs[point] - xs[point - 1];
double dz = zs[point] - zs[point - 1];
along[point] = along[point - 1] + Math.sqrt(dx * dx + dz * dz);
}
return along;
}
private static double middle(double[] along, int segment) {
return (along[segment] + along[segment + 1]) / 2D;
}
private static double protectedEnd(Reach reach, double[] along) {
double end = reach.style()[0] == ReachStyle.POND_OUTLET
? Math.max(ReachShaper.OUTLET_LENGTH, 2D * (reach.halfWidth()[0] + 1D))
: Double.NEGATIVE_INFINITY;
for (int point = 0; point < along.length; point++) {
if (reach.style()[point] == ReachStyle.POND_OUTLET) {
end = Math.max(end, along[point]);
}
}
return end;
}
private static double firstMouth(Reach reach, double[] along) {
for (int point = 0; point < along.length; point++) {
if (reach.style()[point] == ReachStyle.MOUTH) {
return along[point];
}
}
return Double.POSITIVE_INFINITY;
}
static final class Lookup {
private final Map<Reach, ReachGeometry> geometries = new IdentityHashMap<>();
private final long seed;
private final int seaLevel;
Lookup(long seed, int seaLevel) {
this.seed = seed;
this.seaLevel = seaLevel;
}
ReachGeometry of(Reach reach) {
ReachGeometry known = geometries.get(reach);
if (known == null) {
known = ReachGeometry.of(reach, seed, seaLevel);
geometries.put(reach, known);
}
return known;
}
int head(ReachCursor.Choice choice) {
return WaterHeads.channelHead(choice, of(choice.reach), seaLevel);
}
int point(ReachCursor.Choice choice) {
return of(choice.reach).point(choice);
}
}
}
@@ -137,7 +137,7 @@ final class ReachSegments {
first = end;
}
}
cursor.waters.resolve(cursor.channel);
cursor.resolveChannel();
}
private int coveredCell(double x, double z) {
@@ -10,6 +10,10 @@ public final class WaterHeads {
return planned - Math.floorMod(planned - seaLevel, STEP);
}
static int channelHead(ReachCursor.Choice choice, ReachGeometry geometry, int seaLevel) {
return snap(choice.reach.grade()[geometry.point(choice)], seaLevel);
}
public static int lowestAboveSea(int seaLevel) {
return seaLevel + STEP;
}
@@ -18,7 +18,7 @@ public final class ReachShaper {
private static final int SMOOTHING_PASSES = 2;
private static final float TAPER_LENGTH = 24f;
private static final float WAIST = 0.5f;
static final float OUTLET_LENGTH = 8f;
public static final float OUTLET_LENGTH = 8f;
private static final float LIP_MARGIN = 4f;
private static final int LEAD_IN_REACH = 16;
private static final float LIP_HALF_WIDTH = 1f;
@@ -53,6 +53,8 @@ public class ChunkWaterRasterTest {
private static final int MAX_Y = 320;
private static final float SPACING = 2f;
private static final int GENTLE_STEP = 3;
private static final double CELL_LATTICE_BRINK_SPREAD = 1.25D;
private static final double BRINK_SCAN = 0.02D;
@Test
public void flatLakesSkipExtraTerrainSamplingForRiffles() {
@@ -1251,6 +1253,333 @@ public class ChunkWaterRasterTest {
assertEquals(banks + "leaks", 0, scene.leaks(-20, minZ, 56, maxZ));
}
@Test
public void waterfallBrinkCurvesAcrossTheChannelAndBanksStepOnOneLine() {
HydrologyTier tier = tier("stream", 4f, 0.5f, 8, IrisBankStyle.SMOOTH);
Reach reach = line(191L, tier, 0L, -20f, 8f, 60f, 30f, (x, z) -> x < 20f ? 90 : 78);
BrinkFrame frame = new BrinkFrame(reach);
int tongues = 0;
int horseshoes = 0;
for (long seed = 1L; seed <= 24L; seed++) {
String label = "seed " + seed + ": ";
Scene scene = new Scene(seededSettings(seed), (x, z) -> frame.along(x, z) < 0D ? 92 : 80).reach(reach);
double[] positions = new double[7];
for (int offset = -3; offset <= 3; offset++) {
positions[offset + 3] = frame.rasterBrink(scene, offset);
}
for (int offset = 0; offset < 6; offset++) {
assertTrue(label + "offsets " + (offset - 3) + " and " + (offset - 2) + " step at " + positions[offset] + " and " + positions[offset + 1],
Math.abs(positions[offset] - positions[offset + 1]) <= CELL_LATTICE_BRINK_SPREAD);
}
double centre = positions[3];
double edges = (positions[0] + positions[6]) / 2D;
assertTrue(label + "centre " + centre + " against edges " + edges, Math.abs(centre - edges) >= 1D);
if (centre > edges) {
tongues++;
} else {
horseshoes++;
}
assertEquals(label + "leaks", 0, scene.leaks(-30, -10, 70, 50));
assertBanksStepOnOneLine(label, frame, new Scene(seededSettings(seed), (x, z) -> 92).reach(reach));
assertRasterFollowsTheRule(label, scene, reach, seed, -30, -10, 70, 50);
assertTheRuleCurvesSmoothly(label, frame, reach, seed);
}
assertTrue("both tongues and horseshoes across seeds: " + tongues + " and " + horseshoes, tongues >= 4 && horseshoes >= 4);
}
private static void assertTheRuleCurvesSmoothly(String label, BrinkFrame frame, Reach reach, long seed) {
double[] exact = new double[7];
for (int offset = -3; offset <= 3; offset++) {
exact[offset + 3] = frame.ruleBrink(reach, seed, offset);
}
for (int offset = 0; offset < 6; offset++) {
assertTrue(label + "the rule at " + (offset - 3) + " and " + (offset - 2) + " steps at " + exact[offset] + " and " + exact[offset + 1],
Math.abs(exact[offset] - exact[offset + 1]) <= 1D + 2D * BRINK_SCAN);
}
assertTrue(label + "rule centre " + exact[3], Math.abs(exact[3]) >= 1D - BRINK_SCAN);
assertEquals(label + "edges of the rule stay on the straight line", 0D, exact[0], BRINK_SCAN);
assertEquals(label + "edges of the rule stay on the straight line", 0D, exact[6], BRINK_SCAN);
}
private static void assertRasterFollowsTheRule(String label, Scene scene, Reach reach, long seed, int minX, int minZ, int maxX, int maxZ) {
BrinkRule rule = new BrinkRule(seed, reach);
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
if (scene.water(x, z)) {
assertEquals(label + "head at " + x + "," + z, rule.head(x, z), scene.head(x, z));
}
}
}
}
@Test
public void curvedWaterStaysBehindTheStraightLineAtTheChannelEdge() {
int curved = 0;
for (float width : new float[]{2f, 4f, 8f, 16f}) {
HydrologyTier tier = tier("river", width, 0.5f, 8, IrisBankStyle.SMOOTH);
Reach reach = line(192L, tier, 0L, -40f, 8f, 80f, 8f, (x, z) -> x < 20f ? 90 : 58);
for (int degrees : new int[]{0, 30, 60}) {
double normalX = Math.cos(Math.toRadians(degrees));
double normalZ = Math.sin(Math.toRadians(degrees));
IntBinaryOperator cliff = (x, z) -> (x - 20D) * normalX + (z - 8D) * normalZ < 0D ? 92 : 60;
for (long seed = 1L; seed <= 24L; seed++) {
String label = "seed " + seed + " width " + width + " at " + degrees + " degrees: ";
Scene scene = new Scene(seededSettings(seed), cliff).reach(reach);
BrinkRule curve = new BrinkRule(seed, reach);
int reachOut = (int) width + 4;
for (int x = 20 - 2 * reachOut; x <= 20 + 2 * reachOut; x++) {
for (int z = 8 - reachOut; z <= 8 + reachOut; z++) {
if (!scene.water(x, z)) {
continue;
}
curved += scene.head(x, z) != curve.straightHead(x, z) ? 1 : 0;
if (!scene.water(x + 1, z) || !scene.water(x - 1, z) || !scene.water(x, z + 1) || !scene.water(x, z - 1)) {
assertEquals(label + "water beside dry ground at " + x + "," + z, curve.straightHead(x, z), scene.head(x, z));
}
}
}
assertEquals(label + "leaks", 0, scene.leaks(20 - 2 * reachOut, 8 - reachOut, 20 + 2 * reachOut, 8 + reachOut));
}
}
}
assertTrue("cells on the curve: " + curved, curved > 500);
}
@Test
public void brinksStayStraightInOutletZonesAndAboveMouths() {
HydrologyTier tier = tier("river", 6f, 0.5f, 8, IrisBankStyle.SMOOTH);
Reach mouth = mouthed(line(193L, tier, 0L, -20f, 8f, 50f, 8f, (x, z) -> x < 20f ? 59 : SEA_LEVEL), 20f);
Reach zone = withStartStyle(line(194L, tier, 0L, -20f, 8f, 60f, 8f, (x, z) -> x < -14f ? 100 : 88), ReachStyle.POND_OUTLET, 4);
Reach held = withStartStyle(line(195L, tier, 0L, -20f, 8f, 60f, 8f, (x, z) -> x < 30f ? 100 : 88), ReachStyle.POND_OUTLET, 4);
for (long seed = 1L; seed <= 24L; seed++) {
for (Reach reach : List.of(mouth, zone, held)) {
String label = "seed " + seed + " reach " + reach.id() + ": ";
Scene scene = new Scene(seededSettings(seed), (x, z) -> 110).reach(reach);
BrinkRule rule = new BrinkRule(seed, reach);
for (int x = -30; x <= 70; x++) {
for (int z = -8; z <= 24; z++) {
if (scene.water(x, z)) {
assertEquals(label + "head at " + x + "," + z, rule.straightHead(x, z), scene.head(x, z));
}
}
}
}
}
}
@Test
public void aFallBelowTheOutletZoneNeverCurvesBackIntoIt() {
HydrologyTier tier = tier("river", 12f, 0.5f, 8, IrisBankStyle.SMOOTH);
Reach reach = withStartStyle(line(196L, tier, 0L, -20f, 8f, 60f, 8f, (x, z) -> x < 12f ? 100 : x < 16f ? 92 : 84), ReachStyle.POND_OUTLET, 4);
int downstream = 0;
for (long seed = 1L; seed <= 24L; seed++) {
BrinkRule rule = new BrinkRule(seed, reach);
for (double x = -20D; x < 11D; x += 0.25D) {
for (double z = -3D; z <= 19D; z += 0.25D) {
int head = rule.head(x, z);
if (head != Integer.MIN_VALUE) {
assertEquals("seed " + seed + " upstream of the first fall at " + x + "," + z, 100, head);
}
}
}
for (double x = 11.5D; x <= 60D; x += 0.25D) {
for (double z = -3D; z <= 19D; z += 0.25D) {
int head = rule.head(x, z);
if (head != rule.straightHead(x, z)) {
downstream++;
}
}
}
}
assertTrue("the second fall still curves: " + downstream, downstream > 0);
}
@Test
public void wideChannelsKeepTheirBrinkInsideTheCandidateHalo() {
HydrologyTier tier = tier("river", 40f, 0.5f, 8, IrisBankStyle.SMOOTH);
Reach reach = line(199L, tier, 0L, -60f, 8f, 100f, 8f, (x, z) -> x < 20f ? 90 : 78);
double widest = 0D;
for (long seed = 1L; seed <= 24L; seed++) {
BrinkRule rule = new BrinkRule(seed, reach);
for (double along = -14D; along <= 14D; along += BRINK_SCAN) {
if (rule.head(20D + along, 8D) != rule.straightHead(20D + along, 8D)) {
widest = Math.max(widest, Math.abs(along));
}
}
}
assertTrue("widest brink shift " + widest, widest > 8D && widest <= ReachGeometry.BRINK_MAX_SHIFT + 2D * BRINK_SCAN);
}
@Test
public void closeFallsKeepTheirOrderAcrossTheChannel() {
HydrologyTier tier = tier("river", 10f, 0.5f, 8, IrisBankStyle.SMOOTH);
for (int gap : new int[]{2, 4, 6, 10}) {
Reach reach = line(197L, tier, 0L, -20f, 8f, 60f, 8f, (x, z) -> x < 20f ? 100 : x < 20f + gap ? 92 : 84);
for (long seed = 1L; seed <= 24L; seed++) {
BrinkRule rule = new BrinkRule(seed, reach);
for (double z = -1.5D; z <= 17.5D; z += 0.5D) {
int last = Integer.MAX_VALUE;
for (double x = -20D; x <= 60D; x += 0.1D) {
int head = rule.head(x, z);
assertTrue("seed " + seed + " gap " + gap + " head rises to " + head + " from " + last + " at " + x + "," + z, head <= last);
last = head;
}
assertEquals("seed " + seed + " gap " + gap + " ends on the last level at z " + z, 84, last);
}
}
}
}
@Test
public void brinkHeadsAgreeAcrossChunkWindowAndTileLines() {
HydrologyTier tier = tier("river", 8f, 0.5f, 8, IrisBankStyle.SMOOTH);
int curved = 0;
int windowSize = WindowKey.SIZE;
for (int line : new int[]{16, 256, windowSize, -windowSize}) {
Reach reach = line(198L, tier, 0L, line - 40f, 7f, line + 40f, 9f, (x, z) -> x < line ? 90 : 70);
for (long seed = 1L; seed <= 24L; seed++) {
String label = "seed " + seed + " line " + line + ": ";
Scene scene = new Scene(seededSettings(seed), (x, z) -> 92).reach(reach);
BrinkRule rule = new BrinkRule(seed, reach);
for (int x = line - 20; x <= line + 20; x++) {
for (int z = -4; z <= 20; z++) {
if (scene.water(x, z)) {
assertEquals(label + "head at " + x + "," + z, rule.head(x, z), scene.head(x, z));
curved += scene.head(x, z) != rule.straightHead(x, z) ? 1 : 0;
}
}
}
assertWindowOrderFree(scene, Math.floorDiv(line - 16, 16), Math.floorDiv(line + 16, 16), 0);
}
}
assertTrue("curved cells " + curved, curved > 100);
}
private static Reach withStartStyle(Reach reach, ReachStyle style, int points) {
ReachStyle[] styles = reach.style().clone();
for (int point = 0; point < points; point++) {
if (styles[point] == ReachStyle.RUN) {
styles[point] = style;
}
}
return new Reach(reach.id(), reach.tier(), reach.downstreamId(), reach.xs(), reach.zs(), reach.grade(), reach.halfWidth(), reach.depth(),
styles, reach.catchment());
}
private static final class BrinkRule {
private final ReachGeometry.Lookup brinks;
private final ReachSegments segments = new ReachSegments(64);
private final ReachCursor cursor;
private final ReachCursor straight = new ReachCursor();
private BrinkRule(long seed, Reach reach) {
brinks = new ReachGeometry.Lookup(seed, SEA_LEVEL);
cursor = new ReachCursor(brinks);
segments.addAll(reach);
}
private int head(double x, double z) {
segments.nearest(x, z, ReachSegments.Scope.CHANNEL, cursor);
return cursor.channel.reach == null ? Integer.MIN_VALUE : brinks.head(cursor.channel);
}
private int straightHead(double x, double z) {
segments.nearest(x, z, ReachSegments.Scope.CHANNEL, straight);
return straight.channel.reach == null ? Integer.MIN_VALUE : WaterHeads.snap(straight.channel.grade(), SEA_LEVEL);
}
}
private static void assertBanksStepOnOneLine(String label, BrinkFrame frame, Scene scene) {
int checked = 0;
for (int x = -10; x <= 50; x++) {
for (int z = 0; z <= 40; z++) {
double lateral = Math.abs(frame.lateral(x, z));
double along = frame.along(x, z);
if (scene.water(x, z) || lateral <= 5D || lateral > 7D || Math.abs(along) > 12D) {
continue;
}
int ground = scene.terrain(x, z);
checked++;
if (along < -1D) {
assertTrue(label + "upper bank at " + x + "," + z + " is " + ground, ground >= 90);
} else if (along > 1D) {
assertTrue(label + "lower bank at " + x + "," + z + " is " + ground, ground < 90);
}
}
}
assertTrue(label + "bank cells " + checked, checked > 40);
}
private static HydrologySettings seededSettings(long seed) {
return HydrologySettings.compile(new IrisHydrology(), seed, SEA_LEVEL, MIN_Y, MAX_Y);
}
private record BrinkFrame(double originX, double originZ, double unitX, double unitZ) {
private BrinkFrame(Reach reach) {
this(stepMid(reach, reach.xs()), stepMid(reach, reach.zs()), unit(reach, true), unit(reach, false));
}
private static double stepMid(Reach reach, float[] values) {
for (int point = 0; point + 1 < values.length; point++) {
if (reach.grade()[point] != reach.grade()[point + 1]) {
return (values[point] + values[point + 1]) / 2D;
}
}
throw new IllegalArgumentException("no step on " + reach);
}
private static double unit(Reach reach, boolean x) {
int last = reach.xs().length - 1;
double dx = reach.xs()[last] - reach.xs()[0];
double dz = reach.zs()[last] - reach.zs()[0];
return (x ? dx : dz) / Math.hypot(dx, dz);
}
private double along(double x, double z) {
return (x - originX) * unitX + (z - originZ) * unitZ;
}
private double lateral(double x, double z) {
return (z - originZ) * unitX - (x - originX) * unitZ;
}
private double ruleBrink(Reach reach, long seed, int offset) {
BrinkRule rule = new BrinkRule(seed, reach);
double found = Double.NaN;
int last = Integer.MAX_VALUE;
for (double along = -6D; along <= 6D; along += BRINK_SCAN) {
double x = originX + along * unitX - offset * unitZ;
double z = originZ + along * unitZ + offset * unitX;
int head = rule.head(x, z);
if (last != Integer.MAX_VALUE && head != last) {
assertTrue("the head changes once at offset " + offset, Double.isNaN(found));
found = along;
}
last = head;
}
return found;
}
private double rasterBrink(Scene scene, int offset) {
double lastUpper = Double.NEGATIVE_INFINITY;
double firstLower = Double.POSITIVE_INFINITY;
for (int x = (int) originX - 16; x <= originX + 16; x++) {
for (int z = (int) originZ - 16; z <= originZ + 16; z++) {
if (Math.abs(lateral(x, z) - offset) > 0.5D || !scene.water(x, z)) {
continue;
}
double along = along(x, z);
if (scene.head(x, z) >= 90) {
lastUpper = Math.max(lastUpper, along);
} else {
firstLower = Math.min(firstLower, along);
}
}
}
return (lastUpper + firstLower) / 2D;
}
}
@Test
public void mouthColumnsUseTheSeaFluid() {
IntBinaryOperator coast = (x, z) -> x < 40 ? 44 : SEA_LEVEL - 10;
@@ -1,7 +1,13 @@
package art.arcane.iris.generation.hydrology.raster;
import art.arcane.iris.generation.hydrology.config.IrisBankStyle;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.plan.IndexedWindow;
import art.arcane.iris.generation.hydrology.plan.RegionKey;
import art.arcane.iris.generation.hydrology.plan.RegionPlan;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.plan.WindowPlan;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondKind;
@@ -10,15 +16,18 @@ import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PondChannelSettlementTest {
private static final WindowKey WINDOW = new WindowKey(0, 0);
private static final int SEA_LEVEL = 40;
private static final long SEED = 1337L;
@Test
public void aLowerChannelDrainsThePondWhereOnlyItsWidthOverlaps() {
@@ -91,13 +100,46 @@ public class PondChannelSettlementTest {
Reach lower = line(4L, 17, -20, 17, 20, 4f, 94, 94);
assertArrayEquals(new int[]{96, 94}, PondChannelSettlement.levels(WINDOW, List.of(across, lower), List.of(first, second),
new int[]{104, 102}, SEA_LEVEL));
new int[]{104, 102}, SEED, SEA_LEVEL));
assertArrayEquals(new int[]{94, 96}, PondChannelSettlement.levels(WINDOW, List.of(lower, across), List.of(second, first),
new int[]{102, 104}, SEA_LEVEL));
new int[]{102, 104}, SEED, SEA_LEVEL));
}
@Test
public void settlementUsesTheRasterBrinkRule() {
Reach river = line(2L, 504, 108, 504, 148, 6f, 100, 88);
int curved = 0;
for (long seed = 1L; seed <= 24L; seed++) {
HydrologySettings settings = HydrologySettings.compile(new IrisHydrology(), seed, SEA_LEVEL, -64, 320);
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
IndexedWindow window = new IndexedWindow(new WindowPlan(WINDOW, List.of(river), List.of(), List.of()), ReachIndex.build(WINDOW, List.of(river), List.of()));
for (int z = 124; z <= 132; z++) {
Pond pond = pond(1L, PondKind.NATURAL, 94, circle(504, z, 0));
int lowest = Math.min(94, Math.min(rasterHead(rasterizer, window, 504, z), Math.min(rasterHead(rasterizer, window, 505, z),
Math.min(rasterHead(rasterizer, window, 503, z), Math.min(rasterHead(rasterizer, window, 504, z + 1), rasterHead(rasterizer, window, 504, z - 1))))));
int settled = PondChannelSettlement.levels(WINDOW, List.of(river), List.of(pond), new int[]{94}, seed, SEA_LEVEL)[0];
assertEquals("seed " + seed + " pond at z " + z, lowest, settled);
boolean straightTouches = z >= 127;
curved += straightTouches != (settled < 94) ? 1 : 0;
}
}
assertTrue("ponds the curve moved on or off the lower water: " + curved, curved >= 12);
}
private static int rasterHead(ChunkRasterizer rasterizer, IndexedWindow window, int x, int z) {
int chunkX = Math.floorDiv(x, 16);
int chunkZ = Math.floorDiv(z, 16);
List<RegionPlan> regions = new ArrayList<>();
for (RegionKey key : ChunkRasterizer.lakeRegions(chunkX, chunkZ)) {
regions.add(new RegionPlan(key, List.of(), List.of()));
}
ChunkWaterRaster raster = rasterizer.rasterize(chunkX, chunkZ, (a, b) -> 110D, List.of(window), regions);
int head = raster.waterHead(Math.floorMod(x, 16), Math.floorMod(z, 16));
return head == Integer.MIN_VALUE ? Integer.MAX_VALUE : head;
}
private static int settle(List<Reach> reaches, Pond pond) {
return PondChannelSettlement.levels(WINDOW, reaches, List.of(pond), new int[]{pond.level()}, SEA_LEVEL)[0];
return PondChannelSettlement.levels(WINDOW, reaches, List.of(pond), new int[]{pond.level()}, SEED, SEA_LEVEL)[0];
}
private static Pond pond(long id, PondKind kind, int level, PondMask mask) {
@@ -692,8 +692,8 @@ public class ReachShaperTest {
}
}
assertTrue(label + " grouped below the outlet zone", lowered > 0);
List<Pond> groupedPonds = PondChannelSettlement.settle(WINDOW, grouped, SEA_LEVEL).ponds();
List<Pond> plainPonds = PondChannelSettlement.settle(WINDOW, plain, SEA_LEVEL).ponds();
List<Pond> groupedPonds = PondChannelSettlement.settle(WINDOW, grouped, SEED, SEA_LEVEL).ponds();
List<Pond> plainPonds = PondChannelSettlement.settle(WINDOW, plain, SEED, SEA_LEVEL).ponds();
assertEquals(plainPonds.size(), groupedPonds.size());
for (int pond = 0; pond < plainPonds.size(); pond++) {
assertEquals("pond " + pond, plainPonds.get(pond).level(), groupedPonds.get(pond).level());
@@ -826,7 +826,7 @@ public class ReachShaperTest {
Pond shapedPond = shaped.ponds().get(0);
assertEquals(99, shapedPond.level());
assertOutletLeavesAtThePondLevel("lip outlet", shapedPond, byId(shaped.reaches()).get(shapedPond.outletReachId()));
assertEquals(99, PondChannelSettlement.settle(WINDOW, shaped, SEA_LEVEL).ponds().get(0).level());
assertEquals(99, PondChannelSettlement.settle(WINDOW, shaped, SEED, SEA_LEVEL).ponds().get(0).level());
}
@Test
@@ -855,7 +855,7 @@ public class ReachShaperTest {
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,
SeaCells.atOrBelow(flat, SEA_LEVEL), water, fine, SEED), SEA_LEVEL);
SeaCells.atOrBelow(flat, SEA_LEVEL), water, fine, SEED), SEED, SEA_LEVEL);
int lowerings = 0;
while (network.ponds().get(0).level() < water.get(0).level()) {
lowerings++;
@@ -864,7 +864,7 @@ public class ReachShaperTest {
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,
SeaCells.atOrBelow(flat, SEA_LEVEL), water, fine, SEED), SEA_LEVEL);
SeaCells.atOrBelow(flat, SEA_LEVEL), water, fine, SEED), SEED, SEA_LEVEL);
}
Pond settled = network.ponds().get(0);
Map<Long, Reach> byId = byId(network.reaches());
@@ -913,7 +913,7 @@ public class ReachShaperTest {
assertEquals("held grade at " + point, shapedPond.level(), outlet.grade()[point]);
}
assertOutletTouchesAtThePondLevel("fallback outlet", shapedPond, outlet);
assertEquals(99, PondChannelSettlement.settle(WINDOW, shaped, SEA_LEVEL).ponds().get(0).level());
assertEquals(99, PondChannelSettlement.settle(WINDOW, shaped, SEED, SEA_LEVEL).ponds().get(0).level());
}
@Test