From 343da05e3d8ac20d59158bbb49267be8cdb39bc6 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Tue, 3 Nov 2026 23:52:18 -0500 Subject: [PATCH] Add organic sea grottos - Plan winding sea-level passages into tall coastal rock, one per site cell, owned by the mouth's window - Keep walks out of rivers, ponds, own arms, and ground other windows' arms could reach - Shape them with a warped path and a 3D radial function keyed on plan data and CellHash, with caverns, hanging rock, shelves and skylights - Rasterize own-chunk into mantle WET_SOURCE, DRY_AIR and SEAL_GUARD; guards only at or below sea level - Persist grottos in window plans, plugging cut-off wet cells at plan time - Add IrisGrottos to settings, fingerprint, schema and pack validation; recapture pins - Add /iris find river grotto, Studio map drawing, recorded mouths and an export limit - Add grottoProbe and arm lines in the tidal rivers digest --- .../art/arcane/iris/command/CommandFind.java | 2 +- .../command/CommandFindHydrologyTest.java | 2 +- .../hydrology/config/IrisGrottos.java | 45 + .../config/IrisHydrologyUnderground.java | 5 +- .../engine/HydrologyFeatureSearch.java | 9 +- .../engine/HydrologyPlanPreview.java | 8 +- .../hydrology/engine/HydrologyRuntime.java | 28 +- .../hydrology/plan/HydrologyPlanCodec.java | 77 +- .../hydrology/plan/HydrologySettings.java | 37 +- .../generation/hydrology/plan/WindowPlan.java | 8 +- .../hydrology/plan/WindowPlanner.java | 10 +- .../hydrology/query/HydrologyFeatureType.java | 3 +- .../hydrology/underground/Grotto.java | 74 ++ .../hydrology/underground/GrottoPlanner.java | 941 ++++++++++++++ .../underground/GrottoRasterizer.java | 146 +++ .../hydrology/underground/GrottoShape.java | 314 +++++ .../hydrology/underground/GrottoSpace.java | 55 + .../hydrology/water/TidalPlanner.java | 49 +- .../generation/mantle/CaveCeilingMask.java | 34 + .../mantle/MantleCarvedTerrain.java | 21 +- .../mantle/MantleHydrologyComponent.java | 47 + .../iris/pack/PackHydrologyValidator.java | 4 + .../export/compile/terrain/RiverLimits.java | 3 + .../pack/datapack/export/ir/ExportLimit.java | 1 + .../art/arcane/iris/studio/map/MapView.java | 2 +- .../iris/studio/render/IrisRenderer.java | 2 + .../arcane/iris/studio/render/WaterMap.java | 28 +- .../history/GenerationSemanticCapture.java | 11 + .../hydrology/PersistedCodesTest.java | 3 +- .../engine/HydrologyFeatureSearchTest.java | 3 + .../engine/HydrologyRuntimeTest.java | 20 +- .../hydrology/plan/GrottoPlannerTest.java | 273 ++++ .../plan/HydrologyPlanCodecTest.java | 14 +- .../hydrology/plan/HydrologySettingsTest.java | 28 +- .../underground/GrottoRasterizerTest.java | 157 +++ .../underground/GrottoShapeTest.java | 208 ++++ .../compile/terrain/RiverCompilerTest.java | 16 +- .../schema/SchemaBuilderIdentityTest.java | 2 +- .../iris/studio/render/WaterMapTest.java | 13 + probe/build.gradle | 21 + .../art/arcane/iris/probe/GrottoProbe.java | 1101 +++++++++++++++++ .../arcane/iris/probe/TidalReachProbe.java | 4 +- 42 files changed, 3791 insertions(+), 38 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisGrottos.java create mode 100644 core/src/main/java/art/arcane/iris/generation/hydrology/underground/Grotto.java create mode 100644 core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoPlanner.java create mode 100644 core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoRasterizer.java create mode 100644 core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoShape.java create mode 100644 core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoSpace.java create mode 100644 core/src/test/java/art/arcane/iris/generation/hydrology/plan/GrottoPlannerTest.java create mode 100644 core/src/test/java/art/arcane/iris/generation/hydrology/underground/GrottoRasterizerTest.java create mode 100644 core/src/test/java/art/arcane/iris/generation/hydrology/underground/GrottoShapeTest.java create mode 100644 probe/src/main/java/art/arcane/iris/probe/GrottoProbe.java diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandFind.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandFind.java index 8adfcc845..74838ebb9 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandFind.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandFind.java @@ -198,7 +198,7 @@ public class CommandFind implements DirectorExecutor { @Director(description = "Find a hydrology water feature", sync = true) public void river( - @Param(description = "Feature type: stream, river, major_river, cascade, waterfall, mouth, pond, lake, dam, sea_inlet or cave_pool", customHandler = HydrologyTypeHandler.class) + @Param(description = "Feature type: stream, river, major_river, cascade, waterfall, mouth, pond, lake, dam, sea_inlet, grotto or cave_pool", customHandler = HydrologyTypeHandler.class) String type, @Param(description = "Should you be teleported", defaultValue = "true") boolean teleport diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandFindHydrologyTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandFindHydrologyTest.java index e341bb1a9..49b409a71 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandFindHydrologyTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandFindHydrologyTest.java @@ -149,7 +149,7 @@ public class CommandFindHydrologyTest { try (Fixture fixture = new Fixture()) { fixture.command.river("surface", true); - verify(fixture.sender).sendMessage(contains("Use one of: stream, river, major_river, cascade, waterfall, mouth, pond, lake, dam, sea_inlet, cave_pool.")); + verify(fixture.sender).sendMessage(contains("Use one of: stream, river, major_river, cascade, waterfall, mouth, pond, lake, dam, sea_inlet, cave_pool, grotto.")); assertNull(fixture.search.get()); } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisGrottos.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisGrottos.java new file mode 100644 index 000000000..ecb199400 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisGrottos.java @@ -0,0 +1,45 @@ +package art.arcane.iris.generation.hydrology.config; + +import art.arcane.iris.pack.schema.annotation.ArrayType; +import art.arcane.iris.pack.schema.annotation.MaxNumber; +import art.arcane.iris.pack.schema.annotation.MinNumber; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.documentation.Description; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@Description("Sea caves: water passages at sea level that run from the sea into coastal rock, winding like a river under an irregular natural roof and opening out into caverns. They form where tall rock meets the coast and stay clear of rivers, ponds, lakes and sea inlets.") +@Data +public class IrisGrottos { + @Description("Cuts grottos into tall coasts.") + private boolean enabled = true; + + @MinNumber(64) + @MaxNumber(4096) + @Description("Size in blocks of the square cells of the site grid. Each cell holds at most one grotto.") + private int spacing = 176; + + @ArrayType(type = Double.class, min = 2) + @Description("Half-width of the passage in blocks, written as [min, max], each from 2 to 16. Caverns open wider than this, and the rock around a passage can pinch it narrower.") + private KList radius = new KList<>(4D, 7D); + + @ArrayType(type = Integer.class, min = 2) + @Description("Height of the roof above the water in blocks, written as [min, max], each from 3 to 32. Caverns rise higher than this, and a roof stays under the ground above it.") + private KList headroom = new KList<>(5, 10); + + @ArrayType(type = Double.class, min = 2) + @Description("Half-width of the opening at the sea in blocks, written as [min, max], each from 3 to 24.") + private KList mouthWidth = new KList<>(7D, 11D); + + @ArrayType(type = Integer.class, min = 2) + @Description("Length of a grotto in blocks along its winding centre line, written as [min, max]. A passage that cannot reach the min is left out. The max must not exceed 384.") + private KList length = new KList<>(64, 240); + + @MinNumber(0) + @MaxNumber(1) + @Description("How irregular the walls, roof and floor are. 0 leaves smooth arched tubes; 1 gives deep overhangs, hanging rock and pockets.") + private double roughness = 0.6D; +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyUnderground.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyUnderground.java index 5085cfc5f..9de386372 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyUnderground.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyUnderground.java @@ -7,12 +7,15 @@ import lombok.experimental.Accessors; @Accessors(chain = true) @NoArgsConstructor -@Description("Sea inlets on the coast, and water below the surface: pools on cave floors and springs in cave walls.") +@Description("Sea inlets and grottos on the coast, and water below the surface: pools on cave floors and springs in cave walls.") @Data public class IrisHydrologyUnderground { @Description("Tidal arms of the sea that wind inland from low coasts at sea level.") private IrisSeaInlets seaInlets = new IrisSeaInlets(); + @Description("Sea caves: winding water passages at sea level that run from the sea into tall coastal rock.") + private IrisGrottos grottos = new IrisGrottos(); + @Description("Standing water on the floors of carved caves.") private IrisCavePools cavePools = new IrisCavePools(); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearch.java b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearch.java index 2ead71aee..5aa6af959 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearch.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearch.java @@ -11,6 +11,7 @@ import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException; +import art.arcane.iris.generation.hydrology.underground.Grotto; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.PondKind; @@ -39,7 +40,7 @@ final class HydrologyFeatureSearch { private static final int MAX_WINDOWS = 1089; private static final Set WINDOW_TYPES = EnumSet.of(HydrologyFeatureType.STREAM, HydrologyFeatureType.RIVER, HydrologyFeatureType.MAJOR_RIVER, HydrologyFeatureType.CASCADE, HydrologyFeatureType.WATERFALL, HydrologyFeatureType.MOUTH, - HydrologyFeatureType.POND, HydrologyFeatureType.DAM, HydrologyFeatureType.SEA_INLET); + HydrologyFeatureType.POND, HydrologyFeatureType.DAM, HydrologyFeatureType.SEA_INLET, HydrologyFeatureType.GROTTO); private static final double TIDAL_LANDING_FROM = 0.5D; private static final double TIDAL_LANDING_TO = 0.9D; private static final long POLL_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); @@ -101,6 +102,7 @@ final class HydrologyFeatureSearch { case DAM -> !anyPonds ? PONDS_OFF : ponds.dams().enabled() ? null : "hydrology.ponds.dams is disabled"; case LAKE -> settings.lakes().enabled() ? null : "hydrology.lakes is disabled"; case SEA_INLET -> settings.underground().seaInlets().enabled() ? null : "hydrology.underground.seaInlets is disabled"; + case GROTTO -> settings.underground().grottos().enabled() ? null : "hydrology.underground.grottos is disabled"; case CAVE_POOL -> settings.underground().cavePools().enabled() ? null : "hydrology.underground.cavePools is disabled"; }; return Optional.ofNullable(reason); @@ -220,6 +222,11 @@ final class HydrologyFeatureSearch { pond(pond, type); } } + if (types.contains(HydrologyFeatureType.GROTTO)) { + for (Grotto grotto : plan.grottos()) { + offer(grotto.id(), HydrologyFeatureType.GROTTO, grotto.mouthX(), grotto.seaLevel(), grotto.mouthZ()); + } + } } private HydrologyFeatureType pondType(Pond pond) { diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyPlanPreview.java b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyPlanPreview.java index 384986e13..392232d56 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyPlanPreview.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyPlanPreview.java @@ -1,12 +1,13 @@ package art.arcane.iris.generation.hydrology.engine; +import art.arcane.iris.generation.hydrology.underground.Grotto; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.Reach; import java.util.List; import java.util.Objects; -public record HydrologyPlanPreview(List reaches, List ponds, List lakes, boolean complete) { +public record HydrologyPlanPreview(List reaches, List ponds, List lakes, List grottos, boolean complete) { public static final HydrologyPlanPreview EMPTY = new HydrologyPlanPreview(List.of(), List.of(), List.of(), true); public static final HydrologyPlanPreview PENDING = new HydrologyPlanPreview(List.of(), List.of(), List.of(), false); @@ -14,5 +15,10 @@ public record HydrologyPlanPreview(List reaches, List ponds, List

reaches, List ponds, List lakes, boolean complete) { + this(reaches, ponds, lakes, List.of(), complete); } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java index 9365213e7..80fc713cc 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java @@ -19,6 +19,8 @@ import art.arcane.iris.generation.hydrology.raster.ChannelFluids; import art.arcane.iris.generation.hydrology.raster.ChunkRasterizer; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; import art.arcane.iris.generation.hydrology.raster.NaturalHeights; +import art.arcane.iris.generation.hydrology.underground.Grotto; +import art.arcane.iris.generation.hydrology.underground.GrottoRasterizer; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.Reach; @@ -305,6 +307,7 @@ public final class HydrologyRuntime { boolean complete = true; List reaches = new ArrayList<>(); List ponds = new ArrayList<>(); + List grottos = new ArrayList<>(); for (int wz = min.wz() - 1; wz <= max.wz() + 1; wz++) { for (int wx = min.wx() - 1; wx <= max.wx() + 1; wx++) { WindowKey window = new WindowKey(wx, wz); @@ -312,6 +315,7 @@ public final class HydrologyRuntime { if (plan.isPresent()) { reaches.addAll(plan.get().plan().reaches()); ponds.addAll(plan.get().plan().ponds()); + grottos.addAll(plan.get().plan().grottos()); } else { complete = false; requestPreview(window, windowPreviewFailures, key(wx, wz), "window " + wx + "," + wz, () -> cache.previewWindow(window)); @@ -331,7 +335,7 @@ public final class HydrologyRuntime { () -> cache.previewRegion(region)); } } - return new HydrologyPlanPreview(reaches, ponds, List.copyOf(lakes.values()), complete); + return new HydrologyPlanPreview(reaches, ponds, List.copyOf(lakes.values()), grottos, complete); } public ChunkWaterRaster rasterAt(int blockX, int blockZ) { @@ -437,6 +441,28 @@ public final class HydrologyRuntime { return HydrologyFeatureSearch.channelType(settings, tier); } + public List grottos(int chunkX, int chunkZ) { + if (cache == null || !settings.underground().grottos().enabled()) { + return List.of(); + } + if (mainThread.getAsBoolean()) { + throw new IllegalStateException("Hydrology grottos were requested on the main thread."); + } + requireOpen(); + int minX = chunkX << 4; + int minZ = chunkZ << 4; + int shell = GrottoRasterizer.SHELL; + List touching = new ArrayList<>(0); + for (CompletableFuture window : plans(neighbourhood(chunkX, chunkZ), List.of(), PlanMode.DEMAND).windowFutures()) { + for (Grotto grotto : cache.awaitPlan(window).plan().grottos()) { + if (grotto.touches(minX - shell, minZ - shell, minX + 15 + shell, minZ + 15 + shell)) { + touching.add(grotto); + } + } + } + return touching; + } + public Set standingWaterTypes(int chunkX, int chunkZ, long featureId) { if (cache == null) { throw new IllegalStateException("Hydrology is disabled, so it has no standing water."); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologyPlanCodec.java b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologyPlanCodec.java index c53b3b8ca..d410b4326 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologyPlanCodec.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologyPlanCodec.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.hydrology.plan; +import art.arcane.iris.generation.hydrology.underground.Grotto; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.PondKind; @@ -25,27 +26,30 @@ public final class HydrologyPlanCodec { private static final int POINT_BYTES = 5 * Integer.BYTES + 1; private static final int REACH_BYTES = 2 * Long.BYTES + 4 * Integer.BYTES + 2 * POINT_BYTES; private static final int POND_BYTES = 2 * Long.BYTES + 1 + 15 * Integer.BYTES; + private static final int GROTTO_POINT_BYTES = 6 * Integer.BYTES; + private static final int GROTTO_HOLE_BYTES = 4 * Integer.BYTES; + private static final int GROTTO_BYTES = Long.BYTES + 6 * Integer.BYTES + 2 * GROTTO_POINT_BYTES; private HydrologyPlanCodec() { } public static byte[] encode(HydrologySettings settings, WindowPlan plan) { - return encode(settings, WINDOW, plan.key().wx(), plan.key().wz(), plan.reaches(), plan.ponds()); + return encode(settings, WINDOW, plan.key().wx(), plan.key().wz(), plan.reaches(), plan.ponds(), plan.grottos()); } public static byte[] encode(HydrologySettings settings, RegionPlan plan) { - return encode(settings, REGION, plan.key().rx(), plan.key().rz(), plan.majorReaches(), plan.lakes()); + return encode(settings, REGION, plan.key().rx(), plan.key().rz(), plan.majorReaches(), plan.lakes(), List.of()); } public static Optional decodeWindow(HydrologySettings settings, byte[] data) { - return decode(settings, WINDOW, data).map(body -> new WindowPlan(new WindowKey(body.x(), body.z()), body.reaches(), body.ponds())); + return decode(settings, WINDOW, data).map(body -> new WindowPlan(new WindowKey(body.x(), body.z()), body.reaches(), body.ponds(), body.grottos())); } public static Optional decodeRegion(HydrologySettings settings, byte[] data) { return decode(settings, REGION, data).map(body -> new RegionPlan(new RegionKey(body.x(), body.z()), body.reaches(), body.ponds())); } - private static byte[] encode(HydrologySettings settings, byte kind, int x, int z, List reaches, List ponds) { + private static byte[] encode(HydrologySettings settings, byte kind, int x, int z, List reaches, List ponds, List grottos) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (DataOutputStream out = new DataOutputStream(bytes)) { out.writeInt(MAGIC); @@ -61,6 +65,10 @@ public final class HydrologyPlanCodec { for (Pond pond : ponds) { writePond(out, pond); } + out.writeInt(grottos.size()); + for (Grotto grotto : grottos) { + writeGrotto(out, grotto); + } } catch (IOException failure) { throw new UncheckedIOException(failure); } @@ -131,6 +139,31 @@ public final class HydrologyPlanCodec { out.writeInt(pond.floorZ()); } + private static void writeGrotto(DataOutputStream out, Grotto grotto) throws IOException { + out.writeLong(grotto.id()); + out.writeInt(grotto.seaLevel()); + out.writeInt(Float.floatToRawIntBits(grotto.roughness())); + out.writeInt(grotto.coast()); + out.writeInt(grotto.xs().length); + writeFloats(out, grotto.xs()); + writeFloats(out, grotto.zs()); + writeFloats(out, grotto.halfWidth()); + writeFloats(out, grotto.roof()); + writeFloats(out, grotto.floor()); + writeFloats(out, grotto.lift()); + out.writeInt(grotto.holeX().length); + writeFloats(out, grotto.holeX()); + writeFloats(out, grotto.holeZ()); + writeFloats(out, grotto.holeRadius()); + for (int top : grotto.holeTop()) { + out.writeInt(top); + } + out.writeInt(grotto.plugs().length); + for (long plug : grotto.plugs()) { + out.writeLong(plug); + } + } + private static void writeFloats(DataOutputStream out, float[] values) throws IOException { for (float value : values) { out.writeInt(Float.floatToRawIntBits(value)); @@ -155,15 +188,47 @@ public final class HydrologyPlanCodec { for (int index = 0; index < pondCount; index++) { ponds.add(readPond(in)); } + int grottoCount = count(in, GROTTO_BYTES); + List grottos = new ArrayList<>(grottoCount); + for (int index = 0; index < grottoCount; index++) { + grottos.add(readGrotto(in)); + } if (in.hasRemaining()) { return Optional.empty(); } - return Optional.of(new Body(x, z, reaches, ponds)); + return Optional.of(new Body(x, z, reaches, ponds, grottos)); } catch (BufferUnderflowException | IllegalArgumentException | IllegalStateException malformed) { return Optional.empty(); } } + private static Grotto readGrotto(ByteBuffer in) { + long id = in.getLong(); + int seaLevel = in.getInt(); + float roughness = Float.intBitsToFloat(in.getInt()); + int coast = in.getInt(); + int points = count(in, GROTTO_POINT_BYTES); + float[] xs = readFloats(in, points); + float[] zs = readFloats(in, points); + float[] halfWidth = readFloats(in, points); + float[] roof = readFloats(in, points); + float[] floor = readFloats(in, points); + float[] lift = readFloats(in, points); + int holes = count(in, GROTTO_HOLE_BYTES); + float[] holeX = readFloats(in, holes); + float[] holeZ = readFloats(in, holes); + float[] holeRadius = readFloats(in, holes); + int[] holeTop = new int[holes]; + for (int hole = 0; hole < holes; hole++) { + holeTop[hole] = in.getInt(); + } + long[] plugs = new long[count(in, Long.BYTES)]; + for (int plug = 0; plug < plugs.length; plug++) { + plugs[plug] = in.getLong(); + } + return new Grotto(id, seaLevel, roughness, coast, xs, zs, halfWidth, roof, floor, lift, holeX, holeZ, holeRadius, holeTop, plugs); + } + private static Reach readReach(ByteBuffer in, HydrologySettings settings) { long id = in.getLong(); long downstreamId = in.getLong(); @@ -251,6 +316,6 @@ public final class HydrologyPlanCodec { return value; } - private record Body(int x, int z, List reaches, List ponds) { + private record Body(int x, int z, List reaches, List ponds, List grottos) { } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologySettings.java b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologySettings.java index 562abfb96..d9514f41e 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologySettings.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologySettings.java @@ -16,6 +16,7 @@ import art.arcane.iris.generation.hydrology.config.IrisHydrologyLakes; import art.arcane.iris.generation.hydrology.config.IrisHydrologyMaterials; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPonds; import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier; +import art.arcane.iris.generation.hydrology.config.IrisGrottos; import art.arcane.iris.generation.hydrology.config.IrisHydrologyUnderground; import art.arcane.iris.generation.hydrology.config.IrisPondDams; import art.arcane.iris.generation.hydrology.config.IrisPondNatural; @@ -68,6 +69,14 @@ public final class HydrologySettings { private static final double MAX_INLET_MEANDER_WIDTH = 16D; private static final int MIN_INLET_BANK_BAND = 4; private static final int MAX_INLET_BANK_BAND = 64; + private static final int MIN_GROTTO_SPACING = 64; + private static final double MIN_GROTTO_RADIUS = 2D; + private static final double MAX_GROTTO_RADIUS = 16D; + private static final int MIN_GROTTO_HEADROOM = 3; + private static final int MAX_GROTTO_HEADROOM = 32; + private static final double MIN_GROTTO_MOUTH = 3D; + private static final double MAX_GROTTO_MOUTH = 24D; + private static final int MAX_GROTTO_LENGTH = 384; private static final int INLET_LAST_STEP = (int) Math.ceil(WindowPlanner.CELL * Math.sqrt(2D)); private static final double INLET_MEANDER_SCALE = 2.5D; private static final double INLET_MEANDER_MAX = 16D; @@ -384,7 +393,25 @@ public final class HydrologySettings { } private Underground underground(IrisHydrologyUnderground config) { - return new Underground(seaInlets(config.getSeaInlets()), cavePools(config.getCavePools()), caveSprings(config.getCaveSprings())); + return new Underground(seaInlets(config.getSeaInlets()), grottos(config.getGrottos()), cavePools(config.getCavePools()), caveSprings(config.getCaveSprings())); + } + + private Grottos grottos(IrisGrottos config) { + Grottos grottos = new Grottos(config.isEnabled(), config.getSpacing(), + floatRange(config.getRadius(), "underground.grottos.radius", RangeFloor.POSITIVE), + intRange(config.getHeadroom(), "underground.grottos.headroom", RangeFloor.POSITIVE), + floatRange(config.getMouthWidth(), "underground.grottos.mouthWidth", RangeFloor.POSITIVE), + intRange(config.getLength(), "underground.grottos.length", RangeFloor.POSITIVE), (float) config.getRoughness()); + requireWithin(grottos.spacing(), MIN_GROTTO_SPACING, Integer.MAX_VALUE, "underground.grottos.spacing"); + requireWithin(grottos.radius().min(), MIN_GROTTO_RADIUS, MAX_GROTTO_RADIUS, "underground.grottos.radius", config.getRadius()); + requireWithin(grottos.radius().max(), MIN_GROTTO_RADIUS, MAX_GROTTO_RADIUS, "underground.grottos.radius", config.getRadius()); + requireWithin(grottos.headroom().min(), MIN_GROTTO_HEADROOM, MAX_GROTTO_HEADROOM, "underground.grottos.headroom"); + requireWithin(grottos.headroom().max(), MIN_GROTTO_HEADROOM, MAX_GROTTO_HEADROOM, "underground.grottos.headroom"); + requireWithin(grottos.mouthWidth().min(), MIN_GROTTO_MOUTH, MAX_GROTTO_MOUTH, "underground.grottos.mouthWidth", config.getMouthWidth()); + requireWithin(grottos.mouthWidth().max(), MIN_GROTTO_MOUTH, MAX_GROTTO_MOUTH, "underground.grottos.mouthWidth", config.getMouthWidth()); + requireWithin(grottos.length().max(), 1, MAX_GROTTO_LENGTH, "underground.grottos.length"); + requireScalarWithin(config.getRoughness(), 0D, 1D, "underground.grottos.roughness"); + return grottos; } private SeaInlets seaInlets(IrisSeaInlets config) { @@ -792,8 +819,11 @@ public final class HydrologySettings { private void addUnderground(Fingerprint hash) { SeaInlets inlets = underground.seaInlets(); + Grottos grottos = underground.grottos(); CavePools pools = underground.cavePools(); CaveSprings springs = underground.caveSprings(); + hash.add(grottos.enabled()).add(grottos.spacing()).add(grottos.radius()).add(grottos.headroom()).add(grottos.mouthWidth()) + .add(grottos.length()).add(grottos.roughness()); hash.add(inlets.enabled()).add(inlets.spacing()).add(inlets.length()).add(inlets.maximumBankHeight()) .add(inlets.mouthHalfWidth()).add(inlets.headHalfWidth()).add(inlets.taper()).add(inlets.widthVariation()) .add(inlets.meanderWidth()).add(inlets.depth()).add(inlets.bankBand()).add(inlets.bankStyle()) @@ -866,6 +896,9 @@ public final class HydrologySettings { IrisBankStyle bankStyle) { } + public record Grottos(boolean enabled, int spacing, FloatRange radius, IntRange headroom, FloatRange mouthWidth, IntRange length, float roughness) { + } + public record CavePools(boolean enabled, float density, int minArea, int maxArea, int maxDepth, int radius, IntRange freeboard, String fluid, String deepFluid, int deepFluidMaxY) { } @@ -873,7 +906,7 @@ public final class HydrologySettings { public record CaveSprings(boolean enabled, float density, String fluid, int minDepthBelowSurface) { } - public record Underground(SeaInlets seaInlets, CavePools cavePools, CaveSprings caveSprings) { + public record Underground(SeaInlets seaInlets, Grottos grottos, CavePools cavePools, CaveSprings caveSprings) { } private enum RangeFloor { diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlan.java b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlan.java index bad1a9b25..7170828d3 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlan.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlan.java @@ -1,15 +1,21 @@ package art.arcane.iris.generation.hydrology.plan; +import art.arcane.iris.generation.hydrology.underground.Grotto; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.Reach; import java.util.List; import java.util.Objects; -public record WindowPlan(WindowKey key, List reaches, List ponds) { +public record WindowPlan(WindowKey key, List reaches, List ponds, List grottos) { public WindowPlan { Objects.requireNonNull(key, "key"); reaches = List.copyOf(reaches); ponds = List.copyOf(ponds); + grottos = List.copyOf(grottos); + } + + public WindowPlan(WindowKey key, List reaches, List ponds) { + this(key, reaches, ponds, List.of()); } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlanner.java b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlanner.java index 89ec7954e..010c11d38 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlanner.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlanner.java @@ -13,6 +13,8 @@ import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer; import art.arcane.iris.generation.hydrology.grid.PriorityFlood; import art.arcane.iris.generation.hydrology.raster.PondChannelSettlement; import art.arcane.iris.generation.hydrology.raster.TongueGuard; +import art.arcane.iris.generation.hydrology.underground.Grotto; +import art.arcane.iris.generation.hydrology.underground.GrottoPlanner; import art.arcane.iris.generation.hydrology.water.CupSet; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.PondKind; @@ -49,6 +51,7 @@ public final class WindowPlanner { private final PondPlanner ponds; private final ReachShaper shaper; private final TidalPlanner tidal; + private final GrottoPlanner grottos; public WindowPlanner(HydrologySettings settings, HeightLattice fine, PondPlanner ponds, ReachShaper shaper) { this.settings = Objects.requireNonNull(settings, "settings"); @@ -56,6 +59,7 @@ public final class WindowPlanner { this.ponds = Objects.requireNonNull(ponds, "ponds"); this.shaper = Objects.requireNonNull(shaper, "shaper"); this.tidal = new TidalPlanner(settings, fine); + this.grottos = new GrottoPlanner(settings, fine, tidal); if (fine.cell() != FINE_CELL) { throw new IllegalArgumentException("Window fine lattice cell " + fine.cell() + " must be " + FINE_CELL); } @@ -131,8 +135,10 @@ public final class WindowPlanner { List reaches = network.reaches(); List windowPonds = windowPonds(network.ponds()); List ownedReaches = new ArrayList<>(ownedReaches(key, reaches)); - ownedReaches.addAll(tidal.plan(key, natural, samples, network)); - WindowPlan owned = new WindowPlan(key, ownedReaches, ownedPonds(key, windowPonds)); + List arms = tidal.plan(key, natural, samples, network); + ownedReaches.addAll(arms); + List ownedGrottos = grottos.plan(key, natural, samples, network, arms); + WindowPlan owned = new WindowPlan(key, ownedReaches, ownedPonds(key, windowPonds), ownedGrottos); requireSeaConnectedHeads(owned, settings.seaLevel()); return new WindowComputation(owned, reaches, windowPonds); } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/query/HydrologyFeatureType.java b/core/src/main/java/art/arcane/iris/generation/hydrology/query/HydrologyFeatureType.java index 5b8344721..9f6fd1541 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/query/HydrologyFeatureType.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/query/HydrologyFeatureType.java @@ -17,7 +17,8 @@ public enum HydrologyFeatureType { LAKE(7), DAM(8), SEA_INLET(9), - CAVE_POOL(10); + CAVE_POOL(10), + GROTTO(11); private static final List KEYS = keyList(); private static final PersistedCodes CODES = diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/Grotto.java b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/Grotto.java new file mode 100644 index 000000000..46e171616 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/Grotto.java @@ -0,0 +1,74 @@ +package art.arcane.iris.generation.hydrology.underground; + +import java.util.Arrays; + +public record Grotto(long id, int seaLevel, float roughness, int coast, float[] xs, float[] zs, float[] halfWidth, float[] roof, float[] floor, + float[] lift, float[] holeX, float[] holeZ, float[] holeRadius, int[] holeTop, long[] plugs) { + public Grotto { + int points = xs.length; + if (points < 2 || zs.length != points || halfWidth.length != points || roof.length != points || floor.length != points || lift.length != points) { + throw new IllegalArgumentException("Grotto " + id + " needs at least 2 stations with equal profile lengths, got " + points); + } + if (coast < 0 || coast >= points) { + throw new IllegalArgumentException("Grotto " + id + " has coast station " + coast + " outside its " + points + " stations"); + } + int holes = holeX.length; + if (holeZ.length != holes || holeRadius.length != holes || holeTop.length != holes) { + throw new IllegalArgumentException("Grotto " + id + " has uneven skylight data"); + } + for (int point = 0; point < points; point++) { + if (halfWidth[point] <= 0f || roof[point] <= 0f || floor[point] <= 0f) { + throw new IllegalArgumentException("Grotto " + id + " has an empty profile at station " + point); + } + } + } + + @Override + public boolean equals(Object object) { + return object instanceof Grotto other && id == other.id && seaLevel == other.seaLevel && Float.compare(roughness, other.roughness) == 0 && coast == other.coast + && Arrays.equals(xs, other.xs) && Arrays.equals(zs, other.zs) && Arrays.equals(halfWidth, other.halfWidth) && Arrays.equals(roof, other.roof) + && Arrays.equals(floor, other.floor) && Arrays.equals(lift, other.lift) && Arrays.equals(holeX, other.holeX) && Arrays.equals(holeZ, other.holeZ) + && Arrays.equals(holeRadius, other.holeRadius) && Arrays.equals(holeTop, other.holeTop) && Arrays.equals(plugs, other.plugs); + } + + @Override + public int hashCode() { + return 31 * Long.hashCode(id) + Arrays.hashCode(xs); + } + + public static long plug(int x, int y, int z) { + return (x + 0x4000000L) << 38 | (z + 0x4000000L) << 12 | y & 0xFFFL; + } + + public boolean plugged(int x, int y, int z) { + return plugs.length > 0 && Arrays.binarySearch(plugs, plug(x, y, z)) >= 0; + } + + public int mouthX() { + return (int) Math.floor(xs[coast]); + } + + public int mouthZ() { + return (int) Math.floor(zs[coast]); + } + + public int[] bounds() { + float reach = GrottoShape.horizontalReach(this); + float minX = Float.POSITIVE_INFINITY; + float minZ = Float.POSITIVE_INFINITY; + float maxX = Float.NEGATIVE_INFINITY; + float maxZ = Float.NEGATIVE_INFINITY; + for (int point = 0; point < xs.length; point++) { + minX = Math.min(minX, xs[point]); + maxX = Math.max(maxX, xs[point]); + minZ = Math.min(minZ, zs[point]); + maxZ = Math.max(maxZ, zs[point]); + } + return new int[]{(int) Math.floor(minX - reach), (int) Math.floor(minZ - reach), (int) Math.ceil(maxX + reach), (int) Math.ceil(maxZ + reach)}; + } + + public boolean touches(int minX, int minZ, int maxX, int maxZ) { + int[] bounds = bounds(); + return bounds[0] <= maxX && bounds[2] >= minX && bounds[1] <= maxZ && bounds[3] >= minZ; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoPlanner.java b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoPlanner.java new file mode 100644 index 000000000..2adadfc20 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoPlanner.java @@ -0,0 +1,941 @@ +package art.arcane.iris.generation.hydrology.underground; + +import art.arcane.iris.generation.hydrology.grid.CellHash; +import art.arcane.iris.generation.hydrology.grid.DemGrid; +import art.arcane.iris.generation.hydrology.grid.HeightLattice; +import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer; +import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.hydrology.plan.WindowKey; +import art.arcane.iris.generation.hydrology.plan.WindowPlanner; +import art.arcane.iris.generation.hydrology.water.Pond; +import art.arcane.iris.generation.hydrology.water.PondMask; +import art.arcane.iris.generation.hydrology.water.Reach; +import art.arcane.iris.generation.hydrology.water.ShapedNetwork; +import art.arcane.iris.generation.hydrology.water.TidalPlanner; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public final class GrottoPlanner { + private static final int CELL = WindowPlanner.CELL; + private static final int[] SIDE_I = {1, -1, 0, 0}; + private static final int[] SIDE_J = {0, 0, 1, -1}; + private static final int MEMO_SITES = 4096; + private static final int BUILD_ATTEMPTS = 12; + private static final int RAYS = 8; + private static final int ROCK_MARGIN = 6; + private static final float STEP = 4f; + private static final float OFFSHORE = 18f; + private static final float OPEN_RUN = 56f; + private static final float WALK_CLEAR = 9f; + private static final float ROOF_KEEP = 4f; + private static final float MIN_ROCK = 18f; + private static final float MIN_SIDE_GROUND = 3f; + private static final float MIN_COVERED = 32f; + private static final float COVERED_SHARE = 0.45f; + private static final float MIN_HALF_WIDTH = 2.8f; + private static final float MIN_ROOF = 3f; + private static final float CAVERN_WIDTH_MIN = 4f; + private static final float CAVERN_WIDTH_SPAN = 6f; + private static final float CAVERN_ROOF_MIN = 5f; + private static final float CAVERN_ROOF_SPAN = 8f; + private static final float CAVERN_FLOOR = 3f; + private static final float CAVERN_REACH_MIN = 11f; + private static final float CAVERN_REACH_SPAN = 7f; + private static final float CAVERN_EVERY = 90f; + private static final float FUNNEL = 26f; + private static final float FLOOR_MIN = 3f; + private static final float FLOOR_SPAN = 3f; + private static final float BEACH = 14f; + private static final float BEACH_ODDS = 0.75f; + private static final float SHAPE_REACH = 1.35f; + private static final float ROOF_REACH = 1.2f; + private static final float PROFILE_WAVE = 34f; + private static final float MEANDER_MIN = 48f; + private static final float MEANDER_SPAN = 36f; + private static final float MEANDER_RAMP = 22f; + private static final float SELF_APART = 16f; + private static final int SELF_SKIP = 10; + private static final int SMOOTH_PASSES = 3; + private static final float CLEAR_BAND = 32f; + private static final float CLEAR_MARGIN = 6f; + private static final float TERRITORY_MARGIN = 10f; + private static final float HOLE_ODDS = 0.6f; + private static final float HOLE_RADIUS_MIN = 1.6f; + private static final float HOLE_RADIUS_SPAN = 1.6f; + private static final float HOLE_COVER_MIN = 2f; + private static final float HOLE_COVER_MAX = 16f; + private static final float HOLE_FROM = 0.25f; + private static final float HOLE_TO = 0.9f; + private static final int HOLE_ABOVE = 4; + private static final double MEANDER_ANGLE = Math.toRadians(74D); + private static final double SECOND_ANGLE = Math.toRadians(24D); + private static final double SECOND_WAVE = 0.43D; + private static final double MAX_TURN = Math.toRadians(17D); + private static final double OPTION_TURN = Math.toRadians(26D); + private static final int OPTION_PAIRS = 4; + private static final double RISE_WEIGHT = 0.6D; + private static final float CROWD_SHARE = 2f; + private static final float WALK_SHRINK = 1.15f; + private static final float ARM_RING = 12f; + private static final float TALL_WIDTHS = 1.5f; + private static final float TALL_EXTRA = 1.5f; + private static final float CUT_OFF_SHARE = 0.03f; + private static final long SALT_RANK = 0x4752545241L; + private static final long SALT_ID = 0x4752544944L; + private static final long SALT_SITE = 0x4752545354L; + private static final long SALT_DENSITY = 0x4752544454L; + private static final long SALT_TARGET_X = 0x4752545458L; + private static final long SALT_TARGET_Z = 0x475254545AL; + private static final long SALT_LENGTH = 0x4752544C4EL; + private static final long SALT_MEANDER = 0x4752544D52L; + private static final long SALT_PROFILE = 0x4752545046L; + private static final long SALT_CAVERN = 0x4752544356L; + private static final long SALT_BEACH = 0x4752544245L; + private static final long SALT_HOLE = 0x4752544F4CL; + + private final HydrologySettings settings; + private final HydrologySettings.Grottos config; + private final HeightLattice fine; + private final TidalPlanner tidal; + private final int stride; + private final long seed; + private final int sea; + private final float territory; + private final Map anchors = new LinkedHashMap<>(MEMO_SITES, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > MEMO_SITES; + } + }; + + public GrottoPlanner(HydrologySettings settings, HeightLattice fine, TidalPlanner tidal) { + this.tidal = Objects.requireNonNull(tidal, "tidal"); + this.settings = Objects.requireNonNull(settings, "settings"); + this.config = settings.underground().grottos(); + this.fine = Objects.requireNonNull(fine, "fine"); + this.stride = CELL / fine.cell(); + this.seed = settings.seed(); + this.sea = settings.seaLevel(); + this.territory = 2f * ((config.radius().max() + CAVERN_WIDTH_MIN + CAVERN_WIDTH_SPAN) * SHAPE_REACH) + TERRITORY_MARGIN; + } + + public List plan(WindowKey window, DemGrid natural, HydrologySampleBuffer samples, ShapedNetwork network, List arms) { + Objects.requireNonNull(window, "window"); + Objects.requireNonNull(network, "network"); + if (!config.enabled() || settings.density() <= 0f) { + return List.of(); + } + List own = own(window); + if (own.isEmpty()) { + return List.of(); + } + View view = new View(natural, samples, TidalPlanner.coastDistance(natural, samples.ocean()), blocked(natural, network, arms)); + List planned = new ArrayList<>(); + for (Anchor anchor : own) { + Grotto grotto = site(window, view, anchor, rivals(anchor)); + if (grotto != null) { + requireWithinWindow(window, grotto); + planned.add(grotto); + } + } + planned.sort(Comparator.comparingLong(Grotto::id)); + return List.copyOf(planned); + } + + private List own(WindowKey window) { + int spacing = config.spacing(); + int minSiteX = Math.floorDiv(window.wx() * WindowKey.SIZE, spacing) - 1; + int maxSiteX = Math.floorDiv((window.wx() + 1) * WindowKey.SIZE - 1, spacing) + 1; + int minSiteZ = Math.floorDiv(window.wz() * WindowKey.SIZE, spacing) - 1; + int maxSiteZ = Math.floorDiv((window.wz() + 1) * WindowKey.SIZE - 1, spacing) + 1; + List own = new ArrayList<>(); + for (int siteZ = minSiteZ; siteZ <= maxSiteZ; siteZ++) { + for (int siteX = minSiteX; siteX <= maxSiteX; siteX++) { + Anchor anchor = anchor(siteX, siteZ); + if (anchor.active() && anchor.owner().equals(window) && !crowded(anchor)) { + own.add(anchor); + } + } + } + return own; + } + + private boolean crowded(Anchor anchor) { + int spacing = config.spacing(); + double apart = CROWD_SHARE * territory; + int minSiteX = Math.floorDiv((int) Math.floor(anchor.x() - apart), spacing) - 1; + int maxSiteX = Math.floorDiv((int) Math.ceil(anchor.x() + apart), spacing) + 1; + int minSiteZ = Math.floorDiv((int) Math.floor(anchor.z() - apart), spacing) - 1; + int maxSiteZ = Math.floorDiv((int) Math.ceil(anchor.z() + apart), spacing) + 1; + long rank = rank(anchor); + for (int siteZ = minSiteZ; siteZ <= maxSiteZ; siteZ++) { + for (int siteX = minSiteX; siteX <= maxSiteX; siteX++) { + Anchor other = anchor(siteX, siteZ); + if (other.active() && (other.siteX() != anchor.siteX() || other.siteZ() != anchor.siteZ()) + && Math.hypot(other.x() - anchor.x(), other.z() - anchor.z()) < apart && rank(other) > rank) { + return true; + } + } + } + return false; + } + + private long rank(Anchor anchor) { + return CellHash.mix(seed, SALT_RANK, anchor.siteX(), anchor.siteZ()); + } + + private Anchor anchor(int siteX, int siteZ) { + long key = ((long) siteX << 32) | (siteZ & 0xFFFFFFFFL); + synchronized (anchors) { + Anchor known = anchors.get(key); + if (known != null) { + return known; + } + } + Anchor anchor = locate(siteX, siteZ); + synchronized (anchors) { + anchors.put(key, anchor); + } + return anchor; + } + + private Anchor locate(int siteX, int siteZ) { + int spacing = config.spacing(); + double targetX = (siteX + CellHash.unit(CellHash.mix(seed, SALT_TARGET_X, siteX, siteZ))) * spacing; + double targetZ = (siteZ + CellHash.unit(CellHash.mix(seed, SALT_TARGET_Z, siteX, siteZ))) * spacing; + if (settings.density() < 1f && CellHash.unit(CellHash.mix(seed, SALT_DENSITY, siteX, siteZ)) >= settings.density()) { + return new Anchor(siteX, siteZ, WindowKey.containing((int) Math.floor(targetX), (int) Math.floor(targetZ)), targetX, targetZ, false, 0, 0); + } + int firstX = Math.ceilDiv(siteX * spacing, CELL) * CELL; + int firstZ = Math.ceilDiv(siteZ * spacing, CELL) * CELL; + int cellsX = Math.ceilDiv((siteX + 1) * spacing - firstX, CELL); + int cellsZ = Math.ceilDiv((siteZ + 1) * spacing - firstZ, CELL); + int margin = ROCK_MARGIN; + View land = land(firstX - margin * CELL, firstZ - margin * CELL, cellsX + 2 * margin, cellsZ + 2 * margin); + DemGrid grid = land.grid(); + int bestX = 0; + int bestZ = 0; + float bestRock = Float.NEGATIVE_INFINITY; + double bestDistance = Double.POSITIVE_INFINITY; + for (int j = margin; j < margin + cellsZ; j++) { + for (int i = margin; i < margin + cellsX; i++) { + int cell = grid.index(i, j); + if (!coastal(land, cell)) { + continue; + } + float rock = rock(land, cell); + if (rock < MIN_ROCK) { + continue; + } + double distance = Math.hypot(grid.blockX(cell) - targetX, grid.blockZ(cell) - targetZ); + float bucket = bucket(rock); + if (bucket > bestRock || bucket == bestRock && distance < bestDistance) { + bestRock = bucket; + bestDistance = distance; + bestX = grid.blockX(cell); + bestZ = grid.blockZ(cell); + } + } + } + boolean active = bestRock != Float.NEGATIVE_INFINITY; + WindowKey owner = active ? WindowKey.containing(bestX, bestZ) : WindowKey.containing((int) Math.floor(targetX), (int) Math.floor(targetZ)); + return new Anchor(siteX, siteZ, owner, targetX, targetZ, active, bestX, bestZ); + } + + private static float bucket(float rock) { + return (float) Math.floor(rock / 12f); + } + + private View land(int originX, int originZ, int width, int depth) { + HydrologySampleBuffer samples = new HydrologySampleBuffer(width * depth); + fine.fill(Math.floorDiv(originX, fine.cell()), Math.floorDiv(originZ, fine.cell()), width, depth, stride, samples); + DemGrid grid = new DemGrid(originX, originZ, CELL, width, depth); + System.arraycopy(samples.height(), 0, grid.values(), 0, width * depth); + return new View(grid, samples, null, null); + } + + private boolean coastal(View view, int cell) { + HydrologySampleBuffer samples = view.samples(); + return !samples.ocean()[cell] && samples.height()[cell] >= sea && (samples.permission()[cell] & HydrologySampleBuffer.ALLOW_STREAMS) != 0 && oceanSide(view, cell) >= 0; + } + + private static int oceanSide(View view, int cell) { + DemGrid grid = view.grid(); + int i = cell % grid.width(); + int j = cell / grid.width(); + for (int side = 0; side < SIDE_I.length; side++) { + int ni = i + SIDE_I[side]; + int nj = j + SIDE_J[side]; + if (ni >= 0 && nj >= 0 && ni < grid.width() && nj < grid.depth() && view.samples().ocean()[grid.index(ni, nj)]) { + return side; + } + } + return -1; + } + + private float rock(View view, int cell) { + DemGrid grid = view.grid(); + int i = cell % grid.width(); + int j = cell / grid.width(); + float highest = Float.NEGATIVE_INFINITY; + for (int dj = -ROCK_MARGIN; dj <= ROCK_MARGIN; dj++) { + for (int di = -ROCK_MARGIN; di <= ROCK_MARGIN; di++) { + int ni = i + di; + int nj = j + dj; + if (ni >= 0 && nj >= 0 && ni < grid.width() && nj < grid.depth() && di * di + dj * dj >= 4 && !view.samples().ocean()[grid.index(ni, nj)]) { + highest = Math.max(highest, view.samples().height()[grid.index(ni, nj)]); + } + } + } + return highest - sea; + } + + private List rivals(Anchor anchor) { + double reach = 2D * config.length().max() + 2D * territory; + int spacing = config.spacing(); + int minSiteX = Math.floorDiv((int) Math.floor(anchor.x() - reach), spacing); + int maxSiteX = Math.floorDiv((int) Math.ceil(anchor.x() + reach), spacing); + int minSiteZ = Math.floorDiv((int) Math.floor(anchor.z() - reach), spacing); + int maxSiteZ = Math.floorDiv((int) Math.ceil(anchor.z() + reach), spacing); + List rivals = new ArrayList<>(); + for (int siteZ = minSiteZ; siteZ <= maxSiteZ; siteZ++) { + for (int siteX = minSiteX; siteX <= maxSiteX; siteX++) { + Anchor other = anchor(siteX, siteZ); + if (other.active() && (other.siteX() != anchor.siteX() || other.siteZ() != anchor.siteZ()) && !crowded(other)) { + rivals.add(other); + } + } + } + return rivals; + } + + private boolean inTerritory(Anchor anchor, List rivals, double x, double z) { + double own = Math.hypot(x - anchor.x(), z - anchor.z()); + for (Anchor rival : rivals) { + if (own + territory > Math.hypot(x - rival.x(), z - rival.z())) { + return false; + } + } + return true; + } + + private boolean[] blocked(DemGrid grid, ShapedNetwork network, List arms) { + boolean[] blocked = new boolean[grid.values().length]; + for (Reach river : network.reaches()) { + markReach(grid, blocked, river); + } + for (Reach arm : arms) { + markReach(grid, blocked, arm); + } + for (Pond pond : network.ponds()) { + PondMask mask = pond.mask(); + float radius = 1.5f * mask.step() + Math.min(settings.ponds().shore().taper(), CLEAR_BAND) + CLEAR_MARGIN; + for (int j = 0; j < mask.depth(); j++) { + for (int i = 0; i < mask.width(); i++) { + if (mask.node(i, j)) { + mark(grid, blocked, mask.originX() + i * mask.step(), mask.originZ() + j * mask.step(), radius); + } + } + } + } + return blocked; + } + + private static void markReach(DemGrid grid, boolean[] blocked, Reach reach) { + float band = Math.min(reach.tier().bankBand(), CLEAR_BAND) + CLEAR_MARGIN; + for (int point = 0; point < reach.xs().length; point += 2) { + mark(grid, blocked, reach.xs()[point], reach.zs()[point], reach.halfWidth()[point] + band); + } + } + + private static void mark(DemGrid grid, boolean[] blocked, float x, float z, float radius) { + int cell = grid.cell(); + int minI = Math.max(0, (int) Math.floor((x - radius - grid.originX()) / cell)); + int maxI = Math.min(grid.width() - 1, (int) Math.ceil((x + radius - grid.originX()) / cell)); + int minJ = Math.max(0, (int) Math.floor((z - radius - grid.originZ()) / cell)); + int maxJ = Math.min(grid.depth() - 1, (int) Math.ceil((z + radius - grid.originZ()) / cell)); + float squared = radius * radius; + for (int j = minJ; j <= maxJ; j++) { + float dz = grid.originZ() + j * cell - z; + for (int i = minI; i <= maxI; i++) { + float dx = grid.originX() + i * cell - x; + if (dx * dx + dz * dz <= squared) { + blocked[j * grid.width() + i] = true; + } + } + } + } + + private Grotto site(WindowKey window, View view, Anchor anchor, List rivals) { + DemGrid grid = view.grid(); + float around = config.spacing(); + int firstI = Math.floorDiv((int) Math.floor(anchor.x() - around) - grid.originX(), CELL); + int firstJ = Math.floorDiv((int) Math.floor(anchor.z() - around) - grid.originZ(), CELL); + int lastI = Math.floorDiv((int) Math.ceil(anchor.x() + around) - grid.originX(), CELL); + int lastJ = Math.floorDiv((int) Math.ceil(anchor.z() + around) - grid.originZ(), CELL); + List candidates = new ArrayList<>(); + int margin = ROCK_MARGIN; + for (int j = Math.max(margin, firstJ); j <= Math.min(grid.depth() - 1 - margin, lastJ); j++) { + for (int i = Math.max(margin, firstI); i <= Math.min(grid.width() - 1 - margin, lastI); i++) { + int cell = grid.index(i, j); + if (!coastal(view, cell) || view.blocked()[cell] || !window.equals(WindowKey.containing(grid.blockX(cell), grid.blockZ(cell))) + || !inTerritory(anchor, rivals, grid.blockX(cell), grid.blockZ(cell))) { + continue; + } + float rock = rock(view, cell); + if (rock >= MIN_ROCK) { + candidates.add(new Candidate(cell, bucket(rock), Math.hypot(grid.blockX(cell) - anchor.x(), grid.blockZ(cell) - anchor.z()))); + } + } + } + candidates.sort(Comparator.comparingDouble((Candidate candidate) -> -candidate.rock()).thenComparingDouble(Candidate::distance).thenComparingInt(Candidate::cell)); + int attempts = 0; + for (Candidate candidate : candidates) { + Walk walk = walk(window, view, anchor, rivals, candidate.cell()); + if (walk == null) { + continue; + } + Grotto grotto = build(view, anchor, rivals, walk); + if (grotto != null) { + return grotto; + } + if (++attempts >= BUILD_ATTEMPTS) { + return null; + } + } + return null; + } + + private Walk walk(WindowKey window, View view, Anchor anchor, List rivals, int start) { + DemGrid grid = view.grid(); + int side = oceanSide(view, start); + float startX = grid.blockX(start); + float startZ = grid.blockZ(start); + double seaward = Math.atan2(SIDE_J[side], SIDE_I[side]); + float x = startX + SIDE_I[side] * CELL; + float z = startZ + SIDE_J[side] * CELL; + if (!isOcean(x, z)) { + return null; + } + for (float out = 0f; out < OFFSHORE; out += STEP) { + float nx = x + (float) Math.cos(seaward) * STEP; + float nz = z + (float) Math.sin(seaward) * STEP; + if (!isOcean(nx, nz)) { + break; + } + x = nx; + z = nz; + } + int hashX = (int) startX; + int hashZ = (int) startZ; + float target = WALK_SHRINK * (config.length().min() + (config.length().max() - config.length().min()) * (float) CellHash.unit(CellHash.mix(seed, SALT_LENGTH, hashX, hashZ))); + double wave = MEANDER_MIN + MEANDER_SPAN * CellHash.unit(CellHash.mix(seed, SALT_MEANDER, hashX, hashZ)); + double phase = 2D * Math.PI * CellHash.unit(CellHash.mix(seed, SALT_MEANDER + 1L, hashX, hashZ)); + double phaseSecond = 2D * Math.PI * CellHash.unit(CellHash.mix(seed, SALT_MEANDER + 2L, hashX, hashZ)); + List stations = new ArrayList<>(); + stations.add(new float[]{x, z}); + double heading = seaward + Math.PI; + float walked = 0f; + float landed = -1f; + float covered = -1f; + int coast = -1; + int coveredFrom = -1; + while (walked < target + OFFSHORE) { + double base = landed < 0f ? seaward + Math.PI : baseHeading(view, x, z, heading); + float past = landed < 0f ? 0f : walked - landed; + double ramp = Math.min(1D, past / MEANDER_RAMP); + double meander = ramp * (MEANDER_ANGLE * StrictMath.sin(2D * Math.PI * past / wave + phase) + + SECOND_ANGLE * StrictMath.sin(2D * Math.PI * past / (wave * SECOND_WAVE) + phaseSecond)); + double wanted = base + meander; + double turn = Math.clamp(normal(wanted - heading), -MAX_TURN, MAX_TURN); + double sign = meander >= 0D ? 1D : -1D; + boolean moved = false; + for (int option = 0; option <= 2 * OPTION_PAIRS && !moved; option++) { + double offset = option == 0 ? 0D : (option % 2 == 1 ? sign : -sign) * OPTION_TURN * ((option + 1) / 2); + double next = heading + turn + offset; + float nx = x + (float) Math.cos(next) * STEP; + float nz = z + (float) Math.sin(next) * STEP; + Check check = check(window, view, anchor, rivals, stations, nx, nz, landed >= 0f, covered >= 0f, walked + STEP - landed); + if (check == Check.REFUSED) { + continue; + } + heading = next; + x = nx; + z = nz; + walked += STEP; + stations.add(new float[]{x, z}); + if (landed < 0f && check != Check.SEA) { + landed = walked; + coast = stations.size() - 1; + } + if (covered < 0f && check == Check.COVERED) { + covered = walked; + coveredFrom = stations.size() - 1; + } + moved = true; + } + if (!moved) { + break; + } + } + float length = walked - landed; + float coveredLength = walked - covered; + if (coast < 0 || covered < 0f) { + return null; + } + if (length < config.length().min() || coveredLength < Math.max(MIN_COVERED, COVERED_SHARE * length)) { + return null; + } + float[] xs = new float[stations.size()]; + float[] zs = new float[stations.size()]; + for (int index = 0; index < xs.length; index++) { + xs[index] = stations.get(index)[0]; + zs[index] = stations.get(index)[1]; + } + return new Walk(xs, zs, coast, coveredFrom, CellHash.mix(CellHash.mix(seed, SALT_ID, hashX, hashZ), SALT_SITE, (int) xs[0], (int) zs[0])); + } + + private static double normal(double angle) { + return Math.atan2(Math.sin(angle), Math.cos(angle)); + } + + private double baseHeading(View view, float x, float z, double fallback) { + DemGrid grid = view.grid(); + int i = Math.floorDiv((int) Math.floor(x) - grid.originX(), CELL); + int j = Math.floorDiv((int) Math.floor(z) - grid.originZ(), CELL); + if (i < 2 || j < 2 || i >= grid.width() - 2 || j >= grid.depth() - 2) { + return fallback; + } + float[] coast = view.coast(); + float[] height = view.samples().height(); + double coastX = coast[grid.index(i + 2, j)] - coast[grid.index(i - 2, j)]; + double coastZ = coast[grid.index(i, j + 2)] - coast[grid.index(i, j - 2)]; + double coastLength = Math.hypot(coastX, coastZ); + double riseX = height[grid.index(i + 2, j)] - height[grid.index(i - 2, j)]; + double riseZ = height[grid.index(i, j + 2)] - height[grid.index(i, j - 2)]; + double riseLength = Math.hypot(riseX, riseZ); + double dirX = coastLength > 0D ? coastX / coastLength : 0D; + double dirZ = coastLength > 0D ? coastZ / coastLength : 0D; + if (riseLength > 0D) { + dirX += RISE_WEIGHT * riseX / riseLength; + dirZ += RISE_WEIGHT * riseZ / riseLength; + } + return dirX == 0D && dirZ == 0D ? fallback : Math.atan2(dirZ, dirX); + } + + private Check check(WindowKey window, View view, Anchor anchor, List rivals, List stations, float x, float z, boolean landed, boolean covered, float sinceLand) { + DemGrid grid = view.grid(); + int i = Math.floorDiv((int) Math.floor(x) - grid.originX(), CELL); + int j = Math.floorDiv((int) Math.floor(z) - grid.originZ(), CELL); + if (i < 2 || j < 2 || i >= grid.width() - 2 || j >= grid.depth() - 2 || view.blocked()[grid.index(i, j)]) { + return Check.REFUSED; + } + if (!inTerritory(anchor, rivals, x, z) || foreignArmNear(window, x, z)) { + return Check.REFUSED; + } + for (int index = 0; index < stations.size() - SELF_SKIP; index++) { + float[] station = stations.get(index); + float dx = station[0] - x; + float dz = station[1] - z; + if (dx * dx + dz * dz < SELF_APART * SELF_APART) { + return Check.REFUSED; + } + } + int[] columnX = new int[RAYS + 1]; + int[] columnZ = new int[RAYS + 1]; + for (int ray = 0; ray < RAYS; ray++) { + double angle = 2D * Math.PI * ray / RAYS; + columnX[ray] = (int) Math.floor(x + WALK_CLEAR * Math.cos(angle)); + columnZ[ray] = (int) Math.floor(z + WALK_CLEAR * Math.sin(angle)); + } + columnX[RAYS] = (int) Math.floor(x); + columnZ[RAYS] = (int) Math.floor(z); + HydrologySampleBuffer samples = new HydrologySampleBuffer(RAYS + 1); + fine.sampleColumns(columnX, columnZ, samples); + boolean ocean = samples.ocean()[RAYS]; + if (!landed && ocean) { + return Check.SEA; + } + if (landed && ocean || (samples.permission()[RAYS] & HydrologySampleBuffer.ALLOW_STREAMS) == 0 && !ocean) { + return Check.REFUSED; + } + float lowest = samples.height()[RAYS]; + boolean oceanNear = false; + for (int ray = 0; ray < RAYS; ray++) { + oceanNear |= samples.ocean()[ray]; + lowest = Math.min(lowest, samples.height()[ray]); + } + float needed = sea + config.headroom().min() + ROOF_KEEP; + boolean roofed = !oceanNear && lowest >= needed; + if (covered) { + return roofed ? Check.COVERED : Check.REFUSED; + } + if (roofed) { + return Check.COVERED; + } + return sinceLand > OPEN_RUN ? Check.REFUSED : Check.OPEN; + } + + private boolean foreignArmNear(WindowKey window, float x, float z) { + float clearance = CLEAR_BAND + CLEAR_MARGIN + config.radius().max() + CAVERN_WIDTH_MIN; + if (!tidal.foreignArmMayReach(window, x, z, clearance)) { + return false; + } + int rings = (int) Math.ceil(clearance / ARM_RING); + int[] columnX = new int[RAYS * rings + 1]; + int[] columnZ = new int[RAYS * rings + 1]; + for (int ray = 0; ray < RAYS; ray++) { + double angle = 2D * Math.PI * ray / RAYS; + for (int ring = 0; ring < rings; ring++) { + float out = (ring + 1) * ARM_RING; + columnX[ray * rings + ring] = (int) Math.floor(x + out * Math.cos(angle)); + columnZ[ray * rings + ring] = (int) Math.floor(z + out * Math.sin(angle)); + } + } + columnX[RAYS * rings] = (int) Math.floor(x); + columnZ[RAYS * rings] = (int) Math.floor(z); + HydrologySampleBuffer samples = new HydrologySampleBuffer(columnX.length); + fine.sampleColumns(columnX, columnZ, samples); + float limit = tidal.armGroundLimit(); + for (int index = 0; index < columnX.length; index++) { + if (!samples.ocean()[index] && samples.height()[index] <= limit) { + return true; + } + } + return false; + } + + private boolean isOcean(float x, float z) { + int[] columnX = {(int) Math.floor(x)}; + int[] columnZ = {(int) Math.floor(z)}; + HydrologySampleBuffer samples = new HydrologySampleBuffer(1); + fine.sampleColumns(columnX, columnZ, samples); + return samples.ocean()[0] && samples.height()[0] < sea; + } + + private Grotto build(View view, Anchor anchor, List rivals, Walk walk) { + float[] xs = walk.xs().clone(); + float[] zs = walk.zs().clone(); + for (int pass = 0; pass < SMOOTH_PASSES; pass++) { + xs = smoothed(xs); + zs = smoothed(zs); + } + long id = walk.id(); + float roughness = config.roughness(); + float[] along = new float[xs.length]; + for (int point = 1; point < xs.length; point++) { + along[point] = along[point - 1] + (float) Math.hypot(xs[point] - xs[point - 1], zs[point] - zs[point - 1]); + } + float total = along[xs.length - 1]; + float coastAt = along[walk.coast()]; + if (total - coastAt < config.length().min()) { + return null; + } + float[][] caverns = caverns(id, coastAt, total); + int rings = (int) Math.ceil(ringReach() / STEP) + 1; + float[] room = new float[xs.length]; + float[][] lows = new float[xs.length][rings]; + for (int point = 0; point < xs.length; point++) { + boolean walled = point >= walk.coveredFrom() && along[point] - coastAt > FUNNEL; + room[point] = room(view, anchor, rivals, xs[point], zs[point], walled, lows[point]); + } + float[] halfWidth = new float[xs.length]; + float[] roof = new float[xs.length]; + float[] floor = new float[xs.length]; + float[] roofCap = new float[xs.length]; + float mouth = config.mouthWidth().min() + (config.mouthWidth().max() - config.mouthWidth().min()) * (float) CellHash.unit(CellHash.mix(id, SALT_PROFILE, 0, 0)); + float reach = (float) (1D + (GrottoShape.radialMax(roughness) - 1D) * 0.5D); + float warp = (float) GrottoShape.warp(roughness); + for (int point = 0; point < xs.length; point++) { + float s = along[point]; + float width = config.radius().min() + (config.radius().max() - config.radius().min()) * slow(id, SALT_PROFILE + 1L, s); + float high = config.headroom().min() + (config.headroom().max() - config.headroom().min()) * slow(id, SALT_PROFILE + 2L, s); + float deep = FLOOR_MIN + FLOOR_SPAN * slow(id, SALT_PROFILE + 3L, s); + for (float[] cavern : caverns) { + float bump = (s - cavern[0]) / cavern[1]; + float weight = (float) StrictMath.exp(-bump * bump); + width += cavern[2] * weight; + high += cavern[3] * weight; + deep += CAVERN_FLOOR * weight; + } + float funnel = s <= coastAt ? 1f : Math.max(0f, 1f - (s - coastAt) / FUNNEL); + width = Math.max(width, width + (mouth - width) * funnel); + high = Math.max(high, config.headroom().max() * (0.6f + 0.4f * funnel)); + float capped = (room[point] - warp - 1f) / reach; + halfWidth[point] = Math.max(MIN_HALF_WIDTH, Math.min(width, capped)); + int ring = Math.min(rings - 1, (int) Math.ceil(halfWidth[point] / STEP)); + float ceiling = point >= walk.coveredFrom() ? Math.max(MIN_ROOF, (lows[point][ring] - sea - ROOF_KEEP) / ROOF_REACH) : Float.POSITIVE_INFINITY; + roofCap[point] = ceiling; + roof[point] = Math.min(Math.min(high, ceiling), TALL_WIDTHS * halfWidth[point] + TALL_EXTRA); + floor[point] = deep; + } + halfWidth = eased(halfWidth); + roof = eased(roof); + floor = eased(floor); + float[] lift = new float[xs.length]; + boolean beach = CellHash.unit(CellHash.mix(id, SALT_BEACH, 0, 0)) < BEACH_ODDS; + for (int point = 0; point < xs.length; point++) { + roof[point] = Math.min(roof[point], roofCap[point]); + float out = (total - along[point]) / BEACH; + if (beach && out < 1f) { + float rise = 1f - out; + lift[point] = rise * rise * (3f - 2f * rise) * (floor[point] * 1.25f); + roof[point] = Math.max(MIN_ROOF, roof[point] - lift[point] * 0.5f); + } + } + Holes holes = holes(id, xs, zs, along, walk, roof, lift, total); + Grotto grotto = new Grotto(id, sea, roughness, walk.coast(), xs, zs, halfWidth, roof, floor, lift, holes.x(), holes.z(), holes.radius(), holes.top(), new long[0]); + long[] plugs = cutOff(grotto); + if (plugs == null) { + return null; + } + return new Grotto(id, sea, roughness, walk.coast(), xs, zs, halfWidth, roof, floor, lift, holes.x(), holes.z(), holes.radius(), holes.top(), plugs); + } + + private float ringReach() { + return (config.radius().max() + CAVERN_WIDTH_MIN + CAVERN_WIDTH_SPAN) * SHAPE_REACH + 6f; + } + + private float room(View view, Anchor anchor, List rivals, float x, float z, boolean roofed, float[] lows) { + DemGrid grid = view.grid(); + int rings = lows.length; + int[] columnX = new int[RAYS * rings + 1]; + int[] columnZ = new int[RAYS * rings + 1]; + for (int ray = 0; ray < RAYS; ray++) { + double angle = 2D * Math.PI * ray / RAYS; + for (int ring = 0; ring < rings; ring++) { + float out = (ring + 1) * STEP; + columnX[ray * rings + ring] = (int) Math.floor(x + out * Math.cos(angle)); + columnZ[ray * rings + ring] = (int) Math.floor(z + out * Math.sin(angle)); + } + } + columnX[RAYS * rings] = (int) Math.floor(x); + columnZ[RAYS * rings] = (int) Math.floor(z); + HydrologySampleBuffer samples = new HydrologySampleBuffer(columnX.length); + fine.sampleColumns(columnX, columnZ, samples); + Arrays.fill(lows, samples.height()[RAYS * rings]); + float room = rings * STEP; + for (int ray = 0; ray < RAYS; ray++) { + boolean stopped = false; + for (int ring = 0; ring < rings; ring++) { + int index = ray * rings + ring; + float out = (ring + 1) * STEP; + if (ring + 1 < rings) { + lows[ring + 1] = Math.min(lows[ring + 1], samples.height()[index]); + } + if (stopped) { + continue; + } + int i = Math.floorDiv(columnX[index] - grid.originX(), CELL); + int j = Math.floorDiv(columnZ[index] - grid.originZ(), CELL); + if (i < 0 || j < 0 || i >= grid.width() || j >= grid.depth() || view.blocked()[grid.index(i, j)] + || !inTerritory(anchor, rivals, columnX[index], columnZ[index])) { + room = Math.min(room, out - STEP); + stopped = true; + } else if (roofed && (samples.ocean()[index] || samples.height()[index] < sea + MIN_SIDE_GROUND)) { + room = Math.min(room, out); + stopped = true; + } + } + } + for (int ring = 1; ring < rings; ring++) { + lows[ring] = Math.min(lows[ring], lows[ring - 1]); + } + return room; + } + + private float[][] caverns(long id, float coastAt, float total) { + float span = total - coastAt; + int count = Math.max(1, (int) (span / CAVERN_EVERY)); + float[][] caverns = new float[count][]; + for (int index = 0; index < count; index++) { + float place = index == count - 1 ? 0.84f : (index + 0.55f + 0.5f * (float) CellHash.unit(CellHash.mix(id, SALT_CAVERN, index, 0))) / count * 0.84f; + float at = coastAt + span * place; + float reach = CAVERN_REACH_MIN + CAVERN_REACH_SPAN * (float) CellHash.unit(CellHash.mix(id, SALT_CAVERN, index, 1)); + float width = CAVERN_WIDTH_MIN + CAVERN_WIDTH_SPAN * (float) CellHash.unit(CellHash.mix(id, SALT_CAVERN, index, 2)); + float high = CAVERN_ROOF_MIN + CAVERN_ROOF_SPAN * (float) CellHash.unit(CellHash.mix(id, SALT_CAVERN, index, 3)); + caverns[index] = new float[]{at, reach, width, high}; + } + return caverns; + } + + private static float slow(long id, long salt, float s) { + int low = (int) Math.floor(s / PROFILE_WAVE); + float t = s / PROFILE_WAVE - low; + float fade = t * t * (3f - 2f * t); + float a = (float) CellHash.unit(CellHash.mix(id, salt, low, 0)); + float b = (float) CellHash.unit(CellHash.mix(id, salt, low + 1, 0)); + return a + (b - a) * fade; + } + + private Holes holes(long id, float[] xs, float[] zs, float[] along, Walk walk, float[] roof, float[] lift, float total) { + List holes = new ArrayList<>(); + if (CellHash.unit(CellHash.mix(id, SALT_HOLE, 0, 0)) < HOLE_ODDS) { + float wanted = HOLE_FROM + (HOLE_TO - HOLE_FROM) * (float) CellHash.unit(CellHash.mix(id, SALT_HOLE, 1, 0)); + float coastAt = along[walk.coast()]; + int[] columnX = new int[1]; + int[] columnZ = new int[1]; + HydrologySampleBuffer sample = new HydrologySampleBuffer(1); + for (int offset = 0; offset < xs.length && holes.isEmpty(); offset++) { + int point = Math.floorMod(Math.round(xs.length * wanted) + offset, xs.length); + float share = (along[point] - coastAt) / Math.max(1f, total - coastAt); + if (share < HOLE_FROM || share > HOLE_TO || point < walk.coveredFrom()) { + continue; + } + columnX[0] = (int) Math.floor(xs[point]); + columnZ[0] = (int) Math.floor(zs[point]); + fine.sampleColumns(columnX, columnZ, sample); + float cover = sample.height()[0] - sea - roof[point] - lift[point]; + if (cover >= HOLE_COVER_MIN && cover <= HOLE_COVER_MAX) { + float radius = HOLE_RADIUS_MIN + HOLE_RADIUS_SPAN * (float) CellHash.unit(CellHash.mix(id, SALT_HOLE, 2, 0)); + holes.add(new float[]{xs[point], zs[point], radius, sample.height()[0] + HOLE_ABOVE}); + } + } + } + float[] x = new float[holes.size()]; + float[] z = new float[holes.size()]; + float[] radius = new float[holes.size()]; + int[] top = new int[holes.size()]; + for (int index = 0; index < x.length; index++) { + float[] hole = holes.get(index); + x[index] = hole[0]; + z[index] = hole[1]; + radius[index] = hole[2]; + top[index] = (int) Math.ceil(hole[3]); + } + return new Holes(x, z, radius, top); + } + + private static float[] smoothed(float[] values) { + float[] out = values.clone(); + for (int point = 1; point < values.length - 1; point++) { + out[point] = 0.25f * values[point - 1] + 0.5f * values[point] + 0.25f * values[point + 1]; + } + return out; + } + + private static float[] eased(float[] values) { + float[] out = values; + for (int pass = 0; pass < SMOOTH_PASSES; pass++) { + out = smoothed(out); + } + for (int point = 0; point < out.length; point++) { + out[point] = Math.min(out[point], values[point] + 1.5f); + } + return out; + } + + private long[] cutOff(Grotto grotto) { + GrottoShape shape = new GrottoShape(grotto); + int[] bounds = grotto.bounds(); + int width = bounds[2] - bounds[0] + 1; + int depth = bounds[3] - bounds[1] + 1; + int bottom = shape.minY(); + int layers = sea - bottom + 1; + BitSet wet = new BitSet(width * depth * layers); + long total = 0L; + for (int z = 0; z < depth; z++) { + for (int x = 0; x < width; x++) { + if (shape.near(bounds[0] + x, bounds[1] + z)) { + for (int layer = 0; layer < layers; layer++) { + if (shape.inside(bounds[0] + x, bottom + layer, bounds[1] + z)) { + wet.set((layer * depth + z) * width + x); + total++; + } + } + } + } + } + int startX = (int) Math.floor(grotto.xs()[0]) - bounds[0]; + int startZ = (int) Math.floor(grotto.zs()[0]) - bounds[1]; + int start = ((layers - 1) * depth + startZ) * width + startX; + if (!wet.get(start)) { + return null; + } + ArrayDeque frontier = new ArrayDeque<>(); + frontier.add(start); + wet.clear(start); + while (!frontier.isEmpty()) { + int cell = frontier.poll(); + int x = cell % width; + int rest = cell / width; + int z = rest % depth; + int layer = rest / depth; + if (x + 1 < width) { + flood(wet, frontier, cell + 1); + } + if (x > 0) { + flood(wet, frontier, cell - 1); + } + if (z + 1 < depth) { + flood(wet, frontier, cell + width); + } + if (z > 0) { + flood(wet, frontier, cell - width); + } + if (layer + 1 < layers) { + flood(wet, frontier, cell + width * depth); + } + if (layer > 0) { + flood(wet, frontier, cell - width * depth); + } + } + int left = wet.cardinality(); + if (left > CUT_OFF_SHARE * total) { + return null; + } + long[] plugs = new long[left]; + int index = 0; + for (int cell = wet.nextSetBit(0); cell >= 0; cell = wet.nextSetBit(cell + 1)) { + int rest = cell / width; + plugs[index++] = Grotto.plug(bounds[0] + cell % width, bottom + rest / depth, bounds[1] + rest % depth); + } + Arrays.sort(plugs); + return plugs; + } + + private static void flood(BitSet wet, ArrayDeque frontier, int cell) { + if (wet.get(cell)) { + wet.clear(cell); + frontier.add(cell); + } + } + + private void requireWithinWindow(WindowKey window, Grotto grotto) { + int[] bounds = grotto.bounds(); + if (bounds[0] < (window.wx() - 1) * WindowKey.SIZE || bounds[2] >= (window.wx() + 2) * WindowKey.SIZE + || bounds[1] < (window.wz() - 1) * WindowKey.SIZE || bounds[3] >= (window.wz() + 2) * WindowKey.SIZE) { + throw new IllegalStateException("Grotto " + grotto.id() + " of window " + window + " reaches past the next window"); + } + } + + private enum Check { + SEA, + OPEN, + COVERED, + REFUSED + } + + private record View(DemGrid grid, HydrologySampleBuffer samples, float[] coast, boolean[] blocked) { + } + + private record Candidate(int cell, float rock, double distance) { + } + + private record Walk(float[] xs, float[] zs, int coast, int coveredFrom, long id) { + } + + private record Holes(float[] x, float[] z, float[] radius, int[] top) { + } + + private record Anchor(int siteX, int siteZ, WindowKey owner, double targetX, double targetZ, boolean active, int x, int z) { + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoRasterizer.java b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoRasterizer.java new file mode 100644 index 000000000..a42eba920 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoRasterizer.java @@ -0,0 +1,146 @@ +package art.arcane.iris.generation.hydrology.underground; + +import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction; +import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; +import art.arcane.iris.generation.mantle.MantleWriter; +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; + +public final class GrottoRasterizer { + public static final int SHELL = 2; + static final byte NONE = 0; + static final byte WET = 1; + static final byte DRY = 2; + static final byte GUARD = 3; + private static final int CHUNK = 16; + private static final int GRID = CHUNK + 2 * SHELL; + + public interface Exclusion { + Exclusion NOWHERE = (x, y, z) -> false; + + boolean blocked(int x, int y, int z); + } + + public void write(Grotto grotto, int chunkX, int chunkZ, MantleWriter writer, String fluid, Exclusion exclusion) { + Cells cells = cells(grotto, chunkX, chunkZ, exclusion); + if (cells == null) { + return; + } + HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, fluid); + HydrologyCaveCell dry = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, fluid); + HydrologyCaveCell guard = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, fluid); + for (int y = cells.minY(); y <= cells.maxY(); y++) { + for (int lz = 0; lz < CHUNK; lz++) { + for (int lx = 0; lx < CHUNK; lx++) { + int x = (chunkX << 4) + lx; + int z = (chunkZ << 4) + lz; + switch (cells.at(lx, y, lz)) { + case WET -> { + writer.setData(x, y, z, wet); + writer.clearData(x, y, z, NativeBlockState.class); + } + case DRY -> writer.setData(x, y, z, dry); + case GUARD -> { + if (writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class) == null) { + writer.setData(x, y, z, guard); + } + } + default -> { + } + } + } + } + } + } + + static Cells cells(Grotto grotto, int chunkX, int chunkZ, Exclusion exclusion) { + int originX = (chunkX << 4) - SHELL; + int originZ = (chunkZ << 4) - SHELL; + if (!grotto.touches(originX, originZ, originX + GRID - 1, originZ + GRID - 1)) { + return null; + } + GrottoShape shape = new GrottoShape(grotto).scoped(originX, originZ, originX + GRID - 1, originZ + GRID - 1); + if (shape.empty()) { + return null; + } + int sea = grotto.seaLevel(); + int minY = Math.max(1, shape.minY() - SHELL); + int maxY = Math.max(shape.maxY(), sea); + int height = maxY - minY + 1; + boolean[] carved = new boolean[GRID * GRID * height]; + boolean any = false; + for (int gz = 0; gz < GRID; gz++) { + for (int gx = 0; gx < GRID; gx++) { + int x = originX + gx; + int z = originZ + gz; + if (!shape.near(x, z)) { + continue; + } + boolean own = gx >= SHELL && gx < SHELL + CHUNK && gz >= SHELL && gz < SHELL + CHUNK; + int top = own ? maxY : sea; + for (int y = Math.max(minY, shape.minY()); y <= top; y++) { + if (shape.inside(x, y, z) && !exclusion.blocked(x, y, z)) { + carved[index(gx, y - minY, gz)] = true; + any = true; + } + } + } + } + if (!any) { + return null; + } + byte[] kinds = new byte[CHUNK * CHUNK * height]; + for (int gz = 0; gz < GRID; gz++) { + for (int gx = 0; gx < GRID; gx++) { + for (int y = minY; y <= sea; y++) { + if (carved[index(gx, y - minY, gz)]) { + guardAround(kinds, gx, y - minY, gz, sea - minY); + } + } + } + } + for (int lz = 0; lz < CHUNK; lz++) { + for (int lx = 0; lx < CHUNK; lx++) { + for (int y = minY; y <= maxY; y++) { + if (carved[index(lx + SHELL, y - minY, lz + SHELL)]) { + kinds[(y - minY) * CHUNK * CHUNK + lz * CHUNK + lx] = y <= sea ? WET : DRY; + } + } + } + } + return new Cells(minY, maxY, kinds); + } + + private static void guardAround(byte[] kinds, int gx, int level, int gz, int seaLevel) { + for (int dz = -SHELL; dz <= SHELL; dz++) { + int lz = gz + dz - SHELL; + if (lz < 0 || lz >= CHUNK) { + continue; + } + for (int dx = -SHELL; dx <= SHELL; dx++) { + int lx = gx + dx - SHELL; + if (lx < 0 || lx >= CHUNK) { + continue; + } + for (int dy = -SHELL; dy <= SHELL; dy++) { + int at = level + dy; + if (at >= 0 && at <= seaLevel) { + kinds[at * CHUNK * CHUNK + lz * CHUNK + lx] = GUARD; + } + } + } + } + } + + private static int index(int gx, int level, int gz) { + return level * GRID * GRID + gz * GRID + gx; + } + + record Cells(int minY, int maxY, byte[] kinds) { + byte at(int lx, int y, int lz) { + if (y < minY || y > maxY) { + return NONE; + } + return kinds[(y - minY) * CHUNK * CHUNK + lz * CHUNK + lx]; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoShape.java b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoShape.java new file mode 100644 index 000000000..54dff7d16 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoShape.java @@ -0,0 +1,314 @@ +package art.arcane.iris.generation.hydrology.underground; + +import art.arcane.iris.generation.hydrology.grid.CellHash; + +import java.util.ArrayList; +import java.util.List; + +public final class GrottoShape { + private static final double WARP = 3.6D; + private static final double WARP_WAVE = 21D; + private static final double WARP_WAVE_Y = 11D; + private static final double WARP_Y = 1.1D; + private static final double LOBE_WIDE = 0.34D; + private static final double LOBE_MID = 0.26D; + private static final double LOBE_FINE = 0.12D; + private static final double TURN_WIDE = 1.5D; + private static final double TURN_MID = 3.1D; + private static final double TURN_FINE = 6.5D; + private static final double ALONG_WIDE = 19D; + private static final double ALONG_MID = 8.5D; + private static final double ALONG_FINE = 3.7D; + private static final double HANG = 6D; + private static final double HANG_WAVE = 3.1D; + private static final double HANG_SPARSE = 0.42D; + private static final double HANG_BROAD = 9D; + private static final double HANG_LOW = 1.6D; + private static final double MOUND = 2.2D; + private static final double MOUND_WAVE = 6.1D; + private static final double HANG_BAND = 0.45D; + private static final double MIN_RADIAL = 0.62D; + private static final double CORE = 0.5D; + private static final double HOLE_WOBBLE = 0.45D; + private static final double HOLE_WAVE = 3.2D; + private static final long SALT_WARP_X = 0x4752545758L; + private static final long SALT_WARP_Z = 0x47525457ACL; + private static final long SALT_WARP_Y = 0x4752545759L; + private static final long SALT_LOBE = 0x4752544C42L; + private static final long SALT_HANG = 0x4752544847L; + private static final long SALT_MOUND = 0x4752544D44L; + private static final long SALT_HOLE = 0x4752544F4CL; + + private final Grotto grotto; + private final float[] xs; + private final float[] zs; + private final float[] along; + private final int[] segments; + private final double warp; + private final double reachFactor; + private final int minY; + private final int maxY; + + public GrottoShape(Grotto grotto) { + this(grotto, allSegments(grotto)); + } + + private GrottoShape(Grotto grotto, int[] segments) { + this.grotto = grotto; + this.xs = grotto.xs(); + this.zs = grotto.zs(); + this.along = distances(xs, zs); + this.segments = segments; + this.warp = warp(grotto.roughness()); + this.reachFactor = radialMax(grotto.roughness()); + this.minY = verticalMin(grotto); + this.maxY = verticalMax(grotto); + } + + public GrottoShape scoped(int minX, int minZ, int maxX, int maxZ) { + List kept = new ArrayList<>(); + for (int segment = 0; segment < xs.length - 1; segment++) { + float out = segmentReach(segment); + float fromX = Math.min(xs[segment], xs[segment + 1]) - out; + float toX = Math.max(xs[segment], xs[segment + 1]) + out; + float fromZ = Math.min(zs[segment], zs[segment + 1]) - out; + float toZ = Math.max(zs[segment], zs[segment + 1]) + out; + if (fromX <= maxX && toX >= minX && fromZ <= maxZ && toZ >= minZ) { + kept.add(segment); + } + } + int[] scoped = new int[kept.size()]; + for (int index = 0; index < scoped.length; index++) { + scoped[index] = kept.get(index); + } + return new GrottoShape(grotto, scoped); + } + + public boolean empty() { + return segments.length == 0 && grotto.holeX().length == 0; + } + + public int minY() { + return minY; + } + + public int maxY() { + return maxY; + } + + public Grotto grotto() { + return grotto; + } + + public boolean near(int x, int z) { + for (int segment : segments) { + float out = segmentReach(segment); + if (squared(x, z, segment) <= out * out) { + return true; + } + } + float[] holeX = grotto.holeX(); + for (int hole = 0; hole < holeX.length; hole++) { + double out = grotto.holeRadius()[hole] * (1D + HOLE_WOBBLE) + warp + 1D; + double dx = x - holeX[hole]; + double dz = z - grotto.holeZ()[hole]; + if (dx * dx + dz * dz <= out * out) { + return true; + } + } + return false; + } + + public boolean inside(int x, int y, int z) { + if (y < minY || y > maxY || grotto.plugged(x, y, z)) { + return false; + } + double noiseX = x / WARP_WAVE; + double noiseY = y / WARP_WAVE_Y; + double noiseZ = z / WARP_WAVE; + double px = x + warp * noise(SALT_WARP_X, noiseX, noiseY, noiseZ); + double pz = z + warp * noise(SALT_WARP_Z, noiseX + 37.1D, noiseY, noiseZ); + double py = y + WARP_Y * noise(SALT_WARP_Y, noiseX, noiseY + 11.3D, noiseZ); + return inPassage(x, z, px, py, pz) || y > grotto.seaLevel() && inHole(y, px, pz); + } + + private boolean inPassage(int x, int z, double px, double py, double pz) { + int best = -1; + double bestSquared = Double.POSITIVE_INFINITY; + double bestShare = 0D; + for (int segment : segments) { + double ax = xs[segment]; + double az = zs[segment]; + double dx = xs[segment + 1] - ax; + double dz = zs[segment + 1] - az; + double length = dx * dx + dz * dz; + double share = length <= 0D ? 0D : Math.clamp(((px - ax) * dx + (pz - az) * dz) / length, 0D, 1D); + double ox = px - ax - share * dx; + double oz = pz - az - share * dz; + double distance = ox * ox + oz * oz; + if (distance < bestSquared) { + bestSquared = distance; + best = segment; + bestShare = share; + } + } + if (best < 0) { + return false; + } + double width = lerp(grotto.halfWidth(), best, bestShare); + double limit = width * reachFactor; + if (bestSquared > limit * limit) { + return false; + } + double s = along[best] + bestShare * (along[best + 1] - along[best]); + double centre = grotto.seaLevel() + lerp(grotto.lift(), best, bestShare); + double dy = py - centre; + double roughness = grotto.roughness(); + double height; + if (dy > 0D) { + height = lerp(grotto.roof(), best, bestShare); + double hang = noise(SALT_HANG, x / HANG_WAVE, 0D, z / HANG_WAVE); + double broad = noise(SALT_HANG + 1L, x / HANG_BROAD, 0D, z / HANG_BROAD); + dy += roughness * (HANG * Math.max(0D, hang - HANG_SPARSE) + HANG_LOW * broad) * Math.min(1D, dy / (HANG_BAND * height)); + } else { + height = lerp(grotto.floor(), best, bestShare); + double mound = noise(SALT_MOUND, x / MOUND_WAVE, 0D, z / MOUND_WAVE); + dy += roughness * MOUND * mound * Math.min(1D, -dy / (HANG_BAND * height)); + dy = Math.min(dy, 0D); + } + double distance = Math.sqrt(bestSquared); + double dirX = xs[best + 1] - xs[best]; + double dirZ = zs[best + 1] - zs[best]; + double side = dirX * (pz - zs[best]) - dirZ * (px - xs[best]) >= 0D ? 1D : -1D; + double u = side * distance / width; + double v = dy / height; + double rho = Math.sqrt(u * u + v * v); + if (rho < CORE) { + return true; + } + double cos = u / rho; + double sin = v / rho; + double lobes = LOBE_WIDE * noise(SALT_LOBE, cos * TURN_WIDE, sin * TURN_WIDE, s / ALONG_WIDE) + + LOBE_MID * noise(SALT_LOBE + 1L, cos * TURN_MID, sin * TURN_MID, s / ALONG_MID) + + LOBE_FINE * noise(SALT_LOBE + 2L, cos * TURN_FINE, sin * TURN_FINE, s / ALONG_FINE); + double radial = Math.max(MIN_RADIAL, 1D + 2D * roughness * lobes); + return rho < radial; + } + + private boolean inHole(int y, double px, double pz) { + float[] holeX = grotto.holeX(); + for (int hole = 0; hole < holeX.length; hole++) { + if (y > grotto.holeTop()[hole]) { + continue; + } + double dx = px - holeX[hole]; + double dz = pz - grotto.holeZ()[hole]; + double radius = grotto.holeRadius()[hole] * (1D + HOLE_WOBBLE * noise(SALT_HOLE + hole, dx / HOLE_WAVE, y / HOLE_WAVE, dz / HOLE_WAVE)); + if (dx * dx + dz * dz < radius * radius) { + return true; + } + } + return false; + } + + static float horizontalReach(Grotto grotto) { + float widest = 0f; + for (float width : grotto.halfWidth()) { + widest = Math.max(widest, width); + } + return (float) (widest * radialMax(grotto.roughness()) + warp(grotto.roughness()) + 1D); + } + + public static double radialMax(double roughness) { + return 1D + 2D * roughness * (LOBE_WIDE + LOBE_MID + LOBE_FINE); + } + + public static double warp(double roughness) { + return WARP * (0.4D + 0.6D * roughness); + } + + private static int verticalMin(Grotto grotto) { + float deepest = 0f; + for (float floor : grotto.floor()) { + deepest = Math.max(deepest, floor); + } + return grotto.seaLevel() - (int) Math.ceil(deepest * radialMax(grotto.roughness()) + WARP_Y + 1D); + } + + private static int verticalMax(Grotto grotto) { + float highest = 0f; + for (int point = 0; point < grotto.roof().length; point++) { + highest = Math.max(highest, grotto.roof()[point] + grotto.lift()[point]); + } + int top = grotto.seaLevel() + (int) Math.ceil(highest * radialMax(grotto.roughness()) + grotto.roughness() * HANG_LOW + WARP_Y + 1D); + for (int holeTop : grotto.holeTop()) { + top = Math.max(top, holeTop); + } + return top; + } + + private float segmentReach(int segment) { + return (float) (Math.max(grotto.halfWidth()[segment], grotto.halfWidth()[segment + 1]) * reachFactor + warp + 1D); + } + + private double squared(int x, int z, int segment) { + double ax = xs[segment]; + double az = zs[segment]; + double dx = xs[segment + 1] - ax; + double dz = zs[segment + 1] - az; + double length = dx * dx + dz * dz; + double share = length <= 0D ? 0D : Math.clamp(((x - ax) * dx + (z - az) * dz) / length, 0D, 1D); + double ox = x - ax - share * dx; + double oz = z - az - share * dz; + return ox * ox + oz * oz; + } + + private static double lerp(float[] values, int segment, double share) { + return values[segment] + share * (values[segment + 1] - values[segment]); + } + + private static float[] distances(float[] xs, float[] zs) { + float[] along = new float[xs.length]; + for (int point = 1; point < xs.length; point++) { + along[point] = along[point - 1] + (float) Math.hypot(xs[point] - xs[point - 1], zs[point] - zs[point - 1]); + } + return along; + } + + private static int[] allSegments(Grotto grotto) { + int[] all = new int[grotto.xs().length - 1]; + for (int segment = 0; segment < all.length; segment++) { + all[segment] = segment; + } + return all; + } + + private double noise(long salt, double x, double y, double z) { + int ix = (int) Math.floor(x); + int iy = (int) Math.floor(y); + int iz = (int) Math.floor(z); + double fx = fade(x - ix); + double fy = fade(y - iy); + double fz = fade(z - iz); + long id = grotto.id(); + double c000 = lattice(id, salt + iy, ix, iz); + double c100 = lattice(id, salt + iy, ix + 1, iz); + double c010 = lattice(id, salt + iy + 1L, ix, iz); + double c110 = lattice(id, salt + iy + 1L, ix + 1, iz); + double c001 = lattice(id, salt + iy, ix, iz + 1); + double c101 = lattice(id, salt + iy, ix + 1, iz + 1); + double c011 = lattice(id, salt + iy + 1L, ix, iz + 1); + double c111 = lattice(id, salt + iy + 1L, ix + 1, iz + 1); + double near = c000 + fx * (c100 - c000) + fy * (c010 + fx * (c110 - c010) - c000 - fx * (c100 - c000)); + double far = c001 + fx * (c101 - c001) + fy * (c011 + fx * (c111 - c011) - c001 - fx * (c101 - c001)); + return near + fz * (far - near); + } + + private static double lattice(long id, long salt, int x, int z) { + return 2D * CellHash.unit(CellHash.mix(id, salt, x, z)) - 1D; + } + + private static double fade(double t) { + return t * t * (3D - 2D * t); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoSpace.java b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoSpace.java new file mode 100644 index 000000000..72e45ea35 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/GrottoSpace.java @@ -0,0 +1,55 @@ +package art.arcane.iris.generation.hydrology.underground; + +import java.util.Arrays; +import java.util.Collection; + +public final class GrottoSpace { + private static final int NONE = Integer.MIN_VALUE; + + private final int originX; + private final int originZ; + private final int size; + private final int[] lows; + private final int[] highs; + + private GrottoSpace(int originX, int originZ, int size, int[] lows, int[] highs) { + this.originX = originX; + this.originZ = originZ; + this.size = size; + this.lows = lows; + this.highs = highs; + } + + public static GrottoSpace of(Collection grottos, int originX, int originZ, int size) { + int[] lows = new int[size * size]; + int[] highs = new int[size * size]; + Arrays.fill(lows, NONE); + Arrays.fill(highs, NONE); + int shell = GrottoRasterizer.SHELL; + for (Grotto grotto : grottos) { + GrottoShape shape = new GrottoShape(grotto).scoped(originX, originZ, originX + size - 1, originZ + size - 1); + int bottom = shape.minY() - shell; + int top = shape.maxY() + shell; + for (int z = 0; z < size; z++) { + for (int x = 0; x < size; x++) { + if (shape.near(originX + x, originZ + z)) { + int column = z * size + x; + lows[column] = lows[column] == NONE ? bottom : Math.min(lows[column], bottom); + highs[column] = Math.max(highs[column], top); + } + } + } + } + return new GrottoSpace(originX, originZ, size, lows, highs); + } + + public boolean contains(int x, int y, int z) { + int localX = x - originX; + int localZ = z - originZ; + if (localX < 0 || localX >= size || localZ < 0 || localZ >= size) { + return false; + } + int column = localZ * size + localX; + return lows[column] != NONE && y >= lows[column] && y <= highs[column]; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/TidalPlanner.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/TidalPlanner.java index 1efdd321d..856077f58 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/TidalPlanner.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/TidalPlanner.java @@ -23,6 +23,7 @@ public final class TidalPlanner { private static final int[] SIDE_I = {1, -1, 0, 0}; private static final int[] SIDE_J = {0, 0, 1, -1}; private static final int MEMO_SITES = 4096; + private static final int FOREIGN_SITES = 3; private static final int BUILD_ATTEMPTS = 24; private static final int TRIM_PASSES = 8; private static final float MOUTH_ZONE = 32f; @@ -105,7 +106,7 @@ public final class TidalPlanner { return List.of(); } Land land = new Land(natural, samples); - float[] coast = coastDistance(land); + float[] coast = coastDistance(natural, samples.ocean()); boolean[] wet = wet(natural, network); banked(natural, samples, wet); ReachFitter fitter = new ReachFitter(fine, new PondLookup(network.ponds())); @@ -122,6 +123,48 @@ public final class TidalPlanner { return List.copyOf(planned); } + public boolean foreignArmMayReach(WindowKey window, double x, double z, float clearance) { + if (!config.enabled() || settings.density() <= 0f) { + return false; + } + int spacing = config.spacing(); + int centreX = Math.floorDiv((int) Math.floor(x), spacing); + int centreZ = Math.floorDiv((int) Math.floor(z), spacing); + double nearest = Double.POSITIVE_INFINITY; + double second = Double.POSITIVE_INFINITY; + double nearestForeign = Double.POSITIVE_INFINITY; + boolean nearestIsForeign = false; + for (int siteZ = centreZ - FOREIGN_SITES; siteZ <= centreZ + FOREIGN_SITES; siteZ++) { + for (int siteX = centreX - FOREIGN_SITES; siteX <= centreX + FOREIGN_SITES; siteX++) { + Anchor anchor = anchor(siteX, siteZ); + if (!anchor.active()) { + continue; + } + double distance = Math.hypot(x - anchor.x(), z - anchor.z()); + boolean foreign = !anchor.owner().equals(window); + if (foreign) { + nearestForeign = Math.min(nearestForeign, distance); + } + if (distance < nearest) { + second = nearest; + nearest = distance; + nearestIsForeign = foreign; + } else if (distance < second) { + second = distance; + } + } + } + if (nearestForeign == Double.POSITIVE_INFINITY) { + return false; + } + double others = nearestIsForeign && nearestForeign == nearest ? second : nearest; + return nearestForeign + territory - 2D * clearance <= others; + } + + public float armGroundLimit() { + return settings.seaLevel() + FAR_BANK_SHARE * gradedHeight; + } + private List own(WindowKey window) { int spacing = config.spacing(); int minSiteX = Math.floorDiv(window.wx() * WindowKey.SIZE, spacing); @@ -361,9 +404,7 @@ public final class TidalPlanner { return -1; } - private static float[] coastDistance(Land land) { - DemGrid grid = land.grid(); - boolean[] ocean = land.samples().ocean(); + public static float[] coastDistance(DemGrid grid, boolean[] ocean) { int width = grid.width(); int depth = grid.depth(); float[] distance = new float[width * depth]; diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveCeilingMask.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveCeilingMask.java index 924d3d14b..7efc4e4cc 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveCeilingMask.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/CaveCeilingMask.java @@ -54,6 +54,40 @@ public final class CaveCeilingMask { return masked; } + public static int[] grottoTops(int chunkX, int chunkZ, int shell, ChunkRasters rasters) { + int span = CHUNK + 2 * shell; + int field = span + 2 * CONTAINMENT; + int[] ceilings = new int[field * field]; + int originX = (chunkX << 4) - shell - CONTAINMENT; + int originZ = (chunkZ << 4) - shell - CONTAINMENT; + ChunkWaterRaster[] around = new ChunkWaterRaster[9]; + for (int fz = 0; fz < field; fz++) { + int z = originZ + fz; + for (int fx = 0; fx < field; fx++) { + int x = originX + fx; + int slot = ((z >> 4) - chunkZ + 1) * 3 + (x >> 4) - chunkX + 1; + if (around[slot] == null) { + around[slot] = ready(rasters.raster(x >> 4, z >> 4), x >> 4, z >> 4); + } + int ceiling = around[slot].caveCeiling(x & 15, z & 15); + ceilings[fz * field + fx] = ceiling == UNMASKED ? UNMASKED : ceiling - ROOF; + } + } + int[] tops = new int[span * span]; + for (int gz = 0; gz < span; gz++) { + for (int gx = 0; gx < span; gx++) { + int top = UNMASKED; + for (int fz = gz; fz <= gz + 2 * CONTAINMENT; fz++) { + for (int fx = gx; fx <= gx + 2 * CONTAINMENT; fx++) { + top = Math.min(top, ceilings[fz * field + fx]); + } + } + tops[gz * span + gx] = top; + } + } + return tops; + } + public static ChunkWaterRaster ready(ChunkWaterRaster raster, int chunkX, int chunkZ) { if (raster.provisional()) { throw new IllegalStateException("The water raster for chunk " + chunkX + "," + chunkZ diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvedTerrain.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvedTerrain.java index d1bc2c71a..001e765d9 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvedTerrain.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvedTerrain.java @@ -5,6 +5,8 @@ import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.underground.CarvedTerrain; import art.arcane.iris.generation.hydrology.underground.CaveVoxel; +import art.arcane.iris.generation.hydrology.underground.Grotto; +import art.arcane.iris.generation.hydrology.underground.GrottoSpace; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.stream.ProvisionalSampling; @@ -21,7 +23,10 @@ import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; final class MantleCarvedTerrain implements CarvedTerrain { private static final int SPAN = 48; @@ -44,6 +49,7 @@ final class MantleCarvedTerrain implements CarvedTerrain { private final SubterrainPlanner planner; private final List features; private final boolean terrain3D; + private final GrottoSpace grottos; private final MantleChunk[] chunks; private final boolean[] existing; private final int[] surfaces = new int[SPAN * SPAN]; @@ -65,6 +71,7 @@ final class MantleCarvedTerrain implements CarvedTerrain { this.minimumY = engine.getWorld().minHeight(); HydrologyRuntime runtime = complex.getHydrologyRuntime(); this.caveFluids = runtime.caveFluidPolicies(); + this.grottos = GrottoSpace.of(grottos(runtime, chunkX, chunkZ), originX, originZ, SPAN); SubterrainPlanner subterrain = complex.getSubterrainPlanner(); List plans = subterrain == null || subterrain.isEmpty() ? List.of() : subterrain.plansForBounds(originX, originZ, originX + SPAN - 1, originZ + SPAN - 1); @@ -81,7 +88,7 @@ final class MantleCarvedTerrain implements CarvedTerrain { @Override public CaveVoxel voxel(int x, int y, int z) { int column = column(x, z); - if (y <= 0 || y >= height || existing(x, z) || y > surface(x, z, column)) { + if (y <= 0 || y >= height || existing(x, z) || y > surface(x, z, column) || grottos.contains(x, y, z)) { return CaveVoxel.FOREIGN; } if (planner != null && planner.sample(features, x, y + minimumY, z).owned()) { @@ -142,6 +149,18 @@ final class MantleCarvedTerrain implements CarvedTerrain { return false; } + private static Collection grottos(HydrologyRuntime runtime, int chunkX, int chunkZ) { + Map grottos = new LinkedHashMap<>(); + for (int offsetZ = -1; offsetZ <= 1; offsetZ++) { + for (int offsetX = -1; offsetX <= 1; offsetX++) { + for (Grotto grotto : runtime.grottos(chunkX + offsetX, chunkZ + offsetZ)) { + grottos.putIfAbsent(grotto.id(), grotto); + } + } + } + return grottos.values(); + } + private int surface(int x, int z, int column) { int known = surfaces[column]; if (known == UNKNOWN) { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleHydrologyComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleHydrologyComponent.java index f38aac877..641442da7 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleHydrologyComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleHydrologyComponent.java @@ -12,6 +12,8 @@ import art.arcane.iris.generation.hydrology.raster.FluidSeams; import art.arcane.iris.generation.hydrology.underground.CarvedTerrain; import art.arcane.iris.generation.hydrology.underground.CavePoolFiller; import art.arcane.iris.generation.hydrology.underground.CaveSpringPlacer; +import art.arcane.iris.generation.hydrology.underground.Grotto; +import art.arcane.iris.generation.hydrology.underground.GrottoRasterizer; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.subterrain.SubterrainPlan; @@ -33,6 +35,7 @@ public final class MantleHydrologyComponent extends IrisMantleComponent { private static final int CHUNK = 16; private static final int GRID = CHUNK + 2; private static final int[] SIDES = {1, -1, GRID, -GRID}; + private static final GrottoRasterizer GROTTOS = new GrottoRasterizer(); public MantleHydrologyComponent(EngineMantle engineMantle) { super(engineMantle, ReservedFlag.RIVER_HYDROLOGY, PRIORITY); @@ -81,6 +84,13 @@ public final class MantleHydrologyComponent extends IrisMantleComponent { } HydrologyRuntime runtime = complex.getHydrologyRuntime(); ChunkWaterRaster own = CaveCeilingMask.ready(runtime.raster(chunkX, chunkZ), chunkX, chunkZ); + List grottos = runtime.grottos(chunkX, chunkZ); + if (!grottos.isEmpty()) { + GrottoRasterizer.Exclusion exclusion = grottoExclusion(writer, complex, runtime, chunkX, chunkZ); + for (Grotto grotto : grottos) { + GROTTOS.write(grotto, chunkX, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, exclusion); + } + } generateFalls(writer, complex, runtime, own, chunkX, chunkZ); if (caveWaterActive()) { HydrologySettings settings = runtime.settings(); @@ -97,6 +107,43 @@ public final class MantleHydrologyComponent extends IrisMantleComponent { } } + private static GrottoRasterizer.Exclusion grottoExclusion(MantleWriter writer, IrisComplex complex, HydrologyRuntime runtime, int chunkX, int chunkZ) { + int shell = GrottoRasterizer.SHELL; + int span = CHUNK + 2 * shell; + int originX = (chunkX << 4) - shell; + int originZ = (chunkZ << 4) - shell; + int[] tops = CaveCeilingMask.grottoTops(chunkX, chunkZ, shell, runtime::raster); + boolean[] historical = new boolean[9]; + for (int slot = 0; slot < historical.length; slot++) { + historical[slot] = complex.isHistoricalChunk(chunkX + slot % 3 - 1, chunkZ + slot / 3 - 1); + } + SubterrainPlanner planner = complex.getSubterrainPlanner(); + List plans = planner == null || planner.isEmpty() ? List.of() + : planner.plansForBounds(originX, originZ, originX + span - 1, originZ + span - 1); + int minimumY = plans.isEmpty() ? 0 : writer.getEngine().getWorld().minHeight(); + return (x, y, z) -> { + int gx = x - originX; + int gz = z - originZ; + if (y > tops[gz * span + gx] || besideHistorical(historical, x, z, chunkX, chunkZ, shell)) { + return true; + } + return !plans.isEmpty() && planner.sample(plans, x, y + minimumY, z).owned(); + }; + } + + private static boolean besideHistorical(boolean[] historical, int x, int z, int chunkX, int chunkZ, int shell) { + for (int dz = -shell; dz <= shell; dz += shell) { + for (int dx = -shell; dx <= shell; dx += shell) { + int slotX = ((x + dx) >> 4) - chunkX + 1; + int slotZ = ((z + dz) >> 4) - chunkZ + 1; + if (slotX >= 0 && slotX < 3 && slotZ >= 0 && slotZ < 3 && historical[slotZ * 3 + slotX]) { + return true; + } + } + } + return false; + } + private void generateFalls(MantleWriter writer, IrisComplex complex, HydrologyRuntime runtime, ChunkWaterRaster own, int chunkX, int chunkZ) { if (!holdsWater(own)) { diff --git a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java index 9e41920b5..13e5bd386 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java @@ -43,6 +43,10 @@ final class PackHydrologyValidator { new RangeField("underground.seaInlets.mouthHalfWidth", Floor.POSITIVE, false), new RangeField("underground.seaInlets.headHalfWidth", Floor.POSITIVE, false), new RangeField("underground.seaInlets.depth", Floor.POSITIVE, true), + new RangeField("underground.grottos.radius", Floor.POSITIVE, false), + new RangeField("underground.grottos.headroom", Floor.POSITIVE, true), + new RangeField("underground.grottos.mouthWidth", Floor.POSITIVE, false), + new RangeField("underground.grottos.length", Floor.POSITIVE, true), new RangeField("underground.cavePools.freeboard", Floor.NON_NEGATIVE, true) ); private static final List FLUID_REFERENCES = List.of("ponds.fluid", "underground.cavePools.fluid"); diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverLimits.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverLimits.java index ebb3cd3b3..ecbcf5f36 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverLimits.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverLimits.java @@ -70,6 +70,9 @@ final class RiverLimits { if (settings.underground().seaInlets().enabled()) { add(ExportLimit.SEA_INLET, hydrology, "", "Sea inlets are not exported: low coasts have no tidal arms"); } + if (settings.underground().grottos().enabled()) { + add(ExportLimit.GROTTO, hydrology, "", "Grottos are not exported: tall coasts have no sea caves"); + } if (settings.underground().cavePools().enabled() && settings.underground().cavePools().density() > 0.0F) { add(ExportLimit.CAVE_POOL, hydrology, "", "Cave pools are not exported: cave floors hold no standing water of their own"); } diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/ir/ExportLimit.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/ir/ExportLimit.java index eb3768d5d..044e7f4be 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/ir/ExportLimit.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/ir/ExportLimit.java @@ -37,6 +37,7 @@ public enum ExportLimit { RIVER_SHORE_BIOME, RIVER_DECORATOR, SEA_INLET, + GROTTO, CAVE_POOL, DATAPACK_VERSION, DATAPACK_COLLISION, diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapView.java b/core/src/main/java/art/arcane/iris/studio/map/MapView.java index d7e055184..aa02188b5 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/MapView.java +++ b/core/src/main/java/art/arcane/iris/studio/map/MapView.java @@ -30,7 +30,7 @@ enum MapView { REGIONS("Regions", "The region each spot belongs to; pick one to see the biomes it places", Group.WORLD, TileType.REGION, KeyEvent.VK_2), HEIGHT("Height", "Terrain height, from deep water to snowy peaks", Group.WORLD, TileType.HEIGHT, KeyEvent.VK_3), - RIVERS("Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets and cave pools from the hydrology", + RIVERS("Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets, grottos and cave pools from the hydrology", Group.WORLD, TileType.RIVER, KeyEvent.VK_4), WORLD_3D("3D world", "The terrain in 3D, coloured by biome or region", Group.WORLD, null, KeyEvent.VK_5), LAND_BIOMES("Land biomes", "The land biome each spot would get, also where the sea is", diff --git a/core/src/main/java/art/arcane/iris/studio/render/IrisRenderer.java b/core/src/main/java/art/arcane/iris/studio/render/IrisRenderer.java index 914199cde..35502c31e 100644 --- a/core/src/main/java/art/arcane/iris/studio/render/IrisRenderer.java +++ b/core/src/main/java/art/arcane/iris/studio/render/IrisRenderer.java @@ -54,6 +54,7 @@ public final class IrisRenderer { private static final int WATER_LAKE = new Color(40, 96, 140).getRGB(); private static final int WATER_DAM = new Color(150, 120, 84).getRGB(); private static final int WATER_SEA_INLET = new Color(51, 174, 174).getRGB(); + private static final int WATER_GROTTO = new Color(150, 80, 200).getRGB(); private static final int WATER_CAVE_POOL = new Color(102, 86, 196).getRGB(); private static final int NO_RIVER = new Color(28, 31, 38).getRGB(); private static final double RIVER_OVERLAY = 0.72D; @@ -143,6 +144,7 @@ public final class IrisRenderer { case LAKE -> WATER_LAKE; case DAM -> WATER_DAM; case SEA_INLET -> WATER_SEA_INLET; + case GROTTO -> WATER_GROTTO; case CAVE_POOL -> WATER_CAVE_POOL; }; } diff --git a/core/src/main/java/art/arcane/iris/studio/render/WaterMap.java b/core/src/main/java/art/arcane/iris/studio/render/WaterMap.java index 00b3b7b56..6c49fa90f 100644 --- a/core/src/main/java/art/arcane/iris/studio/render/WaterMap.java +++ b/core/src/main/java/art/arcane/iris/studio/render/WaterMap.java @@ -5,6 +5,7 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; import art.arcane.iris.generation.hydrology.water.HydrologyTier; +import art.arcane.iris.generation.hydrology.underground.Grotto; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.PondMask; import art.arcane.iris.generation.hydrology.water.Reach; @@ -32,6 +33,7 @@ final class WaterMap { private final double startX; private final double startZ; private final double step; + private List grottos = List.of(); private final int[] ranks; private final boolean[] resolved; private final IdentityHashMap channels = new IdentityHashMap<>(); @@ -70,9 +72,11 @@ final class WaterMap { prepareFallback(plans); } plansComplete = plans.complete(); + grottos = plans.grottos(); } if (step <= RASTER_STEP) { provisional = drawRasters(plans) || !plansComplete; + drawGrottos(); } else { prepareFallback(plans); System.arraycopy(plannedRanks, 0, ranks, 0, ranks.length); @@ -193,6 +197,21 @@ final class WaterMap { for (Pond lake : plans.lakes()) { drawMask(lake.mask(), HydrologyFeatureType.LAKE); } + grottos = plans.grottos(); + drawGrottos(); + } + + private void drawGrottos() { + for (Grotto grotto : grottos) { + checkCancelled(); + float[] xs = grotto.xs(); + float[] zs = grotto.zs(); + float[] halfWidth = grotto.halfWidth(); + for (int point = 0; point + 1 < xs.length; point++) { + double radius = Math.max(halfWidth[point], halfWidth[point + 1]) + step / 2D; + drawSegment(xs[point], zs[point], xs[point + 1], zs[point + 1], radius, HydrologyFeatureType.GROTTO); + } + } } private void drawReach(Reach reach) { @@ -291,10 +310,11 @@ final class WaterMap { case RIVER -> 4; case STREAM -> 5; case SEA_INLET -> 6; - case POND -> 7; - case LAKE -> 8; - case DAM -> 9; - case CAVE_POOL -> 10; + case GROTTO -> 7; + case POND -> 8; + case LAKE -> 9; + case DAM -> 10; + case CAVE_POOL -> 11; }; } diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticCapture.java b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticCapture.java index 62d257d48..e362f25af 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticCapture.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticCapture.java @@ -18,6 +18,7 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; import art.arcane.iris.generation.hydrology.raster.WaterRole; +import art.arcane.iris.generation.hydrology.underground.Grotto; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.terrain.IrisRegion; @@ -159,6 +160,7 @@ public final class GenerationSemanticCapture { int minimumX = Math.multiplyExact(chunkX, CHUNK_SIZE); int minimumZ = Math.multiplyExact(chunkZ, CHUNK_SIZE); int minimumY = engine.getDimension().getMinHeight(); + captureGrottoMouths(runtime, chunkX, chunkZ, minimumY, semantics); if (raster.empty()) { return; } @@ -195,6 +197,15 @@ public final class GenerationSemanticCapture { } } + private static void captureGrottoMouths(HydrologyRuntime runtime, int chunkX, int chunkZ, int minimumY, ChunkGenerationSemantics.Builder semantics) { + for (Grotto grotto : runtime.grottos(chunkX, chunkZ)) { + if (grotto.mouthX() >> 4 == chunkX && grotto.mouthZ() >> 4 == chunkZ) { + semantics.addRiverFeature(HydrologyFeatureType.GROTTO.key(), HydrologyFeatureType.GROTTO, grotto.id(), grotto.mouthX(), + Math.addExact(grotto.seaLevel(), minimumY), grotto.mouthZ()); + } + } + } + private static Set flowingTypes(HydrologyRuntime runtime, WaterRole role, HydrologyTier tier) { return switch (role) { case CHANNEL -> Set.of(runtime.channelType(tier)); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/PersistedCodesTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/PersistedCodesTest.java index be2ed9f4a..1377b5436 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/PersistedCodesTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/PersistedCodesTest.java @@ -30,7 +30,8 @@ public class PersistedCodesTest { Map.entry(HydrologyFeatureType.LAKE, 7), Map.entry(HydrologyFeatureType.DAM, 8), Map.entry(HydrologyFeatureType.SEA_INLET, 9), - Map.entry(HydrologyFeatureType.CAVE_POOL, 10)); + Map.entry(HydrologyFeatureType.CAVE_POOL, 10), + Map.entry(HydrologyFeatureType.GROTTO, 11)); private static final Map REACH_STYLE_CODES = Map.of( ReachStyle.RUN, 0, ReachStyle.RIFFLE, 1, diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearchTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearchTest.java index 94ee0b281..6b4874f29 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearchTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearchTest.java @@ -78,12 +78,15 @@ public class HydrologyFeatureSearchTest { config.getPonds().getDams().setEnabled(true); config.getUnderground().getSeaInlets().setEnabled(false); config.getUnderground().getCavePools().setEnabled(false); + config.getUnderground().getGrottos().setEnabled(false); }); String ponds = "hydrology.ponds.natural and hydrology.ponds.seeded are disabled"; assertEquals(Optional.of(ponds), HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.POND)); assertEquals(Optional.of(ponds), HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.DAM)); assertEquals(Optional.of("hydrology.underground.seaInlets is disabled"), HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.SEA_INLET)); + assertEquals(Optional.of("hydrology.underground.grottos is disabled"), + HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.GROTTO)); assertEquals(Optional.of("hydrology.underground.cavePools is disabled"), HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.CAVE_POOL)); assertEquals(Optional.empty(), HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.LAKE)); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntimeTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntimeTest.java index a1fb8b222..86d9c34f7 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntimeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntimeTest.java @@ -16,6 +16,7 @@ import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; import art.arcane.iris.generation.hydrology.raster.WaterRole; +import art.arcane.iris.generation.hydrology.underground.Grotto; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.PondKind; import art.arcane.iris.generation.hydrology.water.PondMask; @@ -348,6 +349,18 @@ public class HydrologyRuntimeTest { assertEquals(List.of(INLET), runtime.planPreview(900, 300, 1100, 500).reaches().stream().map(Reach::id).filter(id -> id == INLET).toList()); } + @Test(timeout = 180_000L) + public void grottosAreSearchedAtTheirMouthsAndListedByChunk() throws Exception { + FakePlanners planners = new FakePlanners(settings()); + HydrologyRuntime runtime = runtime(planners, () -> false); + Grotto grotto = FakePlanners.grotto(); + assertEquals(new HydrologyFeatureRef(grotto.id(), HydrologyFeatureType.GROTTO, grotto.mouthX(), grotto.seaLevel(), grotto.mouthZ()), + runtime.nearestFeature(1050, 405, HydrologyFeatureQuery.of(HydrologyFeatureType.GROTTO), 512, ANY, RUNNING).orElseThrow()); + assertEquals(List.of(grotto), runtime.grottos(grotto.mouthX() >> 4, grotto.mouthZ() >> 4)); + assertEquals(List.of(), runtime.grottos(0, 0)); + assertEquals(List.of(grotto), runtime.planPreview(900, 300, 1100, 500).grottos()); + } + @Test(timeout = 180_000L) public void nearestFeatureSkipsIneligibleCandidatesForTheNextNearest() throws Exception { FakePlanners planners = new FakePlanners(settings()); @@ -1282,7 +1295,7 @@ public class HydrologyRuntimeTest { pond(POND + 1, PondKind.SEEDED, 70, 296, 296, 3))); } if (key.equals(new WindowKey(1, 0))) { - return new WindowPlan(key, List.of(tidal()), List.of()); + return new WindowPlan(key, List.of(tidal()), List.of(), List.of(grotto())); } if (key.equals(new WindowKey(3, 0))) { return new WindowPlan(key, List.of(), List.of(pond(FAR_POND, PondKind.NATURAL, 75, 1700, 100, 3))); @@ -1308,6 +1321,11 @@ public class HydrologyRuntimeTest { } } + static Grotto grotto() { + return new Grotto(0x47524FL, 40, 0.5f, 1, new float[]{1090f, 1080f, 1070f, 1060f}, new float[]{420f, 420f, 424f, 430f}, new float[]{6f, 6f, 5f, 5f}, + new float[]{6f, 6f, 6f, 6f}, new float[]{3f, 3f, 3f, 3f}, new float[]{0f, 0f, 0f, 0f}, new float[0], new float[0], new float[0], new int[0], new long[0]); + } + private Reach tidal() { int points = 13; float[] xs = new float[points]; diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/GrottoPlannerTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/GrottoPlannerTest.java new file mode 100644 index 000000000..c40c93411 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/GrottoPlannerTest.java @@ -0,0 +1,273 @@ +package art.arcane.iris.generation.hydrology.plan; + +import art.arcane.iris.generation.hydrology.config.IrisHydrology; +import art.arcane.iris.generation.hydrology.grid.DemGrid; +import art.arcane.iris.generation.hydrology.grid.HeightLattice; +import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer; +import art.arcane.iris.generation.hydrology.underground.Grotto; +import art.arcane.iris.generation.hydrology.underground.GrottoPlanner; +import art.arcane.iris.generation.hydrology.underground.GrottoShape; +import art.arcane.iris.generation.hydrology.water.Reach; +import art.arcane.iris.generation.hydrology.water.ReachStyle; +import art.arcane.iris.generation.hydrology.water.ShapedNetwork; +import art.arcane.iris.generation.hydrology.water.TidalPlanner; +import org.junit.Test; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class GrottoPlannerTest { + private static final long SEED = 1337L; + private static final int SEA = SyntheticTerrain.SEA_LEVEL; + private static final double COAST_X = 300D; + private static final ShapedNetwork NOTHING = new ShapedNetwork(List.of(), List.of()); + private static final List WINDOWS = List.of(new WindowKey(0, -1), new WindowKey(0, 0), new WindowKey(0, 1), new WindowKey(-1, 0), new WindowKey(1, 0), new WindowKey(0, 2)); + + private static HydrologySettings settings(IrisHydrology config) { + return HydrologySettings.compile(config, SEED, SEA, SyntheticTerrain.MIN_Y, SyntheticTerrain.MAX_Y); + } + + private static SyntheticTerrain tallCoast() { + return SyntheticTerrain.cliffCoast(COAST_X); + } + + private record Fixture(GrottoPlanner planner, HeightLattice fine) { + Fixture(HydrologySettings settings, SyntheticTerrain terrain) { + this(settings, new HeightLattice(terrain, WindowPlanner.FINE_CELL, false, 1 << 21)); + } + + Fixture(HydrologySettings settings, HeightLattice lattice) { + this(new GrottoPlanner(settings, lattice, new TidalPlanner(settings, lattice)), lattice); + } + + List plan(WindowKey window, ShapedNetwork network, List arms) { + int span = 3 * WindowKey.SIZE / WindowPlanner.CELL; + int originX = (window.wx() - 1) * WindowKey.SIZE; + int originZ = (window.wz() - 1) * WindowKey.SIZE; + HydrologySampleBuffer samples = new HydrologySampleBuffer(span * span); + fine.fill(originX / WindowPlanner.FINE_CELL, originZ / WindowPlanner.FINE_CELL, span, span, WindowPlanner.CELL / WindowPlanner.FINE_CELL, samples); + DemGrid natural = new DemGrid(originX, originZ, WindowPlanner.CELL, span, span); + System.arraycopy(samples.height(), 0, natural.values(), 0, span * span); + return planner.plan(window, natural, samples, network, arms); + } + + List plan(List windows) { + List grottos = new ArrayList<>(); + for (WindowKey window : windows) { + grottos.addAll(plan(window, NOTHING, List.of())); + } + return grottos; + } + } + + private static double length(Grotto grotto) { + double total = 0D; + for (int point = grotto.coast() + 1; point < grotto.xs().length; point++) { + total += Math.hypot(grotto.xs()[point] - grotto.xs()[point - 1], grotto.zs()[point] - grotto.zs()[point - 1]); + } + return total; + } + + @Test + public void tallCoastHoldsLongWindingGrottosThatStartInTheSea() { + HydrologySettings settings = settings(new IrisHydrology()); + SyntheticTerrain terrain = tallCoast(); + List grottos = new Fixture(settings, terrain).plan(WINDOWS); + assertTrue("grottos " + grottos.size(), grottos.size() >= 2); + int winding = 0; + for (Grotto grotto : grottos) { + assertEquals(SEA, grotto.seaLevel()); + assertTrue(grotto + " starts at sea " + grotto.xs()[0], grotto.xs()[0] < COAST_X); + int last = grotto.xs().length - 1; + assertTrue("head inland " + grotto.xs()[last], grotto.xs()[last] > COAST_X + 16f); + assertTrue("length " + length(grotto), length(grotto) >= settings.underground().grottos().length().min()); + double straight = Math.hypot(grotto.xs()[last] - grotto.xs()[grotto.coast()], grotto.zs()[last] - grotto.zs()[grotto.coast()]); + winding += length(grotto) / straight >= 1.15D ? 1 : 0; + assertTrue(new GrottoShape(grotto).inside((int) Math.floor(grotto.xs()[0]), SEA, (int) Math.floor(grotto.zs()[0]))); + } + assertTrue("winding " + winding + " of " + grottos.size(), winding * 2 >= grottos.size()); + } + + @Test + public void lowCoastHoldsNoGrottos() { + assertTrue(new Fixture(settings(new IrisHydrology()), SyntheticTerrain.lowCoast(COAST_X)).plan(WINDOWS).isEmpty()); + } + + @Test + public void disabledHoldsNoGrottos() { + IrisHydrology config = new IrisHydrology(); + config.getUnderground().getGrottos().setEnabled(false); + assertTrue(new Fixture(settings(config), tallCoast()).plan(WINDOWS).isEmpty()); + } + + @Test + public void everyWetCellConnectsToTheSea() { + HydrologySettings settings = settings(new IrisHydrology()); + for (Grotto grotto : new Fixture(settings, tallCoast()).plan(WINDOWS)) { + GrottoShape shape = new GrottoShape(grotto); + int[] bounds = grotto.bounds(); + int layers = SEA - shape.minY() + 1; + int width = bounds[2] - bounds[0] + 1; + int depth = bounds[3] - bounds[1] + 1; + boolean[] wet = new boolean[width * depth * layers]; + long total = 0L; + for (int z = 0; z < depth; z++) { + for (int x = 0; x < width; x++) { + if (shape.near(bounds[0] + x, bounds[1] + z)) { + for (int layer = 0; layer < layers; layer++) { + if (shape.inside(bounds[0] + x, shape.minY() + layer, bounds[1] + z)) { + wet[(layer * depth + z) * width + x] = true; + total++; + } + } + } + } + } + int start = ((layers - 1) * depth + ((int) Math.floor(grotto.zs()[0]) - bounds[1])) * width + (int) Math.floor(grotto.xs()[0]) - bounds[0]; + assertTrue(wet[start]); + ArrayDeque frontier = new ArrayDeque<>(); + frontier.add(start); + wet[start] = false; + long reached = 1L; + while (!frontier.isEmpty()) { + int cell = frontier.poll(); + for (int offset : new int[]{1, -1, width, -width, width * depth, -width * depth}) { + int next = cell + offset; + if (next >= 0 && next < wet.length && wet[next]) { + wet[next] = false; + reached++; + frontier.add(next); + } + } + } + assertEquals("grotto " + grotto.id(), total, reached); + } + } + + @Test + public void grottosNeverJoin() { + HydrologySettings settings = settings(new IrisHydrology()); + List grottos = new Fixture(settings, tallCoast()).plan(WINDOWS); + for (int a = 0; a < grottos.size(); a++) { + for (int b = a + 1; b < grottos.size(); b++) { + GrottoShape first = new GrottoShape(grottos.get(a)); + GrottoShape second = new GrottoShape(grottos.get(b)); + int[] bounds = grottos.get(a).bounds(); + for (int z = bounds[1]; z <= bounds[3]; z += 2) { + for (int x = bounds[0]; x <= bounds[2]; x += 2) { + if (first.near(x, z) && second.near(x, z)) { + for (int y = SEA - 8; y <= SEA + 20; y += 2) { + assertFalse(x + "," + y + "," + z, first.inside(x, y, z) && second.inside(x, y, z)); + } + } + } + } + } + } + } + + @Test + public void planIgnoresWindowOrderAndRepeats() { + HydrologySettings settings = settings(new IrisHydrology()); + SyntheticTerrain terrain = tallCoast(); + List reversed = new ArrayList<>(WINDOWS); + Collections.reverse(reversed); + List forward = new Fixture(settings, terrain).plan(WINDOWS); + List backward = new Fixture(settings, terrain).plan(reversed); + forward.sort(Comparator.comparingLong(Grotto::id)); + backward.sort(Comparator.comparingLong(Grotto::id)); + assertEquals(forward.size(), backward.size()); + for (int index = 0; index < forward.size(); index++) { + assertEquals(forward.get(index).id(), backward.get(index).id()); + assertArrayEquals(forward.get(index).xs(), backward.get(index).xs(), 0f); + assertArrayEquals(forward.get(index).roof(), backward.get(index).roof(), 0f); + assertArrayEquals(forward.get(index).plugs(), backward.get(index).plugs()); + } + } + + @Test + public void grottosKeepClearOfRiversAndArms() { + HydrologySettings settings = settings(new IrisHydrology()); + SyntheticTerrain terrain = tallCoast(); + Fixture fixture = new Fixture(settings, terrain); + WindowKey window = null; + Grotto clear = null; + for (WindowKey key : WINDOWS) { + List grottos = fixture.plan(key, NOTHING, List.of()); + if (!grottos.isEmpty()) { + window = key; + clear = grottos.get(0); + break; + } + } + assertTrue(clear != null); + int middle = clear.xs().length / 2; + float[] xs = new float[81]; + float[] zs = new float[81]; + int[] grade = new int[81]; + float[] half = new float[81]; + float[] depth = new float[81]; + ReachStyle[] style = new ReachStyle[81]; + for (int point = 0; point < 81; point++) { + xs[point] = clear.xs()[middle]; + zs[point] = clear.zs()[middle] - 200f + point * 5f; + grade[point] = SEA + 10; + half[point] = 4f; + depth[point] = 2f; + style[point] = ReachStyle.RUN; + } + Reach dense = new Reach(1L, settings.tidalTier(), 0L, xs, zs, grade, half, depth, style, 0f); + float apart = dense.tier().bankBand(); + for (Grotto grotto : fixture.plan(window, new ShapedNetwork(List.of(dense), List.of()), List.of())) { + for (int point = 0; point < grotto.xs().length; point++) { + for (int river2 = 0; river2 < xs.length; river2++) { + assertTrue("station " + point, Math.hypot(grotto.xs()[point] - xs[river2], grotto.zs()[point] - zs[river2]) > half[river2] + Math.min(apart, 32f) - 12f); + } + } + } + } + + @Test + public void walkKeepsOutOfTheTerritoryOfArmsOwnedByOtherWindows() { + IrisHydrology config = new IrisHydrology(); + HydrologySettings settings = settings(config); + SyntheticTerrain low = SyntheticTerrain.lowCoast(COAST_X); + TidalPlanner tidal = new TidalPlanner(settings, new HeightLattice(low, WindowPlanner.FINE_CELL, false, 1 << 21)); + boolean foreign = false; + boolean own = false; + for (int z = -800; z <= 800; z += 16) { + WindowKey window = WindowKey.containing((int) COAST_X, z); + boolean here = tidal.foreignArmMayReach(window, COAST_X + 30D, z, 16f); + boolean elsewhere = tidal.foreignArmMayReach(new WindowKey(window.wx() + 7, window.wz()), COAST_X + 30D, z, 16f); + own |= !here; + foreign |= elsewhere; + assertTrue("every anchor is foreign to a far window", !here || elsewhere); + } + assertTrue(own); + assertTrue(foreign); + config.getUnderground().getSeaInlets().setEnabled(false); + TidalPlanner off = new TidalPlanner(settings(config), new HeightLattice(low, WindowPlanner.FINE_CELL, false, 1 << 21)); + assertFalse(off.foreignArmMayReach(new WindowKey(9, 9), COAST_X + 30D, 0D, 16f)); + } + + @Test + public void everyGrottoStaysWithinTheNextWindow() { + HydrologySettings settings = settings(new IrisHydrology()); + Fixture fixture = new Fixture(settings, tallCoast()); + for (WindowKey window : WINDOWS) { + for (Grotto grotto : fixture.plan(window, NOTHING, List.of())) { + int[] bounds = grotto.bounds(); + assertTrue(bounds[0] >= (window.wx() - 1) * WindowKey.SIZE && bounds[2] < (window.wx() + 2) * WindowKey.SIZE); + assertTrue(bounds[1] >= (window.wz() - 1) * WindowKey.SIZE && bounds[3] < (window.wz() + 2) * WindowKey.SIZE); + } + } + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/HydrologyPlanCodecTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/HydrologyPlanCodecTest.java index b7eff9519..4bf4471a8 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/HydrologyPlanCodecTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/HydrologyPlanCodecTest.java @@ -4,6 +4,7 @@ import art.arcane.iris.generation.hydrology.config.IrisBankStyle; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrologyMaterials; import art.arcane.iris.generation.hydrology.grid.HeightLattice; +import art.arcane.iris.generation.hydrology.underground.Grotto; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.PondKind; @@ -46,7 +47,7 @@ public class HydrologyPlanCodecTest { 0577617465720000001c000000060000000000000007020000004400000040ffffffec0000001042898000fffffffc00 00000800000004000000000000000000000000000000000000002900000002000000046c617661ffffffea0000000e00 0000000000000803000000500000003c00000040ffffffc042a10000fffffffc00000008000000040000000000000000 - 00000000ffffffffffffffff00000000ffffffff0000003cffffffc4 + 00000000ffffffffffffffff00000000ffffffff0000003cffffffc400000000 """; @Test @@ -99,6 +100,17 @@ public class HydrologyPlanCodecTest { assertBitExact(planned, HydrologyPlanCodec.decodeWindow(settings, HydrologyPlanCodec.encode(settings, planned)).orElseThrow(), tiers); } + @Test + public void grottosRoundTripBitExact() { + HydrologySettings settings = settings(new IrisHydrology()); + Grotto grotto = new Grotto(99L, 40, 0.6f, 1, new float[]{1.5f, 5.25f, 9f}, new float[]{-2f, -3f, -4f}, new float[]{6f, 7f, 5f}, new float[]{8f, 9f, 6f}, new float[]{3f, 4f, 3f}, + new float[]{0f, 0f, 2f}, new float[]{5f}, new float[]{-3f}, new float[]{2f}, new int[]{70}, new long[]{Grotto.plug(3, 39, -2), Grotto.plug(4, 39, -2)}); + WindowPlan window = new WindowPlan(new WindowKey(4, -2), List.of(), List.of(), List.of(grotto)); + WindowPlan decoded = HydrologyPlanCodec.decodeWindow(settings, HydrologyPlanCodec.encode(settings, window)).orElseThrow(); + assertEquals(window, decoded); + assertEquals(grotto.hashCode(), decoded.grottos().get(0).hashCode()); + } + @Test public void tidalReachesRoundTripOnTheTidalTier() { HydrologySettings settings = settings(new IrisHydrology()); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/HydrologySettingsTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/HydrologySettingsTest.java index f49fe5308..f977c6303 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/HydrologySettingsTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/HydrologySettingsTest.java @@ -8,6 +8,7 @@ import art.arcane.iris.generation.hydrology.config.IrisBankStyle; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier; import art.arcane.iris.generation.hydrology.config.IrisHydrologyMaterials; +import art.arcane.iris.generation.hydrology.config.IrisGrottos; import art.arcane.iris.generation.hydrology.config.IrisSeaInlets; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.terrain.IrisMaterialPalette; @@ -38,7 +39,7 @@ public class HydrologySettingsTest { private static final int SEA_LEVEL = 62; private static final int MIN_Y = -64; private static final int MAX_Y = 320; - private static final long DEFAULT_FINGERPRINT = 8483795183515434045L; + private static final long DEFAULT_FINGERPRINT = 2652772297681753957L; @Test public void densityIsBoundedAndChangesThePlanIdentity() { @@ -227,6 +228,12 @@ public class HydrologySettingsTest { IrisHydrology seaInlets = new IrisHydrology(); seaInlets.getUnderground().getSeaInlets().setSpacing(256); fingerprints.add(compile(seaInlets).fingerprint()); + IrisHydrology grottos = new IrisHydrology(); + grottos.getUnderground().getGrottos().setSpacing(320); + fingerprints.add(compile(grottos).fingerprint()); + IrisHydrology rougher = new IrisHydrology(); + rougher.getUnderground().getGrottos().setRoughness(0.2D); + fingerprints.add(compile(rougher).fingerprint()); IrisHydrology shoreDepth = new IrisHydrology(); shoreDepth.getPonds().getMaterials().setShoreDepth(3); @@ -764,6 +771,25 @@ public class HydrologySettingsTest { assertTrue(failure.getMessage(), failure.getMessage().contains("mouthHalfWidth")); } + @Test + public void grottoKnobsAreBounded() { + List> bad = List.of( + grottos -> grottos.setSpacing(16), + grottos -> grottos.setRadius(new KList<>(1D, 7D)), + grottos -> grottos.setRadius(new KList<>(4D, 40D)), + grottos -> grottos.setHeadroom(new KList<>(1, 7)), + grottos -> grottos.setHeadroom(new KList<>(4, 99)), + grottos -> grottos.setMouthWidth(new KList<>(1D, 8D)), + grottos -> grottos.setLength(new KList<>(32, 600)), + grottos -> grottos.setRoughness(1.5D)); + for (Consumer tweak : bad) { + IrisHydrology config = new IrisHydrology(); + tweak.accept(config.getUnderground().getGrottos()); + IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, () -> compile(config)); + assertTrue(failure.getMessage(), failure.getMessage().contains("underground.grottos")); + } + } + @Test public void overLongSeaInletsFailAtCompile() { compile(inlets(config -> config.setLength(new KList<>(64, 447)).setMouthHalfWidth(new KList<>(11D, 16D)).setBankBand(24))); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/GrottoRasterizerTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/GrottoRasterizerTest.java new file mode 100644 index 000000000..b69bca0cf --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/GrottoRasterizerTest.java @@ -0,0 +1,157 @@ +package art.arcane.iris.generation.hydrology.underground; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class GrottoRasterizerTest { + private static final int SEA = GrottoShapeTest.SEA; + + private static long key(int x, int z) { + return ((long) x << 32) | (z & 0xFFFFFFFFL); + } + + @Test + public void cellsMatchTheShapeInEveryChunk() { + Grotto grotto = GrottoShapeTest.winding(11L, 0.6f); + GrottoShape shape = new GrottoShape(grotto); + int[] bounds = grotto.bounds(); + long wet = 0L; + long dry = 0L; + for (int chunkZ = bounds[1] >> 4; chunkZ <= bounds[3] >> 4; chunkZ++) { + for (int chunkX = bounds[0] >> 4; chunkX <= bounds[2] >> 4; chunkX++) { + GrottoRasterizer.Cells cells = GrottoRasterizer.cells(grotto, chunkX, chunkZ, GrottoRasterizer.Exclusion.NOWHERE); + if (cells == null) { + continue; + } + for (int lz = 0; lz < 16; lz++) { + for (int lx = 0; lx < 16; lx++) { + for (int y = cells.minY(); y <= cells.maxY(); y++) { + int x = (chunkX << 4) + lx; + int z = (chunkZ << 4) + lz; + byte kind = cells.at(lx, y, lz); + boolean inside = shape.inside(x, y, z); + if (inside) { + assertEquals(x + "," + y + "," + z, y <= SEA ? GrottoRasterizer.WET : GrottoRasterizer.DRY, kind); + } else { + assertTrue(x + "," + y + "," + z + " kind " + kind, kind == GrottoRasterizer.NONE || kind == GrottoRasterizer.GUARD); + } + wet += kind == GrottoRasterizer.WET ? 1L : 0L; + dry += kind == GrottoRasterizer.DRY ? 1L : 0L; + } + } + } + } + } + assertTrue("wet " + wet, wet > 2000L); + assertTrue("dry " + dry, dry > 2000L); + } + + @Test + public void everyWetCellIsWalledByGuardAcrossChunkLines() { + Grotto grotto = GrottoShapeTest.winding(12L, 0.6f); + int[] bounds = grotto.bounds(); + Map chunks = new HashMap<>(); + for (int chunkZ = (bounds[1] >> 4) - 1; chunkZ <= (bounds[3] >> 4) + 1; chunkZ++) { + for (int chunkX = (bounds[0] >> 4) - 1; chunkX <= (bounds[2] >> 4) + 1; chunkX++) { + chunks.put(key(chunkX, chunkZ), GrottoRasterizer.cells(grotto, chunkX, chunkZ, GrottoRasterizer.Exclusion.NOWHERE)); + } + } + long checked = 0L; + for (Map.Entry entry : chunks.entrySet()) { + if (entry.getValue() == null) { + continue; + } + int chunkX = (int) (entry.getKey() >> 32); + int chunkZ = (int) (long) entry.getKey(); + GrottoRasterizer.Cells cells = entry.getValue(); + for (int lz = 0; lz < 16; lz++) { + for (int lx = 0; lx < 16; lx++) { + for (int y = cells.minY(); y <= SEA; y++) { + if (cells.at(lx, y, lz) != GrottoRasterizer.WET) { + continue; + } + int x = (chunkX << 4) + lx; + int z = (chunkZ << 4) + lz; + for (int[] side : new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) { + int nx = x + side[0]; + int nz = z + side[1]; + GrottoRasterizer.Cells other = chunks.get(key(nx >> 4, nz >> 4)); + assertNotNull("chunk beside " + nx + "," + nz, other); + byte beside = other.at(nx & 15, y, nz & 15); + assertTrue(nx + "," + y + "," + nz + " is " + beside, beside == GrottoRasterizer.WET || beside == GrottoRasterizer.GUARD); + checked++; + } + } + } + } + } + assertTrue("checked " + checked, checked > 2000L); + } + + @Test + public void guardStaysAtOrBelowTheWaterSoItCannotFillOpenAir() { + Grotto grotto = GrottoShapeTest.winding(13L, 0.6f); + int[] bounds = grotto.bounds(); + boolean any = false; + for (int chunkZ = bounds[1] >> 4; chunkZ <= bounds[3] >> 4; chunkZ++) { + for (int chunkX = bounds[0] >> 4; chunkX <= bounds[2] >> 4; chunkX++) { + GrottoRasterizer.Cells cells = GrottoRasterizer.cells(grotto, chunkX, chunkZ, GrottoRasterizer.Exclusion.NOWHERE); + if (cells == null) { + continue; + } + for (int lz = 0; lz < 16; lz++) { + for (int lx = 0; lx < 16; lx++) { + for (int y = cells.minY(); y <= cells.maxY(); y++) { + if (cells.at(lx, y, lz) == GrottoRasterizer.GUARD) { + any = true; + assertTrue("guard at " + y, y <= SEA); + } + } + } + } + } + } + assertTrue(any); + } + + @Test + public void excludedCellsStayRockAndNextWaterIsGuarded() { + Grotto grotto = GrottoShapeTest.winding(14L, 0.6f); + int wallX = (int) grotto.xs()[24]; + GrottoRasterizer.Exclusion beyond = (x, y, z) -> x >= wallX; + int chunkX = wallX >> 4; + int chunkZ = ((int) grotto.zs()[24]) >> 4; + GrottoRasterizer.Cells cells = GrottoRasterizer.cells(grotto, chunkX, chunkZ, beyond); + assertNotNull(cells); + GrottoShape shape = new GrottoShape(grotto); + boolean guarded = false; + for (int lz = 0; lz < 16; lz++) { + for (int lx = 0; lx < 16; lx++) { + int x = (chunkX << 4) + lx; + int z = (chunkZ << 4) + lz; + for (int y = cells.minY(); y <= cells.maxY(); y++) { + byte kind = cells.at(lx, y, lz); + if (x >= wallX) { + assertFalse(kind == GrottoRasterizer.WET || kind == GrottoRasterizer.DRY); + guarded |= kind == GrottoRasterizer.GUARD && shape.inside(x, y, z); + } + } + } + } + assertTrue(guarded); + } + + @Test + public void chunksFarFromTheGrottoHoldNothing() { + Grotto grotto = GrottoShapeTest.winding(15L, 0.6f); + assertNull(GrottoRasterizer.cells(grotto, 1000, 1000, GrottoRasterizer.Exclusion.NOWHERE)); + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/GrottoShapeTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/GrottoShapeTest.java new file mode 100644 index 000000000..1129e1427 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/GrottoShapeTest.java @@ -0,0 +1,208 @@ +package art.arcane.iris.generation.hydrology.underground; + +import org.junit.Test; + +import java.util.ArrayDeque; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class GrottoShapeTest { + static final int SEA = 100; + + static Grotto winding(long id, float roughness) { + int points = 50; + float[] xs = new float[points]; + float[] zs = new float[points]; + float[] halfWidth = new float[points]; + float[] roof = new float[points]; + float[] floor = new float[points]; + float[] lift = new float[points]; + for (int point = 0; point < points; point++) { + xs[point] = point * 4f; + zs[point] = (float) (22D * Math.sin(point / 7D)); + halfWidth[point] = point > 30 && point < 38 ? 11f : 6f; + roof[point] = point > 30 && point < 38 ? 13f : 7f; + floor[point] = 4f; + } + return new Grotto(id, SEA, roughness, 4, xs, zs, halfWidth, roof, floor, lift, new float[0], new float[0], new float[0], new int[0], new long[0]); + } + + private static int[][] section(GrottoShape shape, Grotto grotto, int point) { + int x = (int) grotto.xs()[point]; + int[][] spans = new int[121][]; + for (int z = -60; z <= 60; z++) { + int low = Integer.MAX_VALUE; + int high = Integer.MIN_VALUE; + for (int y = shape.minY(); y <= shape.maxY(); y++) { + if (shape.inside(x, y, z + (int) grotto.zs()[point])) { + low = Math.min(low, y); + high = Math.max(high, y); + } + } + spans[z + 60] = low == Integer.MAX_VALUE ? null : new int[]{low, high}; + } + return spans; + } + + @Test + public void shapeDependsOnlyOnThePlan() { + Grotto a = winding(77L, 0.6f); + Grotto b = winding(77L, 0.6f); + GrottoShape first = new GrottoShape(a); + GrottoShape second = new GrottoShape(b); + GrottoShape scoped = new GrottoShape(a).scoped(0, -40, 80, 40); + for (int x = 8; x < 72; x += 3) { + for (int z = -30; z < 30; z += 3) { + for (int y = first.minY(); y <= first.maxY(); y += 2) { + assertEquals(first.inside(x, y, z), second.inside(x, y, z)); + assertEquals(first.inside(x, y, z), scoped.inside(x, y, z)); + } + } + } + } + + @Test + public void differentGrottosGetDifferentRock() { + GrottoShape first = new GrottoShape(winding(1L, 0.6f)); + GrottoShape second = new GrottoShape(winding(2L, 0.6f)); + int differ = 0; + for (int x = 8; x < 180; x += 2) { + for (int z = -40; z < 40; z += 2) { + for (int y = SEA - 8; y <= SEA + 16; y += 2) { + differ += first.inside(x, y, z) != second.inside(x, y, z) ? 1 : 0; + } + } + } + assertTrue("differ " + differ, differ > 200); + } + + @Test + public void waterSliceRunsFromMouthToHeadInEveryRoughness() { + for (float roughness : new float[]{0f, 0.3f, 0.6f, 1f}) { + for (long id = 1L; id <= 8L; id++) { + Grotto grotto = winding(id, roughness); + GrottoShape shape = new GrottoShape(grotto); + int startX = (int) grotto.xs()[0]; + int startZ = (int) grotto.zs()[0]; + assertTrue(shape.inside(startX, SEA, startZ)); + Set seen = new HashSet<>(); + ArrayDeque frontier = new ArrayDeque<>(); + frontier.add(new int[]{startX, startZ}); + seen.add(key(startX, startZ)); + while (!frontier.isEmpty()) { + int[] cell = frontier.poll(); + for (int[] side : new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) { + int nx = cell[0] + side[0]; + int nz = cell[1] + side[1]; + if (shape.inside(nx, SEA, nz) && seen.add(key(nx, nz))) { + frontier.add(new int[]{nx, nz}); + } + } + } + int last = grotto.xs().length - 1; + assertTrue("roughness " + roughness + " id " + id, seen.contains(key((int) grotto.xs()[last], (int) grotto.zs()[last])) || nearReached(seen, grotto, last)); + } + } + } + + private static boolean nearReached(Set seen, Grotto grotto, int point) { + for (int dx = -4; dx <= 4; dx++) { + for (int dz = -4; dz <= 4; dz++) { + if (seen.contains(key((int) grotto.xs()[point] + dx, (int) grotto.zs()[point] + dz))) { + return true; + } + } + } + return false; + } + + private static long key(int x, int z) { + return ((long) x << 32) | (z & 0xFFFFFFFFL); + } + + @Test + public void sectionsAreNotBoxes() { + int flatRuns = 0; + int sections = 0; + int widest = 0; + Grotto grotto = winding(5L, 0.6f); + GrottoShape shape = new GrottoShape(grotto); + for (int point = 8; point < 44; point += 3) { + int[][] spans = section(shape, grotto, point); + int longest = 0; + int run = 0; + int width = 0; + Integer last = null; + for (int[] span : spans) { + if (span == null) { + continue; + } + width++; + run = last != null && last == span[1] ? run + 1 : 1; + longest = Math.max(longest, run); + last = span[1]; + } + flatRuns += longest * 2 > width ? 1 : 0; + sections++; + widest = Math.max(widest, width); + } + assertTrue("sections with a flat roof over half their width " + flatRuns + " of " + sections, flatRuns * 5 <= sections); + assertTrue("widest " + widest, widest >= 14); + } + + @Test + public void someColumnsHoldOverhangs() { + Grotto grotto = winding(9L, 0.8f); + GrottoShape shape = new GrottoShape(grotto); + int columns = 0; + int overhangs = 0; + for (int x = 8; x < 190; x++) { + for (int z = -50; z < 50; z++) { + boolean carved = false; + boolean over = false; + for (int y = SEA + 1; y <= shape.maxY() - 3; y++) { + if (!shape.inside(x, y, z)) { + continue; + } + carved = true; + for (int up = 1; up <= 3 && !over; up++) { + over = !shape.inside(x, y + up, z) && (shape.inside(x + 1, y + up, z) || shape.inside(x - 1, y + up, z) + || shape.inside(x, y + up, z + 1) || shape.inside(x, y + up, z - 1)); + } + } + columns += carved ? 1 : 0; + overhangs += over ? 1 : 0; + } + } + assertTrue("overhangs " + overhangs + " of " + columns, overhangs * 4 > columns); + } + + @Test + public void pluggedCellsAreRock() { + Grotto plain = winding(5L, 0.6f); + int x = (int) plain.xs()[20]; + int z = (int) plain.zs()[20]; + assertTrue(new GrottoShape(plain).inside(x, SEA, z)); + Grotto plugged = new Grotto(plain.id(), plain.seaLevel(), plain.roughness(), plain.coast(), plain.xs(), plain.zs(), plain.halfWidth(), plain.roof(), plain.floor(), plain.lift(), + plain.holeX(), plain.holeZ(), plain.holeRadius(), plain.holeTop(), new long[]{Grotto.plug(x, SEA, z)}); + assertFalse(new GrottoShape(plugged).inside(x, SEA, z)); + } + + @Test + public void skylightOpensAboveTheRoofOnly() { + Grotto plain = winding(5L, 0.3f); + float x = plain.xs()[20]; + float z = plain.zs()[20]; + Grotto holed = new Grotto(plain.id(), plain.seaLevel(), plain.roughness(), plain.coast(), plain.xs(), plain.zs(), plain.halfWidth(), plain.roof(), plain.floor(), plain.lift(), + new float[]{x}, new float[]{z}, new float[]{2.5f}, new int[]{SEA + 30}, new long[0]); + GrottoShape shape = new GrottoShape(holed); + assertTrue(shape.maxY() >= SEA + 30); + assertTrue(shape.inside((int) x, SEA + 25, (int) z)); + assertFalse(shape.inside((int) x, SEA + 40, (int) z)); + assertFalse(new GrottoShape(plain).inside((int) x, SEA + 25, (int) z)); + } +} diff --git a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverCompilerTest.java b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverCompilerTest.java index dc52a3540..1316ef8c4 100644 --- a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverCompilerTest.java +++ b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverCompilerTest.java @@ -178,7 +178,7 @@ public class RiverCompilerTest { compile(new Field.Const(SEA_LEVEL + 2.0), overworldHydrology(), registry(), DataVersion.V26_3, diagnostics); - assertEquals(List.of(ExportLimit.ELEVATED_WATER, ExportLimit.RIVER_DRAINAGE, ExportLimit.SEA_INLET, ExportLimit.CAVE_POOL), + assertEquals(List.of(ExportLimit.ELEVATED_WATER, ExportLimit.RIVER_DRAINAGE, ExportLimit.SEA_INLET, ExportLimit.GROTTO, ExportLimit.CAVE_POOL), diagnostics.stream().map(ExportDiagnostic::limit).toList()); assertEquals("dimensions/rivers/hydrology", diagnostics.getFirst().resource()); } @@ -404,6 +404,17 @@ public class RiverCompilerTest { assertTrue(diagnostics.toString(), limited(diagnostics, ExportLimit.CAVE_POOL).isEmpty()); } + @Test + public void grottosReportADiagnostic() { + List diagnostics = new ArrayList<>(); + IrisHydrology hydrology = overworldHydrology(); + hydrology.getUnderground().getSeaInlets().setEnabled(false); + hydrology.getUnderground().getCavePools().setEnabled(false); + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, registry(), DataVersion.V26_3, diagnostics); + assertEquals(1, limited(diagnostics, ExportLimit.GROTTO).size()); + assertEquals("dimensions/rivers/hydrology", limited(diagnostics, ExportLimit.GROTTO).getFirst().resource()); + } + @Test public void cavePoolsReportADiagnostic() { List diagnostics = new ArrayList<>(); @@ -458,7 +469,7 @@ public class RiverCompilerTest { ExportLimit.RIVER_CLIMATE, ExportLimit.RIVER_SHORE_BIOME, ExportLimit.RIVER_DECORATOR, ExportLimit.RIVER_DECORATOR, - ExportLimit.SEA_INLET, ExportLimit.CAVE_POOL), forward.stream().map(ExportDiagnostic::limit).toList()); + ExportLimit.SEA_INLET, ExportLimit.GROTTO, ExportLimit.CAVE_POOL), forward.stream().map(ExportDiagnostic::limit).toList()); assertEquals(List.of("regions/hot", "regions/wet", "biomes/deep"), limited(forward, ExportLimit.RIVER_POLICY).stream().map(ExportDiagnostic::resource).toList()); assertEquals(List.of("dimensions/rivers/hydrology", "biomes/marsh"), @@ -556,6 +567,7 @@ public class RiverCompilerTest { private static IrisHydrologyUnderground underground(boolean enabled) { IrisHydrologyUnderground underground = new IrisHydrologyUnderground(); underground.getSeaInlets().setEnabled(enabled); + underground.getGrottos().setEnabled(enabled); underground.getCavePools().setEnabled(enabled); return underground; } diff --git a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java index 796934039..a8de37f21 100644 --- a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java @@ -84,7 +84,7 @@ public class SchemaBuilderIdentityTest { @ClassRule public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); - private static final String EXPECTED_SCHEMA_DIGEST = "07bb61c7034a6aadae8d03c9c0fe8a31326113f7ad515c99512ded2ab9be686c"; + private static final String EXPECTED_SCHEMA_DIGEST = "9bb901e1c56c0a3996b956b0aeb0f1aa1060489181164790c554f8a89da16794"; private static final List> SCHEMA_ROOTS = List.of( IrisDimension.class, diff --git a/core/src/test/java/art/arcane/iris/studio/render/WaterMapTest.java b/core/src/test/java/art/arcane/iris/studio/render/WaterMapTest.java index 165f8e4ef..e0638500f 100644 --- a/core/src/test/java/art/arcane/iris/studio/render/WaterMapTest.java +++ b/core/src/test/java/art/arcane/iris/studio/render/WaterMapTest.java @@ -3,6 +3,7 @@ package art.arcane.iris.studio.render; import art.arcane.iris.generation.hydrology.engine.HydrologyPlanPreview; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; +import art.arcane.iris.generation.hydrology.underground.Grotto; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.hydrology.water.Pond; import art.arcane.iris.generation.hydrology.water.Reach; @@ -50,6 +51,18 @@ public class WaterMapTest { assertEquals("open lake water", HydrologyFeatureType.LAKE, map.at(13, 7)); } + @Test + public void grottosDrawAtMidZoom() { + Grotto grotto = new Grotto(9L, LEVEL, 0.5f, 0, new float[]{4f, 60f}, new float[]{POND_Z, POND_Z}, new float[]{4f, 4f}, new float[]{5f, 5f}, new float[]{3f, 3f}, new float[]{0f, 0f}, + new float[0], new float[0], new float[0], new int[0], new long[0]); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + when(runtime.planPreview(anyInt(), anyInt(), anyInt(), anyInt())) + .thenReturn(new HydrologyPlanPreview(List.of(), List.of(), List.of(), List.of(grotto), true)); + WaterMap map = new WaterMap(runtime, PIXELS, 0D, 0D, MID_STEP); + map.advance(() -> false); + assertEquals(HydrologyFeatureType.GROTTO, map.at((int) (30D / MID_STEP), (int) (POND_Z / MID_STEP))); + } + private static WaterMap draw(List reaches, List ponds, List lakes) { HydrologyRuntime runtime = mock(HydrologyRuntime.class); when(runtime.planPreview(anyInt(), anyInt(), anyInt(), anyInt())) diff --git a/probe/build.gradle b/probe/build.gradle index 1e5e11e20..95ca4a3fa 100644 --- a/probe/build.gradle +++ b/probe/build.gradle @@ -421,6 +421,27 @@ tasks.register('tidalReachProbe', JavaExec) { } } +tasks.register('grottoProbe', JavaExec) { + group = 'verification' + description = 'Plans real pack grottos, generates their chunks, checks containment and shape, and renders them.' + mainClass = 'art.arcane.iris.probe.GrottoProbe' + classpath = sourceSets.main.runtimeClasspath + jvmArgs('--add-modules', 'jdk.incubator.vector', '-Djava.awt.headless=true') + minHeapSize = '2g' + maxHeapSize = '8g' + dependsOn(':core:compileJava') + doFirst { + Provider windows = providers.gradleProperty('probeWindows') + Provider mode = providers.gradleProperty('probeMode').orElse('plan') + if (!probePack.isPresent() || !probeDimension.isPresent() || !windows.isPresent() || !probeOutput.isPresent()) { + throw new GradleException('grottoProbe requires probePack, probeDimension, probeWindows=x0..x1,z0..z1 and probeOutput') + } + List extra = (providers.gradleProperty('probeExtra').orElse('').get() as String).tokenize(',') + args([mode.get(), probePack.get(), probeDimension.get(), probeSeed.orElse('1337').get(), windows.get(), probeOutput.get(), + providers.gradleProperty('probeThreads').orElse('6').get()] + extra) + } +} + tasks.register('transitionProbe', JavaExec) { group = 'verification' description = 'Exercises a bounded two-pack Studio cutover, transition routing, receipts and semantics with a vanilla-biome pack.' diff --git a/probe/src/main/java/art/arcane/iris/probe/GrottoProbe.java b/probe/src/main/java/art/arcane/iris/probe/GrottoProbe.java new file mode 100644 index 000000000..3b6a91b06 --- /dev/null +++ b/probe/src/main/java/art/arcane/iris/probe/GrottoProbe.java @@ -0,0 +1,1101 @@ +package art.arcane.iris.probe; + +import art.arcane.iris.generation.concurrent.MultiBurst; +import art.arcane.iris.generation.decoration.IrisProceduralBlocks; +import art.arcane.iris.generation.hydrology.engine.HydrologyBinding; +import art.arcane.iris.generation.hydrology.engine.IrisHydrologyTerrainSource; +import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.hydrology.plan.WindowKey; +import art.arcane.iris.generation.hydrology.plan.WindowPlan; +import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; +import art.arcane.iris.generation.hydrology.underground.Grotto; +import art.arcane.iris.generation.hydrology.underground.GrottoShape; +import art.arcane.iris.generation.hydrology.water.Reach; +import art.arcane.iris.generation.hydrology.water.ReachStyle; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.volmlib.nativelib.terrain.NativeBiome; +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import art.arcane.volmlib.util.hunk.Hunk; + +import javax.imageio.ImageIO; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public final class GrottoProbe { + private static final String LOG = "[grotto-probe]"; + private static final int BELOW = 26; + private static final int LEVELS = 110; + private static final int MARGIN = 12; + private static final int SECTION_SCALE = 5; + private static final int SECTION_HALF = 28; + private static final int[][] SIDES = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + private static final int WATER_COLOR = 0x2f62c8; + private static final long TRACE_CHUNK = System.getenv("GROTTO_TRACE") == null ? Long.MIN_VALUE : Long.parseLong(System.getenv("GROTTO_TRACE")); + private static final List> TRACE = Collections.synchronizedList(new ArrayList<>()); + private static final int HASH_RING = 3; + private static final int TOUCH_RING = 1; + + private GrottoProbe() { + } + + public static void main(String[] arguments) { + int code = 2; + try { + String mode = arguments[0]; + HydrologyWindows.Target target = HydrologyWindows.Target.parse(arguments[1], arguments[2], arguments[3], arguments[4], "false"); + File out = new File(arguments[5]); + out.mkdirs(); + int threads = arguments.length > 6 ? Integer.parseInt(arguments[6]) : 6; + long failures = switch (mode) { + case "plan" -> plan(target, out); + case "blocks" -> blocks(target, out, threads, Integer.MAX_VALUE, Integer.MAX_VALUE, arguments.length > 7 ? Integer.parseInt(arguments[7]) : 0); + case "hash" -> hashes(target, out, threads, arguments.length > 7 ? new File(arguments[7]) : null); + case "site" -> blocks(target, out, threads, Integer.parseInt(arguments[7]), Integer.parseInt(arguments[8]), 1); + default -> throw new IllegalArgumentException("Unknown mode " + mode); + }; + System.out.println(LOG + " failures=" + failures); + code = failures == 0L ? 0 : 1; + } catch (Throwable failure) { + failure.printStackTrace(System.out); + } + System.exit(code); + } + + private static HydrologySettings settings(Engine engine) { + IrisDimension dimension = engine.getDimension(); + return HydrologySettings.compile(dimension.getHydrology(), engine.getSeedManager().getBodies(), dimension.getFluidHeight(), 0, engine.getHeight()); + } + + private static HydrologyPlanHarness.Plans plans(Engine engine, HydrologySettings settings, HydrologyWindows.WindowRange range) { + IrisHydrologyTerrainSource terrain = new IrisHydrologyTerrainSource(engine.getComplex(), engine.getDimension(), settings, MultiBurst.hydrology, + MultiBurst.hydrology.parallelism(), HydrologyBinding.UNBOUND); + return new HydrologyPlanHarness.Plans(settings, terrain, terrain::naturalSurface, range); + } + + private static List grottos(HydrologyPlanHarness.Plans plans, HydrologyWindows.WindowRange windows) { + List grottos = new ArrayList<>(); + for (Map.Entry entry : plans.windowPlans().entrySet()) { + if (windows.contains(entry.getKey())) { + grottos.addAll(entry.getValue().grottos()); + } + } + grottos.sort(Comparator.comparingLong(Grotto::id)); + return grottos; + } + + private static double length(Grotto grotto) { + double total = 0D; + for (int point = grotto.coast() + 1; point < grotto.xs().length; point++) { + total += Math.hypot(grotto.xs()[point] - grotto.xs()[point - 1], grotto.zs()[point] - grotto.zs()[point - 1]); + } + return total; + } + + private static double sinuosity(Grotto grotto) { + int last = grotto.xs().length - 1; + return length(grotto) / Math.max(1D, Math.hypot(grotto.xs()[last] - grotto.xs()[grotto.coast()], grotto.zs()[last] - grotto.zs()[grotto.coast()])); + } + + private static long plan(HydrologyWindows.Target target, File out) throws Exception { + try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(target.pack(), target.dimension(), LOG); + RealPackProbeSupport.EngineSession session = workspace.openEngine(target.seed(), false, "plan"); + PrintWriter writer = new PrintWriter(new File(out, "plan-" + target.seed() + ".tsv"))) { + Engine engine = session.engine(); + HydrologySettings settings = settings(engine); + HydrologyPlanHarness.Plans plans = plans(engine, settings, target.windows().grown(1)); + List grottos = grottos(plans, target.windows()); + writer.println("seed\tid\tmouthX\tmouthZ\tstations\tlength\tsinuosity\tmaxWidth\tmaxRoof\tholes\tlift"); + for (Grotto grotto : grottos) { + writer.printf(Locale.ROOT, "%d\t%d\t%d\t%d\t%d\t%.0f\t%.2f\t%.1f\t%.1f\t%d\t%.1f%n", target.seed(), grotto.id(), grotto.mouthX(), grotto.mouthZ(), grotto.xs().length, length(grotto), + sinuosity(grotto), max(grotto.halfWidth()), max(grotto.roof()), grotto.holeX().length, max(grotto.lift())); + } + System.out.println(LOG + " seed " + target.seed() + " grottos " + grottos.size() + " failures " + plans.failures()); + return plans.failures().size(); + } + } + + private static float max(float[] values) { + float max = 0f; + for (float value : values) { + max = Math.max(max, value); + } + return max; + } + + private static long blocks(HydrologyWindows.Target target, File out, int threads, int siteX, int siteZ, int images) throws Exception { + long failures = 0L; + try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(target.pack(), target.dimension(), LOG)) { + long seed = target.seed(); + List grottos; + List order; + Map forward = new ConcurrentHashMap<>(); + try (RealPackProbeSupport.EngineSession session = workspace.openEngine(seed, false, "blocks")) { + Engine engine = session.engine(); + HydrologySettings settings = settings(engine); + HydrologyPlanHarness.Plans plans = plans(engine, settings, target.windows().grown(1)); + failures += plans.failures().size(); + grottos = new ArrayList<>(grottos(plans, target.windows())); + if (siteX != Integer.MAX_VALUE) { + grottos.sort(Comparator.comparingDouble((Grotto grotto) -> Math.hypot(grotto.mouthX() - siteX, grotto.mouthZ() - siteZ))); + for (Grotto grotto : grottos.subList(0, Math.min(5, grottos.size()))) { + System.out.printf(Locale.ROOT, "%s near site: mouth %d,%d off %.0f length %.0f sinuosity %.2f%n", LOG, grotto.mouthX(), grotto.mouthZ(), + Math.hypot(grotto.mouthX() - siteX, grotto.mouthZ() - siteZ), length(grotto), sinuosity(grotto)); + } + grottos = new ArrayList<>(grottos.subList(0, Math.min(images, grottos.size()))); + } + List arms = new ArrayList<>(); + for (WindowPlan plan : plans.windowPlans().values()) { + for (Reach reach : plan.reaches()) { + if (reach.style()[0] == ReachStyle.TIDAL) { + arms.add(reach); + } + } + } + Set chunks = new TreeSet<>(); + for (Grotto grotto : grottos) { + int[] bounds = grotto.bounds(); + for (int chunkZ = (bounds[1] - MARGIN) >> 4; chunkZ <= (bounds[3] + MARGIN) >> 4; chunkZ++) { + for (int chunkX = (bounds[0] - MARGIN) >> 4; chunkX <= (bounds[2] + MARGIN) >> 4; chunkX++) { + chunks.add(key(chunkX, chunkZ)); + } + } + } + order = new ArrayList<>(chunks); + int sea = settings.seaLevel(); + Volume volume = new Volume(sea - BELOW); + generate(engine, order, threads, volume, forward); + List stats = new ArrayList<>(); + try (PrintWriter writer = new PrintWriter(new File(out, "blocks-" + seed + ".tsv"))) { + writer.println("seed\tid\tmouthX\tmouthZ\tlength\tsinuosity\twet\tdry\tleaks\tflowed\tcutOff\tmismatch\twetInRiver\tstrayWater\twallRun4\tflatRoof\tflatRoofAlong\tmultiSpan\toverhang\tmouthOpen\tskyOpen"); + for (Grotto grotto : grottos) { + Stats stat = stats(engine, grotto, volume, sea); + stats.add(stat); + writer.printf(Locale.ROOT, "%d\t%d\t%d\t%d\t%.0f\t%.2f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%.3f\t%.3f\t%.1f\t%.3f\t%.3f\t%d\t%.3f%n", seed, grotto.id(), grotto.mouthX(), grotto.mouthZ(), length(grotto), sinuosity(grotto), + stat.wet, stat.dry, stat.leaks, stat.flowed, stat.cutOff, stat.mismatch, stat.wetInRiver, stat.strayWater, stat.wallRun, stat.flatRoof, stat.flatRoofAlong, stat.multiSpan, stat.overhang, stat.mouthOpen, stat.skyOpen); + failures += stat.leaks + stat.flowed + stat.cutOff + stat.wetInRiver + stat.strayWater; + } + } + long joined = joined(grottos); + long armBreach = armBreach(grottos, arms); + failures += joined; + System.out.println(LOG + " seed " + seed + " grottos " + grottos.size() + " chunks " + order.size() + " joined " + joined + " nearArm " + armBreach + + " leaks " + stats.stream().mapToLong(stat -> stat.leaks).sum() + " flowed " + stats.stream().mapToLong(stat -> stat.flowed).sum() + + " cutOff " + stats.stream().mapToLong(stat -> stat.cutOff).sum() + " mismatch " + stats.stream().mapToLong(stat -> stat.mismatch).sum() + + " wetInRiver " + stats.stream().mapToLong(stat -> stat.wetInRiver).sum() + " stray " + stats.stream().mapToLong(stat -> stat.strayWater).sum()); + int rendered = 0; + for (Grotto grotto : grottos) { + if (rendered++ >= images) { + break; + } + render(grotto, volume, sea, new File(out, "grotto-" + seed + "-" + grotto.mouthX() + "_" + grotto.mouthZ() + ".png")); + } + List reports = RealPackProbeSupport.settleAndDrain(engine); + if (!reports.isEmpty()) { + RealPackProbeSupport.printReports(LOG, "blocks", reports); + failures += reports.size(); + } + } + if (!order.isEmpty()) { + List reversed = new ArrayList<>(order); + Collections.reverse(reversed); + Map backward = new ConcurrentHashMap<>(); + try (RealPackProbeSupport.EngineSession second = workspace.openEngine(seed, false, "blocks-reverse")) { + generate(second.engine(), reversed, Math.max(1, threads / 2), new Volume(0), backward); + } + long mismatches = 0L; + for (Map.Entry entry : forward.entrySet()) { + if (!entry.getValue().equals(backward.get(entry.getKey()))) { + mismatches++; + int chunkX = (int) (entry.getKey() >> 32); + int chunkZ = (int) (long) entry.getKey(); + boolean inside = false; + for (Grotto grotto : grottos) { + inside |= grotto.touches(chunkX << 4, chunkZ << 4, (chunkX << 4) + 15, (chunkZ << 4) + 15); + } + System.out.println(LOG + " seed " + seed + " order differs in chunk " + chunkX + "," + chunkZ + " touching a grotto " + inside); + } + } + if (TRACE.size() == 2) { + int height = TRACE.get(0).size() / 256; + for (int index = 0; index < TRACE.get(0).size(); index++) { + if (!TRACE.get(0).get(index).equals(TRACE.get(1).get(index))) { + System.out.println(LOG + " diff x " + index / height / 16 + " z " + index / height % 16 + " y " + index % height + " " + TRACE.get(0).get(index) + " vs " + TRACE.get(1).get(index)); + } + } + } + failures += mismatches; + System.out.println(LOG + " seed " + seed + " orderMismatches " + mismatches + " of " + forward.size()); + } + } + return failures; + } + + private static long hashes(HydrologyWindows.Target target, File out, int threads, File listed) throws Exception { + try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(target.pack(), target.dimension(), LOG); + RealPackProbeSupport.EngineSession session = workspace.openEngine(target.seed(), false, "hash")) { + Engine engine = session.engine(); + List chunks = new ArrayList<>(); + Set touched = new HashSet<>(); + if (listed != null) { + for (String line : Files.readAllLines(listed.toPath())) { + String[] parts = line.split("\\t"); + chunks.add(Long.parseLong(parts[0])); + } + } else { + HydrologySettings settings = settings(engine); + HydrologyPlanHarness.Plans plans = plans(engine, settings, target.windows().grown(1)); + Set wanted = new TreeSet<>(); + for (Grotto grotto : grottos(plans, target.windows())) { + int[] bounds = grotto.bounds(); + for (int chunkZ = (bounds[1] >> 4) - HASH_RING; chunkZ <= (bounds[3] >> 4) + HASH_RING; chunkZ++) { + for (int chunkX = (bounds[0] >> 4) - HASH_RING; chunkX <= (bounds[2] >> 4) + HASH_RING; chunkX++) { + wanted.add(key(chunkX, chunkZ)); + if (chunkX >= (bounds[0] >> 4) - TOUCH_RING && chunkX <= (bounds[2] >> 4) + TOUCH_RING + && chunkZ >= (bounds[1] >> 4) - TOUCH_RING && chunkZ <= (bounds[3] >> 4) + TOUCH_RING) { + touched.add(key(chunkX, chunkZ)); + } + } + } + } + chunks.addAll(wanted); + } + Map hashes = new ConcurrentHashMap<>(); + generate(engine, chunks, threads, new Volume(0), hashes); + try (PrintWriter writer = new PrintWriter(new File(out, "hash-" + target.seed() + ".tsv"))) { + for (long chunk : chunks) { + writer.println(chunk + "\t" + hashes.get(chunk) + "\t" + (touched.contains(chunk) ? 1 : 0)); + } + } + System.out.println(LOG + " seed " + target.seed() + " hashed " + chunks.size()); + return 0L; + } + } + + private static long joined(List grottos) { + long joined = 0L; + for (int a = 0; a < grottos.size(); a++) { + for (int b = a + 1; b < grottos.size(); b++) { + if (nearest(grottos.get(a), grottos.get(b)) <= 0D) { + joined++; + } + } + } + return joined; + } + + private static double nearest(Grotto a, Grotto b) { + double nearest = Double.POSITIVE_INFINITY; + double factor = GrottoShape.radialMax(a.roughness()); + double warp = GrottoShape.warp(a.roughness()); + for (int i = 0; i < a.xs().length; i++) { + for (int j = 0; j < b.xs().length; j++) { + double apart = Math.hypot(a.xs()[i] - b.xs()[j], a.zs()[i] - b.zs()[j]) - (a.halfWidth()[i] + b.halfWidth()[j]) * factor - 2D * warp; + nearest = Math.min(nearest, apart); + } + } + return nearest; + } + + private static long armBreach(List grottos, List arms) { + long near = 0L; + for (Grotto grotto : grottos) { + boolean close = false; + for (Reach arm : arms) { + for (int i = 0; i < grotto.xs().length && !close; i += 2) { + for (int j = 0; j < arm.xs().length && !close; j += 2) { + close = Math.hypot(grotto.xs()[i] - arm.xs()[j], grotto.zs()[i] - arm.zs()[j]) < grotto.halfWidth()[i] + arm.halfWidth()[j] + 6D; + } + } + } + near += close ? 1L : 0L; + } + return near; + } + + private static void generate(Engine engine, List chunks, int threads, Volume volume, Map hashes) throws Exception { + int height = engine.getTarget().getHeight(); + ExecutorService pool = Executors.newFixedThreadPool(threads); + try { + List> futures = new ArrayList<>(chunks.size()); + for (long chunk : chunks) { + futures.add(pool.submit(() -> { + int chunkX = (int) (chunk >> 32); + int chunkZ = (int) chunk; + Hunk blocks = Hunk.newArrayHunk(16, height, 16); + Hunk biomes = Hunk.newArrayHunk(16, height, 16); + engine.generate(chunkX << 4, chunkZ << 4, blocks, biomes, false); + hashes.put(chunk, hash(blocks, height)); + if (chunk == TRACE_CHUNK) { + List keys = new ArrayList<>(); + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = 0; y < height; y++) { + NativeBlockState state = blocks.get(x, y, z); + keys.add((state == null ? "air" : state.key())); + } + } + } + TRACE.add(keys); + } + if (volume.bottom > 0) { + volume.capture(chunk, blocks); + } + return null; + })); + } + for (Future future : futures) { + future.get(); + } + } finally { + pool.shutdown(); + } + } + + private static long hash(Hunk blocks, int height) { + long hash = 0xcbf29ce484222325L; + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = 0; y < height; y++) { + NativeBlockState state = blocks.get(x, y, z); + String key = state == null ? "air" : state.key(); + if (key.contains("amethyst")) { + key = "air"; + } + hash = (hash ^ key.hashCode()) * 0x100000001b3L; + } + } + } + return hash; + } + + private static final class Volume { + final int bottom; + final Map colors = new ConcurrentHashMap<>(); + final Map names = new ConcurrentHashMap<>(); + + Volume(int bottom) { + this.bottom = bottom; + } + + void capture(long chunk, Hunk blocks) { + int[] cells = new int[16 * 16 * LEVELS]; + for (int level = 0; level < LEVELS; level++) { + for (int lz = 0; lz < 16; lz++) { + for (int lx = 0; lx < 16; lx++) { + NativeBlockState state = bottom + level < blocks.getHeight() ? blocks.get(lx, bottom + level, lz) : null; + cells[level << 8 | lz << 4 | lx] = code(state); + if ((cells[level << 8 | lz << 4 | lx] >>> 24) == 0xFF) { + names.putIfAbsent(cells[level << 8 | lz << 4 | lx], IrisProceduralBlocks.materialKey(state)); + } + } + } + } + colors.put(chunk, cells); + } + + int at(int x, int y, int z) { + int level = y - bottom; + if (level < 0 || level >= LEVELS) { + return y < bottom ? 0xFF888888 : 0; + } + int[] cells = colors.get(key(x >> 4, z >> 4)); + return cells == null ? -1 : cells[level << 8 | (z & 15) << 4 | (x & 15)]; + } + + String name(int x, int y, int z) { + int cell = at(x, y, z); + return (cell >>> 24) == 0xFF ? names.getOrDefault(cell, "?") : "kind" + (cell >>> 24); + } + + boolean water(int x, int y, int z) { + int cell = at(x, y, z); + return cell != -1 && (cell >>> 24) == 2; + } + + boolean open(int x, int y, int z) { + int cell = at(x, y, z); + return cell != -1 && (cell >>> 24) == 0; + } + + boolean solid(int x, int y, int z) { + int cell = at(x, y, z); + return cell != -1 && (cell >>> 24) == 0xFF; + } + + boolean known(int x, int y, int z) { + return at(x, y, z) != -1; + } + } + + private static int code(NativeBlockState state) { + if (state == null || state.isAir()) { + return 0; + } + String key = IrisProceduralBlocks.materialKey(state); + if (key.contains("water") || state.key().contains("waterlogged=true") || key.contains("seagrass") || key.contains("kelp")) { + return 2 << 24 | WATER_COLOR; + } + if (key.contains("lava")) { + return 3 << 24 | 0xe06010; + } + if (key.contains("pointed_dripstone")) { + return 4 << 24 | 0x907860; + } + if (!state.isSolid() || key.contains("leaves")) { + return key.contains("leaves") ? 4 << 24 | 0x2f6a22 : 0; + } + int rgb; + if (key.contains("grass_block") || key.contains("moss")) { + rgb = 0x5f9f3f; + } else if (key.contains("sand")) { + rgb = 0xd8cc90; + } else if (key.contains("gravel")) { + rgb = 0x908880; + } else if (key.contains("mud") || key.contains("clay")) { + rgb = 0x706860; + } else if (key.contains("dirt") || key.contains("podzol") || key.contains("mycelium")) { + rgb = 0x806040; + } else if (key.contains("log") || key.contains("wood")) { + rgb = 0x604020; + } else if (key.contains("snow") || key.contains("ice")) { + rgb = 0xe8eef8; + } else if (key.contains("deepslate") || key.contains("tuff")) { + rgb = 0x5c5c62; + } else if (key.contains("stone") || key.contains("andesite") || key.contains("diorite") || key.contains("granite")) { + rgb = 0x8a8a8a; + } else { + rgb = 0x9a8a6a; + } + return 0xFF << 24 | rgb; + } + + private static final class Stats { + long wet; + long dry; + long leaks; + long flowed; + long cutOff; + long mismatch; + long wetInRiver; + long strayWater; + double wallRun; + double flatRoof; + double flatRoofAlong; + double multiSpan; + double overhang; + long mouthOpen; + double skyOpen; + } + + private static Stats stats(Engine engine, Grotto grotto, Volume volume, int sea) { + Stats stats = new Stats(); + GrottoShape shape = new GrottoShape(grotto); + int[] bounds = grotto.bounds(); + Set wetCells = new HashSet<>(); + long columns = 0L; + long manySpans = 0L; + long overhangs = 0L; + long skyColumns = 0L; + Map rasters = new HashMap<>(); + Map mismatchKinds = new TreeMap<>(); + for (int z = bounds[1]; z <= bounds[3]; z++) { + for (int x = bounds[0]; x <= bounds[2]; x++) { + if (!shape.near(x, z)) { + continue; + } + int spans = 0; + boolean previous = false; + boolean any = false; + for (int y = shape.minY(); y <= shape.maxY(); y++) { + boolean inside = shape.inside(x, y, z); + if (inside && !previous) { + spans++; + } + previous = inside; + if (!inside) { + continue; + } + any = true; + if (!volume.known(x, y, z)) { + continue; + } + if (y <= sea) { + stats.wet++; + if (volume.water(x, y, z)) { + wetCells.add(cell(x, y, z)); + } else { + stats.mismatch++; + mismatchKinds.merge("wet:" + volume.name(x, y, z) + (y >= sea - 2 ? ":top" : ":deep"), 1, Integer::sum); + } + ChunkWaterRaster raster = rasters.computeIfAbsent(key(x >> 4, z >> 4), chunk -> engine.getComplex().getHydrologyRuntime().raster((int) (chunk >> 32), (int) (long) chunk)); + if (raster.role(x & 15, z & 15).wet()) { + stats.wetInRiver++; + } + } else { + stats.dry++; + if (volume.water(x, y, z)) { + stats.strayWater++; + } + if (volume.solid(x, y, z)) { + stats.mismatch++; + mismatchKinds.merge("dry:" + volume.name(x, y, z) + ":" + (y - sea) / 8, 1, Integer::sum); + } + } + } + if (any) { + columns++; + manySpans += spans > 1 ? 1L : 0L; + boolean over = false; + for (int y = sea + 1; y <= shape.maxY() && !over; y++) { + if (!shape.inside(x, y, z)) { + continue; + } + for (int[] side : SIDES) { + for (int up = 1; up <= 3 && !over; up++) { + over = !shape.inside(x, y + up, z) && shape.inside(x + side[0], y + up, z + side[1]) && y + up <= shape.maxY(); + } + } + } + overhangs += over ? 1L : 0L; + boolean sky = true; + for (int y = sea + 1; y <= sea + LEVELS - BELOW - 1 && sky; y++) { + sky = !volume.solid(x, y, z); + } + skyColumns += sky ? 1L : 0L; + } + } + } + for (long cell : wetCells) { + int x = cellX(cell); + int y = cellY(cell); + int z = cellZ(cell); + boolean leak = volume.open(x, y - 1, z); + for (int[] side : SIDES) { + leak |= volume.open(x + side[0], y, z + side[1]); + } + stats.leaks += leak ? 1L : 0L; + } + if (stats.mismatch > 0L) { + System.out.println(LOG + " mismatch " + grotto.mouthX() + "," + grotto.mouthZ() + " " + mismatchKinds); + } + stats.flowed = ticked(volume, wetCells, sea); + stats.cutOff = cutOff(grotto, volume, wetCells, sea); + section(grotto, volume, sea, stats); + stats.multiSpan = columns == 0L ? 0D : (double) manySpans / columns; + stats.overhang = columns == 0L ? 0D : (double) overhangs / columns; + stats.skyOpen = columns == 0L ? 0D : (double) skyColumns / columns; + stats.mouthOpen = mouthOpen(grotto, volume, sea); + return stats; + } + + private static long ticked(Volume volume, Set wetCells, int sea) { + ArrayDeque frontier = new ArrayDeque<>(wetCells); + Set flowed = new HashSet<>(); + Set seen = new HashSet<>(wetCells); + while (!frontier.isEmpty() && flowed.size() < 100000) { + long cell = frontier.poll(); + int x = cellX(cell); + int y = cellY(cell); + int z = cellZ(cell); + for (int[] step : new int[][]{{0, -1, 0}, {1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}}) { + int nx = x + step[0]; + int ny = y + step[1]; + int nz = z + step[2]; + long next = cell(nx, ny, nz); + if (ny <= sea && volume.open(nx, ny, nz) && seen.add(next)) { + flowed.add(next); + frontier.add(next); + } + } + } + return flowed.size(); + } + + private static long cutOff(Grotto grotto, Volume volume, Set wetCells, int sea) { + ArrayDeque frontier = new ArrayDeque<>(); + Set reached = new HashSet<>(); + int startX = (int) Math.floor(grotto.xs()[0]); + int startZ = (int) Math.floor(grotto.zs()[0]); + if (!volume.water(startX, sea, startZ)) { + return wetCells.size(); + } + long start = cell(startX, sea, startZ); + reached.add(start); + frontier.add(start); + int[] bounds = grotto.bounds(); + while (!frontier.isEmpty()) { + long cell = frontier.poll(); + int x = cellX(cell); + int y = cellY(cell); + int z = cellZ(cell); + for (int[] step : new int[][]{{0, -1, 0}, {0, 1, 0}, {1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}}) { + int nx = x + step[0]; + int ny = y + step[1]; + int nz = z + step[2]; + if (nx < bounds[0] - MARGIN || nx > bounds[2] + MARGIN || nz < bounds[1] - MARGIN || nz > bounds[3] + MARGIN) { + continue; + } + long next = cell(nx, ny, nz); + if (volume.water(nx, ny, nz) && reached.add(next)) { + frontier.add(next); + } + } + } + long cut = 0L; + for (long cell : wetCells) { + cut += reached.contains(cell) ? 0L : 1L; + } + return cut; + } + + private static long mouthOpen(Grotto grotto, Volume volume, int sea) { + long open = 0L; + int end = Math.min(grotto.xs().length - 1, grotto.coast() + 8); + for (int point = grotto.coast(); point <= end; point++) { + open += volume.open((int) Math.floor(grotto.xs()[point]), sea + 2, (int) Math.floor(grotto.zs()[point])) ? 1L : 0L; + } + return open; + } + + private static void section(Grotto grotto, Volume volume, int sea, Stats stats) { + long wallCells = 0L; + long wallInRuns = 0L; + double flatSum = 0D; + int sections = 0; + double flatAlong = 0D; + int lastCeiling = Integer.MIN_VALUE; + double run = 0D; + int start = Math.min(grotto.xs().length - 1, grotto.coast() + 6); + for (int point = start; point < grotto.xs().length - 1; point++) { + double dx = grotto.xs()[point + 1] - grotto.xs()[point]; + double dz = grotto.zs()[point + 1] - grotto.zs()[point]; + double length = Math.max(1e-3D, Math.hypot(dx, dz)); + double nx = -dz / length; + double nz = dx / length; + int[] ceilings = new int[2 * SECTION_HALF + 1]; + int[] left = new int[LEVELS]; + int[] right = new int[LEVELS]; + int centreY = sea + 2; + int width = 0; + for (int offset = -SECTION_HALF; offset <= SECTION_HALF; offset++) { + int x = (int) Math.floor(grotto.xs()[point] + offset * nx); + int z = (int) Math.floor(grotto.zs()[point] + offset * nz); + int y = centreY; + ceilings[offset + SECTION_HALF] = Integer.MIN_VALUE; + if (!volume.open(x, y, z)) { + continue; + } + while (y < sea + 60 && volume.open(x, y + 1, z)) { + y++; + } + ceilings[offset + SECTION_HALF] = y; + width++; + } + int centre = SECTION_HALF; + int low = centre; + int high = centre; + while (low > 0 && ceilings[low - 1] != Integer.MIN_VALUE) { + low--; + } + while (high < 2 * SECTION_HALF && ceilings[high + 1] != Integer.MIN_VALUE) { + high++; + } + if (ceilings[centre] == Integer.MIN_VALUE || high - low < 2) { + lastCeiling = Integer.MIN_VALUE; + run = 0D; + continue; + } + int longest = 1; + int current = 1; + for (int offset = low + 1; offset <= high; offset++) { + current = ceilings[offset] == ceilings[offset - 1] ? current + 1 : 1; + longest = Math.max(longest, current); + } + flatSum += (double) longest / (high - low + 1); + sections++; + run = ceilings[centre] == lastCeiling ? run + length : 0D; + lastCeiling = ceilings[centre]; + flatAlong = Math.max(flatAlong, run); + for (int side = -1; side <= 1; side += 2) { + int edge = Integer.MIN_VALUE; + int streak = 0; + for (int y = sea + 1; y <= sea + 24; y++) { + int offset = 0; + int x = (int) Math.floor(grotto.xs()[point]); + int z = (int) Math.floor(grotto.zs()[point]); + if (!volume.open(x, y, z)) { + if (streak >= 4) { + wallInRuns += streak; + } + break; + } + while (Math.abs(offset) < SECTION_HALF) { + int nextX = (int) Math.floor(grotto.xs()[point] + (offset + side) * nx); + int nextZ = (int) Math.floor(grotto.zs()[point] + (offset + side) * nz); + if (!volume.open(nextX, y, nextZ)) { + break; + } + offset += side; + } + wallCells++; + if (offset == edge) { + streak++; + } else { + if (streak >= 4) { + wallInRuns += streak; + } + streak = 1; + edge = offset; + } + } + if (streak >= 4) { + wallInRuns += streak; + } + } + } + stats.wallRun = wallCells == 0L ? 0D : (double) wallInRuns / wallCells; + stats.flatRoof = sections == 0 ? 0D : flatSum / sections; + stats.flatRoofAlong = flatAlong; + } + + private static void render(Grotto grotto, Volume volume, int sea, File file) throws Exception { + int[] bounds = grotto.bounds(); + BufferedImage map = topMap(grotto, volume, sea, bounds); + BufferedImage along = longitudinal(grotto, volume, sea); + BufferedImage sections = sections(grotto, volume, sea); + BufferedImage outside = look(grotto, volume, sea, true); + BufferedImage inside = look(grotto, volume, sea, false); + int width = Math.max(map.getWidth() + outside.getWidth() + 8, Math.max(along.getWidth(), sections.getWidth())); + int height = Math.max(map.getHeight(), outside.getHeight() + inside.getHeight() + 8) + along.getHeight() + sections.getHeight() + 24; + BufferedImage sheet = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics = sheet.createGraphics(); + graphics.setColor(new Color(24, 24, 28)); + graphics.fillRect(0, 0, width, height); + graphics.drawImage(map, 0, 0, null); + graphics.drawImage(outside, map.getWidth() + 8, 0, null); + graphics.drawImage(inside, map.getWidth() + 8, outside.getHeight() + 8, null); + int y = Math.max(map.getHeight(), outside.getHeight() + inside.getHeight() + 8) + 8; + graphics.drawImage(along, 0, y, null); + graphics.drawImage(sections, 0, y + along.getHeight() + 8, null); + graphics.dispose(); + ImageIO.write(sheet, "png", file); + } + + private static BufferedImage topMap(Grotto grotto, Volume volume, int sea, int[] bounds) { + int margin = 24; + int width = bounds[2] - bounds[0] + 1 + 2 * margin; + int depth = bounds[3] - bounds[1] + 1 + 2 * margin; + int scale = Math.max(1, Math.min(3, 520 / Math.max(width, depth))); + BufferedImage image = new BufferedImage(width * scale, depth * scale, BufferedImage.TYPE_INT_RGB); + for (int pz = 0; pz < depth; pz++) { + for (int px = 0; px < width; px++) { + int x = bounds[0] - margin + px; + int z = bounds[1] - margin + pz; + int rgb = 0x202024; + for (int y = volume.bottom + LEVELS - 1; y >= volume.bottom; y--) { + int cell = volume.at(x, y, z); + if (cell == -1) { + break; + } + if ((cell >>> 24) != 0) { + double shade = Math.clamp(0.55D + (y - sea) / 80D, 0.4D, 1.15D); + rgb = shaded(cell & 0xFFFFFF, shade); + break; + } + } + if (volume.water(x, sea, z) && volume.at(x, sea + 1, z) != -1 && !volume.open(x, sea + 1, z)) { + rgb = blend(rgb, 0x4080ff, 0.6D); + } else if (volume.water(x, sea, z)) { + boolean roofed = false; + for (int y = sea + 1; y < sea + 70 && !roofed; y++) { + roofed = volume.solid(x, y, z); + } + if (roofed) { + rgb = blend(rgb, 0x40e0ff, 0.65D); + } + } + for (int sz = 0; sz < scale; sz++) { + for (int sx = 0; sx < scale; sx++) { + image.setRGB(px * scale + sx, pz * scale + sz, rgb); + } + } + } + } + return image; + } + + private static int shaded(int rgb, double shade) { + int r = (int) Math.clamp(((rgb >> 16) & 255) * shade, 0D, 255D); + int g = (int) Math.clamp(((rgb >> 8) & 255) * shade, 0D, 255D); + int b = (int) Math.clamp((rgb & 255) * shade, 0D, 255D); + return r << 16 | g << 8 | b; + } + + private static int blend(int a, int b, double t) { + int r = (int) (((a >> 16) & 255) * (1D - t) + ((b >> 16) & 255) * t); + int g = (int) (((a >> 8) & 255) * (1D - t) + ((b >> 8) & 255) * t); + int blue = (int) ((a & 255) * (1D - t) + (b & 255) * t); + return r << 16 | g << 8 | blue; + } + + private static int sectionPixel(int cell) { + if (cell == -1) { + return 0x303034; + } + int kind = cell >>> 24; + return kind == 0 ? 0xe8f2ff : cell & 0xFFFFFF; + } + + private static BufferedImage longitudinal(Grotto grotto, Volume volume, int sea) { + double total = 0D; + List points = new ArrayList<>(); + int from = Math.max(0, grotto.coast() - 8); + for (int point = from; point + 1 < grotto.xs().length; point++) { + double length = Math.hypot(grotto.xs()[point + 1] - grotto.xs()[point], grotto.zs()[point + 1] - grotto.zs()[point]); + for (double t = 0D; t < length; t += 1D) { + double share = t / length; + points.add(new double[]{grotto.xs()[point] + share * (grotto.xs()[point + 1] - grotto.xs()[point]), grotto.zs()[point] + share * (grotto.zs()[point + 1] - grotto.zs()[point])}); + } + total += length; + } + int scale = total > 400D ? 2 : 3; + int bottom = sea - 16; + int top = sea + 54; + BufferedImage image = new BufferedImage(points.size() * scale, (top - bottom) * scale, BufferedImage.TYPE_INT_RGB); + for (int index = 0; index < points.size(); index++) { + int x = (int) Math.floor(points.get(index)[0]); + int z = (int) Math.floor(points.get(index)[1]); + for (int y = bottom; y < top; y++) { + int rgb = sectionPixel(volume.at(x, y, z)); + for (int sx = 0; sx < scale; sx++) { + for (int sy = 0; sy < scale; sy++) { + image.setRGB(index * scale + sx, (top - 1 - y) * scale + sy, rgb); + } + } + } + } + return image; + } + + private static BufferedImage sections(Grotto grotto, Volume volume, int sea) { + int count = 8; + int half = SECTION_HALF; + int bottom = sea - 14; + int top = sea + 34; + int panelWidth = (2 * half + 1) * 4; + int panelHeight = (top - bottom) * 4; + int columns = 4; + BufferedImage image = new BufferedImage(columns * (panelWidth + 4), (count / columns) * (panelHeight + 4), BufferedImage.TYPE_INT_RGB); + Graphics2D graphics = image.createGraphics(); + int first = grotto.coast(); + int stations = grotto.xs().length - 2 - first; + for (int panel = 0; panel < count; panel++) { + int point = first + (int) Math.round((double) panel / (count - 1) * stations); + double dx = grotto.xs()[point + 1] - grotto.xs()[point]; + double dz = grotto.zs()[point + 1] - grotto.zs()[point]; + double length = Math.max(1e-3D, Math.hypot(dx, dz)); + double nx = -dz / length; + double nz = dx / length; + int originX = (panel % columns) * (panelWidth + 4); + int originY = (panel / columns) * (panelHeight + 4); + for (int offset = -half; offset <= half; offset++) { + int x = (int) Math.floor(grotto.xs()[point] + offset * nx); + int z = (int) Math.floor(grotto.zs()[point] + offset * nz); + for (int y = bottom; y < top; y++) { + graphics.setColor(new Color(sectionPixel(volume.at(x, y, z)))); + graphics.fillRect(originX + (offset + half) * 4, originY + (top - 1 - y) * 4, 4, 4); + } + } + } + graphics.dispose(); + return image; + } + + private static BufferedImage look(Grotto grotto, Volume volume, int sea, boolean outside) { + int width = 640; + int height = 360; + int coast = grotto.coast(); + double eyeX; + double eyeZ; + double aimX; + double aimZ; + double eyeY; + if (outside) { + int aim = Math.min(grotto.xs().length - 1, coast + 3); + double dirX = grotto.xs()[aim] - grotto.xs()[0]; + double dirZ = grotto.zs()[aim] - grotto.zs()[0]; + double length = Math.max(1D, Math.hypot(dirX, dirZ)); + eyeX = grotto.xs()[aim] - dirX / length * 30D; + eyeZ = grotto.zs()[aim] - dirZ / length * 30D; + aimX = grotto.xs()[aim]; + aimZ = grotto.zs()[aim]; + eyeY = sea + 3.5D; + } else { + int at = Math.min(grotto.xs().length - 2, coast + (grotto.xs().length - coast) / 3); + int aim = Math.min(grotto.xs().length - 1, at + 6); + double openX = grotto.xs()[at] + 0.5D; + double openZ = grotto.zs()[at] + 0.5D; + boolean found = false; + for (int radius = 0; radius <= 12 && !found; radius++) { + for (int dz = -radius; dz <= radius && !found; dz++) { + for (int dx = -radius; dx <= radius && !found; dx++) { + int cx = (int) Math.floor(grotto.xs()[at]) + dx; + int cz = (int) Math.floor(grotto.zs()[at]) + dz; + if (volume.open(cx, sea + 2, cz) && volume.open(cx + 1, sea + 2, cz) && volume.open(cx - 1, sea + 2, cz) && volume.open(cx, sea + 2, cz + 1) && volume.open(cx, sea + 2, cz - 1)) { + openX = cx + 0.5D; + openZ = cz + 0.5D; + found = true; + } + } + } + } + eyeX = openX; + eyeZ = openZ; + aimX = grotto.xs()[aim] + 0.5D; + aimZ = grotto.zs()[aim] + 0.5D; + eyeY = sea + 2.2D; + } + double forwardX = aimX - eyeX; + double forwardZ = aimZ - eyeZ; + double forwardLength = Math.hypot(forwardX, forwardZ); + forwardX /= forwardLength; + forwardZ /= forwardLength; + double rightX = -forwardZ; + double rightZ = forwardX; + BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + double fov = 0.85D; + for (int py = 0; py < height; py++) { + for (int px = 0; px < width; px++) { + double sx = (px - width / 2D) / (width / 2D) * fov; + double sy = (height / 2D - py) / (width / 2D) * fov + (outside ? 0.1D : 0.05D); + double rx = forwardX + sx * rightX; + double rz = forwardZ + sx * rightZ; + double ry = sy; + double norm = Math.sqrt(rx * rx + ry * ry + rz * rz); + image.setRGB(px, py, march(volume, eyeX, eyeY, eyeZ, rx / norm, ry / norm, rz / norm, outside)); + } + } + return image; + } + + private static int march(Volume volume, double ox, double oy, double oz, double rx, double ry, double rz, boolean outside) { + int x = (int) Math.floor(ox); + int y = (int) Math.floor(oy); + int z = (int) Math.floor(oz); + int stepX = rx > 0D ? 1 : -1; + int stepY = ry > 0D ? 1 : -1; + int stepZ = rz > 0D ? 1 : -1; + double tDeltaX = Math.abs(1D / rx); + double tDeltaY = Math.abs(1D / ry); + double tDeltaZ = Math.abs(1D / rz); + double tX = (rx > 0D ? x + 1 - ox : ox - x) * tDeltaX; + double tY = (ry > 0D ? y + 1 - oy : oy - y) * tDeltaY; + double tZ = (rz > 0D ? z + 1 - oz : oz - z) * tDeltaZ; + double t = 0D; + int axis = 0; + boolean swam = false; + int waterTint = 0; + while (t < 170D) { + if (tX < tY && tX < tZ) { + x += stepX; + t = tX; + tX += tDeltaX; + axis = 0; + } else if (tY < tZ) { + y += stepY; + t = tY; + tY += tDeltaY; + axis = 1; + } else { + z += stepZ; + t = tZ; + tZ += tDeltaZ; + axis = 2; + } + int cell = volume.at(x, y, z); + if (cell == -1) { + return outside ? 0xa8c8f0 : 0x101014; + } + int kind = cell >>> 24; + if (kind == 2) { + if (!swam) { + swam = true; + waterTint = (int) t; + } + if (t - waterTint > 7D) { + return shaded(WATER_COLOR, light(t, axis, outside) * (outside && roofed(volume, x, y, z) ? 0.3D : 0.8D)); + } + continue; + } + if (kind == 0) { + continue; + } + double shade = light(t, axis, outside); + if (outside && roofed(volume, x, y, z)) { + shade *= 0.32D; + } + int rgb = shaded(cell & 0xFFFFFF, shade); + if (swam) { + rgb = blend(rgb, WATER_COLOR, 0.55D); + } + return rgb; + } + return swam ? WATER_COLOR : 0xa8c8f0; + } + + private static boolean roofed(Volume volume, int x, int y, int z) { + for (int up = 2; up < 40; up++) { + if (volume.solid(x, y + up, z)) { + return true; + } + } + return false; + } + + private static double light(double t, int axis, boolean outside) { + double face = axis == 1 ? 1D : axis == 0 ? 0.78D : 0.62D; + double range = outside ? 1D : Math.clamp(1.15D - t / 70D, 0.22D, 1.1D); + return face * range; + } + + private static long cell(int x, int y, int z) { + return (x + 0x200000L) << 42 | (z + 0x200000L) << 20 | (y + 0x1000L); + } + + private static int cellX(long cell) { + return (int) ((cell >>> 42) - 0x200000L); + } + + private static int cellZ(long cell) { + return (int) (((cell >>> 20) & 0x3FFFFFL) - 0x200000L); + } + + private static int cellY(long cell) { + return (int) ((cell & 0xFFFFFL) - 0x1000L); + } + + private static long key(int x, int z) { + return ((long) x << 32) | (z & 0xFFFFFFFFL); + } +} diff --git a/probe/src/main/java/art/arcane/iris/probe/TidalReachProbe.java b/probe/src/main/java/art/arcane/iris/probe/TidalReachProbe.java index bc177ceea..cf6722961 100644 --- a/probe/src/main/java/art/arcane/iris/probe/TidalReachProbe.java +++ b/probe/src/main/java/art/arcane/iris/probe/TidalReachProbe.java @@ -1149,9 +1149,7 @@ public final class TidalReachProbe { for (Map.Entry entry : plans.windowPlans().entrySet()) { String key = entry.getKey().wx() + " " + entry.getKey().wz(); for (Reach reach : entry.getValue().reaches()) { - if (!tidal(reach)) { - writer.println("R " + key + " " + reach.id() + " " + reach.xs()[0] + " " + reach.zs()[0] + " " + stable(reach)); - } + writer.println((tidal(reach) ? "A " : "R ") + key + " " + reach.id() + " " + reach.xs()[0] + " " + reach.zs()[0] + " " + stable(reach)); } for (Pond pond : entry.getValue().ponds()) { writer.println("P " + key + " " + pond.id() + " " + Arrays.toString(new long[]{pond.floorX(), pond.floorZ(), pond.level(), pond.outletReachId(), pond.kind().ordinal()}));