diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java index 6fb450f27..0de4f651b 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java @@ -11,6 +11,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureFoundat import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceSupportBuilder; import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter; +import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter.SeaSurface; import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVegetationClearer; @@ -238,7 +239,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), - (x, z) -> x < 2 ? groundY - 32 : groundY + 32); + (x, z) -> x < 2 ? groundY - 32 : groundY + 32, SeaSurface.NONE); for (int x = 0; x <= 3; x++) { assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, x, groundY, 0)); @@ -266,7 +267,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { put(blocks, 0, groundY - 19, 0, Blocks.DIRT.defaultBlockState()); NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, - List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY); + List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE); for (int y = groundY - 19; y <= groundY; y++) { assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, y, 0)); @@ -292,7 +293,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureTerrainIntegrator.TerrainTarget target = surfaceTarget(start, StructureTerrainMode.FLATTEN); ((IrisStructureTerrain) target.terrain()).setHorizontalPadding(24).setFlattenRange(64); - NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY); + NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY, SeaSurface.NONE); for (int y = groundY - 34; y <= groundY - 13; y++) { assertEquals("Cave at " + y, Blocks.CAVE_AIR.defaultBlockState(), state(blocks, x, y, z)); @@ -315,7 +316,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { } NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, - List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY); + List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE); for (int y = groundY - 8; y < groundY; y++) { assertEquals("Foundation at " + y, Blocks.STONE.defaultBlockState(), state(blocks, 0, y, 0)); @@ -337,9 +338,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { Map originalSubmerged = new HashMap<>(submerged); NativeStructureSurfaceFitter.prepareSurfaceStructures(world(buried), area, - List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100); + List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures(world(submerged), area, - List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8); + List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8, SeaSurface.NONE); assertEquals(originalBuried, buried); assertEquals(originalSubmerged, submerged); @@ -386,7 +387,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { return method.invoke(delegate, arguments); }); - NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127); + NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127, SeaSurface.NONE); assertEquals(Blocks.GOLD_BLOCK.defaultBlockState(), state(blocks, 0, 94, 0)); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 95, 0)); @@ -477,7 +478,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), - (x, z) -> x == footprint.minX() ? 80 : 112); + (x, z) -> x == footprint.minX() ? 80 : 112, SeaSurface.NONE); assertEquals(81, piece.getBoundingBox().minY()); assertTrue(piece.attemptVanillaAlignment()); @@ -511,7 +512,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { WorldGenLevel world = world(blocks); NativeStructureSurfaceFitter.prepareSurfaceStructures(world, area, List.of(target), - (x, z) -> x == 0 || x == 8 ? 64 : 96); + (x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE); NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve( world, path, BlockPos.ZERO, area, NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager, @@ -555,7 +556,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { WorldGenLevel world = world(chunk); NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32); + world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32, SeaSurface.NONE); assertEquals(96, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 0, 0)); assertEquals(32, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 8, 0)); @@ -615,7 +616,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { WorldGenLevel world = world(chunk); NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96); + world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE); plan.primeHeightmaps(chunk); NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve( world, path, BlockPos.ZERO, area, @@ -670,7 +671,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { } NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(target), - (x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96); + (x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96, SeaSurface.NONE); for (int x = 0; x <= 8; x++) { for (int z = 0; z <= 8; z++) { @@ -740,7 +741,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> 64); + (x, z) -> 64, SeaSurface.NONE); assertEquals(before, blocks); } @@ -866,7 +867,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE))); NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, targets, - (x, z) -> 65); + (x, z) -> 65, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 71, 1)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 11, 71, 1)); @@ -891,7 +892,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> 64); + (x, z) -> 64, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 68, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0)); @@ -912,7 +913,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> 40); + (x, z) -> 40, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 46, 0)); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 47, 0)); @@ -944,7 +945,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64); + (x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 61, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 71, 0)); @@ -972,7 +973,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 64, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 63, 0)); @@ -997,7 +998,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0)); assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 64, 0)); @@ -1018,7 +1019,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 80); + (x, z) -> 80, SeaSurface.NONE); for (int y = 61; y <= 74; y++) { assertFalse(state(blocks, 0, y, 0).isAir()); @@ -1043,7 +1044,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 79); + (x, z) -> 79, SeaSurface.NONE); for (int y = 61; y <= 74; y++) { assertFalse(state(blocks, 0, y, 0).isAir()); @@ -1075,7 +1076,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); for (int y = 61; y <= 64; y++) { put(blocks, 0, y, 0, Blocks.CAVE_AIR.defaultBlockState()); } @@ -1115,7 +1116,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); NativeStructureSurfaceFitter.repairVacuumFoundations( @@ -1145,13 +1146,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.SurfaceTerrainPlan widePlan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(wideBlocks), wideArea, List.of(target), (x, z) -> 60); + world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.SurfaceTerrainPlan westPlan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), westArea, List.of(target), (x, z) -> 60); + world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.SurfaceTerrainPlan eastPlan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), eastArea, List.of(target), (x, z) -> 60); + world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); for (int x = 15; x <= 16; x++) { for (int y = 61; y <= 64; y++) { put(wideBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState()); @@ -1186,7 +1187,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1207,7 +1208,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1231,7 +1232,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 66, 0)); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0)); @@ -1256,7 +1257,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1276,7 +1277,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0)); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0)); @@ -1301,7 +1302,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1322,7 +1323,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 4, 61, 4)); } @@ -1340,7 +1341,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 50); + (x, z) -> 50, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1359,7 +1360,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60, 1); + (x, z) -> 60, SeaSurface.NONE, 1); assertEquals(originalBlocks, blocks); } @@ -1383,7 +1384,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); for (int y = 61; y <= 65; y++) { assertFalse(state(blocks, 10, y, 0).isAir()); @@ -1411,15 +1412,15 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { Map reverseSplitBlocks = flatTerrain(wideArea, 60); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(wideBlocks), wideArea, List.of(target), (x, z) -> 60); + world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), westArea, List.of(target), (x, z) -> 60); + world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), eastArea, List.of(target), (x, z) -> 60); + world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60); + world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60); + world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); assertEquals(wideBlocks, splitBlocks); assertEquals(wideBlocks, reverseSplitBlocks); @@ -1883,7 +1884,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { List targets = List.of(surfaceTarget(start)); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, area, targets, (x, z) -> 60); + world, area, targets, (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 62, 2)); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 2, 65, 2)); @@ -1937,7 +1938,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(lowered), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); + 0, 0, 64, 62, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(lowered, 0, 61, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(lowered, 0, 62, 0)); @@ -1952,7 +1953,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(raised), new BlockPos.MutableBlockPos(), - 0, 0, 64, 68, -64, 319); + 0, 0, 64, 68, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 65, 0)); assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 66, 0)); @@ -1971,7 +1972,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 99, 83, -64, 319); + 0, 0, 99, 83, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 82, 0)); assertEquals(Blocks.SNOW_BLOCK.defaultBlockState(), state(blocks, 0, 83, 0)); @@ -1993,7 +1994,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); + 0, 0, 64, 62, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0)); for (int y = 63; y <= 68; y++) { @@ -2015,7 +2016,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); + 0, 0, 64, 62, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0)); for (int y = 63; y <= 65; y++) { @@ -2034,7 +2035,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 64, -64, 319, true); + 0, 0, 64, 64, -64, 319, true, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 64, 0)); @@ -2047,7 +2048,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 64, -64, 319, true); + 0, 0, 64, 64, -64, 319, true, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0)); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 64, 0)); @@ -2059,7 +2060,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, -64, -64, -64, 319, true); + 0, 0, -64, -64, -64, 319, true, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, -64, 0)); } @@ -2076,7 +2077,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 68, -64, 319); + 0, 0, 64, 68, -64, 319, false, SeaSurface.NONE); assertEquals(log, state(blocks, 0, 66, 0)); assertEquals(leaves, state(blocks, 0, 68, 0)); @@ -2098,7 +2099,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { world, chunk, area, List.of(desertStart())); NativeStructureSurfaceFitter.applySurfaceColumn( world, new BlockPos.MutableBlockPos(), - 0, 0, 64, 68, -64, 319); + 0, 0, 64, 68, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 65, 0))); assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 66, 0))); @@ -2116,7 +2117,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); + 0, 0, 64, 62, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 63, 0)); assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 64, 0)); diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java index b827a9593..8c82f3a0c 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java @@ -3,6 +3,7 @@ package art.arcane.iris.nativegen; import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVerticalPlacer; import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter; +import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter.SeaSurface; import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVegetationClearer; @@ -206,7 +207,7 @@ public class NativeStructurePostProcessorVegetationTest { write(chunk, 4, 106, 4, Blocks.CACTUS_FLOWER.defaultBlockState()); NativeStructureSurfaceFitter.applySurfaceColumn( - world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y); + world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y, false, SeaSurface.NONE); assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 93, 4))); for (int y = 94; y <= 106; y++) { @@ -227,9 +228,9 @@ public class NativeStructurePostProcessorVegetationTest { WorldGenLevel world = world(chunk); NativeStructureSurfaceFitter.applySurfaceColumn( - world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y); + world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE); NativeStructureSurfaceFitter.applySurfaceColumn( - world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y); + world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE); assertTrue(chunk.getBlockState(new BlockPos(4, 65, 4)).isAir()); assertTrue(chunk.getBlockState(new BlockPos(4, 66, 4)).isAir()); @@ -249,7 +250,7 @@ public class NativeStructurePostProcessorVegetationTest { write(chunk, 4, 67, 4, Blocks.CACTUS_FLOWER.defaultBlockState()); NativeStructureSurfaceFitter.applySurfaceColumn( - world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y); + world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE); assertEquals(boundary, chunk.getBlockState(new BlockPos(4, 65, 4))); assertEquals(Blocks.CACTUS.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 66, 4))); @@ -271,9 +272,9 @@ public class NativeStructurePostProcessorVegetationTest { WorldGenLevel world = world(chunk); NativeStructureSurfaceFitter.applySurfaceColumn( - world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y); + world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE); NativeStructureSurfaceFitter.applySurfaceColumn( - world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y); + world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE); assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 60, 4))); for (int y = 61; y <= 67; y++) { diff --git a/adapters/bukkit/nms/v26_3_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java b/adapters/bukkit/nms/v26_3_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java index da482dfce..6fb9a4941 100644 --- a/adapters/bukkit/nms/v26_3_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java +++ b/adapters/bukkit/nms/v26_3_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java @@ -11,6 +11,7 @@ import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureFoundationBu import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceSupportBuilder; import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter; +import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter.SeaSurface; import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVegetationClearer; @@ -238,7 +239,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), - (x, z) -> x < 2 ? groundY - 32 : groundY + 32); + (x, z) -> x < 2 ? groundY - 32 : groundY + 32, SeaSurface.NONE); for (int x = 0; x <= 3; x++) { assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, x, groundY, 0)); @@ -266,7 +267,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { put(blocks, 0, groundY - 19, 0, Blocks.DIRT.defaultBlockState()); NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, - List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY); + List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE); for (int y = groundY - 19; y <= groundY; y++) { assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, y, 0)); @@ -292,7 +293,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureTerrainIntegrator.TerrainTarget target = surfaceTarget(start, StructureTerrainMode.FLATTEN); ((IrisStructureTerrain) target.terrain()).setHorizontalPadding(24).setFlattenRange(64); - NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY); + NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY, SeaSurface.NONE); for (int y = groundY - 34; y <= groundY - 13; y++) { assertEquals("Cave at " + y, Blocks.CAVE_AIR.defaultBlockState(), state(blocks, x, y, z)); @@ -315,7 +316,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { } NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, - List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY); + List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE); for (int y = groundY - 8; y < groundY; y++) { assertEquals("Foundation at " + y, Blocks.STONE.defaultBlockState(), state(blocks, 0, y, 0)); @@ -337,9 +338,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { Map originalSubmerged = new HashMap<>(submerged); NativeStructureSurfaceFitter.prepareSurfaceStructures(world(buried), area, - List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100); + List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures(world(submerged), area, - List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8); + List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8, SeaSurface.NONE); assertEquals(originalBuried, buried); assertEquals(originalSubmerged, submerged); @@ -386,7 +387,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { return method.invoke(delegate, arguments); }); - NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127); + NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127, SeaSurface.NONE); assertEquals(Blocks.GOLD_BLOCK.defaultBlockState(), state(blocks, 0, 94, 0)); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 95, 0)); @@ -477,7 +478,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), - (x, z) -> x == footprint.minX() ? 80 : 112); + (x, z) -> x == footprint.minX() ? 80 : 112, SeaSurface.NONE); assertEquals(81, piece.getBoundingBox().minY()); assertTrue(piece.attemptVanillaAlignment()); @@ -511,7 +512,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { WorldGenLevel world = world(blocks); NativeStructureSurfaceFitter.prepareSurfaceStructures(world, area, List.of(target), - (x, z) -> x == 0 || x == 8 ? 64 : 96); + (x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE); NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve( world, path, BlockPos.ZERO, area, NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager, @@ -555,7 +556,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { WorldGenLevel world = world(chunk); NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32); + world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32, SeaSurface.NONE); assertEquals(96, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 0, 0)); assertEquals(32, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 8, 0)); @@ -615,7 +616,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { WorldGenLevel world = world(chunk); NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96); + world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE); plan.primeHeightmaps(chunk); NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve( world, path, BlockPos.ZERO, area, @@ -670,7 +671,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { } NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(target), - (x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96); + (x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96, SeaSurface.NONE); for (int x = 0; x <= 8; x++) { for (int z = 0; z <= 8; z++) { @@ -740,7 +741,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> 64); + (x, z) -> 64, SeaSurface.NONE); assertEquals(before, blocks); } @@ -866,7 +867,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE))); NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, targets, - (x, z) -> 65); + (x, z) -> 65, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 71, 1)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 11, 71, 1)); @@ -891,7 +892,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> 64); + (x, z) -> 64, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 68, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0)); @@ -912,7 +913,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> 40); + (x, z) -> 40, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 46, 0)); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 47, 0)); @@ -944,7 +945,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64); + (x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 61, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 71, 0)); @@ -972,7 +973,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 64, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 63, 0)); @@ -997,7 +998,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0)); assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 64, 0)); @@ -1018,7 +1019,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 80); + (x, z) -> 80, SeaSurface.NONE); for (int y = 61; y <= 74; y++) { assertFalse(state(blocks, 0, y, 0).isAir()); @@ -1043,7 +1044,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 79); + (x, z) -> 79, SeaSurface.NONE); for (int y = 61; y <= 74; y++) { assertFalse(state(blocks, 0, y, 0).isAir()); @@ -1075,7 +1076,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); for (int y = 61; y <= 64; y++) { put(blocks, 0, y, 0, Blocks.CAVE_AIR.defaultBlockState()); } @@ -1115,7 +1116,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); NativeStructureSurfaceFitter.repairVacuumFoundations( @@ -1145,13 +1146,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.SurfaceTerrainPlan widePlan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(wideBlocks), wideArea, List.of(target), (x, z) -> 60); + world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.SurfaceTerrainPlan westPlan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), westArea, List.of(target), (x, z) -> 60); + world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.SurfaceTerrainPlan eastPlan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), eastArea, List.of(target), (x, z) -> 60); + world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); for (int x = 15; x <= 16; x++) { for (int y = 61; y <= 64; y++) { put(wideBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState()); @@ -1186,7 +1187,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1207,7 +1208,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1231,7 +1232,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 66, 0)); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0)); @@ -1256,7 +1257,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1276,7 +1277,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0)); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0)); @@ -1301,7 +1302,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1322,7 +1323,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 4, 61, 4)); } @@ -1340,7 +1341,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 50); + (x, z) -> 50, SeaSurface.NONE); assertEquals(originalBlocks, blocks); } @@ -1359,7 +1360,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60, 1); + (x, z) -> 60, SeaSurface.NONE, 1); assertEquals(originalBlocks, blocks); } @@ -1383,7 +1384,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.prepareSurfaceStructures( world(blocks), area, List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)), - (x, z) -> 60); + (x, z) -> 60, SeaSurface.NONE); for (int y = 61; y <= 65; y++) { assertFalse(state(blocks, 10, y, 0).isAir()); @@ -1411,15 +1412,15 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { Map reverseSplitBlocks = flatTerrain(wideArea, 60); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(wideBlocks), wideArea, List.of(target), (x, z) -> 60); + world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), westArea, List.of(target), (x, z) -> 60); + world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), eastArea, List.of(target), (x, z) -> 60); + world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60); + world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60); + world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE); assertEquals(wideBlocks, splitBlocks); assertEquals(wideBlocks, reverseSplitBlocks); @@ -1883,7 +1884,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { List targets = List.of(surfaceTarget(start)); NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, area, targets, (x, z) -> 60); + world, area, targets, (x, z) -> 60, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 62, 2)); assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 2, 65, 2)); @@ -1937,7 +1938,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(lowered), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); + 0, 0, 64, 62, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(lowered, 0, 61, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(lowered, 0, 62, 0)); @@ -1952,7 +1953,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(raised), new BlockPos.MutableBlockPos(), - 0, 0, 64, 68, -64, 319); + 0, 0, 64, 68, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 65, 0)); assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 66, 0)); @@ -1971,7 +1972,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 99, 83, -64, 319); + 0, 0, 99, 83, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 82, 0)); assertEquals(Blocks.SNOW_BLOCK.defaultBlockState(), state(blocks, 0, 83, 0)); @@ -1993,7 +1994,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); + 0, 0, 64, 62, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0)); for (int y = 63; y <= 68; y++) { @@ -2015,7 +2016,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); + 0, 0, 64, 62, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0)); for (int y = 63; y <= 65; y++) { @@ -2034,7 +2035,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 64, -64, 319, true); + 0, 0, 64, 64, -64, 319, true, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0)); assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 64, 0)); @@ -2047,7 +2048,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 64, -64, 319, true); + 0, 0, 64, 64, -64, 319, true, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0)); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 64, 0)); @@ -2059,7 +2060,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, -64, -64, -64, 319, true); + 0, 0, -64, -64, -64, 319, true, SeaSurface.NONE); assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, -64, 0)); } @@ -2076,7 +2077,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 68, -64, 319); + 0, 0, 64, 68, -64, 319, false, SeaSurface.NONE); assertEquals(log, state(blocks, 0, 66, 0)); assertEquals(leaves, state(blocks, 0, 68, 0)); @@ -2098,7 +2099,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { world, chunk, area, List.of(desertStart())); NativeStructureSurfaceFitter.applySurfaceColumn( world, new BlockPos.MutableBlockPos(), - 0, 0, 64, 68, -64, 319); + 0, 0, 64, 68, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 65, 0))); assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 66, 0))); @@ -2116,7 +2117,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest { NativeStructureSurfaceFitter.applySurfaceColumn( world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); + 0, 0, 64, 62, -64, 319, false, SeaSurface.NONE); assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 63, 0)); assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 64, 0)); diff --git a/adapters/bukkit/nms/v26_3_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java b/adapters/bukkit/nms/v26_3_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java index 07581aa72..3307c9394 100644 --- a/adapters/bukkit/nms/v26_3_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java +++ b/adapters/bukkit/nms/v26_3_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java @@ -3,6 +3,7 @@ package art.arcane.iris.nativegen.v26_3_R1; import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVerticalPlacer; import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter; +import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter.SeaSurface; import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVegetationClearer; @@ -206,7 +207,7 @@ public class NativeStructurePostProcessorVegetationTest { write(chunk, 4, 106, 4, Blocks.CACTUS_FLOWER.defaultBlockState()); NativeStructureSurfaceFitter.applySurfaceColumn( - world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y); + world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y, false, SeaSurface.NONE); assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 93, 4))); for (int y = 94; y <= 106; y++) { @@ -227,9 +228,9 @@ public class NativeStructurePostProcessorVegetationTest { WorldGenLevel world = world(chunk); NativeStructureSurfaceFitter.applySurfaceColumn( - world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y); + world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE); NativeStructureSurfaceFitter.applySurfaceColumn( - world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y); + world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE); assertTrue(chunk.getBlockState(new BlockPos(4, 65, 4)).isAir()); assertTrue(chunk.getBlockState(new BlockPos(4, 66, 4)).isAir()); @@ -249,7 +250,7 @@ public class NativeStructurePostProcessorVegetationTest { write(chunk, 4, 67, 4, Blocks.CACTUS_FLOWER.defaultBlockState()); NativeStructureSurfaceFitter.applySurfaceColumn( - world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y); + world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE); assertEquals(boundary, chunk.getBlockState(new BlockPos(4, 65, 4))); assertEquals(Blocks.CACTUS.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 66, 4))); @@ -271,9 +272,9 @@ public class NativeStructurePostProcessorVegetationTest { WorldGenLevel world = world(chunk); NativeStructureSurfaceFitter.applySurfaceColumn( - world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y); + world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE); NativeStructureSurfaceFitter.applySurfaceColumn( - world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y); + world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE); assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 60, 4))); for (int y = 61; y <= 67; y++) { diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/api/terrain/IrisColumnSample.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/api/terrain/IrisColumnSample.java index 4bbabe286..1dc31e8de 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/api/terrain/IrisColumnSample.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/api/terrain/IrisColumnSample.java @@ -12,7 +12,8 @@ public record IrisColumnSample( IrisRiverState riverState, double riverDistance, int riverFlow, - int riverWaterSurfaceY + int riverWaterSurfaceY, + boolean provisional ) { public static final int UNAVAILABLE_HEIGHT = Integer.MIN_VALUE; public static final double UNAVAILABLE_RIVER_DISTANCE = Double.NaN; 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 54c03e8ea..8adfcc845 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 @@ -70,6 +70,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.concurrent.CancellationException; @Director(name = "find", origin = DirectorOrigin.PLAYER, description = "Iris Find commands", descriptionKey = "iris.director.commandfind.director.iris_find_commands", aliases = "goto") public class CommandFind implements DirectorExecutor { @@ -218,41 +219,51 @@ public class CommandFind implements DirectorExecutor { commandSender.sendMessage(C.RED + error.getMessage()); return; } - String label = featureType.key().replace('_', ' '); Location origin = target.getLocation(); - World originWorld = origin.getWorld(); - int maximumDistance = GenerationSemanticQueries.RIVER_SEARCH_DISTANCE; - commandSender.sendMessage(C.GRAY + GenerationSemanticQueries.riverSearchMessage(featureType, maximumDistance)); - J.a(() -> { - try { - GenerationSemanticQueries.RiverResult feature = GenerationSemanticQueries.nearestRiver( - activeEngine, - featureType, - origin.getBlockX(), - origin.getBlockZ(), - maximumDistance - ).orElse(null); - if (feature == null) { - sendStructureMessage(target, commandSender, - C.YELLOW + GenerationSemanticQueries.riverNotFoundMessage(featureType, maximumDistance)); - return; - } - if (!teleport) { - sendStructureMessage(target, commandSender, - C.GREEN + "Found " + label + " at " + feature.x() + ", " + feature.y() + ", " + feature.z() + "."); - return; - } - Location destination = new Location( - originWorld, feature.x(), feature.y(), feature.z()); - prepareStructureTeleport( - target, originWorld, commandSender, label, destination, true); - } catch (Throwable error) { - sendStructureMessage(target, commandSender, - C.RED + "Could not search for " + label + ": " + error.getClass().getSimpleName() - + (error.getMessage() == null ? "" : " - " + error.getMessage())); - Iris.reportError("Could not locate hydrology feature '" + featureType.key() + "'.", error); + RiverRequest request = new RiverRequest(target, origin.getWorld(), commandSender, featureType, teleport); + commandSender.sendMessage(C.GRAY + GenerationSemanticQueries.riverSearchMessage(featureType, + GenerationSemanticQueries.RIVER_SEARCH_DISTANCE)); + GenerationSemanticQueries.startRiverSearch(target.getUniqueId(), J::a, activeEngine, featureType, origin.getBlockX(), + origin.getBlockZ()) + .whenComplete((search, failure) -> finishRiverSearch(request, search, failure)); + } + + private void finishRiverSearch(RiverRequest request, GenerationSemanticQueries.RiverSearch search, Throwable failure) { + if (failure instanceof CancellationException) { + return; + } + if (failure != null) { + reportRiverFailure(request, failure); + return; + } + try { + switch (search) { + case GenerationSemanticQueries.RiverSearch.Missing missing -> + sendStructureMessage(request.target(), request.sender(), C.YELLOW + missing.message()); + case GenerationSemanticQueries.RiverSearch.Stopped stopped -> + sendStructureMessage(request.target(), request.sender(), C.YELLOW + stopped.message()); + case GenerationSemanticQueries.RiverSearch.Found found -> arriveAtRiver(request, found.feature()); } - }); + } catch (Throwable error) { + reportRiverFailure(request, error); + } + } + + private void arriveAtRiver(RiverRequest request, GenerationSemanticQueries.RiverResult feature) { + if (!request.teleport()) { + sendStructureMessage(request.target(), request.sender(), + C.GREEN + "Found " + request.label() + " at " + feature.x() + ", " + feature.y() + ", " + feature.z() + "."); + return; + } + Location destination = new Location(request.world(), feature.x(), feature.y(), feature.z()); + prepareStructureTeleport(request.target(), request.world(), request.sender(), request.label(), destination, true); + } + + private void reportRiverFailure(RiverRequest request, Throwable failure) { + Iris.reportError("Could not locate hydrology feature '" + request.type().key() + "'.", failure); + sendStructureMessage(request.target(), request.sender(), + C.RED + "Could not search for " + request.label() + ": " + failure.getClass().getSimpleName() + + (failure.getMessage() == null ? "" : " - " + failure.getMessage())); } @Director(description = "Find a structure (a vanilla key like minecraft:village_plains or minecraft:stronghold, or an imported iris structure key)", descriptionKey = "iris.director.commandfind.director.find_structure_vanilla_key_like_minecraft_village_plains_minecraft_stronghold_imported_iris", sync = true) @@ -919,6 +930,12 @@ public class CommandFind implements DirectorExecutor { int configuredUnregistered, int editableUnplaced, int managedUnregistered) { } + private record RiverRequest(Player target, World world, VolmitSender sender, HydrologyFeatureType type, boolean teleport) { + private String label() { + return type.key().replace('_', ' '); + } + } + private record ManagedDatapackStructure(String key, Set sourceIds) { private ManagedDatapackStructure(String key) { this(key, new LinkedHashSet<>()); diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/platform/bukkit/api/IrisTerrainSVC.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/platform/bukkit/api/IrisTerrainSVC.java index 44449af97..a33297e98 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/platform/bukkit/api/IrisTerrainSVC.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/platform/bukkit/api/IrisTerrainSVC.java @@ -18,6 +18,7 @@ import art.arcane.iris.platform.bukkit.terrain.IrisSurfaceClassifier; import art.arcane.iris.platform.bukkit.terrain.IrisWorldInfoFactory; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.hydrology.raster.WaterRole; +import art.arcane.iris.generation.stream.ProvisionalSampling; import art.arcane.iris.generation.terrain.InferredType; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.terrain.IrisRegion; @@ -91,7 +92,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { } try { - return OptionalInt.of(engine.getHeight(blockX, blockZ) + engine.getMinHeight()); + long revision = ProvisionalSampling.revision(); + int height = engine.getHeight(blockX, blockZ) + engine.getMinHeight(); + return provisionalSince(revision) ? OptionalInt.empty() : OptionalInt.of(height); } catch (Throwable error) { reportQueryFault("surfaceHeight", world, error); return OptionalInt.empty(); @@ -106,6 +109,7 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { } try { + long revision = ProvisionalSampling.revision(); int surface = engine.getHeight(blockX, blockZ); WaterRole role = engine.getComplex().getWaterRoleStream().get(blockX, blockZ); int fluid = (int) Math.round( @@ -115,7 +119,8 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ); inferredType = biome == null ? null : biome.getInferredType(); } - return IrisSurfaceClassifier.classify(surface, fluid, inferredType, role); + IrisSurfaceKind kind = IrisSurfaceClassifier.classify(surface, fluid, inferredType, role); + return provisionalSince(revision) ? IrisSurfaceKind.UNKNOWN : kind; } catch (Throwable error) { reportQueryFault("surfaceKind", world, error); return IrisSurfaceKind.UNKNOWN; @@ -130,7 +135,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { } try { - return key(engine.getSurfaceBiome(blockX, blockZ)); + long revision = ProvisionalSampling.revision(); + Optional key = key(engine.getSurfaceBiome(blockX, blockZ)); + return provisionalSince(revision) ? Optional.empty() : key; } catch (Throwable error) { reportQueryFault("surfaceBiomeKey", world, error); return Optional.empty(); @@ -145,7 +152,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { } try { - return name(engine.getSurfaceBiome(blockX, blockZ)); + long revision = ProvisionalSampling.revision(); + Optional name = name(engine.getSurfaceBiome(blockX, blockZ)); + return provisionalSince(revision) ? Optional.empty() : name; } catch (Throwable error) { reportQueryFault("surfaceBiomeName", world, error); return Optional.empty(); @@ -160,8 +169,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { } try { - return Optional.of(IrisBiomeInfoFactory.surface(engine, blockX, blockZ, - error -> reportQueryFault("surfaceBiomeInfo", world, error))); + long revision = ProvisionalSampling.revision(); + IrisBiomeInfo info = IrisBiomeInfoFactory.surface(engine, blockX, blockZ, + error -> reportQueryFault("surfaceBiomeInfo", world, error)); + return provisionalSince(revision) ? Optional.empty() : Optional.of(info); } catch (Throwable error) { reportQueryFault("surfaceBiomeInfo", world, error); return Optional.empty(); @@ -176,7 +187,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { } try { - return key(engine.getBiome(blockX, blockY - engine.getMinHeight(), blockZ)); + long revision = ProvisionalSampling.revision(); + Optional key = key(engine.getBiome(blockX, blockY - engine.getMinHeight(), blockZ)); + return provisionalSince(revision) ? Optional.empty() : key; } catch (Throwable error) { reportQueryFault("biomeKey", world, error); return Optional.empty(); @@ -191,9 +204,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { } try { + long revision = ProvisionalSampling.revision(); IrisRegion region = engine.getRegion(blockX, blockZ); String loadKey = region == null ? null : region.getLoadKey(); - return loadKey == null || loadKey.isEmpty() ? Optional.empty() : Optional.of(loadKey); + return provisionalSince(revision) || loadKey == null || loadKey.isEmpty() ? Optional.empty() : Optional.of(loadKey); } catch (Throwable error) { reportQueryFault("regionKey", world, error); return Optional.empty(); @@ -208,9 +222,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { } try { + long revision = ProvisionalSampling.revision(); IrisRegion region = engine.getRegion(blockX, blockZ); String name = region == null ? null : region.getName(); - return name == null || name.isEmpty() ? Optional.empty() : Optional.of(name); + return provisionalSince(revision) || name == null || name.isEmpty() ? Optional.empty() : Optional.of(name); } catch (Throwable error) { reportQueryFault("regionName", world, error); return Optional.empty(); @@ -265,6 +280,7 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { return false; } + long revision = ProvisionalSampling.revision(); WaterRole role = wantRiver ? engine.getComplex().getWaterRoleStream().get(blockX, blockZ) : WaterRole.NONE; @@ -309,7 +325,8 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { riverState, riverDistance, riverFlow, - riverWaterSurfaceY + riverWaterSurfaceY, + provisionalSince(revision) )); return true; }); @@ -351,6 +368,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService { return name == null || name.isEmpty() ? Optional.empty() : Optional.of(name); } + private static boolean provisionalSince(long revision) { + return ProvisionalSampling.revision() != revision; + } + private static int noiseCacheChunks() { return IrisSettings.get().getPerformance().getNoiseCacheSize(); } diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/api/terrain/IrisColumnSampleTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/api/terrain/IrisColumnSampleTest.java index 6947f39f3..146117cfa 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/api/terrain/IrisColumnSampleTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/api/terrain/IrisColumnSampleTest.java @@ -139,7 +139,8 @@ public class IrisColumnSampleTest { riverState, riverDistance, riverFlow, - riverWaterSurfaceY + riverWaterSurfaceY, + false ); } } 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 1c507db10..e341bb1a9 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 @@ -1,6 +1,10 @@ package art.arcane.iris.command; import art.arcane.iris.Iris; +import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; +import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; +import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException; +import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; @@ -17,8 +21,10 @@ import org.bukkit.entity.Player; import org.junit.Test; import org.mockito.MockedStatic; +import java.time.Duration; import java.util.Optional; import java.util.OptionalLong; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; @@ -29,6 +35,7 @@ import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; @@ -126,11 +133,12 @@ public class CommandFindHydrologyTest { for (HydrologyFeatureType type : HydrologyFeatureType.values()) { try (Fixture fixture = new Fixture()) { fixture.command.river(type.key(), false); - fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), any(), anyInt(), anyInt(), anyInt()), never()); + fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), any(), anyInt(), anyInt(), anyInt(), any()), + never()); fixture.search.get().run(); - fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(fixture.engine, type, 0, 0, - GenerationSemanticQueries.RIVER_SEARCH_DISTANCE)); + fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), eq(type), eq(0), eq(0), + eq(GenerationSemanticQueries.RIVER_SEARCH_DISTANCE), any())); verify(fixture.sender).sendMessage(contains("Found " + type.key().replace('_', ' ') + " at 32, 63, 32.")); } } @@ -146,11 +154,72 @@ public class CommandFindHydrologyTest { } } + @Test + public void aNewSearchSilentlyReplacesThePlayersRunningSearch() { + try (Fixture fixture = new Fixture()) { + fixture.command.river("pond", false); + Runnable replaced = fixture.search.get(); + fixture.command.river("river", false); + replaced.run(); + + fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), eq(HydrologyFeatureType.POND), anyInt(), anyInt(), + anyInt(), any()), never()); + fixture.search.get().run(); + verify(fixture.sender).sendMessage(contains("Found river at 32, 63, 32.")); + verify(fixture.sender, never()).sendMessage(contains("Found pond")); + verify(fixture.sender, never()).sendMessage(contains("Could not search")); + } + } + + @Test + public void disabledTypeIsReportedWithItsReason() throws Exception { + try (Fixture fixture = new Fixture()) { + fixture.searchForReal(); + when(fixture.runtime.unavailable(HydrologyFeatureType.LAKE)).thenReturn(Optional.of("hydrology.lakes is disabled")); + fixture.command.river("lake", true); + fixture.search.get().run(); + + verify(fixture.sender).sendMessage(contains("No lake forms in this dimension: hydrology.lakes is disabled.")); + verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + } + } + + @Test + public void stoppedSearchReportsTheNearestWaterWithoutTeleporting() throws Exception { + try (Fixture fixture = new Fixture()) { + fixture.searchForReal(); + IrisDimension dimension = mock(IrisDimension.class); + when(fixture.engine.getDimension()).thenReturn(dimension); + when(dimension.getMinHeight()).thenReturn(-64); + when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenThrow( + new HydrologySearchTimeoutException(Duration.ofSeconds(30L), new HydrologyFeatureRef(1L, HydrologyFeatureType.RIVER, 32, 127, 32))); + fixture.command.river("river", true); + fixture.search.get().run(); + + verify(fixture.sender).sendMessage(contains("Stopped searching for the nearest river after 30 seconds. The nearest river found so " + + "far is at 32, 63, 32; a nearer one may exist.")); + fixture.platform.verify(() -> BukkitPlatform.chunkAtAsync(any(World.class), anyInt(), anyInt(), eq(true)), never()); + fixture.platform.verify(() -> BukkitPlatform.teleportAsync(any(Player.class), any(Location.class)), never()); + } + } + + @Test + public void deliveryFailureIsReportedInsteadOfLost() { + try (Fixture fixture = new Fixture()) { + LinkageError failure = new LinkageError("sender gone"); + doThrow(failure).when(fixture.sender).sendMessage(contains("Found river")); + fixture.command.river("river", false); + fixture.search.get().run(); + + fixture.logging.verify(() -> Iris.reportError(any(String.class), eq(failure))); + verify(fixture.sender).sendMessage(contains("Could not search for river: LinkageError - sender gone")); + } + } + @Test public void missingCavePoolIsReportedAsNotFoundInGeneratedChunks() { try (Fixture fixture = new Fixture()) { - fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt())) - .thenReturn(Optional.empty()); + fixture.searchForReal(); fixture.command.river("cave_pool", true); fixture.search.get().run(); @@ -162,8 +231,7 @@ public class CommandFindHydrologyTest { @Test public void missingFeatureIsReportedAsNotFound() { try (Fixture fixture = new Fixture()) { - fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt())) - .thenReturn(Optional.empty()); + fixture.searchForReal(); fixture.command.river("sea_inlet", true); fixture.search.get().run(); @@ -176,7 +244,7 @@ public class CommandFindHydrologyTest { public void plannerFailureIsReportedAsAnErrorNotAsNotFound() { try (Fixture fixture = new Fixture()) { IllegalStateException failure = new IllegalStateException("window planner exploded"); - fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt())) + fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt(), any())) .thenThrow(failure); fixture.command.river("lake", true); fixture.search.get().run(); @@ -191,6 +259,7 @@ public class CommandFindHydrologyTest { private final CommandFind command = mock(CommandFind.class, CALLS_REAL_METHODS); private final Engine engine = mock(Engine.class); private final IrisComplex complex = mock(IrisComplex.class); + private final HydrologyRuntime runtime = mock(HydrologyRuntime.class); private final Player player = mock(Player.class); private final World world = mock(World.class); private final VolmitSender sender = mock(VolmitSender.class); @@ -208,6 +277,8 @@ public class CommandFindHydrologyTest { doReturn(player).when(command).player(); doReturn(sender).when(command).sender(); when(engine.getComplex()).thenReturn(complex); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(player.getUniqueId()).thenReturn(UUID.randomUUID()); when(player.getWorld()).thenReturn(world); when(player.getLocation()).thenReturn(new Location(world, 0, 70, 0)); when(player.isOnline()).thenReturn(true); @@ -227,12 +298,17 @@ public class CommandFindHydrologyTest { }); platform.when(() -> BukkitPlatform.chunkAtAsync(any(World.class), anyInt(), anyInt(), eq(true))).thenReturn(chunk); platform.when(() -> BukkitPlatform.teleportAsync(eq(player), any(Location.class))).thenReturn(teleport); - queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt())) - .thenReturn(Optional.of(new GenerationSemanticQueries.RiverResult( + queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt(), any())) + .thenReturn(new GenerationSemanticQueries.RiverSearch.Found(new GenerationSemanticQueries.RiverResult( GenerationSemanticQueries.RiverSource.ACTIVE_PREDICTION, HydrologyFeatureType.RIVER, 1L, 32, 63, 32, OptionalLong.empty()))); } + private void searchForReal() { + queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt(), any())) + .thenCallRealMethod(); + } + @Override public void close() { logging.close(); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/platform/bukkit/api/IrisTerrainSVCTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/platform/bukkit/api/IrisTerrainSVCTest.java index 09783052f..355cc0d78 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/platform/bukkit/api/IrisTerrainSVCTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/platform/bukkit/api/IrisTerrainSVCTest.java @@ -10,6 +10,7 @@ import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.runtime.BiomeEnvironment; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.generation.stream.ProvisionalSampling; import art.arcane.iris.generation.terrain.InferredType; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisRegion; @@ -26,6 +27,7 @@ import org.bukkit.World; import org.bukkit.generator.ChunkGenerator; import org.junit.Test; import org.mockito.MockedStatic; +import org.mockito.stubbing.Answer; import java.lang.reflect.Field; import java.util.ArrayList; @@ -35,10 +37,12 @@ import java.util.Optional; import java.util.OptionalInt; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.IntPredicate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; @@ -143,6 +147,90 @@ public class IrisTerrainSVCTest { assertEquals(List.of("LAND", "NONE", "NaN", "-1", "unavailable"), sampled(WaterRole.NONE, 50)); } + @Test + public void serverThreadUnplannedColumnsAreProvisional() throws Exception { + List samples = sampledRow(blockX -> blockX < 16, () -> { + }); + + assertEquals(32, samples.size()); + for (IrisColumnSample sample : samples) { + assertEquals("column " + sample.blockX(), sample.blockX() < 16, sample.provisional()); + } + } + + @Test + public void plannedColumnsAreFinal() throws Exception { + ProvisionalSampling.mark(); + List samples = sampledRow(blockX -> false, () -> { + }); + + assertEquals(32, samples.size()); + for (IrisColumnSample sample : samples) { + assertFalse("column " + sample.blockX(), sample.provisional()); + } + } + + @Test + public void aSinkThatReadsProvisionallyDoesNotMarkLaterColumns() throws Exception { + List samples = sampledRow(blockX -> false, ProvisionalSampling::mark); + + assertEquals(32, samples.size()); + for (IrisColumnSample sample : samples) { + assertFalse("column " + sample.blockX(), sample.provisional()); + } + } + + @Test + public void surfaceHeightIsUnavailableUntilTheColumnIsPlanned() throws Exception { + World world = world(engine(blockX -> blockX >= 16)); + IrisTerrainSVC service = enabledService(); + + assertEquals(OptionalInt.empty(), service.surfaceHeight(world, 16, 0)); + assertEquals(OptionalInt.of(-4), service.surfaceHeight(world, 0, 0)); + } + + @Test + public void surfaceKindIsUnknownUntilTheColumnIsPlanned() throws Exception { + World world = world(engine(blockX -> blockX >= 16)); + IrisTerrainSVC service = enabledService(); + + assertEquals(IrisSurfaceKind.UNKNOWN, service.surfaceKind(world, 16, 0)); + assertEquals(IrisSurfaceKind.LAND, service.surfaceKind(world, 0, 0)); + } + + @Test + public void surfaceBiomeReadsAreEmptyUntilTheColumnIsPlanned() throws Exception { + World world = world(engine(blockX -> blockX >= 16)); + IrisTerrainSVC service = enabledService(); + + assertTrue(service.surfaceBiomeKey(world, 16, 0).isEmpty()); + assertTrue(service.surfaceBiomeName(world, 16, 0).isEmpty()); + assertTrue(service.surfaceBiomeInfo(world, 16, 0).isEmpty()); + assertEquals(Optional.of("plains"), service.surfaceBiomeKey(world, 0, 0)); + assertEquals(Optional.of("Plains"), service.surfaceBiomeName(world, 0, 0)); + assertEquals("plains", service.surfaceBiomeInfo(world, 0, 0).orElseThrow().key()); + } + + @Test + public void biomeKeyIsEmptyUntilTheColumnIsPlanned() throws Exception { + World world = world(engine(blockX -> blockX >= 16)); + IrisTerrainSVC service = enabledService(); + + assertTrue(service.biomeKey(world, 16, 64, 0).isEmpty()); + assertEquals(Optional.of("plains"), service.biomeKey(world, 0, 64, 0)); + } + + @Test + public void regionReadsAreEmptyUntilTheColumnIsPlanned() throws Exception { + World world = world(engine(blockX -> blockX >= 16)); + IrisTerrainSVC service = enabledService(); + + assertTrue(service.regionKey(world, 16, 0).isEmpty()); + assertTrue(service.regionName(world, 16, 0).isEmpty()); + assertEquals(Optional.of("temperate"), service.regionKey(world, 0, 0)); + assertEquals(Optional.of("Temperate"), service.regionName(world, 0, 0)); + } + @Test public void pendingBiomeMetadataReturnsAbsenceAndResolvesOnRetryWithoutLogging() throws Exception { Engine engine = mock(Engine.class); @@ -271,6 +359,64 @@ public class IrisTerrainSVCTest { sample.riverWaterSurfaceY() == IrisColumnSample.UNAVAILABLE_HEIGHT ? "unavailable" : String.valueOf(sample.riverWaterSurfaceY())); } + private static List sampledRow(IntPredicate unplanned, Runnable afterAccept) throws Exception { + Engine engine = engine(unplanned); + IrisColumnQuery query = IrisColumnQuery.rect(0, 0, 31, 0, 1, EnumSet.of(IrisColumnField.SURFACE_HEIGHT, + IrisColumnField.SURFACE_KIND, IrisColumnField.BIOME_KEY, IrisColumnField.RIVER_STATE)); + List samples = new ArrayList<>(); + try (MockedStatic settings = mockStatic(IrisSettings.class)) { + settings.when(IrisSettings::get).thenReturn(new IrisSettings()); + assertTrue(enabledService().sampleColumns(world(engine), query, sample -> { + samples.add(sample); + afterAccept.run(); + })); + } + return samples; + } + + private static Engine engine(IntPredicate unplanned) { + Engine engine = mock(Engine.class); + IrisComplex complex = mock(IrisComplex.class); + IrisBiome biome = mock(IrisBiome.class); + IrisRegion region = mock(IrisRegion.class); + when(biome.getInferredType()).thenReturn(InferredType.LAND); + when(biome.getLoadKey()).thenReturn("plains"); + when(biome.getName()).thenReturn("Plains"); + when(region.getLoadKey()).thenReturn("temperate"); + when(region.getName()).thenReturn("Temperate"); + BiomeEnvironment environment = new BiomeEnvironment(1L, biome, region, mock(IrisDimension.class), mock(IrisData.class)); + when(engine.getComplex()).thenReturn(complex); + when(engine.getDimension()).thenReturn(mock(IrisDimension.class)); + when(engine.getMinHeight()).thenReturn(-64); + when(engine.getHeight(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, 60)); + when(engine.getSurfaceBiome(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, biome)); + when(engine.getSurfaceBiomeEnvironment(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, environment)); + when(engine.getBiome(anyInt(), anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, biome)); + when(engine.getRegion(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, region)); + when(complex.getWaterRoleStream()).thenReturn(ProceduralStream.of((Double x, Double z) -> { + serverThreadRead(unplanned, x.intValue()); + return WaterRole.NONE; + }, Interpolated.of(value -> 0D, value -> WaterRole.NONE))); + when(complex.getWaterHeadStream()).thenReturn(ProceduralStream.ofDouble((double x, double z) -> { + serverThreadRead(unplanned, (int) x); + return 50D; + })); + return engine; + } + + private static Answer serverThreadAnswer(IntPredicate unplanned, T value) { + return invocation -> { + serverThreadRead(unplanned, (int) invocation.getArgument(0)); + return value; + }; + } + + private static void serverThreadRead(IntPredicate unplanned, int blockX) { + if (unplanned.test(blockX)) { + ProvisionalSampling.mark(); + } + } + private static World world(Engine engine) { World world = mock(World.class); ChunkGenerator generator = mock(ChunkGenerator.class, withSettings().extraInterfaces(PlatformChunkGenerator.class)); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructurePolicy.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructurePolicy.java index e9fc5f4e4..58711ff44 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructurePolicy.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructurePolicy.java @@ -21,6 +21,7 @@ import art.arcane.volmlib.nativelib.terrain.structure.StructureLocateSearchAcces import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette; import art.arcane.volmlib.nativelib.terrain.structure.StructurePlacementDecision; import art.arcane.volmlib.nativelib.terrain.structure.StructureReferencePolicy; +import art.arcane.volmlib.nativelib.terrain.structure.StructureSeaSurface; import art.arcane.volmlib.nativelib.terrain.structure.StructureVolumePolicy; import art.arcane.volmlib.util.math.RNG; @@ -124,6 +125,11 @@ final class ModdedNativeStructurePolicy implements NativeModdedStructureStage.Po return (x, z) -> Engine.hostHeight(context, x, z, true) + context.getMinHeight(); } + @Override + public StructureSeaSurface seaSurface(Engine context) { + return GenerationWritePolicy.seaSurface(context); + } + @Override public IntBinaryOperator worldgenHeight(Engine context, int runtimeMinY, boolean floor) { return (x, z) -> Engine.hostHeight(context, x, z, floor) + runtimeMinY + 1; diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java index 077f9597d..42e96a5ff 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java @@ -149,39 +149,50 @@ final class ModdedLocateCommands { IrisModdedCommands.fail(source, error.getMessage()); return 0; } - String label = featureType.key().replace('_', ' '); - int originX = player.blockX(); - int originZ = player.blockZ(); - int maximumDistance = GenerationSemanticQueries.RIVER_SEARCH_DISTANCE; NativeModdedServer server = source.server(); - IrisModdedCommands.ok(source, GenerationSemanticQueries.riverSearchMessage(featureType, maximumDistance)); - MultiBurst.burst.completeValueAsync(() -> GenerationSemanticQueries.nearestRiver( - engine, featureType, originX, originZ, maximumDistance).orElse(null)) - .whenComplete((GenerationSemanticQueries.RiverResult feature, Throwable error) -> server.execute(() -> { - if (error != null) { - Throwable cause = error instanceof CompletionException && error.getCause() != null ? error.getCause() : error; - ModdedIrisLog.error("Hydrology locate failed for {}", featureType.key(), cause); - IrisModdedCommands.fail(source, "Could not search for " + label + ": " + cause.getClass().getSimpleName() - + (cause.getMessage() == null ? "" : " - " + cause.getMessage())); - return; - } - if (feature == null) { - IrisModdedCommands.fail(source, GenerationSemanticQueries.riverNotFoundMessage(featureType, maximumDistance)); - return; - } - teleportToStructure( - source, - level, - player, - feature.x(), - feature.y() + 2, - feature.z(), - label - ); - })); + RiverRequest request = new RiverRequest(source, level, player, featureType); + IrisModdedCommands.ok(source, GenerationSemanticQueries.riverSearchMessage(featureType, GenerationSemanticQueries.RIVER_SEARCH_DISTANCE)); + GenerationSemanticQueries.startRiverSearch(player.id(), MultiBurst.burst, engine, featureType, player.blockX(), player.blockZ()) + .whenComplete((GenerationSemanticQueries.RiverSearch search, Throwable error) -> + deliverRiverSearch(server, request, search, error)); return 1; } + private static void deliverRiverSearch(NativeModdedServer server, RiverRequest request, GenerationSemanticQueries.RiverSearch search, + Throwable error) { + if (error instanceof CancellationException) { + return; + } + try { + server.execute(() -> finishRiverSearch(request, search, error)); + } catch (Throwable rejected) { + ModdedIrisLog.error("Hydrology locate result for {} could not reach the server thread", request.type().key(), rejected); + } + } + + private static void finishRiverSearch(RiverRequest request, GenerationSemanticQueries.RiverSearch search, Throwable error) { + if (error != null) { + reportRiverFailure(request, error); + return; + } + try { + switch (search) { + case GenerationSemanticQueries.RiverSearch.Missing missing -> IrisModdedCommands.fail(request.source(), missing.message()); + case GenerationSemanticQueries.RiverSearch.Stopped stopped -> IrisModdedCommands.fail(request.source(), stopped.message()); + case GenerationSemanticQueries.RiverSearch.Found found -> teleportToStructure(request.source(), request.level(), + request.player(), found.feature().x(), found.feature().y() + 2, found.feature().z(), request.label()); + } + } catch (Throwable failure) { + reportRiverFailure(request, failure); + } + } + + private static void reportRiverFailure(RiverRequest request, Throwable error) { + ModdedIrisLog.error("Hydrology locate failed for {}", request.type().key(), error); + IrisModdedCommands.fail(request.source(), "Could not search for " + request.label() + ": " + error.getClass().getSimpleName() + + (error.getMessage() == null ? "" : " - " + error.getMessage())); + } + static int gotoStructure(NativeCommandSource source, String keyRaw) { NativeWorld level = source.world(); Engine engine = IrisModdedCommands.engineFor(level); @@ -706,6 +717,12 @@ final class ModdedLocateCommands { record CaveDestination(SubterrainPosition target, Optional read) { } + private record RiverRequest(NativeCommandSource source, NativeWorld level, NativeProtocolPlayer player, HydrologyFeatureType type) { + private String label() { + return type.key().replace('_', ' '); + } + } + private record CaveLocateRequest(NativeCommandSource source, NativeWorld level, Engine engine, NativeProtocolPlayer player, String label, NativeModdedServer server, UUID playerId, CompletableFuture search, BiomeLocator locator, Position2 at) { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java index 707f4fd7c..ea415b719 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java @@ -998,11 +998,6 @@ public final class ModdedStudioCommands { if (region == null) { continue; } - region.getAllBiomes(() -> dm).forEach((IrisBiome biome) -> { - if (biome != null && biome.getLoadKey() != null) { - biomeKeys.add(biome.getLoadKey()); - } - }); lootKeys.addAll(region.getLoot().getTables()); spawnerKeys.addAll(region.getEntitySpawners()); collectStructureKeys(structureKeys, region.getStructures()); diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/ModdedLocateRiverTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/ModdedLocateRiverTest.java index afd149bb0..a92910e52 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/ModdedLocateRiverTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/ModdedLocateRiverTest.java @@ -4,6 +4,7 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; +import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.terrain.IrisDimension; @@ -18,7 +19,9 @@ import org.mockito.ArgumentCaptor; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; +import java.time.Duration; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @@ -41,7 +44,7 @@ public class ModdedLocateRiverTest { private static final int DISTANCE = GenerationSemanticQueries.RIVER_SEARCH_DISTANCE; @Test - public void unknownTypeFailsBeforeSearching() { + public void unknownTypeFailsBeforeSearching() throws Exception { Fixture fixture = new Fixture(); try (MockedStatic commands = fixture.commands()) { assertEquals(0, ModdedLocateCommands.gotoRiver(fixture.source, "ocean_trench")); @@ -49,14 +52,14 @@ public class ModdedLocateRiverTest { commands.verify(() -> IrisModdedCommands.fail(eq(fixture.source), anyString())); commands.verify(() -> IrisModdedCommands.ok(eq(fixture.source), anyString()), never()); verify(fixture.server, never()).execute(any()); - verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); + verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); } } @Test public void missingFeatureReportsNotFound() throws Exception { Fixture fixture = new Fixture(); - when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())).thenReturn(Optional.empty()); + when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenReturn(Optional.empty()); try (MockedStatic commands = fixture.commands()) { assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "river")); fixture.finishOnServerThread(); @@ -66,10 +69,53 @@ public class ModdedLocateRiverTest { } } + @Test + public void disabledTypeReportsItsReasonWithoutSearching() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.runtime.unavailable(HydrologyFeatureType.DAM)).thenReturn(Optional.of("hydrology.ponds.dams is disabled")); + try (MockedStatic commands = fixture.commands()) { + assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "dam")); + fixture.finishOnServerThread(); + + commands.verify(() -> IrisModdedCommands.fail(fixture.source, "No dam forms in this dimension: hydrology.ponds.dams is disabled.")); + verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + verify(fixture.player, never()).teleport(any(), anyDouble(), anyDouble(), anyDouble()); + } + } + + @Test + public void stoppedSearchReportsTheNearestWaterWithoutTeleporting() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenThrow(new HydrologySearchTimeoutException( + Duration.ofSeconds(30L), new HydrologyFeatureRef(9L, HydrologyFeatureType.WATERFALL, 400, 130, -250))); + try (MockedStatic commands = fixture.commands()) { + assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "waterfall")); + fixture.finishOnServerThread(); + + commands.verify(() -> IrisModdedCommands.fail(fixture.source, "Stopped searching for the nearest waterfall after 30 seconds. " + + "The nearest waterfall found so far is at 400, 66, -250; a nearer one may exist.")); + verify(fixture.player, never()).teleport(any(), anyDouble(), anyDouble(), anyDouble()); + } + } + + @Test + public void deliveryFailureIsReportedInsteadOfLost() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenReturn(Optional.empty()); + try (MockedStatic commands = fixture.commands()) { + commands.when(() -> IrisModdedCommands.fail(fixture.source, "No river found within " + DISTANCE + " blocks.")) + .thenThrow(new LinkageError("source gone")); + assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "river")); + fixture.finishOnServerThread(); + + commands.verify(() -> IrisModdedCommands.fail(fixture.source, "Could not search for river: LinkageError - source gone")); + } + } + @Test public void plannerFailureIsReportedAsAnErrorNotAsNotFound() throws Exception { Fixture fixture = new Fixture(); - when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())) + when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())) .thenThrow(new IllegalStateException("window planner exploded")); try (MockedStatic commands = fixture.commands()) { assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "major_river")); @@ -86,7 +132,7 @@ public class ModdedLocateRiverTest { @Test public void foundFeatureTeleportsAboveItFromThePlayersPosition() throws Exception { Fixture fixture = new Fixture(); - when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())) + when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())) .thenReturn(Optional.of(new HydrologyFeatureRef(9L, HydrologyFeatureType.WATERFALL, 400, 130, -250))); when(fixture.player.teleport(fixture.world, 400.5D, 68D, -249.5D)).thenReturn(true); try (MockedStatic commands = fixture.commands(); @@ -95,7 +141,7 @@ public class ModdedLocateRiverTest { fixture.finishOnServerThread(); ArgumentCaptor query = ArgumentCaptor.forClass(HydrologyFeatureQuery.class); - verify(fixture.runtime).nearestFeature(eq(120), eq(-75), query.capture(), eq(DISTANCE), any()); + verify(fixture.runtime).nearestFeature(eq(120), eq(-75), query.capture(), eq(DISTANCE), any(), any()); assertEquals(HydrologyFeatureQuery.of(HydrologyFeatureType.WATERFALL), query.getValue()); verify(queries.constructed().getFirst()).loadChunk(400 >> 4, -250 >> 4); verify(fixture.player).teleport(fixture.world, 400.5D, 68D, -249.5D); @@ -119,6 +165,7 @@ public class ModdedLocateRiverTest { when(source.player()).thenReturn(player); when(source.world()).thenReturn(world); when(source.server()).thenReturn(server); + when(player.id()).thenReturn(UUID.randomUUID()); when(player.blockX()).thenReturn(120); when(player.blockZ()).thenReturn(-75); when(player.connected()).thenReturn(true); diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java index f98f1660f..e60073b90 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java @@ -92,6 +92,7 @@ import java.util.Objects; @Data @EqualsAndHashCode(callSuper = false) public class IrisBiome extends IrisRegistrant implements Rarity { + public static final int CHILD_HOPS = 4; private static final int BIOME_GENERATOR_CACHE_SIZE = 8; private static final int CHILDREN_SEED_SALT = 2137; diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeColorRenderer.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeColorRenderer.java index bd856067d..5f5ae4308 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeColorRenderer.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeColorRenderer.java @@ -39,7 +39,7 @@ final class IrisBiomeColorRenderer { static Color getColor(IrisBiome biome, Engine engine, RenderType type) { switch (type) { - case BIOME, HEIGHT, CAVE_LAND, REGION, BIOME_SEA, BIOME_LAND, RIVER -> { + case BIOME, HEIGHT, CAVE_LAND, REGION, BIOME_SEA, BIOME_LAND -> { return biome.getCacheColor().aquire(() -> { if (biome.getColor() == null) { RandomColor randomColor = new RandomColor(biome.getName().hashCode()); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/PersistedCodes.java b/core/src/main/java/art/arcane/iris/generation/hydrology/PersistedCodes.java new file mode 100644 index 000000000..9a89b8b72 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/PersistedCodes.java @@ -0,0 +1,48 @@ +package art.arcane.iris.generation.hydrology; + +import java.util.Arrays; +import java.util.function.ToIntFunction; + +public final class PersistedCodes> { + private static final int MAX_CODE = 255; + + private final String type; + private final E[] byCode; + + private PersistedCodes(String type, E[] byCode) { + this.type = type; + this.byCode = byCode; + } + + public static > PersistedCodes of(Class type, ToIntFunction code) { + E[] constants = type.getEnumConstants(); + int size = 0; + for (E constant : constants) { + int value = code.applyAsInt(constant); + if (value < 0 || value > MAX_CODE) { + throw new IllegalStateException(type.getSimpleName() + "." + constant.name() + " has code " + value + + ", outside 0.." + MAX_CODE); + } + size = Math.max(size, value + 1); + } + E[] byCode = Arrays.copyOf(constants, size); + Arrays.fill(byCode, null); + for (E constant : constants) { + int value = code.applyAsInt(constant); + if (byCode[value] != null) { + throw new IllegalStateException(type.getSimpleName() + "." + constant.name() + " reuses code " + value + " of " + + type.getSimpleName() + "." + byCode[value].name()); + } + byCode[value] = constant; + } + return new PersistedCodes<>(type.getSimpleName(), byCode); + } + + public E decode(int code) { + E constant = code >= 0 && code < byCode.length ? byCode[code] : null; + if (constant == null) { + throw new IllegalStateException("Unknown " + type + " code " + code); + } + return constant; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveAction.java b/core/src/main/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveAction.java index a95b53079..0f18befe0 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveAction.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveAction.java @@ -2,7 +2,6 @@ package art.arcane.iris.generation.hydrology.cave; public enum HydrologyCaveAction { WET_SOURCE, - FALLING_FLUID, DRY_AIR, SEAL_GUARD, POOL_SOURCE diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveCell.java b/core/src/main/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveCell.java index dee4a20fb..b4a841a9f 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveCell.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveCell.java @@ -6,56 +6,32 @@ import java.util.Objects; public final class HydrologyCaveCell { public static final String SEA_FLUID = "@sea"; - private static final String DEFAULT_FLUID_PROFILE_KEY = "default"; private static final byte LIQUID_FLUID = 1; private static final byte LIQUID_FORCED_AIR = 3; private final HydrologyCaveAction action; private final String fluidProfileKey; - private final String floodedBiomeKey; private final MatterCavern cavern; - public HydrologyCaveCell( - HydrologyCaveAction action, - String fluidProfileKey, - String floodedBiomeKey - ) { + public HydrologyCaveCell(HydrologyCaveAction action, String fluidProfileKey) { this.action = Objects.requireNonNull(action); if (fluidProfileKey == null || fluidProfileKey.isBlank()) { throw new IllegalArgumentException("fluidProfileKey must not be blank"); } this.fluidProfileKey = fluidProfileKey.trim(); - this.floodedBiomeKey = floodedBiomeKey == null ? "" : floodedBiomeKey.trim(); this.cavern = switch (action) { - case WET_SOURCE, FALLING_FLUID, POOL_SOURCE -> new MatterCavern(true, this.floodedBiomeKey, LIQUID_FLUID); - case DRY_AIR -> new MatterCavern(true, this.floodedBiomeKey, LIQUID_FORCED_AIR); + case WET_SOURCE, POOL_SOURCE -> new MatterCavern(true, "", LIQUID_FLUID); + case DRY_AIR -> new MatterCavern(true, "", LIQUID_FORCED_AIR); case SEAL_GUARD -> null; }; } - public static HydrologyCaveCell of(HydrologyCaveAction action) { - return new HydrologyCaveCell(action, DEFAULT_FLUID_PROFILE_KEY, ""); - } - - public static HydrologyCaveCell of(HydrologyCaveAction action, String fluidProfileKey) { - return new HydrologyCaveCell(action, fluidProfileKey, ""); - } - public boolean carves() { return action != HydrologyCaveAction.SEAL_GUARD; } public boolean isWet() { - return action == HydrologyCaveAction.WET_SOURCE || action == HydrologyCaveAction.FALLING_FLUID - || action == HydrologyCaveAction.POOL_SOURCE; - } - - public boolean isFalling() { - return action == HydrologyCaveAction.FALLING_FLUID; - } - - public boolean protectsPlacement() { - return true; + return action == HydrologyCaveAction.WET_SOURCE || action == HydrologyCaveAction.POOL_SOURCE; } public MatterCavern asCavern() { @@ -66,10 +42,6 @@ public final class HydrologyCaveCell { return action; } - public String floodedBiomeKey() { - return floodedBiomeKey; - } - public String fluidProfileKey() { return fluidProfileKey; } @@ -82,19 +54,16 @@ public final class HydrologyCaveCell { if (!(object instanceof HydrologyCaveCell hydrology)) { return false; } - return action == hydrology.action - && fluidProfileKey.equals(hydrology.fluidProfileKey) - && floodedBiomeKey.equals(hydrology.floodedBiomeKey); + return action == hydrology.action && fluidProfileKey.equals(hydrology.fluidProfileKey); } @Override public int hashCode() { - return (31 * ((31 * action.hashCode()) + fluidProfileKey.hashCode())) + floodedBiomeKey.hashCode(); + return (31 * action.hashCode()) + fluidProfileKey.hashCode(); } @Override public String toString() { - return "HydrologyCaveCell[action=" + action + ", fluidProfileKey=" + fluidProfileKey - + ", floodedBiomeKey=" + floodedBiomeKey + "]"; + return "HydrologyCaveCell[action=" + action + ", fluidProfileKey=" + fluidProfileKey + "]"; } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisCavePools.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisCavePools.java index 691f94982..1170e9b35 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisCavePools.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisCavePools.java @@ -24,12 +24,12 @@ public class IrisCavePools { private double density = 0.15D; @MinNumber(1) - @MaxNumber(4096) + @MaxNumber(961) @Description("Smallest pool surface in square blocks.") private int minArea = 6; @MinNumber(1) - @MaxNumber(65536) + @MaxNumber(961) @Description("Largest pool surface in square blocks.") private int maxArea = 400; @@ -40,7 +40,7 @@ public class IrisCavePools { @MinNumber(1) @MaxNumber(15) - @Description("Distance in blocks a pool may spread from its site, at most 15.") + @Description("Half-size in blocks of the square box, centered on the site column, inside which a pool settles and spreads, at most 15, so a pool stays within one chunk of the chunk that holds its site.") private int radius = 15; @ArrayType(type = Integer.class, min = 2) @@ -48,6 +48,6 @@ public class IrisCavePools { private KList freeboard = new KList<>(0, 1); @Required - @Description("Name of the fluid profile that fills cave pools. A cave biome's hydrology policy fluid replaces it.") + @Description("Name of the fluid profile that fills cave pools. The hydrology policy fluid of the cave biome at the pool replaces it, then that of its region, then that of the dimension. A surface biome's policy never fills cave pools.") private String fluid = "water"; } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyLakes.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyLakes.java index 92f593c0d..78ec8e287 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyLakes.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyLakes.java @@ -9,19 +9,19 @@ import lombok.experimental.Accessors; @Accessors(chain = true) @NoArgsConstructor -@Description("Large lakes that fill the biggest hollows in the terrain. Each lake has one water level across its whole surface.") +@Description("Large lakes that fill the biggest hollows in the terrain. Each lake has one water level across its whole surface. A hollow becomes a lake only when it is at least ponds.natural.minDepth deep and no more than 2048 blocks across. Lakes take their freeboard, climateDrawdown, shore roundness, materials, decorators and fluid from ponds.") @Data public class IrisHydrologyLakes { @Description("Turns large hollows into lakes.") private boolean enabled = true; @MinNumber(1024) - @MaxNumber(134217728) + @MaxNumber(4194304) @Description("Smallest lake surface in square blocks.") private int minArea = 65536; @MinNumber(1024) - @MaxNumber(134217728) + @MaxNumber(4194304) @Description("Largest lake surface in square blocks. Larger hollows are drained by a cut through their rim.") private int maxArea = 4194304; } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPolicy.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPolicy.java index 6f3924f9d..26e9d60c5 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPolicy.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPolicy.java @@ -14,38 +14,44 @@ import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; +import java.util.List; import java.util.function.Function; @Accessors(chain = true) @NoArgsConstructor -@Description("Hydrology settings for a dimension, region or biome. A value left unset is inherited from the region, then from the dimension.") +@Description("Hydrology settings for a dimension, region or biome. A value a biome leaves unset is inherited from the biome it grows inside as a child, up through that biome's own parents, then from the region, then from the dimension, and a value a region leaves unset is inherited from the dimension. wetness is inherited whole: a bound it leaves out is 0 for min and 1 for max. Cave pools take fluid from the cave biome at the pool, then its region, then the dimension, and never from the surface biome above.") @Data public class IrisHydrologyPolicy { + public static final double MAX_MULTIPLIER = 16D; + @MinNumber(0) - @MaxNumber(16) - @Description("Multiplier on the water that falls in this area. Higher values grow more and larger streams and keep ponds fuller. With no value set anywhere it is 1.") + @MaxNumber(MAX_MULTIPLIER) + @Description("Multiplier on the water that falls in this area. Higher values grow more and larger streams. Where the wet and dry zones do not apply, values below 1 also lower pond and lake surfaces. With no value set anywhere it is 1.") private Double rainfall = null; @MinNumber(0) - @MaxNumber(16) + @MaxNumber(MAX_MULTIPLIER) @Description("Multiplier on how many ponds form in this area. With no value set anywhere it is 1.") private Double pondDensity = null; @Description("Whether the dimension's wet and dry zones apply in this area. false keeps this area's full rainfall and pond density even inside a dry zone. With no value set anywhere they apply.") private Boolean climateZones = null; + @Description("Bounds on the wetness of the dimension's wet and dry zones in this area: min keeps a swamp wet inside a dry zone, max keeps a desert mostly dry inside a wet zone. The bounded wetness scales the area's rainfall and pond density and sets how far ponds and lakes whose floor lies here drop below their freeboard. It has no effect where the wet and dry zones are off or climateZones is false. A scope that sets it replaces both bounds, and a bound it leaves out is 0 for min and 1 for max. With no value set anywhere the zone wetness applies unchanged.") + private IrisHydrologyWetness wetness = null; + @Description("Whether streams and rivers may form in this area. With no value set anywhere they are allowed.") private IrisHydrologyPermission streams = null; @Description("Whether ponds may form in this area. With no value set anywhere they are allowed.") private IrisHydrologyPermission ponds = null; - @Description("Name of a fluid profile that fills the water in this area instead of its usual fluid: ponds and lakes whose floor lies here, and every stretch of stream or river that flows through here.") + @Description("Name of a fluid profile that fills the water in this area instead of its usual fluid: ponds and lakes whose floor lies here, and every stretch of stream or river whose upstream end lies here, for the whole stretch. A stretch that starts elsewhere keeps its own fluid while it crosses this area. Set on a cave biome, a region or the dimension, it also fills the cave pools there. It cannot name a seam profile.") private String fluid = null; @RegistryListResource(IrisBiome.class) @ArrayType(type = String.class) - @Description("Biomes placed along the water's edge in this area. An empty list clears the inherited biomes.") + @Description("Biomes placed along the water's edge in this area, in a band as wide as shoreBiomeWidth. Without a shoreBiomeWidth above 0 the list places nothing. An empty list clears the inherited biomes.") private KList shoreBiomes = null; @MinNumber(0) @@ -57,15 +63,31 @@ public class IrisHydrologyPolicy { @Description("Plants for the rivers, streams, ponds and lakes in this area, replacing the decorators of the tiers and ponds there. Written like the tier and pond decorators: partOf SEA_FLOOR, SEA_SURFACE or SHORE_LINE. An empty list grows no plants here. With no value set anywhere, the tiers and ponds use their own decorators.") private KList decorators = null; - public static T inherited(IrisBiome biome, IrisRegion region, IrisDimension dimension, Function field) { - T value = value(biome == null ? null : biome.getHydrologyPolicy(), field); - if (value == null) { - value = value(region == null ? null : region.getHydrologyPolicy(), field); + public static boolean validMultiplier(double value) { + return value >= 0D && value <= MAX_MULTIPLIER; + } + + public static ShoreBand shoreBand(List biomes, IrisRegion region, IrisDimension dimension) { + Integer width = inherited(biomes, region, dimension, IrisHydrologyPolicy::getShoreBiomeWidth); + KList keys = inherited(biomes, region, dimension, IrisHydrologyPolicy::getShoreBiomes); + return width == null || width <= 0 || keys == null || keys.isEmpty() ? null : new ShoreBand(width, keys); + } + + public static T inherited(List biomes, IrisRegion region, IrisDimension dimension, Function field) { + for (int index = 0; index < biomes.size(); index++) { + T value = value(biomes.get(index).getHydrologyPolicy(), field); + if (value != null) { + return value; + } } + T value = value(region == null ? null : region.getHydrologyPolicy(), field); return value != null ? value : value(dimension == null ? null : dimension.getHydrologyPolicy(), field); } private static T value(IrisHydrologyPolicy policy, Function field) { return policy == null ? null : field.apply(policy); } + + public record ShoreBand(int width, List biomes) { + } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPonds.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPonds.java index 1083e3369..bb92196e0 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPonds.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPonds.java @@ -13,7 +13,7 @@ import lombok.experimental.Accessors; @Accessors(chain = true) @NoArgsConstructor -@Description("Standing water above sea level. Ponds fill natural hollows, seeded cups and optional dams, each with its own level, so ponds sit at many heights and streams link them into chains.") +@Description("Standing water above sea level. Ponds fill natural hollows, seeded cups and optional dams, each with its own level, so ponds sit at many heights and streams link them into chains. Lakes take their freeboard, climateDrawdown, shore roundness, materials, decorators and fluid from here as well.") @Data public class IrisHydrologyPonds { @Description("Ponds that fill hollows already present in the terrain.") @@ -26,18 +26,18 @@ public class IrisHydrologyPonds { private IrisPondDams dams = new IrisPondDams(); @ArrayType(type = Integer.class, min = 2) - @Description("Blocks the pond surface sits below its spill point, written as [min, max]. Each pond picks a value in this range.") + @Description("Blocks the pond or lake surface sits below its spill point, written as [min, max]. Each pond and lake picks a value in this range.") private KList freeboard = new KList<>(1, 3); @MinNumber(0) @MaxNumber(32) - @Description("Extra blocks a pond surface drops in the driest climate. Ponds in wet areas stay full.") + @Description("Most extra blocks a pond or lake surface drops below its freeboard, in the driest areas. The drop is this value times the dryness at the floor, rounded: one minus the zone wetness, after the area's wetness bounds, where the dimension's wet and dry zones apply, and one minus the area's rainfall elsewhere, so water at a wetness or rainfall of 1 or more stays full.") private int climateDrawdown = 6; - @Description("Shape of pond shores and floors.") + @Description("Shape of pond shores and floors. Lakes take only its roundness.") private IrisPondShore shore = new IrisPondShore(); - @Description("Blocks painted on pond floors and shores.") + @Description("Blocks painted on pond and lake floors and shores.") private IrisHydrologyMaterials materials = new IrisHydrologyMaterials(); @ArrayType(type = IrisDecorator.class) diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java index ee28932e5..45100fc1b 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java @@ -17,7 +17,7 @@ import lombok.experimental.Accessors; @Data public class IrisHydrologyTier { @Required - @Description("Label for this tier in configuration error messages. Locate, maps and history do not use it: they rank tiers by minCatchment, so the lowest tier is a stream, the highest a major river and any between are rivers.") + @Description("Channel type of this tier for locate, maps and history: stream, river or major (also major_river). Any other name takes the type of its rank by minCatchment instead: the lowest tier is a stream, the highest a major river and any between are rivers. Configuration error messages also use the name.") private String name = "stream"; @MinNumber(0) diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyWetness.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyWetness.java new file mode 100644 index 000000000..b0309bbeb --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyWetness.java @@ -0,0 +1,24 @@ +package art.arcane.iris.generation.hydrology.config; + +import art.arcane.iris.pack.schema.annotation.MaxNumber; +import art.arcane.iris.pack.schema.annotation.MinNumber; +import art.arcane.volmlib.util.documentation.Description; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@Description("Bounds on how wet the dimension's wet and dry zones make this area. The zone wetness runs from the climate's dryRainfall in dry zones to 1 in wet zones and is held between min and max here. The bounded wetness scales rainfall and pond density, and a pond or lake whose floor lies here drops ponds.climateDrawdown times one minus it, rounded, below its freeboard.") +@Data +public class IrisHydrologyWetness { + @MinNumber(0) + @MaxNumber(1) + @Description("Lowest wetness this area falls to, even inside a dry zone. 0.7 keeps 70% of the rainfall and pond density in dry zones and lowers ponds and lakes by at most 30% of ponds.climateDrawdown. Left out, it is 0.") + private double min = 0D; + + @MinNumber(0) + @MaxNumber(1) + @Description("Highest wetness this area reaches, even inside a wet zone. 0.35 keeps at most 35% of the rainfall and pond density and lowers ponds and lakes by at least 65% of ponds.climateDrawdown. Must not be below min. Left out, it is 1.") + private double max = 1D; +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisPondNatural.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisPondNatural.java index b71c299c3..74bf584e7 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisPondNatural.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisPondNatural.java @@ -32,6 +32,6 @@ public class IrisPondNatural { @MinNumber(0.5) @MaxNumber(64) - @Description("Smallest hollow depth in blocks that holds a pond.") + @Description("Smallest hollow depth in blocks that holds a pond or a lake.") private double minDepth = 2D; } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisPondShore.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisPondShore.java index 838658388..59b7ba563 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisPondShore.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisPondShore.java @@ -9,12 +9,12 @@ import lombok.experimental.Accessors; @Accessors(chain = true) @NoArgsConstructor -@Description("Shape of pond and lake shores and floors.") +@Description("Shape of pond shores and floors. Lakes take only roundness.") @Data public class IrisPondShore { @MinNumber(0) @MaxNumber(4) - @Description("Strength of the noise that rounds and roughens pond outlines. 0 follows the terrain exactly.") + @Description("Strength of the noise that rounds and roughens pond and lake outlines. 0 follows the terrain exactly.") private double roundness = 0.5D; @MinNumber(0) 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 9c57c6885..d70724880 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 @@ -10,6 +10,7 @@ import art.arcane.iris.generation.hydrology.plan.WindowPlan; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; +import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException; import art.arcane.iris.generation.hydrology.underground.SeaInlet; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.hydrology.water.Pond; @@ -18,14 +19,21 @@ import art.arcane.iris.generation.hydrology.water.PondMask; import art.arcane.iris.generation.hydrology.water.Reach; import art.arcane.iris.generation.hydrology.water.ReachStyle; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; +import java.util.Locale; +import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; import java.util.function.Predicate; final class HydrologyFeatureSearch { @@ -33,12 +41,15 @@ final class HydrologyFeatureSearch { 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); + private static final long POLL_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); + static final String OFF = "hydrology is off"; + private static final String PONDS_OFF = "hydrology.ponds.natural and hydrology.ponds.seeded are disabled"; private final HydrologySettings settings; private final HydrologyPlanCache cache; private final int originX; private final int originZ; - private final HydrologyFeatureQuery query; + private final Set types; private final Predicate eligible; private final int radius; private final long radiusSquared; @@ -51,29 +62,70 @@ final class HydrologyFeatureSearch { this.cache = cache; this.originX = originX; this.originZ = originZ; - this.query = query; + this.types = enabledTypes(settings, query); this.eligible = eligible; this.radius = radius; this.radiusSquared = (long) radius * radius; } - Optional nearest() { + Optional nearest(Duration timeout, BooleanSupplier running) throws HydrologySearchTimeoutException { + Objects.requireNonNull(timeout, "timeout"); + Objects.requireNonNull(running, "running"); int rings = Math.ceilDiv(radius, WindowKey.SIZE) + 1; long windows = (2L * rings + 1L) * (2L * rings + 1L); if (windows > MAX_WINDOWS) { throw new IllegalArgumentException("Hydrology feature search radius " + radius + " covers " + windows + " windows, above " + MAX_WINDOWS); } - if (query.matches(HydrologyFeatureType.LAKE)) { - searchLakes(); + if (types.isEmpty()) { + return Optional.empty(); } - if (!Collections.disjoint(query.types(), WINDOW_TYPES)) { - searchWindows(rings); + Budget budget = new Budget(System.nanoTime() + timeout.toNanos(), timeout, running); + if (types.contains(HydrologyFeatureType.LAKE)) { + searchLakes(budget); + } + if (!Collections.disjoint(types, WINDOW_TYPES)) { + searchWindows(rings, budget); } return Optional.ofNullable(best); } - private void searchLakes() { + static Optional disabledReason(HydrologySettings settings, HydrologyFeatureType type) { + HydrologySettings.Ponds ponds = settings.ponds(); + boolean anyPonds = ponds.natural().enabled() || ponds.seeded().enabled(); + String reason = switch (type) { + case STREAM, RIVER, MAJOR_RIVER -> hasTier(settings, type) ? null : "it has no " + type.key().replace('_', ' ') + " tier"; + case CASCADE, WATERFALL, MOUTH -> null; + case POND -> anyPonds ? null : PONDS_OFF; + case DAM -> !anyPonds ? PONDS_OFF : ponds.dams().enabled() ? null : "hydrology.ponds.dams is disabled"; + case LAKE -> settings.lakes().enabled() ? null : "hydrology.lakes is disabled"; + case SEA_INLET -> settings.underground().seaInlets().enabled() ? null : "hydrology.underground.seaInlets is disabled"; + case CAVE_POOL -> settings.underground().cavePools().enabled() ? null : "hydrology.underground.cavePools is disabled"; + }; + return Optional.ofNullable(reason); + } + + private static Set enabledTypes(HydrologySettings settings, HydrologyFeatureQuery query) { + Set enabled = EnumSet.noneOf(HydrologyFeatureType.class); + for (HydrologyFeatureType type : query.types()) { + if (disabledReason(settings, type).isEmpty()) { + enabled.add(type); + } + } + return enabled; + } + + private static boolean hasTier(HydrologySettings settings, HydrologyFeatureType type) { + List tiers = settings.tiers(); + for (int index = 0; index < tiers.size(); index++) { + if (channelType(tiers.get(index).name(), index, tiers.size()) == type) { + return true; + } + } + return false; + } + + private void searchLakes(Budget budget) throws HydrologySearchTimeoutException { long minX = (long) originX - radius; long minZ = (long) originZ - radius; long maxX = (long) originX + radius; @@ -85,7 +137,7 @@ final class HydrologyFeatureSearch { plans.add(cache.demandRegion(key)); } for (CompletableFuture plan : plans) { - for (Pond lake : cache.awaitPlan(plan).lakes()) { + for (Pond lake : await(plan, budget).lakes()) { if (seen.add(lake.id())) { pond(lake, HydrologyFeatureType.LAKE); } @@ -93,7 +145,7 @@ final class HydrologyFeatureSearch { } } - private void searchWindows(int rings) { + private void searchWindows(int rings, Budget budget) throws HydrologySearchTimeoutException { WindowKey origin = WindowKey.containing(originX, originZ); for (int ring = 0; ring <= rings; ring++) { long bound = Math.max(0L, (long) (ring - 2) * WindowKey.SIZE); @@ -105,11 +157,43 @@ final class HydrologyFeatureSearch { plans.add(cache.demandWindow(key)); } for (CompletableFuture plan : plans) { - window(cache.awaitPlan(plan).plan()); + window(await(plan, budget).plan()); } } } + private T await(CompletableFuture plan, Budget budget) throws HydrologySearchTimeoutException { + CountDownLatch settled = new CountDownLatch(1); + plan.whenComplete((value, failure) -> settled.countDown()); + boolean ready = false; + while (!ready) { + ready = settle(settled, slice(budget)); + } + return cache.awaitPlan(plan); + } + + private long slice(Budget budget) throws HydrologySearchTimeoutException { + if (!budget.running().getAsBoolean()) { + throw new CancellationException("The hydrology feature search was cancelled."); + } + long remaining = budget.deadline() - System.nanoTime(); + if (remaining <= 0L) { + throw new HydrologySearchTimeoutException(budget.timeout(), best); + } + return Math.min(remaining, POLL_NANOS); + } + + private static boolean settle(CountDownLatch settled, long nanos) { + try { + return settled.await(nanos, TimeUnit.NANOSECONDS); + } catch (InterruptedException interruption) { + Thread.currentThread().interrupt(); + CancellationException cancelled = new CancellationException("The hydrology feature search was interrupted."); + cancelled.initCause(interruption); + throw cancelled; + } + } + private static List ring(WindowKey origin, int ring) { if (ring == 0) { return List.of(origin); @@ -135,7 +219,7 @@ final class HydrologyFeatureSearch { pond(pond, type); } } - if (query.matches(HydrologyFeatureType.SEA_INLET)) { + if (types.contains(HydrologyFeatureType.SEA_INLET)) { for (SeaInlet inlet : plan.inlets()) { inlet(inlet); } @@ -151,22 +235,22 @@ final class HydrologyFeatureSearch { private HydrologyFeatureType pondType(Pond pond) { if (pond.kind() == PondKind.LAKE) { - return query.matches(HydrologyFeatureType.LAKE) ? HydrologyFeatureType.LAKE : null; + return types.contains(HydrologyFeatureType.LAKE) ? HydrologyFeatureType.LAKE : null; } - if (pond.damRaise() > 0 && query.matches(HydrologyFeatureType.DAM)) { + if (pond.damRaise() > 0 && types.contains(HydrologyFeatureType.DAM)) { return HydrologyFeatureType.DAM; } - return query.matches(HydrologyFeatureType.POND) ? HydrologyFeatureType.POND : null; + return types.contains(HydrologyFeatureType.POND) ? HydrologyFeatureType.POND : null; } private void reach(Reach reach) { HydrologyFeatureType channel = channelType(settings, reach.tier()); - boolean whole = query.matches(channel); + boolean whole = types.contains(channel); float[] xs = reach.xs(); float[] zs = reach.zs(); for (int index = 0; index < xs.length; index++) { HydrologyFeatureType point = pointType(reach.style()[index]); - HydrologyFeatureType type = point != null && query.matches(point) ? point : whole ? channel : null; + HydrologyFeatureType type = point != null && types.contains(point) ? point : whole ? channel : null; if (type != null) { offer(reach.id(), type, (int) Math.floor(xs[index]), reach.grade()[index], (int) Math.floor(zs[index])); } @@ -197,10 +281,24 @@ final class HydrologyFeatureSearch { if (index < 0) { throw new IllegalStateException("Reach tier '" + tier.name() + "' is not one of the hydrology tiers"); } - if (tier.equals(settings.majorTier())) { - return HydrologyFeatureType.MAJOR_RIVER; + return channelType(tier.name(), index, tiers.size()); + } + + private static HydrologyFeatureType channelType(String name, int index, int count) { + String normalized = name == null ? "" : name.trim().toLowerCase(Locale.ROOT).replace('-', '_').replace(' ', '_'); + return switch (normalized) { + case "stream" -> HydrologyFeatureType.STREAM; + case "river" -> HydrologyFeatureType.RIVER; + case "major", "major_river" -> HydrologyFeatureType.MAJOR_RIVER; + default -> rankType(index, count); + }; + } + + private static HydrologyFeatureType rankType(int index, int count) { + if (index == 0) { + return HydrologyFeatureType.STREAM; } - return index == 0 ? HydrologyFeatureType.STREAM : HydrologyFeatureType.RIVER; + return index == count - 1 ? HydrologyFeatureType.MAJOR_RIVER : HydrologyFeatureType.RIVER; } private static HydrologyFeatureType pointType(ReachStyle style) { @@ -239,4 +337,7 @@ final class HydrologyFeatureSearch { } return x != best.x() ? x < best.x() : z < best.z(); } + + private record Budget(long deadline, Duration timeout, BooleanSupplier running) { + } } 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 54cde2c6e..335ee3b0f 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 @@ -14,6 +14,7 @@ import art.arcane.iris.generation.hydrology.plan.WindowKey; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; +import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException; import art.arcane.iris.generation.hydrology.raster.ChannelFluids; import art.arcane.iris.generation.hydrology.raster.ChunkRasterizer; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; @@ -30,12 +31,14 @@ import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.IrisEngine; import art.arcane.iris.generation.runtime.PreparedHydrologyCacheIdentity; import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.world.IrisWorld; import java.io.File; import java.io.UncheckedIOException; import java.nio.file.Path; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -64,6 +67,7 @@ public final class HydrologyRuntime { public static final int MAX_PREGENERATION_REGIONS = 4096; private static final int MAX_PREVIEW_REQUESTS = 64; private static final int PREFETCH_CAPACITY = 16; + public static final Duration FEATURE_SEARCH_TIMEOUT = Duration.ofSeconds(30L); private static final HydrologyRuntime DISABLED = new HydrologyRuntime(); private final HydrologySettings settings; @@ -150,8 +154,9 @@ public final class HydrologyRuntime { Objects.requireNonNull(complex, "Hydrology needs the engine's terrain complex"); HydrologySettings settings = HydrologySettings.compile(config, engine.getSeedManager().getBodies(), dimension.getFluidHeight(), 0, engine.getHeight()); - boolean caveFluidPolicies = settings.underground().cavePools().enabled() - && requireBiomeFluids(dimension.getReachableBiomes(engine), settings); + requireBiomeFluids(dimension.getReachableBiomes(engine), settings); + boolean caveFluidPolicies = requireCaveFluids(dimension, dimension.getAllRegions(engine), dimension.getReachableCaveBiomes(engine), settings) + && settings.underground().cavePools().enabled(); if (settings.density() == 0D) { return DISABLED; } @@ -168,20 +173,33 @@ public final class HydrologyRuntime { identity -> store(world, dimensionKey, settings, identity), caveFluidPolicies); } - static boolean requireBiomeFluids(Collection biomes, HydrologySettings settings) { - boolean named = false; + private static void requireBiomeFluids(Collection biomes, HydrologySettings settings) { for (IrisBiome biome : biomes) { - IrisHydrologyPolicy policy = biome == null ? null : biome.getHydrologyPolicy(); - String fluid = policy == null ? null : policy.getFluid(); - if (fluid == null) { - continue; - } - settings.requireFillingFluid(fluid, "biome '" + biome.getLoadKey() + "' hydrologyPolicy.fluid"); - named = true; + requireFluid(biome.getHydrologyPolicy(), "biome '" + biome.getLoadKey() + "'", settings); + } + } + + static boolean requireCaveFluids(IrisDimension dimension, Collection regions, Collection caveBiomes, + HydrologySettings settings) { + boolean named = requireFluid(dimension.getHydrologyPolicy(), "dimension '" + dimension.getLoadKey() + "'", settings); + for (IrisRegion region : regions) { + named |= requireFluid(region.getHydrologyPolicy(), "region '" + region.getLoadKey() + "'", settings); + } + for (IrisBiome biome : caveBiomes) { + named |= requireFluid(biome.getHydrologyPolicy(), "biome '" + biome.getLoadKey() + "'", settings); } return named; } + private static boolean requireFluid(IrisHydrologyPolicy policy, String owner, HydrologySettings settings) { + String fluid = policy == null ? null : policy.getFluid(); + if (fluid == null) { + return false; + } + settings.requireFillingFluid(fluid, owner + " hydrologyPolicy.fluid"); + return true; + } + public boolean caveFluidPolicies() { return caveFluidPolicies; } @@ -388,14 +406,12 @@ public final class HydrologyRuntime { } } - public Optional nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius) { - return nearestFeature(blockX, blockZ, query, radius, feature -> true); - } - public Optional nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius, - Predicate eligible) { + Predicate eligible, BooleanSupplier running) + throws HydrologySearchTimeoutException { Objects.requireNonNull(query, "query"); Objects.requireNonNull(eligible, "eligible"); + Objects.requireNonNull(running, "running"); if (radius < 0) { throw new IllegalArgumentException("Hydrology feature search radius must not be negative, got " + radius); } @@ -406,7 +422,15 @@ public final class HydrologyRuntime { throw new IllegalStateException("Hydrology feature search was requested on the main thread."); } requireOpen(); - return new HydrologyFeatureSearch(settings, cache, blockX, blockZ, query, eligible, radius).nearest(); + return new HydrologyFeatureSearch(settings, cache, blockX, blockZ, query, eligible, radius).nearest(FEATURE_SEARCH_TIMEOUT, running); + } + + public Optional unavailable(HydrologyFeatureType type) { + Objects.requireNonNull(type, "type"); + if (settings == null) { + return Optional.of(HydrologyFeatureSearch.OFF); + } + return HydrologyFeatureSearch.disabledReason(settings, type); } public HydrologyFeatureType channelType(HydrologyTier tier) { diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSource.java b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSource.java index 7440e9ba8..a32aaa9af 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSource.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSource.java @@ -4,6 +4,7 @@ import art.arcane.iris.generation.bake.ChunkBakeCache; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPermission; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness; import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer; import art.arcane.iris.generation.hydrology.grid.HydrologyTerrainSource; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; @@ -38,7 +39,6 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource, private final ExecutorService pool; private final int parallelism; private final ProceduralStream regions; - private final ProceduralStream biomes; private final ProceduralStream continents; private final BiomeBuffetLayout buffet; private final IrisBiome focus; @@ -55,7 +55,6 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource, this.pool = pool; this.parallelism = Math.max(1, parallelism); this.regions = Objects.requireNonNull(complex.getRegionStream(), "region stream"); - this.biomes = Objects.requireNonNull(complex.getBaseBiomeStream(), "base biome stream"); this.continents = Objects.requireNonNull(complex.getBridgeStream(), "continent stream"); this.buffet = complex.getBiomeBuffet(); this.focus = complex.getFocusBiome(); @@ -88,7 +87,7 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource, public String channelFluid(int x, int z) { ChunkBakeCache.enterSparse(); try { - return policy(biomes.get(x, z), regions.get(x, z)).fluid(); + return policy(complex.baseBiomeLineage(x, z), regions.get(x, z)).fluid(); } finally { ChunkBakeCache.exitSparse(); } @@ -164,20 +163,19 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource, if (!Double.isFinite(height)) { throw new IllegalStateException("Hydrology " + (baseOnly ? "base" : "natural") + " height at " + x + "," + z + " is " + height); } - Policy policy = policy(biomes.get(x, z), regions.get(x, z)); + Policy policy = policy(complex.baseBiomeLineage(x, z), regions.get(x, z)); out.height()[index] = (float) height; out.ocean()[index] = StrictMath.round(height) < settings.seaLevel() && oceanIntent(x, z); - float wet = policy.climateZones() ? wetness(x, z) : 1f; + boolean zoned = wetness != null && policy.climateZones(); + float wet = zoned ? (float) Math.clamp(climate.wetness(wetness.noise(x, z)), policy.minWetness(), policy.maxWetness()) : 1f; out.rainfall()[index] = policy.rainfall() * wet; out.pondDensity()[index] = policy.pondDensity() * wet; + out.wetness()[index] = wet; + out.climateZoned()[index] = zoned; out.permission()[index] = policy.permission(); out.fluidProfile()[index] = policy.fluid(); } - private float wetness(int x, int z) { - return wetness == null ? 1f : (float) climate.wetness(wetness.noise(x, z)); - } - private boolean oceanIntent(int x, int z) { BiomeBuffetLayout.Cell cell = buffet == null ? null : buffet.terrain(x, z); IrisBiome focused = cell == null ? focus : cell.biome(); @@ -185,13 +183,13 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource, return type == InferredType.SEA; } - private Policy policy(IrisBiome biome, IrisRegion region) { - PolicyKey key = new PolicyKey(biome, region); + private Policy policy(List biomes, IrisRegion region) { + PolicyKey key = new PolicyKey(biomes, region); Policy known = policies.get(key); if (known != null) { return known; } - Policy resolved = resolve(biome, region); + Policy resolved = resolve(biomes, region); if (policies.size() >= POLICY_CAPACITY) { policies.clear(); } @@ -199,23 +197,28 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource, return raced == null ? resolved : raced; } - private Policy resolve(IrisBiome biome, IrisRegion region) { - double rainfall = inherited(biome, region, IrisHydrologyPolicy::getRainfall, 1D); - double pondDensity = inherited(biome, region, IrisHydrologyPolicy::getPondDensity, 1D); - IrisHydrologyPermission streams = inherited(biome, region, IrisHydrologyPolicy::getStreams, IrisHydrologyPermission.ALLOW); - IrisHydrologyPermission ponds = inherited(biome, region, IrisHydrologyPolicy::getPonds, IrisHydrologyPermission.ALLOW); - String fluid = inherited(biome, region, IrisHydrologyPolicy::getFluid, null); - boolean climateZones = inherited(biome, region, IrisHydrologyPolicy::getClimateZones, Boolean.TRUE); - requireMultiplier("rainfall", rainfall, biome, region); - requireMultiplier("pondDensity", pondDensity, biome, region); + private Policy resolve(List biomes, IrisRegion region) { + double rainfall = inherited(biomes, region, IrisHydrologyPolicy::getRainfall, 1D); + double pondDensity = inherited(biomes, region, IrisHydrologyPolicy::getPondDensity, 1D); + IrisHydrologyPermission streams = inherited(biomes, region, IrisHydrologyPolicy::getStreams, IrisHydrologyPermission.ALLOW); + IrisHydrologyPermission ponds = inherited(biomes, region, IrisHydrologyPolicy::getPonds, IrisHydrologyPermission.ALLOW); + String fluid = inherited(biomes, region, IrisHydrologyPolicy::getFluid, null); + boolean climateZones = inherited(biomes, region, IrisHydrologyPolicy::getClimateZones, Boolean.TRUE); + IrisHydrologyWetness wetness = inherited(biomes, region, IrisHydrologyPolicy::getWetness, null); + requireMultiplier("rainfall", rainfall, biomes, region); + requireMultiplier("pondDensity", pondDensity, biomes, region); if (fluid != null) { - settings.requireFillingFluid(fluid, "the hydrology policy for " + where(biome, region)); + settings.requireFillingFluid(fluid, "the hydrology policy for " + where(biomes, region)); } - return new Policy((float) rainfall, (float) pondDensity, permission(streams, ponds), fluid, climateZones); + double minWetness = wetness == null ? 0D : wetness.getMin(); + double maxWetness = wetness == null ? 1D : wetness.getMax(); + requireWetness(minWetness, maxWetness, biomes, region); + return new Policy((float) rainfall, (float) pondDensity, permission(streams, ponds), fluid, climateZones, (float) minWetness, + (float) maxWetness); } - private T inherited(IrisBiome biome, IrisRegion region, Function field, T fallback) { - T value = IrisHydrologyPolicy.inherited(biome, region, dimension, field); + private T inherited(List biomes, IrisRegion region, Function field, T fallback) { + T value = IrisHydrologyPolicy.inherited(biomes, region, dimension, field); return value == null ? fallback : value; } @@ -225,29 +228,41 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource, return (byte) bits; } - private static void requireMultiplier(String field, double value, IrisBiome biome, IrisRegion region) { - if (!Double.isFinite(value) || value < 0D) { - throw new IllegalArgumentException("Hydrology policy " + field + " for " + where(biome, region) + " must be a finite value of 0 or more, got " - + value); + private static void requireMultiplier(String field, double value, List biomes, IrisRegion region) { + if (!IrisHydrologyPolicy.validMultiplier(value)) { + throw new IllegalArgumentException("Hydrology policy " + field + " for " + where(biomes, region) + " must be a finite value from 0 to " + + (int) IrisHydrologyPolicy.MAX_MULTIPLIER + ", got " + value); } } - private static String where(IrisBiome biome, IrisRegion region) { - return "biome " + (biome == null ? "none" : biome.getLoadKey()) + " in region " + (region == null ? "none" : region.getLoadKey()); + private static void requireWetness(double min, double max, List biomes, IrisRegion region) { + if (!(min >= 0D && min <= max && max <= 1D)) { + throw new IllegalArgumentException("Hydrology policy wetness for " + where(biomes, region) + " must have 0 <= min <= max <= 1, got min " + + min + " and max " + max); + } } - private record Policy(float rainfall, float pondDensity, byte permission, String fluid, boolean climateZones) { + private static String where(List biomes, IrisRegion region) { + StringBuilder where = new StringBuilder("biome ").append(biomes.isEmpty() ? "none" : biomes.getFirst().getLoadKey()); + for (int index = 1; index < biomes.size(); index++) { + where.append(" inside ").append(biomes.get(index).getLoadKey()); + } + return where.append(" in region ").append(region == null ? "none" : region.getLoadKey()).toString(); } - private record PolicyKey(IrisBiome biome, IrisRegion region) { + private record Policy(float rainfall, float pondDensity, byte permission, String fluid, boolean climateZones, float minWetness, + float maxWetness) { + } + + private record PolicyKey(List biomes, IrisRegion region) { @Override public boolean equals(Object other) { - return other instanceof PolicyKey key && key.biome == biome && key.region == region; + return other instanceof PolicyKey key && key.biomes == biomes && key.region == region; } @Override public int hashCode() { - return 31 * System.identityHashCode(biome) + System.identityHashCode(region); + return 31 * System.identityHashCode(biomes) + System.identityHashCode(region); } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/grid/HeightLattice.java b/core/src/main/java/art/arcane/iris/generation/hydrology/grid/HeightLattice.java index 68cf87401..c6bf8b808 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/grid/HeightLattice.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/grid/HeightLattice.java @@ -184,6 +184,8 @@ public final class HeightLattice { out.ocean()[index] = samples.ocean()[sample]; out.rainfall()[index] = samples.rainfall()[sample]; out.pondDensity()[index] = samples.pondDensity()[sample]; + out.wetness()[index] = samples.wetness()[sample]; + out.climateZoned()[index] = samples.climateZoned()[sample]; out.permission()[index] = samples.permission()[sample]; out.fluidProfile()[index] = samples.fluidProfile()[sample]; } @@ -345,6 +347,8 @@ public final class HeightLattice { private final boolean[] ocean; private final float[] rainfall; private final float[] pondDensity; + private final float[] wetness; + private final boolean[] climateZoned; private final byte[] permission; private final String[] fluidProfile; private final AtomicReferenceArray> marks; @@ -356,6 +360,8 @@ public final class HeightLattice { this.ocean = new boolean[cells]; this.rainfall = new float[cells]; this.pondDensity = new float[cells]; + this.wetness = new float[cells]; + this.climateZoned = new boolean[cells]; this.permission = new byte[cells]; this.fluidProfile = new String[cells]; this.marks = new AtomicReferenceArray<>(cells); @@ -366,6 +372,8 @@ public final class HeightLattice { ocean[local] = samples.ocean()[sample]; rainfall[local] = samples.rainfall()[sample]; pondDensity[local] = samples.pondDensity()[sample]; + wetness[local] = samples.wetness()[sample]; + climateZoned[local] = samples.climateZoned()[sample]; permission[local] = samples.permission()[sample]; fluidProfile[local] = samples.fluidProfile()[sample]; } @@ -375,6 +383,8 @@ public final class HeightLattice { out.ocean()[index] = ocean[local]; out.rainfall()[index] = rainfall[local]; out.pondDensity()[index] = pondDensity[local]; + out.wetness()[index] = wetness[local]; + out.climateZoned()[index] = climateZoned[local]; out.permission()[index] = permission[local]; out.fluidProfile()[index] = fluidProfile[local]; } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/grid/HydrologySampleBuffer.java b/core/src/main/java/art/arcane/iris/generation/hydrology/grid/HydrologySampleBuffer.java index dbec39c0d..9fa6d9366 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/grid/HydrologySampleBuffer.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/grid/HydrologySampleBuffer.java @@ -8,6 +8,8 @@ public final class HydrologySampleBuffer { private final boolean[] ocean; private final float[] rainfall; private final float[] pondDensity; + private final float[] wetness; + private final boolean[] climateZoned; private final byte[] permission; private final String[] fluidProfile; @@ -19,6 +21,8 @@ public final class HydrologySampleBuffer { this.ocean = new boolean[capacity]; this.rainfall = new float[capacity]; this.pondDensity = new float[capacity]; + this.wetness = new float[capacity]; + this.climateZoned = new boolean[capacity]; this.permission = new byte[capacity]; this.fluidProfile = new String[capacity]; } @@ -39,6 +43,14 @@ public final class HydrologySampleBuffer { return pondDensity; } + public float[] wetness() { + return wetness; + } + + public boolean[] climateZoned() { + return climateZoned; + } + public byte[] permission() { return permission; } 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 e0fadb691..93941d422 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 @@ -28,8 +28,6 @@ public final class HydrologyPlanCodec { private static final int POND_BYTES = 2 * Long.BYTES + 1 + 15 * Integer.BYTES; private static final int STATION_BYTES = 5 * Integer.BYTES; private static final int INLET_BYTES = Long.BYTES + 5 * Integer.BYTES + 2 * STATION_BYTES; - private static final ReachStyle[] STYLES = ReachStyle.values(); - private static final PondKind[] KINDS = PondKind.values(); private HydrologyPlanCodec() { } @@ -102,13 +100,13 @@ public final class HydrologyPlanCodec { writeFloats(out, reach.halfWidth()); writeFloats(out, reach.depth()); for (ReachStyle style : reach.style()) { - out.writeByte(style.ordinal()); + out.writeByte(style.code()); } } private static void writePond(DataOutputStream out, Pond pond) throws IOException { out.writeLong(pond.id()); - out.writeByte(pond.kind().ordinal()); + out.writeByte(pond.kind().code()); out.writeInt(pond.level()); out.writeInt(pond.floor()); out.writeInt(pond.spillX()); @@ -190,7 +188,7 @@ public final class HydrologyPlanCodec { return Optional.empty(); } return Optional.of(new Body(x, z, reaches, ponds, inlets)); - } catch (BufferUnderflowException | IllegalArgumentException malformed) { + } catch (BufferUnderflowException | IllegalArgumentException | IllegalStateException malformed) { return Optional.empty(); } } @@ -211,14 +209,14 @@ public final class HydrologyPlanCodec { float[] depth = readFloats(in, points); ReachStyle[] style = new ReachStyle[points]; for (int point = 0; point < points; point++) { - style[point] = STYLES[index(in.get(), STYLES.length)]; + style[point] = ReachStyle.fromCode(Byte.toUnsignedInt(in.get())); } return new Reach(id, tier, downstreamId, xs, zs, grade, halfWidth, depth, style, catchment); } private static Pond readPond(ByteBuffer in) { long id = in.getLong(); - PondKind kind = KINDS[index(in.get(), KINDS.length)]; + PondKind kind = PondKind.fromCode(Byte.toUnsignedInt(in.get())); int level = in.getInt(); int floor = in.getInt(); int spillX = in.getInt(); 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 92583cceb..9e327d711 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 @@ -21,8 +21,10 @@ import art.arcane.iris.generation.hydrology.config.IrisPondNatural; import art.arcane.iris.generation.hydrology.config.IrisPondSeeded; import art.arcane.iris.generation.hydrology.config.IrisPondShore; import art.arcane.iris.generation.hydrology.config.IrisSeaInlets; +import art.arcane.iris.generation.hydrology.underground.SeaInletPlanner; import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer; import art.arcane.iris.generation.hydrology.water.HydrologyTier; +import art.arcane.iris.generation.hydrology.water.LakeCandidate; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.terrain.IrisMaterialPalette; import com.google.gson.Gson; @@ -57,6 +59,12 @@ public final class HydrologySettings { private static final int INLET_LAST_STEP = (int) Math.ceil(WindowPlanner.CELL * Math.sqrt(2D)); private static final int INLET_SHELL = SeaInletRasterizer.SHELL; public static final int MAX_CAVE_POOL_RADIUS = 15; + private static final int CAVE_POOL_SPAN = 2 * MAX_CAVE_POOL_RADIUS + 1; + private static final int MAX_CAVE_POOL_AREA = CAVE_POOL_SPAN * CAVE_POOL_SPAN; + private static final int MAX_LAKE_AREA = LakeCandidate.MAX_EXTENT * LakeCandidate.MAX_EXTENT; + private static final int MAX_PREFETCH_RINGS = 4; + private static final int MAX_SEEDED_DENSITY = 64; + private static final int MIN_WATERFALL_DROP = 2; private final long seed; private final int seaLevel; @@ -98,6 +106,7 @@ public final class HydrologySettings { this.seams = seams(config.getFluids()); this.prefetchRings = config.getPrefetchRings(); this.persist = config.isPersist(); + requireBounds(config); requireFluidReferences(); this.fingerprint = computeFingerprint(); } @@ -362,6 +371,12 @@ public final class HydrologySettings { + inlets.length().max() + " + " + INLET_LAST_STEP + " for the last step + the wider of halfWidth max and chamberRadius max" + " + " + (1 + INLET_SHELL) + " for the seal); an inlet must stay within " + WindowKey.SIZE + " blocks"); } + long lookups = SeaInletPlanner.lookupReach(inlets.length().max(), inlets.chamberRadius().max()); + if (lookups > WindowKey.SIZE) { + throw new IllegalArgumentException("Hydrology underground.seaInlets planning looks " + lookups + + " blocks from the coast (length max " + inlets.length().max() + ", chamberRadius max " + inlets.chamberRadius().max() + + "); it must stay within " + WindowKey.SIZE + " blocks"); + } return inlets; } @@ -544,6 +559,77 @@ public final class HydrologySettings { } } + private void requireBounds(IrisHydrology config) { + requireWithin(prefetchRings, 0, MAX_PREFETCH_RINGS, "prefetchRings"); + requirePositive(drainage.fillEpsilon(), "drainage.fillEpsilon"); + for (int index = 0; index < config.getTiers().size(); index++) { + requireTierBounds(config.getTiers().get(index), "tiers[" + index + "]"); + } + double seeded = config.getPonds().getSeeded().getDensity(); + if (!(seeded >= 0D && seeded <= MAX_SEEDED_DENSITY)) { + throw new IllegalArgumentException("Hydrology ponds.seeded.density must stay within 0.." + MAX_SEEDED_DENSITY + ", got " + seeded); + } + requireShoreDepth(ponds.materials(), "ponds.materials"); + requireAtLeast(deformation.maxFill(), 0, "deformation.maxFill"); + if (lakes.maxArea() > MAX_LAKE_AREA) { + throw new IllegalArgumentException("Hydrology lakes.maxArea must not go above " + MAX_LAKE_AREA + " (" + LakeCandidate.MAX_EXTENT + + " by " + LakeCandidate.MAX_EXTENT + " blocks, the widest a lake can span), got " + lakes.maxArea()); + } + requireAtLeast(underground.seaInlets().spacing(), 1, "underground.seaInlets.spacing"); + requireCavePoolBounds(underground.cavePools()); + } + + private static void requireTierBounds(IrisHydrologyTier config, String field) { + requireNonNegative(config.getWidthFactor(), field + ".widthFactor"); + requireNonNegative(config.getDepthRatio(), field + ".depthRatio"); + requireAtLeast(config.getWaterfallMinimumDrop(), MIN_WATERFALL_DROP, field + ".waterfallMinimumDrop"); + requireShoreDepth(config.getMaterials(), field + ".materials"); + } + + private static void requireShoreDepth(IrisHydrologyMaterials materials, String field) { + if (materials != null) { + requireAtLeast(materials.getShoreDepth(), 1, field + ".shoreDepth"); + } + } + + private static void requireCavePoolBounds(CavePools pools) { + if (!pools.enabled()) { + return; + } + if (pools.freeboard().max() >= pools.maxDepth()) { + throw new IllegalArgumentException("Hydrology underground.cavePools.freeboard max " + pools.freeboard().max() + + " must stay below maxDepth " + pools.maxDepth()); + } + if (pools.maxArea() > MAX_CAVE_POOL_AREA) { + throw new IllegalArgumentException("Hydrology underground.cavePools.maxArea must not go above " + MAX_CAVE_POOL_AREA + " (" + + CAVE_POOL_SPAN + " by " + CAVE_POOL_SPAN + " blocks, the widest a pool can spread), got " + pools.maxArea()); + } + } + + private static void requireWithin(int value, int min, int max, String field) { + if (value < min || value > max) { + throw new IllegalArgumentException("Hydrology " + field + " must stay within " + min + ".." + max + ", got " + value); + } + } + + private static void requireAtLeast(int value, int min, String field) { + if (value < min) { + throw new IllegalArgumentException("Hydrology " + field + " must be at least " + min + ", got " + value); + } + } + + private static void requireNonNegative(double value, String field) { + if (!(Double.isFinite(value) && value >= 0D)) { + throw new IllegalArgumentException("Hydrology " + field + " must be a finite value of at least 0, got " + value); + } + } + + private static void requirePositive(float value, String field) { + if (!(Float.isFinite(value) && value > 0f)) { + throw new IllegalArgumentException("Hydrology " + field + " must be a finite value above 0, got " + value); + } + } + private void requireFluidReferences() { for (Map.Entry seam : seams.entrySet()) { requireFluid(seam.getValue(), "the seam of fluid '" + seam.getKey() + "'"); @@ -574,8 +660,7 @@ public final class HydrologySettings { } private long computeFingerprint() { - Fingerprint hash = new Fingerprint().add(seed).add(seaLevel).add(minY).add(maxY).add(enabled) - .add(density).add(prefetchRings).add(persist); + Fingerprint hash = new Fingerprint().add(seed).add(seaLevel).add(minY).add(maxY).add(enabled).add(density); addClimate(hash); addDrainage(hash); addTiers(hash); 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 b1330f231..2f5a979aa 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 @@ -130,7 +130,7 @@ public final class WindowPlanner { } List reaches = network.reaches(); List windowPonds = windowPonds(network.ponds()); - List planned = inlets.plan(raw, samples, drainage.receivers(), drainage.accumulation(), network, settings.seed()); + List planned = inlets.plan(key, raw, samples, drainage.receivers(), drainage.accumulation(), network, settings.seed()); WindowPlan owned = new WindowPlan(key, ownedReaches(key, reaches), ownedPonds(key, windowPonds), ownedInlets(key, planned)); 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 c370aed75..5b8344721 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 @@ -1,23 +1,41 @@ package art.arcane.iris.generation.hydrology.query; +import art.arcane.iris.generation.hydrology.PersistedCodes; + import java.util.ArrayList; import java.util.List; import java.util.Locale; public enum HydrologyFeatureType { - STREAM, - RIVER, - MAJOR_RIVER, - CASCADE, - WATERFALL, - MOUTH, - POND, - LAKE, - DAM, - SEA_INLET, - CAVE_POOL; + STREAM(0), + RIVER(1), + MAJOR_RIVER(2), + CASCADE(3), + WATERFALL(4), + MOUTH(5), + POND(6), + LAKE(7), + DAM(8), + SEA_INLET(9), + CAVE_POOL(10); private static final List KEYS = keyList(); + private static final PersistedCodes CODES = + PersistedCodes.of(HydrologyFeatureType.class, HydrologyFeatureType::code); + + private final int code; + + HydrologyFeatureType(int code) { + this.code = code; + } + + public int code() { + return code; + } + + public static HydrologyFeatureType fromCode(int code) { + return CODES.decode(code); + } public String key() { return name().toLowerCase(Locale.ROOT); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/query/HydrologySearchTimeoutException.java b/core/src/main/java/art/arcane/iris/generation/hydrology/query/HydrologySearchTimeoutException.java new file mode 100644 index 000000000..1c1c341e6 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/query/HydrologySearchTimeoutException.java @@ -0,0 +1,18 @@ +package art.arcane.iris.generation.hydrology.query; + +import java.time.Duration; +import java.util.Optional; +import java.util.concurrent.TimeoutException; + +public final class HydrologySearchTimeoutException extends TimeoutException { + private final HydrologyFeatureRef nearestSoFar; + + public HydrologySearchTimeoutException(Duration timeout, HydrologyFeatureRef nearestSoFar) { + super("The hydrology feature search ran past its " + timeout.toMillis() + " ms limit."); + this.nearestSoFar = nearestSoFar; + } + + public Optional nearestSoFar() { + return Optional.ofNullable(nearestSoFar); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/CavePoolFiller.java b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/CavePoolFiller.java index fb303b98c..833cc9238 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/CavePoolFiller.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/CavePoolFiller.java @@ -21,7 +21,6 @@ public final class CavePoolFiller { private static final long SALT_FLOOR = 0x4341564652L << 20; private static final long SALT_FREEBOARD = 0x43415646524244L; private static final long SALT_DENSITY = 0x43415644454e53L; - private static final HydrologyCaveCell GUARD = HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD); private static final CaveVoxel[] VOXELS = CaveVoxel.values(); private static final int[] DX = {1, -1, 0, 0, 0, 0}; private static final int[] DY = {0, 0, 0, 0, 1, -1}; @@ -143,7 +142,8 @@ public final class CavePoolFiller { } private static void write(int chunkX, int chunkZ, Pool pool, MantleWriter writer) { - HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, pool.fluid(), ""); + HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, pool.fluid()); + HydrologyCaveCell wall = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, pool.fluid()); for (int offsetX = -1; offsetX <= 1; offsetX++) { for (int offsetZ = -1; offsetZ <= 1; offsetZ++) { int targetX = chunkX + offsetX; @@ -151,7 +151,7 @@ public final class CavePoolFiller { if (pool.touches(targetX, targetZ)) { writer.withChunkFence(targetX, targetZ, () -> { writeCells(targetX, targetZ, pool.cells(), wet, writer); - writeCells(targetX, targetZ, pool.walls(), GUARD, writer); + writeCells(targetX, targetZ, pool.walls(), wall, writer); }); } } @@ -166,12 +166,18 @@ public final class CavePoolFiller { continue; } int y = unpackY(cell); - if (writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class) == null) { + HydrologyCaveCell existing = writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class); + if (existing == null || replacesSharedWall(existing, value)) { writer.setData(x, y, z, value); } } } + private static boolean replacesSharedWall(HydrologyCaveCell existing, HydrologyCaveCell value) { + return existing.action() == HydrologyCaveAction.SEAL_GUARD && value.action() == HydrologyCaveAction.SEAL_GUARD + && value.fluidProfileKey().compareTo(existing.fluidProfileKey()) < 0; + } + private String fluid(CarvedTerrain carved, int x, int y, int z) { String policy = carved.caveFluid(x, y, z); return policy != null ? policy : pools.fluid(); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlanner.java b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlanner.java index be18dcdbe..719e5aeff 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlanner.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlanner.java @@ -5,6 +5,7 @@ import art.arcane.iris.generation.hydrology.grid.DemGrid; 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; @@ -20,6 +21,7 @@ import java.util.TreeMap; public final class SeaInletPlanner { private static final int ROOF_MARGIN = 2; private static final int OPEN_LAND_STATIONS = 2; + private static final int STEP_LOOKUP_CELLS = 2; private static final float NOISE_STEP = 32f; private static final int CONTAINMENT = 2; private static final float WET_SLACK = CONTAINMENT + 1 + 6f; @@ -41,8 +43,15 @@ public final class SeaInletPlanner { this.settings = Objects.requireNonNull(settings, "settings"); } - public List plan(DemGrid raw, HydrologySampleBuffer samples, int[] receivers, float[] accumulation, ShapedNetwork network, - long seed) { + public static long lookupReach(int lengthMax, int chamberRadiusMax) { + int cell = WindowPlanner.CELL; + long farthestStation = cell * (long) Math.floor((lengthMax + cell * Math.sqrt(2D) - cell) / cell); + return farthestStation + (long) cell * Math.max(STEP_LOOKUP_CELLS, chamberRing(chamberRadiusMax, cell)); + } + + public List plan(WindowKey window, DemGrid raw, HydrologySampleBuffer samples, int[] receivers, float[] accumulation, + ShapedNetwork network, long seed) { + Objects.requireNonNull(window, "window"); HydrologySettings.SeaInlets config = settings.underground().seaInlets(); if (!config.enabled() || settings.density() == 0f) { return List.of(); @@ -53,31 +62,36 @@ public final class SeaInletPlanner { + " receivers=" + receivers.length + " accumulation=" + accumulation.length); } Terrain terrain = new Terrain(raw, samples, receivers, accumulation, cover(raw, samples.height(), network), seed); - List inlets = new ArrayList<>(); + List traced = new ArrayList<>(); for (Map.Entry> site : sites(terrain, config).entrySet()) { SeaInlet inlet = site(terrain, config, site.getKey(), site.getValue()); - if (inlet != null) { - inlets.add(inlet); + if (inlet == null) { + continue; } + if (terrain.clipped && window.equals(owner(inlet))) { + throw new IllegalStateException("Sea inlet " + inlet.id() + " of window " + window + + " reaches the edge of the window's planning span"); + } + traced.add(new Traced(inlet, !terrain.clipped)); } - inlets.sort(Comparator.comparingLong(SeaInlet::id).thenComparingDouble(inlet -> inlet.xs()[0]) - .thenComparingDouble(inlet -> inlet.zs()[0])); - return separated(inlets); + traced.sort(Comparator.comparingLong((Traced entry) -> entry.inlet().id()).thenComparingDouble(entry -> entry.inlet().xs()[0]) + .thenComparingDouble(entry -> entry.inlet().zs()[0])); + return separated(traced); } - private static List separated(List inlets) { - List footprints = new ArrayList<>(inlets.size()); - for (SeaInlet inlet : inlets) { - footprints.add(SeaInletFootprint.of(inlet)); + private static List separated(List traced) { + List footprints = new ArrayList<>(traced.size()); + for (Traced entry : traced) { + footprints.add(SeaInletFootprint.of(entry.inlet())); } - List kept = new ArrayList<>(inlets.size()); - for (int index = 0; index < inlets.size(); index++) { + List kept = new ArrayList<>(traced.size()); + for (int index = 0; index < traced.size(); index++) { boolean yields = false; for (int earlier = 0; earlier < index && !yields; earlier++) { yields = footprints.get(earlier).conflicts(footprints.get(index)); } - if (!yields) { - kept.add(inlets.get(index)); + if (!yields && traced.get(index).whole()) { + kept.add(traced.get(index).inlet()); } } return List.copyOf(kept); @@ -110,6 +124,7 @@ public final class SeaInletPlanner { double targetZ = (siteZ + CellHash.unit(CellHash.mix(terrain.seed, SALT_SITE_Z, siteX, siteZ))) * config.spacing(); DemGrid grid = terrain.grid; WindowKey owner = WindowKey.containing((int) Math.floor(targetX), (int) Math.floor(targetZ)); + terrain.clipped = siteTouchesBorder(terrain, config, siteX, siteZ, owner); List ordered = new ArrayList<>(candidates.size()); for (int candidate : candidates) { if (owner.equals(WindowKey.containing(grid.blockX(candidate), grid.blockZ(candidate)))) { @@ -180,7 +195,7 @@ public final class SeaInletPlanner { int radius = 0; int preferred = Math.round(lerp(config.chamberRadius().min(), config.chamberRadius().max(), unit(terrain, SALT_RADIUS, end))); for (int candidate : new int[]{preferred, config.chamberRadius().min()}) { - float capacity = capacity(terrain, config, end, (candidate + grid.cell() - 1) / grid.cell() + 1); + float capacity = capacity(terrain, config, end, chamberRing(candidate, grid.cell())); if (capacity - water >= config.headroom().min()) { radius = candidate; chamberCapacity = capacity; @@ -251,12 +266,14 @@ public final class SeaInletPlanner { int i = cell % grid.width(); int j = cell / grid.width(); float lowest = Float.POSITIVE_INFINITY; + boolean outside = false; for (int dj = -ring; dj <= ring; dj++) { for (int di = -ring; di <= ring; di++) { int ni = i + di; int nj = j + dj; if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth()) { - return Float.NEGATIVE_INFINITY; + outside = true; + continue; } int neighbour = grid.index(ni, nj); if (terrain.ocean(neighbour)) { @@ -265,6 +282,10 @@ public final class SeaInletPlanner { lowest = Math.min(lowest, terrain.cover[neighbour]); } } + if (outside) { + terrain.clipped = true; + return Float.NEGATIVE_INFINITY; + } return lowest - config.roofClearance() - ROOF_MARGIN; } @@ -272,16 +293,20 @@ public final class SeaInletPlanner { DemGrid grid = terrain.grid; int i = cell % grid.width(); int j = cell / grid.width(); + boolean outside = false; for (int dj = -1; dj <= 1; dj++) { for (int di = -1; di <= 1; di++) { int ni = i + di; int nj = j + dj; - if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth() || terrain.wet(grid.index(ni, nj))) { + if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth()) { + outside = true; + } else if (terrain.wet(grid.index(ni, nj))) { return false; } } } - return true; + terrain.clipped |= outside; + return !outside; } private static int mouth(Terrain terrain, int land) { @@ -310,14 +335,8 @@ public final class SeaInletPlanner { int best = -1; for (int dj = -1; dj <= 1; dj++) { for (int di = -1; di <= 1; di++) { - int ni = i + di; - int nj = j + dj; - if ((di == 0 && dj == 0) || ni <= 0 || nj <= 0 || ni >= grid.width() - 1 || nj >= grid.depth() - 1) { - continue; - } - int neighbour = grid.index(ni, nj); - if (terrain.receivers[neighbour] != cell || terrain.ocean(neighbour) || path.contains(neighbour) - || distanceSquared(grid, neighbour, grid.blockX(mouth), grid.blockZ(mouth)) <= away) { + int neighbour = onward(terrain, mouth, i + di, j + dj, away, path); + if (neighbour < 0 || terrain.receivers[neighbour] != cell) { continue; } if (best < 0 || terrain.accumulation[neighbour] > terrain.accumulation[best] @@ -339,16 +358,11 @@ public final class SeaInletPlanner { double bestAway = 0D; for (int dj = -1; dj <= 1; dj++) { for (int di = -1; di <= 1; di++) { - int ni = i + di; - int nj = j + dj; - if ((di == 0 && dj == 0) || ni <= 0 || nj <= 0 || ni >= grid.width() - 1 || nj >= grid.depth() - 1) { + int neighbour = onward(terrain, mouth, i + di, j + dj, away, path); + if (neighbour < 0) { continue; } - int neighbour = grid.index(ni, nj); double distance = distanceSquared(grid, neighbour, grid.blockX(mouth), grid.blockZ(mouth)); - if (terrain.ocean(neighbour) || path.contains(neighbour) || distance <= away) { - continue; - } boolean covers = canCover(terrain, config, neighbour); if (best < 0 || covers && !bestCovers || covers == bestCovers && (distance > bestAway || distance == bestAway && terrain.cover[neighbour] > terrain.cover[best])) { @@ -426,6 +440,67 @@ public final class SeaInletPlanner { } } + private static int onward(Terrain terrain, int mouth, int ni, int nj, double away, List path) { + DemGrid grid = terrain.grid; + if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth()) { + terrain.clipped = true; + return -1; + } + int neighbour = grid.index(ni, nj); + if (terrain.ocean(neighbour) || path.contains(neighbour) + || distanceSquared(grid, neighbour, grid.blockX(mouth), grid.blockZ(mouth)) <= away) { + return -1; + } + if (ni == 0 || nj == 0 || ni == grid.width() - 1 || nj == grid.depth() - 1) { + terrain.clipped = true; + return -1; + } + return neighbour; + } + + private boolean siteTouchesBorder(Terrain terrain, HydrologySettings.SeaInlets config, int siteX, int siteZ, WindowKey owner) { + DemGrid grid = terrain.grid; + CellRange columns = siteCells(siteX, config.spacing(), owner.wx(), grid.originX(), grid.cell()); + CellRange rows = siteCells(siteZ, config.spacing(), owner.wz(), grid.originZ(), grid.cell()); + int lastColumn = grid.width() - 1; + int lastRow = grid.depth() - 1; + if (columns.first() < 0L || rows.first() < 0L || columns.last() > lastColumn || rows.last() > lastRow) { + return true; + } + float cliff = settings.seaLevel() + config.minimumCliffHeight(); + for (int i = (int) columns.first(); i <= columns.last(); i++) { + if (rows.first() == 0L && cliffLand(terrain, i, 0, cliff) || rows.last() == lastRow && cliffLand(terrain, i, lastRow, cliff)) { + return true; + } + } + for (int j = (int) rows.first(); j <= rows.last(); j++) { + if (columns.first() == 0L && cliffLand(terrain, 0, j, cliff) + || columns.last() == lastColumn && cliffLand(terrain, lastColumn, j, cliff)) { + return true; + } + } + return false; + } + + private static CellRange siteCells(int site, int spacing, int window, int origin, int cell) { + long from = Math.max((long) site * spacing, (long) window * WindowKey.SIZE); + long to = Math.min(((long) site + 1L) * spacing, ((long) window + 1L) * WindowKey.SIZE); + return new CellRange(Math.ceilDiv(from - origin, cell), Math.ceilDiv(to - origin, cell) - 1L); + } + + private static boolean cliffLand(Terrain terrain, int i, int j, float cliff) { + int cell = terrain.grid.index(i, j); + return !terrain.ocean(cell) && terrain.natural(cell) >= cliff; + } + + private static int chamberRing(int radius, int cell) { + return (radius + cell - 1) / cell + 1; + } + + private static WindowKey owner(SeaInlet inlet) { + return WindowKey.containing((int) Math.floor(inlet.xs()[1]), (int) Math.floor(inlet.zs()[1])); + } + private static double squaredAbove(float radius) { return (double) radius * radius * (1D + SQUARED_MARGIN); } @@ -467,6 +542,12 @@ public final class SeaInletPlanner { private record Cover(float[] cover, boolean[] wet) { } + private record Traced(SeaInlet inlet, boolean whole) { + } + + private record CellRange(long first, long last) { + } + private static final class Terrain { private final DemGrid grid; private final HydrologySampleBuffer samples; @@ -475,6 +556,7 @@ public final class SeaInletPlanner { private final float[] cover; private final boolean[] wet; private final long seed; + private boolean clipped; private Terrain(DemGrid grid, HydrologySampleBuffer samples, int[] receivers, float[] accumulation, Cover cover, long seed) { this.grid = grid; diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletRasterizer.java b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletRasterizer.java index 58ab853d0..44047d351 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletRasterizer.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletRasterizer.java @@ -13,7 +13,8 @@ public final class SeaInletRasterizer { private static final int GRID = CHUNK + 2 * SHELL; static final int NONE = Integer.MIN_VALUE; - public void write(SeaInlet inlet, int chunkX, int chunkZ, MantleWriter writer, String fluid, String floodedBiome, SubterrainFluid subterrain) { + public void write(SeaInlet inlet, int chunkX, int chunkZ, MantleWriter writer, String fluid, SubterrainFluid subterrain, + HistoricalChunks historical) { if (!touches(inlet, chunkX, chunkZ)) { return; } @@ -22,10 +23,11 @@ public final class SeaInletRasterizer { if (!shape(inlet, (chunkX << 4) - SHELL, (chunkZ << 4) - SHELL, GRID, floors, ceilings)) { return; } - HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, fluid, floodedBiome); - HydrologyCaveCell dry = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, fluid, floodedBiome); - HydrologyCaveCell guard = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, fluid, floodedBiome); + HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, fluid); + HydrologyCaveCell dry = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, fluid); + HydrologyCaveCell guard = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, fluid); int water = inlet.waterLevel(); + boolean[] historicalAround = historicalAround(chunkX, chunkZ, historical); for (int lz = 0; lz < CHUNK; lz++) { for (int lx = 0; lx < CHUNK; lx++) { int cell = (lz + SHELL) * GRID + lx + SHELL; @@ -40,6 +42,8 @@ public final class SeaInletRasterizer { guard(writer, x, low - SHELL, water, z, guard); } else if (ceilings[cell] == SeaInlet.OPEN) { guard(writer, x, low - SHELL, floor - 1, z, guard); + } else if (historicalAround != null && besideHistorical(historicalAround, lx, lz)) { + guard(writer, x, low - SHELL, ceilings[cell], z, guard); } else { for (int y = floor + 1; y <= water; y++) { writer.setData(x, y, z, wet); @@ -66,6 +70,12 @@ public final class SeaInletRasterizer { boolean at(int x, int y, int z); } + public interface HistoricalChunks { + HistoricalChunks NONE = (chunkX, chunkZ) -> false; + + boolean at(int chunkX, int chunkZ); + } + public static boolean touches(SeaInlet inlet, int chunkX, int chunkZ) { int[] bounds = bounds(inlet); int minX = chunkX << 4; @@ -182,6 +192,36 @@ public final class SeaInletRasterizer { return roof; } + private static boolean[] historicalAround(int chunkX, int chunkZ, HistoricalChunks historical) { + boolean[] around = null; + for (int dz = -1; dz <= 1; dz++) { + for (int dx = -1; dx <= 1; dx++) { + if ((dx != 0 || dz != 0) && historical.at(chunkX + dx, chunkZ + dz)) { + if (around == null) { + around = new boolean[9]; + } + around[(dz + 1) * 3 + dx + 1] = true; + } + } + } + return around; + } + + private static boolean besideHistorical(boolean[] historicalAround, int lx, int lz) { + int fromX = lx < SHELL ? -1 : 0; + int toX = lx >= CHUNK - SHELL ? 1 : 0; + int fromZ = lz < SHELL ? -1 : 0; + int toZ = lz >= CHUNK - SHELL ? 1 : 0; + for (int dz = fromZ; dz <= toZ; dz++) { + for (int dx = fromX; dx <= toX; dx++) { + if (historicalAround[(dz + 1) * 3 + dx + 1]) { + return true; + } + } + } + return false; + } + private static void guard(MantleWriter writer, int x, int fromY, int toY, int z, HydrologyCaveCell guard) { for (int y = fromY; y <= toY; y++) { if (writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class) == null) { diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/CupCarver.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/CupCarver.java index 212241988..69b4e41c5 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/CupCarver.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/CupCarver.java @@ -13,6 +13,7 @@ import java.util.List; final class CupCarver { private static final long SALT_SITE = 0x43555053495445L; + private static final long SALT_SPLIT = 0x43555053504c54L; private static final long SALT_SITE_X = 0x43555053495858L; private static final long SALT_SITE_Z = 0x4355505349545aL; private static final long SALT_RADIUS = 0x43555052414449L; @@ -53,13 +54,14 @@ final class CupCarver { private void windowCups(DemGrid raw, int wx, int wz, HydrologySampleBuffer samples, List out) { float density = settings.ponds().seeded().density(); - if (!(density > 0f)) { + double expected = (double) density * peakPondDensity(raw, wx, wz, samples); + if (!(expected > 0D)) { return; } - int split = (int) Math.ceil(Math.sqrt(density)); + int split = (int) Math.ceil(Math.sqrt(expected)); double size = (double) WindowKey.SIZE / split; double chance = density / ((double) split * split); - long seed = settings.seed(); + long seed = CellHash.mix(settings.seed(), SALT_SPLIT, split, split); for (int sz = 0; sz < split; sz++) { for (int sx = 0; sx < split; sx++) { int siteX = wx * split + sx; @@ -74,12 +76,28 @@ final class CupCarver { if (suitable(samples, cell, slope) && CellHash.unit(CellHash.mix(seed, SALT_SITE, siteX, siteZ)) < Math.clamp(chance * samples.pondDensity()[cell], 0D, 1D) * settings.density()) { - addCup(raw, samples, cell, slope, siteX, siteZ, false, out); + addCup(raw, samples, cell, slope, x, z, false, out); } } } } + private static float peakPondDensity(DemGrid raw, int wx, int wz, HydrologySampleBuffer samples) { + int cell = raw.cell(); + int i0 = Math.max(0, Math.ceilDiv(wx * WindowKey.SIZE - raw.originX(), cell)); + int i1 = Math.min(raw.width(), Math.ceilDiv((wx + 1) * WindowKey.SIZE - raw.originX(), cell)); + int j0 = Math.max(0, Math.ceilDiv(wz * WindowKey.SIZE - raw.originZ(), cell)); + int j1 = Math.min(raw.depth(), Math.ceilDiv((wz + 1) * WindowKey.SIZE - raw.originZ(), cell)); + float[] pondDensity = samples.pondDensity(); + float peak = 0f; + for (int j = j0; j < j1; j++) { + for (int i = i0; i < i1; i++) { + peak = Math.max(peak, pondDensity[raw.index(i, j)]); + } + } + return peak; + } + private void chainedCups(DemGrid raw, HydrologySampleBuffer samples, BitSet channels, List out) { HydrologySettings.IntRange spacing = settings.ponds().seeded().channelSpacing(); double chance = Math.min(1D, 2D * raw.cell() / Math.max(1, spacing.max() - spacing.min())); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondKind.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondKind.java index 63020b156..e76c8d6b4 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondKind.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondKind.java @@ -1,8 +1,26 @@ package art.arcane.iris.generation.hydrology.water; +import art.arcane.iris.generation.hydrology.PersistedCodes; + public enum PondKind { - NATURAL, - SEEDED, - CHAINED, - LAKE + NATURAL(0), + SEEDED(1), + CHAINED(2), + LAKE(3); + + private static final PersistedCodes CODES = PersistedCodes.of(PondKind.class, PondKind::code); + + private final int code; + + PondKind(int code) { + this.code = code; + } + + public int code() { + return code; + } + + public static PondKind fromCode(int code) { + return CODES.decode(code); + } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondPlanner.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondPlanner.java index 2339718a9..629dac70a 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondPlanner.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondPlanner.java @@ -230,7 +230,7 @@ public final class PondPlanner { >= Math.clamp(settings.ponds().natural().keep() * floor.pondDensity()[0], 0f, 1f) * settings.density()) { return null; } - return new Candidate(basin, kind, floorX, floorZ, floor.rainfall()[0], fluid(floor)); + return new Candidate(basin, kind, floorX, floorZ, dryness(floor), fluid(floor)); } private Pond lake(LakeCandidate candidate, HeightLattice fine) { @@ -241,13 +241,18 @@ public final class PondPlanner { if ((floor.permission()[0] & HydrologySampleBuffer.ALLOW_PONDS) == 0) { return null; } - return measureLake(fine, new LakeSite(candidate, floor.rainfall()[0], fluid(floor))); + return measureLake(fine, new LakeSite(candidate, dryness(floor), fluid(floor))); } private String fluid(HydrologySampleBuffer floor) { return floor.fluidProfile()[0] == null ? settings.ponds().fluid() : floor.fluidProfile()[0]; } + private static float dryness(HydrologySampleBuffer floor) { + float wetness = floor.climateZoned()[0] ? floor.wetness()[0] : floor.rainfall()[0]; + return Math.clamp(1f - wetness, 0f, 1f); + } + private boolean qualifies(DemGrid raw, Basin basin, PondKind kind) { long area = (long) basin.cells().length * raw.cell() * raw.cell(); HydrologySettings.NaturalPonds natural = settings.ponds().natural(); @@ -339,7 +344,7 @@ public final class PondPlanner { return null; } int lowest = Math.max(settings.minY() + 1, settings.seaLevel()); - int level = Math.min(Math.min(Math.max(lowest, (int) Math.floor(spill.height()) - freeboard(site) - drawdown(site.rainfall())), + int level = Math.min(Math.min(Math.max(lowest, (int) Math.floor(spill.height()) - freeboard(site) - drawdown(site.dryness())), settings.maxY() - 1), levelCap); int failures = 0; for (int round = 0; round < LEVEL_ROUNDS && level >= lowest; round++) { @@ -770,8 +775,8 @@ public final class PondPlanner { CellHash.mix(settings.seed(), SALT_FREEBOARD, site.floorX(), site.floorZ())); } - private int drawdown(float rainfall) { - return Math.round(settings.ponds().climateDrawdown() * Math.clamp(1f - rainfall, 0f, 1f)); + private int drawdown(float dryness) { + return Math.round(settings.ponds().climateDrawdown() * dryness); } private static int radius(DemGrid raw, Basin basin) { @@ -807,15 +812,15 @@ public final class PondPlanner { int floorZ(); - float rainfall(); + float dryness(); String fluid(); } - private record Candidate(Basin basin, PondKind kind, int floorX, int floorZ, float rainfall, String fluid) implements Site { + private record Candidate(Basin basin, PondKind kind, int floorX, int floorZ, float dryness, String fluid) implements Site { } - private record LakeSite(LakeCandidate lake, float rainfall, String fluid) implements Site { + private record LakeSite(LakeCandidate lake, float dryness, String fluid) implements Site { @Override public PondKind kind() { return PondKind.LAKE; diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachStyle.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachStyle.java index 0b2bff47b..a4d064d3c 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachStyle.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachStyle.java @@ -1,10 +1,28 @@ package art.arcane.iris.generation.hydrology.water; +import art.arcane.iris.generation.hydrology.PersistedCodes; + public enum ReachStyle { - RUN, - RIFFLE, - CASCADE, - WATERFALL, - POND_OUTLET, - MOUTH + RUN(0), + RIFFLE(1), + CASCADE(2), + WATERFALL(3), + POND_OUTLET(4), + MOUTH(5); + + private static final PersistedCodes CODES = PersistedCodes.of(ReachStyle.class, ReachStyle::code); + + private final int code; + + ReachStyle(int code) { + this.code = code; + } + + public int code() { + return code; + } + + public static ReachStyle fromCode(int code) { + return CODES.decode(code); + } } diff --git a/core/src/main/java/art/arcane/iris/generation/locator/HydrologyShoreTargets.java b/core/src/main/java/art/arcane/iris/generation/locator/HydrologyShoreTargets.java index 299bf1706..c1916fd28 100644 --- a/core/src/main/java/art/arcane/iris/generation/locator/HydrologyShoreTargets.java +++ b/core/src/main/java/art/arcane/iris/generation/locator/HydrologyShoreTargets.java @@ -1,12 +1,10 @@ package art.arcane.iris.generation.locator; -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.generation.terrain.ShoreBiomeLineages; import java.util.Set; @@ -31,28 +29,8 @@ final class HydrologyShoreTargets { static boolean placesAny(Engine engine, Set targets) { IrisDimension dimension = engine.getDimension(); - if (places(engine, dimension.getHydrologyPolicy(), targets)) { - return true; - } - for (IrisRegion region : dimension.getAllRegions(engine)) { - if (region != null && places(engine, region.getHydrologyPolicy(), targets)) { - return true; - } - } - for (IrisBiome biome : dimension.getReachableBiomes(engine)) { - if (biome != null && places(engine, biome.getHydrologyPolicy(), targets)) { - return true; - } - } - return false; - } - - private static boolean places(Engine engine, IrisHydrologyPolicy policy, Set targets) { - if (policy == null || policy.getShoreBiomes() == null) { - return false; - } - for (String key : policy.getShoreBiomes()) { - if (key != null && HintedLocator.closureContains(engine, key, targets)) { + for (String key : ShoreBiomeLineages.placed(dimension, dimension.getAllRegions(engine), engine)) { + if (HintedLocator.closureContains(engine, key, targets)) { return true; } } diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CarveOwnership.java b/core/src/main/java/art/arcane/iris/generation/mantle/CarveOwnership.java new file mode 100644 index 000000000..a1a05d43d --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/mantle/CarveOwnership.java @@ -0,0 +1,51 @@ +package art.arcane.iris.generation.mantle; + +import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; +import art.arcane.iris.generation.subterrain.SubterrainCell; +import art.arcane.iris.generation.subterrain.SubterrainRasterizer; +import art.arcane.iris.generation.terrain.Terrain3DColumn; + +import java.util.function.BooleanSupplier; + +public final class CarveOwnership { + private CarveOwnership() { + } + + public static Owner resolve(boolean hydrology, boolean subterrain, boolean naturalOpening) { + if (hydrology) { + return Owner.HYDROLOGY; + } + if (subterrain) { + return Owner.SUBTERRAIN; + } + return naturalOpening ? Owner.NATURAL_OPENING : Owner.CAVERN; + } + + public static boolean carved(Terrain3DColumn transformed, int y, HydrologyCaveCell hydrology, SubterrainCell subterrain, + BooleanSupplier naturalOpening, BooleanSupplier cavern) { + if (transformed != null) { + if (hydrology == null && SubterrainRasterizer.protectsPlacement(subterrain)) { + return subterrain.carve(); + } + return y >= 0 && y < transformed.topY() && !transformed.isSolid(y); + } + boolean claims = subterrainClaims(subterrain); + return switch (resolve(hydrology != null, claims, hydrology == null && !claims && naturalOpening.getAsBoolean())) { + case HYDROLOGY -> hydrology.carves(); + case SUBTERRAIN -> subterrain.carve(); + case NATURAL_OPENING -> true; + case CAVERN -> cavern.getAsBoolean(); + }; + } + + public static boolean subterrainClaims(SubterrainCell cell) { + return cell != null && cell.owned() && (!cell.solid() || cell.room().reservedSolid()); + } + + public enum Owner { + HYDROLOGY, + SUBTERRAIN, + NATURAL_OPENING, + CAVERN + } +} 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 346f62f77..aeb139d0f 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 @@ -1,8 +1,14 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; +import art.arcane.iris.generation.hydrology.underground.SeaInlet; +import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import java.util.Arrays; +import java.util.List; + public final class CaveCeilingMask { static final int CONTAINMENT = 2; static final int ROOF = 2; @@ -53,6 +59,69 @@ public final class CaveCeilingMask { return masked; } + public static long[] headroom(int chunkX, int chunkZ, HydrologyRuntime runtime, long[] bands) { + List inlets = runtime.inlets(chunkX, chunkZ); + if (inlets.isEmpty()) { + return null; + } + int roofClearance = runtime.settings().underground().seaInlets().roofClearance(); + return fillHeadroom(chunkX, chunkZ, inlets, roofClearance, bands) ? bands : null; + } + + static boolean fillHeadroom(int chunkX, int chunkZ, List inlets, int roofClearance, long[] bands) { + if (inlets.isEmpty()) { + return false; + } + int originX = (chunkX << 4) - CONTAINMENT; + int originZ = (chunkZ << 4) - CONTAINMENT; + int[] bottoms = new int[FIELD * FIELD]; + int[] tops = new int[FIELD * FIELD]; + Arrays.fill(bottoms, Integer.MAX_VALUE); + Arrays.fill(tops, Integer.MIN_VALUE); + int[] column = new int[2]; + boolean roofed = false; + for (SeaInlet inlet : inlets) { + int[] bounds = SeaInletRasterizer.bounds(inlet); + int fromX = Math.max(originX, bounds[0]); + int toX = Math.min(originX + FIELD - 1, bounds[2]); + int toZ = Math.min(originZ + FIELD - 1, bounds[3]); + for (int z = Math.max(originZ, bounds[1]); z <= toZ; z++) { + for (int x = fromX; x <= toX; x++) { + if (!SeaInletRasterizer.column(inlet, x, z, column) || column[1] == SeaInlet.OPEN) { + continue; + } + int index = (z - originZ) * FIELD + x - originX; + bottoms[index] = Math.min(bottoms[index], inlet.waterLevel() + 1); + tops[index] = Math.max(tops[index], column[1] + roofClearance); + roofed = true; + } + } + } + if (!roofed) { + return false; + } + boolean masked = false; + for (int lz = 0; lz < CHUNK; lz++) { + for (int lx = 0; lx < CHUNK; lx++) { + int bottom = Integer.MAX_VALUE; + int top = Integer.MIN_VALUE; + for (int fz = lz; fz <= lz + CONTAINMENT * 2; fz++) { + for (int fx = lx; fx <= lx + CONTAINMENT * 2; fx++) { + bottom = Math.min(bottom, bottoms[fz * FIELD + fx]); + top = Math.max(top, tops[fz * FIELD + fx]); + } + } + bands[PowerOfTwoCoordinates.packLocal16(lx, lz)] = SurfaceFluidBoundaryPlan.boundary(bottom, top); + masked |= bottom <= top; + } + } + return masked; + } + + public static boolean masked(int[] ceilings, long[] headroom, int column, int y) { + return ceilings != null && y > ceilings[column] || SurfaceFluidBoundaryPlan.protects(headroom, column, y); + } + 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/CaveObjectPlacementTransaction.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveObjectPlacementTransaction.java index e8a47f754..445628caf 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveObjectPlacementTransaction.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/CaveObjectPlacementTransaction.java @@ -112,8 +112,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { discard(); return CommitResult.REJECTED_SUBTERRAIN; } - HydrologyCaveCell hydrology = delegate.getData(x, y, z, HydrologyCaveCell.class); - if (hydrology != null && hydrology.protectsPlacement()) { + if (delegate.getData(x, y, z, HydrologyCaveCell.class) != null) { discard(); return CommitResult.REJECTED_HYDROLOGY; } diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveTerrainSnapshot.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveTerrainSnapshot.java index a175e83bb..526af2893 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveTerrainSnapshot.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/CaveTerrainSnapshot.java @@ -85,7 +85,7 @@ public final class CaveTerrainSnapshot { bytes += 16L + (long) section.length * 8L; for (HydrologyCaveCell cell : section) { if (cell != null) { - bytes += 208L + ((long) cell.fluidProfileKey().length() + cell.floodedBiomeKey().length()) * 2L; + bytes += 208L + (long) cell.fluidProfileKey().length() * 2L; } } } diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/EngineMantle.java b/core/src/main/java/art/arcane/iris/generation/mantle/EngineMantle.java index 7f6d7ee2a..7bce9f634 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/EngineMantle.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/EngineMantle.java @@ -28,8 +28,6 @@ import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.EngineTarget; import art.arcane.iris.generation.decoration.tree.TreeBlockMaterial; import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.generation.terrain.Terrain3DColumn; -import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveStorage; import art.arcane.iris.pack.value.IrisPosition; import art.arcane.iris.generation.block.BoundBlockState; @@ -123,16 +121,14 @@ public interface EngineMantle extends MatterGenerator { } default boolean isCarved(int x, int h, int z) { - Terrain3DColumn transformed = getComplex().transformedColumn(x, z); - if (transformed != null) { - return h >= 0 && h < transformed.topY() && !transformed.isSolid(h); - } - HydrologyCaveCell hydrology = HydrologyCaveStorage.getIfPresent(getMantle(), x, h, z); - if (hydrology != null) { - return hydrology.carves(); - } - return getMantle().get(x, h, z, MatterCavern.class) != null - || getComplex().isTerrain3DOpening(x, h, z); + return CarveOwnership.carved( + getComplex().transformedColumn(x, z), + h, + HydrologyCaveStorage.getIfPresent(getMantle(), x, h, z), + getEngine().getSubterrainCell(x, h, z), + () -> getComplex().isTerrain3DOpening(x, h, z), + () -> getMantle().get(x, h, z, MatterCavern.class) != null + ); } default NativeBlockState get(int x, int y, int z) { 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 9c5824770..abefd03d2 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 @@ -12,6 +12,8 @@ import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.stream.ProvisionalSampling; import art.arcane.iris.generation.subterrain.SubterrainPlan; import art.arcane.iris.generation.subterrain.SubterrainPlanner; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.generation.terrain.Terrain3DColumn; import art.arcane.volmlib.util.mantle.flag.MantleFlag; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; @@ -31,6 +33,7 @@ final class MantleCarvedTerrain implements CarvedTerrain { private final MantleWriter writer; private final IrisComplex complex; private final Engine engine; + private final IrisDimension dimension; private final int chunkX; private final int chunkZ; private final int originX; @@ -54,12 +57,13 @@ final class MantleCarvedTerrain implements CarvedTerrain { this.writer = writer; this.complex = complex; this.engine = engine; + this.dimension = engine.getDimension(); this.chunkX = chunkX; this.chunkZ = chunkZ; this.originX = (chunkX - 1) << 4; this.originZ = (chunkZ - 1) << 4; this.height = writer.getMantle().getWorldHeight(); - this.caveLavaHeight = engine.getDimension().getCaveLavaHeight(); + this.caveLavaHeight = dimension.getCaveLavaHeight(); this.minimumY = engine.getWorld().minHeight(); HydrologyRuntime runtime = complex.getHydrologyRuntime(); this.caveFluids = runtime.caveFluidPolicies(); @@ -110,10 +114,10 @@ final class MantleCarvedTerrain implements CarvedTerrain { return null; } long revision = ProvisionalSampling.revision(); - IrisBiome biome = engine.getCaveBiome(x, y, z); + IrisBiome biome = engine.getCaveBiomeBelowSurface(x, y, z); + IrisRegion region = complex.getRegionStream().get(x, z); requireFinal(revision, x, z); - IrisHydrologyPolicy policy = biome == null ? null : biome.getHydrologyPolicy(); - return policy == null ? null : policy.getFluid(); + return IrisHydrologyPolicy.inherited(biome == null ? List.of() : List.of(biome), region, dimension, IrisHydrologyPolicy::getFluid); } private static Collection inlets(HydrologyRuntime runtime, int chunkX, int chunkZ) { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java index 7250cfbb8..3f49d535b 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java @@ -169,6 +169,10 @@ public class MantleCarvingComponent extends IrisMantleComponent { ); int[] caveCeilings = CaveCeilingMask.fill(x, z, complex.getHydrologyRuntime()::raster, blendScratch.caveCeilingField, blendScratch.caveCeilings) ? blendScratch.caveCeilings : null; + long[] inletHeadroom = CaveCeilingMask.headroom(x, z, complex.getHydrologyRuntime(), blendScratch.inletHeadroom); + if (inletHeadroom != null) { + SurfaceFluidBoundaryPlan.join(surfaceFluidBoundaries, inletHeadroom); + } CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); for (WeightedProfile weightedProfile : weightedProfiles) { carveProfile(weightedProfile, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaries, caveCeilings, fluidSupportPlan); @@ -190,10 +194,10 @@ public class MantleCarvingComponent extends IrisMantleComponent { caveCeilings ); } - rasterizeSubterrain(writer, x, z, complex, caveCeilings); + rasterizeSubterrain(writer, x, z, complex, caveCeilings, inletHeadroom); } - private void rasterizeSubterrain(MantleWriter writer, int chunkX, int chunkZ, IrisComplex complex, int[] caveCeilings) { + private void rasterizeSubterrain(MantleWriter writer, int chunkX, int chunkZ, IrisComplex complex, int[] caveCeilings, long[] inletHeadroom) { SubterrainPlanner planner = complex.getSubterrainPlanner(); if (planner == null || planner.isEmpty()) { return; @@ -207,7 +211,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { if (cell.solid() && !cell.room().reservedSolid()) { return; } - if (!cell.solid() && caveCeilings != null && y > caveCeilings[PowerOfTwoCoordinates.packLocal16(x & 15, z & 15)]) { + if (!cell.solid() && CaveCeilingMask.masked(caveCeilings, inletHeadroom, PowerOfTwoCoordinates.packLocal16(x & 15, z & 15), y)) { return; } if (cell.solid()) { @@ -763,6 +767,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { private final double[] chunkSurfaceHeightSamples = new double[CHUNK_AREA]; private final int[] caveCeilingField = new int[CaveCeilingMask.FIELD * CaveCeilingMask.FIELD]; private final int[] caveCeilings = new int[CHUNK_AREA]; + private final long[] inletHeadroom = new long[CHUNK_AREA]; private final double[][] neighbourHeights = new double[NEIGHBOURS][CHUNK_AREA]; private final Object[][] neighbourObjects = new Object[NEIGHBOURS][CHUNK_AREA]; private final long[][] neighbourSubmerged = new long[NEIGHBOURS][4]; 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 078698d3f..9838b1794 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 @@ -81,7 +81,7 @@ public final class MantleHydrologyComponent extends IrisMantleComponent { if (!inlets.isEmpty()) { SeaInletRasterizer.SubterrainFluid subterrain = subterrainFluid(writer, complex, chunkX, chunkZ); for (SeaInlet inlet : inlets) { - INLETS.write(inlet, chunkX, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, "", subterrain); + INLETS.write(inlet, chunkX, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, subterrain, complex::isHistoricalChunk); } } generateFalls(writer, complex, runtime, own, chunkX, chunkZ); diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java index 3d452b5ab..e86ae39dc 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java @@ -897,7 +897,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int y, int lavaHeight ) { - if (hydrology != null && hydrology.protectsPlacement()) { + if (hydrology != null) { return false; } if (cavern == null || !cavern.isCavern()) { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java index dbd905ce2..655525361 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java @@ -54,6 +54,7 @@ import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.iris.generation.block.B; import java.util.LinkedHashMap; +import java.util.function.BooleanSupplier; import java.util.function.Supplier; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; @@ -67,6 +68,8 @@ import static art.arcane.iris.generation.mantle.EngineMantle.AIR; @Data public class MantleWriter implements ObjectPassPlacer, AutoCloseable { private static final int OBJECT_COMPONENT_PRIORITY = 2; + private static final BooleanSupplier ALWAYS = () -> true; + private static final BooleanSupplier NEVER = () -> false; private final EngineMantle engineMantle; private final Mantle mantle; @@ -460,34 +463,25 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { } public boolean isPrerequisiteCarved(int x, int y, int z) { - SubterrainCell feature = getEngine().getSubterrainCell(x, y, z); - if (feature != null && feature.owned()) { - return feature.carve(); - } - Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z); - if (transformed != null) { - return y >= 0 && y < transformed.topY() && !transformed.isSolid(y); - } - HydrologyCaveCell hydrology = getPrerequisiteDataIfPresent(x, y, z, HydrologyCaveCell.class); - if (hydrology != null) { - return hydrology.carves(); - } - return getPrerequisiteDataIfPresent(x, y, z, MatterCavern.class) != null - || engineMantle.getComplex().isTerrain3DOpening(x, y, z); + return CarveOwnership.carved( + engineMantle.getComplex().transformedColumn(x, z), + y, + getPrerequisiteDataIfPresent(x, y, z, HydrologyCaveCell.class), + getEngine().getSubterrainCell(x, y, z), + () -> engineMantle.getComplex().isTerrain3DOpening(x, y, z), + () -> getPrerequisiteDataIfPresent(x, y, z, MatterCavern.class) != null + ); } public byte[] getPrerequisiteCarvedColumn(int x, int z, int height) { int cappedHeight = Math.min(Math.max(height, 0), mantle.getWorldHeight()); - Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z); - if (transformed != null) { - return carvedColumn(transformed, cappedHeight); - } byte[] carvedColumn = new byte[cappedHeight]; if (cappedHeight <= 0) { return carvedColumn; } - Terrain3DColumn terrainColumn = engineMantle.getComplex().terrainColumn(x, z); + Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z); + Terrain3DColumn terrainColumn = transformed == null ? engineMantle.getComplex().terrainColumn(x, z) : null; if (terrainColumn != null) { int maximumY = Math.min(cappedHeight, terrainColumn.topY()); for (int y = Math.max(0, terrainColumn.minY()); y < maximumY; y++) { @@ -499,46 +493,38 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { } MantleChunk chunk = acquireChunk(x >> 4, z >> 4); + SubterrainCell[] subterrain = subterrainColumn(x, z, cappedHeight); if (chunk == null) { + for (int y = 0; y < cappedHeight; y++) { + carvedColumn[y] = carvedByte(transformed, y, null, subterrain, carvedColumn[y] != 0, false); + } return carvedColumn; } synchronized (chunk) { - int lastSection = (cappedHeight - 1) >> 4; - for (int section = 0; section <= lastSection; section++) { - if (!chunk.exists(section)) { - continue; - } - Matter matter = chunk.get(section); - if (matter == null) { - continue; - } - MatterSlice journalSlice = matter.getSlice(PreObjectMatterCell.class); - MatterSlice cavernSlice = matter.getSlice(MatterCavern.class); - MatterSlice hydrologySlice = matter.getSlice(HydrologyCaveCell.class); - int sectionBaseY = section << 4; - int sectionMaxY = Math.min(cappedHeight, sectionBaseY + 16); - for (int y = sectionBaseY; y < sectionMaxY; y++) { - int localY = y & 15; - PreObjectMatterCell cell = journalSlice == null - ? null - : journalSlice.get(x & 15, localY, z & 15); - HydrologyCaveCell hydrology = cell != null && cell.hydrologyCaptured() - ? cell.hydrology() - : hydrologySlice == null - ? null - : hydrologySlice.get(x & 15, localY, z & 15); - if (hydrology != null) { - carvedColumn[y] = hydrology.carves() ? (byte) 1 : 0; - continue; - } - MatterCavern cavern = cell != null && cell.cavernCaptured() - ? cell.cavern() - : cavernSlice == null ? null : cavernSlice.get(x & 15, localY, z & 15); - if (cavern != null) { - carvedColumn[y] = 1; - } + MatterSlice journalSlice = null; + MatterSlice cavernSlice = null; + MatterSlice hydrologySlice = null; + for (int y = 0; y < cappedHeight; y++) { + int localY = y & 15; + if (localY == 0) { + Matter matter = chunk.exists(y >> 4) ? chunk.get(y >> 4) : null; + journalSlice = matter == null ? null : matter.getSlice(PreObjectMatterCell.class); + cavernSlice = matter == null ? null : matter.getSlice(MatterCavern.class); + hydrologySlice = matter == null ? null : matter.getSlice(HydrologyCaveCell.class); } + PreObjectMatterCell cell = journalSlice == null + ? null + : journalSlice.get(x & 15, localY, z & 15); + HydrologyCaveCell hydrology = cell != null && cell.hydrologyCaptured() + ? cell.hydrology() + : hydrologySlice == null + ? null + : hydrologySlice.get(x & 15, localY, z & 15); + MatterCavern cavern = cell != null && cell.cavernCaptured() + ? cell.cavern() + : cavernSlice == null ? null : cavernSlice.get(x & 15, localY, z & 15); + carvedColumn[y] = carvedByte(transformed, y, hydrology, subterrain, carvedColumn[y] != 0, cavern != null); } } return carvedColumn; @@ -599,8 +585,7 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { if (slice == null) { return false; } - HydrologyCaveCell hydrology = slice.get(x & 15, y & 15, z & 15); - return hydrology != null && hydrology.protectsPlacement(); + return slice.get(x & 15, y & 15, z & 15) != null; } private static void clearTile(Matter matter, int x, int y, int z) { @@ -820,35 +805,26 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { @Override public boolean isCarved(int x, int y, int z) { - SubterrainCell feature = getEngine().getSubterrainCell(x, y, z); - if (feature != null && feature.owned()) { - return feature.carve(); - } - Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z); - if (transformed != null) { - return y >= 0 && y < transformed.topY() && !transformed.isSolid(y); - } - HydrologyCaveCell hydrology = getDataIfPresent(x, y, z, HydrologyCaveCell.class); - if (hydrology != null) { - return hydrology.carves(); - } - return getDataIfPresent(x, y, z, MatterCavern.class) != null - || engineMantle.getComplex().isTerrain3DOpening(x, y, z); + return CarveOwnership.carved( + engineMantle.getComplex().transformedColumn(x, z), + y, + getDataIfPresent(x, y, z, HydrologyCaveCell.class), + getEngine().getSubterrainCell(x, y, z), + () -> engineMantle.getComplex().isTerrain3DOpening(x, y, z), + () -> getDataIfPresent(x, y, z, MatterCavern.class) != null + ); } public byte[] getCarvedColumn(int x, int z, int height) { int cappedHeight = Math.min(Math.max(height, 0), mantle.getWorldHeight()); - Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z); - if (transformed != null) { - return carvedColumn(transformed, cappedHeight); - } byte[] carvedColumn = new byte[cappedHeight]; if (cappedHeight <= 0) { return carvedColumn; } - Terrain3DColumn terrainColumn = engineMantle.getComplex().terrainColumn(x, z); + Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z); + Terrain3DColumn terrainColumn = transformed == null ? engineMantle.getComplex().terrainColumn(x, z) : null; if (terrainColumn != null) { int maximumY = Math.min(cappedHeight, terrainColumn.topY()); for (int y = terrainColumn.minY(); y < maximumY; y++) { @@ -859,44 +835,24 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { } MantleChunk chunk = acquireChunk(x >> 4, z >> 4); - if (chunk == null) { - return carvedColumn; - } - + SubterrainCell[] subterrain = subterrainColumn(x, z, cappedHeight); int localX = x & 15; int localZ = z & 15; - int lastSection = (cappedHeight - 1) >> 4; - for (int section = 0; section <= lastSection; section++) { - if (!chunk.exists(section)) { - continue; - } - - Matter matter = chunk.get(section); - if (matter == null) { - continue; - } - - MatterSlice cavernSlice = matter.getSlice(MatterCavern.class); - MatterSlice hydrologySlice = matter.hasSlice(HydrologyCaveCell.class) - ? matter.getSlice(HydrologyCaveCell.class) - : null; - if (cavernSlice == null && hydrologySlice == null) { - continue; - } - int sectionBaseY = section << 4; - int sectionMaxY = Math.min(cappedHeight, sectionBaseY + 16); - for (int y = sectionBaseY; y < sectionMaxY; y++) { - HydrologyCaveCell hydrology = hydrologySlice == null + MatterSlice cavernSlice = null; + MatterSlice hydrologySlice = null; + for (int y = 0; y < cappedHeight; y++) { + int localY = y & 15; + if (localY == 0) { + Matter matter = chunk == null || !chunk.exists(y >> 4) ? null : chunk.get(y >> 4); + cavernSlice = matter == null ? null : matter.getSlice(MatterCavern.class); + hydrologySlice = matter == null || !matter.hasSlice(HydrologyCaveCell.class) ? null - : hydrologySlice.get(localX, y & 15, localZ); - if (hydrology != null) { - carvedColumn[y] = hydrology.carves() ? (byte) 1 : 0; - } else if (cavernSlice != null && cavernSlice.get(localX, y & 15, localZ) != null) { - carvedColumn[y] = 1; - } + : matter.getSlice(HydrologyCaveCell.class); } + HydrologyCaveCell hydrology = hydrologySlice == null ? null : hydrologySlice.get(localX, localY, localZ); + boolean cavern = cavernSlice != null && cavernSlice.get(localX, localY, localZ) != null; + carvedColumn[y] = carvedByte(transformed, y, hydrology, subterrain, carvedColumn[y] != 0, cavern); } - return carvedColumn; } @@ -1033,15 +989,22 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { return blocks > 0 ? Math.ceilDiv(blocks, 16) : 0; } - private static byte[] carvedColumn(Terrain3DColumn terrain, int height) { - byte[] result = new byte[height]; - int maximumY = Math.min(height, terrain.topY()); - for (int y = 0; y < maximumY; y++) { - if (!terrain.isSolid(y)) { - result[y] = 1; - } + private SubterrainCell[] subterrainColumn(int x, int z, int height) { + Engine engine = getEngine(); + if (engine.subterrainAbsentInChunk(x >> 4, z >> 4)) { + return null; } - return result; + SubterrainCell[] cells = new SubterrainCell[height]; + for (int y = 0; y < height; y++) { + cells[y] = engine.getSubterrainCell(x, y, z); + } + return cells; + } + + private static byte carvedByte(Terrain3DColumn transformed, int y, HydrologyCaveCell hydrology, SubterrainCell[] subterrain, + boolean naturalOpening, boolean cavern) { + return CarveOwnership.carved(transformed, y, hydrology, subterrain == null ? null : subterrain[y], + naturalOpening ? ALWAYS : NEVER, cavern ? ALWAYS : NEVER) ? (byte) 1 : 0; } public final class ObjectPlacementCapture implements AutoCloseable { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java index 521941d6f..696545db9 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java @@ -491,8 +491,7 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { } private boolean hasProtectedHydrology(int x, int y, int z) { - HydrologyCaveCell hydrology = getDataIfPresent(x, y, z, HydrologyCaveCell.class); - return hydrology != null && hydrology.protectsPlacement(); + return getDataIfPresent(x, y, z, HydrologyCaveCell.class) != null; } private final class CommitJournal { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectSourcePlan.java b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectSourcePlan.java index ab7e12def..8871dc596 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectSourcePlan.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectSourcePlan.java @@ -364,7 +364,7 @@ final class ObjectSourcePlan { case Identifier identifier -> 24L + stringBytes(identifier.namespace()) + stringBytes(identifier.key()); case NativeBlockState ignored -> 0L; case MatterCavern cavern -> 24L + stringBytes(cavern.getCustomBiome()); - case HydrologyCaveCell cell -> 48L + stringBytes(cell.fluidProfileKey()) + stringBytes(cell.floodedBiomeKey()); + case HydrologyCaveCell cell -> 48L + stringBytes(cell.fluidProfileKey()); case MatterMarker marker -> 16L + stringBytes(marker.getTag()); case TileWrapper ignored -> 4L * UNKNOWN_PAYLOAD_BYTES; case Enum ignored -> 0L; diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/SurfaceFluidBoundaryPlan.java b/core/src/main/java/art/arcane/iris/generation/mantle/SurfaceFluidBoundaryPlan.java index 2e1ea8203..86fc4b6c0 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/SurfaceFluidBoundaryPlan.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/SurfaceFluidBoundaryPlan.java @@ -73,6 +73,17 @@ final class SurfaceFluidBoundaryPlan { } } + static void join(long[] boundaries, long[] bands) { + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + long band = bands[columnIndex]; + if (startY(band) > endY(band)) { + continue; + } + long boundary = boundaries[columnIndex]; + boundaries[columnIndex] = boundary(Math.min(startY(boundary), startY(band)), Math.max(endY(boundary), endY(band))); + } + } + static boolean protects(long[] boundaries, int columnIndex, int y) { if (boundaries == null || columnIndex < 0 || columnIndex >= boundaries.length) { return false; diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/BiomeLineages.java b/core/src/main/java/art/arcane/iris/generation/runtime/BiomeLineages.java new file mode 100644 index 000000000..841337867 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/runtime/BiomeLineages.java @@ -0,0 +1,124 @@ +package art.arcane.iris.generation.runtime; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.block.DataProvider; + +import java.util.ArrayDeque; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +final class BiomeLineages { + private final Set heirs; + private final Object lock = new Object(); + private volatile IdentityHashMap> roots = new IdentityHashMap<>(); + private volatile Map> chains = new HashMap<>(); + + private BiomeLineages(Set heirs) { + this.heirs = heirs; + } + + static BiomeLineages compile(Collection biomes, DataProvider provider) { + Set heirs = new HashSet<>(); + for (IrisBiome biome : biomes) { + if (biome.getHydrologyPolicy() != null) { + addDescendants(biome, provider, heirs); + } + } + return new BiomeLineages(heirs); + } + + boolean inherits(IrisBiome biome) { + return heirs.contains(biome.getLoadKey()); + } + + List root(IrisBiome biome) { + List known = roots.get(biome); + if (known != null) { + return known; + } + synchronized (lock) { + List raced = roots.get(biome); + if (raced != null) { + return raced; + } + List created = List.of(biome); + IdentityHashMap> next = new IdentityHashMap<>(roots); + next.put(biome, created); + roots = next; + return created; + } + } + + List chain(IrisBiome[] leafFirst) { + if (leafFirst.length == 1) { + return root(leafFirst[0]); + } + Chain key = new Chain(leafFirst); + List known = chains.get(key); + if (known != null) { + return known; + } + synchronized (lock) { + List raced = chains.get(key); + if (raced != null) { + return raced; + } + List created = List.of(leafFirst); + Map> next = new HashMap<>(chains); + next.put(key, created); + chains = next; + return created; + } + } + + private static void addDescendants(IrisBiome parent, DataProvider provider, Set heirs) { + Set visited = Collections.newSetFromMap(new IdentityHashMap<>()); + ArrayDeque pending = new ArrayDeque<>(); + addChildren(parent, provider, pending); + while (!pending.isEmpty()) { + IrisBiome child = pending.poll(); + if (visited.add(child)) { + heirs.add(child.getLoadKey()); + addChildren(child, provider, pending); + } + } + } + + private static void addChildren(IrisBiome parent, DataProvider provider, ArrayDeque pending) { + for (IrisBiome child : parent.getRealChildren(provider)) { + if (child != null) { + pending.add(child); + } + } + } + + private record Chain(IrisBiome[] biomes) { + @Override + public boolean equals(Object other) { + if (!(other instanceof Chain chain) || chain.biomes.length != biomes.length) { + return false; + } + for (int index = 0; index < biomes.length; index++) { + if (chain.biomes[index] != biomes[index]) { + return false; + } + } + return true; + } + + @Override + public int hashCode() { + int hash = 1; + for (IrisBiome biome : biomes) { + hash = 31 * hash + System.identityHashCode(biome); + } + return hash; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/Engine.java b/core/src/main/java/art/arcane/iris/generation/runtime/Engine.java index f0739750e..8bf0cec7c 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/Engine.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/Engine.java @@ -47,8 +47,6 @@ import art.arcane.iris.pack.value.IrisPosition; import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.structure.placement.IrisStructure; import art.arcane.iris.world.IrisWorld; -import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; -import art.arcane.iris.generation.hydrology.cave.HydrologyCaveStorage; import art.arcane.volmlib.nativelib.terrain.NativeBiome; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.collection.KList; @@ -367,24 +365,10 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, if (featureBiome != null) { return featureBiome; } - IrisBiome mantleBiome = mantleCaveBiome(x, y, z); + IrisBiome mantleBiome = customCaveBiome(getMantle().getMantle().get(x, y, z, MatterCavern.class)); return mantleBiome != null ? mantleBiome : getCaveBiome(x, y, z); } - private IrisBiome mantleCaveBiome(int x, int y, int z) { - IrisBiome flooded = floodedCaveBiome(x, y, z); - return flooded != null ? flooded : customCaveBiome(getMantle().getMantle().get(x, y, z, MatterCavern.class)); - } - - private IrisBiome floodedCaveBiome(int x, int y, int z) { - HydrologyCaveCell hydrology = HydrologyCaveStorage.getIfPresent( - getMantle().getMantle(), x, y, z); - if (hydrology != null && !hydrology.floodedBiomeKey().isEmpty()) { - return getData().getBiomeLoader().load(hydrology.floodedBiomeKey()); - } - return null; - } - private IrisBiome customCaveBiome(MatterCavern cavern) { if (cavern != null && cavern.getCustomBiome() != null && !cavern.getCustomBiome().isEmpty()) { return getData().getBiomeLoader().load(cavern.getCustomBiome()); @@ -439,15 +423,12 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, biomes[index] = surface; continue; } - IrisBiome biome = floodedCaveBiome(x, y, z); - if (biome == null) { - if (!cavernChunkResolved) { - cavernChunk = useCavernChunk(x, z); - cavernChunkResolved = true; - } - biome = cavernChunk == null || y < 0 || y >= getMantle().getMantle().getWorldHeight() - ? null : customCaveBiome(cavernChunk.get(x & 15, y, z & 15, MatterCavern.class)); + if (!cavernChunkResolved) { + cavernChunk = useCavernChunk(x, z); + cavernChunkResolved = true; } + IrisBiome biome = cavernChunk == null || y < 0 || y >= getMantle().getMantle().getWorldHeight() + ? null : customCaveBiome(cavernChunk.get(x & 15, y, z & 15, MatterCavern.class)); if (biome == null) { biome = resolveConfiguredCaveBiome(x, y, z, null); } @@ -478,8 +459,8 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, @BlockCoordinates default IrisBiome getCaveBiome(int x, int z) { - IrisBiome biome = getComplex().getCaveBiomeStream().get(x, z); - return biome == null || biome.getLoadKey() == null ? getSurfaceBiome(x, z) : biome; + IrisBiome biome = regionCaveBiome(x, z); + return biome == null ? getSurfaceBiome(x, z) : biome; } @BlockCoordinates @@ -489,13 +470,9 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, @BlockCoordinates default IrisBiome getCaveBiome(int x, int y, int z, IrisDimensionCarvingResolver.State state) { - IrisBiome featureBiome = getSubterrainBiome(x, y, z); - if (featureBiome != null) { - return featureBiome; - } - IrisBiome configuredBiome = resolveConfiguredCaveBiome(x, y, z, state); - if (configuredBiome != null) { - return configuredBiome; + IrisBiome placedBiome = placedCaveBiome(x, y, z, state); + if (placedBiome != null) { + return placedBiome; } boolean naturalFallback = answersFromNaturalTerrain(x, z); IrisBiome surfaceBiome = caveDepthSurfaceBiome(x, z, naturalFallback); @@ -503,6 +480,26 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, return resolveDepthCaveBiome(x, y, z, surfaceBiome, surfaceY); } + @BlockCoordinates + default IrisBiome getCaveBiomeBelowSurface(int x, int y, int z) { + IrisBiome placedBiome = placedCaveBiome(x, y, z, null); + if (placedBiome != null) { + return placedBiome; + } + IrisBiome caveBiome = regionCaveBiome(x, z); + return caveBiome == null ? null : depthCaveBiome(caveBiome, y, null, caveDepthSurfaceY(x, z, answersFromNaturalTerrain(x, z))); + } + + private IrisBiome regionCaveBiome(int x, int z) { + IrisBiome biome = getComplex().getCaveBiomeStream().get(x, z); + return biome == null || biome.getLoadKey() == null ? null : biome; + } + + private IrisBiome placedCaveBiome(int x, int y, int z, IrisDimensionCarvingResolver.State state) { + IrisBiome featureBiome = getSubterrainBiome(x, y, z); + return featureBiome != null ? featureBiome : resolveConfiguredCaveBiome(x, y, z, state); + } + private IrisBiome caveDepthSurfaceBiome(int x, int z, boolean naturalFallback) { if (naturalFallback) { return getComplex().naturalSurfaceBiome(x, z); @@ -525,15 +522,8 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, IrisBiome surfaceBiome, int surfaceY ) { - IrisBiome featureBiome = getSubterrainBiome(x, y, z); - if (featureBiome != null) { - return featureBiome; - } - IrisBiome configuredBiome = resolveConfiguredCaveBiome(x, y, z, state); - if (configuredBiome != null) { - return configuredBiome; - } - return resolveDepthCaveBiome(x, y, z, surfaceBiome, surfaceY); + IrisBiome placedBiome = placedCaveBiome(x, y, z, state); + return placedBiome != null ? placedBiome : resolveDepthCaveBiome(x, y, z, surfaceBiome, surfaceY); } private IrisBiome resolveConfiguredCaveBiome( @@ -907,7 +897,7 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, .map(IrisRegistrant::getLoadKey) .collect(Collectors.toSet()); Set regionKeys = getDimension().getAllRegions(this).stream() - .filter((i) -> i.getAllBiomeIds().stream().anyMatch(biomeKeys::contains) + .filter((i) -> i.getAllBiomeIds(getDimension(), this).stream().anyMatch(biomeKeys::contains) || containsObjectPlacement(i.getObjects(), normalizedObjectKey, data)) .map(IrisRegistrant::getLoadKey) .collect(Collectors.toSet()); diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/HydrologyShoreBiomes.java b/core/src/main/java/art/arcane/iris/generation/runtime/HydrologyShoreBiomes.java index bf72db4db..4dc723d8d 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/HydrologyShoreBiomes.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/HydrologyShoreBiomes.java @@ -8,6 +8,7 @@ import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.pack.loading.IrisData; +import java.util.Collection; import java.util.IdentityHashMap; import java.util.List; import java.util.Objects; @@ -22,7 +23,7 @@ final class HydrologyShoreBiomes { private final IrisData data; private final long seed; private final Object policyLock = new Object(); - private volatile IdentityHashMap> policies = new IdentityHashMap<>(); + private volatile IdentityHashMap, IdentityHashMap> policies = new IdentityHashMap<>(); private int policyCount; HydrologyShoreBiomes(IrisDimension dimension, IrisData data, long seed) { @@ -31,8 +32,25 @@ final class HydrologyShoreBiomes { this.seed = seed; } - IrisBiome select(IrisBiome biome, IrisRegion region, int x, int z, int shoreDistance) { - Policy policy = policy(biome, region); + static boolean banded(IrisDimension dimension, Collection regions, Collection biomes) { + if (banded(dimension.getHydrologyPolicy())) { + return true; + } + for (IrisRegion region : regions) { + if (region != null && banded(region.getHydrologyPolicy())) { + return true; + } + } + for (IrisBiome biome : biomes) { + if (biome != null && banded(biome.getHydrologyPolicy())) { + return true; + } + } + return false; + } + + IrisBiome select(List lineage, IrisRegion region, int x, int z, int shoreDistance) { + Policy policy = policy(lineage, region); IrisBiome[] biomes = policy.biomes(); if (shoreDistance > policy.width() || biomes.length == 0) { return null; @@ -44,52 +62,70 @@ final class HydrologyShoreBiomes { return biomes[(int) Long.remainderUnsigned(patch, biomes.length)]; } - private Policy policy(IrisBiome biome, IrisRegion region) { - IdentityHashMap regions = policies.get(biome); + private Policy policy(List lineage, IrisRegion region) { + IdentityHashMap regions = policies.get(lineage); Policy known = regions == null ? null : regions.get(region); - return known != null ? known : remember(biome, region, resolve(biome, region)); + return known != null ? known : remember(lineage, region, resolve(lineage, region)); } - private Policy remember(IrisBiome biome, IrisRegion region, Policy resolved) { + private Policy remember(List lineage, IrisRegion region, Policy resolved) { synchronized (policyLock) { - IdentityHashMap current = policies.get(biome); + IdentityHashMap current = policies.get(lineage); Policy raced = current == null ? null : current.get(region); if (raced != null) { return raced; } boolean full = policyCount >= CAPACITY; - IdentityHashMap> next = full ? new IdentityHashMap<>() : new IdentityHashMap<>(policies); + IdentityHashMap, IdentityHashMap> next = full ? new IdentityHashMap<>() : new IdentityHashMap<>(policies); IdentityHashMap regions = full || current == null ? new IdentityHashMap<>() : new IdentityHashMap<>(current); regions.put(region, resolved); - next.put(biome, regions); + next.put(lineage, regions); policyCount = full ? 1 : policyCount + 1; policies = next; return resolved; } } - private Policy resolve(IrisBiome biome, IrisRegion region) { - Integer width = IrisHydrologyPolicy.inherited(biome, region, dimension, IrisHydrologyPolicy::getShoreBiomeWidth); - List keys = IrisHydrologyPolicy.inherited(biome, region, dimension, IrisHydrologyPolicy::getShoreBiomes); - if (width == null || width <= 0 || keys == null || keys.isEmpty()) { + private Policy resolve(List lineage, IrisRegion region) { + IrisHydrologyPolicy.ShoreBand band = IrisHydrologyPolicy.shoreBand(lineage, region, dimension); + if (band == null) { return NONE; } + List keys = band.biomes(); IrisBiome[] biomes = new IrisBiome[keys.size()]; for (int index = 0; index < biomes.length; index++) { - biomes[index] = load(keys.get(index), biome, region).withInferredType(InferredType.SHORE); + biomes[index] = load(keys.get(index), lineage, region).withInferredType(InferredType.SHORE); } - return new Policy(biomes, width); + return new Policy(biomes, band.width()); } - private IrisBiome load(String key, IrisBiome biome, IrisRegion region) { + private IrisBiome load(String key, List lineage, IrisRegion region) { IrisBiome loaded = key == null || key.isBlank() || data == null ? null : data.getBiomeLoader().load(key); if (loaded == null) { - throw new IllegalStateException("Hydrology shore biome '" + key + "' for biome " + (biome == null ? "none" : biome.getLoadKey()) - + " in region " + (region == null ? "none" : region.getLoadKey()) + " does not exist"); + throw new IllegalStateException("Hydrology shore biome '" + key + "' listed by " + listedBy(lineage, region) + " for biome " + + (lineage.isEmpty() ? "none" : lineage.getFirst().getLoadKey()) + " in region " + (region == null ? "none" : region.getLoadKey()) + + " does not exist"); } return loaded; } + private String listedBy(List lineage, IrisRegion region) { + for (IrisBiome biome : lineage) { + if (lists(biome.getHydrologyPolicy())) { + return "biome " + biome.getLoadKey(); + } + } + return region != null && lists(region.getHydrologyPolicy()) ? "region " + region.getLoadKey() : "dimension " + dimension.getLoadKey(); + } + + private static boolean lists(IrisHydrologyPolicy policy) { + return policy != null && policy.getShoreBiomes() != null; + } + + private static boolean banded(IrisHydrologyPolicy policy) { + return policy != null && policy.getShoreBiomeWidth() != null && policy.getShoreBiomeWidth() > 0; + } + private record Policy(IrisBiome[] biomes, int width) { } } diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/HydrologyVegetationSource.java b/core/src/main/java/art/arcane/iris/generation/runtime/HydrologyVegetationSource.java index c3e960608..19d74a684 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/HydrologyVegetationSource.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/HydrologyVegetationSource.java @@ -26,7 +26,7 @@ final class HydrologyVegetationSource { private final Object lock = new Object(); private boolean planted; private volatile IdentityHashMap, HydrologyVegetation.Decorators> compiled = new IdentityHashMap<>(); - private volatile IdentityHashMap> overrides = new IdentityHashMap<>(); + private volatile IdentityHashMap, IdentityHashMap> overrides = new IdentityHashMap<>(); private HydrologyVegetationSource(IrisData data, IrisDimension dimension, Map tiers, HydrologyVegetation.Decorators ponds) { @@ -62,11 +62,11 @@ final class HydrologyVegetationSource { return planted; } - HydrologyVegetation.Decorators decorators(HydrologyTier tier, IrisBiome biome, IrisRegion region) { + HydrologyVegetation.Decorators decorators(HydrologyTier tier, List lineage, IrisRegion region) { if (data == null) { return HydrologyVegetation.Decorators.EMPTY; } - Resolved override = override(biome, region); + Resolved override = override(lineage, region); if (override.decorators() != null) { return override.decorators(); } @@ -80,28 +80,28 @@ final class HydrologyVegetationSource { return known; } - private Resolved override(IrisBiome biome, IrisRegion region) { - IdentityHashMap regions = overrides.get(biome); + private Resolved override(List lineage, IrisRegion region) { + IdentityHashMap regions = overrides.get(lineage); Resolved known = regions == null ? null : regions.get(region); - return known != null ? known : remember(biome, region, resolve(biome, region)); + return known != null ? known : remember(lineage, region, resolve(lineage, region)); } - private Resolved resolve(IrisBiome biome, IrisRegion region) { - List decorators = IrisHydrologyPolicy.inherited(biome, region, dimension, IrisHydrologyPolicy::getDecorators); + private Resolved resolve(List lineage, IrisRegion region) { + List decorators = IrisHydrologyPolicy.inherited(lineage, region, dimension, IrisHydrologyPolicy::getDecorators); return decorators == null ? Resolved.INHERIT : new Resolved(compiled(decorators, LAZY_POLICY)); } - private Resolved remember(IrisBiome biome, IrisRegion region, Resolved resolved) { + private Resolved remember(List lineage, IrisRegion region, Resolved resolved) { synchronized (lock) { - IdentityHashMap current = overrides.get(biome); + IdentityHashMap current = overrides.get(lineage); Resolved raced = current == null ? null : current.get(region); if (raced != null) { return raced; } - IdentityHashMap> next = new IdentityHashMap<>(overrides); + IdentityHashMap, IdentityHashMap> next = new IdentityHashMap<>(overrides); IdentityHashMap regions = current == null ? new IdentityHashMap<>() : new IdentityHashMap<>(current); regions.put(region, resolved); - next.put(biome, regions); + next.put(lineage, regions); overrides = next; return resolved; } diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java b/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java index b63564d89..8441a3c44 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java @@ -121,8 +121,8 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiFunction; @Data -@EqualsAndHashCode(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks"}) -@ToString(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks"}) +@EqualsAndHashCode(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks", "biomeLineages"}) +@ToString(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks", "biomeLineages"}) public class IrisComplex implements DataProvider { private static final NoiseBounds ZERO_NOISE_BOUNDS = new NoiseBounds(0D, 0D); private static final long NEGATIVE_ZERO_BITS = Double.doubleToRawLongBits(-0D); @@ -277,6 +277,12 @@ public class IrisComplex implements DataProvider { @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private final transient HydrologyShoreBiomes shoreBiomes; + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) + private final transient BiomeLineages biomeLineages; + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) + private final transient boolean shoreBands; @Setter(AccessLevel.NONE) private final transient SubterrainPlanner subterrainPlanner; private transient IrisImageMapRuntime imageMapRuntime; @@ -494,11 +500,15 @@ public class IrisComplex implements DataProvider { Interpolated.of(value -> 0D, value -> null)); naturalTrueBiomeStream = new BakedStream<>(bakeCache, BakePlane.NATURAL_TRUE_BIOME, naturalTrueBiomeSource); shoreBiomes = new HydrologyShoreBiomes(engine.getDimension(), data, engine.getSeedManager().getBodies()); + biomeLineages = BiomeLineages.compile(focusedBiomes == null ? baseCapableBiomes(preparedRegions) : List.of(), this); hydrologyRuntime = HydrologyRuntime.create(engine, this); waterFluidStreams = hydrologyRuntime.enabled() ? createWaterFluidStreams(hydrologyRuntime.settings().fluids(), hydrologyRuntime.settings().seams().values()) : Map.of(); pondMaterials = hydrologyRuntime.enabled() ? hydrologyRuntime.settings().ponds().materials() : null; + KList policyRegions = hydrologyRuntime.enabled() ? engine.getDimension().getAllRegions(engine) : new KList<>(); + KList policyBiomes = hydrologyRuntime.enabled() ? engine.getDimension().getReachableBiomes(engine) : new KList<>(); waterVegetation = hydrologyRuntime.enabled() ? HydrologyVegetationSource.create(engine.getDimension(), hydrologyRuntime.settings(), data, - engine.getDimension().getAllRegions(engine), engine.getDimension().getReachableBiomes(engine)) : HydrologyVegetationSource.NONE; + policyRegions, policyBiomes) : HydrologyVegetationSource.NONE; + shoreBands = hydrologyRuntime.enabled() && HydrologyShoreBiomes.banded(engine.getDimension(), policyRegions, policyBiomes); heightStream = new BakedHeightStream(bakeCache, () -> terrainEngine.getPlatformHooks().isMainThread(), this::resolveHydrologyTerrainHeight, this::resolveHydrologyTerrainHeight); roundedHeighteightStream = GenerationStreams.contextInjecting(heightStream, engine, (c, x, z) -> c.getHeight().getDouble(x, z)) @@ -1400,7 +1410,16 @@ public class IrisComplex implements DataProvider { return HydrologyVegetation.Decorators.EMPTY; } HydrologyTier tier = chunkRasterAt(x, z).tier(x & 15, z & 15); - return waterVegetation.decorators(tier, baseBiomeStream.get(x, z), regionStream.get(x, z)); + return waterVegetation.decorators(tier, baseBiomeLineage(x, z), regionStream.get(x, z)); + } + + public List baseBiomeLineage(int x, int z) { + IrisBiome biome = baseBiomeStream.get(x, z); + if (!biomeLineages.inherits(biome) + || imageMapRuntime.has(IrisImageMapApplication.BIOME) && imageMapRuntime.sampleBiome(x, z) != null) { + return biomeLineages.root(biome); + } + return childLineage(biome, x, z); } private ChunkWaterRaster chunkRasterAt(int blockX, int blockZ) { @@ -1809,7 +1828,10 @@ public class IrisComplex implements DataProvider { || seamWeight(blockX, blockZ) == 0D) { return null; } - IrisBiome shore = shoreBiomes.select(baseBiomeStream.get(x, z), regionStream.get(x, z), blockX, blockZ, distance); + if (!shoreBands) { + return null; + } + IrisBiome shore = shoreBiomes.select(baseBiomeLineage(blockX, blockZ), regionStream.get(x, z), blockX, blockZ, distance); return shore == null ? null : implode(shore, x, z); } @@ -2485,7 +2507,7 @@ public class IrisComplex implements DataProvider { return b; } - return implode(b, x, z, 3); + return implode(b, x, z, IrisBiome.CHILD_HOPS - 1); } private IrisBiome implode(IrisBiome b, double x, double z, int max) { @@ -2497,15 +2519,42 @@ public class IrisComplex implements DataProvider { return b; } - CNG childCell = b.getChildrenGenerator(childStyleSeed, b.getChildShrinkFactor()); - ChildSelectionPlan childSelectionPlan = resolveChildSelectionPlan(b); - IrisBiome biome = childSelectionPlan.select(childCell, x, z).withInferredType(b.getInferredType()); + IrisBiome biome = pickChild(b, x, z); if (biome == b && hasFixedNoise(b.getChildStyle())) { return biome; } return implode(biome, x, z, max - 1); } + private IrisBiome pickChild(IrisBiome parent, double x, double z) { + CNG childCell = parent.getChildrenGenerator(childStyleSeed, parent.getChildShrinkFactor()); + return resolveChildSelectionPlan(parent).select(childCell, x, z).withInferredType(parent.getInferredType()); + } + + private List childLineage(IrisBiome biome, int x, int z) { + IrisBiome[] rootFirst = new IrisBiome[IrisBiome.CHILD_HOPS + 1]; + IrisBiome current = inferredByType.get(bridgeStream.get(x, z)).get(x, z); + rootFirst[0] = current; + int size = 1; + for (int hop = 0; hop < IrisBiome.CHILD_HOPS && !current.getChildren().isEmpty(); hop++) { + IrisBiome picked = pickChild(current, x, z); + if (picked == current) { + break; + } + rootFirst[size++] = picked; + current = picked; + } + if (current != biome) { + throw new IllegalStateException("The child chain at " + x + "," + z + " ends at biome " + current.getLoadKey() + + ", but the base biome there is " + biome.getLoadKey()); + } + IrisBiome[] leafFirst = new IrisBiome[size]; + for (int index = 0; index < size; index++) { + leafFirst[index] = rootFirst[size - 1 - index]; + } + return biomeLineages.chain(leafFirst); + } + static boolean hasFixedNaturalBiomeNoise(IrisDimension dimension, Iterable biomes) { if (!hasFixedNoise(dimension.getRegionStyle()) || !hasFixedNoise(dimension.getContinentalStyle()) || !hasFixedNoise(dimension.getLandBiomeStyle()) || !hasFixedNoise(dimension.getSeaBiomeStyle())) { diff --git a/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveModifier.java b/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveModifier.java index dc69b9b06..5f7a0e61d 100644 --- a/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveModifier.java +++ b/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveModifier.java @@ -34,6 +34,7 @@ import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.volmlib.util.stream.ProceduralStream; import art.arcane.iris.generation.runtime.EngineAssignedModifier; +import art.arcane.iris.generation.mantle.CarveOwnership; import art.arcane.iris.generation.mantle.CaveCeilingMask; import art.arcane.iris.generation.mantle.CaveTerrainSnapshot; import art.arcane.iris.generation.mantle.TerrainMatterView; @@ -163,7 +164,8 @@ public class IrisCarveModifier extends EngineAssignedModifier getEngine().getWorld().minHeight(), resolverState.complex, subterrainPlanner == null ? null : subterrainPlanner.chunkSampler(x, z), - subterrain ? caveCeilings(resolverState.complex, x, z) : null + subterrain ? caveCeilings(resolverState.complex, x, z) : null, + subterrain ? inletHeadroom(resolverState.complex, x, z) : null ); CarveResolver carveResolver = new CarveResolver(resolutionContext); terrain.forEachCell(carveResolver::apply); @@ -261,17 +263,18 @@ public class IrisCarveModifier extends EngineAssignedModifier int minimumY = getEngine().getWorld().minHeight(); SubterrainSurfaceMaterials materials = subterrainMaterials(planner, blockX >> 4, blockZ >> 4); int[] caveCeilings = caveCeilings(getComplex(), blockX >> 4, blockZ >> 4); + long[] inletHeadroom = inletHeadroom(getComplex(), blockX >> 4, blockZ >> 4); MantleChunk chunk = getEngine().getMantle().getMantle().useChunk(blockX >> 4, blockZ >> 4); try { - preserveSubterrain(planner, materials, caveCeilings, minimumY, blockX, blockZ, output, + preserveSubterrain(planner, materials, caveCeilings, inletHeadroom, minimumY, blockX, blockZ, output, (worldX, y, worldZ) -> HydrologyCaveStorage.getIfPresent(chunk, worldX, y, worldZ)); } finally { chunk.release(); } } - private void preserveSubterrain(SubterrainPlanner planner, SubterrainSurfaceMaterials materials, int[] caveCeilings, int minimumY, - int blockX, int blockZ, Hunk output, HydrologyCells hydrology) { + private void preserveSubterrain(SubterrainPlanner planner, SubterrainSurfaceMaterials materials, int[] caveCeilings, long[] inletHeadroom, + int minimumY, int blockX, int blockZ, Hunk output, HydrologyCells hydrology) { SubterrainRasterizer.rasterize(planner, blockX >> 4, blockZ >> 4, (worldX, worldY, worldZ, cell) -> { int y = worldY - minimumY; if (y <= 0 || y >= output.getHeight()) { @@ -279,7 +282,7 @@ public class IrisCarveModifier extends EngineAssignedModifier } int x = worldX & 15; int z = worldZ & 15; - if (!cell.solid() && caveCeilings != null && y > caveCeilings[PowerOfTwoCoordinates.packLocal16(x, z)]) { + if (!cell.solid() && CaveCeilingMask.masked(caveCeilings, inletHeadroom, PowerOfTwoCoordinates.packLocal16(x, z), y)) { return; } if (hydrology.at(worldX, y, worldZ) != null) { @@ -307,6 +310,10 @@ public class IrisCarveModifier extends EngineAssignedModifier new int[CaveCeilingMask.FIELD * CaveCeilingMask.FIELD], ceilings) ? ceilings : null; } + private static long[] inletHeadroom(IrisComplex complex, int chunkX, int chunkZ) { + return CaveCeilingMask.headroom(chunkX, chunkZ, complex.getHydrologyRuntime(), new long[256]); + } + private void restoreSubterrainSolids(Hunk output, int chunkX, int chunkZ, boolean preserveFloorSupports, HydrologyCells hydrology) { SubterrainPlanner planner = getComplex().getSubterrainPlanner(); @@ -379,8 +386,12 @@ public class IrisCarveModifier extends EngineAssignedModifier return cavern.getLiquid() == 3 ? air : null; } - static boolean subterrainOwns(SubterrainCell feature, HydrologyCaveCell hydrology) { - return hydrology == null && feature.owned() && (!feature.solid() || feature.room().reservedSolid()); + static CarveOwnership.Owner carveOwner(HydrologyCaveCell hydrology, SubterrainCell feature, Terrain3DColumn naturalTerrain, int y) { + return CarveOwnership.resolve( + hydrology != null, + CarveOwnership.subterrainClaims(feature), + naturalTerrain != null && y >= naturalTerrain.minY() && y < naturalTerrain.topY() && !naturalTerrain.isSolid(y) + ); } static NativeBlockState sealGuardState(NativeBlockState current, NativeBlockState rock) { @@ -408,7 +419,6 @@ public class IrisCarveModifier extends EngineAssignedModifier } return switch (hydrology.action()) { case WET_SOURCE, POOL_SOURCE -> fluid; - case FALLING_FLUID -> fallingFluidState(fluid); case DRY_AIR -> air; case SEAL_GUARD -> normalizeWaterlogging(current, null); }; @@ -439,16 +449,6 @@ public class IrisCarveModifier extends EngineAssignedModifier return normalizeWaterlogging(state, resultingFluid); } - private static NativeBlockState fallingFluidState(NativeBlockState fluid) { - if (fluid == null || !IrisProceduralBlocks.hasProperty(fluid, "level")) { - return fluid; - } - if ("8".equals(IrisProceduralBlocks.propertyValue(fluid, "level"))) { - return fluid; - } - return fluid.withProperty("level", "8"); - } - private final class CarveResolver { private final CarveResolutionContext context; @@ -473,8 +473,10 @@ public class IrisCarveModifier extends EngineAssignedModifier SubterrainCell feature = context.subterrainSampler() == null ? SubterrainCell.OUTSIDE : context.subterrainSampler().sampleCandidates(context.chunkBlockX() + localX, y + context.minimumY(), context.chunkBlockZ() + localZ); - if (subterrainOwns(feature, hydrology)) { - if (!feature.solid() && context.caveCeilings() != null && y > context.caveCeilings()[columnIndex]) { + CarveOwnership.Owner owner = carveOwner(hydrology, feature, + context.terrainColumns() == null ? null : context.terrainColumns()[columnIndex], y); + if (owner == CarveOwnership.Owner.SUBTERRAIN) { + if (!feature.solid() && CaveCeilingMask.masked(context.caveCeilings(), context.inletHeadroom(), columnIndex, y)) { return; } context.output().setRaw(localX, y, localZ, SubterrainRasterizer.state(feature)); @@ -487,6 +489,14 @@ public class IrisCarveModifier extends EngineAssignedModifier return; } + if (hydrology != null && hydrology.action() == HydrologyCaveAction.SEAL_GUARD) { + NativeBlockState unsealed = context.output().getRaw(localX, y, localZ); + NativeBlockState sealed = sealGuardState(unsealed, context.chunkContext().getRock().get(localX, localZ)); + if (sealed != unsealed) { + context.output().setRaw(localX, y, localZ, sealed); + } + return; + } if (context.upperSurfaceHeights() != null && y >= context.upperSurfaceHeights()[columnIndex]) { return; } @@ -495,20 +505,10 @@ public class IrisCarveModifier extends EngineAssignedModifier return; } - NativeBlockState current = context.output().getRaw(localX, y, localZ); - if (hydrology == null && context.terrainColumns() != null) { - Terrain3DColumn column = context.terrainColumns()[columnIndex]; - if (column != null && y >= column.minY() && y < column.topY() && !column.isSolid(y)) { - return; - } - } - if (hydrology != null && hydrology.action() == HydrologyCaveAction.SEAL_GUARD) { - NativeBlockState sealed = sealGuardState(current, context.chunkContext().getRock().get(localX, localZ)); - if (sealed != current) { - context.output().setRaw(localX, y, localZ, sealed); - } + if (owner == CarveOwnership.Owner.NATURAL_OPENING) { return; } + NativeBlockState current = context.output().getRaw(localX, y, localZ); MatterCavern cavern = composeCavern(baseline, hydrology); if (cavern == null || shouldPreserveExistingFluid(cavern, current)) { @@ -566,7 +566,8 @@ public class IrisCarveModifier extends EngineAssignedModifier int minimumY, IrisComplex complex, SubterrainPlanner.ChunkSampler subterrainSampler, - int[] caveCeilings + int[] caveCeilings, + long[] inletHeadroom ) { } @@ -631,7 +632,7 @@ public class IrisCarveModifier extends EngineAssignedModifier HydrologyCaveCell hydrology = terrain.hydrology(rx, yy, rz); int worldX = rx + chunkBlockX; int worldZ = rz + chunkBlockZ; - if (hydrology != null && hydrology.protectsPlacement() || inputs.cells.cell(worldX, yy, worldZ).owned() + if (hydrology != null || inputs.cells.cell(worldX, yy, worldZ).owned() || yy >= surfaceHeights[PowerOfTwoCoordinates.packLocal16(rx, rz)] || !B.isSolid(output.getRaw(rx, yy, rz))) { return; } @@ -880,9 +881,7 @@ public class IrisCarveModifier extends EngineAssignedModifier break; } HydrologyCaveCell hydrology = terrain.hydrology(rx, floorY, rz); - if (hydrology != null - && hydrology.protectsPlacement() - && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) { + if (hydrology != null && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) { continue; } NativeBlockState existing = output.getRaw(rx, floorY, rz); @@ -910,9 +909,7 @@ public class IrisCarveModifier extends EngineAssignedModifier break; } HydrologyCaveCell hydrology = terrain.hydrology(rx, ceilingY, rz); - if (hydrology != null - && hydrology.protectsPlacement() - && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) { + if (hydrology != null && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) { continue; } NativeBlockState existing = output.getRaw(rx, ceilingY, rz); @@ -976,9 +973,7 @@ public class IrisCarveModifier extends EngineAssignedModifier } int y = zone.floor - i - 1; HydrologyCaveCell hydrology = terrain.hydrology(rx, y, rz); - if (hydrology != null - && hydrology.protectsPlacement() - && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) { + if (hydrology != null && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) { continue; } NativeBlockState block = resolveSubmergedCaveFloorLayer( @@ -1005,9 +1000,7 @@ public class IrisCarveModifier extends EngineAssignedModifier break; } HydrologyCaveCell hydrology = terrain.hydrology(rx, cy, rz); - if (hydrology != null - && hydrology.protectsPlacement() - && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) { + if (hydrology != null && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) { continue; } NativeBlockState block = ceilingBlocks.get(i); @@ -1184,11 +1177,9 @@ public class IrisCarveModifier extends EngineAssignedModifier } MatterCavern baseline = terrain.cavern(localX, y, localZ); NativeBlockState current = output.getRaw(localX, y, localZ); - NativeBlockState columnFluid = getComplex().resolveCaveCellFluid( - hydrology.fluidProfileKey(), - worldX, - worldZ - ); + NativeBlockState columnFluid = hydrology.isWet() + ? getComplex().resolveCaveCellFluid(hydrology.fluidProfileKey(), worldX, worldZ) + : null; NativeBlockState normalized = normalizeHydrologyWaterlogging( current, baseline, diff --git a/core/src/main/java/art/arcane/iris/generation/stage/IrisDepositModifier.java b/core/src/main/java/art/arcane/iris/generation/stage/IrisDepositModifier.java index 7382bd91a..ca364ef6f 100644 --- a/core/src/main/java/art/arcane/iris/generation/stage/IrisDepositModifier.java +++ b/core/src/main/java/art/arcane/iris/generation/stage/IrisDepositModifier.java @@ -441,8 +441,7 @@ public class IrisDepositModifier extends EngineAssignedModifier { if (mantle == null) { return false; } - HydrologyCaveCell cell = HydrologyCaveStorage.getIfPresent(mantle.getMantle(), x, y, z); - return cell != null && cell.protectsPlacement(); + return HydrologyCaveStorage.getIfPresent(mantle.getMantle(), x, y, z) != null; } public void setPostBlock(int x, int y, int z, NativeBlockState d, int originX, int originZ, Hunk currentData) { diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java index f32237b88..27c89264a 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java @@ -113,6 +113,7 @@ import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; @@ -581,12 +582,12 @@ public class IrisDimension extends IrisRegistrant { String biomeKey = Objects.requireNonNull(biome, "focus biome").getLoadKey(); KList available = getAllRegions(provider); for (IrisRegion region : available) { - if (region.getAllBiomeIds().contains(biomeKey)) { + if (region.getAllBiomeIds(this, provider).contains(biomeKey)) { return region; } } for (IrisRegion region : available) { - for (IrisBiome member : region.getAllBiomes(provider)) { + for (IrisBiome member : region.getAllBiomes(this, provider)) { if (biomeKey.equals(member.getLoadKey())) { return region; } @@ -697,29 +698,15 @@ public class IrisDimension extends IrisRegistrant { Deque pending = new ArrayDeque<>(); addReachableBiomeKey(pending, getFocus()); - boolean hydrologyPoliciesActive = hydrology != null && hydrology.isEnabled(); - if (hydrologyPoliciesActive && hydrologyPolicy != null) { - addReachableBiomeKeys(pending, hydrologyPolicy.getShoreBiomes()); - } - for (IrisRegion region : getAllRegions(g)) { + KList regions = getAllRegions(g); + for (IrisRegion region : regions) { if (region == null) { continue; } - addReachableBiomeKeys(pending, - hydrologyPoliciesActive ? region.getAllBiomeIds() : region.getNaturalBiomeIds()); - } - for (IrisImageMapBinding binding : getImageMaps()) { - if (binding == null || binding.getApplication() != IrisImageMapApplication.BIOME) { - continue; - } - IrisImageMap map = data.getImageMapLoader().load(binding.getMap()); - if (map == null) { - continue; - } - for (String target : imageMapTargets(map)) { - addReachableBiomeKey(pending, localImageMapTarget(target)); - } + addReachableBiomeKeys(pending, region.getNaturalBiomeIds()); } + addReachableBiomeKeys(pending, ShoreBiomeLineages.placed(this, regions, g)); + addReachableBiomeKeys(pending, getImageMapBiomeKeys(g)); KList carvingEntries = getCarving(); if (carvingEntries != null) { @@ -763,9 +750,6 @@ public class IrisDimension extends IrisRegistrant { biomes.put(loadKey, biome); addReachableBiomeKeys(pending, biome.getChildren()); addReachableBiomeKey(pending, biome.getCarvingBiome()); - if (hydrologyPoliciesActive && biome.getHydrologyPolicy() != null) { - addReachableBiomeKeys(pending, biome.getHydrologyPolicy().getShoreBiomes()); - } KList floatingChildren = biome.getFloatingChildBiomes(); if (floatingChildren == null) { @@ -785,6 +769,50 @@ public class IrisDimension extends IrisRegistrant { return biomes.v(); } + public KList getReachableCaveBiomes(DataProvider g) { + IrisData data = g == null ? null : g.getData(); + if (data == null || data.getBiomeLoader() == null) { + return new KList<>(); + } + Map biomes = new LinkedHashMap<>(); + for (IrisRegion region : getAllRegions(g)) { + for (IrisBiome biome : region.getRealCaveBiomes(g)) { + biomes.putIfAbsent(biome.getLoadKey(), biome); + } + } + KList carvingEntries = getCarving(); + if (carvingEntries != null) { + for (IrisDimensionCarvingEntry entry : carvingEntries) { + IrisBiome biome = entry == null || !entry.isEnabled() ? null : entry.getRealBiome(data); + if (biome != null) { + biomes.putIfAbsent(biome.getLoadKey(), biome); + } + } + } + return new KList<>(biomes.values()); + } + + public Set getImageMapBiomeKeys(DataProvider g) { + Set keys = new LinkedHashSet<>(); + IrisData data = g == null ? null : g.getData(); + if (data == null) { + return keys; + } + for (IrisImageMapBinding binding : getImageMaps()) { + if (binding == null || binding.getApplication() != IrisImageMapApplication.BIOME) { + continue; + } + IrisImageMap map = data.getImageMapLoader().load(binding.getMap()); + if (map == null) { + continue; + } + for (String target : imageMapTargets(map)) { + keys.add(localImageMapTarget(target)); + } + } + return keys; + } + private Set imageMapTargets(IrisImageMap map) { Set targets = new LinkedHashSet<>(); if (map.getColors() != null) { diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java index 988eb71d2..8d4e565c9 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java @@ -297,11 +297,9 @@ public class IrisRegion extends IrisRegistrant implements Rarity { return getShoreHeightGenerator().fitDouble(shoreHeightMin, shoreHeightMax, x / shoreHeightZoom, z / shoreHeightZoom); } - public KSet getAllBiomeIds() { + public KSet getAllBiomeIds(IrisDimension dimension, DataProvider g) { KSet names = getNaturalBiomeIds(); - if (hydrologyPolicy != null && hydrologyPolicy.getShoreBiomes() != null) { - names.addAll(hydrologyPolicy.getShoreBiomes()); - } + names.addAll(ShoreBiomeLineages.placedIn(dimension, this, g)); return names; } @@ -314,15 +312,15 @@ public class IrisRegion extends IrisRegistrant implements Rarity { return names; } - public KList getAllBiomes(DataProvider g) { - return resolveBiomes(g, getAllBiomeIds(), true); + public KList getAllBiomes(IrisDimension dimension, DataProvider g) { + return resolveBiomes(g, getAllBiomeIds(dimension, g)); } public KList getNaturalBiomes(DataProvider g) { - return resolveBiomes(g, getNaturalBiomeIds(), false); + return resolveBiomes(g, getNaturalBiomeIds()); } - private KList resolveBiomes(DataProvider g, KSet biomeIds, boolean includeShoreBiomes) { + private KList resolveBiomes(DataProvider g, KSet biomeIds) { KMap b = new KMap<>(); KSet names = biomeIds.copy(); @@ -348,9 +346,6 @@ public class IrisRegion extends IrisRegistrant implements Rarity { names.add(biome.getCarvingBiome()); b.put(biome.getLoadKey(), biome); names.addAll(biome.getChildren()); - if (includeShoreBiomes && biome.getHydrologyPolicy() != null && biome.getHydrologyPolicy().getShoreBiomes() != null) { - names.addAll(biome.getHydrologyPolicy().getShoreBiomes()); - } } } @@ -428,7 +423,7 @@ public class IrisRegion extends IrisRegistrant implements Rarity { public Color getColor(DataProvider dataProvider, RenderType type) { return this.cacheColor.aquire(() -> { if (this.color == null) { - Random rand = new Random(getName().hashCode() + getAllBiomeIds().hashCode()); + Random rand = new Random(getName().hashCode() + getNaturalBiomeIds().hashCode()); RandomColor randomColor = new RandomColor(rand); KList biomes = getRealLandBiomes(dataProvider); diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/ShoreBiomeLineages.java b/core/src/main/java/art/arcane/iris/generation/terrain/ShoreBiomeLineages.java new file mode 100644 index 000000000..c0db210ab --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/terrain/ShoreBiomeLineages.java @@ -0,0 +1,119 @@ +package art.arcane.iris.generation.terrain; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.block.DataProvider; +import art.arcane.iris.generation.hydrology.config.IrisHydrology; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.volmlib.util.collection.KSet; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.BiConsumer; + +public final class ShoreBiomeLineages { + private ShoreBiomeLineages() { + } + + public static KSet placed(IrisDimension dimension, Collection regions, DataProvider provider) { + KSet keys = new KSet<>(); + if (enabled(dimension)) { + visit(dimension, regions, provider, (lineage, region) -> addPlaced(keys, lineage, region, dimension)); + } + return keys; + } + + static KSet placedIn(IrisDimension dimension, IrisRegion region, DataProvider provider) { + KSet keys = new KSet<>(); + IrisData data = provider == null ? null : provider.getData(); + if (enabled(dimension) && data != null && data.getBiomeLoader() != null) { + visitRegion(region, data, (lineage, area) -> addPlaced(keys, lineage, area, dimension)); + } + return keys; + } + + public static void visit(IrisDimension dimension, Collection regions, DataProvider provider, + BiConsumer, IrisRegion> visitor) { + IrisData data = provider == null ? null : provider.getData(); + if (data == null || data.getBiomeLoader() == null) { + return; + } + for (IrisRegion region : regions) { + if (region != null) { + visitRegion(region, data, visitor); + } + } + List direct = new ArrayList<>(); + for (String key : dimension.getImageMapBiomeKeys(provider)) { + addLoaded(direct, data, key); + } + addLoaded(direct, data, dimension.getFocus()); + for (IrisBiome biome : direct) { + List lineage = List.of(biome); + for (IrisRegion region : regions) { + if (region != null) { + visitor.accept(lineage, region); + } + } + visitor.accept(lineage, null); + } + } + + private static boolean enabled(IrisDimension dimension) { + IrisHydrology hydrology = dimension.getHydrology(); + return hydrology != null && hydrology.isEnabled(); + } + + private static void visitRegion(IrisRegion region, IrisData data, BiConsumer, IrisRegion> visitor) { + List roots = new ArrayList<>(); + for (String key : region.getLandBiomes()) { + addLoaded(roots, data, key); + } + for (String key : region.getSeaBiomes()) { + addLoaded(roots, data, key); + } + ArrayDeque chain = new ArrayDeque<>(); + for (IrisBiome root : roots) { + descend(root, chain, region, data, visitor); + } + } + + private static void descend(IrisBiome biome, ArrayDeque chain, IrisRegion region, IrisData data, + BiConsumer, IrisRegion> visitor) { + chain.addFirst(biome); + visitor.accept(List.copyOf(chain), region); + if (chain.size() <= IrisBiome.CHILD_HOPS) { + List children = new ArrayList<>(); + for (String key : biome.getChildren()) { + addLoaded(children, data, key); + } + for (IrisBiome child : children) { + if (child != biome) { + descend(child, chain, region, data, visitor); + } + } + } + chain.removeFirst(); + } + + private static void addLoaded(List biomes, IrisData data, String key) { + IrisBiome biome = key == null || key.isBlank() ? null : data.getBiomeLoader().load(key); + if (biome != null && !biome.isCompatExcluded()) { + biomes.add(biome); + } + } + + private static void addPlaced(KSet keys, List lineage, IrisRegion region, IrisDimension dimension) { + IrisHydrologyPolicy.ShoreBand band = IrisHydrologyPolicy.shoreBand(lineage, region, dimension); + if (band == null) { + return; + } + for (String key : band.biomes()) { + if (key != null && !key.isBlank()) { + keys.add(key); + } + } + } +} 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 57e2fcbfb..e0a93d75b 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java @@ -5,21 +5,29 @@ import art.arcane.iris.generation.decoration.HydrologyVegetation; import art.arcane.iris.generation.decoration.IrisDecorator; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.generation.terrain.ShoreBiomeLineages; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; +import art.arcane.volmlib.util.mantle.flag.ReservedFlag; import java.io.File; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; +import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.TreeMap; final class PackHydrologyValidator { private static final String CONFIG = "hydrology"; @@ -38,31 +46,36 @@ final class PackHydrologyValidator { new RangeField("underground.cavePools.freeboard", Floor.NON_NEGATIVE, true) ); private static final List FLUID_REFERENCES = List.of("ponds.fluid", "underground.cavePools.fluid"); + private static final IrisHydrologyTier DEFAULT_TIER = new IrisHydrologyTier(); + private static final String MANTLE_WATER = "the falling water at waterfalls and cascades, sea inlets and cave pools"; private PackHydrologyValidator() { } static Validation validate(File packFolder, File[] dimensionFiles) { List errors = new ArrayList<>(); + List warnings = new ArrayList<>(); if (packFolder == null || !packFolder.isDirectory() || dimensionFiles == null) { - return new Validation(errors, List.of()); + return new Validation(errors, warnings); } List sortedDimensions = new ArrayList<>(List.of(dimensionFiles)); sortedDimensions.sort(Comparator.comparing(File::getPath)); File dimensionsFolder = new File(packFolder, PackValidator.DIMENSIONS_FOLDER); + Findings findings = new Findings(errors, warnings); IrisData data = null; try { for (File dimensionFile : sortedDimensions) { - data = validateDimension(packFolder, dimensionsFolder, dimensionFile, data, errors); + data = validateDimension(packFolder, dimensionsFolder, dimensionFile, data, findings); } } finally { close(packFolder, data, errors); } - return new Validation(errors, List.of()); + return new Validation(errors, warnings); } private static IrisData validateDimension(File packFolder, File dimensionsFolder, File dimensionFile, IrisData data, - List errors) { + Findings findings) { + List errors = findings.errors(); JSONObject dimension = PackValidationIo.readJson(dimensionFile); if (dimension == null || !dimension.has(CONFIG)) { return data; @@ -78,6 +91,7 @@ final class PackHydrologyValidator { } int reported = errors.size(); validateRanges(path, hydrology, errors); + warnPartialTiers(path, hydrology, findings.warnings()); Set fluids = fluidNames(hydrology); Set seams = seamNames(hydrology); validateFluidReferences(path, hydrology, fluids, errors); @@ -86,7 +100,9 @@ final class PackHydrologyValidator { if (loadedDimension == null) { return loaded; } + warnMantleOff("Dimension '" + dimensionKey + "'", loadedDimension, findings.warnings()); validatePolicies(path, dimensionKey, loaded, loadedDimension, new PolicyFluids(fluids, seams), errors); + warnShoreBiomesWithoutWidth(dimensionKey, loaded, loadedDimension, findings.warnings()); if (errors.size() == reported && validateCompile(path, loadedDimension, errors)) { validateDecoratorBlocks(path, loaded, loadedDimension.getHydrology(), errors); } @@ -149,6 +165,37 @@ final class PackHydrologyValidator { } } + private static void warnPartialTiers(String path, JSONObject hydrology, List warnings) { + JSONArray tiers = hydrology.optJSONArray("tiers"); + if (tiers == null) { + return; + } + for (int index = 0; index < tiers.length(); index++) { + JSONObject tier = tiers.optJSONObject(index); + if (tier == null) { + continue; + } + String field = path + ".tiers[" + index + "] ('" + tier.optString("name", DEFAULT_TIER.getName()) + "')"; + if (!tier.has("halfWidth")) { + warnings.add(field + " does not set halfWidth, so it takes the default " + DEFAULT_TIER.getHalfWidth() + "."); + } + if (!tier.has("bankBand")) { + warnings.add(field + " does not set bankBand, so it takes the default " + DEFAULT_TIER.getBankBand() + + " and leaves the ground beside its channels as it is."); + } + } + } + + private static void warnMantleOff(String path, IrisDimension dimension, List warnings) { + if (!dimension.isUseMantle()) { + warnings.add(path + " sets useMantle to false while hydrology is enabled, so " + MANTLE_WATER + " are not generated."); + } + if (dimension.getDisabledComponents() != null && dimension.getDisabledComponents().contains(ReservedFlag.RIVER_HYDROLOGY)) { + warnings.add(path + " disables the " + ReservedFlag.RIVER_HYDROLOGY + " component while hydrology is enabled, so " + MANTLE_WATER + + " are not generated."); + } + } + private static double[] range(String field, Object value, Floor floor, boolean whole, List errors) { if (!(value instanceof JSONArray pair) || pair.length() != 2 || !(pair.opt(0) instanceof Number first) || !(pair.opt(1) instanceof Number second)) { @@ -259,6 +306,58 @@ final class PackHydrologyValidator { if (policy.getDecorators() != null) { validateDecorators(field + ".decorators", policy.getDecorators(), data, errors); } + requireMultiplier(field + ".rainfall", policy.getRainfall(), errors); + requireMultiplier(field + ".pondDensity", policy.getPondDensity(), errors); + IrisHydrologyWetness wetness = policy.getWetness(); + if (wetness != null && !(wetness.getMin() >= 0D && wetness.getMin() <= wetness.getMax() && wetness.getMax() <= 1D)) { + errors.add(field + ".wetness must have 0 <= min <= max <= 1, got min " + wetness.getMin() + " and max " + wetness.getMax() + "."); + } + } + + private static void warnShoreBiomesWithoutWidth(String dimensionKey, IrisData data, IrisDimension dimension, List warnings) { + List regions = new ArrayList<>(dimension.getAllRegions(() -> data)); + regions.sort(Comparator.comparing(IrisRegion::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder()))); + Set widened = Collections.newSetFromMap(new IdentityHashMap<>()); + Map lineageBiomes = new TreeMap<>(); + ShoreBiomeLineages.visit(dimension, regions, () -> data, (lineage, region) -> { + Integer width = IrisHydrologyPolicy.inherited(lineage, region, dimension, IrisHydrologyPolicy::getShoreBiomeWidth); + boolean wide = width != null && width > 0; + for (IrisBiome biome : lineage) { + if (biome.getLoadKey() != null) { + lineageBiomes.putIfAbsent(biome.getLoadKey(), biome); + } + if (wide && biome.getHydrologyPolicy() != null) { + widened.add(biome.getHydrologyPolicy()); + } + } + if (wide && region != null && region.getHydrologyPolicy() != null) { + widened.add(region.getHydrologyPolicy()); + } + if (wide && dimension.getHydrologyPolicy() != null) { + widened.add(dimension.getHydrologyPolicy()); + } + }); + warnShoreBiomesWithoutWidth("Dimension '" + dimensionKey + "'", dimension.getHydrologyPolicy(), widened, warnings); + for (IrisRegion region : regions) { + warnShoreBiomesWithoutWidth("Region '" + region.getLoadKey() + "'", region.getHydrologyPolicy(), widened, warnings); + } + for (IrisBiome biome : lineageBiomes.values()) { + warnShoreBiomesWithoutWidth("Biome '" + biome.getLoadKey() + "'", biome.getHydrologyPolicy(), widened, warnings); + } + } + + private static void warnShoreBiomesWithoutWidth(String scope, IrisHydrologyPolicy policy, Set widened, + List warnings) { + if (policy != null && policy.getShoreBiomes() != null && !policy.getShoreBiomes().isEmpty() && !widened.contains(policy)) { + warnings.add(scope + "." + POLICY + ".shoreBiomes lists shore biomes, but no shoreBiomeWidth above 0 applies to them," + + " so none are placed."); + } + } + + private static void requireMultiplier(String field, Double value, List errors) { + if (value != null && !IrisHydrologyPolicy.validMultiplier(value)) { + errors.add(field + " must be a finite value from 0 to " + (int) IrisHydrologyPolicy.MAX_MULTIPLIER + ", got " + value + "."); + } } private static void close(File packFolder, IrisData data, List errors) { @@ -307,4 +406,7 @@ final class PackHydrologyValidator { private record PolicyFluids(Set defined, Set seams) { } + + private record Findings(List errors, List warnings) { + } } diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/DimensionStage.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/DimensionStage.java index 8cc5eb530..246464721 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/DimensionStage.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/DimensionStage.java @@ -34,7 +34,7 @@ public final class DimensionStage implements CompileStage { dimension.getLogicalHeight(), dimension.getFluidHeight() + minY, paletteBlock(dimension.getRockPalette(), DEFAULT_ROCK, "rock"), - paletteBlock(dimension.getFluidPalette(), DEFAULT_FLUID, "fluid"), + fluidBlock(dimension), new JsonObject(), context.diagnostics()); IrisDimensionType type = new IrisDimensionType( @@ -55,6 +55,17 @@ public final class DimensionStage implements CompileStage { typeJson)); } + public static String fluidBlock(IrisDimension dimension) { + return paletteBlock(dimension.getFluidPalette(), DEFAULT_FLUID, "fluid"); + } + + public static String blockId(String raw) { + String block = raw == null ? "" : raw.trim().toLowerCase(Locale.ROOT); + int properties = block.indexOf('['); + String id = properties < 0 ? block : block.substring(0, properties); + return id.indexOf(':') < 0 ? "minecraft:" + id : id; + } + private static IrisDimensionTypeOptions typeOptions(IrisDimension dimension) { IrisDimensionTypeOptions options = dimension.getDimensionOptions(); return dimension.isFullbright() ? options.copy().ambientLight(FULLBRIGHT_AMBIENT_LIGHT) : options; @@ -65,11 +76,6 @@ public final class DimensionStage implements CompileStage { if (entries == null || entries.isEmpty() || entries.getFirst() == null) { return fallback; } - String raw = entries.getFirst().getBlock(); - String block = raw == null ? "" : raw.trim().toLowerCase(Locale.ROOT); - int properties = block.indexOf('['); - String id = properties < 0 ? block : block.substring(0, properties); - String namespaced = id.indexOf(':') < 0 ? "minecraft:" + id : id; - return VanillaResourceIdentifier.requireIdentifier(namespaced, "dimension " + role + " block"); + return VanillaResourceIdentifier.requireIdentifier(blockId(entries.getFirst().getBlock()), "dimension " + role + " block"); } } diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/ExportedBiomes.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/ExportedBiomes.java index a3cafe046..7ca311e3e 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/ExportedBiomes.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/ExportedBiomes.java @@ -104,7 +104,7 @@ public final class ExportedBiomes { if (region == null) { continue; } - for (IrisBiome biome : region.getAllBiomes(() -> context.data())) { + for (IrisBiome biome : region.getAllBiomes(context.dimension(), () -> context.data())) { if (biome != null && biome.getLoadKey() != null) { regions.putIfAbsent(biome.getLoadKey(), region); } diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverCompiler.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverCompiler.java index 72184b77c..b18dcae36 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverCompiler.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverCompiler.java @@ -1,10 +1,12 @@ package art.arcane.iris.pack.datapack.export.compile.terrain; +import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.hydrology.config.IrisBankStyle; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry; import art.arcane.iris.pack.datapack.export.ir.CostClass; import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic; @@ -17,6 +19,7 @@ import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.function.Supplier; public final class RiverCompiler { public static final String CARVED_HEIGHT = "height/carved"; @@ -59,8 +62,9 @@ public final class RiverCompiler { this.diagnostics = Objects.requireNonNull(diagnostics, "diagnostics"); } - public Field compile(Field height, IrisDimension dimension, NoiseRegistry registry, ExportCapabilities capabilities) { + public Field compile(Field height, IrisDimension dimension, Supplier> areas, NoiseRegistry registry, ExportCapabilities capabilities) { Objects.requireNonNull(height, "height"); + Objects.requireNonNull(areas, "areas"); IrisHydrology hydrology = dimension.getHydrology(); if (hydrology == null || !hydrology.isEnabled()) { return height; @@ -73,6 +77,7 @@ public final class RiverCompiler { return height; } report(ExportLimit.RIVER_DRAINAGE, resource, "Rivers follow seeded noise channels instead of drainage: tributaries cross instead of joining and widths follow elevation"); + diagnostics.addAll(RiverLimits.diagnostics(dimension, settings, areas.get(), resource)); Field elevation = FieldMacros.sum(List.of(height, new Field.Const(-fluidHeight))); Carving carving = new Carving(elevation, variation(registry), bankNoise(settings.deformation(), registry), settings.deformation(), registry, capabilities); List tiers = settings.tiers(); @@ -287,6 +292,16 @@ public final class RiverCompiler { return new Field.Binary(Field.BinaryOp.MAX, first, second); } + public record Area(IrisRegion region, List biomes) { + public Area { + Objects.requireNonNull(region, "region"); + biomes = List.copyOf(biomes); + if (biomes.isEmpty()) { + throw new IllegalArgumentException("A river area in region " + region.getLoadKey() + " needs a biome"); + } + } + } + private record Carving(Field elevation, Field variation, Field bankNoise, HydrologySettings.Deformation deformation, NoiseRegistry registry, ExportCapabilities capabilities) { } 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 new file mode 100644 index 000000000..a8a7992e6 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverLimits.java @@ -0,0 +1,207 @@ +package art.arcane.iris.pack.datapack.export.compile.terrain; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.block.IrisBlockData; +import art.arcane.iris.generation.decoration.IrisDecorator; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyPermission; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness; +import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.hydrology.water.HydrologyTier; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisMaterialPalette; +import art.arcane.iris.pack.datapack.export.compile.DimensionStage; +import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic; +import art.arcane.iris.pack.datapack.export.ir.ExportLimit; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.function.Function; + +final class RiverLimits { + private static final double NEUTRAL_RAINFALL = 1.0; + private static final Comparator ORDER = Comparator.comparing(Finding::limit) + .thenComparingInt(finding -> finding.owner().rank()) + .thenComparing(finding -> finding.owner().resource()) + .thenComparing(Finding::subject); + + private final IrisDimension dimension; + private final HydrologySettings settings; + private final Owner hydrology; + private final Owner dimensionPolicy; + private final String exportFluid; + private final SortedMap findings = new TreeMap<>(ORDER); + + private RiverLimits(IrisDimension dimension, HydrologySettings settings, String resource) { + this.dimension = dimension; + this.settings = settings; + this.hydrology = new Owner(Owner.HYDROLOGY, resource); + this.dimensionPolicy = new Owner(Owner.DIMENSION, "dimensions/" + dimension.getLoadKey()); + this.exportFluid = DimensionStage.fluidBlock(dimension); + } + + static List diagnostics(IrisDimension dimension, HydrologySettings settings, List areas, String resource) { + RiverLimits limits = new RiverLimits(dimension, settings, resource); + for (RiverCompiler.Area area : areas) { + limits.inspect(area); + } + limits.inspectUnderground(); + List diagnostics = new ArrayList<>(limits.findings.size()); + for (Map.Entry entry : limits.findings.entrySet()) { + Finding finding = entry.getKey(); + diagnostics.add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, finding.limit(), finding.owner().resource(), entry.getValue())); + } + return diagnostics; + } + + private void inspect(RiverCompiler.Area area) { + inspectFluid(area); + inspectPolicy(area); + inspectClimate(area); + inspectShore(area); + inspectDecorators(area); + } + + private void inspectUnderground() { + if (settings.underground().seaInlets().enabled()) { + add(ExportLimit.SEA_INLET, hydrology, "", "Sea inlets are not exported: coastal cliffs have no flooded passages"); + } + 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"); + } + } + + private void inspectFluid(RiverCompiler.Area area) { + Sourced fluid = sourced(area, IrisHydrologyPolicy::getFluid); + if (fluid != null) { + settings.requireFillingFluid(fluid.value(), "the hydrology policy of " + fluid.owner().resource()); + fluid(fluid.owner(), fluid.value()); + return; + } + for (HydrologyTier tier : settings.tiers()) { + fluid(hydrology, tier.fluid()); + } + } + + private void inspectPolicy(RiverCompiler.Area area) { + Sourced rainfall = sourced(area, IrisHydrologyPolicy::getRainfall); + if (rainfall != null && rainfall.value() != NEUTRAL_RAINFALL) { + add(ExportLimit.RIVER_POLICY, rainfall.owner(), "rainfall", + "Hydrology policy rainfall is not exported: rivers form at the dimension density here"); + } + Sourced streams = sourced(area, IrisHydrologyPolicy::getStreams); + if (streams != null && streams.value() == IrisHydrologyPermission.BLOCK) { + add(ExportLimit.RIVER_POLICY, streams.owner(), "streams", + "Hydrology policy streams BLOCK is not exported: rivers start here as they do elsewhere"); + } + } + + private void inspectClimate(RiverCompiler.Area area) { + HydrologySettings.Climate climate = settings.climate(); + Sourced zones = sourced(area, IrisHydrologyPolicy::getClimateZones); + if (!climate.enabled() || zones != null && !zones.value()) { + return; + } + boolean zoned = climate.dryness() > 0.0F && climate.dryRainfall() < 1.0F; + if (zoned) { + add(ExportLimit.RIVER_CLIMATE, hydrology, "", "Wet and dry zones are not exported: rivers start in dry zones as they do in wet ones"); + } + Sourced wetness = sourced(area, IrisHydrologyPolicy::getWetness); + double driest = zoned ? climate.dryRainfall() : 1.0; + if (wetness != null && (wetness.value().getMin() > driest || wetness.value().getMax() < 1.0)) { + add(ExportLimit.RIVER_CLIMATE, wetness.owner(), "wetness", + "Hydrology policy wetness is not exported: rivers form at the dimension density here"); + } + } + + private void inspectShore(RiverCompiler.Area area) { + Sourced width = sourced(area, IrisHydrologyPolicy::getShoreBiomeWidth); + Sourced> biomes = sourced(area, IrisHydrologyPolicy::getShoreBiomes); + if (width == null || width.value() <= 0 || biomes == null || biomes.value().isEmpty()) { + return; + } + add(ExportLimit.RIVER_SHORE_BIOME, biomes.owner(), "", + "Hydrology shore biomes are not exported: the water's edge keeps the biome around it"); + } + + private void inspectDecorators(RiverCompiler.Area area) { + Sourced> decorators = sourced(area, IrisHydrologyPolicy::getDecorators); + if (decorators != null) { + if (!decorators.value().isEmpty()) { + decorators(decorators.owner()); + } + return; + } + for (HydrologyTier tier : settings.tiers()) { + if (tier.decorators() != null && !tier.decorators().isEmpty()) { + decorators(hydrology); + return; + } + } + } + + private void decorators(Owner owner) { + add(ExportLimit.RIVER_DECORATOR, owner, "", "Hydrology decorators are not exported: rivers grow no water plants of their own"); + } + + private void fluid(Owner owner, String name) { + String seam = settings.seams().get(name); + if (!exported(settings.fluids().get(name))) { + String subject = seam == null ? "Fluid '" + name + "' is" : "Fluid '" + name + "' and its seam '" + seam + "' are"; + add(ExportLimit.RIVER_FLUID, owner, name, subject + " not exported: rivers fill with " + exportFluid + " up to fluidHeight"); + return; + } + if (seam != null) { + add(ExportLimit.RIVER_FLUID, owner, name, "Seam '" + seam + "' of fluid '" + name + "' is not exported: rivers have no seam band at their edges"); + } + } + + private boolean exported(IrisMaterialPalette palette) { + for (IrisBlockData block : palette.getPalette()) { + if (!exportFluid.equals(DimensionStage.blockId(block.getBlock()))) { + return false; + } + } + return true; + } + + private void add(ExportLimit limit, Owner owner, String subject, String message) { + findings.putIfAbsent(new Finding(limit, owner, subject), message); + } + + private Sourced sourced(RiverCompiler.Area area, Function field) { + for (IrisBiome biome : area.biomes()) { + T value = value(biome.getHydrologyPolicy(), field); + if (value != null) { + return new Sourced<>(new Owner(Owner.BIOME, "biomes/" + biome.getLoadKey()), value); + } + } + T region = value(area.region().getHydrologyPolicy(), field); + if (region != null) { + return new Sourced<>(new Owner(Owner.REGION, "regions/" + area.region().getLoadKey()), region); + } + T inherited = value(dimension.getHydrologyPolicy(), field); + return inherited == null ? null : new Sourced<>(dimensionPolicy, inherited); + } + + private static T value(IrisHydrologyPolicy policy, Function field) { + return policy == null ? null : field.apply(policy); + } + + private record Owner(int rank, String resource) { + private static final int HYDROLOGY = 0; + private static final int DIMENSION = 1; + private static final int REGION = 2; + private static final int BIOME = 3; + } + + private record Finding(ExportLimit limit, Owner owner, String subject) { + } + + private record Sourced(Owner owner, T value) { + } +} diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverStage.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverStage.java index 8ee623905..8a104ebd3 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverStage.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverStage.java @@ -1,8 +1,20 @@ package art.arcane.iris.pack.datapack.export.compile.terrain; +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.pack.datapack.export.compile.CompileStage; import art.arcane.iris.pack.datapack.export.compile.PackCompileContext; import art.arcane.iris.pack.datapack.export.ir.Field; +import art.arcane.iris.pack.loading.IrisData; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; public final class RiverStage implements CompileStage { private static final String ESTIMATE_TAG = "estimate"; @@ -15,8 +27,68 @@ public final class RiverStage implements CompileStage { @Override public void apply(PackCompileContext context) { Field natural = context.naturalHeight(); - Field carved = new RiverCompiler(context.diagnostics()).compile(natural, context.dimension(), context.noises(), context.capabilities()); + Field carved = new RiverCompiler(context.diagnostics()).compile(natural, context.dimension(), () -> areas(context), context.noises(), context.capabilities()); context.setCarvedHeight(carved); context.setSurfaceEstimate(FieldMacros.substitute(carved, natural, context.climateHeight(), ESTIMATE_TAG)); } + + private static List areas(PackCompileContext context) { + IrisData data = context.data(); + Set exported = new HashSet<>(context.baseBiomeCodes().loadKeyByBiomeId().values()); + List regions = new ArrayList<>(); + for (IrisRegion region : data.getRegionLoader().loadAll(context.dimension().getRegions())) { + if (!region.isCompatExcluded()) { + regions.add(region); + } + } + regions.sort(Comparator.comparing(IrisRegion::getLoadKey)); + List areas = new ArrayList<>(); + for (IrisRegion region : regions) { + for (List lineage : lineages(region, data, exported)) { + areas.add(new RiverCompiler.Area(region, lineage)); + } + } + return areas; + } + + private static Collection> lineages(IrisRegion region, IrisData data, Set exported) { + List roots = new ArrayList<>(); + roots.addAll(region.getLandBiomes()); + roots.addAll(region.getSeaBiomes()); + roots.addAll(region.getShoreBiomes()); + SortedMap> lineages = new TreeMap<>(); + for (String key : roots) { + IrisBiome root = exportedBiome(key, data, exported); + if (root != null) { + addLineages(List.of(root), data, exported, lineages); + } + } + return lineages.values(); + } + + private static void addLineages(List leafFirst, IrisData data, Set exported, SortedMap> lineages) { + StringBuilder key = new StringBuilder(leafFirst.getFirst().getLoadKey()); + for (int index = 1; index < leafFirst.size(); index++) { + key.append('<').append(leafFirst.get(index).getLoadKey()); + } + if (lineages.putIfAbsent(key.toString(), leafFirst) != null || leafFirst.size() > IrisBiome.CHILD_HOPS) { + return; + } + IrisBiome leaf = leafFirst.getFirst(); + for (String childKey : leaf.getChildren()) { + IrisBiome child = exportedBiome(childKey, data, exported); + if (child == null || child.getLoadKey().equals(leaf.getLoadKey())) { + continue; + } + List lineage = new ArrayList<>(leafFirst.size() + 1); + lineage.add(child); + lineage.addAll(leafFirst); + addLineages(List.copyOf(lineage), data, exported, lineages); + } + } + + private static IrisBiome exportedBiome(String key, IrisData data, Set exported) { + IrisBiome biome = key == null ? null : data.getBiomeLoader().load(key); + return biome == null || biome.isCompatExcluded() || !exported.contains(biome.getLoadKey()) ? null : biome; + } } 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 67add04c6..eb3768d5d 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 @@ -31,6 +31,13 @@ public enum ExportLimit { OBJECT_BOUNDS, RIVER_DRAINAGE, ELEVATED_WATER, + RIVER_FLUID, + RIVER_POLICY, + RIVER_CLIMATE, + RIVER_SHORE_BIOME, + RIVER_DECORATOR, + SEA_INLET, + CAVE_POOL, DATAPACK_VERSION, DATAPACK_COLLISION, DATAPACK_FILE, diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicy.java b/core/src/main/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicy.java index e67cc4331..f07674803 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicy.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicy.java @@ -21,6 +21,7 @@ import art.arcane.volmlib.nativelib.terrain.structure.StructureLocateSearchAcces import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette; import art.arcane.volmlib.nativelib.terrain.structure.StructurePlacementDecision; import art.arcane.volmlib.nativelib.terrain.structure.StructureReferencePolicy; +import art.arcane.volmlib.nativelib.terrain.structure.StructureSeaSurface; import art.arcane.volmlib.nativelib.terrain.structure.StructureVolumePolicy; import art.arcane.volmlib.util.math.RNG; @@ -120,6 +121,11 @@ public final class BukkitStructureStagePolicy implements StructureStagePolicy< return (x, z) -> Engine.hostHeight(context, x, z, true) + context.getMinHeight(); } + @Override + public StructureSeaSurface seaSurface(Engine context) { + return GenerationWritePolicy.seaSurface(context); + } + @Override public IntBinaryOperator worldgenHeight(Engine context, int runtimeMinY, boolean floor) { return (x, z) -> Engine.hostHeight(context, x, z, floor) + runtimeMinY + 1; diff --git a/core/src/main/java/art/arcane/iris/structure/nativegen/GenerationWritePolicy.java b/core/src/main/java/art/arcane/iris/structure/nativegen/GenerationWritePolicy.java index 7c055204f..3dcabae23 100644 --- a/core/src/main/java/art/arcane/iris/structure/nativegen/GenerationWritePolicy.java +++ b/core/src/main/java/art/arcane/iris/structure/nativegen/GenerationWritePolicy.java @@ -4,9 +4,12 @@ import art.arcane.iris.generation.runtime.DimensionStackContext; import art.arcane.iris.generation.runtime.DimensionStackLayout; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisEngine; +import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter; import art.arcane.iris.structure.object.IrisStaticObjectLayer; import art.arcane.volmlib.nativelib.terrain.NativeBlockPositionPredicate; +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import art.arcane.volmlib.nativelib.terrain.structure.StructureSeaSurface; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -23,6 +26,20 @@ public final class GenerationWritePolicy { return router != null && activation < router.history().activeActivation().activationId(); } + public static StructureSeaSurface seaSurface(Engine engine) { + IrisDimension dimension = engine.getDimension(); + int fluidHeight = dimension.getFluidHeight(); + if (fluidHeight <= 0) { + return StructureSeaSurface.NONE; + } + for (NativeBlockState fluid : dimension.getFluidPalette().getBlockData(engine.getData())) { + if (fluid.isFluid()) { + return new StructureSeaSurface(engine.getMinHeight() + fluidHeight, fluid); + } + } + return StructureSeaSurface.NONE; + } + public static NativeBlockPositionPredicate protectedPositions( IrisStaticObjectLayer staticObjects, DimensionStackContext stackContext, diff --git a/core/src/main/java/art/arcane/iris/structure/nativegen/IrisVanillaStructureAdjustment.java b/core/src/main/java/art/arcane/iris/structure/nativegen/IrisVanillaStructureAdjustment.java index a529e75fd..cd2f9ff1a 100644 --- a/core/src/main/java/art/arcane/iris/structure/nativegen/IrisVanillaStructureAdjustment.java +++ b/core/src/main/java/art/arcane/iris/structure/nativegen/IrisVanillaStructureAdjustment.java @@ -58,7 +58,7 @@ public class IrisVanillaStructureAdjustment { @Description("Optional foundation columns placed beneath the native structure piece bases after placement.") private IrisStructureStiltSettings stilt = null; - @Description("Optional terrain integration override. FLATTEN cuts and fills exposed surface foundations within flattenRange, blending across horizontalPadding blocks while preserving buried and submerged structures. VACUUM raises processed rigid-template foundations with a fixed 12-block falloff without lowering ground. BORE and FORCE_CARVE clear every intersecting chunk before native placement, while ENCASE fills it. Left unset, SOURCE replays the registered structure's authored terrain adaptation.") + @Description("Optional terrain integration override. FLATTEN cuts and fills exposed surface foundations within flattenRange, blending across horizontalPadding blocks while preserving buried and submerged structures. It never lowers dry ground outside a structure footprint below the dimension fluidHeight. A cut beneath water or lava, such as a riverbed, fills with that fluid, and other cuts at or below fluidHeight fill with the dimension sea fluid instead of air. VACUUM raises processed rigid-template foundations with a fixed 12-block falloff without lowering ground. BORE and FORCE_CARVE clear every intersecting chunk before native placement, while ENCASE fills it. Left unset, SOURCE replays the registered structure's authored terrain adaptation.") private IrisStructureTerrain terrain = null; public boolean matches(String key) { diff --git a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureTerrain.java b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureTerrain.java index f828fb388..2f8e99290 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureTerrain.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureTerrain.java @@ -30,7 +30,7 @@ public class IrisStructureTerrain implements StructureTerrainSettings { private static final double MAX_EROSION_FREQUENCY = 1D; private static final double MAX_LOBE_FREQUENCY = 1D; - @Description("Terrain operation. SOURCE applies the registered native structure's authored terrain adaptation and is a no-op for editable Iris structures. PRESERVE disables terrain integration. FLATTEN cuts and fills exposed native structure terrain within flattenRange, blending across horizontalPadding blocks. VACUUM raises terrain from processed rigid-template foundations with a fixed 12-block falloff without lowering ground. BORE and FORCE_CARVE clear the requested envelope, while ENCASE fills it before placement.") + @Description("Terrain operation. SOURCE applies the registered native structure's authored terrain adaptation and is a no-op for editable Iris structures. PRESERVE disables terrain integration. FLATTEN cuts and fills exposed native structure terrain within flattenRange, blending across horizontalPadding blocks, and never lowers dry ground outside a structure footprint below the dimension fluidHeight. SOURCE and FLATTEN surface cuts beneath water or lava, such as a riverbed, fill with that fluid, and other cuts at or below fluidHeight fill with the dimension sea fluid instead of air. VACUUM raises terrain from processed rigid-template foundations with a fixed 12-block falloff without lowering ground. BORE and FORCE_CARVE clear the requested envelope, while ENCASE fills it before placement.") private StructureTerrainMode mode = StructureTerrainMode.SOURCE; @MinNumber(0) diff --git a/core/src/main/java/art/arcane/iris/structure/placement/StructureCaveAnchorResolver.java b/core/src/main/java/art/arcane/iris/structure/placement/StructureCaveAnchorResolver.java index 4f282fd0d..794c2d68b 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/StructureCaveAnchorResolver.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/StructureCaveAnchorResolver.java @@ -274,7 +274,7 @@ public final class StructureCaveAnchorResolver { int blockZ ) { HydrologyCaveCell hydrology = hydrologyAt(engine, blockX, mantleY, blockZ); - if (hydrology != null && hydrology.protectsPlacement()) { + if (hydrology != null) { return false; } MatterCavern cavern = engine.getMantle().getMantle() @@ -303,7 +303,7 @@ public final class StructureCaveAnchorResolver { int mantleY, int defaultLavaHeight ) { - if (hydrology != null && hydrology.protectsPlacement()) { + if (hydrology != null) { return false; } if (cavern == null || !cavern.isCavern()) { 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 0905a9ba2..d7e055184 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", "Rivers, falls, grottos and the rest of the hydrology the engine plans", + RIVERS("Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets 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/map/VisionRenderController.java b/core/src/main/java/art/arcane/iris/studio/map/VisionRenderController.java index 2f330d98b..619fa86fd 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/VisionRenderController.java +++ b/core/src/main/java/art/arcane/iris/studio/map/VisionRenderController.java @@ -339,7 +339,8 @@ final class VisionRenderController implements AutoCloseable { tilesInFlight.remove(key); Frame frame = currentFrame; VisibleTile visible = frame == null ? null : frame.tile(key); - if (cancelled && visible != null && visible.needsRender(nanoTime.getAsLong(), frame.spec().renderer().previewRevision())) { + if (cancelled && visible != null && visible.needsRender(nanoTime.getAsLong(), frame.spec().renderer().previewRevision(), + frame.spec().renderer().riverRevision())) { frame.nextCandidate = 0; } } @@ -349,6 +350,7 @@ final class VisionRenderController implements AutoCloseable { boolean cancelled = false; try { long previewRevision = job.renderer().previewRevision(); + long riverRevision = job.renderer().riverRevision(); double tileSpan = TILE_PIXELS * key.blocksPerPixel(); MapTileRenderer.TileRender work = job.work(); if (work == null) { @@ -364,13 +366,14 @@ final class VisionRenderController implements AutoCloseable { ? FIRST_RETRY_NANOS : Math.min(LAST_RETRY_NANOS, previous.retryDelay() * 2L); } long completedAt = nanoTime.getAsLong(); + boolean retained = work.retainsWater(); TileState state = new TileState(tile, provisional, delay, completedAt + delay, - completedAt + FIRST_RETRY_NANOS, previewRevision); + completedAt + FIRST_RETRY_NANOS, previewRevision, riverRevision, retained); synchronized (this) { if (closed.get()) { return; } - cache.put(key, state, provisional ? work : null); + cache.put(key, state, provisional || retained ? work : null); if (isWanted(key)) { currentFrame.tile(key).state = state; } @@ -573,9 +576,10 @@ final class VisionRenderController implements AutoCloseable { // Tiles are sorted centre first, and everything before the cursor is drawn or claimed, so each search resumes there. private VisibleTile nextMissing(Set inFlight, boolean advance, long now) { long previewRevision = spec.renderer().previewRevision(); + long riverRevision = spec.renderer().riverRevision(); for (int index = nextCandidate; index < tiles.size(); index++) { VisibleTile tile = tiles.get(index); - if (tile.needsRender(now, previewRevision) && !inFlight.contains(tile.key())) { + if (tile.needsRender(now, previewRevision, riverRevision) && !inFlight.contains(tile.key())) { if (advance) { nextCandidate = index + 1; } @@ -625,10 +629,16 @@ final class VisionRenderController implements AutoCloseable { return current != null && current.provisional(); } - private boolean needsRender(long now, long previewRevision) { + private boolean needsRender(long now, long previewRevision, long riverRevision) { TileState current = state; - return current == null || current.provisional() && (now - current.retryAt() >= 0L - || previewRevision != current.previewRevision() && now - current.earliestRetryAt() >= 0L); + if (current == null) { + return true; + } + if (current.provisional()) { + return now - current.retryAt() >= 0L + || previewRevision != current.previewRevision() && now - current.earliestRetryAt() >= 0L; + } + return current.retained() && riverRevision != current.riverRevision() && now - current.earliestRetryAt() >= 0L; } } @@ -681,7 +691,7 @@ final class VisionRenderController implements AutoCloseable { } private record TileState(MapTile tile, boolean provisional, long retryDelay, long retryAt, long earliestRetryAt, - long previewRevision) { + long previewRevision, long riverRevision, boolean retained) { } private static final class WeightedTileCache { diff --git a/core/src/main/java/art/arcane/iris/studio/map/components/MapTileRenderer.java b/core/src/main/java/art/arcane/iris/studio/map/components/MapTileRenderer.java index 5ff3aca9a..20e0628e1 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/components/MapTileRenderer.java +++ b/core/src/main/java/art/arcane/iris/studio/map/components/MapTileRenderer.java @@ -28,6 +28,7 @@ import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.studio.render.IrisRenderer; import art.arcane.iris.studio.render.RenderType; +import art.arcane.iris.world.history.GenerationSemanticQueries; import art.arcane.volmlib.util.stream.ProceduralStream; import java.awt.Color; @@ -58,6 +59,7 @@ public final class MapTileRenderer { private static final int NOISE_LOW = rgb(5, 5, 5); private static final int NOISE_HIGH = rgb(255, 255, 255); private static final double DARKEST_PICK_SHADE = 0.3D; + private static final double POOL_REFRESH_BLOCKS_PER_PIXEL = 4D; private final Engine engine; private final IrisRenderer hydrologyRenderer; @@ -78,6 +80,10 @@ public final class MapTileRenderer { return runtime == null ? 0L : runtime.previewRevision(); } + public long riverRevision() { + return GenerationSemanticQueries.recordedRiverRevision(engine); + } + /** * Renders the square of {@code size} pixels whose top left pixel samples the given world position. * @@ -351,6 +357,7 @@ public final class MapTileRenderer { public final class TileRender { private final TileRequest request; + private final boolean retainsWater; private short[] subjects; private short[] regions; private int[] baseColors; @@ -367,18 +374,22 @@ public final class MapTileRenderer { private TileRender(TileRequest request) { this.request = request; + boolean drawsWater = request.layer().type() == TileType.RIVER || request.layer().waterOverlay(); + this.retainsWater = drawsWater && request.blocksPerPixel() <= POOL_REFRESH_BLOCKS_PER_PIXEL; heightsComplete = !request.withHeights() && request.layer().type() != TileType.HEIGHT; - waterComplete = request.layer().type() != TileType.RIVER && !request.layer().waterOverlay(); + waterComplete = !drawsWater; } public MapTile render(BooleanSupplier cancelled) { Objects.requireNonNull(cancelled, "cancelled"); checkCancelled(cancelled); - TileGrid grid = new TileGrid(request.size() + 2, request.startX() - request.blocksPerPixel(), - request.startZ() - request.blocksPerPixel(), request.blocksPerPixel(), cancelled); - sampleSubjects(grid); - sampleBaseColors(grid); - sampleTerrain(grid, cancelled); + if (!identitiesComplete || !baseComplete || !heightsComplete) { + TileGrid grid = new TileGrid(request.size() + 2, request.startX() - request.blocksPerPixel(), + request.startZ() - request.blocksPerPixel(), request.blocksPerPixel(), cancelled); + sampleSubjects(grid); + sampleBaseColors(grid); + sampleTerrain(grid, cancelled); + } int[] colors = sampleWater(cancelled); checkCancelled(cancelled); complete = baseComplete && heightsComplete && waterComplete; @@ -396,6 +407,10 @@ public final class MapTileRenderer { return complete; } + public boolean retainsWater() { + return retainsWater; + } + public long bytes() { return bytes; } @@ -445,19 +460,21 @@ public final class MapTileRenderer { } private int[] sampleWater(BooleanSupplier cancelled) { - if (waterComplete) { - return finalColors == null ? baseColors : finalColors; - } if (water == null) { + if (waterComplete) { + return finalColors == null ? baseColors : finalColors; + } water = hydrologyRenderer.prepareStudioWater(request.startX(), request.startZ(), request.blocksPerPixel(), request.size()); } int[] colors = water.render(baseColors, request.layer().waterOverlay(), cancelled); if (baseComplete && water.complete()) { - finalColors = colors; - baseColors = null; waterComplete = true; - water = null; + if (!retainsWater) { + finalColors = colors; + baseColors = null; + water = null; + } } return colors; } 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 24eb3bdaf..914199cde 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 @@ -88,64 +88,6 @@ public final class IrisRenderer { int resolution, RenderType currentType, BooleanSupplier cancelled - ) { - return render(sx, sz, size, resolution, currentType, cancelled, false, false); - } - - public BufferedImage renderStudio( - double sx, - double sz, - double size, - int resolution, - RenderType currentType, - BooleanSupplier cancelled - ) { - return render(sx, sz, size, resolution, currentType, cancelled, true, true); - } - - public BufferedImage renderStudioBase( - double sx, - double sz, - double size, - int resolution, - RenderType currentType, - BooleanSupplier cancelled - ) { - return render(sx, sz, size, resolution, currentType, cancelled, true, false); - } - - public BufferedImage refineStudioBiome( - double sx, - double sz, - double size, - BufferedImage base, - BooleanSupplier cancelled - ) { - Objects.requireNonNull(base, "base"); - Objects.requireNonNull(cancelled, "cancelled"); - checkCancelled(cancelled); - if (!Double.isFinite(sx) || !Double.isFinite(sz) || !Double.isFinite(size) || size <= 0D - || base.getWidth() != base.getHeight()) { - throw new IllegalArgumentException("Vision biome refinement requires finite coordinates and a square base image"); - } - int resolution = base.getWidth(); - BufferedImage image = new BufferedImage(resolution, resolution, BufferedImage.TYPE_INT_RGB); - base.copyData(image.getRaster()); - int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - renderRiverAtlas(pixels, resolution, sx, sz, size / resolution, renderer, cancelled, true); - checkCancelled(cancelled); - return image; - } - - private BufferedImage render( - double sx, - double sz, - double size, - int resolution, - RenderType currentType, - BooleanSupplier cancelled, - boolean studio, - boolean riverOverlay ) { if (!Double.isFinite(sx) || !Double.isFinite(sz) || !Double.isFinite(size) || size <= 0D) { throw new IllegalArgumentException("Vision render coordinates and size must be finite"); @@ -160,23 +102,7 @@ public final class IrisRenderer { BufferedImage image = new BufferedImage(resolution, resolution, BufferedImage.TYPE_INT_RGB); int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); double step = size / resolution; - if (studio && currentType == RenderType.HEIGHT) { - renderHeightAtlas(pixels, resolution, sx, sz, step, renderer, cancelled); - return image; - } - if (currentType == RenderType.RIVER) { - Arrays.fill(pixels, NO_RIVER); - renderRiverAtlas(pixels, resolution, sx, sz, step, renderer, cancelled, false); - return image; - } - PixelShader shader = shader(currentType, studio); - if (studio && adaptiveStudioType(currentType)) { - renderAdaptiveAtlas(pixels, resolution, sx, sz, step, shader, cancelled); - if (currentType == RenderType.BIOME && riverOverlay) { - renderRiverAtlas(pixels, resolution, sx, sz, step, renderer, cancelled, true); - } - return image; - } + PixelShader shader = shader(currentType); int groupSize = sampleGroup(step, resolution); for (int groupZ = 0; groupZ < resolution; groupZ += groupSize) { @@ -248,118 +174,19 @@ public final class IrisRenderer { return Math.max(1, Math.min(resolution, (int) Math.floor(16D / absoluteStep))); } - private PixelShader shader(RenderType currentType, boolean studio) { + private PixelShader shader(RenderType currentType) { IrisComplex complex = renderer.getComplex(); return switch (currentType) { - case BIOME, DECORATOR_LOAD, OBJECT_LOAD, LAYER_LOAD -> biomeShader( - studio ? complex.getBaseBiomeStream() : complex.getTrueBiomeStream(), currentType); + case BIOME, DECORATOR_LOAD, OBJECT_LOAD, LAYER_LOAD -> biomeShader(complex.getTrueBiomeStream(), currentType); case BIOME_LAND -> biomeShader(complex.getLandBiomeStream(), currentType); case BIOME_SEA -> biomeShader(complex.getSeaBiomeStream(), currentType); case REGION -> regionShader(complex, currentType); case CAVE_LAND -> biomeShader(complex.getCaveBiomeStream(), currentType); - case HEIGHT -> heightShader(studio ? complex.getNaturalHeightStream() : complex.getHeightStream()); - case RIVER -> throw new IllegalArgumentException("River maps render from the water raster atlas, not a pixel shader"); - case CONTINENT -> studio - ? continentShader(complex.getBaseBiomeStream()) - : this::continentColor; + case HEIGHT -> heightShader(complex.getHeightStream()); + case CONTINENT -> this::continentColor; }; } - private static boolean adaptiveStudioType(RenderType type) { - return switch (type) { - case BIOME, DECORATOR_LOAD, OBJECT_LOAD, LAYER_LOAD, BIOME_LAND, BIOME_SEA, REGION, CAVE_LAND, - CONTINENT -> true; - case HEIGHT, RIVER -> false; - }; - } - - private static void renderAdaptiveAtlas( - int[] pixels, - int resolution, - double startX, - double startZ, - double step, - PixelShader shader, - BooleanSupplier cancelled - ) { - int maximumPixels = Math.max(1, Math.min(16, (int) Math.floor(64D / step))); - int blockPixels = Integer.highestOneBit(maximumPixels); - AdaptiveSampler sampler = new AdaptiveSampler(pixels, resolution, startX, startZ, step, shader, cancelled); - for (int pixelZ = 0; pixelZ < resolution; pixelZ += blockPixels) { - int height = Math.min(blockPixels, resolution - pixelZ); - for (int pixelX = 0; pixelX < resolution; pixelX += blockPixels) { - sampler.render(pixelX, pixelZ, Math.min(blockPixels, resolution - pixelX), height); - } - } - } - - private static void renderHeightAtlas( - int[] pixels, - int resolution, - double startX, - double startZ, - double step, - Engine engine, - BooleanSupplier cancelled - ) { - IrisComplex complex = engine.getComplex(); - IrisDimension dimension = engine.getDimension(); - double fluidHeight = dimension == null ? 0D : dimension.getFluidHeight(); - int maximumPixels = Math.max(1, Math.min(16, (int) Math.floor(64D / step))); - int blockPixels = Integer.highestOneBit(maximumPixels); - HeightSampler sampler = new HeightSampler( - pixels, - resolution, - startX, - startZ, - step, - complex.getNaturalHeightStream(), - engine.getHeight(), - fluidHeight, - cancelled - ); - for (int pixelZ = 0; pixelZ < resolution; pixelZ += blockPixels) { - int height = Math.min(blockPixels, resolution - pixelZ); - for (int pixelX = 0; pixelX < resolution; pixelX += blockPixels) { - sampler.render(pixelX, pixelZ, Math.min(blockPixels, resolution - pixelX), height); - } - } - } - - private static void renderRiverAtlas( - int[] pixels, - int resolution, - double startX, - double startZ, - double step, - Engine engine, - BooleanSupplier cancelled, - boolean composite - ) { - HydrologyRuntime runtime = engine.getComplex().getHydrologyRuntime(); - if (runtime == null || !runtime.enabled() || step > WaterMap.MAX_STEP) { - return; - } - WaterMap map = WaterMap.draw(runtime, resolution, startX, startZ, step, cancelled); - map.drawCavePools(GenerationSemanticQueries.recordedCavePools(engine, Math.floorDiv((int) Math.floor(startX), 16), - Math.floorDiv((int) Math.floor(startZ), 16), Math.floorDiv((int) Math.ceil(startX + resolution * step) - 1, 16), - Math.floorDiv((int) Math.ceil(startZ + resolution * step) - 1, 16))); - for (int pixelZ = 0; pixelZ < resolution; pixelZ++) { - for (int pixelX = 0; pixelX < resolution; pixelX++) { - HydrologyFeatureType type = map.at(pixelX, pixelZ); - if (type == null) { - continue; - } - int index = pixelZ * resolution + pixelX; - int color = hydrologyFeatureColor(type); - pixels[index] = composite ? blend(pixels[index], color, RIVER_OVERLAY) : color; - } - } - if (map.provisional()) { - ProvisionalSampling.mark(); - } - } - private PixelShader biomeShader(ProceduralStream stream, RenderType currentType) { IdentityHashMap colors = new IdentityHashMap<>(); return (double x, double z) -> { @@ -403,19 +230,6 @@ public final class IrisRenderer { return continentColor(biome); } - private PixelShader continentShader(ProceduralStream stream) { - IdentityHashMap colors = new IdentityHashMap<>(); - return (double x, double z) -> { - IrisBiome biome = stream.get(x, z); - Integer color = colors.get(biome); - if (color == null) { - color = continentColor(biome); - colors.put(biome, color); - } - return color; - }; - } - private int continentColor(IrisBiome biome) { if (biome == null) { return GREEN; @@ -459,6 +273,7 @@ public final class IrisRenderer { private final int resolution; private final WaterMap map; private boolean complete; + private long poolRevision; private WaterTile(double startX, double startZ, double step, int resolution) { this.startX = startX; @@ -477,13 +292,8 @@ public final class IrisRenderer { if (composite && (base == null || base.length != resolution * resolution)) { throw new IllegalArgumentException("Water overlay requires matching base pixels"); } - if (!complete) { - map.advance(cancelled); - map.drawCavePools(GenerationSemanticQueries.recordedCavePools(renderer, - Math.floorDiv((int) Math.floor(startX), 16), Math.floorDiv((int) Math.floor(startZ), 16), - Math.floorDiv((int) Math.ceil(startX + resolution * step) - 1, 16), - Math.floorDiv((int) Math.ceil(startZ + resolution * step) - 1, 16))); - complete = !map.provisional(); + if (map != null) { + draw(cancelled); } int[] colors = composite ? base.clone() : new int[resolution * resolution]; if (!composite) { @@ -515,260 +325,27 @@ public final class IrisRenderer { public long bytes() { return map == null ? 0L : map.bytes(); } + + private void draw(BooleanSupplier cancelled) { + long revision = GenerationSemanticQueries.recordedRiverRevision(renderer); + boolean advanced = !complete; + if (advanced) { + map.advance(cancelled); + complete = !map.provisional(); + } + if (!advanced && revision == poolRevision) { + return; + } + map.drawCavePools(GenerationSemanticQueries.recordedCavePools(renderer, + Math.floorDiv((int) Math.floor(startX), 16), Math.floorDiv((int) Math.floor(startZ), 16), + Math.floorDiv((int) Math.ceil(startX + resolution * step) - 1, 16), + Math.floorDiv((int) Math.ceil(startZ + resolution * step) - 1, 16))); + poolRevision = revision; + } } @FunctionalInterface private interface PixelShader { int color(double x, double z); } - - private static final class AdaptiveSampler { - private final int[] pixels; - private final boolean[] sampled; - private final int resolution; - private final double startX; - private final double startZ; - private final double step; - private final PixelShader shader; - private final BooleanSupplier cancelled; - - private AdaptiveSampler( - int[] pixels, - int resolution, - double startX, - double startZ, - double step, - PixelShader shader, - BooleanSupplier cancelled - ) { - this.pixels = pixels; - this.sampled = new boolean[pixels.length]; - this.resolution = resolution; - this.startX = startX; - this.startZ = startZ; - this.step = step; - this.shader = shader; - this.cancelled = cancelled; - } - - private void render(int pixelX, int pixelZ, int width, int height) { - checkCancelled(cancelled); - if (width == 1 && height == 1) { - sample(pixelX, pixelZ); - return; - } - int maximumX = pixelX + width - 1; - int maximumZ = pixelZ + height - 1; - int centerX = pixelX + width / 2; - int centerZ = pixelZ + height / 2; - int color = sample(pixelX, pixelZ); - if (sample(maximumX, pixelZ) == color - && sample(pixelX, maximumZ) == color - && sample(maximumX, maximumZ) == color - && sample(centerX, centerZ) == color) { - fill(pixelX, pixelZ, width, height, color); - return; - } - int leftWidth = Math.max(1, width / 2); - int rightWidth = width - leftWidth; - int topHeight = Math.max(1, height / 2); - int bottomHeight = height - topHeight; - render(pixelX, pixelZ, leftWidth, topHeight); - if (rightWidth > 0) { - render(pixelX + leftWidth, pixelZ, rightWidth, topHeight); - } - if (bottomHeight > 0) { - render(pixelX, pixelZ + topHeight, leftWidth, bottomHeight); - if (rightWidth > 0) { - render(pixelX + leftWidth, pixelZ + topHeight, rightWidth, bottomHeight); - } - } - } - - private int sample(int pixelX, int pixelZ) { - int index = pixelZ * resolution + pixelX; - if (!sampled[index]) { - pixels[index] = shader.color(startX + pixelX * step, startZ + pixelZ * step); - sampled[index] = true; - } - return pixels[index]; - } - - private void fill(int pixelX, int pixelZ, int width, int height, int color) { - for (int row = pixelZ; row < pixelZ + height; row++) { - int start = row * resolution + pixelX; - Arrays.fill(pixels, start, start + width, color); - Arrays.fill(sampled, start, start + width, true); - } - } - } - - private static final class HeightSampler { - private static final double MAXIMUM_INTERPOLATION_ERROR = 1.5D; - - private final int[] pixels; - private final double[] heights; - private final boolean[] sampled; - private final int resolution; - private final double startX; - private final double startZ; - private final double step; - private final ProceduralStream stream; - private final double maximumHeight; - private final double fluidHeight; - private final BooleanSupplier cancelled; - - private HeightSampler( - int[] pixels, - int resolution, - double startX, - double startZ, - double step, - ProceduralStream stream, - double maximumHeight, - double fluidHeight, - BooleanSupplier cancelled - ) { - this.pixels = pixels; - this.heights = new double[pixels.length]; - this.sampled = new boolean[pixels.length]; - this.resolution = resolution; - this.startX = startX; - this.startZ = startZ; - this.step = step; - this.stream = stream; - this.maximumHeight = maximumHeight; - this.fluidHeight = fluidHeight; - this.cancelled = cancelled; - } - - private void render(int pixelX, int pixelZ, int width, int height) { - checkCancelled(cancelled); - if (width == 1 && height == 1) { - pixels[pixelZ * resolution + pixelX] = heightColor( - sample(pixelX, pixelZ), maximumHeight, fluidHeight); - return; - } - int maximumX = pixelX + width - 1; - int maximumZ = pixelZ + height - 1; - int centerX = pixelX + width / 2; - int centerZ = pixelZ + height / 2; - double topLeft = sample(pixelX, pixelZ); - double topRight = sample(maximumX, pixelZ); - double bottomLeft = sample(pixelX, maximumZ); - double bottomRight = sample(maximumX, maximumZ); - if (matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight, - centerX, pixelZ) - && matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight, - pixelX, centerZ) - && matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight, - maximumX, centerZ) - && matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight, - centerX, maximumZ) - && matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight, - centerX, centerZ)) { - fillPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight); - return; - } - int leftWidth = Math.max(1, width / 2); - int rightWidth = width - leftWidth; - int topHeight = Math.max(1, height / 2); - int bottomHeight = height - topHeight; - render(pixelX, pixelZ, leftWidth, topHeight); - if (rightWidth > 0) { - render(pixelX + leftWidth, pixelZ, rightWidth, topHeight); - } - if (bottomHeight > 0) { - render(pixelX, pixelZ + topHeight, leftWidth, bottomHeight); - if (rightWidth > 0) { - render(pixelX + leftWidth, pixelZ + topHeight, rightWidth, bottomHeight); - } - } - } - - private boolean matchesPlane( - int pixelX, - int pixelZ, - int width, - int height, - double topLeft, - double topRight, - double bottomLeft, - double bottomRight, - int sampleX, - int sampleZ - ) { - double predicted = interpolate( - pixelX, - pixelZ, - width, - height, - topLeft, - topRight, - bottomLeft, - bottomRight, - sampleX, - sampleZ - ); - return Math.abs(sample(sampleX, sampleZ) - predicted) <= MAXIMUM_INTERPOLATION_ERROR; - } - - private void fillPlane( - int pixelX, - int pixelZ, - int width, - int height, - double topLeft, - double topRight, - double bottomLeft, - double bottomRight - ) { - for (int row = pixelZ; row < pixelZ + height; row++) { - int offset = row * resolution; - for (int column = pixelX; column < pixelX + width; column++) { - double value = interpolate( - pixelX, - pixelZ, - width, - height, - topLeft, - topRight, - bottomLeft, - bottomRight, - column, - row - ); - pixels[offset + column] = heightColor(value, maximumHeight, fluidHeight); - } - } - } - - private double sample(int pixelX, int pixelZ) { - int index = pixelZ * resolution + pixelX; - if (!sampled[index]) { - heights[index] = stream.getDouble(startX + pixelX * step, startZ + pixelZ * step); - sampled[index] = true; - } - return heights[index]; - } - - private static double interpolate( - int pixelX, - int pixelZ, - int width, - int height, - double topLeft, - double topRight, - double bottomLeft, - double bottomRight, - int sampleX, - int sampleZ - ) { - double x = width <= 1 ? 0D : (sampleX - pixelX) / (double) (width - 1); - double z = height <= 1 ? 0D : (sampleZ - pixelZ) / (double) (height - 1); - double top = topLeft + (topRight - topLeft) * x; - double bottom = bottomLeft + (bottomRight - bottomLeft) * x; - return top + (bottom - top) * z; - } - } } diff --git a/core/src/main/java/art/arcane/iris/studio/render/RenderType.java b/core/src/main/java/art/arcane/iris/studio/render/RenderType.java index 2e56b37b4..dde611493 100644 --- a/core/src/main/java/art/arcane/iris/studio/render/RenderType.java +++ b/core/src/main/java/art/arcane/iris/studio/render/RenderType.java @@ -19,5 +19,5 @@ package art.arcane.iris.studio.render; public enum RenderType { - BIOME, BIOME_LAND, BIOME_SEA, REGION, CAVE_LAND, RIVER, HEIGHT, OBJECT_LOAD, DECORATOR_LOAD, CONTINENT, LAYER_LOAD + BIOME, BIOME_LAND, BIOME_SEA, REGION, CAVE_LAND, HEIGHT, OBJECT_LOAD, DECORATOR_LOAD, CONTINENT, LAYER_LOAD } 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 33c33db23..f632f2fec 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 @@ -24,12 +24,8 @@ import java.util.function.BooleanSupplier; final class WaterMap { static final double RASTER_STEP = 2D; static final double MAX_STEP = 16D; - static final List DRAWN = List.of(HydrologyFeatureType.WATERFALL, HydrologyFeatureType.CASCADE, - HydrologyFeatureType.MOUTH, HydrologyFeatureType.MAJOR_RIVER, HydrologyFeatureType.RIVER, HydrologyFeatureType.STREAM, - HydrologyFeatureType.SEA_INLET, HydrologyFeatureType.LAKE, HydrologyFeatureType.POND, HydrologyFeatureType.DAM, - HydrologyFeatureType.CAVE_POOL); + static final List DRAWN = drawn(); private static final int DRY = Integer.MAX_VALUE; - private static final int[] RANK = ranks(); private final HydrologyRuntime runtime; private final int resolution; @@ -57,12 +53,6 @@ final class WaterMap { provisional = true; } - static WaterMap draw(HydrologyRuntime runtime, int resolution, double startX, double startZ, double step, BooleanSupplier cancelled) { - WaterMap map = new WaterMap(runtime, resolution, startX, startZ, step); - map.advance(cancelled); - return map; - } - void advance(BooleanSupplier cancelled) { if (!provisional) { return; @@ -280,7 +270,7 @@ final class WaterMap { int lastX = Math.min(resolution - 1, (int) Math.floor((centreX + half - 1 - startX) / step)); for (int pixelZ = firstZ; pixelZ <= lastZ; pixelZ++) { for (int pixelX = firstX; pixelX <= lastX; pixelX++) { - ranks[pixelZ * resolution + pixelX] = RANK[type.ordinal()]; + stamp(pixelX, pixelZ, type); } } } @@ -296,7 +286,7 @@ final class WaterMap { return; } int index = pixelZ * resolution + pixelX; - int rank = RANK[type.ordinal()]; + int rank = rank(type); if (rank < ranks[index]) { ranks[index] = rank; } @@ -308,12 +298,31 @@ final class WaterMap { } } - private static int[] ranks() { - int[] ranks = new int[HydrologyFeatureType.values().length]; - Arrays.fill(ranks, DRY); - for (int index = 0; index < DRAWN.size(); index++) { - ranks[DRAWN.get(index).ordinal()] = index; + private static int rank(HydrologyFeatureType type) { + return switch (type) { + case WATERFALL -> 0; + case CASCADE -> 1; + case MOUTH -> 2; + case MAJOR_RIVER -> 3; + case RIVER -> 4; + case STREAM -> 5; + case SEA_INLET -> 6; + case POND -> 7; + case LAKE -> 8; + case DAM -> 9; + case CAVE_POOL -> 10; + }; + } + + private static List drawn() { + HydrologyFeatureType[] drawn = new HydrologyFeatureType[HydrologyFeatureType.values().length]; + for (HydrologyFeatureType type : HydrologyFeatureType.values()) { + int rank = rank(type); + if (drawn[rank] != null) { + throw new IllegalStateException("Water map ranks " + drawn[rank] + " and " + type + " equally"); + } + drawn[rank] = type; } - return ranks; + return List.of(drawn); } } diff --git a/core/src/main/java/art/arcane/iris/studio/workspace/IrisPackageCompiler.java b/core/src/main/java/art/arcane/iris/studio/workspace/IrisPackageCompiler.java index 97911807a..8d2b6f377 100644 --- a/core/src/main/java/art/arcane/iris/studio/workspace/IrisPackageCompiler.java +++ b/core/src/main/java/art/arcane/iris/studio/workspace/IrisPackageCompiler.java @@ -139,7 +139,6 @@ public class IrisPackageCompiler { exportedDimension.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp))); } - regions.forEach((i) -> biomes.addAll(i.getAllBiomes(() -> dm))); regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i)))); regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp)))); biomes.forEach((i) -> i.getGenerators().forEach((j) -> addIfPresent(generators, j.getCachedGenerator(() -> dm)))); diff --git a/core/src/main/java/art/arcane/iris/world/history/ChunkGenerationSemantics.java b/core/src/main/java/art/arcane/iris/world/history/ChunkGenerationSemantics.java index cdbeb5a36..05db4b46f 100644 --- a/core/src/main/java/art/arcane/iris/world/history/ChunkGenerationSemantics.java +++ b/core/src/main/java/art/arcane/iris/world/history/ChunkGenerationSemantics.java @@ -28,7 +28,7 @@ public final class ChunkGenerationSemantics { .thenComparingInt(point -> point.position().y()); private static final Comparator RIVER_FEATURE_COMPARATOR = Comparator .comparing(RiverFeatureOccurrence::profileKey) - .thenComparing(RiverFeatureOccurrence::type) + .thenComparingInt(occurrence -> occurrence.type().code()) .thenComparingInt(occurrence -> occurrence.position().x()) .thenComparingInt(occurrence -> occurrence.position().z()) .thenComparingInt(occurrence -> occurrence.position().y()) diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java b/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java index 7731c1774..548ad2e5b 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java @@ -866,6 +866,10 @@ public final class GenerationHistory { return semantics.get(chunkX, chunkZ); } + public long riverRevision() { + return semantics.riverRevision(); + } + public synchronized Optional findRecorded( GenerationSemanticIndex.Query query ) { 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 6f77ef84d..c0d8b36a3 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 @@ -277,7 +277,7 @@ public final class GenerationSemanticCapture { blockX, y, blockZ, - cell == null ? null : cell.floodedBiomeKey() + null ); if (cell != null && cell.isWet() && cell.fluidProfileKey() != null && !cell.fluidProfileKey().isBlank() && !HydrologyCaveCell.SEA_FLUID.equals(cell.fluidProfileKey())) { diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticIndex.java b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticIndex.java index 64cd9a50c..c6daba662 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticIndex.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticIndex.java @@ -45,6 +45,7 @@ import java.util.Optional; import java.util.OptionalLong; import java.util.Set; import java.util.TreeSet; +import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Predicate; @@ -96,6 +97,7 @@ public final class GenerationSemanticIndex { private final CatalogPublisher catalogPublisher; private final boolean unpublished; private final DeferredDurability durability; + private final AtomicLong riverRevision = new AtomicLong(); private long regionDecodeCount; private volatile IOException journalFailure; private long appendingRegionKey; @@ -245,6 +247,7 @@ public final class GenerationSemanticIndex { RegionShard baseRegion = loadRegionLocked(regionKey, regionX, regionZ); RegionShard nextRegion = baseRegion; List updates = new ArrayList<>(claims.size()); + boolean water = false; for (Claim pending : claims) { ChunkGenerationSemantics update = pending.update; ChunkGenerationSemantics existing = nextRegion.get(update.chunkX(), update.chunkZ()); @@ -261,6 +264,7 @@ public final class GenerationSemanticIndex { } nextRegion = nextRegion.withRecord(merged); updates.add(merged); + water |= waterChanged(existing, merged); pending.persisted = true; } if (updates.isEmpty()) { @@ -286,6 +290,9 @@ public final class GenerationSemanticIndex { cacheRegion(regionKey, nextRegion); regionRecordCounts.put(regionKey, nextRegion.recordCount()); journalEntries.addTo(regionKey, updates.size()); + if (water) { + riverRevision.incrementAndGet(); + } for (Claim pending : claims) { pending.completed = true; } @@ -452,6 +459,9 @@ public final class GenerationSemanticIndex { if (existing == null) { regionRecordCounts.addTo(regionKey, 1); } + if (waterChanged(existing, merged)) { + riverRevision.incrementAndGet(); + } shardHashes.put(regionKey, shardHash); deleteUnreferencedShard(regionX, regionZ, previousHash, shardHash); return true; @@ -473,6 +483,10 @@ public final class GenerationSemanticIndex { } } + public long riverRevision() { + return riverRevision.get(); + } + public int recordCount() { lock.readLock().lock(); publicationLock.lock(); @@ -1153,6 +1167,10 @@ public final class GenerationSemanticIndex { } } + private static boolean waterChanged(ChunkGenerationSemantics existing, ChunkGenerationSemantics merged) { + return existing == null ? !merged.riverFeatures().isEmpty() : !existing.riverFeatures().equals(merged.riverFeatures()); + } + private static Set keys(ChunkGenerationSemantics semantics, SemanticKind kind) { return switch (kind) { case SURFACE_BIOME -> semantics.surfaceBiomeKeys(); @@ -1750,14 +1768,14 @@ public final class GenerationSemanticIndex { } else if (riverTypeCount > HydrologyFeatureType.values().length) { throw invalid(source, "invalid summary river type count " + riverTypeCount); } - int previousOrdinal = -1; + int previousCode = -1; for (int index = 0; index < riverTypeCount; index++) { - int ordinal = input.readUnsignedByte(); - if (ordinal <= previousOrdinal || ordinal >= HydrologyFeatureType.values().length) { - throw invalid(source, "invalid summary river type ordinal " + ordinal); + int code = input.readUnsignedByte(); + if (code <= previousCode) { + throw invalid(source, "summary river type codes are not in canonical order"); } - riverTypes.add(HydrologyFeatureType.values()[ordinal]); - previousOrdinal = ordinal; + riverTypes.add(RegionShard.riverFeatureType(source, code)); + previousCode = code; } LongOpenHashSet activations = readActivations(source, input, "summary activation"); LongOpenHashSet sealedActivations = readActivations(source, input, "sealed summary activation"); @@ -1791,8 +1809,8 @@ public final class GenerationSemanticIndex { } } output.writeByte(riverTypes.size()); - for (HydrologyFeatureType type : riverTypes) { - output.writeByte(type.ordinal()); + for (int code : riverTypes.stream().mapToInt(HydrologyFeatureType::code).sorted().toArray()) { + output.writeByte(code); } writeActivations(output, activations); writeActivations(output, sealedActivations); @@ -2707,7 +2725,7 @@ public final class GenerationSemanticIndex { output.writeShort(semantics.riverFeatures().size()); for (ChunkGenerationSemantics.RiverFeatureOccurrence occurrence : semantics.riverFeatures()) { output.writeShort(paletteIndexes.get(occurrence.profileKey())); - output.writeByte(occurrence.type().ordinal()); + output.writeByte(occurrence.type().code()); output.writeLong(occurrence.featureId()); output.writeInt(occurrence.position().x()); output.writeInt(occurrence.position().y()); @@ -2916,21 +2934,17 @@ public final class GenerationSemanticIndex { return; } ChunkGenerationSemantics.RiverFeatureOccurrence previous = null; - HydrologyFeatureType[] types = HydrologyFeatureType.values(); for (int index = 0; index < count; index++) { int paletteIndex = input.readUnsignedShort(); if (paletteIndex >= palette.length) { throw invalid(file, "river profile key palette index is out of range"); } - int typeOrdinal = input.readUnsignedByte(); - if (typeOrdinal >= types.length) { - throw invalid(file, "river feature type ordinal is out of range"); - } + HydrologyFeatureType type = riverFeatureType(file, input.readUnsignedByte()); paletteUsed[paletteIndex] = true; ChunkGenerationSemantics.RiverFeatureOccurrence occurrence = new ChunkGenerationSemantics.RiverFeatureOccurrence( palette[paletteIndex], - types[typeOrdinal], + type, input.readLong(), new ChunkGenerationSemantics.BlockPosition( input.readInt(), @@ -2948,6 +2962,14 @@ public final class GenerationSemanticIndex { } } + private static HydrologyFeatureType riverFeatureType(Path file, int code) throws IOException { + try { + return HydrologyFeatureType.fromCode(code); + } catch (IllegalStateException unknown) { + throw invalid(file, unknown.getMessage(), unknown); + } + } + private static void skipLegacyRiverFeatures( Path file, DataInputStream input, diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticQueries.java b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticQueries.java index 7d30617ee..0cb57659a 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticQueries.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticQueries.java @@ -9,6 +9,7 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef; import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; +import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException; import java.math.BigInteger; import java.io.IOException; @@ -21,11 +22,18 @@ import java.util.Objects; import java.util.Optional; import java.util.OptionalLong; import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; import java.util.function.Predicate; import java.util.function.BooleanSupplier; public final class GenerationSemanticQueries { public static final int RIVER_SEARCH_DISTANCE = 7168; + private static final ConcurrentHashMap> RIVER_SEARCHES = new ConcurrentHashMap<>(); private GenerationSemanticQueries() { } @@ -153,15 +161,41 @@ public final class GenerationSemanticQueries { IrisStructureLocator.LocateStatus.FOUND, position.x(), position.y(), position.z()); } - public static Optional nearestRiver( + public static CompletableFuture startRiverSearch( + UUID searcher, + Executor executor, + Engine engine, + HydrologyFeatureType type, + int blockX, + int blockZ + ) { + UUID requiredSearcher = Objects.requireNonNull(searcher, "searcher"); + Executor requiredExecutor = Objects.requireNonNull(executor, "executor"); + CompletableFuture search = new CompletableFuture<>(); + CompletableFuture previous = RIVER_SEARCHES.put(requiredSearcher, search); + if (previous != null) { + previous.cancel(false); + } + search.whenComplete((result, failure) -> RIVER_SEARCHES.remove(requiredSearcher, search)); + try { + requiredExecutor.execute(() -> runRiverSearch(search, engine, type, blockX, blockZ)); + } catch (RejectedExecutionException rejected) { + search.completeExceptionally(rejected); + } + return search; + } + + public static RiverSearch nearestRiver( Engine engine, HydrologyFeatureType type, int blockX, int blockZ, - int maximumDistance + int maximumDistance, + BooleanSupplier running ) { Engine requiredEngine = Objects.requireNonNull(engine, "engine"); HydrologyFeatureType requiredType = Objects.requireNonNull(type, "type"); + Objects.requireNonNull(running, "running"); if (maximumDistance < 0) { throw new IllegalArgumentException("Maximum river search distance cannot be negative."); } @@ -173,23 +207,63 @@ public final class GenerationSemanticQueries { blockZ, maximumDistance ); - RiverResult active = recordedOnly(requiredType) ? null : activeRiver( - requiredEngine, - history, - requiredType, - blockX, - blockZ, - maximumDistance - ); + Optional unavailable = requiredEngine.getComplex().getHydrologyRuntime().unavailable(requiredType); + if (recordedOnly(requiredType) || unavailable.isPresent()) { + if (recorded != null) { + return new RiverSearch.Found(recorded); + } + return new RiverSearch.Missing(unavailable.map(reason -> riverUnavailableMessage(requiredType, reason)) + .orElseGet(() -> riverNotFoundMessage(requiredType, maximumDistance))); + } + int activeDistance = recorded == null ? maximumDistance : Math.min(maximumDistance, distanceCeiling(blockX, blockZ, recorded)); + RiverResult active; + try { + active = activeRiver(requiredEngine, history, requiredType, blockX, blockZ, activeDistance, running); + } catch (HydrologySearchTimeoutException timedOut) { + RiverResult planned = timedOut.nearestSoFar().map(feature -> activeResult(requiredEngine, history, feature)).orElse(null); + return stoppedSearch(requiredType, nearer(blockX, blockZ, recorded, planned)); + } + RiverResult nearest = nearer(blockX, blockZ, recorded, active); + return nearest == null + ? new RiverSearch.Missing(riverNotFoundMessage(requiredType, maximumDistance)) + : new RiverSearch.Found(nearest); + } + + private static void runRiverSearch( + CompletableFuture search, + Engine engine, + HydrologyFeatureType type, + int blockX, + int blockZ + ) { + if (search.isDone()) { + return; + } + try { + search.complete(nearestRiver(engine, type, blockX, blockZ, RIVER_SEARCH_DISTANCE, () -> !search.isDone())); + } catch (CancellationException stopped) { + search.completeExceptionally(new IllegalStateException(stopped.getMessage(), stopped)); + } catch (Throwable failure) { + search.completeExceptionally(failure); + } + } + + private static int distanceCeiling(int blockX, int blockZ, RiverResult feature) { + BigInteger squared = horizontalDistanceSquared(blockX, blockZ, feature.x(), feature.z()); + BigInteger root = squared.sqrt(); + return (root.multiply(root).equals(squared) ? root : root.add(BigInteger.ONE)).intValueExact(); + } + + private static RiverResult nearer(int blockX, int blockZ, RiverResult recorded, RiverResult active) { if (recorded == null) { - return Optional.ofNullable(active); + return active; } if (active == null) { - return Optional.of(recorded); + return recorded; } int comparison = horizontalDistanceSquared(blockX, blockZ, recorded.x(), recorded.z()) .compareTo(horizontalDistanceSquared(blockX, blockZ, active.x(), active.z())); - return Optional.of(comparison <= 0 ? recorded : active); + return comparison <= 0 ? recorded : active; } private static boolean recordedOnly(HydrologyFeatureType type) { @@ -197,14 +271,32 @@ public final class GenerationSemanticQueries { } public static String riverSearchMessage(HydrologyFeatureType type, int maximumDistance) { - String label = type.key().replace('_', ' '); + String label = label(type); return recordedOnly(type) ? "Searching generated chunks for the nearest " + label + " within " + maximumDistance + " blocks..." : "Searching for the nearest " + label + " within " + maximumDistance + " blocks..."; } - public static String riverNotFoundMessage(HydrologyFeatureType type, int maximumDistance) { - String label = type.key().replace('_', ' '); + private static String riverUnavailableMessage(HydrologyFeatureType type, String reason) { + return "No " + label(type) + " forms in this dimension: " + reason + "."; + } + + private static RiverSearch stoppedSearch(HydrologyFeatureType type, RiverResult nearestSoFar) { + String stopped = "Stopped searching for the nearest " + label(type) + " after " + + HydrologyRuntime.FEATURE_SEARCH_TIMEOUT.toSeconds() + " seconds"; + if (nearestSoFar == null) { + return new RiverSearch.Stopped(Optional.empty(), stopped + " without finding one."); + } + return new RiverSearch.Stopped(Optional.of(nearestSoFar), stopped + ". The nearest " + label(type) + " found so far is at " + + nearestSoFar.x() + ", " + nearestSoFar.y() + ", " + nearestSoFar.z() + "; a nearer one may exist."); + } + + private static String label(HydrologyFeatureType type) { + return type.key().replace('_', ' '); + } + + private static String riverNotFoundMessage(HydrologyFeatureType type, int maximumDistance) { + String label = label(type); return recordedOnly(type) ? "No " + label + " found in generated chunks within " + maximumDistance + " blocks. Cave pools form in carved caves, so " + "only chunks that have already generated can hold one." @@ -239,6 +331,11 @@ public final class GenerationSemanticQueries { return pools; } + public static long recordedRiverRevision(Engine engine) { + GenerationHistory history = history(Objects.requireNonNull(engine, "engine")).orElse(null); + return history == null ? 0L : history.riverRevision(); + } + public static boolean allowsActivePrediction(Engine engine, int chunkX, int chunkZ) { Engine requiredEngine = Objects.requireNonNull(engine, "engine"); if (!requiredEngine.getComplex().allowsNewGenerationChunk(chunkX, chunkZ)) { @@ -300,12 +397,10 @@ public final class GenerationSemanticQueries { HydrologyFeatureType type, int blockX, int blockZ, - int maximumDistance - ) { + int maximumDistance, + BooleanSupplier running + ) throws HydrologySearchTimeoutException { HydrologyRuntime runtime = engine.getComplex().getHydrologyRuntime(); - if (runtime == null || !runtime.enabled()) { - return null; - } Map eligibleChunks = new HashMap<>(); TransitionDisplacementField displacement = engine.getComplex().getTransitionDisplacement(); Predicate eligibility = feature -> (displacement == null @@ -317,11 +412,13 @@ public final class GenerationSemanticQueries { blockZ, HydrologyFeatureQuery.of(type), maximumDistance, - eligibility + eligibility, + running ).orElse(null); - if (feature == null) { - return null; - } + return feature == null ? null : activeResult(engine, history, feature); + } + + private static RiverResult activeResult(Engine engine, GenerationHistory history, HydrologyFeatureRef feature) { OptionalLong activationId = history == null ? OptionalLong.empty() : OptionalLong.of(history.activeActivation().activationId()); @@ -379,4 +476,25 @@ public final class GenerationSemanticQueries { activationId = Objects.requireNonNull(activationId, "activationId"); } } + + public sealed interface RiverSearch { + record Found(RiverResult feature) implements RiverSearch { + public Found { + Objects.requireNonNull(feature, "feature"); + } + } + + record Missing(String message) implements RiverSearch { + public Missing { + Objects.requireNonNull(message, "message"); + } + } + + record Stopped(Optional nearestSoFar, String message) implements RiverSearch { + public Stopped { + Objects.requireNonNull(nearestSoFar, "nearestSoFar"); + Objects.requireNonNull(message, "message"); + } + } + } } diff --git a/core/src/main/java/art/arcane/iris/world/history/TransitionBoundarySampler.java b/core/src/main/java/art/arcane/iris/world/history/TransitionBoundarySampler.java index c0bac2e4f..e22703820 100644 --- a/core/src/main/java/art/arcane/iris/world/history/TransitionBoundarySampler.java +++ b/core/src/main/java/art/arcane/iris/world/history/TransitionBoundarySampler.java @@ -114,11 +114,9 @@ final class TransitionBoundarySampler { Math.min(distance, terrainWidth), terrainWidth ); - double hydrologyWeight = newEpochWeight; return new TransitionGenerationPlan.TerrainSample( Math.min(distance, searchWidth), newEpochWeight, - hydrologyWeight, nearest.signatures[0], weightedHeight(nearest, true), weightedHeight(nearest, false), diff --git a/core/src/main/java/art/arcane/iris/world/history/TransitionGenerationPlan.java b/core/src/main/java/art/arcane/iris/world/history/TransitionGenerationPlan.java index a90300a4f..b97dbacfd 100644 --- a/core/src/main/java/art/arcane/iris/world/history/TransitionGenerationPlan.java +++ b/core/src/main/java/art/arcane/iris/world/history/TransitionGenerationPlan.java @@ -88,10 +88,6 @@ public final class TransitionGenerationPlan { return terrainSampleAt(blockX, blockZ).newEpochWeight(); } - public double hydrologyWeightAt(int blockX, int blockZ) { - return terrainSampleAt(blockX, blockZ).hydrologyWeight(); - } - public boolean allowsNewDiscreteContentAt(int blockX, int blockZ) { return !boundary.isHistoricalBlock(blockX, blockZ); } @@ -191,7 +187,6 @@ public final class TransitionGenerationPlan { public record TerrainSample( double distanceToHistoricalTerrain, double newEpochWeight, - double hydrologyWeight, TerrainBoundarySignature nearestSignature, double historicalSurfaceHeight, double historicalOceanFloorHeight, @@ -204,9 +199,6 @@ public final class TransitionGenerationPlan { if (!Double.isFinite(newEpochWeight) || newEpochWeight < 0D || newEpochWeight > 1D) { throw new IllegalArgumentException("New epoch weight must be between zero and one"); } - if (!Double.isFinite(hydrologyWeight) || hydrologyWeight < 0D || hydrologyWeight > 1D) { - throw new IllegalArgumentException("Hydrology weight must be between zero and one"); - } if (nearestSignature != null && (!Double.isFinite(historicalSurfaceHeight) || !Double.isFinite(historicalOceanFloorHeight) @@ -217,11 +209,11 @@ public final class TransitionGenerationPlan { } static TerrainSample newTerrain(double distance) { - return new TerrainSample(distance, 1D, 1D, null, 0D, 0D, 0D); + return new TerrainSample(distance, 1D, null, 0D, 0D, 0D); } static TerrainSample historicalTerrain() { - return new TerrainSample(0D, 0D, 0D, null, 0D, 0D, 0D); + return new TerrainSample(0D, 0D, null, 0D, 0D, 0D); } public boolean hasHistoricalSignature() { diff --git a/core/src/main/java/art/arcane/iris/world/pregen/MedievalPregenMethod.java b/core/src/main/java/art/arcane/iris/world/pregen/MedievalPregenMethod.java index ae8f5be1a..044fff0df 100644 --- a/core/src/main/java/art/arcane/iris/world/pregen/MedievalPregenMethod.java +++ b/core/src/main/java/art/arcane/iris/world/pregen/MedievalPregenMethod.java @@ -62,7 +62,6 @@ public class MedievalPregenMethod implements PregeneratorMethod { private final Executor chunkIoExecutor; private final PregenSerialWorker chunkFlush; private volatile Engine cachedEngine; - private volatile boolean engineResolutionAttempted; private final AtomicBoolean closing = new AtomicBoolean(); private final PregenHydrology hydrology = new PregenHydrology(this::resolveEngine); @@ -99,10 +98,6 @@ public class MedievalPregenMethod implements PregeneratorMethod { if (cached != null) { return cached; } - if (engineResolutionAttempted) { - return null; - } - engineResolutionAttempted = true; try { if (!IrisToolbelt.isIrisWorld(world)) { return null; diff --git a/core/src/main/java/art/arcane/iris/world/storage/matter/HydrologyCaveMatter.java b/core/src/main/java/art/arcane/iris/world/storage/matter/HydrologyCaveMatter.java index 9f4dd302a..af1f7a0e2 100644 --- a/core/src/main/java/art/arcane/iris/world/storage/matter/HydrologyCaveMatter.java +++ b/core/src/main/java/art/arcane/iris/world/storage/matter/HydrologyCaveMatter.java @@ -29,19 +29,20 @@ public final class HydrologyCaveMatter extends RawMatter { public void writeNode(HydrologyCaveCell hydrology, DataOutputStream output) throws IOException { output.writeByte(actionCode(hydrology.action())); output.writeUTF(hydrology.fluidProfileKey()); - output.writeUTF(hydrology.floodedBiomeKey()); + output.writeUTF(""); } @Override public HydrologyCaveCell readNode(DataInputStream input) throws IOException { HydrologyCaveAction action = actionFromCode(input.readUnsignedByte()); - return new HydrologyCaveCell(action, input.readUTF(), input.readUTF()); + String fluidProfileKey = input.readUTF(); + input.readUTF(); + return new HydrologyCaveCell(action, fluidProfileKey); } private int actionCode(HydrologyCaveAction action) { return switch (action) { case WET_SOURCE -> 1; - case FALLING_FLUID -> 2; case DRY_AIR -> 3; case SEAL_GUARD -> 4; case POOL_SOURCE -> 5; @@ -50,8 +51,7 @@ public final class HydrologyCaveMatter extends RawMatter { private HydrologyCaveAction actionFromCode(int code) throws IOException { return switch (code) { - case 1 -> HydrologyCaveAction.WET_SOURCE; - case 2 -> HydrologyCaveAction.FALLING_FLUID; + case 1, 2 -> HydrologyCaveAction.WET_SOURCE; case 3 -> HydrologyCaveAction.DRY_AIR; case 4 -> HydrologyCaveAction.SEAL_GUARD; case 5 -> HydrologyCaveAction.POOL_SOURCE; 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 new file mode 100644 index 000000000..6e4535762 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/PersistedCodesTest.java @@ -0,0 +1,129 @@ +package art.arcane.iris.generation.hydrology; + +import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; +import art.arcane.iris.generation.hydrology.water.PondKind; +import art.arcane.iris.generation.hydrology.water.ReachStyle; +import org.junit.Test; + +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.IntFunction; +import java.util.function.ToIntFunction; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class PersistedCodesTest { + private static final Map FEATURE_TYPE_CODES = Map.ofEntries( + Map.entry(HydrologyFeatureType.STREAM, 0), + Map.entry(HydrologyFeatureType.RIVER, 1), + Map.entry(HydrologyFeatureType.MAJOR_RIVER, 2), + Map.entry(HydrologyFeatureType.CASCADE, 3), + Map.entry(HydrologyFeatureType.WATERFALL, 4), + Map.entry(HydrologyFeatureType.MOUTH, 5), + Map.entry(HydrologyFeatureType.POND, 6), + Map.entry(HydrologyFeatureType.LAKE, 7), + Map.entry(HydrologyFeatureType.DAM, 8), + Map.entry(HydrologyFeatureType.SEA_INLET, 9), + Map.entry(HydrologyFeatureType.CAVE_POOL, 10)); + private static final Map REACH_STYLE_CODES = Map.of( + ReachStyle.RUN, 0, + ReachStyle.RIFFLE, 1, + ReachStyle.CASCADE, 2, + ReachStyle.WATERFALL, 3, + ReachStyle.POND_OUTLET, 4, + ReachStyle.MOUTH, 5); + private static final Map POND_KIND_CODES = Map.of( + PondKind.NATURAL, 0, + PondKind.SEEDED, 1, + PondKind.CHAINED, 2, + PondKind.LAKE, 3); + + @Test + public void codesAreUniqueAndPinned() { + assertPinned(HydrologyFeatureType.class, FEATURE_TYPE_CODES, HydrologyFeatureType::code, HydrologyFeatureType::fromCode); + assertPinned(ReachStyle.class, REACH_STYLE_CODES, ReachStyle::code, ReachStyle::fromCode); + assertPinned(PondKind.class, POND_KIND_CODES, PondKind::code, PondKind::fromCode); + } + + @Test + public void unknownCodesFailClosed() { + assertUnknown("HydrologyFeatureType", FEATURE_TYPE_CODES, HydrologyFeatureType::fromCode); + assertUnknown("ReachStyle", REACH_STYLE_CODES, ReachStyle::fromCode); + assertUnknown("PondKind", POND_KIND_CODES, PondKind::fromCode); + } + + @Test + public void conflictingCodesAreRejected() { + try { + PersistedCodes.of(SharedCode.class, SharedCode::code); + fail("two constants share code 7"); + } catch (IllegalStateException expected) { + assertTrue(expected.getMessage(), expected.getMessage().contains("SharedCode") && expected.getMessage().contains("7")); + } + try { + PersistedCodes.of(WideCode.class, WideCode::code); + fail("code 256 does not fit one byte"); + } catch (IllegalStateException expected) { + assertTrue(expected.getMessage(), expected.getMessage().contains("WideCode") && expected.getMessage().contains("256")); + } + } + + private static > void assertPinned(Class type, Map pins, ToIntFunction code, + IntFunction fromCode) { + assertEquals(type.getSimpleName() + " constants need a pinned code", EnumSet.allOf(type), pins.keySet()); + Set seen = new HashSet<>(); + for (E constant : type.getEnumConstants()) { + int pinned = pins.get(constant); + assertEquals(type.getSimpleName() + "." + constant.name(), pinned, code.applyAsInt(constant)); + assertTrue(type.getSimpleName() + " reuses code " + pinned, seen.add(pinned)); + assertSame(constant, fromCode.apply(pinned)); + } + } + + private static > void assertUnknown(String name, Map pins, IntFunction fromCode) { + int unused = Collections.max(pins.values()) + 1; + for (int code : new int[]{-1, unused, 256}) { + try { + fromCode.apply(code); + fail(name + " decoded unknown code " + code); + } catch (IllegalStateException expected) { + assertTrue(expected.getMessage(), expected.getMessage().contains(name) && expected.getMessage().contains(Integer.toString(code))); + } + } + } + + private enum SharedCode { + FIRST(7), + SECOND(7); + + private final int code; + + SharedCode(int code) { + this.code = code; + } + + private int code() { + return code; + } + } + + private enum WideCode { + ONLY(256); + + private final int code; + + WideCode(int code) { + this.code = code; + } + + private int code() { + return code; + } + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveStorageTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveStorageTest.java index 21899905e..366a82375 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveStorageTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/cave/HydrologyCaveStorageTest.java @@ -19,7 +19,7 @@ public class HydrologyCaveStorageTest { MantleChunk chunk = mock(MantleChunk.class); Matter matter = mock(Matter.class); MatterSlice slice = mock(MatterSlice.class); - HydrologyCaveCell expected = HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE); + HydrologyCaveCell expected = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"); when(chunk.exists(2)).thenReturn(true); when(chunk.get(2)).thenReturn(matter); when(matter.hasSlice(HydrologyCaveCell.class)).thenReturn(true); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDefaultsTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDefaultsTest.java index 02070f8bc..81d3dc62b 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDefaultsTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDefaultsTest.java @@ -83,6 +83,7 @@ public class IrisHydrologyDefaultsTest { assertNull(policy.getDecorators()); assertNull(policy.getShoreBiomes()); assertNull(policy.getShoreBiomeWidth()); + assertNull(policy.getWetness()); } @Test diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/EngineFixture.java b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/EngineFixture.java index 36e82d61a..346f4e3ae 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/EngineFixture.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/EngineFixture.java @@ -108,11 +108,17 @@ final class EngineFixture implements AutoCloseable { + ",\"seed\":" + Math.abs(key.hashCode()) + ",\"composite\":" + composite.strip() + "}"); } - private static void biome(Path pack, String key, String generators, String extra) throws IOException { + static void biome(Path pack, String key, String generators, String extra) throws IOException { Files.writeString(pack.resolve("biomes/" + key + ".json"), "{\"layers\":[{\"palette\":[{\"block\":\"minecraft:stone\"}]}],\"generators\":" + generators + extra.strip() + "}"); } + static void extend(Path pack, String key, String extra) throws IOException { + Path file = pack.resolve("biomes/" + key + ".json"); + String json = Files.readString(file).strip(); + Files.writeString(file, json.substring(0, json.length() - 1) + extra.strip() + "}"); + } + @Override public void close() { complex.close(); 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 new file mode 100644 index 000000000..90718a1ab --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/HydrologyFeatureSearchTest.java @@ -0,0 +1,264 @@ +package art.arcane.iris.generation.hydrology.engine; + +import art.arcane.iris.generation.hydrology.config.IrisHydrology; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier; +import art.arcane.iris.generation.hydrology.plan.HydrologyPlanCache; +import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.hydrology.plan.RegionKey; +import art.arcane.iris.generation.hydrology.plan.RegionPlan; +import art.arcane.iris.generation.hydrology.plan.WindowKey; +import art.arcane.iris.generation.hydrology.plan.WindowPlan; +import art.arcane.iris.generation.hydrology.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.water.HydrologyTier; +import art.arcane.iris.generation.hydrology.water.Reach; +import art.arcane.iris.generation.hydrology.water.ReachStyle; +import art.arcane.iris.testsupport.FakeHydrology; +import art.arcane.volmlib.util.collection.KList; +import org.junit.After; +import org.junit.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class HydrologyFeatureSearchTest { + private static final long SEED = 1337L; + private static final long CHANNEL = 0x4348414eL; + private static final Duration LONG_TIMEOUT = Duration.ofSeconds(30L); + + private final List pools = new ArrayList<>(); + private final List caches = new ArrayList<>(); + private final CountDownLatch gate = new CountDownLatch(1); + + @After + public void shutDown() { + gate.countDown(); + for (HydrologyPlanCache cache : caches) { + cache.close(); + } + for (ExecutorService pool : pools) { + pool.shutdownNow(); + } + } + + @Test(timeout = 20_000L) + public void disabledTypeAnswersImmediately() throws Exception { + HydrologySettings settings = settings(config -> config.getLakes().setEnabled(false)); + Planners planners = new Planners(gate); + HydrologyPlanCache cache = cache(settings, planners); + + assertEquals(Optional.empty(), search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE)) + .nearest(LONG_TIMEOUT, () -> true)); + assertEquals(Optional.empty(), search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE, HydrologyFeatureType.DAM)) + .nearest(LONG_TIMEOUT, () -> true)); + assertEquals(0, planners.calls.get()); + assertEquals(Optional.of("hydrology.lakes is disabled"), HydrologyFeatureSearch.disabledReason(settings, HydrologyFeatureType.LAKE)); + assertEquals(Optional.of("hydrology.ponds.dams is disabled"), HydrologyFeatureSearch.disabledReason(settings, HydrologyFeatureType.DAM)); + assertEquals(Optional.empty(), HydrologyFeatureSearch.disabledReason(settings, HydrologyFeatureType.POND)); + assertEquals(Optional.empty(), HydrologyFeatureSearch.disabledReason(settings, HydrologyFeatureType.WATERFALL)); + + HydrologySettings dry = settings(config -> { + config.getPonds().getNatural().setEnabled(false); + config.getPonds().getSeeded().setEnabled(false); + config.getPonds().getDams().setEnabled(true); + config.getUnderground().getSeaInlets().setEnabled(false); + config.getUnderground().getCavePools().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.cavePools is disabled"), + HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.CAVE_POOL)); + assertEquals(Optional.empty(), HydrologyFeatureSearch.disabledReason(dry, HydrologyFeatureType.LAKE)); + assertEquals(Optional.of("hydrology is off"), FakeHydrology.disabled().unavailable(HydrologyFeatureType.RIVER)); + } + + @Test(timeout = 20_000L) + public void searchStopsAtTheTimeout() { + HydrologySettings settings = settings(config -> { + }); + Planners planners = new Planners(gate); + HydrologyPlanCache cache = cache(settings, planners); + Duration timeout = Duration.ofMillis(200L); + HydrologyFeatureSearch search = search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.POND)); + + long started = System.nanoTime(); + HydrologySearchTimeoutException stopped = assertThrows(HydrologySearchTimeoutException.class, + () -> search.nearest(timeout, () -> true)); + + assertTrue(System.nanoTime() - started >= timeout.toNanos()); + assertTrue(planners.calls.get() > 0); + assertEquals(Optional.empty(), stopped.nearestSoFar()); + } + + @Test(timeout = 20_000L) + public void timedOutSearchKeepsTheNearestFeatureFoundSoFar() { + HydrologySettings settings = settings(config -> { + }); + Planners planners = new Planners(gate); + planners.channelTier = settings.tiers().getFirst(); + HydrologyPlanCache cache = cache(settings, planners); + + HydrologySearchTimeoutException stopped = assertThrows(HydrologySearchTimeoutException.class, + () -> search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM)).nearest(Duration.ofMillis(200L), () -> true)); + + assertEquals(Optional.of(new HydrologyFeatureRef(CHANNEL, HydrologyFeatureType.STREAM, 100, 70, 100)), stopped.nearestSoFar()); + } + + @Test(timeout = 20_000L) + public void boundedRadiusFinishesWhenNothingNearIsEligible() throws Exception { + HydrologySettings settings = settings(config -> { + }); + Planners planners = new Planners(gate); + planners.channelTier = settings.tiers().getFirst(); + planners.openRing = 2; + HydrologyPlanCache cache = cache(settings, planners); + Duration timeout = Duration.ofSeconds(2L); + + assertEquals(Optional.empty(), new HydrologyFeatureSearch(settings, cache, 0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM), + feature -> false, 50).nearest(timeout, () -> true)); + assertThrows(HydrologySearchTimeoutException.class, () -> new HydrologyFeatureSearch(settings, cache, 0, 0, + HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM), feature -> false, 7168).nearest(timeout, () -> true)); + } + + @Test(timeout = 20_000L) + public void cancelledSearchStopsWaitingForPlans() { + HydrologySettings settings = settings(config -> { + }); + Planners planners = new Planners(gate); + HydrologyPlanCache cache = cache(settings, planners); + AtomicInteger checks = new AtomicInteger(); + + assertThrows(CancellationException.class, () -> search(settings, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER)) + .nearest(LONG_TIMEOUT, () -> checks.incrementAndGet() < 3)); + assertTrue(checks.get() >= 3); + } + + @Test(timeout = 20_000L) + public void oneTierPacksMatchStream() throws Exception { + HydrologySettings oneTier = settings(config -> config.setTiers(new KList<>(new IrisHydrologyTier()))); + HydrologyTier only = oneTier.tiers().getFirst(); + Planners planners = new Planners(null); + planners.channelTier = only; + HydrologyPlanCache cache = cache(oneTier, planners); + + assertEquals(HydrologyFeatureType.STREAM, HydrologyFeatureSearch.channelType(oneTier, only)); + assertEquals(new HydrologyFeatureRef(CHANNEL, HydrologyFeatureType.STREAM, 100, 70, 100), + search(oneTier, cache, HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM)).nearest(LONG_TIMEOUT, () -> true).orElseThrow()); + assertEquals(Optional.of("it has no river tier"), HydrologyFeatureSearch.disabledReason(oneTier, HydrologyFeatureType.RIVER)); + assertEquals(Optional.of("it has no major river tier"), HydrologyFeatureSearch.disabledReason(oneTier, HydrologyFeatureType.MAJOR_RIVER)); + + HydrologySettings creek = settings(config -> config.setTiers(new KList<>(new IrisHydrologyTier().setName("creek")))); + assertEquals(HydrologyFeatureType.STREAM, HydrologyFeatureSearch.channelType(creek, creek.tiers().getFirst())); + + HydrologySettings twoTier = settings(config -> config.setTiers(new KList<>(new IrisHydrologyTier(), + new IrisHydrologyTier().setName("river").setMinCatchment(20000D)))); + assertEquals(HydrologyFeatureType.STREAM, HydrologyFeatureSearch.channelType(twoTier, twoTier.tiers().getFirst())); + assertEquals(HydrologyFeatureType.RIVER, HydrologyFeatureSearch.channelType(twoTier, twoTier.majorTier())); + assertEquals(Optional.of("it has no major river tier"), HydrologyFeatureSearch.disabledReason(twoTier, HydrologyFeatureType.MAJOR_RIVER)); + + HydrologySettings ranked = settings(config -> config.setTiers(new KList<>(new IrisHydrologyTier().setName("brook"), + new IrisHydrologyTier().setName("channel").setMinCatchment(20000D), + new IrisHydrologyTier().setName("trunk").setMinCatchment(320000D)))); + assertEquals(HydrologyFeatureType.STREAM, HydrologyFeatureSearch.channelType(ranked, ranked.tiers().get(0))); + assertEquals(HydrologyFeatureType.RIVER, HydrologyFeatureSearch.channelType(ranked, ranked.tiers().get(1))); + assertEquals(HydrologyFeatureType.MAJOR_RIVER, HydrologyFeatureSearch.channelType(ranked, ranked.tiers().get(2))); + } + + private HydrologyPlanCache cache(HydrologySettings settings, Planners planners) { + ExecutorService pool = Executors.newFixedThreadPool(2, runnable -> { + Thread thread = new Thread(runnable, "feature-search-planner"); + thread.setDaemon(true); + return thread; + }); + pools.add(pool); + HydrologyPlanCache cache = new HydrologyPlanCache(settings, planners::region, planners::window, pool, () -> false); + caches.add(cache); + return cache; + } + + private static HydrologyFeatureSearch search(HydrologySettings settings, HydrologyPlanCache cache, HydrologyFeatureQuery query) { + return new HydrologyFeatureSearch(settings, cache, 0, 0, query, feature -> true, 2048); + } + + private static HydrologySettings settings(Consumer change) { + IrisHydrology config = new IrisHydrology().setEnabled(true).setPersist(false); + change.accept(config); + return HydrologySettings.compile(config, SEED, 40, 0, 384); + } + + private static final class Planners { + private final CountDownLatch gate; + private final AtomicInteger calls = new AtomicInteger(); + private volatile HydrologyTier channelTier; + private volatile int openRing = -1; + + private Planners(CountDownLatch gate) { + this.gate = gate; + } + + RegionPlan region(RegionKey key) { + calls.incrementAndGet(); + return new RegionPlan(key, List.of(), List.of()); + } + + WindowPlan window(WindowKey key, List plans) { + calls.incrementAndGet(); + if (channelTier != null && key.equals(new WindowKey(0, 0))) { + return new WindowPlan(key, List.of(channel(channelTier)), List.of(), List.of()); + } + if (Math.max(Math.abs(key.wx()), Math.abs(key.wz())) > openRing) { + hold(); + } + return new WindowPlan(key, List.of(), List.of(), List.of()); + } + + private void hold() { + if (gate == null) { + return; + } + try { + gate.await(60L, TimeUnit.SECONDS); + } catch (InterruptedException interruption) { + Thread.currentThread().interrupt(); + throw new CancellationException("Planning interrupted."); + } + } + + private static Reach channel(HydrologyTier tier) { + int points = 3; + float[] xs = new float[points]; + float[] zs = new float[points]; + int[] grade = new int[points]; + float[] halfWidth = new float[points]; + float[] depth = new float[points]; + ReachStyle[] style = new ReachStyle[points]; + for (int index = 0; index < points; index++) { + xs[index] = 100f + index * 50f; + zs[index] = 100f; + grade[index] = 70; + halfWidth[index] = 1f; + depth[index] = 1f; + style[index] = ReachStyle.RUN; + } + return new Reach(CHANNEL, tier, 0L, xs, zs, grade, halfWidth, depth, style, 2000f); + } + } +} 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 cbf79be3f..93abba8d8 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 @@ -29,10 +29,14 @@ import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.PreparedHydrologyCacheIdentity; import art.arcane.iris.generation.runtime.SeedManager; import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.pack.loading.ResourceLoader; import art.arcane.iris.spi.LogLevel; import art.arcane.iris.testsupport.FakeHydrology; import art.arcane.iris.testsupport.PlatformLeakGuard; import art.arcane.iris.world.IrisWorld; +import art.arcane.volmlib.util.collection.KList; import org.junit.After; import org.junit.ClassRule; import org.junit.Rule; @@ -58,13 +62,16 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; +import java.util.function.Predicate; import java.util.stream.Stream; import static org.junit.Assert.assertArrayEquals; @@ -101,6 +108,8 @@ public class HydrologyRuntimeTest { private static final long LAKE = 0x4c414b45L; private static final long RIVER = 0x52495645L; private static final long INLET = 0x494e4c4554L; + private static final Predicate ANY = feature -> true; + private static final BooleanSupplier RUNNING = () -> true; @ClassRule public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); @@ -295,24 +304,29 @@ public class HydrologyRuntimeTest { FakePlanners planners = new FakePlanners(settings()); HydrologyRuntime runtime = runtime(planners, () -> false); - HydrologyFeatureRef pond = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048).orElseThrow(); + HydrologyFeatureRef pond = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048, ANY, RUNNING) + .orElseThrow(); assertEquals(new HydrologyFeatureRef(POND, HydrologyFeatureType.POND, 2, 70, 2), pond); assertEquals(0, planners.windowCalls(new WindowKey(3, 3))); assertEquals(new HydrologyFeatureRef(POND + 1, HydrologyFeatureType.POND, 300, 70, 300), - runtime.nearestFeature(301, 299, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64).orElseThrow()); - HydrologyFeatureRef river = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER), 2048).orElseThrow(); + runtime.nearestFeature(301, 299, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64, ANY, RUNNING).orElseThrow()); + HydrologyFeatureRef river = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER), 2048, ANY, RUNNING) + .orElseThrow(); assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.RIVER, 1000, 80, 200), river); - HydrologyFeatureRef fall = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.WATERFALL), 2048).orElseThrow(); + HydrologyFeatureRef fall = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.WATERFALL), 2048, ANY, + RUNNING).orElseThrow(); assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.WATERFALL, 1050, 75, 200), fall); HydrologyFeatureQuery water = HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER, HydrologyFeatureType.POND); - assertEquals(pond, runtime.nearestFeature(0, 0, water, 2048).orElseThrow()); - assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.RIVER, 1100, 70, 200), runtime.nearestFeature(1100, 100, water, 2048) - .orElseThrow()); - assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2)); + assertEquals(pond, runtime.nearestFeature(0, 0, water, 2048, ANY, RUNNING).orElseThrow()); + assertEquals(new HydrologyFeatureRef(RIVER, HydrologyFeatureType.RIVER, 1100, 70, 200), + runtime.nearestFeature(1100, 100, water, 2048, ANY, RUNNING).orElseThrow()); + assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2, ANY, RUNNING)); assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, - HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM, HydrologyFeatureType.MAJOR_RIVER), 2048)); - assertEquals(FAR_POND, runtime.nearestFeature(1700, 150, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 512).orElseThrow().id()); - HydrologyFeatureRef lake = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 4096).orElseThrow(); + HydrologyFeatureQuery.of(HydrologyFeatureType.STREAM, HydrologyFeatureType.MAJOR_RIVER), 2048, ANY, RUNNING)); + assertEquals(FAR_POND, runtime.nearestFeature(1700, 150, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 512, ANY, RUNNING) + .orElseThrow().id()); + HydrologyFeatureRef lake = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 4096, ANY, RUNNING) + .orElseThrow(); assertEquals(new HydrologyFeatureRef(LAKE, HydrologyFeatureType.LAKE, 2500, 90, 2500), lake); } @@ -347,13 +361,16 @@ public class HydrologyRuntimeTest { written.put(((long) x << 40) ^ ((long) (int) call.getArgument(2) << 20) ^ (int) call.getArgument(1), cell); return null; }).when(writer).setData(anyInt(), anyInt(), anyInt(), any(HydrologyCaveCell.class)); - new SeaInletRasterizer().write(tail.getFirst(), 68, 25, writer, HydrologyCaveCell.SEA_FLUID, "", SeaInletRasterizer.SubterrainFluid.NOWHERE); + new SeaInletRasterizer().write(tail.getFirst(), 68, 25, writer, HydrologyCaveCell.SEA_FLUID, SeaInletRasterizer.SubterrainFluid.NOWHERE, + SeaInletRasterizer.HistoricalChunks.NONE); assertTrue("the chunk past the owner window writes inlet water", written.values().stream().anyMatch(cell -> cell.action() == HydrologyCaveAction.WET_SOURCE)); - HydrologyFeatureRef nearest = runtime.nearestFeature(1050, 405, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 512).orElseThrow(); + HydrologyFeatureRef nearest = runtime.nearestFeature(1050, 405, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 512, ANY, + RUNNING).orElseThrow(); assertEquals(new HydrologyFeatureRef(INLET, HydrologyFeatureType.SEA_INLET, 1048, 40, 400), nearest); - assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 64)); + assertEquals(Optional.empty(), + runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 64, ANY, RUNNING)); assertEquals(List.of(FakePlanners.inlet()), runtime.planPreview(900, 300, 1100, 500).inlets()); assertEquals(List.of(), FakeHydrology.disabled().inlets(0, 0)); } @@ -364,11 +381,11 @@ public class HydrologyRuntimeTest { HydrologyRuntime runtime = runtime(planners, () -> false); HydrologyFeatureRef seeded = runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048, - feature -> feature.id() != POND).orElseThrow(); + feature -> feature.id() != POND, RUNNING).orElseThrow(); assertEquals(POND + 1, seeded.id()); assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 2048, - feature -> false)); + feature -> false, RUNNING)); } @Test(timeout = 180_000L) @@ -801,7 +818,7 @@ public class HydrologyRuntimeTest { AtomicBoolean main = new AtomicBoolean(true); HydrologyRuntime runtime = runtime(planners, pool, main::get); try { - runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64); + runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64, ANY, RUNNING); fail("A feature search on the main thread must refuse"); } catch (IllegalStateException expected) { assertTrue(expected.getMessage(), expected.getMessage().contains("main thread")); @@ -811,20 +828,20 @@ public class HydrologyRuntimeTest { assertEquals(0, planners.windowOrder().size()); assertEquals(0, planners.regionArrivals.get()); - assertEquals(Optional.empty(), runtime.nearestFeature(10_000, 10_000, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64)); + assertEquals(Optional.empty(), + runtime.nearestFeature(10_000, 10_000, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64, ANY, RUNNING)); assertEquals(25, planners.windowOrder().size()); CountDownLatch regions = new CountDownLatch(1); planners.regionGate = regions; int before = planners.regionArrivals.get(); - AtomicReference> lake = new AtomicReference<>(); - Thread search = new Thread(() -> lake.set(runtime.nearestFeature(-20_000, -20_000, - HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 64))); + FutureTask> lake = new FutureTask<>(() -> runtime.nearestFeature(-20_000, -20_000, + HydrologyFeatureQuery.of(HydrologyFeatureType.LAKE), 64, ANY, RUNNING)); + Thread search = new Thread(lake); search.start(); await(() -> planners.regionArrivals.get() - before >= 4, "every lake region to plan at once"); regions.countDown(); - search.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); - assertEquals(Optional.empty(), lake.get()); + assertEquals(Optional.empty(), lake.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); } @Test(timeout = 180_000L) @@ -848,22 +865,32 @@ public class HydrologyRuntimeTest { } @Test - public void biomeFluidPoliciesAreCheckedWhenTheEngineLoads() { + public void caveFluidPoliciesAreCheckedWhenTheEngineLoads() { + IrisDimension dimension = new IrisDimension(); + IrisRegion region = new IrisRegion(); IrisBiome plain = new IrisBiome(); - IrisBiome flooded = new IrisBiome(); - flooded.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("water")); - IrisBiome magma = new IrisBiome(); - magma.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("magma")); + IrisBiome flooded = new IrisBiome().setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("water")); + IrisBiome magma = new IrisBiome().setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("magma")); - assertFalse(HydrologyRuntime.requireBiomeFluids(List.of(plain), settings())); - assertTrue(HydrologyRuntime.requireBiomeFluids(List.of(plain, flooded), settings())); + assertFalse(HydrologyRuntime.requireCaveFluids(dimension, List.of(region), List.of(plain), settings())); + assertTrue(HydrologyRuntime.requireCaveFluids(dimension, List.of(region), List.of(plain, flooded), settings())); IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, - () -> HydrologyRuntime.requireBiomeFluids(List.of(plain, magma), settings())); + () -> HydrologyRuntime.requireCaveFluids(dimension, List.of(region), List.of(plain, magma), settings())); + assertTrue(failure.getMessage(), failure.getMessage().contains("'magma'")); + + region.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("water")); + assertTrue(HydrologyRuntime.requireCaveFluids(dimension, List.of(region), List.of(plain), settings())); + region.setHydrologyPolicy(null); + dimension.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("water")); + assertTrue(HydrologyRuntime.requireCaveFluids(dimension, List.of(region), List.of(plain), settings())); + dimension.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("magma")); + failure = assertThrows(IllegalArgumentException.class, + () -> HydrologyRuntime.requireCaveFluids(dimension, List.of(region), List.of(plain), settings())); assertTrue(failure.getMessage(), failure.getMessage().contains("'magma'")); } @Test - public void createStaysDisabledWithoutHydrology() { + public void createStaysDisabledWithoutHydrology() throws Exception { Engine engine = mock(Engine.class); IrisComplex complex = mock(IrisComplex.class); IrisDimension dimension = new IrisDimension(); @@ -879,7 +906,52 @@ public class HydrologyRuntimeTest { } @Test - public void zeroDensitySkipsRuntimePlanningAfterValidatingSettings() { + @SuppressWarnings("unchecked") + public void createChecksEveryPolicyFluidWhetherCavePoolsAreOnOrOff() throws Exception { + IrisDimension dimension = new IrisDimension().setRegions(new KList<>("tropical")); + dimension.setLoadKey("main"); + dimension.setHydrology(new IrisHydrology().setEnabled(true).setDensity(0D)); + IrisRegion tropical = new IrisRegion().setLandBiomes(new KList<>("volcanoes")); + tropical.setLoadKey("tropical"); + IrisBiome volcanoes = new IrisBiome().setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("magma")); + volcanoes.setLoadKey("volcanoes"); + IrisData data = mock(IrisData.class); + ResourceLoader regions = mock(ResourceLoader.class); + ResourceLoader biomes = mock(ResourceLoader.class); + when(data.getRegionLoader()).thenReturn(regions); + when(data.getBiomeLoader()).thenReturn(biomes); + when(regions.load("tropical")).thenReturn(tropical); + when(biomes.load("volcanoes")).thenReturn(volcanoes); + Engine engine = mock(Engine.class); + when(engine.getDimension()).thenReturn(dimension); + when(engine.getData()).thenReturn(data); + when(engine.getSeedManager()).thenReturn(new SeedManager(1337L)); + when(engine.getHeight()).thenReturn(384); + IrisComplex complex = mock(IrisComplex.class); + + IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, () -> HydrologyRuntime.create(engine, complex)); + assertTrue(failure.getMessage(), failure.getMessage().contains("'magma'") && failure.getMessage().contains("volcanoes")); + + dimension.getHydrology().getUnderground().getCavePools().setEnabled(false); + assertEquals("Unknown hydrology fluid profile 'magma' in biome 'volcanoes' hydrologyPolicy.fluid; fluids defines [water]", + assertThrows(IllegalArgumentException.class, () -> HydrologyRuntime.create(engine, complex)).getMessage()); + + volcanoes.setHydrologyPolicy(null); + tropical.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("magma")); + assertEquals("Unknown hydrology fluid profile 'magma' in region 'tropical' hydrologyPolicy.fluid; fluids defines [water]", + assertThrows(IllegalArgumentException.class, () -> HydrologyRuntime.create(engine, complex)).getMessage()); + + tropical.setHydrologyPolicy(null); + dimension.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("magma")); + assertEquals("Unknown hydrology fluid profile 'magma' in dimension 'main' hydrologyPolicy.fluid; fluids defines [water]", + assertThrows(IllegalArgumentException.class, () -> HydrologyRuntime.create(engine, complex)).getMessage()); + + dimension.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("water")); + assertDisabled(HydrologyRuntime.create(engine, complex)); + } + + @Test + public void zeroDensitySkipsRuntimePlanningAfterValidatingSettings() throws Exception { Engine engine = mock(Engine.class); IrisComplex complex = mock(IrisComplex.class); IrisDimension dimension = new IrisDimension(); @@ -1014,13 +1086,14 @@ public class HydrologyRuntimeTest { } } - private static void assertDisabled(HydrologyRuntime runtime) { + private static void assertDisabled(HydrologyRuntime runtime) throws TimeoutException { assertFalse(runtime.enabled()); + assertEquals(Optional.of("hydrology is off"), runtime.unavailable(HydrologyFeatureType.RIVER)); assertEquals(0L, runtime.previewRevision()); assertSame(ChunkWaterRaster.EMPTY, runtime.raster(0, 0)); assertSame(ChunkWaterRaster.EMPTY, runtime.rasterSnapshot(0, 0)); assertSame(ChunkWaterRaster.EMPTY, runtime.rasterAt(0, 0)); - assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64)); + assertEquals(Optional.empty(), runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.POND), 64, ANY, RUNNING)); assertTrue(runtime.prepareWindowsAround(0, 0, 0, 0, 1).isDone()); try (HydrologyPregeneration pregeneration = runtime.openPregeneration()) { pregeneration.prepare(List.of(new long[]{0L, 0L})); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSourceTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSourceTest.java index 9ec081021..9298015e3 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSourceTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSourceTest.java @@ -3,15 +3,29 @@ package art.arcane.iris.generation.hydrology.engine; import art.arcane.iris.generation.bake.BakePlane; import art.arcane.iris.generation.bake.ChunkBakeCache; import art.arcane.iris.generation.bake.GeneratorEvaluations; +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.hydrology.config.IrisFluidProfile; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness; +import art.arcane.iris.generation.hydrology.grid.Basin; +import art.arcane.iris.generation.hydrology.grid.BasinExtractor; +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.grid.HydrologyTerrainSource; +import art.arcane.iris.generation.hydrology.grid.PriorityFlood; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.hydrology.plan.WindowKey; +import art.arcane.iris.generation.hydrology.water.CupSet; +import art.arcane.iris.generation.hydrology.water.Pond; +import art.arcane.iris.generation.hydrology.water.PondPlanner; import art.arcane.iris.generation.stream.ChunkFillableDoubleStream2D; import art.arcane.iris.generation.terrain.InferredType; +import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.testsupport.PlatformLeakGuard; +import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.stream.ProceduralStream; import org.junit.After; import org.junit.ClassRule; @@ -20,14 +34,18 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.nio.file.Path; +import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -155,15 +173,18 @@ public class IrisHydrologyTerrainSourceTest { boolean alpha = fixture.complex.getRegionStream().get(x, z).getLoadKey().equals("alpha"); String at = x + "," + z; assertEquals(at, alpha ? "water" : null, source.channelFluid(x, z)); + assertEquals(at, !meadow, samples.climateZoned()[index]); if (meadow) { assertEquals(at, 2f, samples.rainfall()[index], 0f); assertEquals(at, alpha ? 3f : 1f, samples.pondDensity()[index], 0f); + assertEquals(at, 1f, samples.wetness()[index], 0f); kept++; continue; } boolean zoneDry = samples.rainfall()[index] == 0f; assertEquals(at, zoneDry ? 0f : 0.5f, samples.rainfall()[index], 0f); assertEquals(at, zoneDry ? 0f : alpha ? 3f : 1f, samples.pondDensity()[index], 0f); + assertEquals(at, zoneDry ? 0f : 1f, samples.wetness()[index], 0f); if (zoneDry) { dry++; } else { @@ -175,6 +196,323 @@ public class IrisHydrologyTerrainSourceTest { } } + @Test + public void wetnessClampKeepsSwampsWet() throws Exception { + Path pack = childPack(""); + int[][] grid = childGrid(); + int[] xs = grid[0]; + int[] zs = grid[1]; + try (EngineFixture.Environment ignored = EngineFixture.environment(); EngineFixture fixture = new EngineFixture(pack)) { + HydrologySettings settings = climateSettings(fixture); + HydrologySampleBuffer zoned = new HydrologySampleBuffer(xs.length); + new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, null, 1, HydrologyBinding.UNBOUND).sample(xs, zs, zoned, false); + fixture.data.getBiomeLoader().load("meadow").getHydrologyPolicy().setWetness(new IrisHydrologyWetness().setMin(0.7D)); + fixture.data.getRegionLoader().load("beta").setHydrologyPolicy(new IrisHydrologyPolicy().setWetness(new IrisHydrologyWetness().setMax(0.35D))); + HydrologySampleBuffer clamped = new HydrologySampleBuffer(xs.length); + new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, null, 1, HydrologyBinding.UNBOUND).sample(xs, zs, clamped, false); + HydrologySampleBuffer unzoned = new HydrologySampleBuffer(xs.length); + new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, lavaSettings(fixture), null, 1, HydrologyBinding.UNBOUND) + .sample(xs, zs, unzoned, false); + Set seen = new HashSet<>(); + for (int index = 0; index < xs.length; index++) { + int x = xs[index]; + int z = zs[index]; + String chain = chain(fixture, x, z); + String leaf = chain.split("<")[0]; + boolean alpha = fixture.complex.getRegionStream().get(x, z).getLoadKey().equals("alpha"); + boolean swamp = leaf.equals("meadow") || leaf.equals("glade"); + boolean zoneDry = zoned.rainfall()[index] == 0f; + float rainfall = swamp ? 2f : 0.5f; + float ponds = chain.contains("peaks") ? 5f : alpha ? 3f : 1f; + String at = chain + "@" + (alpha ? "alpha" : "beta") + " " + x + "," + z; + assertEquals(at, zoneDry ? 0f : rainfall, zoned.rainfall()[index], 0f); + float wet = Math.clamp(zoneDry ? 0f : 1f, swamp ? 0.7f : 0f, swamp || alpha ? 1f : 0.35f); + assertEquals(at, rainfall * wet, clamped.rainfall()[index], 0f); + assertEquals(at, ponds * wet, clamped.pondDensity()[index], 0f); + assertEquals(at, wet, clamped.wetness()[index], 0f); + assertTrue(at, clamped.climateZoned()[index]); + assertEquals(at, rainfall, unzoned.rainfall()[index], 0f); + assertEquals(at, ponds, unzoned.pondDensity()[index], 0f); + assertEquals(at, 1f, unzoned.wetness()[index], 0f); + assertFalse(at, unzoned.climateZoned()[index]); + seen.add(leaf + "@" + (alpha ? "alpha" : "beta") + (zoneDry ? " dry" : " wet")); + } + assertTrue("sampled " + seen, seen.containsAll(List.of("meadow@alpha dry", "glade@beta dry", "meadow@beta wet", "spires@beta wet", + "spires@beta dry", "peaks@alpha wet", "peaks@alpha dry"))); + assertInvertedWetnessRejected(fixture, settings, xs, zs); + } + } + + @Test + public void wetnessMinKeepsADryZonePondFromDrawingDown() throws Exception { + Path pack = childPack(""); + int[][] grid = childGrid(); + try (EngineFixture.Environment ignored = EngineFixture.environment(); EngineFixture fixture = new EngineFixture(pack)) { + IrisHydrology config = new IrisHydrology().setEnabled(true).setPersist(false); + config.getFluids().add(new IrisFluidProfile().setName("lava").setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:lava"))); + config.getClimate().setEnabled(true).setDryness(0.5D).setTransition(0D).setDryRainfall(0.15D).getStyle().setZoom(4D); + config.getPonds().setFreeboard(new KList<>(1, 1)); + config.getPonds().getSeeded().setEnabled(false); + HydrologySettings settings = HydrologySettings.compile(config, EngineFixture.SEED, fixture.dimension.getFluidHeight(), 0, + EngineFixture.HEIGHT); + IrisBiome spires = fixture.data.getBiomeLoader().load("spires"); + spires.setHydrologyPolicy(new IrisHydrologyPolicy().setPondDensity(16D)); + int[] column = dryZoneColumn(fixture, settings, grid, "spires"); + Pond dry = floorPond(fixture, settings, column); + spires.setHydrologyPolicy(new IrisHydrologyPolicy().setPondDensity(16D).setWetness(new IrisHydrologyWetness().setMin(0.7D))); + Pond swamp = floorPond(fixture, settings, column); + spires.setHydrologyPolicy(new IrisHydrologyPolicy().setPondDensity(16D).setWetness(new IrisHydrologyWetness().setMin(1D))); + Pond kept = floorPond(fixture, settings, column); + int drawdown = settings.ponds().climateDrawdown(); + assertEquals((int) Math.floor(kept.spillHeight()) - 1, kept.level()); + assertEquals(kept.level() - Math.round(drawdown * 0.3f), swamp.level()); + assertEquals(kept.level() - Math.round(drawdown * 0.85f), dry.level()); + } + } + + private static int[] dryZoneColumn(EngineFixture fixture, HydrologySettings settings, int[][] grid, String biome) { + HydrologySampleBuffer samples = new HydrologySampleBuffer(grid[0].length); + new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, null, 1, HydrologyBinding.UNBOUND) + .sample(grid[0], grid[1], samples, false); + for (int index = 0; index < grid[0].length; index++) { + if (samples.rainfall()[index] < 0.1f && fixture.complex.getBaseBiomeStream().get(grid[0][index], grid[1][index]).getLoadKey().equals(biome)) { + return new int[]{grid[0][index], grid[1][index]}; + } + } + throw new AssertionError("No sampled " + biome + " column lies in a dry zone"); + } + + private static Pond floorPond(EngineFixture fixture, HydrologySettings settings, int[] column) { + HydrologySampleBuffer floor = new HydrologySampleBuffer(1); + new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, null, 1, HydrologyBinding.UNBOUND) + .sample(new int[]{column[0]}, new int[]{column[1]}, floor, false); + FloorBowl bowl = new FloorBowl(settings, floor); + int span = 64; + HydrologySampleBuffer samples = new HydrologySampleBuffer(span * span); + new HeightLattice(bowl, 8, false, 1 << 16).fill(0, 0, span, span, samples); + DemGrid grid = new DemGrid(0, 0, 8, span, span); + System.arraycopy(samples.height(), 0, grid.values(), 0, span * span); + PondPlanner planner = new PondPlanner(settings); + CupSet cups = planner.subtractCups(grid, new WindowKey(0, 0), samples, new BitSet()); + BitSet seeds = new BitSet(span * span); + for (int j = 0; j < span; j++) { + for (int i = 0; i < span; i++) { + if (i == 0 || j == 0 || i == span - 1 || j == span - 1) { + seeds.set(grid.index(i, j)); + } + } + } + float[] filled = PriorityFlood.fill(grid, seeds, settings.drainage().fillEpsilon()); + List basins = BasinExtractor.basins(grid, filled, 0.5f, settings.seaLevel()); + List ponds = planner.ponds(grid, filled, basins, List.of(), new HeightLattice(bowl, 4, false, 1 << 18), cups); + assertEquals("ponds " + ponds, 1, ponds.size()); + return ponds.getFirst(); + } + + @Test + public void policyMultipliersOutsideZeroToSixteenAreRejected() throws Exception { + Path pack = EngineFixture.pack(temporaryFolder.newFolder().toPath()); + int[] xs = new int[COLUMNS]; + int[] zs = new int[COLUMNS]; + columns(xs, zs); + try (EngineFixture.Environment ignored = EngineFixture.environment(); EngineFixture fixture = new EngineFixture(pack)) { + HydrologySettings settings = settings(fixture); + int[] column = spiresColumn(fixture, xs, zs); + IrisBiome spires = fixture.data.getBiomeLoader().load("spires"); + spires.setHydrologyPolicy(new IrisHydrologyPolicy().setPondDensity(17D)); + assertPolicyRejected(fixture, settings, column, + "Hydrology policy pondDensity for biome spires in region beta must be a finite value from 0 to 16, got 17.0"); + spires.setHydrologyPolicy(new IrisHydrologyPolicy().setRainfall(16.5D).setPondDensity(16D)); + assertPolicyRejected(fixture, settings, column, + "Hydrology policy rainfall for biome spires in region beta must be a finite value from 0 to 16, got 16.5"); + spires.setHydrologyPolicy(new IrisHydrologyPolicy().setRainfall(16D).setPondDensity(16D)); + HydrologySampleBuffer bounds = new HydrologySampleBuffer(1); + new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, null, 1, HydrologyBinding.UNBOUND) + .sample(new int[]{column[0]}, new int[]{column[1]}, bounds, false); + assertEquals(16f, bounds.rainfall()[0], 0f); + assertEquals(16f, bounds.pondDensity()[0], 0f); + } + } + + private static int[] spiresColumn(EngineFixture fixture, int[] xs, int[] zs) { + for (int index = 0; index < xs.length; index++) { + if (fixture.complex.getBaseBiomeStream().get(xs[index], zs[index]).getLoadKey().equals("spires")) { + return new int[]{xs[index], zs[index]}; + } + } + throw new AssertionError("No sampled column is spires"); + } + + private static void assertPolicyRejected(EngineFixture fixture, HydrologySettings settings, int[] column, String message) { + try { + new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, null, 1, HydrologyBinding.UNBOUND) + .sample(new int[]{column[0]}, new int[]{column[1]}, new HydrologySampleBuffer(1), false); + fail("Expected rejection: " + message); + } catch (IllegalArgumentException expected) { + assertEquals(message, expected.getMessage()); + } + } + + private static void assertInvertedWetnessRejected(EngineFixture fixture, HydrologySettings settings, int[] xs, int[] zs) { + fixture.data.getBiomeLoader().load("meadow").getHydrologyPolicy().setWetness(new IrisHydrologyWetness().setMin(0.8D).setMax(0.3D)); + for (int index = 0; index < xs.length; index++) { + if (!fixture.complex.getBaseBiomeStream().get(xs[index], zs[index]).getLoadKey().equals("meadow")) { + continue; + } + try { + new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, null, 1, HydrologyBinding.UNBOUND) + .sample(new int[]{xs[index]}, new int[]{zs[index]}, new HydrologySampleBuffer(1), false); + fail("A wetness min above its max must be rejected"); + } catch (IllegalArgumentException expected) { + assertTrue(expected.getMessage(), expected.getMessage().contains("wetness") && expected.getMessage().contains("biome meadow")); + } + return; + } + fail("No sampled column is meadow"); + } + + @Test + public void childBiomesInheritTheParentPolicy() throws Exception { + Path pack = childPack(""); + int[][] grid = childGrid(); + int[] xs = grid[0]; + int[] zs = grid[1]; + pool = Executors.newFixedThreadPool(4); + try (EngineFixture.Environment ignored = EngineFixture.environment(); EngineFixture fixture = new EngineFixture(pack)) { + HydrologySettings settings = lavaSettings(fixture); + IrisHydrologyTerrainSource source = new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, null, 1, + HydrologyBinding.UNBOUND); + HydrologySampleBuffer samples = new HydrologySampleBuffer(xs.length); + source.sample(xs, zs, samples, false); + HydrologySampleBuffer pooled = new HydrologySampleBuffer(xs.length); + new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, pool, 4, HydrologyBinding.UNBOUND).sample(xs, zs, pooled, false); + assertSameSamples(samples, pooled, xs.length); + Map chains = new HashMap<>(); + for (int index = 0; index < xs.length; index++) { + int x = xs[index]; + int z = zs[index]; + String chain = chain(fixture, x, z); + boolean alpha = fixture.complex.getRegionStream().get(x, z).getLoadKey().equals("alpha"); + String at = chain + "@" + (alpha ? "alpha" : "beta") + " " + x + "," + z; + chains.merge(chain + "@" + (alpha ? "alpha" : "beta"), 1, Integer::sum); + assertChildPolicy(at, source, samples, new int[]{x, z, index}, alpha, chain.contains("peaks"), chain.contains("meadow")); + } + assertTrue("sampled chains " + chains, chains.containsKey("meadow lineage = fixture.complex.baseBiomeLineage(x, z); + String at = gladeExtra + " " + root.getLoadKey() + ">" + leaf.getLoadKey() + " " + x + "," + z; + assertSame(at, leaf, lineage.getFirst()); + assertSame(at, root, lineage.getLast()); + assertTrue(at, lineage.size() <= 5); + Set keys = new HashSet<>(); + for (int link = 0; link < lineage.size(); link++) { + keys.add(lineage.get(link).getLoadKey()); + if (link > 0) { + assertTrue(at, lineage.get(link).getChildren().contains(lineage.get(link - 1).getLoadKey())); + assertTrue(at, lineage.get(link) != lineage.get(link - 1)); + } + } + repeated += keys.size() < lineage.size() ? 1 : 0; + glades += leaf.getLoadKey().equals("glade") ? 1 : 0; + boolean alpha = fixture.complex.getRegionStream().get(x, z).getLoadKey().equals("alpha"); + boolean meadow = leaf.getLoadKey().equals("meadow") || leaf.getLoadKey().equals("glade"); + assertChildPolicy(at, source, samples, new int[]{x, z, index}, alpha, root.getLoadKey().equals("peaks"), meadow); + } + assertTrue(gladeExtra + " glade columns " + glades, glades > 0); + assertTrue(gladeExtra + " columns whose chain repeats a biome " + repeated, repeats == repeated > 0); + } + } + + private static void assertChildPolicy(String at, IrisHydrologyTerrainSource source, HydrologySampleBuffer samples, int[] column, boolean alpha, + boolean peaks, boolean meadow) { + int index = column[2]; + assertEquals(at, meadow ? 2f : 0.5f, samples.rainfall()[index], 0f); + assertEquals(at, peaks ? 5f : alpha ? 3f : 1f, samples.pondDensity()[index], 0f); + int permission = (peaks || !alpha ? HydrologySampleBuffer.ALLOW_STREAMS : 0) | (meadow ? 0 : HydrologySampleBuffer.ALLOW_PONDS); + assertEquals(at, permission, samples.permission()[index]); + String fluid = peaks ? "lava" : alpha ? "water" : null; + assertEquals(at, fluid, samples.fluidProfile()[index]); + assertEquals(at, fluid, source.channelFluid(column[0], column[1])); + } + + private Path childPack(String gladeExtra) throws Exception { + Path pack = EngineFixture.pack(temporaryFolder.newFolder().toPath(), false); + EngineFixture.extend(pack, "peaks", ",\"hydrologyPolicy\":{\"pondDensity\":5,\"streams\":\"ALLOW\",\"fluid\":\"lava\"}"); + EngineFixture.extend(pack, "meadow", ",\"children\":[\"glade\"],\"childShrinkFactor\":2.5"); + EngineFixture.biome(pack, "glade", "[{\"generator\":\"plain\",\"min\":4,\"max\":10}]", gladeExtra); + return pack; + } + + private static int[][] childGrid() { + int side = 96; + int[][] grid = new int[2][side * side]; + for (int index = 0; index < side * side; index++) { + grid[0][index] = (index % side) * 9 - 432; + grid[1][index] = (index / side) * 9 - 432; + } + return grid; + } + + private static HydrologySettings lavaSettings(EngineFixture fixture) { + IrisHydrology config = new IrisHydrology().setEnabled(true).setPersist(false); + config.getFluids().add(new IrisFluidProfile().setName("lava").setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:lava"))); + return HydrologySettings.compile(config, EngineFixture.SEED, fixture.dimension.getFluidHeight(), 0, EngineFixture.HEIGHT); + } + + private static HydrologySettings climateSettings(EngineFixture fixture) { + IrisHydrology config = new IrisHydrology().setEnabled(true).setPersist(false); + config.getFluids().add(new IrisFluidProfile().setName("lava").setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:lava"))); + config.getClimate().setEnabled(true).setDryness(0.5D).setTransition(0D).getStyle().setZoom(4D); + return HydrologySettings.compile(config, EngineFixture.SEED, fixture.dimension.getFluidHeight(), 0, EngineFixture.HEIGHT); + } + + private static IrisBiome root(EngineFixture fixture, int x, int z) { + boolean sea = fixture.complex.getBridgeStream().get(x, z) == InferredType.SEA; + return (sea ? fixture.complex.getSeaBiomeStream() : fixture.complex.getLandBiomeStream()).get(x, z); + } + + private static String chain(EngineFixture fixture, int x, int z) { + IrisBiome leaf = fixture.complex.getBaseBiomeStream().get(x, z); + IrisBiome root = root(fixture, x, z); + String pair = root.getLoadKey() + ">" + leaf.getLoadKey(); + return switch (pair) { + case "peaks>meadow" -> "meadowglade" -> "gladeglade" -> "glade { + assertEquals("a biome outside the child chains at " + x + "," + z, root.getLoadKey(), leaf.getLoadKey()); + yield leaf.getLoadKey(); + } + }; + } + private static void assertUnknownFluidRejected(EngineFixture fixture, HydrologySettings settings, int[] xs, int[] zs) { IrisRegion beta = fixture.data.getRegionLoader().load("beta"); beta.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("slime")); @@ -272,6 +610,8 @@ public class IrisHydrologyTerrainSourceTest { assertEquals(at, expected.ocean()[index], actual.ocean()[index]); assertEquals(at, Float.floatToRawIntBits(expected.rainfall()[index]), Float.floatToRawIntBits(actual.rainfall()[index])); assertEquals(at, Float.floatToRawIntBits(expected.pondDensity()[index]), Float.floatToRawIntBits(actual.pondDensity()[index])); + assertEquals(at, Float.floatToRawIntBits(expected.wetness()[index]), Float.floatToRawIntBits(actual.wetness()[index])); + assertEquals(at, expected.climateZoned()[index], actual.climateZoned()[index]); assertEquals(at, expected.permission()[index], actual.permission()[index]); assertEquals(at, expected.fluidProfile()[index], actual.fluidProfile()[index]); } @@ -295,6 +635,46 @@ public class IrisHydrologyTerrainSourceTest { } } + private static final class FloorBowl implements HydrologyTerrainSource { + private final HydrologySettings settings; + private final HydrologySampleBuffer floor; + + private FloorBowl(HydrologySettings settings, HydrologySampleBuffer floor) { + this.settings = settings; + this.floor = floor; + } + + @Override + public void sample(int[] xs, int[] zs, HydrologySampleBuffer out, boolean baseOnly) { + for (int index = 0; index < xs.length; index++) { + double ratio = Math.hypot(xs[index] - 256D, zs[index] - 256D) / 60D; + out.height()[index] = (float) (ratio < 1D ? 200D + 12D * ratio * ratio : 212D - 6D * (ratio - 1D)); + out.ocean()[index] = false; + out.rainfall()[index] = floor.rainfall()[0]; + out.pondDensity()[index] = floor.pondDensity()[0]; + out.wetness()[index] = floor.wetness()[0]; + out.climateZoned()[index] = floor.climateZoned()[0]; + out.permission()[index] = floor.permission()[0]; + out.fluidProfile()[index] = floor.fluidProfile()[0]; + } + } + + @Override + public int seaLevel() { + return settings.seaLevel(); + } + + @Override + public int minY() { + return settings.minY(); + } + + @Override + public int maxY() { + return settings.maxY(); + } + } + private static double[] chunk(Map chunks, ChunkFillableDoubleStream2D stream, int x, int z) { long key = ((long) (x >> 4) << 32) | ((z >> 4) & 0xFFFFFFFFL); return chunks.computeIfAbsent(key, ignored -> { diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/grid/HeightLatticeTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/grid/HeightLatticeTest.java index bce372d77..665c91c16 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/grid/HeightLatticeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/grid/HeightLatticeTest.java @@ -365,6 +365,8 @@ public class HeightLatticeTest { assertEquals(Float.floatToIntBits(expected.height()[index]), Float.floatToIntBits(actual.height()[index])); assertEquals(Float.floatToIntBits(expected.rainfall()[index]), Float.floatToIntBits(actual.rainfall()[index])); assertEquals(Float.floatToIntBits(expected.pondDensity()[index]), Float.floatToIntBits(actual.pondDensity()[index])); + assertEquals(Float.floatToIntBits(expected.wetness()[index]), Float.floatToIntBits(actual.wetness()[index])); + assertEquals(expected.climateZoned()[index], actual.climateZoned()[index]); assertEquals(expected.ocean()[index], actual.ocean()[index]); assertEquals(expected.permission()[index], actual.permission()[index]); assertEquals(expected.fluidProfile()[index], actual.fluidProfile()[index]); @@ -410,6 +412,8 @@ public class HeightLatticeTest { out.height()[index] = Float.intBitsToFloat(((int) hash & 0x807FFFFF) | 0x42000000); out.rainfall()[index] = Float.intBitsToFloat(((int) (hash >>> 23) & 0x007FFFFF) | 0x3F000000); out.pondDensity()[index] = Float.intBitsToFloat(((int) (hash >>> 37) & 0x007FFFFF) | 0x3F800000); + out.wetness()[index] = Float.intBitsToFloat(((int) (hash >>> 11) & 0x007FFFFF) | 0x3F000000); + out.climateZoned()[index] = ((hash >>> 58) & 1L) != 0L; out.ocean()[index] = ((hash >>> 62) & 1L) != 0L; out.permission()[index] = (byte) ((hash >>> 60) & (HydrologySampleBuffer.ALLOW_STREAMS | HydrologySampleBuffer.ALLOW_PONDS)); out.fluidProfile()[index] = ((hash >>> 59) & 1L) == 0L ? "water" : "lava"; 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 4cfd734c5..231013558 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 @@ -15,8 +15,10 @@ import art.arcane.iris.generation.hydrology.water.ReachShaper; import art.arcane.iris.generation.hydrology.water.ReachStyle; import org.junit.Test; +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; +import java.util.HexFormat; import java.util.List; import java.util.Optional; import java.util.SplittableRandom; @@ -33,6 +35,20 @@ public class HydrologyPlanCodecTest { private static final float NAN_PAYLOAD = Float.intBitsToFloat(0x7fc00123); private static final float NEGATIVE_NAN = Float.intBitsToFloat(0xffa00001); private static final WindowKey LAND = new WindowKey(4, 4); + private static final int FINGERPRINT_OFFSET = Integer.BYTES + 1; + private static final String PINNED_WINDOW = """ + 4948595057000000000000000000000002fffffffd000000010000000000000029000000000000006100000000444b20 + 0000000006000000004080000041000000414000004180000041a00000c1000000c0c00000c0800000c0000000000000 + 0040000000000000480000004700000046000000420000003f0000003e3f8000003fa000003fc000003fe00000400000 + 00402000003f8000003f8000003fc0000040000000400000003f80000000010203040500000004000000000000000500 + 00000046000000420000000cfffffffc428d0000fffffffc000000080000000400000000000000000000000000000000 + 0000002900000000ffffffff0000000afffffffa0000000000000006010000004a000000470000001e00000008429480 + 0000000003fffffffd000000010000004000000001000000018000000000000001ffffffffffffffff00000001000000 + 0577617465720000001c000000060000000000000007020000004400000040ffffffec0000001042898000fffffffc00 + 00000800000004000000000000000000000000000000000000002900000002000000046c617661ffffffea0000000e00 + 0000000000000803000000500000003c00000040ffffffc042a10000fffffffc00000008000000040000000000000000 + 00000000ffffffffffffffff00000000ffffffff0000003cffffffc400000000 + """; @Test public void codecRoundTripsBitExact() { @@ -138,6 +154,29 @@ public class HydrologyPlanCodecTest { } } + @Test + public void decodesPinnedBytes() { + HydrologySettings settings = settings(new IrisHydrology()); + WindowPlan expected = pinnedWindow(settings.tiers().get(0)); + byte[] fixture = HexFormat.of().parseHex(PINNED_WINDOW.replaceAll("\\s", "")); + ByteBuffer.wrap(fixture).putLong(FINGERPRINT_OFFSET, settings.fingerprint()); + assertBitExact(expected, HydrologyPlanCodec.decodeWindow(settings, fixture).orElseThrow(), settings.tiers()); + assertArrayEquals(fixture, HydrologyPlanCodec.encode(settings, expected)); + } + + private static WindowPlan pinnedWindow(HydrologyTier tier) { + Reach reach = new Reach(41L, tier, 97L, new float[]{0f, 4f, 8f, 12f, 16f, 20f}, new float[]{-8f, -6f, -4f, -2f, 0f, 2f}, + new int[]{72, 71, 70, 66, 63, 62}, new float[]{1f, 1.25f, 1.5f, 1.75f, 2f, 2.5f}, new float[]{1f, 1f, 1.5f, 2f, 2f, 1f}, + new ReachStyle[]{ReachStyle.RUN, ReachStyle.RIFFLE, ReachStyle.CASCADE, ReachStyle.WATERFALL, ReachStyle.POND_OUTLET, + ReachStyle.MOUTH}, 812.5f); + List ponds = List.of( + new Pond(5L, PondKind.NATURAL, 70, 66, 12, -4, 70.5f, mask(0), 41L, 0, null, 10, -6), + new Pond(6L, PondKind.SEEDED, 74, 71, 30, 8, 74.25f, mask(2), -1L, 1, "water", 28, 6), + new Pond(7L, PondKind.CHAINED, 68, 64, -20, 16, 68.75f, mask(0), 41L, 2, "lava", -22, 14), + new Pond(8L, PondKind.LAKE, 80, 60, 64, -64, 80.5f, mask(0), -1L, 0, null, 60, -60)); + return new WindowPlan(new WindowKey(2, -3), List.of(reach), ponds, List.of()); + } + private static void assertBitExact(WindowPlan expected, WindowPlan actual, List tiers) { assertEquals(expected, actual); assertReachesBitExact(expected.reaches(), actual.reaches(), tiers); 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 8378eb3d1..177170025 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 @@ -22,6 +22,7 @@ import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; @@ -32,7 +33,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 = -5309117903859653038L; + private static final long DEFAULT_FINGERPRINT = 7576271788988330967L; @Test public void densityIsBoundedAndChangesThePlanIdentity() { @@ -265,6 +266,18 @@ public class HydrologySettingsTest { assertEquals("fingerprint must be identical in every JVM run", DEFAULT_FINGERPRINT, first); } + @Test + public void schedulingKnobsDoNotChangeTheFingerprint() { + HydrologySettings eager = compile(new IrisHydrology().setPrefetchRings(4)); + HydrologySettings inMemory = compile(new IrisHydrology().setPersist(false)); + HydrologySettings both = compile(new IrisHydrology().setPrefetchRings(0).setPersist(false)); + assertEquals(4, eager.prefetchRings()); + assertFalse(inMemory.persist()); + assertEquals(DEFAULT_FINGERPRINT, eager.fingerprint()); + assertEquals(DEFAULT_FINGERPRINT, inMemory.fingerprint()); + assertEquals(DEFAULT_FINGERPRINT, both.fingerprint()); + } + @Test public void compileRejectsUnknownFluidProfile() { IrisHydrology config = new IrisHydrology(); @@ -345,6 +358,30 @@ public class HydrologySettingsTest { assertRejected(cavePools, "underground.cavePools.minArea"); } + @Test + public void compileBoundsTheSeededCupDensity() { + for (double invalid : new double[]{-0.5D, 64.5D, Double.NaN, Double.POSITIVE_INFINITY}) { + IrisHydrology config = new IrisHydrology(); + config.getPonds().getSeeded().setDensity(invalid); + assertRejected(config, "ponds.seeded.density must stay within 0..64, got " + invalid); + } + IrisHydrology densest = new IrisHydrology(); + densest.getPonds().getSeeded().setDensity(64D); + assertEquals(64f, compile(densest).ponds().seeded().density(), 0f); + } + + @Test + public void compileRejectsAFillEpsilonThatIsNotPositiveAsAFloat() { + for (double invalid : new double[]{0D, -0.001D, 1e-50D, Double.MIN_VALUE, 1e300D, Double.NaN, Double.POSITIVE_INFINITY}) { + IrisHydrology config = new IrisHydrology(); + config.getDrainage().setFillEpsilon(invalid); + assertRejected(config, "drainage.fillEpsilon must be a finite value above 0"); + } + IrisHydrology finest = new IrisHydrology(); + finest.getDrainage().setFillEpsilon(0.00001D); + assertEquals(0.00001f, compile(finest).drainage().fillEpsilon(), 0f); + } + @Test public void compileRejectsCavePoolsThatReachPastTheNeighbouringChunks() { IrisHydrology wide = new IrisHydrology(); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/CavePoolFillerTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/CavePoolFillerTest.java index 860215a9a..908a3b361 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/CavePoolFillerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/CavePoolFillerTest.java @@ -188,6 +188,26 @@ public class CavePoolFillerTest { assertNoMixedBodies(forward); } + @Test + public void wallsSharedByTwoFluidsKeepOneKeyWhateverTheChunkOrder() { + VoxelWorld world = room(0, 14, 0, 15, FLOOR, 52); + world.carve(16, 30, 0, 15, FLOOR, 52); + world.policyFluid(x -> x >= 16 ? "lava" : null); + HydrologySettings settings = settings(pools -> pools.setDensity(8D).setFreeboard(new KList<>(0, 0))); + + Map forward = new HashMap<>(); + Map reverse = new HashMap<>(); + new CavePoolFiller(settings).fill(0, 0, () -> world, writer(forward), SEED); + new CavePoolFiller(settings).fill(1, 0, () -> world, writer(forward), SEED); + new CavePoolFiller(settings).fill(1, 0, () -> world, writer(reverse), SEED); + new CavePoolFiller(settings).fill(0, 0, () -> world, writer(reverse), SEED); + + assertFalse(wetCells(forward, "water").isEmpty()); + assertFalse(wetCells(forward, "lava").isEmpty()); + assertGuard(forward, 15, 51, 8); + assertEquals(forward, reverse); + } + @Test public void depressionsSpanningTwoCaveFluidsGetNoPool() { VoxelWorld mixed = roomWithSill(); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/InletTerrain.java b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/InletTerrain.java index 844158387..7c0279e24 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/InletTerrain.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/InletTerrain.java @@ -7,6 +7,7 @@ import art.arcane.iris.generation.hydrology.grid.FlowAccumulator; import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer; import art.arcane.iris.generation.hydrology.grid.PriorityFlood; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.hydrology.plan.WindowKey; import art.arcane.iris.generation.hydrology.water.Reach; import art.arcane.iris.generation.hydrology.water.ReachStyle; import art.arcane.iris.generation.hydrology.water.ShapedNetwork; @@ -24,21 +25,28 @@ final class InletTerrain { static final int CELL = 8; static final int WIDTH = 96; static final int DEPTH = 64; + static final int SPAN = 3 * WindowKey.SIZE / CELL; final DoubleBinaryOperator natural; + final WindowKey window; final DemGrid grid; final HydrologySampleBuffer samples; final int[] receivers; final float[] accumulation; private InletTerrain(DoubleBinaryOperator natural) { - this(natural, 0, 0); + this(natural, new WindowKey(0, 0)); } - private InletTerrain(DoubleBinaryOperator natural, int originX, int originZ) { + private InletTerrain(DoubleBinaryOperator natural, WindowKey window) { + this(natural, window, (window.wx() - 1) * WindowKey.SIZE, (window.wz() - 1) * WindowKey.SIZE, SPAN, SPAN); + } + + private InletTerrain(DoubleBinaryOperator natural, WindowKey window, int originX, int originZ, int width, int depth) { this.natural = natural; - this.grid = new DemGrid(originX, originZ, CELL, WIDTH, DEPTH); - int count = WIDTH * DEPTH; + this.window = window; + this.grid = new DemGrid(originX, originZ, CELL, width, depth); + int count = width * depth; this.samples = new HydrologySampleBuffer(count); BitSet seeds = new BitSet(count); for (int cell = 0; cell < count; cell++) { @@ -48,14 +56,14 @@ final class InletTerrain { grid.values()[cell] = height; samples.height()[cell] = height; samples.ocean()[cell] = Math.round(height) < SEA; - int i = cell % WIDTH; - int j = cell / WIDTH; - if (samples.ocean()[cell] || i == 0 || j == 0 || i == WIDTH - 1 || j == DEPTH - 1) { + int i = cell % width; + int j = cell / width; + if (samples.ocean()[cell] || i == 0 || j == 0 || i == width - 1 || j == depth - 1) { seeds.set(cell); } } float[] filled = PriorityFlood.fill(grid, seeds, 0.001f); - DemGrid surface = new DemGrid(originX, originZ, CELL, WIDTH, DEPTH); + DemGrid surface = new DemGrid(originX, originZ, CELL, width, depth); System.arraycopy(filled, 0, surface.values(), 0, count); this.receivers = D8Router.receivers(surface, filled); float[] weights = new float[count]; @@ -72,6 +80,34 @@ final class InletTerrain { return new InletTerrain((x, z) -> x < COAST_X ? SEA - 20D : SEA + cliffHeight + 0.08D * (x - COAST_X)); } + InletTerrain wide(WindowKey window, int windows) { + int cells = (2 * windows + 1) * WindowKey.SIZE / CELL; + int originX = (window.wx() - windows) * WindowKey.SIZE; + int originZ = (window.wz() - windows) * WindowKey.SIZE; + return new InletTerrain(natural, window, originX, originZ, cells, cells); + } + + static InletTerrain bay(int westX, int eastX, int bayZ) { + return new InletTerrain((x, z) -> { + if (z > bayZ - CELL / 2D) { + return Math.abs(z - bayZ) < CELL / 2D && x > westX - CELL / 2D && x < eastX + CELL / 2D ? SEA - 20D : SEA + 5D; + } + return SEA + 30D + 0.08D * (bayZ - z); + }); + } + + static InletTerrain eastEdgeCoast() { + double coast = WindowKey.SIZE - CELL; + return new InletTerrain((x, z) -> x < coast - CELL / 2D ? SEA - 20D : SEA + 30D + 0.08D * (x - coast)); + } + + static InletTerrain openCoast() { + return new InletTerrain((x, z) -> { + double coast = 768D + 120D * Math.sin(z / 180D) + 40D * Math.sin(z / 53D); + return x < coast ? SEA - 20D : SEA + 30D + 0.08D * (x - coast); + }); + } + static InletTerrain cliffWithTrough(double cliffHeight, double troughFrom, double troughTo, double troughHeight) { return new InletTerrain((x, z) -> { if (x < COAST_X) { @@ -123,12 +159,16 @@ final class InletTerrain { return HydrologySettings.compile(config, SEED, SEA, MIN_Y, MAX_Y); } - InletTerrain shifted(int originX, int originZ) { - return new InletTerrain(natural, originX, originZ); + InletTerrain span(WindowKey window) { + return new InletTerrain(natural, window); + } + + InletTerrain narrow(int originX, int originZ) { + return new InletTerrain(natural, WindowKey.containing(originX, originZ), originX, originZ, WIDTH, DEPTH); } List plan(HydrologySettings settings, ShapedNetwork network) { - return new SeaInletPlanner(settings).plan(grid, samples, receivers, accumulation, network, SEED); + return new SeaInletPlanner(settings).plan(window, grid, samples, receivers, accumulation, network, SEED); } List plan(HydrologySettings settings) { @@ -136,7 +176,7 @@ final class InletTerrain { } boolean ocean(float x, float z) { - int cell = grid.index(Math.round(x / CELL), Math.round(z / CELL)); + int cell = grid.index(Math.round((x - grid.originX()) / CELL), Math.round((z - grid.originZ()) / CELL)); return samples.ocean()[cell]; } @@ -164,7 +204,7 @@ final class InletTerrain { } static Reach northSouthReach(HydrologySettings settings, float x, int grade, float halfWidth, float depth) { - int points = 9; + int points = 25; float[] xs = new float[points]; float[] zs = new float[points]; int[] grades = new int[points]; @@ -173,7 +213,7 @@ final class InletTerrain { ReachStyle[] styles = new ReachStyle[points]; for (int point = 0; point < points; point++) { xs[point] = x; - zs[point] = point * 64f; + zs[point] = point * 64f - WindowKey.SIZE; grades[point] = grade; widths[point] = halfWidth; depths[point] = depth; diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlannerTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlannerTest.java index 1f58e3b2d..6a7df1665 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlannerTest.java @@ -9,8 +9,11 @@ import art.arcane.iris.generation.hydrology.water.ShapedNetwork; import art.arcane.volmlib.util.collection.KList; import org.junit.Test; +import java.util.ArrayList; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; @@ -32,15 +35,15 @@ public class SeaInletPlannerTest { int baseline = 0; int retained = 0; for (int offset = 0; offset < 32; offset++) { - InletTerrain shifted = terrain.shifted(0, offset * 512); - List all = shifted.plan(InletTerrain.settings(full)); - List reduced = shifted.plan(InletTerrain.settings(half)); + InletTerrain view = terrain.span(new WindowKey(0, offset)); + List all = view.plan(InletTerrain.settings(full)); + List reduced = view.plan(InletTerrain.settings(half)); baseline += all.size(); retained += reduced.size(); for (SeaInlet inlet : reduced) { assertTrue("retained inlets keep the same full passage", all.contains(inlet)); } - assertEquals(reduced, shifted.plan(InletTerrain.settings(half))); + assertEquals(reduced, view.plan(InletTerrain.settings(half))); } assertTrue("cliff provides enough candidates", baseline >= 32); assertTrue("half density retains approximately half the sites", retained > baseline * 0.3 && retained < baseline * 0.7); @@ -188,11 +191,11 @@ public class SeaInletPlannerTest { IrisHydrology dense = new IrisHydrology(); dense.getUnderground().getSeaInlets().setSpacing(32); HydrologySettings settings = InletTerrain.settings(dense); - InletTerrain pocket = InletTerrain.pocket(152, 256); - List here = fromPocket(pocket.shifted(-232, 0).plan(settings)); + InletTerrain pocket = InletTerrain.pocket(512, 256); + List here = fromPocket(pocket.span(new WindowKey(0, 0)).plan(settings), 512, 256); assertTrue("inlets opening from the pocket " + here, here.size() >= 2); assertEquals("another grid holding every competitor well inside decides the same", here, - fromPocket(pocket.shifted(-200, -24).plan(settings))); + fromPocket(pocket.span(new WindowKey(1, 0)).plan(settings), 512, 256)); for (int first = 0; first < here.size(); first++) { for (int second = first + 1; second < here.size(); second++) { assertFalse(here.get(first) + " and " + here.get(second) + " cross a covered passage with an open slot", @@ -201,8 +204,8 @@ public class SeaInletPlannerTest { } } - private static List fromPocket(List inlets) { - return inlets.stream().filter(inlet -> inlet.xs()[0] == 152f && inlet.zs()[0] == 256f).toList(); + private static List fromPocket(List inlets, float pocketX, float pocketZ) { + return inlets.stream().filter(inlet -> inlet.xs()[0] == pocketX && inlet.zs()[0] == pocketZ).toList(); } private static boolean coveredMeetsOpen(SeaInlet covered, SeaInlet open) { @@ -399,11 +402,153 @@ public class SeaInletPlannerTest { assertEquals(first.size(), first.stream().mapToLong(SeaInlet::id).distinct().count()); InletTerrain terrain = InletTerrain.cliff(30D); List otherSeed = new SeaInletPlanner(HydrologySettings.compile(new IrisHydrology(), 99L, SEA, InletTerrain.MIN_Y, - InletTerrain.MAX_Y)).plan(terrain.grid, terrain.samples, terrain.receivers, terrain.accumulation, + InletTerrain.MAX_Y)).plan(terrain.window, terrain.grid, terrain.samples, terrain.receivers, terrain.accumulation, new ShapedNetwork(List.of(), List.of()), 99L); assertNotEquals(first, otherSeed); } + @Test + public void inletsAgreeAcrossWindowsOnOpenCoast() { + IrisHydrology dense = new IrisHydrology(); + dense.getUnderground().getSeaInlets().setSpacing(64); + HydrologySettings settings = InletTerrain.settings(dense); + InletTerrain coast = InletTerrain.openCoast(); + List windows = new ArrayList<>(9); + for (int wz = 0; wz <= 2; wz++) { + for (int wx = 0; wx <= 2; wx++) { + windows.add(new WindowKey(wx, wz)); + } + } + Map> views = views(coast, settings, windows); + assertEquals("planning the windows in reverse order changes nothing", views, views(coast, settings, windows.reversed())); + List disagreements = new ArrayList<>(); + int owned = 0; + int crossing = 0; + int seen = 0; + for (WindowKey owner : windows) { + for (SeaInlet inlet : views.get(owner)) { + if (!owner.equals(owner(inlet))) { + continue; + } + owned++; + crossing += leavesWindow(inlet, owner) ? 1 : 0; + for (WindowKey view : windows) { + if (view.equals(owner)) { + continue; + } + for (SeaInlet other : views.get(view)) { + if (other.id() != inlet.id()) { + continue; + } + seen++; + if (!other.equals(inlet)) { + disagreements.add(inlet + " of " + owner + " is " + other + " in " + view); + } + } + } + } + } + assertTrue(disagreements.size() + " views disagree with the owner: " + disagreements, disagreements.isEmpty()); + assertTrue("owned inlets " + owned, owned >= 20); + assertTrue("owned inlets that neighbouring windows also plan " + seen, seen >= 60); + assertTrue("owned inlets crossing a window line " + crossing, crossing > 0); + } + + private static Map> views(InletTerrain coast, HydrologySettings settings, List order) { + Map> views = new LinkedHashMap<>(); + for (WindowKey window : order) { + views.put(window, coast.span(window).plan(settings)); + } + return views; + } + + private static WindowKey owner(SeaInlet inlet) { + return WindowKey.containing((int) Math.floor(inlet.xs()[1]), (int) Math.floor(inlet.zs()[1])); + } + + private static boolean leavesWindow(SeaInlet inlet, WindowKey owner) { + int[] bounds = SeaInletRasterizer.bounds(inlet); + return !WindowKey.containing(bounds[0], bounds[1]).equals(owner) || !WindowKey.containing(bounds[2], bounds[3]).equals(owner); + } + + @Test + public void ownedInletsNeverConflictAcrossAWindowLine() { + IrisHydrology config = new IrisHydrology(); + config.getUnderground().getSeaInlets().setSpacing(WindowKey.SIZE); + config.getUnderground().getSeaInlets().setLength(new KList<>(256, 400)); + config.getUnderground().getSeaInlets().setHalfWidth(new KList<>(12D, 12D)); + HydrologySettings settings = InletTerrain.settings(config); + int bayZ = 904; + WindowKey west = new WindowKey(1, 1); + WindowKey east = new WindowKey(2, 1); + single(InletTerrain.bay(1008, 1008, bayZ).wide(west, 3).plan(settings), west); + single(InletTerrain.bay(1032, 1032, bayZ).wide(east, 3).plan(settings), east); + InletTerrain bay = InletTerrain.bay(1016, 1024, bayZ); + List reference = bay.wide(west, 3).plan(settings); + List union = new ArrayList<>(); + for (int wz = 0; wz <= 2; wz++) { + for (int wx = 0; wx <= 2; wx++) { + WindowKey window = new WindowKey(wx, wz); + List own = bay.span(window).plan(settings).stream().filter(inlet -> owner(inlet).equals(window)).toList(); + assertEquals(window + " owns what the full-context plan gives it", reference.stream() + .filter(inlet -> owner(inlet).equals(window)).toList(), own); + union.addAll(own); + } + } + assertEquals("the two windows beside the bay keep one inlet between them: " + union, 1, union.size()); + for (int first = 0; first < union.size(); first++) { + for (int second = first + 1; second < union.size(); second++) { + assertFalse(union.get(first) + " and " + union.get(second) + " cross a covered passage with an open slot", + coveredMeetsOpen(union.get(first), union.get(second)) || coveredMeetsOpen(union.get(second), union.get(first))); + } + } + } + + private static SeaInlet single(List inlets, WindowKey window) { + List own = inlets.stream().filter(inlet -> owner(inlet).equals(window)).toList(); + assertEquals(window + " owns one bay inlet: " + own, 1, own.size()); + return own.getFirst(); + } + + @Test + public void extentGuardKeepsEveryPlannerLookupInsideTheOwnersSpan() { + for (double halfWidth : new double[]{1D, 16D}) { + for (int chamber = 1; chamber <= 32; chamber++) { + int length = WindowKey.SIZE - 12 - Math.max((int) Math.ceil(halfWidth), chamber) - 3; + IrisHydrology config = new IrisHydrology(); + config.getUnderground().getSeaInlets().setLength(new KList<>(64, length)); + config.getUnderground().getSeaInlets().setHalfWidth(new KList<>(1D, halfWidth)); + config.getUnderground().getSeaInlets().setChamberRadius(new KList<>(1, chamber)); + InletTerrain.settings(config); + long reach = SeaInletPlanner.lookupReach(length, chamber); + assertTrue("length " + length + " chamber " + chamber + " looks " + reach + " blocks out", reach <= WindowKey.SIZE); + } + } + } + + @Test + public void longestInletAtTheFarEdgeOfItsWindowStaysInsideItsSpan() { + IrisHydrology config = new IrisHydrology(); + config.getUnderground().getSeaInlets().setLength(new KList<>(465, 465)); + config.getUnderground().getSeaInlets().setChamberRadius(new KList<>(32, 32)); + HydrologySettings settings = InletTerrain.settings(config); + WindowKey window = new WindowKey(0, 0); + List owned = InletTerrain.eastEdgeCoast().plan(settings).stream().filter(inlet -> owner(inlet).equals(window)).toList(); + assertFalse("inlets start on the window's last column", owned.isEmpty()); + for (SeaInlet inlet : owned) { + assertEquals(inlet + " starts on the window's last column", WindowKey.SIZE - InletTerrain.CELL, inlet.xs()[1], 0f); + assertTrue(inlet + " runs the full length toward the span edge", inlet.chamberX() >= WindowKey.SIZE + 448); + } + } + + @Test + public void ownInletCutOffByTheGridEdgeFailsClosed() { + InletTerrain narrow = InletTerrain.cliff(30D).narrow(0, 0); + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> narrow.plan(InletTerrain.settings())); + assertTrue(failure.getMessage(), + failure.getMessage().matches("Sea inlet -?\\d+ of window WindowKey\\[wx=0, wz=0\\] reaches the edge of .*")); + } + @Test public void inletsReachingPastTheNextWindowAreRejected() { IrisHydrology fits = new IrisHydrology(); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/SeaInletRasterizerTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/SeaInletRasterizerTest.java index 8292f9c95..ab4aef8f2 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/underground/SeaInletRasterizerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/underground/SeaInletRasterizerTest.java @@ -258,6 +258,84 @@ public class SeaInletRasterizerTest { assertTrue(wet > 10); } + @Test + public void passageEndingAtAnOldChunkIsSealed() { + SeaInlet inlet = inlet(1L, 15f); + SeaInletRasterizer.HistoricalChunks old = (chunkX, chunkZ) -> chunkX == 2; + Map open = rasterize(List.of(inlet), order(false), SeaInletRasterizer.SubterrainFluid.NOWHERE, + SeaInletRasterizer.HistoricalChunks.NONE); + Map cells = rasterize(List.of(inlet), newChunks(order(false), old), SeaInletRasterizer.SubterrainFluid.NOWHERE, + old); + int[] column = new int[2]; + int seamColumns = 0; + for (int z = -16; z <= 63; z++) { + for (int x = -32; x <= 79; x++) { + if (old.at(x >> 4, z >> 4) || !nearOldChunk(old, x, z)) { + continue; + } + if (!SeaInletRasterizer.column(inlet, x, z, column) || column[1] == SeaInlet.OPEN) { + continue; + } + assertEquals("without old chunks the seam column " + x + "," + z + " holds water", HydrologyCaveAction.WET_SOURCE, + open.get(key(x, inlet.waterLevel(), z)).action()); + for (int y = column[0] - SeaInletRasterizer.SHELL; y <= column[1]; y++) { + HydrologyCaveCell sealed = cells.get(key(x, y, z)); + assertNotNull("no seal at " + x + "," + y + "," + z + " beside the old chunk", sealed); + assertEquals("seal at " + x + "," + y + "," + z + " beside the old chunk", HydrologyCaveAction.SEAL_GUARD, sealed.action()); + } + seamColumns++; + } + } + int wet = 0; + for (Map.Entry entry : cells.entrySet()) { + int x = x(entry.getKey()); + int y = y(entry.getKey()); + int z = z(entry.getKey()); + assertFalse("old chunk " + (x >> 4) + "," + (z >> 4) + " was written", old.at(x >> 4, z >> 4)); + HydrologyCaveAction action = entry.getValue().action(); + if (action == HydrologyCaveAction.SEAL_GUARD) { + continue; + } + assertFalse(action + " at " + x + "," + y + "," + z + " lies within two blocks of an old chunk", nearOldChunk(old, x, z)); + if (action != HydrologyCaveAction.WET_SOURCE) { + continue; + } + for (int[] side : new int[][]{{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}, {0, -1, 0}}) { + if (paintedSlot(List.of(inlet), x + side[0], y + side[1], z + side[2])) { + continue; + } + HydrologyCaveCell neighbour = cells.get(key(x + side[0], y + side[1], z + side[2])); + assertNotNull("water at " + x + "," + y + "," + z + " has an open side " + side[0] + "," + side[1] + "," + side[2], neighbour); + assertTrue(neighbour.action() == HydrologyCaveAction.WET_SOURCE || neighbour.action() == HydrologyCaveAction.SEAL_GUARD); + } + wet++; + } + assertTrue("covered seam columns " + seamColumns, seamColumns > 10); + assertTrue("water cells away from the old chunks " + wet, wet > 300); + assertEquals(cells, rasterize(List.of(inlet), newChunks(order(true), old), SeaInletRasterizer.SubterrainFluid.NOWHERE, old)); + } + + private static boolean nearOldChunk(SeaInletRasterizer.HistoricalChunks old, int x, int z) { + for (int dz = -SeaInletRasterizer.SHELL; dz <= SeaInletRasterizer.SHELL; dz++) { + for (int dx = -SeaInletRasterizer.SHELL; dx <= SeaInletRasterizer.SHELL; dx++) { + if (old.at((x + dx) >> 4, (z + dz) >> 4)) { + return true; + } + } + } + return false; + } + + private static List newChunks(List chunks, SeaInletRasterizer.HistoricalChunks old) { + List fresh = new ArrayList<>(); + for (int[] chunk : chunks) { + if (!old.at(chunk[0], chunk[1])) { + fresh.add(chunk); + } + } + return fresh; + } + @Test public void chunkOrderAndInletOrderDoNotChangeTheCells() { List inlets = List.of(inlet(1L, 15f), inlet(2L, 22f)); @@ -272,14 +350,16 @@ public class SeaInletRasterizerTest { SeaInlet inlet = inlet(1L, 15f); Map cells = new TreeMap<>(); MantleWriter writer = writer(cells, 1, 0); - new SeaInletRasterizer().write(inlet, 1, 0, writer, FLUID, "", SeaInletRasterizer.SubterrainFluid.NOWHERE); + new SeaInletRasterizer().write(inlet, 1, 0, writer, FLUID, SeaInletRasterizer.SubterrainFluid.NOWHERE, + SeaInletRasterizer.HistoricalChunks.NONE); assertFalse(cells.isEmpty()); for (long key : cells.keySet()) { assertEquals(1, x(key) >> 4); assertEquals(0, z(key) >> 4); } Map far = new TreeMap<>(); - new SeaInletRasterizer().write(inlet, 20, 20, writer(far, 20, 20), FLUID, "", SeaInletRasterizer.SubterrainFluid.NOWHERE); + new SeaInletRasterizer().write(inlet, 20, 20, writer(far, 20, 20), FLUID, SeaInletRasterizer.SubterrainFluid.NOWHERE, + SeaInletRasterizer.HistoricalChunks.NONE); assertTrue(far.isEmpty()); assertFalse(SeaInletRasterizer.touches(inlet, 20, 20)); } @@ -317,12 +397,17 @@ public class SeaInletRasterizerTest { } private static Map rasterize(List inlets, List chunks, SeaInletRasterizer.SubterrainFluid subterrain) { + return rasterize(inlets, chunks, subterrain, SeaInletRasterizer.HistoricalChunks.NONE); + } + + private static Map rasterize(List inlets, List chunks, SeaInletRasterizer.SubterrainFluid subterrain, + SeaInletRasterizer.HistoricalChunks old) { Map cells = new TreeMap<>(); SeaInletRasterizer rasterizer = new SeaInletRasterizer(); for (int[] chunk : chunks) { MantleWriter writer = writer(cells, chunk[0], chunk[1]); for (SeaInlet inlet : inlets) { - rasterizer.write(inlet, chunk[0], chunk[1], writer, FLUID, "", subterrain); + rasterizer.write(inlet, chunk[0], chunk[1], writer, FLUID, subterrain, old); } } return cells; diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/water/PondPlannerTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/water/PondPlannerTest.java index af13a97e6..b57001e87 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/water/PondPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/water/PondPlannerTest.java @@ -106,12 +106,61 @@ public class PondPlannerTest { assertTrue("retained fraction " + fraction, fraction > 0.44D && fraction < 0.56D); } + @Test + public void pondDensityAboveOneAddsPonds() { + HydrologySettings settings = settings(config -> { + seededOnly(config); + config.getPonds().getSeeded().setDensity(10D).setRadius(new KList<>(6, 6)).setDepth(new KList<>(4, 4)).setAlongChannels(false); + config.getPonds().setFreeboard(new KList<>(1, 1)); + }, MIN_Y, MAX_Y); + Terrain flat = new Terrain((x, z) -> 100D, 1f, ALLOW_ALL, null, MIN_Y, MAX_Y); + int moderate = seededPonds(settings, flat.pondDensity((x, z) -> 1.6D)); + int dense = seededPonds(settings, flat.pondDensity((x, z) -> 3D)); + assertTrue("seeded ponds at pondDensity 1.6: " + moderate, moderate >= 10); + assertTrue("seeded ponds at pondDensity 3: " + dense + ", at 1.6: " + moderate, dense > moderate * 1.4D); + } + + @Test + public void seededCupsAgreeAcrossWindowsWherePondDensityVaries() { + HydrologySettings settings = settings(config -> { + seededOnly(config); + config.getPonds().getSeeded().setDensity(10D).setAlongChannels(false); + }, MIN_Y, MAX_Y); + Terrain terrain = new Terrain((x, z) -> 120D + 6D * Math.sin(x / 97D) * Math.cos(z / 131D), 1f, ALLOW_ALL, null, MIN_Y, MAX_Y) + .pondDensity((x, z) -> (0.25D + 0.003D * (x + 512D)) * (1D + 0.3D * Math.sin(z / 150D))); + Set west = sharedCups(settings, terrain, new WindowKey(0, 0)); + Set east = sharedCups(settings, terrain, new WindowKey(1, 0)); + assertTrue("shared cups " + west.size(), west.size() >= 40); + assertEquals(west, east); + } + + private static int seededPonds(HydrologySettings settings, Terrain terrain) { + int seeded = 0; + for (Pond pond : plan(settings, terrain, 0, 0, 64, 64, new BitSet(), List.of())) { + assertEquals(PondKind.SEEDED, pond.kind()); + seeded++; + } + return seeded; + } + + private static Set sharedCups(HydrologySettings settings, Terrain terrain, WindowKey key) { + int span = 3 * WindowKey.SIZE / 8; + Sampled sampled = sample(terrain, 8, (key.wx() - 1) * WindowKey.SIZE, (key.wz() - 1) * WindowKey.SIZE, span, span); + CupSet cups = new PondPlanner(settings).subtractCups(sampled.grid(), key, sampled.samples(), new BitSet()); + Set shared = new HashSet<>(); + for (CupSet.Cup cup : cups.within(-WindowKey.SIZE, -WindowKey.SIZE, 2 * WindowKey.SIZE, 2 * WindowKey.SIZE)) { + if (cup.x() >= 16 && cup.x() < 2 * WindowKey.SIZE - 16 && cup.z() >= 16 - WindowKey.SIZE && cup.z() < 2 * WindowKey.SIZE - 16) { + shared.add(cup); + } + } + return shared; + } + private static Set seededSites(HydrologySettings settings, Terrain terrain) { Set sites = new HashSet<>(); for (int window = 0; window < 32; window++) { int x = window * WindowKey.SIZE; Sampled sampled = sample(terrain, 8, x, 0, 64, 64); - Arrays.fill(sampled.samples().pondDensity(), 100f); CupSet cups = new PondPlanner(settings).subtractCups(sampled.grid(), new WindowKey(window, 0), sampled.samples(), new BitSet()); for (CupSet.Cup cup : cups.within(x, 0, x + WindowKey.SIZE, WindowKey.SIZE)) { sites.add(((long) cup.x() << 32) | (cup.z() & 0xFFFFFFFFL)); @@ -262,7 +311,12 @@ public class PondPlannerTest { config.getPonds().setFreeboard(new KList<>(1, 2)); }, MIN_Y, MAX_Y); DoubleBinaryOperator terrain = (x, z) -> 250D - 0.4D * x; - List ponds = plan(settings, new Terrain(terrain, 1f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, new BitSet(), List.of()); + List ponds = new ArrayList<>(); + for (Pond pond : plan(settings, new Terrain(terrain, 1f, ALLOW_ALL, null, MIN_Y, MAX_Y), -64, -64, 80, 80, new BitSet(), List.of())) { + if (pond.floorX() >= 0 && pond.floorX() < WindowKey.SIZE && pond.floorZ() >= 0 && pond.floorZ() < WindowKey.SIZE) { + ponds.add(pond); + } + } assertTrue("seeded ponds " + ponds.size(), ponds.size() >= 3); for (Pond pond : ponds) { assertEquals(PondKind.SEEDED, pond.kind()); @@ -390,7 +444,7 @@ public class PondPlannerTest { } @Test - public void dryClimateDrawsDownLevel() { + public void lowRainfallDrawsDownPondsOutsideClimateZones() { HydrologySettings settings = settings(PondPlannerTest::naturalOnly, MIN_Y, MAX_Y); DoubleBinaryOperator terrain = bowl(256, 256, 60, 100, 12, 0.1); Pond wet = single(plan(settings, new Terrain(terrain, 1f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, null, List.of())); @@ -402,6 +456,31 @@ public class PondPlannerTest { assertContained(dry, terrain); } + @Test + public void drawdownFollowsClimateDryness() { + HydrologySettings settings = settings(PondPlannerTest::naturalOnly, MIN_Y, MAX_Y); + DoubleBinaryOperator terrain = bowl(256, 256, 60, 100, 12, 0.1); + int drawdown = settings.ponds().climateDrawdown(); + Pond full = single(plan(settings, new Terrain(terrain, 1f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, null, List.of())); + Pond wetZone = single(plan(settings, new Terrain(terrain, 0.5f, ALLOW_ALL, null, MIN_Y, MAX_Y).climateZoned((x, z) -> 1D), + 0, 0, 64, 64, null, List.of())); + Pond dryZone = single(plan(settings, new Terrain(terrain, 1.2f, ALLOW_ALL, null, MIN_Y, MAX_Y).climateZoned((x, z) -> 0.15D), + 0, 0, 64, 64, null, List.of())); + DoubleBinaryOperator band = (x, z) -> Math.clamp(0.5D + (x - 256D) / 512D, 0D, 1D); + Terrain transition = new Terrain(terrain, 1f, ALLOW_ALL, null, MIN_Y, MAX_Y).climateZoned(band); + Pond west = single(plan(settings, transition, 0, 0, 64, 64, null, List.of())); + Pond east = single(plan(settings, transition, 128, 64, 64, 64, null, List.of())); + Pond outsideZones = single(plan(settings, new Terrain(terrain, 0.5f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, null, List.of())); + assertEquals(full.id(), dryZone.id()); + assertEquals(full.level(), wetZone.level()); + assertEquals(full.level() - Math.round(drawdown * 0.85f), dryZone.level()); + assertEquals(full.level() - Math.round(drawdown * 0.5f), west.level()); + assertEquals(west.id(), east.id()); + assertEquals(west.level(), east.level()); + assertEquals(full.level() - Math.round(drawdown * 0.5f), outsideZones.level()); + assertContained(dryZone, terrain); + } + @Test public void pondMaskNeverTouchesHalo() { HydrologySettings settings = settings(config -> { @@ -810,12 +889,15 @@ public class PondPlannerTest { private final int minY; private final int maxY; private final boolean inland; + private final DoubleBinaryOperator pondDensity; + private final DoubleBinaryOperator wetness; private Terrain(DoubleBinaryOperator height, float rainfall, byte permission, String fluid, int minY, int maxY) { - this(height, rainfall, permission, fluid, minY, maxY, false); + this(height, rainfall, permission, fluid, minY, maxY, false, (x, z) -> 1D, null); } - private Terrain(DoubleBinaryOperator height, float rainfall, byte permission, String fluid, int minY, int maxY, boolean inland) { + private Terrain(DoubleBinaryOperator height, float rainfall, byte permission, String fluid, int minY, int maxY, boolean inland, + DoubleBinaryOperator pondDensity, DoubleBinaryOperator wetness) { this.height = height; this.rainfall = rainfall; this.permission = permission; @@ -823,10 +905,20 @@ public class PondPlannerTest { this.minY = minY; this.maxY = maxY; this.inland = inland; + this.pondDensity = pondDensity; + this.wetness = wetness; } private Terrain inland() { - return new Terrain(height, rainfall, permission, fluid, minY, maxY, true); + return new Terrain(height, rainfall, permission, fluid, minY, maxY, true, pondDensity, wetness); + } + + private Terrain pondDensity(DoubleBinaryOperator density) { + return new Terrain(height, rainfall, permission, fluid, minY, maxY, inland, density, wetness); + } + + private Terrain climateZoned(DoubleBinaryOperator zoneWetness) { + return new Terrain(height, rainfall, permission, fluid, minY, maxY, inland, pondDensity, zoneWetness); } @Override @@ -836,7 +928,9 @@ public class PondPlannerTest { out.height()[index] = value; out.ocean()[index] = !inland && value <= SEA_LEVEL; out.rainfall()[index] = rainfall; - out.pondDensity()[index] = 1f; + out.pondDensity()[index] = (float) pondDensity.applyAsDouble(xs[index], zs[index]); + out.wetness()[index] = wetness == null ? 1f : (float) wetness.applyAsDouble(xs[index], zs[index]); + out.climateZoned()[index] = wetness != null; out.permission()[index] = permission; out.fluidProfile()[index] = fluid; } diff --git a/core/src/test/java/art/arcane/iris/generation/locator/BiomeSearchFilterTest.java b/core/src/test/java/art/arcane/iris/generation/locator/BiomeSearchFilterTest.java index 424d8e9e1..980ed7776 100644 --- a/core/src/test/java/art/arcane/iris/generation/locator/BiomeSearchFilterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/locator/BiomeSearchFilterTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.generation.locator; import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.image.IrisImageMapApplication; @@ -132,11 +133,15 @@ public class BiomeSearchFilterTest { @Test public void hydrologyColumnsAreAdmittedForShoreBiomesThePolicyPlaces() { - stubRegions(); - when(complex.getRegionStream()).thenReturn(constantStream(region("host"))); + IrisRegion host = region("host"); + host.setLandBiomes(keys("land_root")); + stubBiome(biome("land_root")); + stubRegions(host); + when(complex.getRegionStream()).thenReturn(constantStream(host)); HydrologyRuntime hydrology = enabledHydrology(); when(complex.getHydrologyRuntime()).thenReturn(hydrology); - when(dimension.getHydrologyPolicy()).thenReturn(new IrisHydrologyPolicy().setShoreBiomes(keys("river_root"))); + when(dimension.getHydrology()).thenReturn(new IrisHydrology().setEnabled(true)); + when(dimension.getHydrologyPolicy()).thenReturn(new IrisHydrologyPolicy().setShoreBiomes(keys("river_root")).setShoreBiomeWidth(4)); IrisBiome river = biome("river_root"); river.setChildren(keys("target")); stubBiome(river); @@ -150,11 +155,15 @@ public class BiomeSearchFilterTest { @Test public void hydrologyIsNotConsultedForBiomesNoHydrologyPolicyPlaces() { - stubRegions(); - when(complex.getRegionStream()).thenReturn(constantStream(region("host"))); + IrisRegion host = region("host"); + host.setLandBiomes(keys("land_root")); + stubBiome(biome("land_root")); + stubRegions(host); + when(complex.getRegionStream()).thenReturn(constantStream(host)); HydrologyRuntime hydrology = enabledHydrology(); when(complex.getHydrologyRuntime()).thenReturn(hydrology); - when(dimension.getHydrologyPolicy()).thenReturn(new IrisHydrologyPolicy().setShoreBiomes(keys("river_root"))); + when(dimension.getHydrology()).thenReturn(new IrisHydrology().setEnabled(true)); + when(dimension.getHydrologyPolicy()).thenReturn(new IrisHydrologyPolicy().setShoreBiomes(keys("river_root")).setShoreBiomeWidth(4)); stubBiome(biome("river_root")); when(engine.answersFromNaturalTerrain(anyInt(), anyInt())).thenReturn(false); @@ -166,10 +175,14 @@ public class BiomeSearchFilterTest { @Test public void disabledHydrologyIsNeverConsultedForPolicyShoreBiomes() { - stubRegions(); - when(complex.getRegionStream()).thenReturn(constantStream(region("host"))); + IrisRegion host = region("host"); + host.setLandBiomes(keys("land_root")); + stubBiome(biome("land_root")); + stubRegions(host); + when(complex.getRegionStream()).thenReturn(constantStream(host)); when(complex.getHydrologyRuntime()).thenReturn(mock(HydrologyRuntime.class)); - when(dimension.getHydrologyPolicy()).thenReturn(new IrisHydrologyPolicy().setShoreBiomes(keys("target"))); + when(dimension.getHydrology()).thenReturn(new IrisHydrology().setEnabled(true)); + when(dimension.getHydrologyPolicy()).thenReturn(new IrisHydrologyPolicy().setShoreBiomes(keys("target")).setShoreBiomeWidth(4)); stubBiome(biome("target")); when(engine.answersFromNaturalTerrain(anyInt(), anyInt())).thenReturn(false); diff --git a/core/src/test/java/art/arcane/iris/generation/locator/HintedLocatorTest.java b/core/src/test/java/art/arcane/iris/generation/locator/HintedLocatorTest.java index 4da71fa2c..08b913783 100644 --- a/core/src/test/java/art/arcane/iris/generation/locator/HintedLocatorTest.java +++ b/core/src/test/java/art/arcane/iris/generation/locator/HintedLocatorTest.java @@ -16,6 +16,7 @@ import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.structure.object.IrisObjectPlacement; import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; import art.arcane.iris.world.history.GenerationSemanticIndex; import art.arcane.iris.spi.IrisPlatform; @@ -283,9 +284,14 @@ public class HintedLocatorTest { HydrologyShoreTargets placed = new HydrologyShoreTargets(Set.of(riverShore.getLoadKey())); HydrologyShoreTargets unplaced = new HydrologyShoreTargets(Set.of(riverShore.getLoadKey())); - when(dimension.getHydrologyPolicy()).thenReturn(new IrisHydrologyPolicy().setShoreBiomes(keys(riverShore.getLoadKey()))); - stubRegions(); + IrisRegion host = region("host"); + host.setLandBiomes(keys(plains.getLoadKey())); + when(dimension.getHydrology()).thenReturn(new IrisHydrology().setEnabled(true)); + when(dimension.getHydrologyPolicy()).thenReturn(new IrisHydrologyPolicy() + .setShoreBiomes(keys(riverShore.getLoadKey())).setShoreBiomeWidth(4)); + stubRegions(host); stubBiome(riverShore); + stubBiome(plains); assertTrue(Locator.chunkContainsSurfaceBiome(engine, new Position2(2, 0), riverShore.getLoadKey(), placed)); assertFalse(Locator.chunkContainsSurfaceBiome(engine, new Position2(8, 0), riverShore.getLoadKey(), placed)); diff --git a/core/src/test/java/art/arcane/iris/generation/locator/HydrologyShoreTargetsTest.java b/core/src/test/java/art/arcane/iris/generation/locator/HydrologyShoreTargetsTest.java new file mode 100644 index 000000000..a569dcff1 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/locator/HydrologyShoreTargetsTest.java @@ -0,0 +1,62 @@ +package art.arcane.iris.generation.locator; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.hydrology.config.IrisHydrology; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.pack.loading.ResourceLoader; +import art.arcane.volmlib.util.collection.KList; +import org.junit.Test; + +import java.util.Set; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class HydrologyShoreTargetsTest { + @Test + @SuppressWarnings("unchecked") + public void listsWithoutWidthPlaceNothing() { + IrisDimension dimension = new IrisDimension() + .setRegions(new KList<>("coast")) + .setHydrology(new IrisHydrology().setEnabled(true)) + .setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("beach"))); + IrisRegion coast = new IrisRegion() + .setLandBiomes(new KList<>("plains")) + .setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("dune"))); + coast.setLoadKey("coast"); + IrisData data = mock(IrisData.class); + ResourceLoader regionLoader = mock(ResourceLoader.class); + ResourceLoader biomeLoader = mock(ResourceLoader.class); + when(data.getRegionLoader()).thenReturn(regionLoader); + when(data.getBiomeLoader()).thenReturn(biomeLoader); + when(regionLoader.load("coast")).thenReturn(coast); + when(biomeLoader.load("plains")).thenReturn(biome("plains")); + when(biomeLoader.load("beach")).thenReturn(biome("beach")); + when(biomeLoader.load("dune")).thenReturn(biome("dune")); + Engine engine = mock(Engine.class); + when(engine.getDimension()).thenReturn(dimension); + when(engine.getData()).thenReturn(data); + + assertFalse(HydrologyShoreTargets.placesAny(engine, Set.of("beach"))); + assertFalse(HydrologyShoreTargets.placesAny(engine, Set.of("dune"))); + + dimension.getHydrologyPolicy().setShoreBiomeWidth(3); + assertTrue(HydrologyShoreTargets.placesAny(engine, Set.of("dune"))); + assertFalse(HydrologyShoreTargets.placesAny(engine, Set.of("beach"))); + + coast.getHydrologyPolicy().setShoreBiomeWidth(0); + assertFalse(HydrologyShoreTargets.placesAny(engine, Set.of("dune"))); + } + + private static IrisBiome biome(String key) { + IrisBiome biome = new IrisBiome(); + biome.setLoadKey(key); + return biome; + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/CarveOwnershipTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/CarveOwnershipTest.java new file mode 100644 index 000000000..d448ee00f --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/mantle/CarveOwnershipTest.java @@ -0,0 +1,216 @@ +package art.arcane.iris.generation.mantle; + +import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction; +import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.generation.subterrain.IrisSubterrainFamily; +import art.arcane.iris.generation.subterrain.SubterrainCell; +import art.arcane.iris.generation.subterrain.SubterrainRoom; +import art.arcane.iris.generation.terrain.Terrain3DColumn; +import art.arcane.iris.testsupport.PlatformBinding; +import art.arcane.volmlib.util.mantle.runtime.Mantle; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.mantle.runtime.TectonicPlate; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.MatterSlice; +import org.junit.Rule; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class CarveOwnershipTest { + private static final int X = 1; + private static final int Y = 2; + private static final int Z = 3; + private static final int HEIGHT = 64; + private static final SubterrainCell OPEN_ROOM = new SubterrainCell(SubterrainCell.Kind.AIR, "", room(false, false)); + private static final SubterrainCell RESERVED_SOLID = new SubterrainCell(SubterrainCell.Kind.SOLID, "", room(false, true)); + private static final SubterrainCell RESERVED_PASSAGE = new SubterrainCell(SubterrainCell.Kind.AIR, "", room(true, false)); + private static final SubterrainCell SHELL = new SubterrainCell(SubterrainCell.Kind.SOLID, "", room(false, false)); + private static final HydrologyCaveCell[] HYDROLOGY = { + null, new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")}; + private static final SubterrainCell[] SUBTERRAIN = {SubterrainCell.OUTSIDE, OPEN_ROOM, RESERVED_SOLID, RESERVED_PASSAGE, SHELL}; + + @Rule + public final PlatformBinding platform = PlatformBinding.mockPlatform(); + + @Test + public void resolveRanksHydrologyThenSubterrainThenNaturalOpening() { + assertEquals(CarveOwnership.Owner.CAVERN, CarveOwnership.resolve(false, false, false)); + assertEquals(CarveOwnership.Owner.NATURAL_OPENING, CarveOwnership.resolve(false, false, true)); + assertEquals(CarveOwnership.Owner.SUBTERRAIN, CarveOwnership.resolve(false, true, false)); + assertEquals(CarveOwnership.Owner.SUBTERRAIN, CarveOwnership.resolve(false, true, true)); + assertEquals(CarveOwnership.Owner.HYDROLOGY, CarveOwnership.resolve(true, false, false)); + assertEquals(CarveOwnership.Owner.HYDROLOGY, CarveOwnership.resolve(true, false, true)); + assertEquals(CarveOwnership.Owner.HYDROLOGY, CarveOwnership.resolve(true, true, false)); + assertEquals(CarveOwnership.Owner.HYDROLOGY, CarveOwnership.resolve(true, true, true)); + } + + @Test + public void subterrainClaimsOpenRoomsAndReservedSolidsButNotShells() { + assertFalse(CarveOwnership.subterrainClaims(null)); + assertFalse(CarveOwnership.subterrainClaims(SubterrainCell.OUTSIDE)); + assertTrue(CarveOwnership.subterrainClaims(OPEN_ROOM)); + assertTrue(CarveOwnership.subterrainClaims(new SubterrainCell(SubterrainCell.Kind.WATER, "", room(false, false)))); + assertTrue(CarveOwnership.subterrainClaims(RESERVED_SOLID)); + assertTrue(CarveOwnership.subterrainClaims(RESERVED_PASSAGE)); + assertFalse(CarveOwnership.subterrainClaims(SHELL)); + } + + @Test + public void allReadersAgreeOnTheNaturalLayer() { + List disagreements = new ArrayList<>(); + for (HydrologyCaveCell hydrology : HYDROLOGY) { + for (SubterrainCell subterrain : SUBTERRAIN) { + for (boolean naturalOpening : new boolean[]{false, true}) { + for (boolean cavern : new boolean[]{false, true}) { + boolean claims = subterrain == OPEN_ROOM || subterrain == RESERVED_SOLID + || subterrain == RESERVED_PASSAGE; + boolean expected = switch (CarveOwnership.resolve(hydrology != null, claims, naturalOpening)) { + case HYDROLOGY -> hydrology.carves(); + case SUBTERRAIN -> subterrain.carve(); + case NATURAL_OPENING -> true; + case CAVERN -> cavern; + }; + Sources sources = Sources.mocked(hydrology, subterrain, naturalOpening, cavern, null); + String state = "hydrology=" + (hydrology == null ? "none" : hydrology.action()) + + " subterrain=" + describe(subterrain) + " naturalOpening=" + naturalOpening + + " cavern=" + cavern; + compare(disagreements, state, expected, readers(sources)); + } + } + } + } + assertTrue(String.join("\n", disagreements), disagreements.isEmpty()); + } + + @Test + public void transformedColumnsYieldOnlyToReservedSubterrainOutsideHydrology() { + List disagreements = new ArrayList<>(); + for (boolean transformedOpen : new boolean[]{false, true}) { + for (HydrologyCaveCell hydrology : HYDROLOGY) { + for (SubterrainCell subterrain : SUBTERRAIN) { + for (boolean cavern : new boolean[]{false, true}) { + boolean reserved = subterrain == RESERVED_SOLID || subterrain == RESERVED_PASSAGE; + boolean expected = hydrology == null && reserved ? subterrain.carve() : transformedOpen; + Sources sources = Sources.mocked(hydrology, subterrain, false, cavern, column(transformedOpen)); + String state = "transformedOpen=" + transformedOpen + + " hydrology=" + (hydrology == null ? "none" : hydrology.action()) + + " subterrain=" + describe(subterrain) + " cavern=" + cavern; + compare(disagreements, state, expected, readers(sources)); + } + } + } + } + assertTrue(String.join("\n", disagreements), disagreements.isEmpty()); + } + + private static void compare(List disagreements, String state, boolean expected, Map readers) { + for (Map.Entry reader : readers.entrySet()) { + if (reader.getValue() != expected) { + disagreements.add(state + ": " + reader.getKey() + " gives " + reader.getValue() + ", the rule gives " + expected); + } + } + agree(disagreements, state, readers, "MantleWriter.isCarved", "MantleWriter.getCarvedColumn"); + agree(disagreements, state, readers, "MantleWriter.isPrerequisiteCarved", "MantleWriter.getPrerequisiteCarvedColumn"); + } + + private static void agree(List disagreements, String state, Map readers, String point, String column) { + if (!readers.get(point).equals(readers.get(column))) { + disagreements.add(state + ": " + point + " gives " + readers.get(point) + " but " + column + " gives " + + readers.get(column)); + } + } + + private static Map readers(Sources sources) { + Map readers = new LinkedHashMap<>(); + readers.put("MantleWriter.isCarved", sources.writer(writer -> writer.isCarved(X, Y, Z))); + readers.put("MantleWriter.isPrerequisiteCarved", sources.writer(writer -> writer.isPrerequisiteCarved(X, Y, Z))); + readers.put("MantleWriter.getCarvedColumn", sources.writer(writer -> writer.getCarvedColumn(X, Z, HEIGHT)[Y] != 0)); + readers.put("MantleWriter.getPrerequisiteCarvedColumn", + sources.writer(writer -> writer.getPrerequisiteCarvedColumn(X, Z, HEIGHT)[Y] != 0)); + readers.put("EngineMantle.isCarved", sources.engineMantle().isCarved(X, Y, Z)); + return readers; + } + + private static String describe(SubterrainCell subterrain) { + if (subterrain == OPEN_ROOM) { + return "open-room"; + } + if (subterrain == RESERVED_SOLID) { + return "reserved-solid"; + } + if (subterrain == RESERVED_PASSAGE) { + return "reserved-passage"; + } + return subterrain == SHELL ? "shell" : "outside"; + } + + private static SubterrainRoom room(boolean reservedPassage, boolean reservedSolid) { + return new SubterrainRoom("room", "", IrisSubterrainFamily.CENOTE, + 0, 0, 0, 0, 0, 0, -10, 10, 1D, 0, reservedPassage, reservedSolid, SubterrainCell.Kind.AIR); + } + + private static Terrain3DColumn column(boolean openAtY) { + return Terrain3DColumn.fromOccupancy(HEIGHT - 1, HEIGHT, y -> !openAtY || y != Y); + } + + private record Sources(EngineMantle engineMantle, Mantle mantle) { + private boolean writer(Predicate query) { + try (MantleWriter writer = new MantleWriter(engineMantle, mantle, 0, 0, 0, false)) { + return query.test(writer); + } + } + + @SuppressWarnings("unchecked") + private static Sources mocked(HydrologyCaveCell hydrology, SubterrainCell subterrain, boolean naturalOpening, + boolean cavern, Terrain3DColumn transformed) { + MatterCavern carved = cavern ? new MatterCavern(true, "", (byte) 0) : null; + EngineMantle engineMantle = mock(EngineMantle.class); + Engine engine = mock(Engine.class); + IrisComplex complex = mock(IrisComplex.class); + Mantle mantle = mock(Mantle.class); + TectonicPlate plate = mock(TectonicPlate.class); + MantleChunk chunk = mock(MantleChunk.class); + Matter matter = mock(Matter.class); + MatterSlice hydrologySlice = mock(MatterSlice.class); + MatterSlice cavernSlice = mock(MatterSlice.class); + when(engineMantle.getEngine()).thenReturn(engine); + when(engineMantle.getComplex()).thenReturn(complex); + when(engineMantle.getMantle()).thenReturn(mantle); + when(engineMantle.isCarved(anyInt(), anyInt(), anyInt())).thenCallRealMethod(); + when(engine.getSubterrainCell(X, Y, Z)).thenReturn(subterrain); + when(complex.transformedColumn(X, Z)).thenReturn(transformed); + when(complex.terrainColumn(X, Z)).thenReturn(transformed != null ? transformed : naturalOpening ? column(true) : null); + when(complex.isTerrain3DOpening(X, Y, Z)).thenReturn(naturalOpening); + when(mantle.getWorldHeight()).thenReturn(HEIGHT); + when(mantle.useChunk(0, 0)).thenReturn(chunk); + when(mantle.getLoadedRegion(0, 0)).thenReturn(plate); + when(mantle.get(X, Y, Z, MatterCavern.class)).thenReturn(carved); + when(plate.get(0, 0)).thenReturn(chunk); + when(chunk.exists(0)).thenReturn(true); + when(chunk.get(0)).thenReturn(matter); + when(matter.hasSlice(HydrologyCaveCell.class)).thenReturn(true); + when(matter.hasSlice(MatterCavern.class)).thenReturn(true); + doReturn(hydrologySlice).when(matter).getSlice(HydrologyCaveCell.class); + doReturn(cavernSlice).when(matter).getSlice(MatterCavern.class); + when(hydrologySlice.get(X, Y, Z)).thenReturn(hydrology); + when(cavernSlice.get(X, Y, Z)).thenReturn(carved); + return new Sources(engineMantle, mantle); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/CaveCeilingMaskTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/CaveCeilingMaskTest.java index 6a999af17..83b3c5af9 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/CaveCeilingMaskTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/CaveCeilingMaskTest.java @@ -2,11 +2,14 @@ package art.arcane.iris.generation.mantle; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; +import art.arcane.iris.generation.hydrology.underground.SeaInlet; +import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer; import art.arcane.iris.testsupport.WaterScene; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import org.junit.Test; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.function.IntBinaryOperator; @@ -17,6 +20,9 @@ import static org.junit.Assert.assertTrue; public class CaveCeilingMaskTest { private static final int UNMASKED = CaveCeilingMask.UNMASKED; + private static final int SEA = 63; + private static final int ROOF_CLEARANCE = 6; + private static final int NO_ROOF = Integer.MIN_VALUE; @Test public void cavesStopTwoBlocksBelowEveryBedAndColumnsWithinTwoBlocksTakeTheLowestCeiling() { @@ -95,6 +101,99 @@ public class CaveCeilingMaskTest { } } + @Test + public void cavesStayOutOfInletHeadroom() { + SeaInlet inlet = inlet(); + int[] bounds = SeaInletRasterizer.bounds(inlet); + long[] bands = new long[256]; + int[] column = new int[2]; + int covered = 0; + int around = 0; + 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++) { + boolean masked = CaveCeilingMask.fillHeadroom(chunkX, chunkZ, List.of(inlet), ROOF_CLEARANCE, bands); + long[] headroom = masked ? bands : null; + boolean expectedMasked = 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; + int index = PowerOfTwoCoordinates.packLocal16(lx, lz); + int top = highestRoofWithinTwo(inlet, x, z); + if (top == NO_ROOF) { + for (int y = 0; y <= SEA + 64; y++) { + assertFalse("caves stay possible at " + x + "," + y + "," + z + " away from the inlet", + CaveCeilingMask.masked(null, headroom, index, y)); + } + continue; + } + expectedMasked = true; + for (int y = inlet.waterLevel() + 1; y <= top; y++) { + assertTrue("caves stay out of the inlet headroom and roof at " + x + "," + y + "," + z, + CaveCeilingMask.masked(null, headroom, index, y)); + } + assertFalse("the seal holds caves at the water level " + x + "," + z, + CaveCeilingMask.masked(null, headroom, index, inlet.waterLevel())); + assertFalse("caves stay possible above the inlet roof at " + x + "," + z, + CaveCeilingMask.masked(null, headroom, index, top + 1)); + if (SeaInletRasterizer.column(inlet, x, z, column) && column[1] != SeaInlet.OPEN) { + covered++; + } else { + around++; + } + } + } + assertEquals("headroom flag for chunk " + chunkX + "," + chunkZ, expectedMasked, masked); + } + } + assertTrue("covered columns " + covered, covered > 300); + assertTrue("columns around the passage " + around, around > 100); + assertFalse(CaveCeilingMask.fillHeadroom(0, 0, List.of(), ROOF_CLEARANCE, bands)); + } + + @Test + public void headroomJoinsTheWaterCeilings() { + int[] ceilings = new int[256]; + Arrays.fill(ceilings, UNMASKED); + ceilings[3] = 40; + long[] bands = new long[256]; + assertTrue(CaveCeilingMask.fillHeadroom(0, 0, List.of(inlet()), ROOF_CLEARANCE, bands)); + int index = PowerOfTwoCoordinates.packLocal16(12, 6); + assertTrue(CaveCeilingMask.masked(ceilings, null, 3, 41)); + assertFalse(CaveCeilingMask.masked(ceilings, null, 3, 40)); + assertFalse(CaveCeilingMask.masked(ceilings, bands, index, SEA)); + assertTrue(CaveCeilingMask.masked(ceilings, bands, index, SEA + 1)); + assertFalse(CaveCeilingMask.masked(null, null, index, SEA + 1)); + } + + private static SeaInlet inlet() { + float[] xs = {-8f, 0f, 8f, 16f, 24f, 32f, 40f, 48f}; + float[] zs = new float[xs.length]; + float[] halfWidth = new float[xs.length]; + int[] floor = new int[xs.length]; + int[] ceiling = new int[xs.length]; + for (int station = 0; station < xs.length; station++) { + zs[station] = 6f + (station % 2 == 0 ? 0f : 3f); + halfWidth[station] = 5f - station * 0.4f; + floor[station] = SEA - 2 - station % 3; + ceiling[station] = station < 2 ? SeaInlet.OPEN : SEA + 4 + station % 4; + } + return new SeaInlet(1L, xs, zs, halfWidth, SEA, floor, ceiling, 48, 6, 7); + } + + private static int highestRoofWithinTwo(SeaInlet inlet, int x, int z) { + int top = NO_ROOF; + int[] column = new int[2]; + for (int dz = -CaveCeilingMask.CONTAINMENT; dz <= CaveCeilingMask.CONTAINMENT; dz++) { + for (int dx = -CaveCeilingMask.CONTAINMENT; dx <= CaveCeilingMask.CONTAINMENT; dx++) { + if (SeaInletRasterizer.column(inlet, x + dx, z + dz, column) && column[1] != SeaInlet.OPEN) { + top = Math.max(top, column[1] + ROOF_CLEARANCE); + } + } + } + return top; + } + static WaterScene scene(IrisHydrology config) { IntBinaryOperator natural = (x, z) -> 80; return new WaterScene(config, natural) diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/CaveObjectPlacementTransactionTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/CaveObjectPlacementTransactionTest.java index a92b31257..c01fbe959 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/CaveObjectPlacementTransactionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/CaveObjectPlacementTransactionTest.java @@ -231,7 +231,7 @@ public class CaveObjectPlacementTransactionTest { public void dryHydrologyHeadroomRejectsTheWholePlacement() { IObjectPlacer delegate = createPlacer(128, 80, 20, 90); when(delegate.getData(4, 30, 7, HydrologyCaveCell.class)) - .thenReturn(HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR)); + .thenReturn(new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water")); CaveObjectPlacementTransaction transaction = new CaveObjectPlacementTransaction(delegate, 20, 10); transaction.set(4, 30, 7, mock(NativeBlockState.class)); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/CaveTerrainSnapshotTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/CaveTerrainSnapshotTest.java index aacd00b00..e58ce2e1b 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/CaveTerrainSnapshotTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/CaveTerrainSnapshotTest.java @@ -143,7 +143,7 @@ public class CaveTerrainSnapshotTest { } HydrologyCaveCell[] hydrology = new HydrologyCaveCell[HydrologyCaveAction.values().length]; for (int index = 0; index < hydrology.length; index++) { - hydrology[index] = new HydrologyCaveCell(HydrologyCaveAction.values()[index], "river", "flooded-" + index); + hydrology[index] = new HydrologyCaveCell(HydrologyCaveAction.values()[index], "river"); } Matter[] sections = new Matter[SECTIONS]; for (int section = 0; section < SECTIONS; section++) { diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvedTerrainTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvedTerrainTest.java index de5db777c..4fe83f70f 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvedTerrainTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvedTerrainTest.java @@ -3,6 +3,7 @@ package art.arcane.iris.generation.mantle; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; +import art.arcane.iris.generation.hydrology.config.IrisFluidProfile; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; @@ -12,12 +13,15 @@ import art.arcane.iris.generation.hydrology.underground.CaveVoxel; import art.arcane.iris.generation.hydrology.underground.SeaInlet; import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer; import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.EnginePlatformHooks; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.stream.ProvisionalSampling; import art.arcane.iris.generation.subterrain.SubterrainCell; import art.arcane.iris.generation.subterrain.SubterrainPlan; import art.arcane.iris.generation.subterrain.SubterrainPlanner; import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisMaterialPalette; +import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.generation.terrain.Terrain3DColumn; import art.arcane.iris.world.IrisWorld; import art.arcane.iris.world.storage.matter.IrisMatterSupport; @@ -31,13 +35,18 @@ import art.arcane.volmlib.util.matter.IrisMatter; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.stream.ProceduralStream; +import art.arcane.volmlib.util.stream.interpolation.Interpolated; import org.junit.BeforeClass; import org.junit.Test; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -78,8 +87,8 @@ public class MantleCarvedTerrainTest { sections[1].slice(PreObjectMatterCell.class).set(9, 4, 9, PreObjectMatterCell.cavern(null)); IrisBiome flooded = new IrisBiome(); flooded.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("lava")); - when(scene.engine.getCaveBiome(1, 20, 1)).thenReturn(flooded); - when(scene.engine.getCaveBiome(5, 20, 5)).thenReturn(new IrisBiome()); + when(scene.engine.getCaveBiomeBelowSurface(1, 20, 1)).thenReturn(flooded); + when(scene.engine.getCaveBiomeBelowSurface(5, 20, 5)).thenReturn(new IrisBiome()); MantleCarvedTerrain carved = scene.carved(); @@ -214,6 +223,92 @@ public class MantleCarvedTerrainTest { } } + @Test + public void shallowPoolsUnderVolcanicSurfacesStayWater() { + IrisBiome volcanoes = biome("tropical/volcanoes", 0, "lava"); + IrisRegion tropical = region("tropical", null); + Scene shallow = poolRoom(new Underground(volcanoes, biome("carving/hollow", 24, null), tropical, new IrisDimension())); + Scene uncovered = poolRoom(new Underground(volcanoes, new IrisBiome(), tropical, new IrisDimension())); + + assertNull("above the cave biome's depth", shallow.carved().caveFluid(7, 23, 7)); + assertNull("in a region without cave biomes", uncovered.carved().caveFluid(7, 23, 7)); + assertEquals(Set.of("water"), poolFluids(shallow.generate(0))); + assertEquals(Set.of("water"), poolFluids(uncovered.generate(0))); + } + + @Test + public void caveBiomeFluidSwitchesPools() { + IrisBiome plains = biome("temperate/plains", 0, null); + IrisBiome hollow = biome("carving/hollow", 0, null); + IrisRegion temperate = region("temperate", null); + IrisRegion volcanic = region("volcanic", "lava"); + IrisDimension molten = new IrisDimension().setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("lava")); + + assertEquals("the cave biome's own fluid", Set.of("lava"), + poolFluids(poolRoom(new Underground(plains, biome("carving/magma", 0, "lava"), temperate, new IrisDimension())).generate(0))); + assertEquals("the region's fluid under a cave biome without one", Set.of("lava"), + poolFluids(poolRoom(new Underground(plains, hollow, volcanic, new IrisDimension())).generate(0))); + assertEquals("the dimension's fluid under a region without one", Set.of("lava"), + poolFluids(poolRoom(new Underground(plains, hollow, temperate, molten)).generate(0))); + assertEquals("the cave biome's fluid before the region and the dimension", Set.of("water"), + poolFluids(poolRoom(new Underground(plains, biome("carving/spring", 0, "water"), volcanic, molten)).generate(0))); + assertEquals("a cave biome's fluid only where the cave biome reaches", Set.of("water"), + poolFluids(poolRoom(new Underground(plains, biome("carving/deep-magma", 24, "lava"), temperate, new IrisDimension())).generate(0))); + } + + @Test + public void caveBiomesTakeNoFluidFromBiomesThatListThemAsChildren() { + IrisBiome volcanic = biome("tropical/volcanic-plains", 0, "lava").setChildren(new KList<>("carving/hollow")); + IrisBiome magma = biome("carving/magma", 0, "lava").setChildren(new KList<>("carving/hollow")); + IrisBiome hollow = biome("carving/hollow", 0, null); + + assertEquals("a cave biome under a surface parent that names lava", Set.of("water"), + poolFluids(poolRoom(new Underground(volcanic, hollow, region("temperate", null), new IrisDimension())).generate(0))); + assertEquals("the parent itself still fills its own pools", Set.of("lava"), + poolFluids(poolRoom(new Underground(volcanic, magma, region("temperate", null), new IrisDimension())).generate(0))); + } + + private static Scene poolRoom(Underground underground) { + Scene scene = new Scene(underground); + Matter[] room = scene.chunk(0, 0); + for (int x = 1; x <= 14; x++) { + for (int z = 1; z <= 14; z++) { + for (int y = 22; y <= 30; y++) { + cavern(room, x, y, z, (byte) 0); + } + } + } + return scene; + } + + private static Set poolFluids(Map written) { + Set fluids = new HashSet<>(); + for (HydrologyCaveCell cell : written.values()) { + if (cell.action() == HydrologyCaveAction.POOL_SOURCE) { + fluids.add(cell.fluidProfileKey()); + } + } + return fluids; + } + + private static IrisBiome biome(String key, int caveMinDepth, String fluid) { + IrisBiome biome = new IrisBiome().setCaveMinDepthBelowSurface(caveMinDepth); + biome.setLoadKey(key); + if (fluid != null) { + biome.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid(fluid)); + } + return biome; + } + + private static IrisRegion region(String key, String fluid) { + IrisRegion region = new IrisRegion(); + region.setLoadKey(key); + if (fluid != null) { + region.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid(fluid)); + } + return region; + } + private static Scene inletScene() { Scene scene = new Scene(); Matter[] room = scene.chunk(0, 0); @@ -263,24 +358,62 @@ public class MantleCarvedTerrainTest { sections[y >> 4].slice(MatterCavern.class).set(x & 15, y & 15, z & 15, new MatterCavern(true, "", liquid)); } + private record Underground(IrisBiome surface, IrisBiome cave, IrisRegion region, IrisDimension dimension) { + private Engine engine(IrisComplex complex) { + IrisWorld world = mock(IrisWorld.class); + EnginePlatformHooks hooks = new EnginePlatformHooks() { + }; + return (Engine) Proxy.newProxyInstance(Engine.class.getClassLoader(), new Class[]{Engine.class}, + (proxy, method, arguments) -> switch (method.getName()) { + case "getComplex" -> complex; + case "getDimension" -> dimension; + case "getWorld" -> world; + case "getPlatformHooks" -> hooks; + case "getData" -> null; + default -> InvocationHandler.invokeDefault(proxy, method, arguments); + }); + } + } + private static final class Scene { private final Map> chunks = new HashMap<>(); private final Map sections = new HashMap<>(); private final MantleWriter writer = mock(MantleWriter.class); private final IrisComplex complex = mock(IrisComplex.class); - private final Engine engine = mock(Engine.class); + private final Engine engine; private final List inlets = new ArrayList<>(); private final Map cells = new HashMap<>(); - @SuppressWarnings("unchecked") private Scene() { + this.engine = mock(Engine.class); + when(engine.getDimension()).thenReturn(new IrisDimension()); + when(engine.getWorld()).thenReturn(mock(IrisWorld.class)); + wire(); + } + + private Scene(Underground underground) { + this.engine = underground.engine(complex); + wire(); + when(complex.getTrueBiomeStream()).thenReturn(constant(underground.surface())); + when(complex.getCaveBiomeStream()).thenReturn(constant(underground.cave())); + when(complex.getRegionStream()).thenReturn(constant(underground.region())); + } + + private static ProceduralStream constant(T value) { + return ProceduralStream.of((x, z) -> value, Interpolated.of(ignored -> 0D, ignored -> value)); + } + + @SuppressWarnings("unchecked") + private void wire() { Mantle mantle = mock(Mantle.class); when(mantle.getWorldHeight()).thenReturn(HEIGHT); when(writer.getMantle()).thenReturn(mantle); when(writer.acquireChunk(anyInt(), anyInt())).thenAnswer(invocation -> mantleChunk(invocation.getArgument(0), invocation.getArgument(1))); ProceduralStream heights = mock(ProceduralStream.class); when(heights.getDouble(anyDouble(), anyDouble())).thenReturn(40.4D); + when(heights.get(anyDouble(), anyDouble())).thenReturn(40.4D); when(complex.getHeightStream()).thenReturn(heights); + when(complex.getRegionStream()).thenReturn(constant(new IrisRegion())); when(complex.allowsMantleChunkWrite(anyInt(), anyInt())).thenReturn(true); HydrologyRuntime runtime = mock(HydrologyRuntime.class); when(runtime.caveFluidPolicies()).thenReturn(true); @@ -296,9 +429,6 @@ public class MantleCarvedTerrainTest { return null; }).when(writer).withChunkFence(anyInt(), anyInt(), any(Runnable.class)); when(complex.getHydrologyRuntime()).thenReturn(runtime); - when(engine.getDimension()).thenReturn(new IrisDimension()); - when(engine.getWorld()).thenReturn(mock(IrisWorld.class)); - when(engine.getCaveBiome(anyInt(), anyInt(), anyInt())).thenReturn(null); } private MantleCarvedTerrain carved() { @@ -317,12 +447,14 @@ public class MantleCarvedTerrainTest { private Map generate(int... chunkZs) { IrisHydrology config = new IrisHydrology().setEnabled(true); + config.getFluids().add(new IrisFluidProfile().setName("lava").setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:lava"))); config.getUnderground().getCavePools().setDensity(8D).setFreeboard(new KList<>(0, 0)); HydrologySettings settings = HydrologySettings.compile(config, SEED, 63, 0, 384); SeaInletRasterizer rasterizer = new SeaInletRasterizer(); for (int chunkZ : chunkZs) { for (SeaInlet inlet : complex.getHydrologyRuntime().inlets(0, chunkZ)) { - rasterizer.write(inlet, 0, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, "", SeaInletRasterizer.SubterrainFluid.NOWHERE); + rasterizer.write(inlet, 0, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, SeaInletRasterizer.SubterrainFluid.NOWHERE, + SeaInletRasterizer.HistoricalChunks.NONE); } new CavePoolFiller(settings).fill(0, chunkZ, () -> new MantleCarvedTerrain(writer, complex, engine, 0, chunkZ), writer, SEED); } diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentWaterMaskTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentWaterMaskTest.java index 7ee67d098..ece508d96 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentWaterMaskTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentWaterMaskTest.java @@ -4,8 +4,12 @@ import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.block.B; import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.context.ChunkContext; +import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; +import art.arcane.iris.generation.hydrology.plan.HydrologySettings; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; +import art.arcane.iris.generation.hydrology.underground.SeaInlet; +import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.EngineMetrics; import art.arcane.iris.generation.runtime.IrisComplex; @@ -21,6 +25,7 @@ import art.arcane.iris.world.IrisWorld; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.mantle.runtime.Mantle; import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.stream.ProceduralStream; import org.junit.Before; @@ -34,6 +39,7 @@ import java.util.List; 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; @@ -47,6 +53,7 @@ import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; public class MantleCarvingComponentWaterMaskTest { + private static final int ROOF_CLEARANCE = 6; private Engine engine; private MantleCarvingComponent component; private IrisDimension dimension; @@ -141,6 +148,105 @@ public class MantleCarvingComponentWaterMaskTest { } } + @Test + public void inletHeadroomJoinsTheProfilePassProtection() throws Exception { + SeaInlet inlet = coveredInlet(32, 40, 40); + installInlet(inlet); + IrisCaveCarver3D carver = installProfile(); + List boundaries = new ArrayList<>(); + doAnswer(call -> { + boundaries.add(((long[]) call.getArgument(8)).clone()); + return 0; + }).when(carver).carve(any(), anyInt(), anyInt(), any(), anyDouble(), anyDouble(), any(), any(), any(), any(), any(), any()); + + component.generateLayer(writer, 2, 2, context); + + assertEquals(1, boundaries.size()); + int[] column = new int[2]; + int covered = 0; + for (int lz = 0; lz < 16; lz++) { + for (int lx = 0; lx < 16; lx++) { + int index = PowerOfTwoCoordinates.packLocal16(lx, lz); + if (!SeaInletRasterizer.column(inlet, 32 + lx, 32 + lz, column)) { + continue; + } + for (int y = inlet.waterLevel() + 1; y <= column[1] + ROOF_CLEARANCE; y++) { + assertTrue("the carver keeps out of the inlet headroom at " + (32 + lx) + "," + y + "," + (32 + lz), + SurfaceFluidBoundaryPlan.protects(boundaries.getFirst(), index, y)); + } + assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries.getFirst(), index, inlet.waterLevel())); + covered++; + } + } + assertTrue("covered columns " + covered, covered > 80); + } + + @Test + public void subterrainFeaturesStayOutOfInletHeadroom() { + IrisSubterrainFeature feature = new IrisSubterrainFeature().setId("room").setFamily(IrisSubterrainFamily.CENOTE) + .setProbability(1).setLength(64).setRadius(12).setHeight(24).setPillarSpacing(0).setFormationFraction(0) + .setWorldYRange(new IrisRange(-48, 60)); + SubterrainPlanner planner = new SubterrainPlanner(new SubterrainPlanner.Options(List.of(feature), 83L, -64, 128, (x, z) -> "region")); + SubterrainPlan plan = planner.plansForBounds(-512, -512, 512, 512).getFirst(); + int chunkX = plan.centerX() >> 4; + int chunkZ = plan.centerZ() >> 4; + when(complex.getSubterrainPlanner()).thenReturn(planner); + try (MockedStatic blocks = mockStatic(B.class)) { + blocks.when(() -> B.getState(anyString())).thenReturn(mock(NativeBlockState.class)); + List open = openedCells(chunkX, chunkZ); + int[] heights = open.stream().mapToInt(cell -> cell[1]).sorted().toArray(); + int water = heights[heights.length / 4]; + SeaInlet inlet = coveredInlet(chunkX << 4, (chunkZ << 4) + 8, water); + int[] column = new int[2]; + int inside = 0; + for (int[] cell : open) { + if (SeaInletRasterizer.column(inlet, cell[0], cell[2], column) && cell[1] > water && cell[1] <= column[1] + ROOF_CLEARANCE) { + inside++; + } + } + assertTrue("subterrain cells in the headroom before the inlet " + inside, inside > 20); + + installInlet(inlet); + List sealed = openedCells(chunkX, chunkZ); + assertTrue(sealed.size() > 0); + for (int[] cell : sealed) { + boolean headroom = SeaInletRasterizer.column(inlet, cell[0], cell[2], column) && cell[1] > water + && cell[1] <= column[1] + ROOF_CLEARANCE; + assertFalse("subterrain opened " + cell[0] + "," + cell[1] + "," + cell[2] + " in the inlet headroom", headroom); + } + } + } + + private void installInlet(SeaInlet inlet) { + when(hydrology.inlets(anyInt(), anyInt())).thenAnswer(call -> SeaInletRasterizer.touches(inlet, call.getArgument(0), call.getArgument(1)) + ? List.of(inlet) : List.of()); + when(hydrology.settings()).thenReturn(HydrologySettings.compile(new IrisHydrology().setEnabled(true), 1L, 63, 0, 128)); + } + + private static SeaInlet coveredInlet(int startX, int z, int water) { + float[] xs = {startX - 4f, startX + 4f, startX + 12f, startX + 20f}; + float[] zs = {z, z, z, z}; + float[] halfWidth = {4f, 4f, 3.5f, 3f}; + int[] floor = {water - 3, water - 3, water - 3, water - 3}; + int[] ceiling = {water + 5, water + 5, water + 4, water + 4}; + return new SeaInlet(5L, xs, zs, halfWidth, water, floor, ceiling, startX + 20, z, 3); + } + + private List openedCells(int chunkX, int chunkZ) { + List opened = new ArrayList<>(); + Mantle storage = writer.getMantle(); + MantleWriter capture = mock(MantleWriter.class); + when(capture.getMantle()).thenReturn(storage); + doAnswer(call -> { + if (call.getArgument(3) instanceof MatterCavern) { + opened.add(new int[]{call.getArgument(0), call.getArgument(1), call.getArgument(2)}); + } + return null; + }).when(capture).setData(anyInt(), anyInt(), anyInt(), any()); + component.generateLayer(capture, chunkX, chunkZ, context); + return opened; + } + private List openedHeights(int chunkX, int chunkZ) { List opened = new ArrayList<>(); Mantle storage = writer.getMantle(); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentCaveAnchorTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentCaveAnchorTest.java index 985069737..b0650b863 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentCaveAnchorTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentCaveAnchorTest.java @@ -64,13 +64,13 @@ public class MantleObjectComponentCaveAnchorTest { MatterCavern forcedAir = new MatterCavern(true, "", (byte) 3); assertFalse(MantleObjectComponent.acceptsCaveAnchorFluid( - true, water, HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE), 20, 8)); + true, water, new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"), 20, 8)); assertFalse(MantleObjectComponent.acceptsCaveAnchorFluid( - true, water, HydrologyCaveCell.of(HydrologyCaveAction.FALLING_FLUID), 20, 8)); + true, water, new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water"), 20, 8)); assertFalse(MantleObjectComponent.acceptsCaveAnchorFluid( - true, null, HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD), 20, 8)); + true, null, new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"), 20, 8)); assertFalse(MantleObjectComponent.acceptsCaveAnchorFluid( - false, forcedAir, HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR), 20, 8)); + false, forcedAir, new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), 20, 8)); } @Test diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterOverlayTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterOverlayTest.java index bb7f0cfa6..776a4cb94 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterOverlayTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterOverlayTest.java @@ -138,7 +138,7 @@ public class MantleWriterOverlayTest { NativeBlockState custom = customState(base); when(matter.hasSlice(HydrologyCaveCell.class)).thenReturn(true); when(hydrologySlice.get(X, Y, Z)) - .thenReturn(HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)); + .thenReturn(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); writer.set(X, Y, Z, custom); @@ -176,7 +176,7 @@ public class MantleWriterOverlayTest { MatterCavern cavern = new MatterCavern(true, "", (byte) 3); when(matter.hasSlice(HydrologyCaveCell.class)).thenReturn(true); when(hydrologySlice.get(X, Y, Z)) - .thenReturn(HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)); + .thenReturn(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); writer.setData(X, Y, Z, replacement); assertFalse(writer.carveDataIfAbsent(X, Y, Z, cavern)); @@ -217,9 +217,9 @@ public class MantleWriterOverlayTest { when(matter.hasSlice(HydrologyCaveCell.class)).thenReturn(true); when(cavernSlice.get(X, Y, Z)).thenReturn(baseline); when(hydrologySlice.get(X, Y, Z)) - .thenReturn(HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)); + .thenReturn(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); when(hydrologySlice.get(X, Y + 1, Z)) - .thenReturn(HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR)); + .thenReturn(new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water")); assertFalse(writer.isCarved(X, Y, Z)); assertTrue(writer.isCarved(X, Y + 1, Z)); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterPreObjectJournalTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterPreObjectJournalTest.java index ec805cfaa..de1e9aedc 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterPreObjectJournalTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterPreObjectJournalTest.java @@ -369,8 +369,8 @@ public class MantleWriterPreObjectJournalTest { @Test public void hydrologyPrerequisitesHonorCapturedOriginalsAndNulls() { - HydrologyCaveCell original = HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR); - HydrologyCaveCell live = HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD); + HydrologyCaveCell original = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"); + HydrologyCaveCell live = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"); matter.slice(HydrologyCaveCell.class).set(X, Y, Z, live); matter.slice(HydrologyCaveCell.class).set(X, Y + 1, Z, live); matter.slice(PreObjectMatterCell.class) @@ -386,8 +386,8 @@ public class MantleWriterPreObjectJournalTest { @Test public void carvedColumnsHonorCapturedHydrologyBeforeLiveCells() { - HydrologyCaveCell original = HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR); - HydrologyCaveCell live = HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD); + HydrologyCaveCell original = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"); + HydrologyCaveCell live = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"); MatterSlice hydrology = matter.slice(HydrologyCaveCell.class); MatterSlice journal = matter.slice(PreObjectMatterCell.class); hydrology.set(X, Y, Z, live); @@ -488,10 +488,10 @@ public class MantleWriterPreObjectJournalTest { writer.clearData(X, Y + 1, Z, MatterCavern.class); }); matter.slice(HydrologyCaveCell.class) - .set(X, Y + 2, Z, HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)); + .set(X, Y + 2, Z, new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); matter.slice(MatterCavern.class).set(X, Y + 2, Z, original); matter.slice(HydrologyCaveCell.class) - .set(X, Y + 3, Z, HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR)); + .set(X, Y + 3, Z, new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water")); byte[] column = writer.getPrerequisiteCarvedColumn(X, Z, Y + 4); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java index 52a18d580..3f4da3276 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java @@ -328,7 +328,7 @@ public class ObjectDestinationTransactionTest { when(destinationWriter.getEngine().getDimension().isBedrock()).thenReturn(true); for (int x = 0; x < 3; x++) { when(destinationWriter.getPrerequisiteDataIfPresent(x, 4, 0, HydrologyCaveCell.class)) - .thenReturn(HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)); + .thenReturn(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); } ObjectDestinationTransaction destination = new ObjectDestinationTransaction(destinationWriter, 0, 0); @@ -391,8 +391,8 @@ public class ObjectDestinationTransactionTest { when(fluid.isFluid()).thenReturn(true); MatterCavern cavern = new MatterCavern(true, "", (byte) 0); Object[] values = {solid, air, fluid, cavern, - HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD), - HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR)}; + new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"), + new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water")}; Map expected = new HashMap<>(); Random random = new Random(918241L); for (int pass = 0; pass < 12; pass++) { @@ -401,10 +401,8 @@ public class ObjectDestinationTransactionTest { int y = random.nextInt(64); Object value = values[random.nextInt(values.length)]; transaction.setData(column[0], y, column[1], value); - HydrologyCaveCell hydrology = (HydrologyCaveCell) expected.get( - new ObjectDestinationTransaction.DataKey(column[0], y, column[1], HydrologyCaveCell.class)); - if (!(value instanceof HydrologyCaveCell) - && hydrology != null && hydrology.protectsPlacement()) { + if (!(value instanceof HydrologyCaveCell) && expected.containsKey( + new ObjectDestinationTransaction.DataKey(column[0], y, column[1], HydrologyCaveCell.class))) { continue; } Class type = value instanceof NativeBlockState ? NativeBlockState.class : value.getClass(); @@ -583,7 +581,7 @@ public class ObjectDestinationTransactionTest { when(writer.getPrerequisiteCarvedColumn(0, 0, 8)).thenReturn(prerequisite); when(writer.isPrerequisiteCarved(0, 4, 0)).thenReturn(true); ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0); - HydrologyCaveCell sealed = HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD); + HydrologyCaveCell sealed = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"); MatterCavern cavern = new MatterCavern(true, "", (byte) 0); transaction.setData(0, 4, 0, sealed); @@ -623,9 +621,9 @@ public class ObjectDestinationTransactionTest { fixture.writer.setData(0, 4, 0, cavern); }); fixture.matter.slice(HydrologyCaveCell.class) - .set(0, 6, 0, HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)); + .set(0, 6, 0, new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); fixture.matter.slice(HydrologyCaveCell.class) - .set(0, 12, 0, HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR)); + .set(0, 12, 0, new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water")); ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(fixture.writer, 0, 0); assertArrayEquals(new byte[]{0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0}, @@ -687,7 +685,7 @@ public class ObjectDestinationTransactionTest { when(writer.getPrerequisiteBlock(0, 0, 0)).thenReturn(prerequisite); when(writer.getEngine().getDimension().isBedrock()).thenReturn(true); when(writer.getPrerequisiteDataIfPresent(1, 4, 0, HydrologyCaveCell.class)) - .thenReturn(HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)); + .thenReturn(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0); transaction.setData(0, 0, 0, rejected); @@ -731,7 +729,7 @@ public class ObjectDestinationTransactionTest { when(custom.placementBaseState()).thenReturn(base); when(writer.getEngine().getDimension().isBedrock()).thenReturn(true); when(writer.getPrerequisiteDataIfPresent(1, 4, 0, HydrologyCaveCell.class)) - .thenReturn(HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)); + .thenReturn(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0); transaction.set(0, 0, 0, custom); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/SurfaceFluidBoundaryPlanTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/SurfaceFluidBoundaryPlanTest.java index ff63279fe..c3ce21b9c 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/SurfaceFluidBoundaryPlanTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/SurfaceFluidBoundaryPlanTest.java @@ -16,6 +16,32 @@ public class SurfaceFluidBoundaryPlanTest { private static final int PADDING = 3; private static final int FLUID_HEIGHT = 64; + @Test + public void joinedBandsWidenTheProtectionToCoverBoth() { + long none = SurfaceFluidBoundaryPlan.boundary(SurfaceFluidBoundaryPlan.NO_BOUNDARY, Integer.MIN_VALUE); + long[] boundaries = new long[CHUNK_SIZE * CHUNK_SIZE]; + long[] bands = new long[CHUNK_SIZE * CHUNK_SIZE]; + Arrays.fill(boundaries, none); + Arrays.fill(bands, none); + boundaries[0] = SurfaceFluidBoundaryPlan.boundary(60, 64); + bands[0] = SurfaceFluidBoundaryPlan.boundary(65, 80); + bands[1] = SurfaceFluidBoundaryPlan.boundary(70, 75); + boundaries[2] = SurfaceFluidBoundaryPlan.boundary(60, 64); + + SurfaceFluidBoundaryPlan.join(boundaries, bands); + + assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries, 0, 59)); + assertTrue(SurfaceFluidBoundaryPlan.protects(boundaries, 0, 60)); + assertTrue(SurfaceFluidBoundaryPlan.protects(boundaries, 0, 80)); + assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries, 0, 81)); + assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries, 1, 69)); + assertTrue(SurfaceFluidBoundaryPlan.protects(boundaries, 1, 70)); + assertTrue(SurfaceFluidBoundaryPlan.protects(boundaries, 1, 75)); + assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries, 1, 76)); + assertEquals(SurfaceFluidBoundaryPlan.boundary(60, 64), boundaries[2]); + assertEquals(none, boundaries[3]); + } + @Test public void submergedColumnProtectsItsSeabedWithoutBlockingTheCaveBelow() { Fixture fixture = new Fixture(); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/TerrainComposedCavernTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/TerrainComposedCavernTest.java index bc24f3d56..1fa008855 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/TerrainComposedCavernTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/TerrainComposedCavernTest.java @@ -44,7 +44,7 @@ public class TerrainComposedCavernTest { List hydrology = new ArrayList<>(); hydrology.add(null); for (HydrologyCaveAction action : HydrologyCaveAction.values()) { - hydrology.add(new HydrologyCaveCell(action, "river", "iris:flooded")); + hydrology.add(new HydrologyCaveCell(action, "river")); } List journals = new ArrayList<>(); journals.add(null); @@ -94,7 +94,7 @@ public class TerrainComposedCavernTest { public void composedReadUsesOneLockedSectionAndJournalLookup() { Matter matter = spy(new IrisMatter(16, 16, 16)); MatterCavern natural = new MatterCavern(true, "iris:natural", (byte) 0); - HydrologyCaveCell seal = HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD); + HydrologyCaveCell seal = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"); matter.slice(MatterCavern.class).set(15, 3, 2, natural); matter.slice(HydrologyCaveCell.class).set(15, 3, 2, seal); matter.slice(PreObjectMatterCell.class).set(15, 3, 2, diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/TerrainComposedFaceTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/TerrainComposedFaceTest.java index b13a1e374..112b5b1e9 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/TerrainComposedFaceTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/TerrainComposedFaceTest.java @@ -48,7 +48,7 @@ public class TerrainComposedFaceTest { MatterCavern original = new MatterCavern(false, "original", (byte) 2); HydrologyCaveCell[] hydrology = new HydrologyCaveCell[HydrologyCaveAction.values().length + 1]; for (int index = 1; index < hydrology.length; index++) { - hydrology[index] = new HydrologyCaveCell(HydrologyCaveAction.values()[index - 1], "river", "flooded"); + hydrology[index] = new HydrologyCaveCell(HydrologyCaveAction.values()[index - 1], "river"); } PreObjectMatterCell[] journal = {null, PreObjectMatterCell.string(null), PreObjectMatterCell.cavern(null), PreObjectMatterCell.cavern(original), diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/TerrainMatterViewTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/TerrainMatterViewTest.java index 17fd5ff60..ac3f5d054 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/TerrainMatterViewTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/TerrainMatterViewTest.java @@ -128,8 +128,8 @@ public class TerrainMatterViewTest { new MatterCavern(true, "iris:object", (byte) 0), PreObjectMatterCell::cavern); assertJournalIteration(String.class, "iris:natural", "iris:object", PreObjectMatterCell::string); assertJournalIteration(HydrologyCaveCell.class, - HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR), - HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE), PreObjectMatterCell::hydrology); + new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), + new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"), PreObjectMatterCell::hydrology); assertJournalIteration(NativeBlockState.class, mock(NativeBlockState.class), mock(NativeBlockState.class), PreObjectMatterCell::block); } diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/HydrologyVegetationSourceTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/HydrologyVegetationSourceTest.java index 1fb14691b..6a3c075d2 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/HydrologyVegetationSourceTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/HydrologyVegetationSourceTest.java @@ -75,23 +75,26 @@ public class HydrologyVegetationSourceTest { HydrologyVegetationSource source = HydrologyVegetationSource.create(dimension, settings, data, List.of(plain, marsh), List.of(meadow, bog, desert)); - assertEquals("minecraft:fern", grown(source.decorators(river, meadow, plain))); - assertEquals("minecraft:air", grown(source.decorators(stream, meadow, plain))); - assertEquals("minecraft:short_grass", grown(source.decorators(null, meadow, plain))); - assertEquals("minecraft:poppy", grown(source.decorators(river, meadow, marsh))); - assertEquals("minecraft:poppy", grown(source.decorators(null, meadow, marsh))); - assertEquals("minecraft:dandelion", grown(source.decorators(river, bog, marsh))); - assertEquals("minecraft:dandelion", grown(source.decorators(null, bog, plain))); - assertSame(HydrologyVegetation.Decorators.EMPTY, source.decorators(river, desert, marsh)); + assertEquals("minecraft:fern", grown(source.decorators(river, List.of(meadow), plain))); + assertEquals("minecraft:air", grown(source.decorators(stream, List.of(meadow), plain))); + assertEquals("minecraft:short_grass", grown(source.decorators(null, List.of(meadow), plain))); + assertEquals("minecraft:poppy", grown(source.decorators(river, List.of(meadow), marsh))); + assertEquals("minecraft:poppy", grown(source.decorators(null, List.of(meadow), marsh))); + assertEquals("minecraft:dandelion", grown(source.decorators(river, List.of(bog), marsh))); + assertEquals("minecraft:dandelion", grown(source.decorators(null, List.of(bog), plain))); + assertSame(HydrologyVegetation.Decorators.EMPTY, source.decorators(river, List.of(desert), marsh)); + assertEquals("a child biome takes its parent's list", "minecraft:dandelion", grown(source.decorators(river, List.of(meadow, bog), plain))); + assertSame("a child's own empty list wins over its parent", HydrologyVegetation.Decorators.EMPTY, + source.decorators(river, List.of(desert, bog), plain)); dimension.setHydrologyPolicy(policy(shore("minecraft:dead_bush"))); HydrologyVegetationSource dimensional = HydrologyVegetationSource.create(dimension, settings, data, List.of(plain, marsh), List.of(meadow, bog, desert)); - assertEquals("minecraft:dead_bush", grown(dimensional.decorators(river, meadow, plain))); - assertEquals("minecraft:dead_bush", grown(dimensional.decorators(null, meadow, plain))); - assertEquals("minecraft:poppy", grown(dimensional.decorators(river, meadow, marsh))); - assertEquals("minecraft:dandelion", grown(dimensional.decorators(river, bog, marsh))); - assertSame(HydrologyVegetation.Decorators.EMPTY, HydrologyVegetationSource.NONE.decorators(river, bog, marsh)); + assertEquals("minecraft:dead_bush", grown(dimensional.decorators(river, List.of(meadow), plain))); + assertEquals("minecraft:dead_bush", grown(dimensional.decorators(null, List.of(meadow), plain))); + assertEquals("minecraft:poppy", grown(dimensional.decorators(river, List.of(meadow), marsh))); + assertEquals("minecraft:dandelion", grown(dimensional.decorators(river, List.of(bog), marsh))); + assertSame(HydrologyVegetation.Decorators.EMPTY, HydrologyVegetationSource.NONE.decorators(river, List.of(bog), marsh)); } @Test @@ -140,6 +143,7 @@ public class HydrologyVegetationSourceTest { HydrologyVegetationSource source = HydrologyVegetationSource.create(new IrisDimension(), settings, data, List.of(plain), List.of()); IrisBiome unseen = new IrisBiome(); unseen.setHydrologyPolicy(policy(shore("minecraft:dandelion"))); + List lineage = List.of(unseen); int threads = 8; CyclicBarrier start = new CyclicBarrier(threads); ExecutorService pool = Executors.newFixedThreadPool(threads); @@ -148,7 +152,7 @@ public class HydrologyVegetationSourceTest { for (int thread = 0; thread < threads; thread++) { results.add(pool.submit(() -> { start.await(); - return source.decorators(settings.tiers().get(1), unseen, plain); + return source.decorators(settings.tiers().get(1), lineage, plain); })); } HydrologyVegetation.Decorators first = results.get(0).get(30, TimeUnit.SECONDS); @@ -156,7 +160,7 @@ public class HydrologyVegetationSourceTest { assertSame(first, result.get(30, TimeUnit.SECONDS)); } assertEquals("minecraft:dandelion", grown(first)); - assertSame(first, source.decorators(null, unseen, plain)); + assertSame(first, source.decorators(null, lineage, plain)); } finally { pool.shutdownNow(); } diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSurfaceBiomeTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSurfaceBiomeTest.java index d5a75fe01..49d657b73 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSurfaceBiomeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSurfaceBiomeTest.java @@ -27,9 +27,11 @@ import org.junit.rules.TemporaryFolder; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashSet; +import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; @@ -135,14 +137,24 @@ public class IrisComplexSurfaceBiomeTest { } @Test - public void shorePolicyInheritsBiomeThenRegionThenDimension() { + public void shorePolicyInheritsBiomeThenParentsThenRegionThenDimension() { ShorePolicyPack pack = new ShorePolicyPack(); assertEquals("dune", shoreSelect(pack, 1).getLoadKey()); pack.region.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("sand"))); assertEquals("sand", shoreSelect(pack, 4).getLoadKey()); assertNull(shoreSelect(pack, 5)); - pack.inland.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("gravel")).setShoreBiomeWidth(8)); - assertEquals("gravel", shoreSelect(pack, 8).getLoadKey()); + IrisBiome parent = pack.biome("highland"); + parent.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("gravel")).setShoreBiomeWidth(6)); + IrisBiome grandparent = pack.biome("upland"); + grandparent.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("dune")).setShoreBiomeWidth(8)); + List child = List.of(pack.inland, parent, grandparent); + assertEquals("gravel", shoreSelect(pack, child, 6).getLoadKey()); + assertNull(shoreSelect(pack, child, 7)); + parent.getHydrologyPolicy().setShoreBiomeWidth(null); + assertEquals("gravel", shoreSelect(pack, child, 8).getLoadKey()); + pack.inland.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("sand")).setShoreBiomeWidth(8)); + assertEquals("sand", shoreSelect(pack, 8).getLoadKey()); + assertEquals("sand", shoreSelect(pack, child, 8).getLoadKey()); assertSame(InferredType.SHORE, shoreSelect(pack, 8).getInferredType()); } @@ -152,8 +164,8 @@ public class IrisComplexSurfaceBiomeTest { pack.region.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>())); assertNull(shoreSelect(pack, 1)); pack.region.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomeWidth(0)); - assertNull(new HydrologyShoreBiomes(pack.dimension, pack.data, 7L).select(pack.inland, pack.region, 0, 0, 1)); - assertNull(new HydrologyShoreBiomes(new IrisDimension(), pack.data, 7L).select(pack.inland, new IrisRegion(), 0, 0, 1)); + assertNull(new HydrologyShoreBiomes(pack.dimension, pack.data, 7L).select(List.of(pack.inland), pack.region, 0, 0, 1)); + assertNull(new HydrologyShoreBiomes(new IrisDimension(), pack.data, 7L).select(List.of(pack.inland), new IrisRegion(), 0, 0, 1)); } @Test @@ -162,11 +174,12 @@ public class IrisComplexSurfaceBiomeTest { pack.region.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("sand", "dune", "gravel"))); HydrologyShoreBiomes shores = new HydrologyShoreBiomes(pack.dimension, pack.data, 7L); HydrologyShoreBiomes again = new HydrologyShoreBiomes(pack.dimension, pack.data, 7L); + List inland = List.of(pack.inland); Set picked = new HashSet<>(); for (int patch = -8; patch < 8; patch++) { - IrisBiome first = shores.select(pack.inland, pack.region, patch * 64, 0, 2); - assertEquals(first.getLoadKey(), shores.select(pack.inland, pack.region, patch * 64 + 63, 63, 2).getLoadKey()); - assertEquals(first.getLoadKey(), again.select(pack.inland, pack.region, patch * 64 + 17, 40, 1).getLoadKey()); + IrisBiome first = shores.select(inland, pack.region, patch * 64, 0, 2); + assertEquals(first.getLoadKey(), shores.select(inland, pack.region, patch * 64 + 63, 63, 2).getLoadKey()); + assertEquals(first.getLoadKey(), again.select(inland, pack.region, patch * 64 + 17, 40, 1).getLoadKey()); picked.add(first.getLoadKey()); } assertTrue(picked.toString(), picked.size() > 1); @@ -177,11 +190,39 @@ public class IrisComplexSurfaceBiomeTest { ShorePolicyPack pack = new ShorePolicyPack(); pack.region.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("ghost"))); IllegalStateException failure = assertThrows(IllegalStateException.class, () -> shoreSelect(pack, 1)); - assertTrue(failure.getMessage(), failure.getMessage().contains("'ghost'") && failure.getMessage().contains("coast")); + assertTrue(failure.getMessage(), failure.getMessage().contains("'ghost' listed by region coast for biome plain in region coast")); + IrisBiome parent = pack.biome("highland"); + parent.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("phantom"))); + failure = assertThrows(IllegalStateException.class, () -> shoreSelect(pack, List.of(pack.inland, parent), 1)); + assertTrue(failure.getMessage(), failure.getMessage().contains("'phantom' listed by biome highland for biome plain in region coast")); + pack.region.setHydrologyPolicy(null); + pack.dimension.getHydrologyPolicy().setShoreBiomes(new KList<>("wraith")); + failure = assertThrows(IllegalStateException.class, () -> shoreSelect(pack, 1)); + assertTrue(failure.getMessage(), failure.getMessage().contains("'wraith' listed by dimension ")); + } + + @Test + public void shoreBandsNeedAPositiveWidthAtSomeScope() { + IrisDimension dimension = new IrisDimension().setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("dune"))); + IrisRegion region = new IrisRegion().setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomeWidth(0)); + IrisBiome biome = new IrisBiome(); + assertFalse(HydrologyShoreBiomes.banded(dimension, List.of(region), List.of(biome))); + biome.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomeWidth(3)); + assertTrue(HydrologyShoreBiomes.banded(dimension, List.of(region), List.of(biome))); + biome.setHydrologyPolicy(null); + region.getHydrologyPolicy().setShoreBiomeWidth(2); + assertTrue(HydrologyShoreBiomes.banded(dimension, List.of(region), List.of(biome))); + region.setHydrologyPolicy(null); + dimension.getHydrologyPolicy().setShoreBiomeWidth(1); + assertTrue(HydrologyShoreBiomes.banded(dimension, List.of(region), List.of(biome))); } private static IrisBiome shoreSelect(ShorePolicyPack pack, int distance) { - return new HydrologyShoreBiomes(pack.dimension, pack.data, 7L).select(pack.inland, pack.region, 10, 20, distance); + return shoreSelect(pack, List.of(pack.inland), distance); + } + + private static IrisBiome shoreSelect(ShorePolicyPack pack, List lineage, int distance) { + return new HydrologyShoreBiomes(pack.dimension, pack.data, 7L).select(lineage, pack.region, 10, 20, distance); } private static final class ShorePolicyPack { diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationRuntimeScopeTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationRuntimeScopeTest.java index 4157ce2d1..934ca72d4 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationRuntimeScopeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationRuntimeScopeTest.java @@ -40,6 +40,7 @@ import java.lang.reflect.Field; import java.nio.file.Path; import java.util.Collections; import java.util.IdentityHashMap; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; @@ -96,10 +97,12 @@ public class IrisEngineGenerationRuntimeScopeTest { when(historical.dimension.getFluidHeight()).thenReturn(40); when(historical.dimension.getLoadKey()).thenReturn("historical"); when(historical.dimension.getReachableBiomes(any())).thenReturn(new KList<>()); + when(historical.dimension.getAllRegions(any())).thenReturn(new KList<>()); + when(historical.dimension.getReachableCaveBiomes(any())).thenReturn(new KList<>()); when(historical.target.getWorld().getHeight()).thenReturn(384); IrisBiome biome = new IrisBiome(); IrisRegion region = new IrisRegion(); - when(historicalComplex.getBaseBiomeStream()).thenReturn(ProceduralStream.of((x, z) -> biome, Interpolated.of(value -> 0D, value -> biome))); + when(historicalComplex.baseBiomeLineage(anyInt(), anyInt())).thenReturn(List.of(biome)); when(historicalComplex.getRegionStream()).thenReturn(ProceduralStream.of((x, z) -> region, Interpolated.of(value -> 0D, value -> region))); when(historicalComplex.getBridgeStream()).thenReturn(ProceduralStream.of((x, z) -> InferredType.LAND, Interpolated.of(value -> 0D, value -> InferredType.LAND))); diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierBoundarySupportTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierBoundarySupportTest.java index e22b42886..dbd465150 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierBoundarySupportTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierBoundarySupportTest.java @@ -219,7 +219,7 @@ public class IrisCarveModifierBoundarySupportTest { @Test public void hydrologyGuardOnlyAcceptsStableSolidBoundaryLayers() { - HydrologyCaveCell guard = HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD); + HydrologyCaveCell guard = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"); NativeBlockState stone = state("minecraft:stone", true); NativeBlockState sand = state("minecraft:sand", true); NativeBlockState water = state("minecraft:water", false, true); @@ -237,7 +237,7 @@ public class IrisCarveModifierBoundarySupportTest { NativeBlockState grass = state("minecraft:grass_block", true); NativeBlockState dirt = state("minecraft:dirt", true); NativeBlockState moss = state("minecraft:moss_block", true); - HydrologyCaveCell wet = HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE); + HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"); doReturn(dirt).when(output).getRaw(0, 4, 0); @@ -246,7 +246,7 @@ public class IrisCarveModifierBoundarySupportTest { assertSame(dirt, IrisCarveModifier.resolveSubmergedCaveFloorLayer( output, 0, 5, 0, moss, wet)); assertSame(grass, IrisCarveModifier.resolveSubmergedCaveFloorLayer( - output, 0, 5, 0, grass, HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR))); + output, 0, 5, 0, grass, new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"))); } private NativeBlockState state(String key, boolean solid) { diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierHydrologyTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierHydrologyTest.java index a68cc01fd..e49ddb1bc 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierHydrologyTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierHydrologyTest.java @@ -1,26 +1,80 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.generation.context.ChunkContext; +import art.arcane.iris.generation.context.ChunkedDataCache; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; +import art.arcane.iris.generation.hydrology.config.IrisHydrology; +import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.hydrology.underground.CavePoolFiller; +import art.arcane.iris.generation.hydrology.underground.CaveVoxel; +import art.arcane.iris.generation.hydrology.underground.CarvedTerrain; +import art.arcane.iris.generation.mantle.CarveOwnership; +import art.arcane.iris.generation.mantle.CaveTerrainSnapshot; +import art.arcane.iris.generation.mantle.MantleWriter; +import art.arcane.iris.generation.runtime.DimensionStackLayout; +import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.subterrain.IrisSubterrainFamily; import art.arcane.iris.generation.subterrain.SubterrainCell; import art.arcane.iris.generation.subterrain.SubterrainRoom; +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.LogLevel; import art.arcane.iris.testsupport.KeyedBlockState; +import art.arcane.iris.world.storage.matter.IrisMatterSupport; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.hunk.Hunk; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.IrisMatter; +import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.stream.ProceduralStream; +import org.junit.BeforeClass; import org.junit.Test; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.RecordComponent; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; public class IrisCarveModifierHydrologyTest { + private static final long SEED = 1337L; + private static final int SECTIONS = 4; + private static final int POOL_FLOOR = 50; + private static final int POOL_TOP = 52; + private static final int PROTECTED_FROM = 40; + + @BeforeClass + public static void registerMatter() { + IrisMatterSupport.ensureRegistered(); + } + @Test public void explicitHydrologyCanMaterializeIntoAnUninitializedCell() { NativeBlockState air = mock(NativeBlockState.class); @@ -38,19 +92,15 @@ public class IrisCarveModifierHydrologyTest { assertSame(baseline, IrisCarveModifier.composeCavern(baseline, null)); assertNull(IrisCarveModifier.composeCavern( - baseline, HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD))); + baseline, new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"))); MatterCavern wet = IrisCarveModifier.composeCavern( - baseline, new HydrologyCaveCell( - HydrologyCaveAction.WET_SOURCE, - "deep_lava", - "iris:flooded" - )); + baseline, new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "deep_lava")); MatterCavern dry = IrisCarveModifier.composeCavern( - baseline, HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR)); + baseline, new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water")); assertEquals(1, wet.getLiquid()); - assertEquals("iris:flooded", wet.getCustomBiome()); + assertEquals("", wet.getCustomBiome()); assertEquals(3, dry.getLiquid()); assertEquals(2, baseline.getLiquid()); assertEquals("baseline", baseline.getCustomBiome()); @@ -60,17 +110,14 @@ public class IrisCarveModifierHydrologyTest { public void hydrologyActionsResolveDistinctFluidStates() { NativeBlockState current = mock(NativeBlockState.class); NativeBlockState source = mock(NativeBlockState.class); - NativeBlockState falling = mock(NativeBlockState.class); NativeBlockState air = mock(NativeBlockState.class); - when(source.key()).thenReturn("minecraft:water[level=0]"); - when(source.withProperty("level", "8")).thenReturn(falling); assertSame(source, IrisCarveModifier.resolveHydrologyState( - HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE), current, source, air)); - assertSame(falling, IrisCarveModifier.resolveHydrologyState( - HydrologyCaveCell.of(HydrologyCaveAction.FALLING_FLUID), current, source, air)); + new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"), current, source, air)); + assertSame(source, IrisCarveModifier.resolveHydrologyState( + new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water"), current, source, air)); assertSame(air, IrisCarveModifier.resolveHydrologyState( - HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR), current, source, air)); + new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), current, source, air)); } @Test @@ -87,7 +134,7 @@ public class IrisCarveModifierHydrologyTest { assertSame(dry, IrisCarveModifier.normalizeWaterlogging(waterlogged, null)); assertSame(dry, IrisCarveModifier.normalizeWaterlogging(waterlogged, lava)); assertSame(dry, IrisCarveModifier.resolveHydrologyState( - HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD), waterlogged, water, null)); + new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"), waterlogged, water, null)); } @Test @@ -118,13 +165,13 @@ public class IrisCarveModifierHydrologyTest { assertSame(waterlogged, IrisCarveModifier.normalizeHydrologyWaterlogging( waterlogged, flooded, - HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE), + new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"), water )); assertSame(dry, IrisCarveModifier.normalizeHydrologyWaterlogging( waterlogged, flooded, - HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR), + new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), water )); } @@ -151,29 +198,249 @@ public class IrisCarveModifierHydrologyTest { assertSame(water, IrisCarveModifier.sealGuardState(water, rock)); } + @Test + public void sealGuardsHoldInsideProtectedUpperAndStackRanges() throws Exception { + NativeBlockState rock = new KeyedBlockState("minecraft:stone"); + NativeBlockState caveAir = new KeyedBlockState("minecraft:cave_air"); + NativeBlockState air = mock(NativeBlockState.class); + when(air.isAir()).thenReturn(true); + NativeBlockState granite = solid("minecraft:granite"); + int[] upperSurface = new int[256]; + Arrays.fill(upperSurface, PROTECTED_FROM); + DimensionStackLayout layout = mock(DimensionStackLayout.class); + when(layout.isHostFeatureProtectedY(anyInt())).thenAnswer(call -> call.getArgument(0) >= PROTECTED_FROM); + DimensionStackLayout[] stack = new DimensionStackLayout[256]; + Arrays.fill(stack, layout); + for (boolean upper : new boolean[]{true, false}) { + String range = upper ? "upper-dimension range" : "dimension-stack range"; + Hunk output = Hunk.newArrayHunk(16, SECTIONS * 16, 16); + for (int y : new int[]{PROTECTED_FROM - 2, PROTECTED_FROM + 2}) { + output.setRaw(3, y, 4, air); + output.setRaw(3, y + 1, 4, granite); + output.setRaw(3, y + 2, 4, granite); + } + CarveCall apply = resolver(output, rock, caveAir, upper ? upperSurface : null, upper ? null : stack); + for (int y : new int[]{PROTECTED_FROM - 2, PROTECTED_FROM + 2}) { + apply.at(3, y, 4, null, new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); + apply.at(3, y + 1, 4, null, new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water")); + apply.at(3, y + 2, 4, new MatterCavern(true, "", (byte) 0), null); + } + assertSame("a seal guard below the " + range + " seals", rock, output.getRaw(3, PROTECTED_FROM - 2, 4)); + assertSame("inlet air below the " + range + " opens", caveAir, output.getRaw(3, PROTECTED_FROM - 1, 4)); + assertSame("a seal guard inside the " + range + " still seals", rock, output.getRaw(3, PROTECTED_FROM + 2, 4)); + assertSame("inlet air does not open inside the " + range, granite, output.getRaw(3, PROTECTED_FROM + 3, 4)); + assertSame("caves do not open inside the " + range, granite, output.getRaw(3, PROTECTED_FROM + 4, 4)); + } + } + + @FunctionalInterface + private interface CarveCall { + void at(int x, int y, int z, MatterCavern baseline, HydrologyCaveCell hydrology) throws Exception; + } + + @SuppressWarnings("unchecked") + private static CarveCall resolver(Hunk output, NativeBlockState rock, NativeBlockState air, int[] upperSurface, + DimensionStackLayout[] stack) throws Exception { + ChunkContext chunkContext = mock(ChunkContext.class); + ChunkedDataCache rocks = mock(ChunkedDataCache.class); + when(rocks.get(anyInt(), anyInt())).thenReturn(rock); + when(chunkContext.getRock()).thenReturn(rocks); + IrisCarveScratch scratch = new IrisCarveScratch(); + Map values = new HashMap<>(); + values.put("output", output); + values.put("chunkContext", chunkContext); + values.put("scratch", scratch); + values.put("columnMasks", scratch.columnMasks); + values.put("upperSurfaceHeights", upperSurface); + values.put("stackLayouts", stack); + values.put("worldHeightSpan", SECTIONS * 16); + Class contextType = Class.forName(IrisCarveModifier.class.getName() + "$CarveResolutionContext"); + RecordComponent[] components = contextType.getRecordComponents(); + Class[] types = new Class[components.length]; + Object[] arguments = new Object[components.length]; + for (int index = 0; index < components.length; index++) { + types[index] = components[index].getType(); + arguments[index] = values.containsKey(components[index].getName()) ? values.get(components[index].getName()) + : types[index] == int.class ? 0 : null; + } + Constructor contextConstructor = contextType.getDeclaredConstructor(types); + contextConstructor.setAccessible(true); + Object context = contextConstructor.newInstance(arguments); + IrisCarveModifier modifier = mock(IrisCarveModifier.class, CALLS_REAL_METHODS); + Field airField = IrisCarveModifier.class.getDeclaredField("AIR"); + airField.setAccessible(true); + airField.set(modifier, air); + Class resolverType = Class.forName(IrisCarveModifier.class.getName() + "$CarveResolver"); + Constructor resolverConstructor = resolverType.getDeclaredConstructor(IrisCarveModifier.class, contextType); + resolverConstructor.setAccessible(true); + Object resolver = resolverConstructor.newInstance(modifier, context); + Method apply = resolverType.getDeclaredMethod("apply", int.class, int.class, int.class, MatterCavern.class, HydrologyCaveCell.class); + apply.setAccessible(true); + return (x, y, z, baseline, hydrology) -> apply.invoke(resolver, x, y, z, baseline, hydrology); + } + @Test public void subterrainRoomsNeverTakeAnyInletCell() { SubterrainRoom room = new SubterrainRoom("room", "", IrisSubterrainFamily.CENOTE, 0, 0, 0, 0, 0, 0, -10, 10, 1D, 0, false, false, SubterrainCell.Kind.AIR); SubterrainCell open = new SubterrainCell(SubterrainCell.Kind.AIR, "", room); - assertTrue(IrisCarveModifier.subterrainOwns(open, null)); - assertFalse(IrisCarveModifier.subterrainOwns(open, HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR))); - assertFalse(IrisCarveModifier.subterrainOwns(open, HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE))); - assertFalse(IrisCarveModifier.subterrainOwns(open, HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD))); - assertFalse(IrisCarveModifier.subterrainOwns(SubterrainCell.OUTSIDE, null)); + assertEquals(CarveOwnership.Owner.SUBTERRAIN, IrisCarveModifier.carveOwner(null, open, null, 0)); + assertEquals(CarveOwnership.Owner.HYDROLOGY, + IrisCarveModifier.carveOwner(new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), open, null, 0)); + assertEquals(CarveOwnership.Owner.HYDROLOGY, + IrisCarveModifier.carveOwner(new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"), open, null, 0)); + assertEquals(CarveOwnership.Owner.HYDROLOGY, + IrisCarveModifier.carveOwner(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"), open, null, 0)); + assertEquals(CarveOwnership.Owner.CAVERN, IrisCarveModifier.carveOwner(null, SubterrainCell.OUTSIDE, null, 0)); for (SubterrainCell.Kind kind : new SubterrainCell.Kind[]{SubterrainCell.Kind.WATER, SubterrainCell.Kind.LAVA}) { SubterrainCell fluid = new SubterrainCell(kind, "", room); - assertTrue(IrisCarveModifier.subterrainOwns(fluid, null)); - assertFalse("subterrain " + kind + " yields the inlet seal", IrisCarveModifier.subterrainOwns(fluid, - HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD))); + assertEquals(CarveOwnership.Owner.SUBTERRAIN, IrisCarveModifier.carveOwner(null, fluid, null, 0)); + assertEquals("subterrain " + kind + " yields the inlet seal", CarveOwnership.Owner.HYDROLOGY, + IrisCarveModifier.carveOwner(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"), fluid, null, 0)); } } + @Test + public void poolWallsResolveNoUnknownFluid() throws Exception { + IrisHydrology config = new IrisHydrology().setEnabled(true); + config.getUnderground().getCavePools().setDensity(1D).setFreeboard(new KList<>(0, 0)); + Map written = new HashMap<>(); + new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384)) + .fill(0, 0, SealedRoom::new, recordingWriter(written), SEED); + Matter[] sections = new Matter[SECTIONS]; + Set wallFluids = new HashSet<>(); + for (Map.Entry entry : written.entrySet()) { + HydrologyCaveCell cell = entry.getValue(); + if (cell.action() == HydrologyCaveAction.SEAL_GUARD) { + wallFluids.add(cell.fluidProfileKey()); + } + int x = x(entry.getKey()); + int y = y(entry.getKey()); + int z = z(entry.getKey()); + if (x >> 4 == 0 && z >> 4 == 0) { + section(sections, y).slice(HydrologyCaveCell.class).set(x, y & 15, z, cell); + } + } + section(sections, POOL_TOP + 1).slice(HydrologyCaveCell.class) + .set(0, (POOL_TOP + 1) & 15, 0, new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); + CaveTerrainSnapshot terrain = CaveTerrainSnapshot.capture(chunk(sections), 0, 0); + IrisCarveModifier.CaveZone zone = new IrisCarveModifier.CaveZone(); + zone.setFloor(POOL_FLOOR); + zone.setCeiling(POOL_TOP); + IrisCarveModifier modifier = mock(IrisCarveModifier.class, CALLS_REAL_METHODS); + doReturn(complexWithWater()).when(modifier).getComplex(); + Method normalize = IrisCarveModifier.class.getDeclaredMethod("normalizeCaveZoneWaterlogging", Hunk.class, + CaveTerrainSnapshot.class, IrisCarveModifier.CaveZone.class, int.class, int.class, int.class, int.class); + normalize.setAccessible(true); + Hunk output = Hunk.newArrayHunk(16, SECTIONS * 16, 16); + + List logged = new ArrayList<>(); + IrisPlatform platform = mock(IrisPlatform.class); + doAnswer(invocation -> { + logged.add(invocation.getArgument(0) + " " + invocation.getArgument(1)); + return null; + }).when(platform).log(any(LogLevel.class), anyString()); + IrisPlatforms.bind(platform); + try { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + normalize.invoke(modifier, output, terrain, zone, x, z, x, z); + } + } + } finally { + IrisPlatforms.unbind(); + } + + assertEquals(List.of(), logged.stream().filter(line -> line.contains("unknown fluid profile")).distinct().toList()); + assertEquals("pool walls carry the pool's fluid", Set.of("water"), wallFluids); + } + + private static IrisComplex complexWithWater() throws Exception { + IrisComplex complex = mock(IrisComplex.class, CALLS_REAL_METHODS); + setField(complex, "waterFluidStreams", Map.of("water", mock(ProceduralStream.class))); + setField(complex, "fluidStream", mock(ProceduralStream.class)); + return complex; + } + + private static void setField(Object target, String name, Object value) throws Exception { + Field field = IrisComplex.class.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } + + private static MantleWriter recordingWriter(Map written) { + MantleWriter writer = mock(MantleWriter.class); + doAnswer(invocation -> written.put(key(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2)), + invocation.getArgument(3))).when(writer).setData(anyInt(), anyInt(), anyInt(), any()); + when(writer.getDataIfPresent(anyInt(), anyInt(), anyInt(), eq(HydrologyCaveCell.class))).thenAnswer(invocation -> + written.get(key(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2)))); + doAnswer(invocation -> { + invocation.getArgument(2).run(); + return null; + }).when(writer).withChunkFence(anyInt(), anyInt(), any(Runnable.class)); + return writer; + } + + private static Matter section(Matter[] sections, int y) { + if (sections[y >> 4] == null) { + sections[y >> 4] = new IrisMatter(16, 16, 16); + } + return sections[y >> 4]; + } + + @SuppressWarnings("unchecked") + private static MantleChunk chunk(Matter[] sections) { + MantleChunk chunk = mock(MantleChunk.class, withSettings().stubOnly()); + when(chunk.sectionCount()).thenReturn(sections.length); + when(chunk.exists(anyInt())).thenAnswer(call -> sections[call.getArgument(0)] != null); + when(chunk.get(anyInt())).thenAnswer(call -> sections[call.getArgument(0)]); + return chunk; + } + + private static long key(int x, int y, int z) { + return ((long) (x + 4096) << 40) | ((long) y << 20) | (z + 4096); + } + + private static int x(long key) { + return (int) (key >>> 40) - 4096; + } + + private static int z(long key) { + return (int) (key & 0xFFFFF) - 4096; + } + + private static int y(long key) { + return (int) ((key >>> 20) & 0xFFFFF); + } + private static NativeBlockState solid(String key) { NativeBlockState state = mock(NativeBlockState.class); when(state.isSolid()).thenReturn(true); when(state.key()).thenReturn(key); return state; } + + private static final class SealedRoom implements CarvedTerrain { + private static final int SURFACE = 120; + + @Override + public CaveVoxel voxel(int x, int y, int z) { + if (y <= 0 || y > SURFACE) { + return CaveVoxel.FOREIGN; + } + boolean inside = x >= 0 && x < 16 && z >= 0 && z < 16 && y >= POOL_FLOOR && y <= POOL_TOP; + return inside ? CaveVoxel.AIR : CaveVoxel.SOLID; + } + + @Override + public int surface(int x, int z) { + return SURFACE; + } + + @Override + public String caveFluid(int x, int y, int z) { + return null; + } + } } diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierOwnershipTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierOwnershipTest.java new file mode 100644 index 000000000..4c7f1b3e1 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierOwnershipTest.java @@ -0,0 +1,61 @@ +package art.arcane.iris.generation.stage; + +import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction; +import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; +import art.arcane.iris.generation.mantle.CarveOwnership; +import art.arcane.iris.generation.subterrain.IrisSubterrainFamily; +import art.arcane.iris.generation.subterrain.SubterrainCell; +import art.arcane.iris.generation.subterrain.SubterrainRoom; +import art.arcane.iris.generation.terrain.Terrain3DColumn; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class IrisCarveModifierOwnershipTest { + private static final int Y = 2; + private static final int HEIGHT = 64; + + @Test + public void carveOwnerAgreesOnTheNaturalLayer() { + SubterrainCell openRoom = new SubterrainCell(SubterrainCell.Kind.AIR, "", room(false, false)); + SubterrainCell reservedSolid = new SubterrainCell(SubterrainCell.Kind.SOLID, "", room(false, true)); + SubterrainCell reservedPassage = new SubterrainCell(SubterrainCell.Kind.AIR, "", room(true, false)); + SubterrainCell shell = new SubterrainCell(SubterrainCell.Kind.SOLID, "", room(false, false)); + Terrain3DColumn openTerrain = column(true); + HydrologyCaveCell[] hydrologyCells = { + null, new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")}; + SubterrainCell[] subterrainCells = {SubterrainCell.OUTSIDE, openRoom, reservedSolid, reservedPassage, shell}; + Terrain3DColumn[] terrainColumns = {null, column(false), openTerrain}; + List disagreements = new ArrayList<>(); + for (HydrologyCaveCell hydrology : hydrologyCells) { + for (SubterrainCell subterrain : subterrainCells) { + for (Terrain3DColumn terrain : terrainColumns) { + boolean claims = subterrain == openRoom || subterrain == reservedSolid || subterrain == reservedPassage; + CarveOwnership.Owner expected = CarveOwnership.resolve(hydrology != null, claims, terrain == openTerrain); + CarveOwnership.Owner actual = IrisCarveModifier.carveOwner(hydrology, subterrain, terrain, Y); + if (actual != expected) { + disagreements.add("hydrology=" + (hydrology == null ? "none" : hydrology.action()) + + " subterrain=" + subterrain.kind() + " reservedSolid=" + + (subterrain.room() != null && subterrain.room().reservedSolid()) + + " reservedPassage=" + (subterrain.room() != null && subterrain.room().reservedPassage()) + + " terrain=" + (terrain == null ? "none" : terrain == openTerrain ? "open" : "solid") + + ": carveOwner gives " + actual + ", the rule gives " + expected); + } + } + } + } + assertTrue(String.join("\n", disagreements), disagreements.isEmpty()); + } + + private static SubterrainRoom room(boolean reservedPassage, boolean reservedSolid) { + return new SubterrainRoom("room", "", IrisSubterrainFamily.CENOTE, + 0, 0, 0, 0, 0, 0, -10, 10, 1D, 0, reservedPassage, reservedSolid, SubterrainCell.Kind.AIR); + } + + private static Terrain3DColumn column(boolean openAtY) { + return Terrain3DColumn.fromOccupancy(HEIGHT - 1, HEIGHT, y -> !openAtY || y != Y); + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierSubterrainMaskTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierSubterrainMaskTest.java index 3d1329b46..e93fc1f1e 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierSubterrainMaskTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierSubterrainMaskTest.java @@ -3,8 +3,12 @@ package art.arcane.iris.generation.stage; import art.arcane.iris.generation.block.B; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; +import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; +import art.arcane.iris.generation.hydrology.plan.HydrologySettings; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; +import art.arcane.iris.generation.hydrology.underground.SeaInlet; +import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer; import art.arcane.iris.generation.mantle.EngineMantle; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; @@ -32,6 +36,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -48,6 +53,7 @@ import static org.mockito.Mockito.when; public class IrisCarveModifierSubterrainMaskTest { private static final int MINIMUM_Y = -64; private static final int ROOF = 2; + private static final int ROOF_CLEARANCE = 6; @Test public void preservedSubterrainNeverReopensACellAboveTheCaveCeiling() { @@ -80,6 +86,74 @@ public class IrisCarveModifierSubterrainMaskTest { } } + @Test + public void preservedSubterrainStaysOutOfInletHeadroom() { + IrisSubterrainFeature feature = new IrisSubterrainFeature().setId("room").setFamily(IrisSubterrainFamily.CENOTE) + .setProbability(1).setLength(64).setRadius(12).setHeight(24).setPillarSpacing(0).setFormationFraction(0) + .setWorldYRange(new IrisRange(-48, 60)); + SubterrainPlanner planner = new SubterrainPlanner(new SubterrainPlanner.Options(List.of(feature), 83L, MINIMUM_Y, 128, (x, z) -> "region")); + SubterrainPlan plan = planner.plansForBounds(-512, -512, 512, 512).getFirst(); + int blockX = plan.centerX() >> 4 << 4; + int blockZ = plan.centerZ() >> 4 << 4; + HydrologyRuntime hydrology = mock(HydrologyRuntime.class); + when(hydrology.raster(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.EMPTY); + IrisCarveModifier modifier = modifier(planner, hydrology); + try (MockedStatic blocks = mockStatic(B.class)) { + blocks.when(() -> B.getState(anyString())).thenReturn(mock(NativeBlockState.class)); + List open = reopenedCells(modifier, planner, blockX, blockZ); + int[] heights = open.stream().mapToInt(cell -> cell[1]).sorted().toArray(); + int water = heights[heights.length / 4]; + SeaInlet inlet = coveredInlet(blockX, blockZ + 8, water); + assertTrue("subterrain cells in the headroom before the inlet " + inHeadroom(inlet, open).size(), inHeadroom(inlet, open).size() > 20); + + when(hydrology.inlets(anyInt(), anyInt())).thenAnswer(call -> SeaInletRasterizer.touches(inlet, call.getArgument(0), + call.getArgument(1)) ? List.of(inlet) : List.of()); + when(hydrology.settings()).thenReturn(HydrologySettings.compile(new IrisHydrology().setEnabled(true), 1L, 63, 0, 128)); + List sealed = reopenedCells(modifier, planner, blockX, blockZ); + assertTrue(sealed.size() > 0); + assertEquals("subterrain reopened cells in the inlet headroom", List.of(), inHeadroom(inlet, sealed)); + } + } + + private static List inHeadroom(SeaInlet inlet, List cells) { + List inside = new ArrayList<>(); + int[] column = new int[2]; + for (int[] cell : cells) { + if (SeaInletRasterizer.column(inlet, cell[0], cell[2], column) && cell[1] > inlet.waterLevel() + && cell[1] <= column[1] + ROOF_CLEARANCE) { + inside.add(cell[0] + "," + cell[1] + "," + cell[2]); + } + } + return inside; + } + + private static SeaInlet coveredInlet(int startX, int z, int water) { + float[] xs = {startX - 4f, startX + 4f, startX + 12f, startX + 20f}; + float[] zs = {z, z, z, z}; + float[] halfWidth = {4f, 4f, 3.5f, 3f}; + int[] floor = {water - 3, water - 3, water - 3, water - 3}; + int[] ceiling = {water + 5, water + 5, water + 4, water + 4}; + return new SeaInlet(5L, xs, zs, halfWidth, water, floor, ceiling, startX + 20, z, 3); + } + + @SuppressWarnings("unchecked") + private static List reopenedCells(IrisCarveModifier modifier, SubterrainPlanner planner, int blockX, int blockZ) { + List open = new ArrayList<>(); + Hunk output = mock(Hunk.class); + when(output.getHeight()).thenReturn(128); + doAnswer(call -> { + int x = blockX + (int) call.getArgument(0); + int y = call.getArgument(1); + int z = blockZ + (int) call.getArgument(2); + if (!planner.sample(x, y + MINIMUM_Y, z).solid()) { + open.add(new int[]{x, y, z}); + } + return null; + }).when(output).setRaw(anyInt(), anyInt(), anyInt(), any()); + modifier.preserveSubterrain(blockX, blockZ, output); + return open; + } + @Test public void preservedSubterrainLeavesEveryInletCellAlone() { IrisSubterrainFeature feature = new IrisSubterrainFeature().setId("room").setFamily(IrisSubterrainFamily.CENOTE) @@ -104,7 +178,7 @@ public class IrisCarveModifierSubterrainMaskTest { if (y <= water + 2 && y >= water - 3) { HydrologyCaveAction action = y > water ? HydrologyCaveAction.DRY_AIR : y == water - 3 ? HydrologyCaveAction.SEAL_GUARD : HydrologyCaveAction.WET_SOURCE; - inlet.put(cell, new HydrologyCaveCell(action, HydrologyCaveCell.SEA_FLUID, "")); + inlet.put(cell, new HydrologyCaveCell(action, HydrologyCaveCell.SEA_FLUID)); } } assertTrue("inlet cells crossing the room " + inlet.size(), inlet.size() > 20); diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierPoolGuardTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierPoolGuardTest.java index 41cda4770..577e34018 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierPoolGuardTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierPoolGuardTest.java @@ -97,8 +97,8 @@ public class IrisDepositModifierPoolGuardTest { IrisDepositGenerator gravelDeposit = gravelDeposit(); when(engine.getDimension().getDeposits()).thenReturn(new KList<>(gravelDeposit)); MantleChunk chunk = mock(MantleChunk.class); - when(chunk.get(5, 4, 5, HydrologyCaveCell.class)).thenReturn(HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)); - when(chunk.get(6, 4, 6, HydrologyCaveCell.class)).thenReturn(new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water", "")); + when(chunk.get(5, 4, 5, HydrologyCaveCell.class)).thenReturn(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")); + when(chunk.get(6, 4, 6, HydrologyCaveCell.class)).thenReturn(new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water")); Mantle mantle = engine.getMantle().getMantle(); doReturn(chunk).when(mantle).useChunk(0, 0); MultiBurst pool = mock(MultiBurst.class, withSettings().stubOnly()); diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisDimensionStackActuatorMetadataTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisDimensionStackActuatorMetadataTest.java index 378a667ea..ad18d6beb 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisDimensionStackActuatorMetadataTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisDimensionStackActuatorMetadataTest.java @@ -68,7 +68,7 @@ public class IrisDimensionStackActuatorMetadataTest { IrisMatterSupport.ensureRegistered(); Matter section = new IrisMatter(16, 16, 16); MatterCavern cavern = new MatterCavern(true, "cave", (byte) 0); - HydrologyCaveCell hydrology = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "river", "flooded"); + HydrologyCaveCell hydrology = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "river"); section.slice(MatterCavern.class).set(3, 4, 7, cavern); section.slice(HydrologyCaveCell.class).set(3, 4, 7, hydrology); MantleChunk chunk = mock(MantleChunk.class); diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisPostModifierWallShoreTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisPostModifierWallShoreTest.java index 991fe3c7c..e470e1d2a 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisPostModifierWallShoreTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisPostModifierWallShoreTest.java @@ -155,7 +155,7 @@ public class IrisPostModifierWallShoreTest { @SuppressWarnings("unchecked") private static EngineMantle sealedMantle() { MatterSlice cells = mock(MatterSlice.class); - doReturn(HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD)).when(cells).get(0, SURFACE & 15, 0); + doReturn(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water")).when(cells).get(0, SURFACE & 15, 0); Matter section = mock(Matter.class); doReturn(true).when(section).hasSlice(HydrologyCaveCell.class); doReturn(cells).when(section).getSlice(HydrologyCaveCell.class); diff --git a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionFocusRegionTest.java b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionFocusRegionTest.java index b68d0a232..b52f4109c 100644 --- a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionFocusRegionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionFocusRegionTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.generation.terrain; import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; import art.arcane.iris.pack.loading.IrisData; @@ -18,6 +19,7 @@ import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -51,11 +53,12 @@ public class IrisDimensionFocusRegionTest { biome("wilds").setChildren(new KList<>("highlands")); IrisBiome highlands = biome("highlands").setChildren(new KList<>("wilds")) .setCarvingBiome("chalk-gardens") - .setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("shore"))); + .setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("shore")).setShoreBiomeWidth(4)); IrisBiome chalk = biome("chalk-gardens").setChildren(new KList<>("chalk-child")); IrisBiome chalkChild = biome("chalk-child"); IrisBiome shore = biome("shore").setChildren(new KList<>("shore-child")); IrisBiome shoreChild = biome("shore-child").setCarvingBiome("wilds"); + dimension.setHydrology(new IrisHydrology().setEnabled(true)); for (IrisBiome focus : List.of(highlands, chalk, chalkChild, shore, shoreChild)) { assertSame(tropical, dimension.resolveFocusRegion(focus, () -> data)); @@ -73,16 +76,21 @@ public class IrisDimensionFocusRegionTest { } @Test - public void hydrologyPolicyShoreBiomesBelongToTheirRegion() { - IrisRegion tropical = region("tropical").setLandBiomes(new KList<>("wilds")) + public void placedHydrologyShoreBiomesBelongToTheirRegion() { + IrisRegion tropical = region("tropical").setLandBiomes(new KList<>("wilds", "dunes")) .setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("beach"))); biome("wilds").setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("reef"))); + biome("dunes"); IrisBiome beach = biome("beach"); IrisBiome reef = biome("reef"); + dimension.setHydrology(new IrisHydrology().setEnabled(true)); + assertNotSame(tropical, dimension.resolveFocusRegion(beach, () -> data)); + assertNotSame(tropical, dimension.resolveFocusRegion(reef, () -> data)); + tropical.getHydrologyPolicy().setShoreBiomeWidth(3); assertSame(tropical, dimension.resolveFocusRegion(beach, () -> data)); assertSame(tropical, dimension.resolveFocusRegion(reef, () -> data)); - assertEquals(Set.of("wilds"), tropical.getNaturalBiomes(() -> data).stream() + assertEquals(Set.of("wilds", "dunes"), tropical.getNaturalBiomes(() -> data).stream() .map(IrisBiome::getLoadKey).collect(Collectors.toSet())); } diff --git a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionReachableBiomesTest.java b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionReachableBiomesTest.java index f36f5ffd5..e11438427 100644 --- a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionReachableBiomesTest.java +++ b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionReachableBiomesTest.java @@ -204,12 +204,12 @@ public class IrisDimensionReachableBiomesTest { @Test @SuppressWarnings("unchecked") - public void includesHydrologyPolicyShoreBiomesOnlyWhileHydrologyIsEnabled() { + public void includesHydrologyShoreBiomesOnlyWhereAWidthPlacesThem() { IrisDimension dimension = new IrisDimension() .setRegions(new KList<>("reachable")) .setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("dimension-shore"))); IrisRegion reachable = new IrisRegion() - .setLandBiomes(new KList<>("root")) + .setLandBiomes(new KList<>("root", "plain")) .setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("region-shore"))); IrisBiome root = biome("root").setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("biome-shore"))); IrisBiome regionShore = biome("region-shore").setChildren(new KList<>("shore-child")); @@ -221,16 +221,83 @@ public class IrisDimensionReachableBiomesTest { when(data.getBiomeLoader()).thenReturn(biomeLoader); when(regionLoader.load("reachable")).thenReturn(reachable); when(biomeLoader.load("root")).thenReturn(root); + when(biomeLoader.load("plain")).thenReturn(biome("plain")); when(biomeLoader.load("dimension-shore")).thenReturn(biome("dimension-shore")); when(biomeLoader.load("region-shore")).thenReturn(regionShore); when(biomeLoader.load("shore-child")).thenReturn(biome("shore-child")); when(biomeLoader.load("biome-shore")).thenReturn(biome("biome-shore")); - assertEquals(Set.of("root"), reachableKeys(dimension, data)); - dimension.setHydrology(new IrisHydrology().setEnabled(false)); - assertEquals(Set.of("root"), reachableKeys(dimension, data)); + assertEquals(Set.of("root", "plain"), reachableKeys(dimension, data)); dimension.setHydrology(new IrisHydrology().setEnabled(true)); - assertEquals(Set.of("root", "dimension-shore", "region-shore", "shore-child", "biome-shore"), reachableKeys(dimension, data)); + assertEquals(Set.of("root", "plain"), reachableKeys(dimension, data)); + dimension.getHydrologyPolicy().setShoreBiomeWidth(3); + assertEquals(Set.of("root", "plain", "region-shore", "shore-child", "biome-shore"), reachableKeys(dimension, data)); + dimension.setHydrology(new IrisHydrology().setEnabled(false)); + assertEquals(Set.of("root", "plain"), reachableKeys(dimension, data)); + dimension.setHydrology(new IrisHydrology().setEnabled(true)); + reachable.getHydrologyPolicy().setShoreBiomeWidth(0); + assertEquals(Set.of("root", "plain"), reachableKeys(dimension, data)); + root.getHydrologyPolicy().setShoreBiomeWidth(2); + assertEquals(Set.of("root", "plain", "biome-shore"), reachableKeys(dimension, data)); + } + + @Test + @SuppressWarnings("unchecked") + public void aParentWidthReachesTheShoreListOfItsChildren() { + IrisDimension dimension = new IrisDimension() + .setRegions(new KList<>("reachable")) + .setHydrology(new IrisHydrology().setEnabled(true)); + IrisRegion reachable = new IrisRegion().setLandBiomes(new KList<>("parent")); + IrisBiome parent = biome("parent").setChildren(new KList<>("child")); + IrisBiome child = biome("child").setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomes(new KList<>("child-shore"))); + + IrisData data = mock(IrisData.class); + ResourceLoader regionLoader = mock(ResourceLoader.class); + ResourceLoader biomeLoader = mock(ResourceLoader.class); + when(data.getRegionLoader()).thenReturn(regionLoader); + when(data.getBiomeLoader()).thenReturn(biomeLoader); + when(regionLoader.load("reachable")).thenReturn(reachable); + when(biomeLoader.load("parent")).thenReturn(parent); + when(biomeLoader.load("child")).thenReturn(child); + when(biomeLoader.load("child-shore")).thenReturn(biome("child-shore")); + + assertEquals(Set.of("parent", "child"), reachableKeys(dimension, data)); + parent.setHydrologyPolicy(new IrisHydrologyPolicy().setShoreBiomeWidth(5)); + assertEquals(Set.of("parent", "child", "child-shore"), reachableKeys(dimension, data)); + } + + @Test + @SuppressWarnings("unchecked") + public void caveBiomesAreTheRegionCaveBiomesAndTheEnabledCarvingBands() { + IrisDimension dimension = new IrisDimension().setRegions(new KList<>("tropical")); + dimension.setCarving(new KList<>( + new IrisDimensionCarvingEntry().setId("deep").setBiome("deep-dark"), + new IrisDimensionCarvingEntry().setId("off").setEnabled(false).setBiome("disabled-band"))); + IrisRegion tropical = new IrisRegion() + .setLandBiomes(new KList<>("volcanoes")) + .setShoreBiomes(new KList<>("beach")) + .setCaveBiomes(new KList<>("hollow", "magma", "missing")); + tropical.setLoadKey("tropical"); + IrisBiome volcanoes = biome("volcanoes").setCarvingBiome("magma").setChildren(new KList<>("ash")); + + IrisData data = mock(IrisData.class); + ResourceLoader regionLoader = mock(ResourceLoader.class); + ResourceLoader biomeLoader = mock(ResourceLoader.class); + when(data.getRegionLoader()).thenReturn(regionLoader); + when(data.getBiomeLoader()).thenReturn(biomeLoader); + when(regionLoader.load("tropical")).thenReturn(tropical); + when(biomeLoader.load("volcanoes")).thenReturn(volcanoes); + when(biomeLoader.load("ash")).thenReturn(biome("ash")); + when(biomeLoader.load("beach")).thenReturn(biome("beach")); + when(biomeLoader.load("hollow")).thenReturn(biome("hollow")); + when(biomeLoader.load("magma")).thenReturn(biome("magma")); + when(biomeLoader.load("deep-dark")).thenReturn(biome("deep-dark")); + when(biomeLoader.load("disabled-band")).thenReturn(biome("disabled-band")); + + KList caves = dimension.getReachableCaveBiomes(() -> data); + + assertEquals(Set.of("hollow", "magma", "deep-dark"), caves.stream().map(IrisBiome::getLoadKey).collect(Collectors.toSet())); + assertEquals(3, caves.size()); } private static Set reachableKeys(IrisDimension dimension, IrisData data) { diff --git a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java index 7e8cb0892..7db7a4e5b 100644 --- a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java @@ -34,8 +34,8 @@ public class PackHydrologyValidatorTest { { "enabled": true, "tiers": [ - {"name": "stream", "minCatchment": 1500, "halfWidth": [0.5, 2], "fluid": "water"}, - {"name": "river", "minCatchment": 20000, "halfWidth": [2, 64], "fluid": "lava"} + {"name": "stream", "minCatchment": 1500, "halfWidth": [0.5, 2], "bankBand": 0, "fluid": "water"}, + {"name": "river", "minCatchment": 20000, "halfWidth": [2, 64], "bankBand": 32, "fluid": "lava"} ], "ponds": {"freeboard": [0, 2], "fluid": "lava", "seeded": {"radius": [4, 12], "depth": [2, 8], "channelSpacing": [48, 160]}}, @@ -120,6 +120,41 @@ public class PackHydrologyValidatorTest { assertEquals(errors.toString(), 1, errors.size()); } + @Test + public void rejectsPolicyWetnessOutsideItsOrderedBounds() throws Exception { + File pack = pack(dimension(WATER_ONLY, "\"hydrologyPolicy\": {\"wetness\": {\"min\": 0.2, \"max\": 0.6}},")); + write(pack, "regions/region.json", """ + {"landBiomes": ["biome"], "hydrologyPolicy": {"wetness": {"max": 1.5}}} + """); + write(pack, "biomes/biome.json", """ + {"name": "Biome", "hydrologyPolicy": {"wetness": {"min": 0.8, "max": 0.3}}} + """); + + List errors = validate(pack).errors(); + + assertContains(errors, "Region 'region'.hydrologyPolicy.wetness must have 0 <= min <= max <= 1, got min 0.0 and max 1.5."); + assertContains(errors, "Biome 'biome'.hydrologyPolicy.wetness must have 0 <= min <= max <= 1, got min 0.8 and max 0.3."); + assertEquals(errors.toString(), 2, errors.size()); + } + + @Test + public void rejectsPolicyMultipliersOutsideZeroToSixteen() throws Exception { + File pack = pack(dimension(WATER_ONLY, "\"hydrologyPolicy\": {\"rainfall\": 16, \"pondDensity\": 0},")); + write(pack, "regions/region.json", """ + {"landBiomes": ["biome"], "hydrologyPolicy": {"pondDensity": 17}} + """); + write(pack, "biomes/biome.json", """ + {"name": "Biome", "hydrologyPolicy": {"rainfall": -0.5, "pondDensity": 16.5}} + """); + + List errors = validate(pack).errors(); + + assertContains(errors, "Region 'region'.hydrologyPolicy.pondDensity must be a finite value from 0 to 16, got 17.0."); + assertContains(errors, "Biome 'biome'.hydrologyPolicy.rainfall must be a finite value from 0 to 16, got -0.5."); + assertContains(errors, "Biome 'biome'.hydrologyPolicy.pondDensity must be a finite value from 0 to 16, got 16.5."); + assertEquals(errors.toString(), 3, errors.size()); + } + @Test public void rejectsFluidReferencesTheFluidProfilesDoNotDefine() throws Exception { File pack = pack(dimension(""" @@ -429,6 +464,218 @@ public class PackHydrologyValidatorTest { } } + @Test + public void rejectsSeaInletSpacingBelowOne() throws Exception { + File pack = pack(dimension("{\"enabled\": true, \"underground\": {\"seaInlets\": {\"spacing\": 0}}}", "")); + write(pack, "dimensions/edge.json", dimension("{\"enabled\": true, \"underground\": {\"seaInlets\": {\"spacing\": 1}}}", "")); + + assertEquals(List.of("Dimension 'main'.hydrology does not compile: Hydrology underground.seaInlets.spacing must be at least 1, got 0"), + validate(pack).errors()); + } + + @Test + public void rejectsPrefetchRingsOutsideZeroToFour() throws Exception { + File pack = pack(dimension("{\"enabled\": true, \"prefetchRings\": 5}", "")); + write(pack, "dimensions/low.json", dimension("{\"enabled\": true, \"prefetchRings\": -1}", "")); + write(pack, "dimensions/edge.json", dimension("{\"enabled\": true, \"prefetchRings\": 4}", "")); + + assertEquals(List.of( + "Dimension 'low'.hydrology does not compile: Hydrology prefetchRings must stay within 0..4, got -1", + "Dimension 'main'.hydrology does not compile: Hydrology prefetchRings must stay within 0..4, got 5"), validate(pack).errors()); + } + + @Test + public void rejectsSeededPondDensityOutsideZeroToSixtyFour() throws Exception { + File pack = pack(dimension("{\"enabled\": true, \"ponds\": {\"seeded\": {\"density\": 64.5}}}", "")); + write(pack, "dimensions/low.json", dimension("{\"enabled\": true, \"ponds\": {\"seeded\": {\"density\": -1}}}", "")); + write(pack, "dimensions/edge.json", dimension("{\"enabled\": true, \"ponds\": {\"seeded\": {\"density\": 64}}}", "")); + + assertEquals(List.of( + "Dimension 'low'.hydrology does not compile: Hydrology ponds.seeded.density must stay within 0..64, got -1.0", + "Dimension 'main'.hydrology does not compile: Hydrology ponds.seeded.density must stay within 0..64, got 64.5"), + validate(pack).errors()); + } + + @Test + public void rejectsFillEpsilonAtOrBelowZero() throws Exception { + File pack = pack(dimension("{\"enabled\": true, \"drainage\": {\"fillEpsilon\": 0}}", "")); + write(pack, "dimensions/low.json", dimension("{\"enabled\": true, \"drainage\": {\"fillEpsilon\": -0.001}}", "")); + write(pack, "dimensions/edge.json", dimension("{\"enabled\": true, \"drainage\": {\"fillEpsilon\": 0.00001}}", "")); + + assertEquals(List.of( + "Dimension 'low'.hydrology does not compile: Hydrology drainage.fillEpsilon must be a finite value above 0, got -0.001", + "Dimension 'main'.hydrology does not compile: Hydrology drainage.fillEpsilon must be a finite value above 0, got 0.0"), + validate(pack).errors()); + } + + @Test + public void rejectsWaterfallMinimumDropBelowTwo() throws Exception { + File pack = pack(dimension(""" + {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0}, + {"name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "bankBand": 32, "waterfallMinimumDrop": 1}]} + """, "")); + write(pack, "dimensions/edge.json", dimension(""" + {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "waterfallMinimumDrop": 2}]} + """, "")); + + assertEquals(List.of("Dimension 'main'.hydrology does not compile: Hydrology tiers[1].waterfallMinimumDrop must be at least 2, got 1"), + validate(pack).errors()); + } + + @Test + public void rejectsShoreDepthBelowOne() throws Exception { + File pack = pack(dimension(""" + {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "materials": {"shoreDepth": 0}}]} + """, "")); + write(pack, "dimensions/ponds.json", dimension("{\"enabled\": true, \"ponds\": {\"materials\": {\"shoreDepth\": 0}}}", "")); + write(pack, "dimensions/edge.json", dimension(""" + {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "materials": {"shoreDepth": 1}}], + "ponds": {"materials": {"shoreDepth": 1}}} + """, "")); + + assertEquals(List.of( + "Dimension 'main'.hydrology does not compile: Hydrology tiers[0].materials.shoreDepth must be at least 1, got 0", + "Dimension 'ponds'.hydrology does not compile: Hydrology ponds.materials.shoreDepth must be at least 1, got 0"), + validate(pack).errors()); + } + + @Test + public void rejectsNegativeWidthFactorDepthRatioAndMaxFill() throws Exception { + File pack = pack(dimension(""" + {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "widthFactor": -1}]} + """, "")); + write(pack, "dimensions/ratio.json", dimension(""" + {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "depthRatio": -0.1}]} + """, "")); + write(pack, "dimensions/fill.json", dimension("{\"enabled\": true, \"deformation\": {\"maxFill\": -1}}", "")); + write(pack, "dimensions/edge.json", dimension(""" + {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "widthFactor": 0, "depthRatio": 0}], + "deformation": {"maxFill": 0}} + """, "")); + + assertEquals(List.of( + "Dimension 'fill'.hydrology does not compile: Hydrology deformation.maxFill must be at least 0, got -1", + "Dimension 'main'.hydrology does not compile: Hydrology tiers[0].widthFactor must be a finite value of at least 0, got -1.0", + "Dimension 'ratio'.hydrology does not compile: Hydrology tiers[0].depthRatio must be a finite value of at least 0, got -0.1"), + validate(pack).errors()); + } + + @Test + public void rejectsCavePoolFreeboardThatReachesMaxDepth() throws Exception { + File pack = pack(dimension("{\"enabled\": true, \"underground\": {\"cavePools\": {\"maxDepth\": 2, \"freeboard\": [0, 2]}}}", "")); + write(pack, "dimensions/edge.json", dimension(""" + {"enabled": true, "underground": {"cavePools": {"maxDepth": 3, "freeboard": [0, 2]}}} + """, "")); + write(pack, "dimensions/off.json", dimension(""" + {"enabled": true, "underground": {"cavePools": {"enabled": false, "maxDepth": 2, "freeboard": [0, 2]}}} + """, "")); + + assertEquals(List.of( + "Dimension 'main'.hydrology does not compile: Hydrology underground.cavePools.freeboard max 2 must stay below maxDepth 2"), + validate(pack).errors()); + } + + @Test + public void rejectsLakesWiderThanTheLakeExtent() throws Exception { + File pack = pack(dimension("{\"enabled\": true, \"lakes\": {\"maxArea\": 4194305}}", "")); + write(pack, "dimensions/edge.json", dimension("{\"enabled\": true, \"lakes\": {\"maxArea\": 4194304}}", "")); + + assertEquals(List.of("Dimension 'main'.hydrology does not compile: Hydrology lakes.maxArea must not go above 4194304" + + " (2048 by 2048 blocks, the widest a lake can span), got 4194305"), validate(pack).errors()); + } + + @Test + public void rejectsCavePoolsWiderThanTheirReach() throws Exception { + File pack = pack(dimension("{\"enabled\": true, \"underground\": {\"cavePools\": {\"maxArea\": 962}}}", "")); + write(pack, "dimensions/edge.json", dimension("{\"enabled\": true, \"underground\": {\"cavePools\": {\"maxArea\": 961}}}", "")); + write(pack, "dimensions/off.json", dimension(""" + {"enabled": true, "underground": {"cavePools": {"enabled": false, "maxArea": 962}}} + """, "")); + + assertEquals(List.of("Dimension 'main'.hydrology does not compile: Hydrology underground.cavePools.maxArea must not go above 961" + + " (31 by 31 blocks, the widest a pool can spread), got 962"), validate(pack).errors()); + } + + @Test + public void rejectsRegionAndDimensionPolicyFluidsWhileCavePoolsAreOff() throws Exception { + File pack = pack(dimension(""" + {"enabled": true, "underground": {"cavePools": {"enabled": false}}, "fluids": [{"name": "water"}]} + """, "\"hydrologyPolicy\": {\"fluid\": \"brine\"},")); + write(pack, "regions/region.json", """ + {"landBiomes": ["biome"], "hydrologyPolicy": {"fluid": "tar"}} + """); + + assertEquals(List.of( + "Dimension 'main'.hydrologyPolicy.fluid names fluid 'brine', which Dimension 'main'.hydrology.fluids does not define [water].", + "Region 'region'.hydrologyPolicy.fluid names fluid 'tar', which Dimension 'main'.hydrology.fluids does not define [water]."), + validate(pack).errors()); + } + + @Test + public void warnsWhenAWrittenTierLeavesHalfWidthOrBankBandUnset() throws Exception { + PackHydrologyValidator.Validation validation = validate(pack(dimension(""" + {"enabled": true, "tiers": [ + {"name": "stream", "halfWidth": [0.5, 2], "bankBand": 4}, + {"name": "river", "minCatchment": 20000, "bankBand": 32}, + {"name": "major", "minCatchment": 320000, "halfWidth": [8, 16]}]} + """, ""))); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertEquals(List.of( + "Dimension 'main'.hydrology.tiers[1] ('river') does not set halfWidth, so it takes the default [0.5, 2.0].", + "Dimension 'main'.hydrology.tiers[2] ('major') does not set bankBand, so it takes the default 0" + + " and leaves the ground beside its channels as it is."), validation.warnings()); + assertTrue(validate(pack(dimension("{\"enabled\": true}", ""))).warnings().isEmpty()); + } + + @Test + public void warnsWhenTheMantleCannotWriteHydrology() throws Exception { + File pack = pack(dimension("{\"enabled\": true}", "\"useMantle\": false,")); + write(pack, "dimensions/other.json", dimension("{\"enabled\": true}", "\"disabledComponents\": [\"RIVER_HYDROLOGY\"],")); + write(pack, "dimensions/off.json", dimension("{\"enabled\": false}", "\"useMantle\": false,")); + + PackHydrologyValidator.Validation validation = validate(pack); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertEquals(List.of( + "Dimension 'main' sets useMantle to false while hydrology is enabled, so the falling water at waterfalls and cascades," + + " sea inlets and cave pools are not generated.", + "Dimension 'other' disables the RIVER_HYDROLOGY component while hydrology is enabled, so the falling water at waterfalls" + + " and cascades, sea inlets and cave pools are not generated."), validation.warnings()); + } + + @Test + public void shoreBiomesWithoutWidthWarn() throws Exception { + PackHydrologyValidator.Validation unset = validate(shorePack("")); + PackHydrologyValidator.Validation widened = validate(shorePack(", \"shoreBiomeWidth\": 3")); + + assertTrue(unset.errors().toString(), unset.errors().isEmpty()); + assertEquals(List.of( + "Dimension 'main'.hydrologyPolicy.shoreBiomes lists shore biomes, but no shoreBiomeWidth above 0 applies to them," + + " so none are placed.", + "Region 'region'.hydrologyPolicy.shoreBiomes lists shore biomes, but no shoreBiomeWidth above 0 applies to them," + + " so none are placed.", + "Biome 'dune'.hydrologyPolicy.shoreBiomes lists shore biomes, but no shoreBiomeWidth above 0 applies to them," + + " so none are placed."), unset.warnings()); + assertTrue(widened.errors().toString(), widened.errors().isEmpty()); + assertTrue(widened.warnings().toString(), widened.warnings().isEmpty()); + } + + private File shorePack(String dimensionWidth) throws Exception { + File pack = pack(dimension(WATER_ONLY, "\"hydrologyPolicy\": {\"shoreBiomes\": [\"beach\"]" + dimensionWidth + "},")); + write(pack, "regions/region.json", """ + {"landBiomes": ["biome", "dune", "bare"], "hydrologyPolicy": {"shoreBiomes": ["beach"]}} + """); + write(pack, "biomes/dune.json", """ + {"name": "Dune", "hydrologyPolicy": {"shoreBiomes": ["beach"]}} + """); + write(pack, "biomes/bare.json", """ + {"name": "Bare", "hydrologyPolicy": {"shoreBiomes": []}} + """); + write(pack, "biomes/beach.json", "{\"name\": \"Beach\"}"); + return pack; + } + private PackHydrologyValidator.Validation validate(File pack) { File[] dimensions = new File(pack, "dimensions").listFiles( file -> file.isFile() && file.getName().endsWith(".json")); 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 d70a7a479..dc52a3540 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 @@ -1,10 +1,22 @@ package art.arcane.iris.pack.datapack.export.compile.terrain; +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.block.IrisBlockData; +import art.arcane.iris.generation.decoration.IrisDecorationPart; +import art.arcane.iris.generation.decoration.IrisDecorator; import art.arcane.iris.generation.hydrology.config.IrisBankStyle; +import art.arcane.iris.generation.hydrology.config.IrisFluidProfile; import art.arcane.iris.generation.hydrology.config.IrisHydrology; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyClimate; import art.arcane.iris.generation.hydrology.config.IrisHydrologyDeformation; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyPermission; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyUnderground; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness; import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisMaterialPalette; +import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.pack.datapack.DataVersion; import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry; import art.arcane.iris.pack.datapack.export.ir.Axis; @@ -20,12 +32,15 @@ import art.arcane.volmlib.util.collection.KList; import org.junit.Test; import java.util.ArrayList; +import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; +import java.util.function.Supplier; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; public class RiverCompilerTest { @@ -163,10 +178,293 @@ 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), diagnostics.stream().map(ExportDiagnostic::limit).toList()); + assertEquals(List.of(ExportLimit.ELEVATED_WATER, ExportLimit.RIVER_DRAINAGE, ExportLimit.SEA_INLET, ExportLimit.CAVE_POOL), + diagnostics.stream().map(ExportDiagnostic::limit).toList()); assertEquals("dimensions/rivers/hydrology", diagnostics.getFirst().resource()); } + @Test + public void lavaRiversReportADiagnostic() { + List diagnostics = new ArrayList<>(); + IrisBiome volcano = biome("tropical/volcanoes", new IrisHydrologyPolicy().setFluid("lava")); + List areas = List.of( + new RiverCompiler.Area(region("tropical", null), List.of(volcano)), + new RiverCompiler.Area(region("hot", null), List.of(volcano)), + new RiverCompiler.Area(region("hot", null), List.of(biome("plains", null)))); + + compile(new Field.Const(SEA_LEVEL + 2.0), withLava(overworldHydrology()), areas, diagnostics); + + List fluids = limited(diagnostics, ExportLimit.RIVER_FLUID); + assertEquals(diagnostics.toString(), 1, fluids.size()); + assertEquals("biomes/tropical/volcanoes", fluids.getFirst().resource()); + assertEquals(ExportDiagnostic.Severity.WARNING, fluids.getFirst().severity()); + assertTrue(fluids.getFirst().message(), fluids.getFirst().message().contains("'lava'")); + assertTrue(fluids.getFirst().message(), fluids.getFirst().message().contains("minecraft:water")); + } + + @Test + public void childBiomesInheritTheParentLava() { + List diagnostics = new ArrayList<>(); + IrisBiome plains = biome("tropical/volcanic-plains", new IrisHydrologyPolicy().setFluid("lava")); + IrisBiome cone = biome("tropical/cone", new IrisHydrologyPolicy().setRainfall(1.0)); + IrisBiome spring = biome("tropical/spring", new IrisHydrologyPolicy().setFluid("water")); + + compile(new Field.Const(SEA_LEVEL + 2.0), withLava(overworldHydrology()), List.of( + new RiverCompiler.Area(region("tropical", null), List.of(cone, plains)), + new RiverCompiler.Area(region("tropical", null), List.of(spring, plains))), diagnostics); + + List fluids = limited(diagnostics, ExportLimit.RIVER_FLUID); + assertEquals(diagnostics.toString(), 1, fluids.size()); + assertEquals("biomes/tropical/volcanic-plains", fluids.getFirst().resource()); + assertTrue(fluids.getFirst().message(), fluids.getFirst().message().contains("'lava'")); + } + + @Test + public void lavaTiersReportTheirFluidAndSeamOnTheHydrology() { + List diagnostics = new ArrayList<>(); + IrisHydrology hydrology = withLava(overworldHydrology()); + hydrology.getFluids().getLast().setSeam("obsidian"); + hydrology.getFluids().add(new IrisFluidProfile().setName("obsidian").setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:obsidian"))); + for (IrisHydrologyTier tier : hydrology.getTiers()) { + tier.setFluid("lava"); + } + + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, List.of(new RiverCompiler.Area(region("region", null), List.of(biome("plains", null)))), diagnostics); + + List fluids = limited(diagnostics, ExportLimit.RIVER_FLUID); + assertEquals(diagnostics.toString(), 1, fluids.size()); + assertEquals("dimensions/rivers/hydrology", fluids.getFirst().resource()); + assertTrue(fluids.getFirst().message(), fluids.getFirst().message().contains("'obsidian'")); + } + + @Test + public void waterSeamsReportADiagnostic() { + List diagnostics = new ArrayList<>(); + IrisHydrology hydrology = overworldHydrology().setFluids(new KList<>( + new IrisFluidProfile().setSeam("mud"), + new IrisFluidProfile().setName("mud").setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:mud")))); + + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, List.of(new RiverCompiler.Area(region("region", null), List.of(biome("plains", null)))), diagnostics); + + List fluids = limited(diagnostics, ExportLimit.RIVER_FLUID); + assertEquals(diagnostics.toString(), 1, fluids.size()); + assertEquals("dimensions/rivers/hydrology", fluids.getFirst().resource()); + assertTrue(fluids.getFirst().message(), fluids.getFirst().message().contains("Seam 'mud' of fluid 'water'")); + } + + @Test + public void unknownPolicyFluidFailsTheExport() { + IrisBiome acid = biome("acid-lake", new IrisHydrologyPolicy().setFluid("acid")); + List areas = List.of(new RiverCompiler.Area(region("region", null), List.of(acid))); + + IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, + () -> compile(new Field.Const(SEA_LEVEL + 2.0), overworldHydrology(), areas, new ArrayList<>())); + + assertTrue(failure.getMessage(), failure.getMessage().contains("'acid'")); + assertTrue(failure.getMessage(), failure.getMessage().contains("biomes/acid-lake")); + } + + @Test + public void areasAreBuiltOnlyWhenRiversExport() { + Supplier> refused = () -> { + throw new AssertionError("areas built without exported rivers"); + }; + for (IrisHydrology hydrology : new IrisHydrology[]{null, overworldHydrology().setEnabled(false), overworldHydrology().setDensity(0.0)}) { + List diagnostics = new ArrayList<>(); + + compile(new Field.Const(SEA_LEVEL + 2.0), dimension(hydrology, null), refused, registry(), DataVersion.V26_3, diagnostics); + + assertTrue(diagnostics.toString(), limited(diagnostics, ExportLimit.RIVER_DRAINAGE).isEmpty()); + } + } + + @Test + public void fluidsMatchingTheExportedFluidReportNothing() { + List water = new ArrayList<>(); + IrisBiome wet = biome("plains", new IrisHydrologyPolicy().setFluid("water")); + compile(new Field.Const(SEA_LEVEL + 2.0), withLava(overworldHydrology()), List.of(new RiverCompiler.Area(region("region", null), List.of(wet))), water); + + List lava = new ArrayList<>(); + IrisHydrology molten = withLava(overworldHydrology()); + for (IrisHydrologyTier tier : molten.getTiers()) { + tier.setFluid("lava"); + } + IrisDimension nether = dimension(molten, new IrisHydrologyPolicy().setFluid("lava")); + nether.setFluidPalette(new IrisMaterialPalette().qclear().qadd("lava")); + compile(new Field.Const(SEA_LEVEL + 2.0), nether, List.of(new RiverCompiler.Area(region("region", null), List.of(biome("plains", null)))), + registry(), DataVersion.V26_3, lava); + + assertTrue(water.toString(), limited(water, ExportLimit.RIVER_FLUID).isEmpty()); + assertTrue(lava.toString(), limited(lava, ExportLimit.RIVER_FLUID).isEmpty()); + } + + @Test + public void rainfallAndBlockedStreamsReportPolicyDiagnostics() { + List diagnostics = new ArrayList<>(); + IrisRegion hot = region("hot", new IrisHydrologyPolicy().setRainfall(1.4)); + IrisBiome deep = biome("ocean/deep", new IrisHydrologyPolicy().setStreams(IrisHydrologyPermission.BLOCK)); + IrisBiome neutral = biome("plains", new IrisHydrologyPolicy().setRainfall(1.0)); + IrisDimension dimension = dimension(overworldHydrology(), new IrisHydrologyPolicy().setRainfall(1.2)); + + compile(new Field.Const(SEA_LEVEL + 2.0), dimension, List.of(new RiverCompiler.Area(hot, List.of(deep)), new RiverCompiler.Area(hot, List.of(neutral))), + registry(), DataVersion.V26_3, diagnostics); + + List policies = limited(diagnostics, ExportLimit.RIVER_POLICY); + assertEquals(List.of("regions/hot", "biomes/ocean/deep"), policies.stream().map(ExportDiagnostic::resource).toList()); + assertTrue(policies.getFirst().message(), policies.getFirst().message().contains("rainfall")); + assertTrue(policies.getLast().message(), policies.getLast().message().contains("BLOCK")); + } + + @Test + public void wetAndDryZonesReportAClimateDiagnostic() { + List zoned = new ArrayList<>(); + IrisHydrology hydrology = overworldHydrology().setClimate(new IrisHydrologyClimate().setEnabled(true)); + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, List.of(new RiverCompiler.Area(region("region", null), List.of(biome("plains", null)))), zoned); + + List exempt = new ArrayList<>(); + IrisRegion everywhere = region("region", new IrisHydrologyPolicy().setClimateZones(false)); + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, List.of(new RiverCompiler.Area(everywhere, List.of(biome("plains", null)))), exempt); + + List climate = limited(zoned, ExportLimit.RIVER_CLIMATE); + assertEquals(zoned.toString(), 1, climate.size()); + assertEquals("dimensions/rivers/hydrology", climate.getFirst().resource()); + assertTrue(exempt.toString(), limited(exempt, ExportLimit.RIVER_CLIMATE).isEmpty()); + } + + @Test + public void wetnessBoundsReportAClimateDiagnostic() { + IrisHydrology hydrology = overworldHydrology().setClimate(new IrisHydrologyClimate().setEnabled(true)); + IrisRegion hot = region("hot", new IrisHydrologyPolicy().setWetness(new IrisHydrologyWetness().setMax(0.35))); + List areas = List.of( + new RiverCompiler.Area(hot, List.of(biome("swamp", new IrisHydrologyPolicy().setWetness(new IrisHydrologyWetness().setMin(0.7))))), + new RiverCompiler.Area(hot, List.of(biome("desert", null))), + new RiverCompiler.Area(region("plain", null), List.of(biome("plains", new IrisHydrologyPolicy().setWetness(new IrisHydrologyWetness()))))); + List zoned = new ArrayList<>(); + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, areas, zoned); + + List unzoned = new ArrayList<>(); + compile(new Field.Const(SEA_LEVEL + 2.0), overworldHydrology(), areas, unzoned); + + List exempt = new ArrayList<>(); + IrisRegion everywhere = region("hot", new IrisHydrologyPolicy().setClimateZones(false).setWetness(new IrisHydrologyWetness().setMax(0.35))); + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, List.of(new RiverCompiler.Area(everywhere, List.of(biome("desert", null)))), exempt); + + List climate = limited(zoned, ExportLimit.RIVER_CLIMATE); + assertEquals(List.of("dimensions/rivers/hydrology", "regions/hot", "biomes/swamp"), climate.stream().map(ExportDiagnostic::resource).toList()); + assertTrue(climate.getLast().message(), climate.getLast().message().contains("wetness")); + assertTrue(unzoned.toString(), limited(unzoned, ExportLimit.RIVER_CLIMATE).isEmpty()); + assertTrue(exempt.toString(), limited(exempt, ExportLimit.RIVER_CLIMATE).isEmpty()); + } + + @Test + public void shoreBiomesWithAWidthReportADiagnostic() { + List diagnostics = new ArrayList<>(); + IrisDimension dimension = dimension(overworldHydrology(), new IrisHydrologyPolicy().setShoreBiomes(new KList<>("shore/beach"))); + List areas = List.of( + new RiverCompiler.Area(region("banked", new IrisHydrologyPolicy().setShoreBiomeWidth(4)), List.of(biome("plains", null))), + new RiverCompiler.Area(region("bare", null), List.of(biome("plains", null)))); + + compile(new Field.Const(SEA_LEVEL + 2.0), dimension, areas, registry(), DataVersion.V26_3, diagnostics); + + List widthless = new ArrayList<>(); + compile(new Field.Const(SEA_LEVEL + 2.0), dimension, List.of(areas.getLast()), registry(), DataVersion.V26_3, widthless); + + assertEquals(List.of("dimensions/rivers"), limited(diagnostics, ExportLimit.RIVER_SHORE_BIOME).stream().map(ExportDiagnostic::resource).toList()); + assertTrue(widthless.toString(), limited(widthless, ExportLimit.RIVER_SHORE_BIOME).isEmpty()); + } + + @Test + public void waterDecoratorsReportADiagnostic() { + List diagnostics = new ArrayList<>(); + IrisHydrology hydrology = overworldHydrology(); + hydrology.getTiers().getFirst().setDecorators(new KList<>(seagrass())); + IrisBiome reeds = biome("swamp", new IrisHydrologyPolicy().setDecorators(new KList<>(seagrass()))); + IrisBiome barren = biome("desert", new IrisHydrologyPolicy().setDecorators(new KList<>())); + IrisRegion region = region("region", null); + + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, List.of(new RiverCompiler.Area(region, List.of(reeds)), new RiverCompiler.Area(region, List.of(barren))), diagnostics); + + List plain = new ArrayList<>(); + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, List.of(new RiverCompiler.Area(region, List.of(biome("plains", null)))), plain); + + assertEquals(List.of("biomes/swamp"), limited(diagnostics, ExportLimit.RIVER_DECORATOR).stream().map(ExportDiagnostic::resource).toList()); + assertEquals(List.of("dimensions/rivers/hydrology"), limited(plain, ExportLimit.RIVER_DECORATOR).stream().map(ExportDiagnostic::resource).toList()); + } + + @Test + public void seaInletsReportADiagnostic() { + List diagnostics = new ArrayList<>(); + IrisHydrology hydrology = overworldHydrology(); + hydrology.getUnderground().getCavePools().setEnabled(false); + + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, registry(), DataVersion.V26_3, diagnostics); + + assertEquals(1, limited(diagnostics, ExportLimit.SEA_INLET).size()); + assertEquals("dimensions/rivers/hydrology", limited(diagnostics, ExportLimit.SEA_INLET).getFirst().resource()); + assertTrue(diagnostics.toString(), limited(diagnostics, ExportLimit.CAVE_POOL).isEmpty()); + } + + @Test + public void cavePoolsReportADiagnostic() { + List diagnostics = new ArrayList<>(); + IrisHydrology hydrology = overworldHydrology(); + hydrology.getUnderground().getSeaInlets().setEnabled(false); + + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, registry(), DataVersion.V26_3, diagnostics); + + assertEquals(1, limited(diagnostics, ExportLimit.CAVE_POOL).size()); + assertEquals("dimensions/rivers/hydrology", limited(diagnostics, ExportLimit.CAVE_POOL).getFirst().resource()); + assertTrue(diagnostics.toString(), limited(diagnostics, ExportLimit.SEA_INLET).isEmpty()); + } + + @Test + public void unusedHydrologyFeaturesReportNoLimits() { + List plain = new ArrayList<>(); + IrisHydrology hydrology = withLava(overworldHydrology()).setUnderground(underground(false)); + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, registry(), DataVersion.V26_3, plain); + + List dry = new ArrayList<>(); + IrisHydrology still = overworldHydrology().setDensity(0.0).setClimate(new IrisHydrologyClimate().setEnabled(true)); + still.getTiers().getFirst().setDecorators(new KList<>(seagrass())); + compile(new Field.Const(SEA_LEVEL + 2.0), still, registry(), DataVersion.V26_3, dry); + + assertEquals(List.of(ExportLimit.ELEVATED_WATER, ExportLimit.RIVER_DRAINAGE), plain.stream().map(ExportDiagnostic::limit).toList()); + assertEquals(List.of(ExportLimit.ELEVATED_WATER), dry.stream().map(ExportDiagnostic::limit).toList()); + } + + @Test + public void limitOrderIgnoresAreaOrder() { + IrisHydrology hydrology = withLava(overworldHydrology()).setClimate(new IrisHydrologyClimate().setEnabled(true)); + hydrology.getTiers().getFirst().setDecorators(new KList<>(seagrass())); + IrisRegion hot = region("hot", new IrisHydrologyPolicy().setRainfall(0.5).setShoreBiomes(new KList<>("hot/beach")).setShoreBiomeWidth(3)); + IrisRegion wet = region("wet", new IrisHydrologyPolicy().setRainfall(2.0)); + List areas = List.of( + new RiverCompiler.Area(hot, List.of(biome("volcano", new IrisHydrologyPolicy().setFluid("lava")))), + new RiverCompiler.Area(hot, List.of(biome("deep", new IrisHydrologyPolicy().setStreams(IrisHydrologyPermission.BLOCK)))), + new RiverCompiler.Area(wet, List.of(biome("marsh", new IrisHydrologyPolicy().setDecorators(new KList<>(seagrass()))))), + new RiverCompiler.Area(wet, List.of(biome("plains", null)))); + List reversed = new ArrayList<>(areas); + Collections.reverse(reversed); + List forward = new ArrayList<>(); + List backward = new ArrayList<>(); + + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, areas, forward); + compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, reversed, backward); + + assertEquals(forward, backward); + assertEquals(List.of(ExportLimit.ELEVATED_WATER, ExportLimit.RIVER_DRAINAGE, + ExportLimit.RIVER_FLUID, + ExportLimit.RIVER_POLICY, ExportLimit.RIVER_POLICY, ExportLimit.RIVER_POLICY, + 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()); + 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"), + limited(forward, ExportLimit.RIVER_DECORATOR).stream().map(ExportDiagnostic::resource).toList()); + } + @Test public void expensiveChildrenOnlyBehindMuxOrGate() { IrisHydrology hydrology = hydrology( @@ -206,11 +504,65 @@ public class RiverCompilerTest { } private static Field compile(Field natural, IrisHydrology hydrology, NoiseRegistry registry, DataVersion target, List diagnostics) { + return compile(natural, dimension(hydrology, null), List.of(new RiverCompiler.Area(region("region", null), List.of(biome("plains", null)))), + registry, target, diagnostics); + } + + private static Field compile(Field natural, IrisHydrology hydrology, List areas, List diagnostics) { + return compile(natural, dimension(hydrology, null), areas, registry(), DataVersion.V26_3, diagnostics); + } + + private static Field compile(Field natural, IrisDimension dimension, List areas, NoiseRegistry registry, DataVersion target, + List diagnostics) { + return compile(natural, dimension, () -> areas, registry, target, diagnostics); + } + + private static Field compile(Field natural, IrisDimension dimension, Supplier> areas, NoiseRegistry registry, + DataVersion target, List diagnostics) { + return new RiverCompiler(diagnostics).compile(natural, dimension, areas, registry, ExportCapabilities.forTarget(target)); + } + + private static IrisDimension dimension(IrisHydrology hydrology, IrisHydrologyPolicy policy) { IrisDimension dimension = new IrisDimension(); dimension.setLoadKey("rivers"); dimension.setFluidHeight(SEA_LEVEL); dimension.setHydrology(hydrology); - return new RiverCompiler(diagnostics).compile(natural, dimension, registry, ExportCapabilities.forTarget(target)); + dimension.setHydrologyPolicy(policy); + return dimension; + } + + private static IrisRegion region(String key, IrisHydrologyPolicy policy) { + IrisRegion region = new IrisRegion(); + region.setLoadKey(key); + region.setHydrologyPolicy(policy); + return region; + } + + private static IrisBiome biome(String key, IrisHydrologyPolicy policy) { + IrisBiome biome = new IrisBiome(); + biome.setLoadKey(key); + biome.setHydrologyPolicy(policy); + return biome; + } + + private static List limited(List diagnostics, ExportLimit limit) { + return diagnostics.stream().filter(diagnostic -> diagnostic.limit() == limit).toList(); + } + + private static IrisDecorator seagrass() { + return new IrisDecorator().setPartOf(IrisDecorationPart.SEA_FLOOR).setPalette(new KList<>(new IrisBlockData("minecraft:seagrass"))); + } + + private static IrisHydrologyUnderground underground(boolean enabled) { + IrisHydrologyUnderground underground = new IrisHydrologyUnderground(); + underground.getSeaInlets().setEnabled(enabled); + underground.getCavePools().setEnabled(enabled); + return underground; + } + + private static IrisHydrology withLava(IrisHydrology hydrology) { + IrisFluidProfile lava = new IrisFluidProfile().setName("lava").setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:lava")); + return hydrology.setFluids(new KList<>(new IrisFluidProfile(), lava)); } private static double sample(Field field, Map noises, DataVersion target, int x, int z) { diff --git a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverStageTest.java b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverStageTest.java index ba799f837..33ac30abe 100644 --- a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverStageTest.java +++ b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/RiverStageTest.java @@ -8,6 +8,7 @@ import art.arcane.iris.pack.datapack.export.WorldgenExportRequest; import art.arcane.iris.pack.datapack.export.compile.DimensionStage; import art.arcane.iris.pack.datapack.export.compile.PackCompileContext; import art.arcane.iris.pack.datapack.export.compile.PackCompiler; +import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes; import art.arcane.iris.pack.datapack.export.ir.Axis; import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic; import art.arcane.iris.pack.datapack.export.ir.ExportLimit; @@ -24,6 +25,7 @@ import org.junit.rules.TemporaryFolder; import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -65,6 +67,51 @@ public class RiverStageTest { } } + @Test + public void stageReportsTheHydrologyPoliciesOfExportedBiomes() throws Exception { + File pack = pack(false); + String fluids = "\"fluids\":[{\"name\":\"water\"},{\"name\":\"lava\",\"palette\":{\"palette\":[{\"block\":\"minecraft:lava\"}]}}]"; + CompatTestPlatform.write(pack, "dimensions/" + TerrainTestPacks.DIMENSION + ".json", + "{\"regions\":[\"region\"],\"hydrology\":{\"enabled\":true,\"density\":0.5," + fluids + "}}"); + CompatTestPlatform.write(pack, "regions/region.json", "{\"landBiomes\":[\"a\",\"b\"],\"hydrologyPolicy\":{\"rainfall\":1.5}}"); + TerrainTestPacks.biome(pack, "a", "{\"name\":\"A\",\"generators\":[" + TerrainTestPacks.link("hills", 0, 40) + "]," + + "\"hydrologyPolicy\":{\"fluid\":\"lava\"}}"); + IrisData data = IrisData.openRuntime(pack); + try { + PackCompileContext context = terrainContext(data, DataVersion.V26_3); + + new RiverStage().apply(context); + + assertEquals(List.of("biomes/a"), resources(context.diagnostics(), ExportLimit.RIVER_FLUID)); + assertEquals(List.of("regions/region"), resources(context.diagnostics(), ExportLimit.RIVER_POLICY)); + } finally { + data.close(); + } + } + + @Test + public void stageReadsExportedSurfaceBiomesAndTheirChildren() throws Exception { + File pack = pack(true); + CompatTestPlatform.write(pack, "regions/region.json", "{\"landBiomes\":[\"a\",\"b\"],\"caveBiomes\":[\"e\"]}"); + TerrainTestPacks.biome(pack, "a", "{\"name\":\"A\",\"generators\":[" + TerrainTestPacks.link("hills", 0, 40) + "],\"children\":[\"c\",\"d\"]}"); + TerrainTestPacks.biome(pack, "c", "{\"name\":\"C\",\"hydrologyPolicy\":{\"rainfall\":1.5}}"); + TerrainTestPacks.biome(pack, "d", "{\"name\":\"D\",\"hydrologyPolicy\":{\"streams\":\"BLOCK\"}}"); + TerrainTestPacks.biome(pack, "e", "{\"name\":\"E\",\"hydrologyPolicy\":{\"rainfall\":2.0}}"); + IrisData data = IrisData.openRuntime(pack); + try { + PackCompileContext context = terrainContext(data, DataVersion.V26_3); + BiomeCodes codes = context.baseBiomeCodes(); + context.setBiomeCodes(new BiomeCodes(codes.surfaceCode(), codes.caveCode(), codes.class3d(), codes.layout(), Map.of( + TerrainTestSupport.NAMESPACE + ":a", "a", TerrainTestSupport.NAMESPACE + ":b", "b", TerrainTestSupport.NAMESPACE + ":c", "c"))); + + new RiverStage().apply(context); + + assertEquals(List.of("biomes/c"), resources(context.diagnostics(), ExportLimit.RIVER_POLICY)); + } finally { + data.close(); + } + } + @Test public void aquiferSurfaceCarvesTheClimateHeight() throws Exception { IrisData data = IrisData.openRuntime(pack(true)); @@ -149,6 +196,10 @@ public class RiverStageTest { return pack; } + private static List resources(List diagnostics, ExportLimit limit) { + return diagnostics.stream().filter(diagnostic -> diagnostic.limit() == limit).map(ExportDiagnostic::resource).toList(); + } + private static PackCompileContext terrainContext(IrisData data, DataVersion target) { PackCompileContext context = context(data, target); new DimensionStage().apply(context); 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 94bca63a5..07c4affe0 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 = "3e10064463f6935c5ac8fe0558f0bb06483e5b0e116f5bfe6e54d13f2e0877d1"; + private static final String EXPECTED_SCHEMA_DIGEST = "15aa978844532aa9c10a82ca5408ae8a91b504545eab62297e0199768b34cbcb"; private static final List> SCHEMA_ROOTS = List.of( IrisDimension.class, diff --git a/core/src/test/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicySeaSurfaceTest.java b/core/src/test/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicySeaSurfaceTest.java new file mode 100644 index 000000000..acb899d16 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicySeaSurfaceTest.java @@ -0,0 +1,89 @@ +package art.arcane.iris.platform.bukkit.nms; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisMaterialPalette; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.pack.value.IrisRange; +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import art.arcane.volmlib.nativelib.terrain.structure.StructureSeaSurface; +import art.arcane.volmlib.util.collection.KList; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class BukkitStructureStagePolicySeaSurfaceTest { + private static final int MIN_HEIGHT = -256; + private static final int SEA_LEVEL = 50; + private static final IrisData DATA = mock(IrisData.class); + + @Test + public void topYIsMinHeightPlusFluidHeight() { + NativeBlockState water = fluid(); + Engine engine = engine(dimension(SEA_LEVEL, water)); + + StructureSeaSurface sea = new BukkitStructureStagePolicy(engine).seaSurface(engine); + + assertEquals(engine.getMinHeight() + engine.getDimension().getFluidHeight(), sea.topY()); + assertEquals(SEA_LEVEL, sea.topY()); + assertSame(water, sea.fluid()); + } + + @Test + public void lavaSeaDimensionSuppliesLava() { + NativeBlockState lava = fluid(); + Engine engine = engine(dimension(SEA_LEVEL, lava)); + + StructureSeaSurface sea = new BukkitStructureStagePolicy(engine).seaSurface(engine); + + assertEquals(SEA_LEVEL, sea.topY()); + assertSame(lava, sea.fluid()); + } + + @Test + public void seaFluidIsTheFirstFluidOfThePalette() { + NativeBlockState lava = fluid(); + Engine engine = engine(dimension(SEA_LEVEL, nonFluid(), lava, fluid())); + + assertSame(lava, new BukkitStructureStagePolicy(engine).seaSurface(engine).fluid()); + } + + @Test + public void dimensionWithoutASeaSuppliesNone() { + Engine dryPalette = engine(dimension(SEA_LEVEL, nonFluid())); + Engine seaAtTheFloor = engine(dimension(MIN_HEIGHT, fluid())); + + assertSame(StructureSeaSurface.NONE, new BukkitStructureStagePolicy(dryPalette).seaSurface(dryPalette)); + assertSame(StructureSeaSurface.NONE, new BukkitStructureStagePolicy(seaAtTheFloor).seaSurface(seaAtTheFloor)); + } + + private static IrisDimension dimension(int fluidHeight, NativeBlockState... fluidPalette) { + IrisMaterialPalette palette = mock(IrisMaterialPalette.class); + when(palette.getBlockData(DATA)).thenReturn(new KList<>(fluidPalette)); + return new IrisDimension() + .setDimensionHeight(new IrisRange(MIN_HEIGHT, 512)) + .setFluidHeight(fluidHeight) + .setFluidPalette(palette); + } + + private static Engine engine(IrisDimension dimension) { + Engine engine = mock(Engine.class); + when(engine.getMinHeight()).thenReturn(MIN_HEIGHT); + when(engine.getDimension()).thenReturn(dimension); + when(engine.getData()).thenReturn(DATA); + return engine; + } + + private static NativeBlockState fluid() { + NativeBlockState state = nonFluid(); + when(state.isFluid()).thenReturn(true); + return state; + } + + private static NativeBlockState nonFluid() { + return mock(NativeBlockState.class); + } +} diff --git a/core/src/test/java/art/arcane/iris/structure/placement/StructureCaveAnchorColumnScanTest.java b/core/src/test/java/art/arcane/iris/structure/placement/StructureCaveAnchorColumnScanTest.java index 5514bdbee..6e96848a8 100644 --- a/core/src/test/java/art/arcane/iris/structure/placement/StructureCaveAnchorColumnScanTest.java +++ b/core/src/test/java/art/arcane/iris/structure/placement/StructureCaveAnchorColumnScanTest.java @@ -44,9 +44,9 @@ public class StructureCaveAnchorColumnScanTest { baseline[y] = new MatterCavern(true, "", (byte) (y % 31 == 0 ? 1 : 0)); } } - hydrology[55] = HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE); - hydrology[56] = HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD); - hydrology[200] = HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR); + hydrology[55] = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"); + hydrology[56] = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"); + hydrology[200] = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"); Engine engine = fixture(baseline); try (MockedStatic storage = mockStatic(HydrologyCaveStorage.class)) { storage.when(() -> HydrologyCaveStorage.getIfPresent(any(Mantle.class), anyInt(), anyInt(), anyInt())) diff --git a/core/src/test/java/art/arcane/iris/structure/placement/StructureCaveAnchorResolverTest.java b/core/src/test/java/art/arcane/iris/structure/placement/StructureCaveAnchorResolverTest.java index 675819788..81201c90e 100644 --- a/core/src/test/java/art/arcane/iris/structure/placement/StructureCaveAnchorResolverTest.java +++ b/core/src/test/java/art/arcane/iris/structure/placement/StructureCaveAnchorResolverTest.java @@ -183,7 +183,7 @@ public class StructureCaveAnchorResolverTest { @Test public void protectedHydrologyRejectsBeforeReadingAnchorCavernAgain() { Engine engine = engineWithFloorAnchor(new MatterCavern(true, "", (byte) 0), 0); - HydrologyCaveCell protectedCell = HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR); + HydrologyCaveCell protectedCell = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"); AtomicInteger overlayReads = new AtomicInteger(); try (MockedStatic storage = mockStatic(HydrologyCaveStorage.class)) { storage.when(() -> HydrologyCaveStorage.getIfPresent(any(Mantle.class), anyInt(), anyInt(), anyInt())) @@ -223,13 +223,13 @@ public class StructureCaveAnchorResolverTest { MatterCavern forcedAir = new MatterCavern(true, "", (byte) 3); assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid( - true, fluid, HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE), 20, 8)); + true, fluid, new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"), 20, 8)); assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid( - true, fluid, HydrologyCaveCell.of(HydrologyCaveAction.FALLING_FLUID), 20, 8)); + true, fluid, new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water"), 20, 8)); assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid( - true, null, HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD), 20, 8)); + true, null, new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"), 20, 8)); assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid( - false, forcedAir, HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR), 0, 8)); + false, forcedAir, new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), 0, 8)); } private static Engine engineWithFloorAnchor(MatterCavern anchorCavern, int surfaceHeight) { diff --git a/core/src/test/java/art/arcane/iris/studio/map/MapCavePoolRefreshTest.java b/core/src/test/java/art/arcane/iris/studio/map/MapCavePoolRefreshTest.java new file mode 100644 index 000000000..89e5ceddf --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/map/MapCavePoolRefreshTest.java @@ -0,0 +1,197 @@ +package art.arcane.iris.studio.map; + +import art.arcane.iris.generation.biome.IrisBiome; +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.raster.ChunkWaterRaster; +import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.generation.runtime.IrisEngine; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.studio.map.components.MapLayer; +import art.arcane.iris.studio.map.components.MapStyle; +import art.arcane.iris.studio.map.components.MapTile; +import art.arcane.iris.studio.map.components.MapTileRenderer; +import art.arcane.iris.studio.map.components.TileType; +import art.arcane.iris.studio.render.IrisRenderer; +import art.arcane.iris.world.history.ChunkGenerationSemantics; +import art.arcane.iris.world.history.GenerationHistory; +import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter; +import art.arcane.volmlib.util.stream.ProceduralStream; +import art.arcane.volmlib.util.stream.interpolation.Interpolated; +import org.junit.Test; + +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.BooleanSupplier; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class MapCavePoolRefreshTest { + private static final int POOL_X = 20; + private static final int POOL_Z = 24; + private static final int POOL = IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.CAVE_POOL) & 0xFFFFFF; + + @Test + public void completeTilesPickUpRecordedCavePools() throws Exception { + Scene scene = new Scene(); + AtomicLong time = new AtomicLong(); + try (VisionRenderController controller = new VisionRenderController(() -> { }, time::get)) { + VisionRenderController.Frame frame = controller.request(spec(scene.renderer, 4D)); + await(() -> controller.progress(frame).ready() == 1 && controller.progress(frame).activeWorkers() == 0); + assertNotEquals(POOL, pixel(frame, 4D)); + long sampled = scene.samples.get(); + + scene.record(); + controller.retryProvisional(frame); + await(() -> controller.progress(frame).activeWorkers() == 0); + assertNotEquals("refreshes wait for the retry cadence", POOL, pixel(frame, 4D)); + time.set(VisionRenderController.FIRST_RETRY_NANOS); + await(() -> { + controller.retryProvisional(frame); + return pixel(frame, 4D) == POOL; + }); + + assertEquals("a refresh redraws only the water", sampled, scene.samples.get()); + assertEquals(1, controller.progress(frame).ready()); + } + } + + @Test + public void coarseTilesKeepNoWaterState() throws Exception { + Scene scene = new Scene(); + MapTileRenderer.TileRender detailed = settle(scene.renderer.prepareTile(0D, 0D, 4D, VisionRenderController.TILE_PIXELS, + MapLayer.of(TileType.RIVER), false)); + MapTileRenderer.TileRender coarse = settle(scene.renderer.prepareTile(0D, 0D, 8D, VisionRenderController.TILE_PIXELS, + MapLayer.of(TileType.RIVER), false)); + assertTrue(detailed.retainsWater()); + assertTrue(detailed.bytes() > 0L); + assertFalse(coarse.retainsWater()); + assertEquals(0L, coarse.bytes()); + + AtomicLong time = new AtomicLong(); + try (VisionRenderController controller = new VisionRenderController(() -> { }, time::get)) { + VisionRenderController.Frame frame = controller.request(spec(scene.renderer, 8D)); + await(() -> controller.progress(frame).ready() == 1 && controller.progress(frame).activeWorkers() == 0); + MapTile drawn = frame.tiles().getFirst().tile(); + + scene.record(); + time.set(VisionRenderController.FIRST_RETRY_NANOS); + controller.retryProvisional(frame); + await(() -> controller.progress(frame).activeWorkers() == 0); + + assertSame(drawn, frame.tiles().getFirst().tile()); + assertNotEquals(POOL, pixel(frame, 8D)); + } + } + + @Test + public void poolsRecordedAfterARasterLandsStillRefresh() throws Exception { + Scene scene = new Scene(); + AtomicBoolean landed = new AtomicBoolean(); + when(scene.runtime.rasterPreview(anyInt(), anyInt())) + .thenAnswer(invocation -> landed.get() ? ChunkWaterRaster.EMPTY : ChunkWaterRaster.PROVISIONAL); + AtomicLong time = new AtomicLong(); + try (VisionRenderController controller = new VisionRenderController(() -> { }, time::get)) { + VisionRenderController.Frame frame = controller.request(spec(scene.renderer, 2D)); + await(() -> frame.tiles().getFirst().tile() != null && controller.progress(frame).activeWorkers() == 0); + assertTrue(frame.tiles().getFirst().provisional()); + + landed.set(true); + scene.preview.incrementAndGet(); + time.addAndGet(VisionRenderController.FIRST_RETRY_NANOS); + await(() -> { + controller.retryProvisional(frame); + return controller.progress(frame).ready() == 1 && controller.progress(frame).activeWorkers() == 0; + }); + assertNotEquals("the chunk records its pool after its raster lands", POOL, pixel(frame, 2D)); + + scene.record(); + time.addAndGet(VisionRenderController.FIRST_RETRY_NANOS); + await(() -> { + controller.retryProvisional(frame); + return pixel(frame, 2D) == POOL; + }); + } + } + + private static MapTileRenderer.TileRender settle(MapTileRenderer.TileRender work) throws Exception { + await(() -> { + work.render(() -> false); + return work.complete(); + }); + return work; + } + + private static int pixel(VisionRenderController.Frame frame, double blocksPerPixel) { + MapTile tile = frame.tiles().getFirst().tile(); + return tile.image(MapStyle.PLAIN).getRGB((int) (POOL_X / blocksPerPixel), (int) (POOL_Z / blocksPerPixel)) & 0xFFFFFF; + } + + private static VisionRenderController.RenderSpec spec(MapTileRenderer renderer, double blocksPerPixel) { + double centre = VisionRenderController.TILE_PIXELS * blocksPerPixel / 2D; + return new VisionRenderController.RenderSpec(renderer, MapLayer.of(TileType.RIVER), 1L, centre, centre, blocksPerPixel, + VisionRenderController.TILE_PIXELS, VisionRenderController.TILE_PIXELS, false); + } + + private static void await(BooleanSupplier condition) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5L); + while (!condition.getAsBoolean()) { + assertTrue("condition never held", System.nanoTime() < deadline); + Thread.sleep(5L); + } + } + + private static final class Scene { + private final AtomicLong samples = new AtomicLong(); + private final AtomicLong preview = new AtomicLong(); + private final AtomicLong water = new AtomicLong(); + private final AtomicBoolean recorded = new AtomicBoolean(); + private final HydrologyRuntime runtime = mock(HydrologyRuntime.class); + private final MapTileRenderer renderer; + + private Scene() { + when(runtime.enabled()).thenReturn(true); + when(runtime.planPreview(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(HydrologyPlanPreview.EMPTY); + when(runtime.rasterPreview(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.EMPTY); + when(runtime.previewRevision()).thenAnswer(invocation -> preview.get()); + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + when(engine.getComplex()).thenReturn(complex); + when(engine.getHeight()).thenReturn(256); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + IrisBiome biome = new IrisBiome(); + biome.setColor("#738249"); + IrisRegion region = new IrisRegion(); + when(complex.getBaseBiomeStream()).thenReturn(ProceduralStream.of((x, z) -> biome, Interpolated.of(b -> 0D, d -> biome))); + when(complex.getRegionStream()).thenReturn(ProceduralStream.of((x, z) -> { + samples.incrementAndGet(); + return region; + }, Interpolated.of(r -> 0D, d -> region))); + GenerationHistory history = mock(GenerationHistory.class); + GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); + when(router.history()).thenReturn(history); + when(history.riverRevision()).thenAnswer(invocation -> water.get()); + ChunkGenerationSemantics pool = ChunkGenerationSemantics.builder(1, 1, 1L) + .addRiverFeature("water", HydrologyFeatureType.CAVE_POOL, 7L, POOL_X, 12, POOL_Z).build(); + when(history.semantics(anyInt(), anyInt())).thenReturn(Optional.empty()); + when(history.semantics(1, 1)).thenAnswer(invocation -> recorded.get() ? Optional.of(pool) : Optional.empty()); + renderer = new MapTileRenderer(engine); + } + + private void record() { + recorded.set(true); + water.incrementAndGet(); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/map/MapHydrologyTest.java b/core/src/test/java/art/arcane/iris/studio/map/MapHydrologyTest.java index 4b33db467..ace30bbbc 100644 --- a/core/src/test/java/art/arcane/iris/studio/map/MapHydrologyTest.java +++ b/core/src/test/java/art/arcane/iris/studio/map/MapHydrologyTest.java @@ -23,7 +23,7 @@ import art.arcane.volmlib.util.stream.interpolation.Interpolated; import org.junit.Test; import java.awt.Color; -import java.awt.image.BufferedImage; +import java.util.Arrays; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; @@ -39,9 +39,9 @@ public class MapHydrologyTest { Engine engine = engine(water.runtime, biome()); MapTileRenderer renderer = new MapTileRenderer(engine); MapTile tile = settled(renderer, MapLayer.of(TileType.BIOME)); - BufferedImage expected = new IrisRenderer(engine).renderStudio(0, 0, 64, 64, RenderType.BIOME, () -> false); - assertNotEquals(new Color(0x738249).getRGB(), expected.getRGB(16, 16)); - assertEquals(expected.getRGB(16, 16), tile.image(MapStyle.PLAIN).getRGB(16, 16)); + int expected = 0xFF000000 | overlaid(engine, 0x738249)[16 * 64 + 16]; + assertNotEquals(new Color(0x738249).getRGB(), expected); + assertEquals(expected, tile.image(MapStyle.PLAIN).getRGB(16, 16)); MapTile dry = settled(renderer, MapLayer.biomes(PickDisplay.PICKS, false)); assertEquals(new Color(0x738249).getRGB(), dry.image(MapStyle.PLAIN).getRGB(16, 16)); assertNotEquals(MapLayer.biomes(PickDisplay.PICKS, true), MapLayer.biomes(PickDisplay.PICKS, false)); @@ -105,6 +105,21 @@ public class MapHydrologyTest { } } + private static int[] overlaid(Engine engine, int biomeColor) throws Exception { + IrisRenderer.WaterTile water = new IrisRenderer(engine).prepareStudioWater(0D, 0D, 1D, 64); + int[] base = new int[64 * 64]; + Arrays.fill(base, biomeColor); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10L); + while (true) { + int[] colors = water.render(base, true, () -> false); + if (water.complete()) { + return colors; + } + assertTrue("water never settled", System.nanoTime() < deadline); + Thread.sleep(10L); + } + } + private static IrisBiome biome() { IrisBiome biome = new IrisBiome(); biome.setColor("#738249"); diff --git a/core/src/test/java/art/arcane/iris/studio/map/MapTileProgressTest.java b/core/src/test/java/art/arcane/iris/studio/map/MapTileProgressTest.java index 7ee12f31a..6554170c2 100644 --- a/core/src/test/java/art/arcane/iris/studio/map/MapTileProgressTest.java +++ b/core/src/test/java/art/arcane/iris/studio/map/MapTileProgressTest.java @@ -111,7 +111,8 @@ public class MapTileProgressTest { pending.set(false); MapTile complete = progress.render(() -> false); assertTrue(progress.complete()); - assertEquals(0L, progress.bytes()); + assertTrue(progress.retainsWater()); + assertTrue(progress.bytes() > 0L); assertArrayEquals(pixels(first.image(MapStyle.PLAIN)), pixels(complete.image(MapStyle.PLAIN))); } @@ -159,7 +160,8 @@ public class MapTileProgressTest { pending.set(false); MapTile actual = progress.render(() -> false); assertTrue(progress.complete()); - assertEquals(0L, progress.bytes()); + assertTrue(progress.retainsWater()); + assertTrue(progress.bytes() > 0L); BufferedImage colors = actual.image(MapStyle.PLAIN); assertEquals(0xFF738249, colors.getRGB(14, 14)); assertNotEquals(0xFF738249, colors.getRGB(8, 8)); diff --git a/core/src/test/java/art/arcane/iris/studio/render/IrisRendererPerformanceContractTest.java b/core/src/test/java/art/arcane/iris/studio/render/IrisRendererPerformanceContractTest.java index 180d6da02..ceb19adb0 100644 --- a/core/src/test/java/art/arcane/iris/studio/render/IrisRendererPerformanceContractTest.java +++ b/core/src/test/java/art/arcane/iris/studio/render/IrisRendererPerformanceContractTest.java @@ -2,24 +2,16 @@ package art.arcane.iris.studio.render; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.volmlib.util.stream.ProceduralStream; -import art.arcane.volmlib.util.collection.KList; import org.junit.Test; -import java.awt.Color; -import java.awt.image.BufferedImage; import java.util.concurrent.CancellationException; -import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -71,117 +63,19 @@ public class IrisRendererPerformanceContractTest { } @Test - public void studioHeightUsesNaturalTerrainWhileProtocolRenderRemainsExact() { + public void heightRenderSamplesTheExactHeightStream() { Engine engine = mock(Engine.class); IrisComplex complex = mock(IrisComplex.class); @SuppressWarnings("unchecked") - ProceduralStream natural = mock(ProceduralStream.class); - @SuppressWarnings("unchecked") ProceduralStream exact = mock(ProceduralStream.class); when(engine.getComplex()).thenReturn(complex); when(engine.getHeight()).thenReturn(320); - when(complex.getNaturalHeightStream()).thenReturn(natural); when(complex.getHeightStream()).thenReturn(exact); - when(natural.getDouble(0D, 0D)).thenReturn(80D); when(exact.getDouble(0D, 0D)).thenReturn(96D); - IrisRenderer renderer = new IrisRenderer(engine); - renderer.renderStudio(0D, 0D, 1D, 1, RenderType.HEIGHT, () -> false); - - verify(natural).getDouble(0D, 0D); - verifyNoInteractions(exact); - - renderer.render(0D, 0D, 1D, 1, RenderType.HEIGHT); + new IrisRenderer(engine).render(0D, 0D, 1D, 1, RenderType.HEIGHT); verify(exact).getDouble(0D, 0D); - } - - @Test - public void studioBiomeAndContinentAvoidRiverAdjustedEngineLookups() { - Engine engine = mock(Engine.class); - IrisComplex complex = mock(IrisComplex.class); - IrisBiome biome = mock(IrisBiome.class); - @SuppressWarnings("unchecked") - ProceduralStream base = mock(ProceduralStream.class); - when(engine.getComplex()).thenReturn(complex); - when(complex.getBaseBiomeStream()).thenReturn(base); - when(base.get(0D, 0D)).thenReturn(biome); - when(biome.getColor(engine, RenderType.BIOME)).thenReturn(Color.GREEN); - when(biome.getGenerators()).thenReturn(new KList<>()); - IrisRenderer renderer = new IrisRenderer(engine); - - renderer.renderStudio(0D, 0D, 1D, 1, RenderType.BIOME, () -> false); - renderer.renderStudio(0D, 0D, 1D, 1, RenderType.CONTINENT, () -> false); - - verify(base, times(2)).get(0D, 0D); - verify(engine, never()).getBiome(anyInt(), anyInt(), anyInt()); - } - - @Test - public void uniformStudioBiomePagesUseAdaptiveDomainSampling() { - Engine engine = mock(Engine.class); - IrisComplex complex = mock(IrisComplex.class); - IrisBiome biome = mock(IrisBiome.class); - @SuppressWarnings("unchecked") - ProceduralStream base = mock(ProceduralStream.class); - AtomicInteger samples = new AtomicInteger(); - when(engine.getComplex()).thenReturn(complex); - when(complex.getBaseBiomeStream()).thenReturn(base); - when(base.get(org.mockito.ArgumentMatchers.anyDouble(), org.mockito.ArgumentMatchers.anyDouble())) - .thenAnswer(invocation -> { - samples.incrementAndGet(); - return biome; - }); - when(biome.getColor(engine, RenderType.BIOME)).thenReturn(Color.GREEN); - - new IrisRenderer(engine).renderStudio(0D, 0D, 256D, 64, RenderType.BIOME, () -> false); - - assertTrue(samples.get() < 128); - } - - @Test - public void studioBiomeBaseDoesNotEnterHydrologyPlanning() { - Engine engine = mock(Engine.class); - IrisComplex complex = mock(IrisComplex.class); - IrisBiome biome = mock(IrisBiome.class); - @SuppressWarnings("unchecked") - ProceduralStream base = mock(ProceduralStream.class); - when(engine.getComplex()).thenReturn(complex); - when(complex.getBaseBiomeStream()).thenReturn(base); - when(base.get(org.mockito.ArgumentMatchers.anyDouble(), org.mockito.ArgumentMatchers.anyDouble())) - .thenReturn(biome); - when(biome.getColor(engine, RenderType.BIOME)).thenReturn(Color.GREEN); - - BufferedImage image = new IrisRenderer(engine).renderStudioBase( - 0D, 0D, 256D, 64, RenderType.BIOME, () -> false); - - assertEquals(Color.GREEN.getRGB(), image.getRGB(0, 0)); - assertEquals(Color.GREEN.getRGB(), image.getRGB(63, 63)); - verify(complex, never()).getHydrologyRuntime(); - } - - @Test - public void planarStudioHeightPagesInterpolateWithoutPerPixelEngineSampling() { - Engine engine = mock(Engine.class); - IrisComplex complex = mock(IrisComplex.class); - @SuppressWarnings("unchecked") - ProceduralStream natural = mock(ProceduralStream.class); - AtomicInteger samples = new AtomicInteger(); - when(engine.getComplex()).thenReturn(complex); - when(engine.getHeight()).thenReturn(320); - when(complex.getNaturalHeightStream()).thenReturn(natural); - when(natural.getDouble(org.mockito.ArgumentMatchers.anyDouble(), org.mockito.ArgumentMatchers.anyDouble())) - .thenAnswer(invocation -> { - samples.incrementAndGet(); - double x = invocation.getArgument(0); - double z = invocation.getArgument(1); - return 80D + x * 0.05D + z * 0.025D; - }); - - BufferedImage image = new IrisRenderer(engine).renderStudio( - 0D, 0D, 256D, 64, RenderType.HEIGHT, () -> false); - - assertTrue(samples.get() < 256); - assertNotEquals(image.getRGB(0, 0), image.getRGB(63, 63)); + verify(complex, never()).getNaturalHeightStream(); } } diff --git a/core/src/test/java/art/arcane/iris/studio/render/IrisRendererRiverTest.java b/core/src/test/java/art/arcane/iris/studio/render/IrisRendererRiverTest.java index 689d43965..ebd9fbad2 100644 --- a/core/src/test/java/art/arcane/iris/studio/render/IrisRendererRiverTest.java +++ b/core/src/test/java/art/arcane/iris/studio/render/IrisRendererRiverTest.java @@ -1,6 +1,5 @@ package art.arcane.iris.studio.render; -import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.hydrology.engine.HydrologyPlanPreview; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; @@ -18,11 +17,10 @@ import art.arcane.iris.generation.stream.ProvisionalSampling; import art.arcane.iris.generation.hydrology.underground.SeaInlet; import art.arcane.iris.testsupport.FakeHydrology; import art.arcane.iris.testsupport.WaterScene; -import art.arcane.volmlib.util.stream.ProceduralStream; import org.junit.Test; import java.awt.Color; -import java.awt.image.BufferedImage; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -33,7 +31,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; @@ -44,7 +41,8 @@ import static org.mockito.Mockito.when; public class IrisRendererRiverTest { private static final int SEA_LEVEL = 40; - private static final int NO_RIVER = new Color(28, 31, 38).getRGB(); + private static final int NO_RIVER = new Color(28, 31, 38).getRGB() & 0xFFFFFF; + private static final int GREEN = Color.GREEN.getRGB() & 0xFFFFFF; private static final int PIXELS = 64; private static final long SETTLE_SECONDS = 10L; private static final int POND_X = 30; @@ -59,7 +57,7 @@ public class IrisRendererRiverTest { public void everyFeatureTypeHasItsOwnColor() { Set colors = new HashSet<>(); for (HydrologyFeatureType type : HydrologyFeatureType.values()) { - assertTrue(type.name(), colors.add(IrisRenderer.hydrologyFeatureColor(type))); + assertTrue(type.name(), colors.add(water(type))); } assertFalse(colors.contains(NO_RIVER)); } @@ -72,7 +70,8 @@ public class IrisRendererRiverTest { assertEquals("cave pools sit under everything else", HydrologyFeatureType.CAVE_POOL, drawn.getLast()); assertTrue(drawn.containsAll(List.of(HydrologyFeatureType.STREAM, HydrologyFeatureType.RIVER, HydrologyFeatureType.MAJOR_RIVER, HydrologyFeatureType.LAKE, HydrologyFeatureType.POND, HydrologyFeatureType.DAM, HydrologyFeatureType.SEA_INLET))); - assertTrue(drawn.indexOf(HydrologyFeatureType.LAKE) < drawn.indexOf(HydrologyFeatureType.POND)); + assertTrue(drawn.indexOf(HydrologyFeatureType.STREAM) < drawn.indexOf(HydrologyFeatureType.POND)); + assertTrue(drawn.indexOf(HydrologyFeatureType.POND) < drawn.indexOf(HydrologyFeatureType.LAKE)); } @Test @@ -82,16 +81,16 @@ public class IrisRendererRiverTest { hydrology.hold(); long before = ProvisionalSampling.revision(); - BufferedImage provisional = new IrisRenderer(engine).renderStudio(0D, 0D, 64D, 64, RenderType.RIVER, () -> false); + int[] provisional = new IrisRenderer(engine).prepareStudioWater(0D, 0D, 1D, 64).render(null, false, () -> false); assertNotEquals(before, ProvisionalSampling.revision()); - assertEquals(NO_RIVER, provisional.getRGB(16, 16)); + assertEquals(NO_RIVER, at(provisional, 64, 16, 16)); hydrology.release(); - BufferedImage planned = settled(engine, 64D, 64, RenderType.RIVER); + int[] planned = settled(engine, 64D, 64); - assertEquals(IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.POND), planned.getRGB(16, 16)); - assertEquals(NO_RIVER, planned.getRGB(48, 48)); + assertEquals(water(HydrologyFeatureType.POND), at(planned, 64, 16, 16)); + assertEquals(NO_RIVER, at(planned, 64, 48, 48)); } } @@ -105,21 +104,21 @@ public class IrisRendererRiverTest { when(runtime.rasterPreview(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.PROVISIONAL); IrisRenderer renderer = new IrisRenderer(engine(runtime)); - BufferedImage overview = renderer.renderStudio(0D, 0D, 256D, 64, RenderType.RIVER, () -> false); - int water = IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.POND); - assertEquals(water, overview.getRGB(4, 4)); + int[] overview = renderer.prepareStudioWater(0D, 0D, 4D, 64).render(null, false, () -> false); + int water = water(HydrologyFeatureType.POND); + assertEquals(water, at(overview, 64, 4, 4)); for (int step : new int[]{2, 1}) { long before = ProvisionalSampling.revision(); - BufferedImage detailed = renderer.renderStudio(0D, 0D, step * 64D, 64, RenderType.RIVER, () -> false); - assertEquals(water, detailed.getRGB(16 / step, 16 / step)); + int[] detailed = renderer.prepareStudioWater(0D, 0D, step, 64).render(null, false, () -> false); + assertEquals(water, at(detailed, 64, 16 / step, 16 / step)); assertNotEquals(before, ProvisionalSampling.revision()); } when(runtime.rasterPreview(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.EMPTY); long before = ProvisionalSampling.revision(); - BufferedImage settled = renderer.renderStudio(0D, 0D, 64D, 64, RenderType.RIVER, () -> false); - assertEquals(NO_RIVER, settled.getRGB(16, 16)); + int[] settled = renderer.prepareStudioWater(0D, 0D, 1D, 64).render(null, false, () -> false); + assertEquals(NO_RIVER, at(settled, 64, 16, 16)); assertEquals(before, ProvisionalSampling.revision()); } @@ -128,12 +127,10 @@ public class IrisRendererRiverTest { HydrologySettings settings = FakeHydrology.settings(SEA_LEVEL); Reach brook = WaterScene.line(11L, settings.tiers().getFirst(), 2, 40, 29, 40, (x, z) -> 62); try (FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> 60, SEA_LEVEL, List.of(brook), List.of())) { - Engine engine = engine(hydrology.runtime); + int[] colors = settled(engine(hydrology.runtime), 32D, 32D, 32, null); - BufferedImage image = settled(engine, 32D, 32D, 32, RenderType.RIVER); - - assertEquals(IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.STREAM), image.getRGB(16, 8)); - assertEquals(NO_RIVER, image.getRGB(16, 0)); + assertEquals(water(HydrologyFeatureType.STREAM), at(colors, 32, 16, 8)); + assertEquals(NO_RIVER, at(colors, 32, 16, 0)); } } @@ -142,7 +139,7 @@ public class IrisRendererRiverTest { try (FakeHydrology hydrology = scene()) { HydrologyRuntime runtime = spy(hydrology.runtime); - assertScene(settled(engine(runtime), 2D * PIXELS, PIXELS, RenderType.RIVER), 2); + assertScene(settled(engine(runtime), 2D * PIXELS, PIXELS), 2); verify(runtime, atLeastOnce()).rasterPreview(anyInt(), anyInt()); verify(runtime, never()).rasterSnapshot(anyInt(), anyInt()); } @@ -153,7 +150,7 @@ public class IrisRendererRiverTest { try (FakeHydrology hydrology = scene()) { HydrologyRuntime runtime = spy(hydrology.runtime); - assertScene(settled(engine(runtime), 4D * PIXELS, PIXELS, RenderType.RIVER), 4); + assertScene(settled(engine(runtime), 4D * PIXELS, PIXELS), 4); assertNoRasters(runtime); } } @@ -163,7 +160,7 @@ public class IrisRendererRiverTest { try (FakeHydrology hydrology = scene()) { HydrologyRuntime runtime = spy(hydrology.runtime); - assertScene(settled(engine(runtime), 16D * PIXELS, PIXELS, RenderType.RIVER), 16); + assertScene(settled(engine(runtime), 16D * PIXELS, PIXELS), 16); assertNoRasters(runtime); } } @@ -187,41 +184,33 @@ public class IrisRendererRiverTest { try (FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> 90, SEA_LEVEL, List.of(), List.of(), List.of(), List.of(inlet))) { HydrologyRuntime runtime = spy(hydrology.runtime); - BufferedImage plan = settled(engine(runtime), 16D * PIXELS, PIXELS, RenderType.RIVER); - assertEquals(IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.SEA_INLET), plan.getRGB(200 / 16, 200 / 16)); - assertEquals(NO_RIVER, plan.getRGB(200 / 16, 400 / 16)); + int[] plan = settled(engine(runtime), 16D * PIXELS, PIXELS); + assertEquals(water(HydrologyFeatureType.SEA_INLET), at(plan, PIXELS, 200 / 16, 200 / 16)); + assertEquals(NO_RIVER, at(plan, PIXELS, 200 / 16, 400 / 16)); assertNoRasters(runtime); } } @Test - public void standingWaterCoversChannelsInBothDrawModes() throws Exception { + public void standingWaterCoversChannelsInRasters() throws Exception { HydrologySettings settings = FakeHydrology.settings(SEA_LEVEL); Reach through = WaterScene.line(31L, settings.tiers().getFirst(), 4, POND_Z, 60, POND_Z, (x, z) -> 62); Pond pond = WaterScene.pond(32L, 62, POND_X, POND_Z, 10); try (FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> 60, SEA_LEVEL, List.of(through), List.of(pond))) { - Engine engine = engine(hydrology.runtime); + int[] colors = settled(engine(hydrology.runtime), 2D * PIXELS, PIXELS); - for (int step : new int[]{2, 4}) { - BufferedImage image = settled(engine, (double) step * PIXELS, PIXELS, RenderType.RIVER); - - assertEquals("pond over the channel at " + step + " b/px", IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.POND), - image.getRGB(POND_X / step, POND_Z / step)); - assertEquals("channel outside the pond at " + step + " b/px", - IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.STREAM), image.getRGB(8 / step, POND_Z / step)); - } + assertEquals(water(HydrologyFeatureType.POND), at(colors, PIXELS, POND_X / 2, POND_Z / 2)); + assertEquals(water(HydrologyFeatureType.STREAM), at(colors, PIXELS, 4, POND_Z / 2)); } } @Test public void zoomedOutPixelsKeepTheStrongestWaterInTheirFootprint() throws Exception { try (FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> 60, SEA_LEVEL, 63)) { - Engine engine = engine(hydrology.runtime); + int[] colors = settled(engine(hydrology.runtime), 32D, 2); - BufferedImage image = settled(engine, 32D, 2, RenderType.RIVER); - - assertEquals(IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.POND), image.getRGB(0, 0)); - assertEquals(IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.POND), image.getRGB(1, 1)); + assertEquals(water(HydrologyFeatureType.POND), at(colors, 2, 0, 0)); + assertEquals(water(HydrologyFeatureType.POND), at(colors, 2, 1, 1)); } } @@ -240,11 +229,11 @@ public class IrisRendererRiverTest { when(history.semantics(1, 1)).thenReturn(Optional.of(ChunkGenerationSemantics.builder(1, 1, 1L) .addRiverFeature("water", HydrologyFeatureType.CAVE_POOL, 7L, 20, 12, 24).build())); - BufferedImage image = settled(engine, 64D, 32, RenderType.RIVER); + int[] colors = settled(engine, 64D, 32); - assertEquals(IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.CAVE_POOL), image.getRGB(10, 12)); - assertEquals(NO_RIVER, image.getRGB(20, 20)); - assertEquals(NO_RIVER, image.getRGB(10, 13)); + assertEquals(water(HydrologyFeatureType.CAVE_POOL), at(colors, 32, 10, 12)); + assertEquals(NO_RIVER, at(colors, 32, 20, 20)); + assertEquals(NO_RIVER, at(colors, 32, 10, 13)); } } @@ -254,9 +243,9 @@ public class IrisRendererRiverTest { when(runtime.enabled()).thenReturn(true); long before = ProvisionalSampling.revision(); - BufferedImage image = new IrisRenderer(engine(runtime)).renderStudio(0D, 0D, 2048D, 64, RenderType.RIVER, () -> false); + int[] colors = new IrisRenderer(engine(runtime)).prepareStudioWater(0D, 0D, 32D, 64).render(null, false, () -> false); - assertEquals(NO_RIVER, image.getRGB(0, 0)); + assertEquals(NO_RIVER, at(colors, 64, 0, 0)); assertEquals(before, ProvisionalSampling.revision()); verify(runtime, never()).planPreview(anyInt(), anyInt(), anyInt(), anyInt()); assertNoRasters(runtime); @@ -266,54 +255,35 @@ public class IrisRendererRiverTest { public void disabledHydrologyLeavesTheRiverMapEmpty() { long before = ProvisionalSampling.revision(); - BufferedImage image = new IrisRenderer(engine(FakeHydrology.disabled())).renderStudio(0D, 0D, 32D, 32, RenderType.RIVER, - () -> false); + int[] colors = new IrisRenderer(engine(FakeHydrology.disabled())).prepareStudioWater(0D, 0D, 1D, 32) + .render(null, false, () -> false); - assertEquals(NO_RIVER, image.getRGB(16, 16)); + assertEquals(NO_RIVER, at(colors, 32, 16, 16)); assertEquals(before, ProvisionalSampling.revision()); } @Test - public void biomeRefinementCompositesThePlannedWaterOverTheBase() throws Exception { + public void compositeTilesBlendThePlannedWaterOverTheBase() throws Exception { try (FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> 60, SEA_LEVEL, 63)) { - Engine engine = engine(hydrology.runtime); - greenBiomes(engine); - settled(engine, 64D, 64, RenderType.RIVER); - IrisRenderer renderer = new IrisRenderer(engine); - BufferedImage preview = renderer.renderStudioBase(0D, 0D, 64D, 64, RenderType.BIOME, () -> false); + int[] composite = settled(engine(hydrology.runtime), 64D, 64, green(64)); - BufferedImage refined = renderer.refineStudioBiome(0D, 0D, 64D, preview, () -> false); - BufferedImage complete = renderer.renderStudio(0D, 0D, 64D, 64, RenderType.BIOME, () -> false); - - assertEquals(Color.GREEN.getRGB(), preview.getRGB(16, 16)); - assertNotEquals(preview.getRGB(16, 16), refined.getRGB(16, 16)); - assertEquals(Color.GREEN.getRGB(), refined.getRGB(48, 48)); - assertEquals(complete.getRGB(16, 16), refined.getRGB(16, 16)); + assertNotEquals(GREEN, at(composite, 64, 16, 16)); + assertNotEquals(water(HydrologyFeatureType.POND), at(composite, 64, 16, 16)); + assertEquals(GREEN, at(composite, 64, 48, 48)); } } @Test - public void studioBiomeViewShowsWaterAtItsDefaultZoomWithoutRasters() throws Exception { + public void compositeTilesShowWaterAtTheDefaultZoomWithoutRasters() throws Exception { try (FakeHydrology hydrology = scene()) { HydrologyRuntime runtime = spy(hydrology.runtime); - Engine engine = engine(runtime); - greenBiomes(engine); - IrisRenderer renderer = new IrisRenderer(engine); - BufferedImage preview = renderer.renderStudioBase(0D, 0D, 4D * PIXELS, PIXELS, RenderType.BIOME, () -> false); - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SETTLE_SECONDS); - BufferedImage refined; - long revision; - do { - assertTrue("The studio water never settled", System.nanoTime() < deadline); - Thread.sleep(10L); - revision = ProvisionalSampling.revision(); - refined = renderer.refineStudioBiome(0D, 0D, 4D * PIXELS, preview, () -> false); - } while (ProvisionalSampling.revision() != revision); - assertNotEquals(Color.GREEN.getRGB(), refined.getRGB(POND_X / 4, POND_Z / 4)); - assertNotEquals(Color.GREEN.getRGB(), refined.getRGB(LAKE_X / 4, LAKE_Z / 4)); - assertNotEquals(Color.GREEN.getRGB(), refined.getRGB(STREAM_X / 4, STREAM_Z / 4)); - assertEquals(Color.GREEN.getRGB(), refined.getRGB(DRY / 4, DRY / 4)); + int[] composite = settled(engine(runtime), 4D * PIXELS, PIXELS, green(PIXELS)); + + assertNotEquals(GREEN, at(composite, PIXELS, POND_X / 4, POND_Z / 4)); + assertNotEquals(GREEN, at(composite, PIXELS, LAKE_X / 4, LAKE_Z / 4)); + assertNotEquals(GREEN, at(composite, PIXELS, STREAM_X / 4, STREAM_Z / 4)); + assertEquals(GREEN, at(composite, PIXELS, DRY / 4, DRY / 4)); assertNoRasters(runtime); } } @@ -326,11 +296,11 @@ public class IrisRendererRiverTest { return new FakeHydrology(() -> false, (x, z) -> 60, SEA_LEVEL, List.of(brook), List.of(pond), List.of(lake)); } - private static void assertScene(BufferedImage image, int step) { - assertEquals(IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.POND), image.getRGB(POND_X / step, POND_Z / step)); - assertEquals(IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.LAKE), image.getRGB(LAKE_X / step, LAKE_Z / step)); - assertEquals(IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.STREAM), image.getRGB(STREAM_X / step, STREAM_Z / step)); - assertEquals(NO_RIVER, image.getRGB(DRY / step, DRY / step)); + private static void assertScene(int[] colors, int step) { + assertEquals(water(HydrologyFeatureType.POND), at(colors, PIXELS, POND_X / step, POND_Z / step)); + assertEquals(water(HydrologyFeatureType.LAKE), at(colors, PIXELS, LAKE_X / step, LAKE_Z / step)); + assertEquals(water(HydrologyFeatureType.STREAM), at(colors, PIXELS, STREAM_X / step, STREAM_Z / step)); + assertEquals(NO_RIVER, at(colors, PIXELS, DRY / step, DRY / step)); } private static void assertNoRasters(HydrologyRuntime runtime) { @@ -339,28 +309,36 @@ public class IrisRendererRiverTest { verify(runtime, never()).raster(anyInt(), anyInt()); } - private static void greenBiomes(Engine engine) { - IrisBiome biome = mock(IrisBiome.class); - @SuppressWarnings("unchecked") - ProceduralStream base = mock(ProceduralStream.class); - when(engine.getComplex().getBaseBiomeStream()).thenReturn(base); - when(base.get(anyDouble(), anyDouble())).thenReturn(biome); - when(biome.getColor(engine, RenderType.BIOME)).thenReturn(Color.GREEN); + private static int water(HydrologyFeatureType type) { + return IrisRenderer.hydrologyFeatureColor(type) & 0xFFFFFF; } - private static BufferedImage settled(Engine engine, double span, int pixels, RenderType type) throws InterruptedException { - return settled(engine, 0D, span, pixels, type); + private static int at(int[] colors, int pixels, int x, int z) { + return colors[z * pixels + x]; } - private static BufferedImage settled(Engine engine, double startZ, double span, int pixels, RenderType type) - throws InterruptedException { - IrisRenderer renderer = new IrisRenderer(engine); + private static int[] green(int pixels) { + int[] base = new int[pixels * pixels]; + Arrays.fill(base, GREEN); + return base; + } + + private static int[] settled(Engine engine, double span, int pixels) throws InterruptedException { + return settled(engine, 0D, span, pixels, null); + } + + private static int[] settled(Engine engine, double span, int pixels, int[] base) throws InterruptedException { + return settled(engine, 0D, span, pixels, base); + } + + private static int[] settled(Engine engine, double startZ, double span, int pixels, int[] base) throws InterruptedException { + IrisRenderer.WaterTile tile = new IrisRenderer(engine).prepareStudioWater(0D, startZ, span / pixels, pixels); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SETTLE_SECONDS); while (true) { long revision = ProvisionalSampling.revision(); - BufferedImage image = renderer.renderStudio(0D, startZ, span, pixels, type, () -> false); + int[] colors = tile.render(base, base != null, () -> false); if (ProvisionalSampling.revision() == revision) { - return image; + return colors; } assertTrue("The water map never settled", System.nanoTime() < deadline); Thread.sleep(10L); diff --git a/core/src/test/java/art/arcane/iris/studio/render/IrisRendererTest.java b/core/src/test/java/art/arcane/iris/studio/render/IrisRendererTest.java new file mode 100644 index 000000000..e847725ea --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/render/IrisRendererTest.java @@ -0,0 +1,75 @@ +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.runtime.IrisComplex; +import art.arcane.iris.generation.runtime.IrisEngine; +import art.arcane.iris.world.history.ChunkGenerationSemantics; +import art.arcane.iris.world.history.GenerationHistory; +import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter; +import org.junit.Test; + +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class IrisRendererTest { + private static final int PIXELS = 32; + private static final double STEP = 4D; + + @Test + public void cavePoolsRefreshOnRevision() { + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + AtomicLong preview = new AtomicLong(7L); + when(runtime.enabled()).thenReturn(true); + when(runtime.planPreview(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(HydrologyPlanPreview.EMPTY); + when(runtime.previewRevision()).thenAnswer(invocation -> preview.get()); + AtomicBoolean recorded = new AtomicBoolean(); + AtomicLong water = new AtomicLong(3L); + IrisEngine engine = engine(runtime, recorded, water); + IrisRenderer.WaterTile tile = new IrisRenderer(engine).prepareStudioWater(0D, 0D, STEP, PIXELS); + int pool = IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.CAVE_POOL) & 0xFFFFFF; + int index = (24 / (int) STEP) * PIXELS + 20 / (int) STEP; + + int[] before = tile.render(null, false, () -> false); + assertTrue(tile.complete()); + assertNotEquals(pool, before[index]); + + preview.incrementAndGet(); + int[] rasterLanded = tile.render(null, false, () -> false); + assertNotEquals("the chunk's semantics are not recorded yet", pool, rasterLanded[index]); + + recorded.set(true); + int[] unannounced = tile.render(null, false, () -> false); + assertNotEquals("pools refresh only when the recorded water revision moves", pool, unannounced[index]); + + water.incrementAndGet(); + int[] refreshed = tile.render(null, false, () -> false); + assertEquals(pool, refreshed[index]); + } + + private static IrisEngine engine(HydrologyRuntime runtime, AtomicBoolean recorded, AtomicLong water) { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + GenerationHistory history = mock(GenerationHistory.class); + GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); + when(router.history()).thenReturn(history); + when(history.riverRevision()).thenAnswer(invocation -> water.get()); + ChunkGenerationSemantics pool = ChunkGenerationSemantics.builder(1, 1, 1L) + .addRiverFeature("water", HydrologyFeatureType.CAVE_POOL, 7L, 20, 12, 24).build(); + when(history.semantics(anyInt(), anyInt())).thenReturn(Optional.empty()); + when(history.semantics(1, 1)).thenAnswer(invocation -> recorded.get() ? Optional.of(pool) : Optional.empty()); + return engine; + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/render/WaterMapProgressTest.java b/core/src/test/java/art/arcane/iris/studio/render/WaterMapProgressTest.java index dd09b60bd..b7f201a8f 100644 --- a/core/src/test/java/art/arcane/iris/studio/render/WaterMapProgressTest.java +++ b/core/src/test/java/art/arcane/iris/studio/render/WaterMapProgressTest.java @@ -34,7 +34,8 @@ public class WaterMapProgressTest { .thenReturn(new HydrologyPlanPreview(List.of(reach), List.of(), List.of(), List.of(), true)); when(runtime.rasterPreview(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.EMPTY); - WaterMap map = WaterMap.draw(runtime, 32, 0D, 0D, 1D, () -> false); + WaterMap map = new WaterMap(runtime, 32, 0D, 0D, 1D); + map.advance(() -> false); assertFalse(map.provisional()); verifyNoInteractions(reach); @@ -84,7 +85,8 @@ public class WaterMapProgressTest { assertTrue(map.provisional()); map.advance(() -> false); assertFalse(map.provisional()); - WaterMap expected = WaterMap.draw(runtime, 32, -16.5D, -16.5D, 0.5D, () -> false); + WaterMap expected = new WaterMap(runtime, 32, -16.5D, -16.5D, 0.5D); + expected.advance(() -> false); for (int z = 0; z < 32; z++) { for (int x = 0; x < 32; x++) { assertEquals(expected.at(x, z), map.at(x, z)); 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 new file mode 100644 index 000000000..605d0ad04 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/render/WaterMapTest.java @@ -0,0 +1,62 @@ +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.water.HydrologyTier; +import art.arcane.iris.generation.hydrology.water.Pond; +import art.arcane.iris.generation.hydrology.water.Reach; +import art.arcane.iris.testsupport.WaterScene; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class WaterMapTest { + private static final int PIXELS = 32; + private static final double MID_STEP = 4D; + private static final int LEVEL = 62; + private static final int POND_X = 30; + private static final int POND_Z = 30; + + @Test + public void channelsDrawOverPondsAtMidZoom() { + HydrologyTier tier = WaterScene.stream(); + Reach across = WaterScene.line(1L, tier, 4, POND_Z, 60, POND_Z, (x, z) -> LEVEL); + Reach fall = WaterScene.line(2L, tier, POND_X, 10, POND_X, 50, (x, z) -> z < POND_Z ? LEVEL + 8 : LEVEL); + Pond pond = WaterScene.pond(3L, LEVEL, POND_X, POND_Z, 10); + + WaterMap map = draw(List.of(across, fall), List.of(pond), List.of()); + + assertEquals("the fall where both channels cross the pond", HydrologyFeatureType.WATERFALL, map.at(7, 7)); + assertEquals("the channel across the pond", HydrologyFeatureType.STREAM, map.at(6, 7)); + assertEquals("the channel below the fall", HydrologyFeatureType.STREAM, map.at(7, 9)); + assertEquals("open pond water", HydrologyFeatureType.POND, map.at(9, 9)); + } + + @Test + public void pondsDrawOverLakesAtMidZoom() { + Pond pond = WaterScene.pond(4L, LEVEL, POND_X, POND_Z, 10); + Pond lake = WaterScene.pond(5L, LEVEL, 44, POND_Z, 12); + + WaterMap map = draw(List.of(), List.of(pond), List.of(lake)); + + assertEquals("pond and lake share the pixel", HydrologyFeatureType.POND, map.at(9, 7)); + assertEquals("open lake water", HydrologyFeatureType.LAKE, map.at(13, 7)); + } + + private static WaterMap draw(List reaches, List ponds, List lakes) { + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + when(runtime.planPreview(anyInt(), anyInt(), anyInt(), anyInt())) + .thenReturn(new HydrologyPlanPreview(reaches, ponds, lakes, List.of(), true)); + when(runtime.channelType(any(HydrologyTier.class))).thenReturn(HydrologyFeatureType.STREAM); + WaterMap map = new WaterMap(runtime, PIXELS, 0D, 0D, MID_STEP); + map.advance(() -> false); + return map; + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/workspace/IrisRiverSchemaTest.java b/core/src/test/java/art/arcane/iris/studio/workspace/IrisRiverSchemaTest.java index e16f189f6..281e961f3 100644 --- a/core/src/test/java/art/arcane/iris/studio/workspace/IrisRiverSchemaTest.java +++ b/core/src/test/java/art/arcane/iris/studio/workspace/IrisRiverSchemaTest.java @@ -110,6 +110,11 @@ public class IrisRiverSchemaTest { assertEquals(List.of("ALLOW", "BLOCK"), enumValues(definitions, properties.getJSONObject("streams"))); assertEquals(List.of("ALLOW", "BLOCK"), enumValues(definitions, properties.getJSONObject("ponds"))); assertEquals("string", properties.getJSONObject("fluid").getString("type")); + JSONObject wetness = referencedProperties(definitions, properties.getJSONObject("wetness")); + for (String bound : List.of("min", "max")) { + assertEquals(bound, 0D, wetness.getJSONObject(bound).getDouble("minimum"), 0D); + assertEquals(bound, 1D, wetness.getJSONObject(bound).getDouble("maximum"), 0D); + } assertEquals("array", properties.getJSONObject("shoreBiomes").getString("type")); assertEquals("#/definitions/erzbiomes", properties.getJSONObject("shoreBiomes").getJSONObject("items").getString("$ref")); diff --git a/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticCaptureTest.java b/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticCaptureTest.java index 07ce189ad..79fa56a69 100644 --- a/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticCaptureTest.java +++ b/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticCaptureTest.java @@ -115,7 +115,6 @@ public final class GenerationSemanticCaptureTest { return null; }).when(fixture.mantle).iterateChunk(eq(-2), eq(3), eq(MatterCavern.class), any()); HydrologyCaveCell duplicate = mock(HydrologyCaveCell.class); - when(duplicate.floodedBiomeKey()).thenReturn("iris:duplicate"); when(duplicate.fluidProfileKey()).thenReturn("iris:river"); when(duplicate.isWet()).thenReturn(true); doAnswer(invocation -> { @@ -355,10 +354,10 @@ public final class GenerationSemanticCaptureTest { IrisDimension dimension = mock(IrisDimension.class); when(dimension.getMinHeight()).thenReturn(-64); when(fixture.engine.getDimension()).thenReturn(dimension); - HydrologyCaveCell water = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water", ""); - HydrologyCaveCell lava = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "lava", ""); - HydrologyCaveCell guard = HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD); - HydrologyCaveCell inlet = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water", ""); + HydrologyCaveCell water = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water"); + HydrologyCaveCell lava = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "lava"); + HydrologyCaveCell guard = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "water"); + HydrologyCaveCell inlet = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"); TransitionDisplacementField seam = mock(TransitionDisplacementField.class); when(seam.seamWeight(anyInt(), anyInt())).thenReturn(0.5D); when(fixture.complex.getTransitionDisplacement()).thenReturn(seam); @@ -419,7 +418,6 @@ public final class GenerationSemanticCaptureTest { return null; }).when(fixture.mantle).iterateChunk(eq(-2), eq(3), eq(MatterCavern.class), any()); HydrologyCaveCell duplicate = mock(HydrologyCaveCell.class); - when(duplicate.floodedBiomeKey()).thenReturn("iris:duplicate"); when(duplicate.fluidProfileKey()).thenReturn("iris:river"); when(duplicate.isWet()).thenReturn(true); doAnswer(invocation -> { @@ -560,8 +558,8 @@ public final class GenerationSemanticCaptureTest { when(fixture.engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(-64).maxHeight(320).build()); doAnswer(invocation -> { Consumer4 consumer = invocation.getArgument(3); - consumer.accept(1, 4, 2, new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, HydrologyCaveCell.SEA_FLUID, "")); - consumer.accept(1, 5, 2, new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "iris:river", "")); + consumer.accept(1, 4, 2, new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, HydrologyCaveCell.SEA_FLUID)); + consumer.accept(1, 5, 2, new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "iris:river")); return null; }).when(fixture.mantle).iterateChunk(eq(-2), eq(3), eq(HydrologyCaveCell.class), any()); GenerationHistory.GenerationStage stage = mock(GenerationHistory.GenerationStage.class); diff --git a/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticIndexTest.java b/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticIndexTest.java index 9a3b6867e..ed90bc74f 100644 --- a/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticIndexTest.java +++ b/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticIndexTest.java @@ -66,6 +66,30 @@ public final class GenerationSemanticIndexTest { assertEquals(new ChunkGenerationSemantics.BlockPosition(-520, 72, -7), structure.exactPosition().orElseThrow()); } + @Test + public void riverRevisionMovesOnlyWhenRecordedWaterChanges() throws Exception { + Path root = temporaryFolder.newFolder("river-revision").toPath(); + GenerationSemanticIndex index = GenerationSemanticIndex.initialize(root); + long start = index.riverRevision(); + + index.claimAndPersist(ChunkGenerationSemantics.builder(0, 0, 1L).addObject("iris:oak").seal().build()); + assertEquals(start, index.riverRevision()); + + ChunkGenerationSemantics pool = ChunkGenerationSemantics.builder(1, 1, 1L) + .addRiverFeature("water", HydrologyFeatureType.CAVE_POOL, 7L, 20, 12, 24).seal().build(); + index.claimAndPersist(pool); + long claimed = index.riverRevision(); + assertTrue(claimed > start); + assertEquals(Optional.of(pool), index.get(1, 1)); + + index.claimAndPersist(pool); + assertEquals(claimed, index.riverRevision()); + + index.recordAndPersist(ChunkGenerationSemantics.builder(2, 2, 1L) + .addRiverFeature("water", HydrologyFeatureType.STREAM, 9L, 40, 62, 40).build()); + assertTrue(index.riverRevision() > claimed); + } + @Test public void packFilenameKeysSurviveJournalCompactionAndExactQueries() throws Exception { Path root = temporaryFolder.newFolder("pack-filename-keys").toPath(); @@ -568,6 +592,31 @@ public final class GenerationSemanticIndexTest { assertEquals(Set.of("temperate"), semantics.regionKeys()); } + @Test + public void unknownRiverFeatureCodesFailClosed() throws Exception { + Path recordRoot = temporaryFolder.newFolder("unknown-record-river-code").toPath(); + Path recordShard = streamShard(recordRoot); + byte[] record = Files.readAllBytes(recordShard); + record[firstRiverTypeOffset(record)] = (byte) 200; + rewriteChecksum(record); + replaceReferencedShard(recordRoot, recordShard, record); + GenerationSemanticIndex recordIndex = GenerationSemanticIndex.load(recordRoot); + IllegalStateException recordError = assertThrows(IllegalStateException.class, () -> recordIndex.get(0, 0)); + assertTrue(recordError.getCause().getMessage(), + recordError.getCause().getMessage().contains("Unknown HydrologyFeatureType code 200")); + + Path summaryRoot = temporaryFolder.newFolder("unknown-summary-river-code").toPath(); + Path summaryShard = streamShard(summaryRoot); + byte[] summary = Files.readAllBytes(summaryShard); + summary[summaryRiverTypeOffset(summary)] = (byte) 200; + rewriteChecksum(summary); + replaceReferencedShard(summaryRoot, summaryShard, summary); + GenerationSemanticIndex summaryIndex = GenerationSemanticIndex.load(summaryRoot); + IllegalStateException summaryError = assertThrows(IllegalStateException.class, () -> summaryIndex.get(0, 0)); + assertTrue(summaryError.getCause().getMessage(), + summaryError.getCause().getMessage().contains("Unknown HydrologyFeatureType code 200")); + } + @Test public void currentShardKeepsEveryHydrologyFeatureType() throws Exception { Path dimensionRoot = temporaryFolder.newFolder("current-hydrology").toPath(); @@ -879,6 +928,16 @@ public final class GenerationSemanticIndexTest { .build(); } + private static Path streamShard(Path dimensionRoot) throws Exception { + GenerationSemanticIndex index = GenerationSemanticIndex.load(dimensionRoot); + index.recordAndPersist(ChunkGenerationSemantics.builder(0, 0, 1L) + .addRegion("temperate") + .addRiverFeature("water", HydrologyFeatureType.STREAM, 9L, 3, 70, 4) + .seal() + .build()); + return onlyShard(index.storageDirectory()); + } + private static Path onlyShard(Path directory) throws Exception { try (Stream files = Files.list(directory)) { List shards = files.filter(path -> path.getFileName().toString().endsWith(".isem")).toList(); diff --git a/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticQueriesTest.java b/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticQueriesTest.java index d9757ba06..86cdbaeab 100644 --- a/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticQueriesTest.java +++ b/core/src/test/java/art/arcane/iris/world/history/GenerationSemanticQueriesTest.java @@ -8,12 +8,22 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; 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.terrain.IrisDimension; import org.junit.Test; import org.mockito.MockedStatic; +import java.time.Duration; +import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; import java.util.function.Predicate; import static org.junit.Assert.assertEquals; @@ -25,9 +35,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -135,7 +147,7 @@ public final class GenerationSemanticQueriesTest { } @Test - public void rejectsTaperedPredictionsAndMergesTheNearestEligibleRiver() { + public void rejectsTaperedPredictionsAndMergesTheNearestEligibleRiver() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -178,11 +190,10 @@ public final class GenerationSemanticQueriesTest { when(history.semantics(anyInt(), anyInt())).thenReturn(Optional.empty()); when(history.activeActivation()).thenReturn(activation); when(activation.activationId()).thenReturn(2L); - when(runtime.nearestFeature(eq(0), eq(0), eq(HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER)), eq(200), any())) + when(runtime.nearestFeature(eq(0), eq(0), eq(HydrologyFeatureQuery.of(HydrologyFeatureType.RIVER)), eq(100), any(), any())) .thenAnswer(invocation -> firstEligible(List.of(tapered, eligible), invocation.getArgument(4))); - GenerationSemanticQueries.RiverResult active = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.RIVER, 0, 0, 200).orElseThrow(); + GenerationSemanticQueries.RiverResult active = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); assertEquals(GenerationSemanticQueries.RiverSource.ACTIVE_PREDICTION, active.source()); assertEquals(HydrologyFeatureType.RIVER, active.type()); @@ -191,10 +202,9 @@ public final class GenerationSemanticQueriesTest { HydrologyFeatureRef fartherActive = feature(4L, 120, 20, 0); doAnswer(invocation -> firstEligible(List.of(tapered, fartherActive), invocation.getArgument(4))) - .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); + .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); - GenerationSemanticQueries.RiverResult historical = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.RIVER, 0, 0, 200).orElseThrow(); + GenerationSemanticQueries.RiverResult historical = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); assertEquals(GenerationSemanticQueries.RiverSource.RECORDED, historical.source()); assertEquals(100, historical.x()); @@ -202,7 +212,7 @@ public final class GenerationSemanticQueriesTest { } @Test - public void seamWeightIsJudgedPerCandidateInsideOneTransitionChunk() { + public void seamWeightIsJudgedPerCandidateInsideOneTransitionChunk() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -220,29 +230,28 @@ public final class GenerationSemanticQueriesTest { when(displacement.seamWeight(anyInt(), anyInt())).thenAnswer(invocation -> invocation.getArgument(0) < 8 ? 0.4D : 1D); when(dimension.getMinHeight()).thenReturn(-64); - when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())) + when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())) .thenAnswer(invocation -> firstEligible(List.of(tapered, solid), invocation.getArgument(4))); - GenerationSemanticQueries.RiverResult taperedFirst = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.RIVER, 0, 0, 200).orElseThrow(); + GenerationSemanticQueries.RiverResult taperedFirst = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); doAnswer(invocation -> firstEligible(List.of(solid, tapered), invocation.getArgument(4))) - .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); - GenerationSemanticQueries.RiverResult solidFirst = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.RIVER, 0, 0, 200).orElseThrow(); + .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + GenerationSemanticQueries.RiverResult solidFirst = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); doAnswer(invocation -> { Predicate eligible = invocation.getArgument(4); assertTrue(eligible.test(solid)); assertFalse(eligible.test(tapered)); return Optional.empty(); - }).when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); + }).when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); assertEquals(2L, taperedFirst.featureId()); assertEquals(2L, solidFirst.featureId()); - assertTrue(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200).isEmpty()); + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("No river found within 200 blocks."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 200, () -> true)); } @Test - public void returnsRecordedRiverWhenTheActivePackHasNoHydrology() { + public void returnsRecordedRiverWhenTheActivePackHasNoHydrology() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -258,6 +267,7 @@ public final class GenerationSemanticQueriesTest { when(engine.getComplex()).thenReturn(complex); when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.unavailable(any())).thenReturn(Optional.of("hydrology is off")); when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); when(router.history()).thenReturn(history); when(history.findRecordedRiver(any())).thenReturn(Optional.of( @@ -267,16 +277,214 @@ public final class GenerationSemanticQueriesTest { ) )); - GenerationSemanticQueries.RiverResult result = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.WATERFALL, 0, 0, 100).orElseThrow(); + GenerationSemanticQueries.RiverResult result = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.WATERFALL, 0, 0, 100, () -> true)); assertEquals(GenerationSemanticQueries.RiverSource.RECORDED, result.source()); assertEquals(HydrologyFeatureType.WATERFALL, result.type()); assertEquals(9L, result.featureId()); + verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + + when(history.findRecordedRiver(any())).thenReturn(Optional.empty()); + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("No waterfall forms in this dimension: hydrology is off."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.WATERFALL, 0, 0, 100, () -> true)); } @Test - public void cavePoolsAreFoundOnlyInRecordedHistory() { + public void disabledTypeAnswersWithItsReasonWithoutPlanning() throws Exception { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + GenerationHistory history = mock(GenerationHistory.class); + GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + when(runtime.unavailable(HydrologyFeatureType.DAM)).thenReturn(Optional.of("hydrology.ponds.dams is disabled")); + when(runtime.unavailable(HydrologyFeatureType.CAVE_POOL)).thenReturn(Optional.of("hydrology.underground.cavePools is disabled")); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); + when(router.history()).thenReturn(history); + when(history.findRecordedRiver(any())).thenReturn(Optional.empty()); + + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("No dam forms in this dimension: hydrology.ponds.dams is disabled."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.DAM, 0, 0, 100, () -> true)); + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing( + "No cave pool forms in this dimension: hydrology.underground.cavePools is disabled."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100, () -> true)); + + ChunkGenerationSemantics.RiverFeatureOccurrence older = new ChunkGenerationSemantics.RiverFeatureOccurrence( + "water", HydrologyFeatureType.DAM, 5L, new ChunkGenerationSemantics.BlockPosition(30, 64, 0)); + when(history.findRecordedRiver(any())).thenReturn(Optional.of( + new GenerationSemanticIndex.RiverMatch(older, new GenerationSemanticIndex.ChunkReference(1, 0, 1L)))); + GenerationSemanticQueries.RiverResult recorded = found( + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.DAM, 0, 0, 100, () -> true)); + + assertEquals(GenerationSemanticQueries.RiverSource.RECORDED, recorded.source()); + assertEquals(5L, recorded.featureId()); + verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + } + + @Test + public void stoppedSearchReportsTheNearestWaterFoundSoFar() throws Exception { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + IrisDimension dimension = mock(IrisDimension.class); + GenerationHistory history = mock(GenerationHistory.class); + GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class); + GenerationActivation activation = mock(GenerationActivation.class); + when(engine.getComplex()).thenReturn(complex); + when(engine.getDimension()).thenReturn(dimension); + when(dimension.getMinHeight()).thenReturn(-64); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())) + .thenThrow(new HydrologySearchTimeoutException(Duration.ofSeconds(30L), null)); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty()); + + assertEquals(new GenerationSemanticQueries.RiverSearch.Stopped(Optional.empty(), + "Stopped searching for the nearest river after 30 seconds without finding one."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true)); + + ChunkGenerationSemantics.RiverFeatureOccurrence occurrence = new ChunkGenerationSemantics.RiverFeatureOccurrence( + "water", HydrologyFeatureType.RIVER, 8L, new ChunkGenerationSemantics.BlockPosition(60, 70, 0)); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); + when(router.history()).thenReturn(history); + when(history.activeActivation()).thenReturn(activation); + when(activation.activationId()).thenReturn(2L); + when(history.findRecordedRiver(any())).thenReturn(Optional.of( + new GenerationSemanticIndex.RiverMatch(occurrence, new GenerationSemanticIndex.ChunkReference(3, 0, 1L)))); + GenerationSemanticQueries.RiverSearch.Stopped recorded = stopped( + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true)); + + assertEquals(8L, recorded.nearestSoFar().orElseThrow().featureId()); + assertEquals("Stopped searching for the nearest river after 30 seconds. The nearest river found so far is at 60, 70, 0; " + + "a nearer one may exist.", recorded.message()); + + doThrow(new HydrologySearchTimeoutException(Duration.ofSeconds(30L), feature(4L, 20, 20, 0))) + .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + GenerationSemanticQueries.RiverSearch.Stopped planned = stopped( + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 100, () -> true)); + + GenerationSemanticQueries.RiverResult nearer = planned.nearestSoFar().orElseThrow(); + assertEquals(GenerationSemanticQueries.RiverSource.ACTIVE_PREDICTION, nearer.source()); + assertEquals(4L, nearer.featureId()); + assertEquals(-44, nearer.y()); + assertTrue(planned.message(), planned.message().contains("at 20, -44, 0;")); + } + + @Test + public void recordedWaterBoundsThePlannedSearchSoExploredAreasFinishEarly() throws Exception { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + IrisDimension dimension = mock(IrisDimension.class); + GenerationHistory history = mock(GenerationHistory.class); + GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class); + GenerationActivation activation = mock(GenerationActivation.class); + ChunkGenerationSemantics.RiverFeatureOccurrence occurrence = new ChunkGenerationSemantics.RiverFeatureOccurrence( + "water", HydrologyFeatureType.RIVER, 7L, new ChunkGenerationSemantics.BlockPosition(30, 70, 40)); + when(engine.getComplex()).thenReturn(complex); + when(engine.getDimension()).thenReturn(dimension); + when(dimension.getMinHeight()).thenReturn(-64); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); + when(router.history()).thenReturn(history); + when(history.activeActivation()).thenReturn(activation); + when(activation.activationId()).thenReturn(2L); + when(history.findRecordedRiver(any())).thenReturn(Optional.of( + new GenerationSemanticIndex.RiverMatch(occurrence, new GenerationSemanticIndex.ChunkReference(1, 2, 1L)))); + when(runtime.nearestFeature(eq(0), eq(0), any(), eq(7168), any(), any())) + .thenThrow(new HydrologySearchTimeoutException(Duration.ofSeconds(30L), null)); + when(runtime.nearestFeature(eq(0), eq(0), any(), eq(50), any(), any())).thenReturn(Optional.empty()); + + GenerationSemanticQueries.RiverResult recorded = found( + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 7168, () -> true)); + + assertEquals(GenerationSemanticQueries.RiverSource.RECORDED, recorded.source()); + assertEquals(7L, recorded.featureId()); + + when(runtime.nearestFeature(eq(0), eq(0), any(), eq(50), any(), any())).thenReturn(Optional.of(feature(6L, 20, 100, 30))); + GenerationSemanticQueries.RiverResult planned = found( + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.RIVER, 0, 0, 7168, () -> true)); + + assertEquals(GenerationSemanticQueries.RiverSource.ACTIVE_PREDICTION, planned.source()); + assertEquals(6L, planned.featureId()); + } + + @Test + public void aNewSearchCancelsThePlayersPreviousSearch() throws Exception { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + when(engine.getComplex()).thenReturn(complex); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty()); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenReturn(Optional.empty()); + List queued = new ArrayList<>(); + UUID player = UUID.randomUUID(); + UUID other = UUID.randomUUID(); + GenerationSemanticQueries.RiverSearch missing = new GenerationSemanticQueries.RiverSearch.Missing( + "No river found within " + GenerationSemanticQueries.RIVER_SEARCH_DISTANCE + " blocks."); + + CompletableFuture first = GenerationSemanticQueries.startRiverSearch( + player, queued::add, engine, HydrologyFeatureType.RIVER, 0, 0); + CompletableFuture elsewhere = GenerationSemanticQueries.startRiverSearch( + other, queued::add, engine, HydrologyFeatureType.RIVER, 0, 0); + CompletableFuture second = GenerationSemanticQueries.startRiverSearch( + player, queued::add, engine, HydrologyFeatureType.RIVER, 0, 0); + + assertTrue(first.isCancelled()); + assertFalse(elsewhere.isDone()); + for (Runnable search : queued) { + search.run(); + } + assertEquals(missing, second.join()); + assertEquals(missing, elsewhere.join()); + verify(runtime, times(2)).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + } + + @Test + public void supersededSearchStopsAndOtherCancellationsAreFailures() throws Exception { + IrisEngine engine = mock(IrisEngine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + when(engine.getComplex()).thenReturn(complex); + when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty()); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + UUID player = UUID.randomUUID(); + AtomicReference> replacement = new AtomicReference<>(); + AtomicBoolean stillRunning = new AtomicBoolean(true); + doAnswer(invocation -> { + BooleanSupplier running = invocation.getArgument(5); + assertTrue(running.getAsBoolean()); + replacement.set(GenerationSemanticQueries.startRiverSearch(player, ignored -> { + }, engine, HydrologyFeatureType.RIVER, 0, 0)); + stillRunning.set(running.getAsBoolean()); + throw new CancellationException("The hydrology feature search was cancelled."); + }).when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + + CompletableFuture superseded = GenerationSemanticQueries.startRiverSearch( + player, Runnable::run, engine, HydrologyFeatureType.RIVER, 0, 0); + + assertFalse(stillRunning.get()); + assertTrue(superseded.isCancelled()); + replacement.get().cancel(false); + + doThrow(new CancellationException("Hydrology plan cache is closed.")) + .when(runtime).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); + CompletableFuture closed = GenerationSemanticQueries.startRiverSearch( + player, Runnable::run, engine, HydrologyFeatureType.RIVER, 0, 0); + + assertFalse(closed.isCancelled()); + ExecutionException failure = assertThrows(ExecutionException.class, closed::get); + assertTrue(String.valueOf(failure.getCause()), failure.getCause() instanceof IllegalStateException); + assertEquals("Hydrology plan cache is closed.", failure.getCause().getMessage()); + } + + @Test + public void cavePoolsAreFoundOnlyInRecordedHistory() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -292,21 +500,19 @@ public final class GenerationSemanticQueriesTest { when(history.findRecordedRiver(any())).thenReturn(Optional.of( new GenerationSemanticIndex.RiverMatch(occurrence, new GenerationSemanticIndex.ChunkReference(2, 0, 1L)))); - GenerationSemanticQueries.RiverResult found = GenerationSemanticQueries.nearestRiver( - engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100).orElseThrow(); + GenerationSemanticQueries.RiverResult found = found(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100, () -> true)); assertEquals(GenerationSemanticQueries.RiverSource.RECORDED, found.source()); assertEquals(40, found.x()); assertEquals(-20, found.y()); - verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); + verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); when(history.findRecordedRiver(any())).thenReturn(Optional.empty()); - assertTrue(GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100).isEmpty()); - verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()); - assertTrue(GenerationSemanticQueries.riverNotFoundMessage(HydrologyFeatureType.CAVE_POOL, 100) - .startsWith("No cave pool found in generated chunks within 100 blocks.")); + assertEquals(new GenerationSemanticQueries.RiverSearch.Missing("No cave pool found in generated chunks within 100 blocks. Cave pools " + + "form in carved caves, so only chunks that have already generated can hold one."), + GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.CAVE_POOL, 0, 0, 100, () -> true)); + verify(runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()); assertTrue(GenerationSemanticQueries.riverSearchMessage(HydrologyFeatureType.CAVE_POOL, 100).contains("generated chunks")); - assertEquals("No river found within 100 blocks.", GenerationSemanticQueries.riverNotFoundMessage(HydrologyFeatureType.RIVER, 100)); } @Test @@ -328,7 +534,7 @@ public final class GenerationSemanticQueriesTest { } @Test - public void plannerFailureEscapesInsteadOfReportingNothingFound() { + public void plannerFailureEscapesInsteadOfReportingNothingFound() throws Exception { IrisEngine engine = mock(IrisEngine.class); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -337,10 +543,10 @@ public final class GenerationSemanticQueriesTest { when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.empty()); when(complex.getHydrologyRuntime()).thenReturn(runtime); when(runtime.enabled()).thenReturn(true); - when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())).thenThrow(failure); + when(runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenThrow(failure); IllegalStateException thrown = assertThrows(IllegalStateException.class, - () -> GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.LAKE, 0, 0, 100)); + () -> GenerationSemanticQueries.nearestRiver(engine, HydrologyFeatureType.LAKE, 0, 0, 100, () -> true)); assertSame(failure, thrown); } @@ -357,6 +563,20 @@ public final class GenerationSemanticQueriesTest { return Optional.empty(); } + private static GenerationSemanticQueries.RiverResult found(GenerationSemanticQueries.RiverSearch search) { + if (search instanceof GenerationSemanticQueries.RiverSearch.Found found) { + return found.feature(); + } + throw new AssertionError("Expected a river, the search said: " + search); + } + + private static GenerationSemanticQueries.RiverSearch.Stopped stopped(GenerationSemanticQueries.RiverSearch search) { + if (search instanceof GenerationSemanticQueries.RiverSearch.Stopped stopped) { + return stopped; + } + throw new AssertionError("Expected a stopped search, the search said: " + search); + } + private static HydrologyFeatureRef feature(long id, int x, int y, int z) { return new HydrologyFeatureRef(id, HydrologyFeatureType.RIVER, x, y, z); } diff --git a/core/src/test/java/art/arcane/iris/world/history/TransitionGenerationPlanTest.java b/core/src/test/java/art/arcane/iris/world/history/TransitionGenerationPlanTest.java index 6bd8f1b99..75952e1d4 100644 --- a/core/src/test/java/art/arcane/iris/world/history/TransitionGenerationPlanTest.java +++ b/core/src/test/java/art/arcane/iris/world/history/TransitionGenerationPlanTest.java @@ -89,7 +89,6 @@ public class TransitionGenerationPlanTest { assertEquals(0D, plan.newEpochWeightAt(15, 8), 0D); assertEquals(1D, plan.newEpochWeightAt(16, 8), 0D); - assertEquals(1D, plan.hydrologyWeightAt(16, 8), 0D); assertFalse(plan.terrainSampleAt(16, 8).hasHistoricalSignature()); assertFalse(plan.hasTransitionAtChunk(1, 0)); assertEquals(BoundaryGeometryInfluence.none(), plan.geometryAt(16, 8)); @@ -123,7 +122,7 @@ public class TransitionGenerationPlanTest { } @Test - public void samplesTerrainAndHydrologyWithinTheSameFiniteWidth() throws Exception { + public void samplesTerrainWithinTheFiniteWidth() throws Exception { GenerationBoundary boundary = GenerationBoundary.freeze("terrain", List.of( new GenerationBoundary.ChunkCoordinate(0, 0) )); @@ -138,14 +137,12 @@ public class TransitionGenerationPlanTest { assertNotNull(edge.nearestSignature()); assertEquals(1D, edge.distanceToHistoricalTerrain(), 0D); assertEquals(64D, edge.historicalSurfaceHeight(), 0D); - assertEquals(edge.newEpochWeight(), edge.hydrologyWeight(), 0D); assertTrue(edge.newEpochWeight() > 0D); assertTrue(edge.newEpochWeight() < 0.001D); assertEquals(1D, plan.newEpochWeightAt(47, 8), 0D); - assertEquals(1D, plan.hydrologyWeightAt(47, 8), 0D); - assertEquals(1D, plan.hydrologyWeightAt(63, 8), 0D); - assertEquals(1D, plan.hydrologyWeightAt(79, 8), 0D); + assertEquals(1D, plan.newEpochWeightAt(63, 8), 0D); + assertEquals(1D, plan.newEpochWeightAt(79, 8), 0D); assertTrue(plan.allowsNewFootprint(31, 8, 48, 8)); assertTrue(plan.allowsNewFootprint(47, 8, 63, 8)); } @@ -247,7 +244,6 @@ public class TransitionGenerationPlanTest { TransitionGenerationPlan.TerrainSample sample = plan.terrainSampleAt(-120, 240); assertFalse(sample.hasHistoricalSignature()); assertEquals(1D, sample.newEpochWeight(), 0D); - assertEquals(1D, sample.hydrologyWeight(), 0D); assertTrue(plan.allowsNewDiscreteContentAt(-120, 240)); } diff --git a/core/src/test/java/art/arcane/iris/world/pregen/MedievalPregenMethodTest.java b/core/src/test/java/art/arcane/iris/world/pregen/MedievalPregenMethodTest.java new file mode 100644 index 000000000..a09e51955 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/world/pregen/MedievalPregenMethodTest.java @@ -0,0 +1,92 @@ +package art.arcane.iris.world.pregen; + +import art.arcane.iris.configuration.IrisSettings; +import art.arcane.iris.generation.hydrology.engine.HydrologyPregeneration; +import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.platform.generation.PlatformChunkGenerator; +import art.arcane.iris.world.task.J; +import org.bukkit.World; +import org.bukkit.generator.ChunkGenerator; +import org.junit.Test; +import org.mockito.MockedStatic; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +public class MedievalPregenMethodTest { + private static final int CONCURRENT_PREPARES = 4; + + @Test + public void hydrologyPrefetchStartsOnceTheEngineExists() throws Exception { + World world = mock(World.class); + when(world.getName()).thenReturn("world"); + ChunkGenerator generator = mock(ChunkGenerator.class, withSettings().extraInterfaces(PlatformChunkGenerator.class)); + PlatformChunkGenerator platform = (PlatformChunkGenerator) generator; + when(world.getGenerator()).thenReturn(generator); + Engine engine = mock(Engine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + HydrologyPregeneration epoch = mock(HydrologyPregeneration.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.openPregeneration()).thenReturn(epoch); + when(platform.getEngine()).thenReturn(null, engine, null); + List early = List.of(new long[]{0L, 0L}); + List ready = List.of(new long[]{1L, 0L}); + IrisSettings previous = IrisSettings.settings; + IrisSettings.settings = new IrisSettings(); + ExecutorService announcers = Executors.newFixedThreadPool(CONCURRENT_PREPARES); + try (MockedStatic scheduling = mockStatic(J.class)) { + scheduling.when(J::isFolia).thenReturn(true); + MedievalPregenMethod method = new MedievalPregenMethod(world); + method.onRegionBounds(-1, -1, 3, 1); + method.onRegionsAhead(early); + verifyNoInteractions(runtime); + + CountDownLatch start = new CountDownLatch(1); + List> prepares = new ArrayList<>(); + for (int i = 0; i < CONCURRENT_PREPARES; i++) { + prepares.add(announcers.submit(() -> { + assertTrue(start.await(5L, TimeUnit.SECONDS)); + method.onRegionsAhead(ready); + return null; + })); + } + start.countDown(); + for (Future prepare : prepares) { + prepare.get(5L, TimeUnit.SECONDS); + } + + verify(runtime, times(1)).openPregeneration(); + verify(epoch, times(1)).bound(-1, -1, 3, 1); + verify(epoch, times(CONCURRENT_PREPARES)).prepare(ready); + verify(epoch, times(CONCURRENT_PREPARES)).prepare(anyList()); + verify(epoch, never()).close(); + + method.close(); + verify(epoch).close(); + } finally { + IrisSettings.settings = previous; + announcers.shutdownNow(); + assertTrue(announcers.awaitTermination(5L, TimeUnit.SECONDS)); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/world/storage/matter/HydrologyCaveMatterTest.java b/core/src/test/java/art/arcane/iris/world/storage/matter/HydrologyCaveMatterTest.java index 068fbc04d..962d44a65 100644 --- a/core/src/test/java/art/arcane/iris/world/storage/matter/HydrologyCaveMatterTest.java +++ b/core/src/test/java/art/arcane/iris/world/storage/matter/HydrologyCaveMatterTest.java @@ -12,15 +12,18 @@ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; public class HydrologyCaveMatterTest { - private static final String SAVED_CAVE_CELLS = "000000020000000200000002010000000001a16ef850cf00010000007400376172742e617263616e652e697269732e656e67696e652e687964726f6c6f67792e636176652e487964726f6c6f67794361766543656c6c08040100057269766572000c697269733a666c6f6f6465640200057269766572000003000764656661756c7400000400046c61766100009180b004"; + private static final String SAVED_CAVE_CELLS = "000000020000000200000002010000000001a16ef850cf00010000007200376172742e617263616e652e697269732e656e67696e652e687964726f6c6f67792e636176652e487964726f6c6f67794361766543656c6c08040100057269766572000c697269733a666c6f6f64656402000572697665720000030005776174657200000400046c61766100009180b004"; @Test public void caveCellsSavedByEarlierWorldsStillLoad() throws IOException { @@ -28,23 +31,20 @@ public class HydrologyCaveMatterTest { Matter matter = Matter.read(new ByteArrayInputStream(HexFormat.of().parseHex(SAVED_CAVE_CELLS))); MatterSlice cells = matter.getSlice(HydrologyCaveCell.class); - assertEquals(new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "river", "iris:flooded"), cells.get(0, 0, 0)); - assertEquals(new HydrologyCaveCell(HydrologyCaveAction.FALLING_FLUID, "river", ""), cells.get(1, 0, 0)); - assertEquals(HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR), cells.get(0, 1, 1)); - assertEquals(HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD, "lava"), cells.get(1, 1, 1)); + assertEquals(new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "river"), cells.get(0, 0, 0)); + assertEquals("a saved falling-fluid cell loads as a wet source", + new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "river"), cells.get(1, 0, 0)); + assertEquals(new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), cells.get(0, 1, 1)); + assertEquals(new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, "lava"), cells.get(1, 1, 1)); assertNull(cells.get(1, 1, 0)); } @Test - public void everyActionAndBiomeRoundTrips() throws IOException { + public void everyActionAndProfileRoundTrips() throws IOException { HydrologyCaveMatter matter = new HydrologyCaveMatter(); for (HydrologyCaveAction action : HydrologyCaveAction.values()) { - for (String profileKey : List.of("default", "underworld", "deep_lava")) { - HydrologyCaveCell expected = new HydrologyCaveCell( - action, - profileKey, - "iris:flooded_grotto" - ); + for (String profileKey : List.of("water", "underworld", "deep_lava")) { + HydrologyCaveCell expected = new HydrologyCaveCell(action, profileKey); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); matter.writeNode(expected, new DataOutputStream(bytes)); @@ -57,44 +57,43 @@ public class HydrologyCaveMatterTest { } @Test - public void savedActionCodesOnlyEverGrowByAppending() throws IOException { + public void savedActionCodesStayFixedWithTheFallingFluidCodeReserved() throws IOException { HydrologyCaveMatter matter = new HydrologyCaveMatter(); - List order = List.of(HydrologyCaveAction.WET_SOURCE, HydrologyCaveAction.FALLING_FLUID, - HydrologyCaveAction.DRY_AIR, HydrologyCaveAction.SEAL_GUARD, HydrologyCaveAction.POOL_SOURCE); - assertEquals(order, List.of(HydrologyCaveAction.values())); - for (int index = 0; index < order.size(); index++) { + Map codes = new LinkedHashMap<>(); + codes.put(HydrologyCaveAction.WET_SOURCE, 1); + codes.put(HydrologyCaveAction.DRY_AIR, 3); + codes.put(HydrologyCaveAction.SEAL_GUARD, 4); + codes.put(HydrologyCaveAction.POOL_SOURCE, 5); + assertEquals(List.copyOf(codes.keySet()), List.of(HydrologyCaveAction.values())); + for (Map.Entry entry : codes.entrySet()) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - matter.writeNode(HydrologyCaveCell.of(order.get(index)), new DataOutputStream(bytes)); - assertEquals(index + 1, bytes.toByteArray()[0]); + matter.writeNode(new HydrologyCaveCell(entry.getKey(), "water"), new DataOutputStream(bytes)); + assertEquals((int) entry.getValue(), bytes.toByteArray()[0]); } - HydrologyCaveCell pool = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water", ""); + assertEquals(new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "river"), + matter.readNode(new DataInputStream(new ByteArrayInputStream(new byte[]{2, 0, 5, 'r', 'i', 'v', 'e', 'r', 0, 0})))); + HydrologyCaveCell pool = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water"); assertTrue(pool.isWet()); assertTrue(pool.carves()); assertTrue(pool.asCavern().isWater()); } @Test - public void emptyBiomeAndInvalidActionRemainUnambiguous() throws IOException { + public void retiredBiomeSlotAndInvalidActionRemainUnambiguous() throws IOException { HydrologyCaveMatter matter = new HydrologyCaveMatter(); - HydrologyCaveCell expected = HydrologyCaveCell.of(HydrologyCaveAction.DRY_AIR); + HydrologyCaveCell expected = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); matter.writeNode(expected, new DataOutputStream(bytes)); + assertArrayEquals(new byte[]{3, 0, 5, 'w', 'a', 't', 'e', 'r', 0, 0}, bytes.toByteArray()); assertEquals(expected, matter.readNode( new DataInputStream(new ByteArrayInputStream(bytes.toByteArray())))); + assertEquals("a biome key saved by earlier worlds is skipped", expected, matter.readNode(new DataInputStream( + new ByteArrayInputStream(new byte[]{3, 0, 5, 'w', 'a', 't', 'e', 'r', 0, 4, 'i', 'r', 'i', 's'})))); assertThrows(IOException.class, () -> matter.readNode( new DataInputStream(new ByteArrayInputStream(new byte[]{99})))); - assertThrows(IllegalArgumentException.class, () -> new HydrologyCaveCell( - HydrologyCaveAction.WET_SOURCE, - " ", - "iris:flooded_grotto" - )); - } - - @Test - public void everyPlannedCellProtectsItsAcceptedVolume() { - for (HydrologyCaveAction action : HydrologyCaveAction.values()) { - assertTrue(HydrologyCaveCell.of(action).protectsPlacement()); - } + assertThrows(IOException.class, () -> matter.readNode( + new DataInputStream(new ByteArrayInputStream(new byte[]{0, 0, 5, 'w', 'a', 't', 'e', 'r', 0, 0})))); + assertThrows(IllegalArgumentException.class, () -> new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, " ")); } } diff --git a/core/src/test/java/art/arcane/iris/world/storage/matter/IrisMatterPersistenceTest.java b/core/src/test/java/art/arcane/iris/world/storage/matter/IrisMatterPersistenceTest.java index c3535a3b6..c488e3beb 100644 --- a/core/src/test/java/art/arcane/iris/world/storage/matter/IrisMatterPersistenceTest.java +++ b/core/src/test/java/art/arcane/iris/world/storage/matter/IrisMatterPersistenceTest.java @@ -59,8 +59,7 @@ public class IrisMatterPersistenceTest { spawner.setLoadKey("test-spawner"); KMap tileProperties = new KMap<>(); tileProperties.put("CustomName", "stored chest"); - HydrologyCaveCell hydrology = new HydrologyCaveCell( - HydrologyCaveAction.WET_SOURCE, "river", "iris:flooded"); + HydrologyCaveCell hydrology = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "river"); NativeStructureOwnershipRecord ownership = new NativeStructureOwnershipRecord( NativeStructureOwnershipRecord.CURRENT_SCHEMA, "minecraft:village_plains", 0, 0, 42L, 64, 0, 64, 0, 15, 80, 15, 70, diff --git a/core/src/test/java/art/arcane/iris/world/storage/matter/PreObjectMatterTest.java b/core/src/test/java/art/arcane/iris/world/storage/matter/PreObjectMatterTest.java index c7608b00b..9cc4be192 100644 --- a/core/src/test/java/art/arcane/iris/world/storage/matter/PreObjectMatterTest.java +++ b/core/src/test/java/art/arcane/iris/world/storage/matter/PreObjectMatterTest.java @@ -66,7 +66,7 @@ public class PreObjectMatterTest { PreObjectMatterCell expected = PreObjectMatterCell.block(null) .captureString("object-owner") .captureCavern(cavern) - .captureHydrology(new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "river", "flooded")); + .captureHydrology(new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "river")); Matter matter = new IrisMatter(16, 16, 16); matter.slice(PreObjectMatterCell.class).set(2, 3, 4, expected); diff --git a/probe/src/main/java/art/arcane/iris/probe/CavePoolProbe.java b/probe/src/main/java/art/arcane/iris/probe/CavePoolProbe.java index eaa3e6ff5..1f825a46d 100644 --- a/probe/src/main/java/art/arcane/iris/probe/CavePoolProbe.java +++ b/probe/src/main/java/art/arcane/iris/probe/CavePoolProbe.java @@ -76,7 +76,23 @@ public final class CavePoolProbe { Map chunkSpans, int airLeaks, int openLeaks, int skyLeaks, int foreignFluid, int waterloggableWalls, int unsupportedGravity, int fluidAbove, int gravityCeilings, Map replaced, List examples) { long failures() { - return (long) airLeaks + openLeaks + skyLeaks + foreignFluid + waterloggableWalls + unsupportedGravity + fluidAbove + gravityCeilings; + long replacedCells = 0L; + for (int cells : replaced.values()) { + replacedCells += cells; + } + return (long) airLeaks + openLeaks + skyLeaks + foreignFluid + waterloggableWalls + unsupportedGravity + fluidAbove + gravityCeilings + + replacedCells; + } + } + + record Gate(Counts counts, int orderMismatches) { + long failures() { + return counts.failures() + orderMismatches; + } + + String line() { + return String.format(Locale.ROOT, "CAVE_POOL_GATE status=%s failures=%d containment_failures=%d order_mismatches=%d", + failures() == 0L ? "PASS" : "FAIL", failures(), counts.failures(), orderMismatches); } } @@ -85,14 +101,14 @@ public final class CavePoolProbe { } public static void main(String[] arguments) { + int exitCode = 1; try { - scan(Configuration.parse(arguments)); - System.exit(0); + exitCode = scan(Configuration.parse(arguments)).failures() == 0L ? 0 : 1; } catch (Throwable failure) { System.out.println(LOG_PREFIX + " FAIL"); failure.printStackTrace(System.out); - System.exit(1); } + System.exit(exitCode); } private static RealPackProbeSupport.Workspace workspace(Configuration configuration) throws Exception { @@ -100,7 +116,7 @@ public final class CavePoolProbe { LOG_PREFIX, null, configuration.work())); } - private static void scan(Configuration configuration) throws Exception { + private static Gate scan(Configuration configuration) throws Exception { try (RealPackProbeSupport.Workspace workspace = workspace(configuration)) { Survey forward; try (RealPackProbeSupport.EngineSession session = workspace.openEngine(configuration.seed(), false, "forward")) { @@ -109,7 +125,8 @@ public final class CavePoolProbe { forward = survey(engine, configuration.area(), null); requireQuiet(engine, "forward"); } - report(count(forward, configuration.area())); + Counts counts = count(forward, configuration.area()); + report(counts); Map shuffled; try (RealPackProbeSupport.EngineSession session = workspace.openEngine(configuration.seed(), false, "shuffled")) { Engine engine = session.engine(); @@ -117,7 +134,9 @@ public final class CavePoolProbe { shuffled = hashes(engine, configuration); requireQuiet(engine, "shuffled"); } - compare(forward.hashes(), shuffled); + Gate gate = new Gate(counts, compare(forward.hashes(), shuffled)); + System.out.println(gate.line()); + return gate; } } @@ -238,7 +257,8 @@ public final class CavePoolProbe { } pool.add(new Cell(pack((chunkX << 4) + x, y, (chunkZ << 4) + z), cell.fluidProfileKey())); NativeBlockState state = blocks.get(x, y, z); - if (!source(state, cell.fluidProfileKey())) { + NativeBlockState expected = engine.getComplex().resolveCaveCellFluid(cell.fluidProfileKey(), (chunkX << 4) + x, (chunkZ << 4) + z); + if (!source(state, expected)) { replaced.merge(cell.fluidProfileKey() + "->" + (state == null ? "null" : state.key()), 1, Integer::sum); } }); @@ -248,14 +268,13 @@ public final class CavePoolProbe { return guards[0]; } - private static boolean source(NativeBlockState state, String fluid) { + static boolean source(NativeBlockState state, NativeBlockState expected) { if (state == null || !state.isFluid()) { return false; } String level = IrisProceduralBlocks.propertyValue(state, "level"); boolean still = level == null || "0".equals(level); - boolean matches = "lava".equals(fluid) ? state.key().startsWith("minecraft:lava") : state.isWater(); - return still && matches; + return still && IrisProceduralBlocks.materialKey(state).equals(IrisProceduralBlocks.materialKey(expected)); } private static ChunkRecord record(Hunk blocks, int height) { @@ -338,7 +357,7 @@ public final class CavePoolProbe { } } - private static void compare(Map forward, Map shuffled) { + static int compare(Map forward, Map shuffled) { int mismatches = 0; List examples = new ArrayList<>(); for (Map.Entry entry : forward.entrySet()) { @@ -355,6 +374,7 @@ public final class CavePoolProbe { } System.out.printf(Locale.ROOT, "CAVE_POOL_ORDER chunks=%d mismatches=%d signature=%016x examples=%s%n", forward.size(), mismatches, signature, examples); + return mismatches; } static Counts count(Survey survey, Area area) { diff --git a/probe/src/main/java/art/arcane/iris/probe/HydrologyReport.java b/probe/src/main/java/art/arcane/iris/probe/HydrologyReport.java index df62bb87d..37a4bb4d0 100644 --- a/probe/src/main/java/art/arcane/iris/probe/HydrologyReport.java +++ b/probe/src/main/java/art/arcane/iris/probe/HydrologyReport.java @@ -43,7 +43,7 @@ final class HydrologyReport { boolean passes() { return maxDependencyDepth() == 0 && sum(WindowMetrics::containmentLeaks) == 0 && sum(WindowMetrics::risingWaterSegments) == 0 && sum(WindowMetrics::seamMismatches) == 0 && sum(WindowMetrics::tickConversionCells) == 0 - && sum(WindowMetrics::missingSurface) == 0 + && sum(WindowMetrics::missingSurface) == 0 && sum(WindowMetrics::bermOverCap) == 0 && sum(WindowMetrics::inletFailures) == 0 && sum(WindowMetrics::cavePoolFailures) == 0 && generationErrors == 0 && failures.isEmpty(); } diff --git a/probe/src/main/java/art/arcane/iris/probe/SeaInletProbe.java b/probe/src/main/java/art/arcane/iris/probe/SeaInletProbe.java index 924ed8f82..ec261b149 100644 --- a/probe/src/main/java/art/arcane/iris/probe/SeaInletProbe.java +++ b/probe/src/main/java/art/arcane/iris/probe/SeaInletProbe.java @@ -61,21 +61,23 @@ public final class SeaInletProbe { } public static void main(String[] arguments) { + int exitCode = 1; try { Configuration configuration = Configuration.parse(arguments); + long failures = 0L; if (configuration.mode().equals("inventory")) { - inventory(configuration); + failures = inventory(configuration); } else if (configuration.mode().equals("dump")) { dump(configuration); } else { - gate(configuration); + failures = gate(configuration).failures(); } - System.exit(0); + exitCode = failures == 0L ? 0 : 1; } catch (Throwable failure) { System.out.println(LOG + " FAIL"); failure.printStackTrace(System.out); - System.exit(1); } + System.exit(exitCode); } private static void dump(Configuration configuration) throws Exception { @@ -101,7 +103,8 @@ public final class SeaInletProbe { } } - private static void inventory(Configuration configuration) throws Exception { + private static int inventory(Configuration configuration) throws Exception { + int failedWindows = 0; try (RealPackProbeSupport.Workspace workspace = workspace(configuration, configuration.packOn()); RealPackProbeSupport.EngineSession session = workspace.openEngine(configuration.seed(), false, "inventory")) { HydrologyRuntime runtime = session.engine().getComplex().getHydrologyRuntime(); @@ -113,6 +116,7 @@ public final class SeaInletProbe { owned = coast[1] == 0 ? Map.of() : owned(runtime, wx, wx, wz, wz); } catch (RuntimeException failure) { System.out.println("SEA_INLET_WINDOW_FAILED wx=" + wx + " wz=" + wz + " " + rootMessage(failure)); + failedWindows++; continue; } double length = 0D; @@ -124,6 +128,7 @@ public final class SeaInletProbe { } } } + return failedWindows; } private static String rootMessage(Throwable failure) { @@ -164,7 +169,7 @@ public final class SeaInletProbe { return new int[]{below, cliff}; } - private static void gate(Configuration configuration) throws Exception { + private static Gate gate(Configuration configuration) throws Exception { List tiles = tileChunks(configuration); Run forward = run(configuration, configuration.packOn(), tiles, null, false, true, 1, "on-forward"); List all = new ArrayList<>(forward.order); @@ -175,7 +180,7 @@ public final class SeaInletProbe { System.out.println(LOG + " scan chunks " + forward.scanChunks.size() + ", generated chunks " + all.size()); Run reverse = run(configuration, configuration.packOn(), all, null, true, false, configuration.threads(), "on-reverse"); Run baseline = run(configuration, configuration.packOff(), scanned, forward.scanChunks, false, false, configuration.threads(), "off"); - report(configuration, forward.inlets, forward, reverse, baseline); + return report(configuration, forward.inlets, forward, reverse, baseline); } private static Run run(Configuration configuration, File pack, List chunks, Set scanChunks, boolean reverse, boolean inventory, @@ -256,7 +261,19 @@ public final class SeaInletProbe { static final Checks NONE = new Checks(0, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, List.of()); long failures() { - return leaks + missingWater + waterAbove + roofViolations + openRoofViolations + disconnected + shellOpen + shellLoose; + return leaks + missingWater + waterAbove + roofViolations + roofBreaches + openRoofViolations + disconnected + shellOpen + shellLoose; + } + } + + record Gate(Checks checks, int orderMismatches, int inletsWithOtherLevel, int addedLeaks) { + long failures() { + return checks.failures() + orderMismatches + inletsWithOtherLevel + addedLeaks; + } + + String line() { + return String.format(Locale.ROOT, "SEA_INLET_GATE status=%s failures=%d checkFailures=%d orderMismatches=%d inletsWithOtherLevel=%d" + + " addedLeaks=%d", failures() == 0L ? "PASS" : "FAIL", failures(), checks.failures(), orderMismatches, + inletsWithOtherLevel, addedLeaks); } } @@ -295,8 +312,12 @@ public final class SeaInletProbe { } Scan scan = new Scan(run, run.sea, run.roofClearance, inlets); scan.run(); + return checks(scan); + } + + private static Checks checks(Scan scan) { Scan.InletStats total = scan.total; - return new Checks(inlets.size(), total.leaks, total.missingWater, total.waterAbove, total.roofViolations, total.roofBreaches, + return new Checks(scan.inlets.size(), total.leaks, total.missingWater, total.waterAbove, total.roofViolations, total.roofBreaches, total.openRoofViolations, total.disconnected, scan.shellOpen, scan.shellLoose, total.looseBeds, List.copyOf(scan.examples)); } @@ -363,7 +384,7 @@ public final class SeaInletProbe { return chunks; } - private static void report(Configuration configuration, Map touching, Run on, Run reverse, Run off) { + private static Gate report(Configuration configuration, Map touching, Run on, Run reverse, Run off) { int sea = on.sea; int clearance = on.roofClearance; List owned = new ArrayList<>(); @@ -374,8 +395,9 @@ public final class SeaInletProbe { } Scan scan = new Scan(on, sea, clearance, owned); scan.run(); - int onLeaks = scan.countAllLeaks(); - int offLeaks = new Scan(off, sea, clearance, owned).countAllLeaks(); + Set onLeaks = scan.allLeaks(); + Set offLeaks = new Scan(off, sea, clearance, owned).allLeaks(); + int addedLeaks = addedLeaks(onLeaks, offLeaks); int mismatches = mismatches(on.hashes, reverse.hashes); System.out.println("SEA_INLET_INVENTORY owned=" + owned.size() + " touching=" + touching.size()); @@ -403,7 +425,8 @@ public final class SeaInletProbe { scan.total.missingWater, scan.total.seaPlants, scan.total.seaLayers, scan.total.decorations, scan.total.nonSource, scan.total.waterAbove, scan.total.wet, scan.total.dry); System.out.printf(Locale.ROOT, "SEA_INLET_LEVEL sea=%d inletsWithOtherLevel=%d%n", sea, offLevel); - System.out.printf(Locale.ROOT, "SEA_INLET_ALL_WATER_LEAKS scanChunks=%d inletsOn=%d inletsOff=%d%n", on.bands.size(), onLeaks, offLeaks); + System.out.printf(Locale.ROOT, "SEA_INLET_ALL_WATER_LEAKS scanChunks=%d inletsOn=%d inletsOff=%d added=%d%n", on.bands.size(), + onLeaks.size(), offLeaks.size(), addedLeaks); System.out.printf(Locale.ROOT, "SEA_INLET_ROOF min=%d violations=%d breaches=%d openRoofViolations=%d coveredColumns=%d openColumns=%d%n", scan.total.roofMin, scan.total.roofViolations, scan.total.roofBreaches, scan.total.openRoofViolations, scan.total.covered, scan.total.open); @@ -413,6 +436,9 @@ public final class SeaInletProbe { scan.shellOpen, scan.shellLoose, maxOpenLandStations(owned), scan.total.looseBeds); System.out.printf(Locale.ROOT, "SEA_INLET_DETERMINISM chunks=%d reverseChunks=%d mismatches=%d crossChunkInlets=%d crossWindowInlets=%d%n", on.hashes.size(), reverse.hashes.size(), mismatches, scan.crossChunk(), scan.crossWindow()); + Gate gate = new Gate(checks(scan), mismatches, offLevel, addedLeaks); + System.out.println(gate.line()); + return gate; } private static int openStations(SeaInlet inlet) { @@ -485,6 +511,18 @@ public final class SeaInletProbe { return (int) key; } + static int addedLeaks(Set on, Set off) { + int added = 0; + for (long leak : on) { + added += off.contains(leak) ? 0 : 1; + } + return added; + } + + static long cellKey(int x, int y, int z) { + return ((long) x & 0x3FFFFFFL) << 38 | ((long) z & 0x3FFFFFFL) << 12 | (y & 0xFFFL); + } + static byte classify(NativeBlockState state, String seaFluid) { if (state == null || state.isAir()) { return AIR; @@ -963,8 +1001,8 @@ public final class SeaInletProbe { return level >= 0 && level < band.levels && seen[((z & 15) << 4 | (x & 15)) * band.levels + level]; } - private int countAllLeaks() { - int leaks = 0; + private Set allLeaks() { + Set leaks = new HashSet<>(); for (Band band : run.bands.values()) { for (int lz = 0; lz < 16; lz++) { for (int lx = 0; lx < 16; lx++) { @@ -984,7 +1022,7 @@ public final class SeaInletProbe { byte below = band.at(lx, y - 1, lz); open |= below == AIR || below == OTHER; if (open) { - leaks++; + leaks.add(cellKey(x, y, z)); } } } diff --git a/probe/src/test/java/art/arcane/iris/probe/CavePoolChecksTest.java b/probe/src/test/java/art/arcane/iris/probe/CavePoolChecksTest.java index 3d13e649a..ff91762d3 100644 --- a/probe/src/test/java/art/arcane/iris/probe/CavePoolChecksTest.java +++ b/probe/src/test/java/art/arcane/iris/probe/CavePoolChecksTest.java @@ -1,11 +1,16 @@ package art.arcane.iris.probe; +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import org.junit.Test; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class CavePoolChecksTest { @Test @@ -16,9 +21,59 @@ public class CavePoolChecksTest { assertEquals(0L, counts(0, 0, 0, 0, 0, 0, 0, 0).failures()); } + @Test + public void theGateFailsOnContainmentAndOrderMismatches() { + CavePoolProbe.Gate passing = new CavePoolProbe.Gate(counts(0, 0, 0, 0, 0, 0, 0, 0), 0); + assertEquals(0L, passing.failures()); + assertTrue(passing.line(), passing.line().startsWith("CAVE_POOL_GATE status=PASS failures=0 ")); + assertEquals(2L, new CavePoolProbe.Gate(counts(0, 0, 0, 0, 0, 0, 0, 0), 2).failures()); + CavePoolProbe.Gate failing = new CavePoolProbe.Gate(counts(1, 2, 3, 4, 5, 6, 7, 8), 1); + assertEquals(37L, failing.failures()); + assertTrue(failing.line(), failing.line().startsWith("CAVE_POOL_GATE status=FAIL failures=37 ")); + } + + @Test + public void poolCellsThatDidNotStayStillSourcesOfTheirFluidFail() { + CavePoolProbe.Counts replaced = new CavePoolProbe.Counts(1, 1, 1, 1, Map.of(), List.of(), List.of(), Map.of(), 0, 0, 0, 0, 0, 0, 0, 0, + Map.of("water->minecraft:stone", 2, "lava->null", 1), List.of()); + assertEquals(3L, replaced.failures()); + assertEquals(3L, new CavePoolProbe.Gate(replaced, 0).failures()); + } + + @Test + public void poolSourcesMatchTheFluidTheCellResolvesTo() { + NativeBlockState water = fluid("minecraft:water", true); + NativeBlockState lava = fluid("minecraft:lava", false); + assertTrue(CavePoolProbe.source(fluid("minecraft:water", true), water)); + assertTrue(CavePoolProbe.source(fluid("minecraft:water[level=0]", true), water)); + assertFalse("flowing water is not a pool source", CavePoolProbe.source(fluid("minecraft:water[level=1]", true), water)); + assertFalse("lava is not a water pool source", CavePoolProbe.source(fluid("minecraft:lava", false), water)); + assertTrue(CavePoolProbe.source(fluid("minecraft:lava[level=0]", false), lava)); + assertFalse(CavePoolProbe.source(fluid("minecraft:water", true), lava)); + assertFalse(CavePoolProbe.source(null, water)); + NativeBlockState stone = mock(NativeBlockState.class); + when(stone.key()).thenReturn("minecraft:stone"); + assertFalse(CavePoolProbe.source(stone, water)); + } + + @Test + public void orderMismatchesCountChunksWhoseHashesDiffer() { + assertEquals(0, CavePoolProbe.compare(Map.of(1L, 10L, 2L, 20L), Map.of(2L, 20L, 1L, 10L))); + assertEquals(1, CavePoolProbe.compare(Map.of(1L, 10L, 2L, 20L), Map.of(1L, 10L, 2L, 21L))); + assertEquals("a chunk missing from the shuffled run is a mismatch", 1, CavePoolProbe.compare(Map.of(1L, 10L, 2L, 20L), Map.of(1L, 10L))); + } + private static CavePoolProbe.Counts counts(int air, int open, int sky, int foreign, int waterlogged, int gravity, int fluidAbove, int gravityCeilings) { return new CavePoolProbe.Counts(1, 1, 1, 1, Map.of(), List.of(), List.of(), Map.of(), air, open, sky, foreign, waterlogged, gravity, fluidAbove, gravityCeilings, Map.of(), List.of()); } + + private static NativeBlockState fluid(String key, boolean water) { + NativeBlockState state = mock(NativeBlockState.class); + when(state.key()).thenReturn(key); + when(state.isFluid()).thenReturn(true); + when(state.isWater()).thenReturn(water); + return state; + } } diff --git a/probe/src/test/java/art/arcane/iris/probe/HydrologyProbeTest.java b/probe/src/test/java/art/arcane/iris/probe/HydrologyProbeTest.java index 001b34c31..85f12ac58 100644 --- a/probe/src/test/java/art/arcane/iris/probe/HydrologyProbeTest.java +++ b/probe/src/test/java/art/arcane/iris/probe/HydrologyProbeTest.java @@ -8,9 +8,11 @@ import org.junit.Test; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.UnaryOperator; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -188,6 +190,24 @@ public class HydrologyProbeTest { } } + @Test + public void bermOverCapFailsTheProbe() { + HydrologyReport.Result clean = result(0L); + assertTrue(clean.lines().toString(), clean.passes()); + HydrologyReport.Result raised = result(3L); + assertFalse(raised.passes()); + Map total = fields(line(raised.lines(), "IRIS_HYDROLOGY_TOTAL")); + assertEquals("3", total.get("bermOverCap")); + assertEquals("FAIL", total.get("status")); + assertTrue(total.get("missedTargets"), total.get("missedTargets").contains("bermOverCap")); + } + + private static HydrologyReport.Result result(long bermOverCap) { + HydrologyReport.WindowMetrics window = new HydrologyReport.WindowMetrics(new WindowKey(4, 4), 1D, 0L, 0L, 1D, 1D, 0, 1D, 1, 1D, 1, + Set.of(64), 0, 0L, 0L, 0L, 0L, 0L, bermOverCap, 0, 0L, 0, 0L, 1L, "digest"); + return new HydrologyReport.Result(List.of(window), 1D, 1, 1, 0L, 0L, 1D, 0L, "digest", List.of(), List.of()); + } + private static int[] bankBesideWater(SyntheticHydrology fixture) { int[][] offsets = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int min = LAND.minX() * HydrologyWindows.CHUNKS; diff --git a/probe/src/test/java/art/arcane/iris/probe/SeaInletChecksTest.java b/probe/src/test/java/art/arcane/iris/probe/SeaInletChecksTest.java index 67aa8f493..fe36fb0ec 100644 --- a/probe/src/test/java/art/arcane/iris/probe/SeaInletChecksTest.java +++ b/probe/src/test/java/art/arcane/iris/probe/SeaInletChecksTest.java @@ -4,19 +4,56 @@ import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import org.junit.Test; import java.util.List; +import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SeaInletChecksTest { @Test - public void roofBreachesAndLooseBedsAreReportedButOnlyContainmentAndSealChecksFail() { - SeaInletProbe.Checks reported = new SeaInletProbe.Checks(3, 0L, 0L, 0L, 0L, 1939L, 0L, 0L, 0L, 0L, 952L, List.of()); + public void roofBreachesFailWithTheContainmentSealAndRoofChecks() { + SeaInletProbe.Checks breached = new SeaInletProbe.Checks(3, 0L, 0L, 0L, 0L, 1939L, 0L, 0L, 0L, 0L, 0L, List.of()); + assertEquals(1939L, breached.failures()); + SeaInletProbe.Checks failing = new SeaInletProbe.Checks(3, 1L, 2L, 3L, 4L, 9L, 5L, 6L, 7L, 8L, 0L, List.of()); + assertEquals(45L, failing.failures()); + } + + @Test + public void looseBedsAreReportedButDoNotFail() { + SeaInletProbe.Checks reported = new SeaInletProbe.Checks(3, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 952L, List.of()); assertEquals(0L, reported.failures()); - SeaInletProbe.Checks failing = new SeaInletProbe.Checks(3, 1L, 2L, 3L, 4L, 0L, 5L, 6L, 7L, 8L, 0L, List.of()); - assertEquals(36L, failing.failures()); + } + + @Test + public void theGateFailsOnEveryCheckIncludingOrderSeaLevelAndAddedLeaks() { + SeaInletProbe.Checks clean = new SeaInletProbe.Checks(3, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 952L, List.of()); + SeaInletProbe.Gate passing = new SeaInletProbe.Gate(clean, 0, 0, 0); + assertEquals(0L, passing.failures()); + assertTrue(passing.line(), passing.line().startsWith("SEA_INLET_GATE status=PASS failures=0 ")); + assertEquals(2L, new SeaInletProbe.Gate(clean, 0, 0, 2).failures()); + assertEquals(1L, new SeaInletProbe.Gate(clean, 1, 0, 0).failures()); + assertEquals(1L, new SeaInletProbe.Gate(clean, 0, 1, 0).failures()); + SeaInletProbe.Checks breached = new SeaInletProbe.Checks(3, 0L, 0L, 0L, 0L, 4L, 0L, 0L, 0L, 0L, 0L, List.of()); + SeaInletProbe.Gate failing = new SeaInletProbe.Gate(breached, 0, 0, 0); + assertEquals(4L, failing.failures()); + assertTrue(failing.line(), failing.line().startsWith("SEA_INLET_GATE status=FAIL failures=4 ")); + } + + @Test + public void addedLeaksAreTheLeaksMissingWithoutInlets() { + long kept = SeaInletProbe.cellKey(10, 300, -20); + long removed = SeaInletProbe.cellKey(11, 300, -20); + long added = SeaInletProbe.cellKey(10, 301, -20); + assertEquals(0, SeaInletProbe.addedLeaks(Set.of(kept), Set.of(kept))); + assertEquals("inlets that remove natural leaks do not fail", 0, SeaInletProbe.addedLeaks(Set.of(kept), Set.of(kept, removed))); + assertEquals("a leak the inlets move counts although the totals match", 1, SeaInletProbe.addedLeaks(Set.of(kept, added), + Set.of(kept, removed))); + assertEquals(2, SeaInletProbe.addedLeaks(Set.of(added, removed), Set.of())); + assertNotEquals(SeaInletProbe.cellKey(-1, 300, 0), SeaInletProbe.cellKey(0, 300, -1)); + assertNotEquals(SeaInletProbe.cellKey(5, 0, 5), SeaInletProbe.cellKey(5, 4095, 5)); } @Test