diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index eaed4f3d6..cc19633ba 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -272,7 +272,8 @@ running Iris is the pack publisher's responsibility. - Decode IrisApi's value types like settings: `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range` and `BlockPosition` from the JSON shapes in their docs, `Object` as maps, lists, `Double`s, strings and booleans. Read and write a `@JsonForms` class through its codec, created once with its no-argument constructor, handing it - those same plain values; a member written as `null` stays left out and never reaches the codec. + those same plain values; a member written as `null` stays left out and never reaches the codec. Its `Parts` read a + part of a form exactly as the host reads that type anywhere else. Read a `"snippet/"` or `"snippet//"` string of a `@Snippet` type from `snippet//.json`. Complete `NOISE_STYLE` references and `@ResourceRef` of the host kinds (`EXPRESSIONS`, `IMAGE_MAPS` among them); diff --git a/api/DESIGN.md b/api/DESIGN.md index da5b2752d..c660e9628 100644 --- a/api/DESIGN.md +++ b/api/DESIGN.md @@ -919,7 +919,9 @@ Every settings class, value type and pack resource kind is read the same way, by - A class annotated `@JsonForms(Codec.class)` is the one exception: a value packs write in several shapes, such as a number, a `[min, max]` range or a curve object. The host reads its JSON as plain values (maps, lists, `Double`s, strings, booleans), hands them to the codec, and writes the value back through it. It never creates the class or - reads its fields, and studio describes it as any JSON value. + reads its fields, and studio describes it as any JSON value. A form may hold a part of another type, such as a + `NoiseStyle`; the codec reads it with the `Parts` the host hands it, so the part reads as that type does anywhere + else, a pack's expression included. - A member the JSON leaves out keeps the field's initialiser. A member written as `null` counts as left out. - The host never writes `null` into a field. An enum name the enum does not know is an error that lists the known names; it does not become `null` or the default. diff --git a/api/api/src/main/java/com/volmit/config/JsonForms.java b/api/api/src/main/java/com/volmit/config/JsonForms.java index 62dacc24b..b91892b58 100644 --- a/api/api/src/main/java/com/volmit/config/JsonForms.java +++ b/api/api/src/main/java/com/volmit/config/JsonForms.java @@ -22,11 +22,23 @@ public @interface JsonForms { /** * The value {@code json} writes; never null, since a member written as {@code null} counts as left out. * + * @param parts reads a part of a form that is a type of its own, such as a {@code NoiseStyle} * @throws IllegalArgumentException when {@code json} is none of the forms, saying which forms there are */ - T read(Object json); + T read(Object json, Parts parts); /** {@code value} as plain values {@link #read} reads back as an equal value. */ Object write(T value); } + + /** Reads a part of a form exactly as the host reads that type anywhere else, so a style in a form may name a pack's expression. */ + interface Parts { + /** + * {@code json}, as plain values, read as a {@code type}: a settings class, a value type or another + * {@code @JsonForms} class. + * + * @throws IllegalArgumentException when {@code json} does not read as a {@code type} + */ + V read(Object json, Class type); + } } diff --git a/api/host/src/test/java/com/volmit/host/PackSchemaTest.java b/api/host/src/test/java/com/volmit/host/PackSchemaTest.java index 6ae28913d..e01dc85b0 100644 --- a/api/host/src/test/java/com/volmit/host/PackSchemaTest.java +++ b/api/host/src/test/java/com/volmit/host/PackSchemaTest.java @@ -542,7 +542,7 @@ class PackSchemaTest { public static final class Forms implements JsonForms.Codec { @Override - public Height read(Object json) { + public Height read(Object json, JsonForms.Parts parts) { return new Height((Double) json); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/JsonFormsCodecs.java b/core/src/main/java/art/arcane/iris/core/modules/JsonFormsCodecs.java index 3c8f5f3ac..ae28848c6 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/JsonFormsCodecs.java +++ b/core/src/main/java/art/arcane/iris/core/modules/JsonFormsCodecs.java @@ -46,6 +46,7 @@ public final class JsonFormsCodecs implements TypeAdapterFactory { } JsonForms.Codec codec = codecOf(forms); TypeAdapter plainValues = gson.getAdapter(Object.class); + JsonForms.Parts parts = partsReadBy(gson); String typeName = type.getRawType().getSimpleName(); return new TypeAdapter() { @Override @@ -57,7 +58,7 @@ public final class JsonFormsCodecs implements TypeAdapterFactory { public T read(JsonReader in) throws IOException { Object json = plainValues.read(in); try { - return codec.read(json); + return codec.read(json, parts); } catch (IllegalArgumentException notAForm) { throw new JsonParseException(typeName + ": " + notAForm.getMessage(), notAForm); } @@ -65,6 +66,20 @@ public final class JsonFormsCodecs implements TypeAdapterFactory { }.nullSafe(); } + /** Reads a part of a form with the same Gson that reads the form, so a part reads as its type does anywhere else. */ + private static JsonForms.Parts partsReadBy(Gson gson) { + return new JsonForms.Parts() { + @Override + public V read(Object json, Class type) { + try { + return gson.fromJson(gson.toJsonTree(json), type); + } catch (JsonParseException notAPart) { + throw new IllegalArgumentException(notAPart.getMessage(), notAPart); + } + } + }; + } + @SuppressWarnings("unchecked") private JsonForms.Codec codecOf(JsonForms forms) { return (JsonForms.Codec) codecs.computeIfAbsent(forms.value(), JsonFormsCodecs::newCodec); diff --git a/core/src/test/java/art/arcane/iris/core/modules/JsonFormsCodecsTest.java b/core/src/test/java/art/arcane/iris/core/modules/JsonFormsCodecsTest.java index 1e1fa484a..8db568d38 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/JsonFormsCodecsTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/JsonFormsCodecsTest.java @@ -4,9 +4,11 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.volmit.config.JsonForms; +import com.volmit.noise.NoiseStyle; import org.junit.Test; import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; @@ -44,16 +46,46 @@ public class JsonFormsCodecsTest { assertTrue(failure.getMessage(), failure.getMessage().startsWith("Height: ")); } + @Test + public void aPartOfAFormIsReadAsItsOwnType() { + Shaded shaded = GSON.fromJson("{\"blocks\": 3, \"style\": {\"style\": \"SIMPLEX\", \"zoom\": 2}}", Shaded.class); + + assertEquals(NoiseStyle.of("SIMPLEX").withZoom(2), shaded.style()); + } + + @Test + public void aPartThatDoesNotReadFailsNamingTheClass() { + JsonParseException failure = assertThrows(JsonParseException.class, () -> GSON.fromJson("{\"blocks\": 3, \"style\": 4}", Shaded.class)); + + assertTrue(failure.getMessage(), failure.getMessage().startsWith("Shaded: ")); + } + private static final class Settings { private Height height = new Height(1, 1); private List steps = List.of(); } + @JsonForms(Shaded.Forms.class) + private record Shaded(double blocks, NoiseStyle style) { + static final class Forms implements JsonForms.Codec { + @Override + public Shaded read(Object json, JsonForms.Parts parts) { + Map object = (Map) json; + return new Shaded((Double) object.get("blocks"), parts.read(object.get("style"), NoiseStyle.class)); + } + + @Override + public Object write(Shaded value) { + return Map.of("blocks", value.blocks()); + } + } + } + @JsonForms(Height.Forms.class) private record Height(double min, double max) { static final class Forms implements JsonForms.Codec { @Override - public Height read(Object json) { + public Height read(Object json, JsonForms.Parts parts) { return switch (json) { case Double blocks -> new Height(blocks, blocks); case List range -> new Height((Double) range.get(0), (Double) range.get(1)); diff --git a/core/src/test/java/art/arcane/iris/modules/carve/field/CarvedArea.java b/core/src/test/java/art/arcane/iris/modules/carve/field/CarvedArea.java new file mode 100644 index 000000000..18abab8eb --- /dev/null +++ b/core/src/test/java/art/arcane/iris/modules/carve/field/CarvedArea.java @@ -0,0 +1,221 @@ +package art.arcane.iris.modules.carve.field; + +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.modules.carve.Cave; +import com.volmit.noise.NoiseFactory; + +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.BitSet; +import java.util.function.IntPredicate; + +/** + * The blocks a cave carves in a square of chunks under a flat surface, in a world from Y 0 to 256, with measurements of + * their shape: shares, runs along an axis and connected pieces. Blocks are indexed by {@link #index}. + */ +final class CarvedArea { + static final int WORLD_BOTTOM_Y = 0; + static final int WORLD_HEIGHT = 256; + static final int SURFACE_Y = 160; + static final int LAYERS = SURFACE_Y + 1; + + final int size; + final BitSet carved; + + private CarvedArea(int size, BitSet carved) { + this.size = size; + this.carved = carved; + } + + static CarvedArea carve(NoiseFactory noise, String caveJson, long seed, int chunks) { + return carveAt(noise, caveJson, seed, chunks, 0, 0); + } + + /** {@link #carve} of the square whose first block is {@code offsetX}, {@code offsetZ}; blocks are indexed from that corner. */ + static CarvedArea carveAt(NoiseFactory noise, String caveJson, long seed, int chunks, int offsetX, int offsetZ) { + CaveCarver carver = new CaveCarver(TestSettings.of(Cave.class, caveJson), noise, seed, WORLD_BOTTOM_Y, WORLD_HEIGHT); + int size = chunks * 16; + int[] surfaceY = new int[256]; + Arrays.fill(surfaceY, SURFACE_Y); + double[] weight = new double[256]; + Arrays.fill(weight, 1D); + boolean[] sealed = new boolean[256]; + BitSet carved = new BitSet(size * size * LAYERS); + for (int chunkX = 0; chunkX < chunks; chunkX++) { + for (int chunkZ = 0; chunkZ < chunks; chunkZ++) { + int originX = chunkX * 16; + int originZ = chunkZ * 16; + carver.carve(offsetX + originX, offsetZ + originZ, surfaceY, weight, sealed, + (localX, y, localZ) -> carved.set((y * size * size) + ((originZ + localZ) * size) + originX + localX)); + } + } + return new CarvedArea(size, carved); + } + + int index(int x, int y, int z) { + return (y * size * size) + (z * size) + x; + } + + int x(int block) { + return block % size; + } + + int z(int block) { + return (block / size) % size; + } + + int y(int block) { + return block / (size * size); + } + + /** {@code where}, tested once for every block of the area, for tests that ask it about every block more than once. */ + IntPredicate cached(IntPredicate where) { + BitSet holds = new BitSet(size * size * LAYERS); + for (int block = 0; block < size * size * LAYERS; block++) { + if (where.test(block)) { + holds.set(block); + } + } + return holds::get; + } + + /** Carved blocks among the blocks {@code where} takes, as a share of them. */ + double carvedShare(IntPredicate where) { + long inside = 0; + long carvedInside = 0; + for (int block = 0; block < size * size * LAYERS; block++) { + if (!where.test(block)) { + continue; + } + inside++; + if (carved.get(block)) { + carvedInside++; + } + } + return carvedInside / (double) Math.max(1, inside); + } + + /** Mean length of the unbroken runs of carved blocks along one axis, counting runs that start where {@code where} holds. */ + double meanRun(int stepX, int stepY, int stepZ, IntPredicate where) { + long blocks = 0; + long runs = 0; + for (int block = carved.nextSetBit(0); block >= 0; block = carved.nextSetBit(block + 1)) { + if (!where.test(block)) { + continue; + } + blocks++; + int previousX = x(block) - stepX; + int previousY = y(block) - stepY; + int previousZ = z(block) - stepZ; + boolean previousInside = previousX >= 0 && previousY >= 0 && previousZ >= 0; + if (!previousInside || !carved.get(index(previousX, previousY, previousZ))) { + runs++; + } + } + return blocks / (double) Math.max(1, runs); + } + + double horizontalMeanRun(IntPredicate where) { + return (meanRun(1, 0, 0, where) + meanRun(0, 0, 1, where)) / 2D; + } + + /** Share of the blocks either area carves that only one of them carves, among blocks {@code where} takes. */ + double differenceShare(CarvedArea other, IntPredicate where) { + long either = 0; + long onlyOne = 0; + for (int block = 0; block < size * size * LAYERS; block++) { + if (!where.test(block)) { + continue; + } + boolean mine = carved.get(block); + boolean theirs = other.carved.get(block); + if (mine || theirs) { + either++; + } + if (mine != theirs) { + onlyOne++; + } + } + return onlyOne / (double) Math.max(1, either); + } + + /** Pieces of carved blocks joined face to face, smaller than {@code blocks}. */ + int carvedPiecesSmallerThan(int blocks) { + return piecesSmallerThan(carved, blocks, false); + } + + /** Pieces of rock that touch no edge of the area and are smaller than {@code blocks}: rock left floating in the caves. */ + int floatingRockSmallerThan(int blocks) { + BitSet rock = (BitSet) carved.clone(); + rock.flip(0, size * size * LAYERS); + return piecesSmallerThan(rock, blocks, true); + } + + double largestPieceShare() { + int largest = 0; + for (int piece : pieceSizes(carved, false)) { + largest = Math.max(largest, piece); + } + return largest / (double) Math.max(1, carved.cardinality()); + } + + private int piecesSmallerThan(BitSet blocks, int limit, boolean onlyEnclosed) { + int count = 0; + for (int piece : pieceSizes(blocks, onlyEnclosed)) { + if (piece < limit) { + count++; + } + } + return count; + } + + /** Sizes of the face-joined pieces of {@code blocks}; with {@code onlyEnclosed}, of those touching no edge of the area. */ + private int[] pieceSizes(BitSet blocks, boolean onlyEnclosed) { + BitSet seen = new BitSet(blocks.size()); + ArrayDeque open = new ArrayDeque<>(); + int[] sizes = new int[0]; + int count = 0; + for (int root = blocks.nextSetBit(0); root >= 0; root = blocks.nextSetBit(root + 1)) { + if (seen.get(root)) { + continue; + } + int pieceSize = 0; + boolean touchesEdge = false; + seen.set(root); + open.add(root); + while (!open.isEmpty()) { + int block = open.poll(); + pieceSize++; + int x = x(block); + int z = z(block); + int y = y(block); + touchesEdge |= x == 0 || z == 0 || y == 0 || x == size - 1 || z == size - 1 || y == LAYERS - 1; + visit(blocks, seen, open, x + 1, y, z); + visit(blocks, seen, open, x - 1, y, z); + visit(blocks, seen, open, x, y + 1, z); + visit(blocks, seen, open, x, y - 1, z); + visit(blocks, seen, open, x, y, z + 1); + visit(blocks, seen, open, x, y, z - 1); + } + if (onlyEnclosed && touchesEdge) { + continue; + } + if (count == sizes.length) { + sizes = Arrays.copyOf(sizes, Math.max(16, count * 2)); + } + sizes[count++] = pieceSize; + } + return Arrays.copyOf(sizes, count); + } + + private void visit(BitSet blocks, BitSet seen, ArrayDeque open, int x, int y, int z) { + if (x < 0 || z < 0 || y < 0 || x >= size || z >= size || y >= LAYERS) { + return; + } + int block = index(x, y, z); + if (blocks.get(block) && !seen.get(block)) { + seen.set(block); + open.add(block); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/modules/carve/field/CaveValuesTest.java b/core/src/test/java/art/arcane/iris/modules/carve/field/CaveValuesTest.java new file mode 100644 index 000000000..9518d57df --- /dev/null +++ b/core/src/test/java/art/arcane/iris/modules/carve/field/CaveValuesTest.java @@ -0,0 +1,551 @@ +package art.arcane.iris.modules.carve.field; + +import art.arcane.iris.core.modules.CarveTestWorld; +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.modules.carve.Cave; +import art.arcane.iris.modules.carve.CaveValue; +import com.google.gson.JsonParseException; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseStyle; +import org.junit.Test; + +import java.util.BitSet; +import java.util.List; +import java.util.function.IntPredicate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** + * Every number that shapes a cave may be a plain number, a range a smooth noise picks from, or a range with the style + * that picks. Where a value's noise is at its low end the cave carves as its min would, and at its high end as its max + * would. The places are found by reading the value's own noise, seeded by its name as the carver seeds it. + */ +public class CaveValuesTest { + private static final long SEED = 91_277L; + private static final int CHUNKS = 8; + private static final int WIDE_CHUNKS = 16; + /** Patches about 50 blocks across, so a few of each end fit in the carved area. */ + private static final String PATCHES = "{\"style\": \"SIMPLEX\", \"zoom\": 0.6}"; + /** Patches about 160 blocks across, wide enough to hold rooms of the size and height they pick. */ + private static final String BROAD_PATCHES = "{\"style\": \"SIMPLEX\", \"zoom\": 2}"; + private static final String TUNNEL_SPACING = "\"spacing\": {\"horizontal\": 48, \"vertical\": 34}"; + private static final String OPEN_CAVERN_KEYS = "\"size\": 40, \"height\": 18, \"coverage\": 0.3"; + /** Rooms tall enough for the finer wall noise that roughness weighs: under about 20 blocks it is finer than the lattice. */ + private static final String TALL_CAVERN_KEYS = "\"size\": 40, \"height\": 24, \"coverage\": 0.3"; + private static final double UNUSED_CHANGE_BLOCKS = 1D; + + private final NoiseFactory noise = new CarveTestWorld().resources().noise(); + + private static String range(double min, double max) { + return "{\"min\": " + min + ", \"max\": " + max + ", \"style\": " + PATCHES + "}"; + } + + private static String broadRange(double min, double max) { + return "{\"min\": " + min + ", \"max\": " + max + ", \"style\": " + BROAD_PATCHES + "}"; + } + + private CarvedArea carve(String caveJson) { + return CarvedArea.carve(noise, caveJson, SEED, CHUNKS); + } + + private CarvedArea carveWide(String caveJson) { + return CarvedArea.carve(noise, caveJson, SEED, WIDE_CHUNKS); + } + + private static String tunnel(String keys) { + return "{\"tunnel\": {" + TUNNEL_SPACING + ", " + keys + "}, \"opensToSurface\": true}"; + } + + private static String cavern(String keys) { + return "{\"cavern\": {" + keys + "}}"; + } + + @Test + public void aRangeWithEqualEndsCarvesWhatThePlainNumberCarves() { + String plain = """ + {"tunnel": {"width": 5, "height": 7, "spacing": {"horizontal": 48, "vertical": 34}, "verticalWarp": 0.3, + "coverage": {"share": 0.6, "softness": 0.5}}, + "cavern": {"size": 40, "height": 24, "coverage": 0.2, "roughness": 0.5, + "pillars": {"spacing": 16, "thickness": 4, "flare": 3, "vertical": 24}}, + "depth": {"min": 20, "max": 140}, "fade": 10, "surfaceClearance": 9, "ceilingFade": 6} + """; + String equalEnds = """ + {"tunnel": {"width": {"min": 5, "max": 5, "style": {"style": "SIMPLEX"}}, "height": {"min": 7, "max": 7}, + "spacing": {"horizontal": 48, "vertical": 34}, "verticalWarp": {"min": 0.3, "max": 0.3}, + "coverage": {"share": {"min": 0.6, "max": 0.6}, "softness": {"min": 0.5, "max": 0.5}}}, + "cavern": {"size": {"min": 40, "max": 40}, "height": {"min": 24, "max": 24}, "coverage": {"min": 0.2, "max": 0.2}, + "roughness": {"min": 0.5, "max": 0.5}, + "pillars": {"spacing": {"min": 16, "max": 16}, "thickness": {"min": 4, "max": 4}, + "flare": {"min": 3, "max": 3}, "vertical": {"min": 24, "max": 24}}}, + "depth": {"min": {"min": 20, "max": 20}, "max": {"min": 140, "max": 140}}, "fade": {"min": 10, "max": 10}, + "surfaceClearance": {"min": 9, "max": 9}, "ceilingFade": {"min": 6, "max": 6}} + """; + + BitSet byPlainNumbers = carve(plain).carved; + + assertTrue(byPlainNumbers.cardinality() > 10_000); + assertEquals(byPlainNumbers, carve(equalEnds).carved); + } + + @Test + public void theNewKeysAtTheirDefaultsCarveWhatTheConstantsTheyReplaceCarved() { + String leftOut = "{\"tunnel\": {" + TUNNEL_SPACING + ", \"coverage\": 0.5}, \"cavern\": {" + TALL_CAVERN_KEYS + "}}"; + String spelledOut = "{\"tunnel\": {" + TUNNEL_SPACING + ", \"verticalWarp\": 0.5, \"coverage\": {\"share\": 0.5, \"softness\": 0.3}}," + + " \"cavern\": {" + TALL_CAVERN_KEYS + ", \"roughness\": 0.3}, \"ceilingFade\": 8}"; + + assertEquals(carve(leftOut).carved, carve(spelledOut).carved); + } + + @Test + public void eachNewKeyChangesTheCaveAwayFromItsDefault() { + String tunnels = "\"coverage\": {\"share\": 0.5}"; + CarvedArea defaultTunnels = carve(tunnel(tunnels)); + CarvedArea defaultCavern = carve(cavern(TALL_CAVERN_KEYS)); + CarvedArea closedTunnels = carve("{\"tunnel\": {" + TUNNEL_SPACING + "}}"); + + assertChanged("verticalWarp", defaultTunnels, carve(tunnel(tunnels + ", \"verticalWarp\": 0"))); + assertChanged("softness", defaultTunnels, carve(tunnel("\"coverage\": {\"share\": 0.5, \"softness\": 1}"))); + assertChanged("roughness", defaultCavern, carve(cavern(TALL_CAVERN_KEYS + ", \"roughness\": 0"))); + assertTrue("ceilingFade", closedTunnels.differenceShare(carve("{\"tunnel\": {" + TUNNEL_SPACING + "}, \"ceilingFade\": 40}"), block -> true) > 0.005D); + } + + private static void assertChanged(String key, CarvedArea byDefault, CarvedArea changed) { + double difference = byDefault.differenceShare(changed, block -> true); + assertTrue(key + " changes " + difference + " of the cave", difference > 0.05D); + } + + @Test + public void aShareAloneIsShorthandForATunnelCoverage() { + assertEquals(carve(tunnel("\"coverage\": {\"share\": 0.4}")).carved, carve(tunnel("\"coverage\": 0.4")).carved); + } + + @Test + public void aSofterCoverageThinsTunnelsOutOverALongerStretch() { + int abrupt = carve(tunnel("\"coverage\": {\"share\": 0.5, \"softness\": 0}")).carved.cardinality(); + int soft = carve(tunnel("\"coverage\": {\"share\": 0.5, \"softness\": 1}")).carved.cardinality(); + + assertTrue(abrupt + " abrupt against " + soft + " soft", soft < abrupt * 0.8D); + } + + @Test + public void aRoughnessOfZeroGivesSmoothWalls() { + double smooth = wallShare(carve(cavern(TALL_CAVERN_KEYS + ", \"roughness\": 0"))); + double rough = wallShare(carve(cavern(TALL_CAVERN_KEYS + ", \"roughness\": 1"))); + + assertTrue(smooth + " smooth against " + rough + " rough", rough > smooth * 1.1D); + } + + @Test + public void aVerticalWarpOfZeroKeepsTheWarpFromMovingTunnelsUpAndDown() { + String warp = "\"warp\": {\"style\": \"SIMPLEX\", \"zoom\": 0.3, \"multiplier\": 30}"; + double level = heightChangePerBlock(carve(tunnel(warp + ", \"verticalWarp\": 0"))); + double bobbing = heightChangePerBlock(carve(tunnel(warp + ", \"verticalWarp\": 1"))); + + assertTrue(level + " level against " + bobbing + " bobbing", bobbing > level * 1.3D); + } + + /** + * How far a tunnel rises or falls from one column to the next, on average: the middle heights of neighbouring + * columns that each cross exactly one tunnel. + */ + private static double heightChangePerBlock(CarvedArea area) { + double[] middleY = new double[area.size * area.size]; + for (int x = 0; x < area.size; x++) { + for (int z = 0; z < area.size; z++) { + middleY[(z * area.size) + x] = middleOfOnlyRun(area, x, z); + } + } + double change = 0D; + long pairs = 0; + for (int x = 0; x < area.size - 1; x++) { + for (int z = 0; z < area.size - 1; z++) { + double here = middleY[(z * area.size) + x]; + for (double next : new double[]{middleY[(z * area.size) + x + 1], middleY[((z + 1) * area.size) + x]}) { + if (!Double.isNaN(here) && !Double.isNaN(next)) { + change += Math.abs(next - here); + pairs++; + } + } + } + } + return change / Math.max(1, pairs); + } + + private static double middleOfOnlyRun(CarvedArea area, int x, int z) { + int runs = 0; + int lowest = -1; + int highest = -1; + boolean inRun = false; + for (int y = 0; y < CarvedArea.LAYERS; y++) { + boolean carved = area.carved.get(area.index(x, y, z)); + if (carved && !inRun) { + runs++; + lowest = y; + } + if (carved) { + highest = y; + } + inRun = carved; + } + return runs == 1 ? (lowest + highest) / 2D : Double.NaN; + } + + @Test + public void aValueWrittenInNoFormFailsSayingWhichFormsThereAre() { + JsonParseException text = assertThrows(JsonParseException.class, () -> TestSettings.of(Cave.class, "{\"fade\": \"wide\"}")); + JsonParseException misspelt = assertThrows(JsonParseException.class, () -> TestSettings.of(Cave.class, "{\"fade\": {\"min\": 1, \"mx\": 4}}")); + JsonParseException halfRange = assertThrows(JsonParseException.class, () -> TestSettings.of(Cave.class, "{\"fade\": {\"min\": 1}}")); + + assertTrue(text.getMessage(), text.getMessage().contains("a number or {min, max}")); + assertTrue(misspelt.getMessage(), misspelt.getMessage().contains("not mx")); + assertTrue(halfRange.getMessage(), halfRange.getMessage().contains("needs both min and max")); + } + + @Test + public void valuesOutsideTheirBoundsAreReportedByTheirPlaceInTheFile() { + Cave cave = TestSettings.of(Cave.class, """ + {"fade": 200, "tunnel": {"width": {"min": 0, "max": 6}, "coverage": {"share": 2}}, + "cavern": {"pillars": {"flare": 0.5}}} + """); + + assertEquals(List.of("fade is 200; it must be at most 128", "tunnel.width.min is 0; it must be at least 1", + "tunnel.coverage.share is 2; it must be at most 1", "cavern.pillars.flare is 0.5; it must be at least 1"), cave.valuesOutOfBounds()); + assertEquals(List.of(), TestSettings.of(Cave.class, "{\"tunnel\": {}, \"cavern\": {\"pillars\": {}}}").valuesOutOfBounds()); + } + + @Test + public void aRangeWithoutAStyleChangesSmoothlyWhereAStaticStyleJumps() { + CaveValue smooth = TestSettings.of(CaveValue.class, "{\"min\": 0, \"max\": 1}"); + CaveValue jumping = TestSettings.of(CaveValue.class, "{\"min\": 0, \"max\": 1, \"style\": {\"style\": \"STATIC\"}}"); + + double smoothStep = largestStep(ValueField.inColumns(smooth, new CaveNoise(noise, SEED), "fade", Cave.VALUE_CHANGE_BLOCKS)); + double jumpingStep = largestStep(ValueField.inColumns(jumping, new CaveNoise(noise, SEED), "fade", Cave.VALUE_CHANGE_BLOCKS)); + + assertTrue("smooth range moves up to " + smoothStep + " per block", smoothStep < 0.03D); + assertTrue("static style moves up to " + jumpingStep + " per block", jumpingStep > 0.3D); + } + + private static double largestStep(ValueField value) { + double largest = 0D; + double previous = value.at(0, 0); + double spread = 0D; + double lowest = previous; + double highest = previous; + for (int x = 1; x < 4096; x++) { + double current = value.at(x, x * 0.37D); + largest = Math.max(largest, Math.abs(current - previous)); + lowest = Math.min(lowest, current); + highest = Math.max(highest, current); + previous = current; + } + spread = highest - lowest; + assertTrue("the range is used: " + spread, spread > 0.9D); + return largest; + } + + /** A value of the whole cave is read per column, so each column at an end of its noise carves exactly as that end does. */ + @Test + public void aVaryingCaveValueCarvesEachColumnExactlyAsItsLowOrHighNumberWould() { + String tunnels = "{\"tunnel\": {" + TUNNEL_SPACING + ", \"width\": 6}, "; + assertMatchesItsEndsExactly("fade", tunnels + "\"depth\": {\"min\": 30, \"max\": 120}, \"fade\": %s}", 2, 40); + assertMatchesItsEndsExactly("surfaceClearance", tunnels + "\"surfaceClearance\": %s}", 2, 40); + assertMatchesItsEndsExactly("ceilingFade", tunnels + "\"ceilingFade\": %s}", 0, 60); + assertMatchesItsEndsExactly("depth.min", tunnels + "\"depth\": {\"min\": %s, \"max\": 150}}", 10, 90); + assertMatchesItsEndsExactly("depth.max", tunnels + "\"depth\": {\"min\": 10, \"max\": %s}}", 60, 150); + } + + private void assertMatchesItsEndsExactly(String name, String caveFormat, double min, double max) { + CarvedArea byMin = carve(caveFormat.formatted(min)); + CarvedArea byMax = carve(caveFormat.formatted(max)); + CarvedArea byRange = carve(caveFormat.formatted(range(min, max))); + ValueField share = columnShares(name); + IntPredicate atMin = byRange.cached(block -> share.at(byRange.x(block), byRange.z(block)) == 0D); + IntPredicate atMax = byRange.cached(block -> share.at(byRange.x(block), byRange.z(block)) == 1D); + + assertTrue(name + " differs between its ends", byMin.differenceShare(byMax, block -> true) > 0.01D); + assertEquals(name + " at its min", 0D, byRange.differenceShare(byMin, atMin), 0D); + assertEquals(name + " at its max", 0D, byRange.differenceShare(byMax, atMax), 0D); + assertTrue(name + " carves at both ends", byRange.carvedShare(atMin) > 0D && byRange.carvedShare(atMax) > 0D); + } + + @Test + public void aVaryingTunnelValueCarvesLikeItsLowOrHighNumberWhereItsNoiseIsAtThatEnd() { + assertFollowsItsEnds("tunnel.verticalWarp", false, + tunnel("\"warp\": {\"style\": \"SIMPLEX\", \"zoom\": 0.3, \"multiplier\": 30}, \"verticalWarp\": %s"), 0, 1); + assertFollowsItsEnds("tunnel.coverage.share", false, tunnel("\"coverage\": {\"share\": %s}"), 0.2, 0.9); + assertFollowsItsEnds("tunnel.coverage.softness", false, tunnel("\"coverage\": {\"share\": 0.5, \"softness\": %s}"), 0, 1); + assertFollowsItsEnds("tunnel.height", false, tunnel("\"width\": 6, \"height\": %s"), 3, 12); + } + + @Test + public void aVaryingCavernValueCarvesLikeItsLowOrHighNumberWhereItsNoiseIsAtThatEnd() { + assertFollowsItsEnds("cavern.coverage", false, cavern("\"size\": 40, \"height\": 18, \"coverage\": %s"), 0.05, 0.4); + assertFollowsItsEnds("cavern.roughness", false, cavern(TALL_CAVERN_KEYS + ", \"roughness\": %s"), 0, 1); + assertFollowsItsEnds("cavern.pillars.thickness", true, cavern(OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": 14, \"thickness\": %s}"), 2, 6); + assertFollowsItsEnds("cavern.pillars.flare", true, cavern(OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": 14, \"thickness\": 4, \"flare\": %s}"), 1, 8); + } + + /** + * Where the value's noise is at its min, the cave carves much more like the min than the max, and the other way + * round where it is at its max. Values read on the lattice are interpolated near the edge of an end, so they only + * come close; values read per column match the ends exactly. + */ + private void assertFollowsItsEnds(String name, boolean inColumns, String caveFormat, double min, double max) { + CarvedArea byMin = carve(caveFormat.formatted(min)); + CarvedArea byMax = carve(caveFormat.formatted(max)); + CarvedArea byRange = carve(caveFormat.formatted(range(min, max))); + CaveValue shares = TestSettings.of(CaveValue.class, range(0, 1)); + CaveNoise caveNoise = new CaveNoise(noise, SEED); + ValueField share = inColumns + ? ValueField.inColumns(shares, caveNoise, name, UNUSED_CHANGE_BLOCKS) + : ValueField.inBlocks(shares, caveNoise, name, UNUSED_CHANGE_BLOCKS); + IntPredicate atMin = byRange.cached(block -> share.at(byRange.x(block), byRange.y(block), byRange.z(block)) == 0D); + IntPredicate atMax = byRange.cached(block -> share.at(byRange.x(block), byRange.y(block), byRange.z(block)) == 1D); + + double minAgainstMin = byRange.differenceShare(byMin, atMin); + double minAgainstMax = byRange.differenceShare(byMax, atMin); + double maxAgainstMax = byRange.differenceShare(byMax, atMax); + double maxAgainstMin = byRange.differenceShare(byMin, atMax); + + assertNotEquals(name + " differs between its ends", byMin.carved, byMax.carved); + assertTrue(name + " at its min: " + minAgainstMin + " from min, " + minAgainstMax + " from max", minAgainstMin < minAgainstMax * 0.5D); + assertTrue(name + " at its max: " + maxAgainstMax + " from max, " + maxAgainstMin + " from min", maxAgainstMax < maxAgainstMin * 0.5D); + } + + @Test + public void aVaryingTunnelWidthIsNarrowWhereItsNoiseIsLowAndWideWhereItIsHigh() { + CaveNoise caveNoise = new CaveNoise(noise, SEED); + for (int field = 0; field < 6; field++) { + caveNoise.smooth(48, 34); + } + Field3 widthNoise = caveNoise.inBlocks(TestSettings.of(NoiseStyle.class, PATCHES)); + CarvedArea varying = carve(tunnel("\"width\": " + range(2, 10))); + + double narrow = varying.horizontalMeanRun(block -> ValueField.shareAt(widthNoise.at(varying.x(block), varying.y(block), varying.z(block))) == 0D); + double wide = varying.horizontalMeanRun(block -> ValueField.shareAt(widthNoise.at(varying.x(block), varying.y(block), varying.z(block))) == 1D); + + assertTrue("narrow end runs " + narrow + ", wide end " + wide, wide > narrow * 2D); + } + + @Test + public void aCavernCoverageRangeFromZeroLeavesAreasWithoutRooms() { + CarvedArea varying = carve(cavern("\"size\": 40, \"height\": 18, \"coverage\": " + range(0, 0.4))); + ValueField share = ValueField.inBlocks(TestSettings.of(CaveValue.class, range(0, 1)), new CaveNoise(noise, SEED), "cavern.coverage", UNUSED_CHANGE_BLOCKS); + + double withoutRooms = varying.carvedShare(block -> share.at(varying.x(block), varying.y(block), varying.z(block)) == 0D); + double withRooms = varying.carvedShare(block -> share.at(varying.x(block), varying.y(block), varying.z(block)) == 1D); + + assertTrue("carved where coverage is 0: " + withoutRooms, withoutRooms < 0.005D); + assertTrue("carved where coverage is 0.4: " + withRooms, withRooms > 0.2D); + } + + @Test + public void aVaryingPillarThicknessKeepsMoreRockWhereItsNoiseIsHigh() { + CarvedArea open = carve(cavern(OPEN_CAVERN_KEYS)); + CarvedArea varying = carve(cavern(OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": 14, \"thickness\": " + range(2, 7) + "}")); + ValueField share = columnShares("cavern.pillars.thickness"); + + double thin = keptShare(open, varying, block -> share.at(open.x(block), open.z(block)) == 0D); + double thick = keptShare(open, varying, block -> share.at(open.x(block), open.z(block)) == 1D); + + assertTrue("pillars keep " + thin + " of the room where thin, " + thick + " where thick", thick > thin * 2D); + } + + @Test + public void aVaryingRoomSizeMakesLargerRoomsWhereItsNoiseIsHighWithoutLooseRock() { + String keys = "\"height\": 20, \"coverage\": 0.2}, \"depth\": {\"min\": 10, \"max\": 150}"; + CarvedArea small = carveWide("{\"cavern\": {\"size\": 30, " + keys + "}"); + CarvedArea large = carveWide("{\"cavern\": {\"size\": 90, " + keys + "}"); + CarvedArea varying = carveWide("{\"cavern\": {\"size\": " + broadRange(30, 90) + ", " + keys + "}"); + ValueField share = ValueField.inBlocks(TestSettings.of(CaveValue.class, broadRange(0, 1)), new CaveNoise(noise, SEED), "cavern.size", UNUSED_CHANGE_BLOCKS); + + double smallRuns = varying.horizontalMeanRun(block -> share.at(varying.x(block), 80, varying.z(block)) <= 0.15D); + double largeRuns = varying.horizontalMeanRun(block -> share.at(varying.x(block), 80, varying.z(block)) >= 0.85D); + + assertTrue("rooms run " + smallRuns + " where small, " + largeRuns + " where large", largeRuns > smallRuns * 1.3D); + assertNoMoreLooseRockThanEitherEnd(varying, small, large); + } + + /** + * The coverage threshold is measured once on the whole room field, so where size, height or roughness vary the + * carved share is only close to what the ends carve: within a fifth of their average over nine far-apart areas. + */ + @Test + public void aRangeInSizeHeightOrRoughnessCarvesCloseToTheShareItsEndsCarve() { + String depth = ", \"coverage\": 0.2}, \"depth\": {\"min\": 10, \"max\": 150}}"; + assertCarvesBetween("size", "{\"cavern\": {\"height\": 20, \"size\": %s" + depth, 30, 90); + assertCarvesBetween("height", "{\"cavern\": {\"size\": 40, \"height\": %s" + depth, 12, 40); + assertCarvesBetween("roughness", "{\"cavern\": {\"size\": 40, \"height\": 24, \"roughness\": %s" + depth, 0, 1); + } + + private void assertCarvesBetween(String key, String caveFormat, double min, double max) { + double byMin = carvedInFarApartAreas(caveFormat.formatted(min)); + double byMax = carvedInFarApartAreas(caveFormat.formatted(max)); + double byRange = carvedInFarApartAreas(caveFormat.formatted("{\"min\": " + min + ", \"max\": " + max + "}")); + + assertWithin(key + " range against its ends' average", byRange, (byMin + byMax) / 2D, 0.2D); + } + + private double carvedInFarApartAreas(String caveJson) { + long carved = 0; + for (int area = 0; area < 9; area++) { + carved += CarvedArea.carveAt(noise, caveJson, SEED, CHUNKS, (area % 3) * 7000, (area / 3) * 7000).carved.cardinality(); + } + return carved; + } + + @Test + public void aVaryingRoomHeightMakesTallerRoomsWhereItsNoiseIsHighWithoutLooseRock() { + String keys = "\"size\": 40, \"coverage\": 0.2}, \"depth\": {\"min\": 10, \"max\": 150}"; + CarvedArea low = carveWide("{\"cavern\": {\"height\": 12, " + keys + "}"); + CarvedArea tall = carveWide("{\"cavern\": {\"height\": 40, " + keys + "}"); + CarvedArea varying = carveWide("{\"cavern\": {\"height\": " + broadRange(12, 40) + ", " + keys + "}"); + ValueField share = ValueField.inColumns(TestSettings.of(CaveValue.class, broadRange(0, 1)), new CaveNoise(noise, SEED), "cavern.height", UNUSED_CHANGE_BLOCKS); + + double lowRuns = varying.meanRun(0, 1, 0, block -> share.at(varying.x(block), varying.z(block)) == 0D); + double tallRuns = varying.meanRun(0, 1, 0, block -> share.at(varying.x(block), varying.z(block)) == 1D); + + assertTrue("rooms run " + lowRuns + " high where low, " + tallRuns + " where tall", tallRuns > lowRuns * 1.4D); + assertNoMoreLooseRockThanEitherEnd(varying, low, tall); + } + + @Test + public void aVaryingPillarSpacingSpreadsThePillarsWhereItsNoiseIsHigh() { + CarvedArea open = carve(cavern(OPEN_CAVERN_KEYS)); + CarvedArea varying = carve(cavern(OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": " + range(10, 40) + ", \"thickness\": 4}")); + ValueField share = columnShares("cavern.pillars.spacing"); + + double close = keptShare(open, varying, block -> share.at(open.x(block), open.z(block)) == 0D); + double far = keptShare(open, varying, block -> share.at(open.x(block), open.z(block)) == 1D); + + assertTrue("pillars keep " + close + " of the room where close, " + far + " where far apart", close > far * 4D); + } + + @Test + public void aVaryingPillarVerticalBreaksPillarsMoreOftenWhereItIsLow() { + String pillars = OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": 14, \"thickness\": 4, \"flare\": 1, \"vertical\": "; + CarvedArea open = carve(cavern(OPEN_CAVERN_KEYS)); + CarvedArea varying = carve(cavern(pillars + range(12, 60) + "}")); + ValueField share = columnShares("cavern.pillars.vertical"); + + int often = partlyKeptColumns(open, varying, (x, z) -> share.at(x, z) == 0D); + int seldom = partlyKeptColumns(open, varying, (x, z) -> share.at(x, z) == 1D); + int oftenColumns = columns(open, (x, z) -> share.at(x, z) == 0D); + int seldomColumns = columns(open, (x, z) -> share.at(x, z) == 1D); + + double oftenShare = often / (double) oftenColumns; + double seldomShare = seldom / (double) seldomColumns; + assertTrue("pillars change in " + oftenShare + " of columns where vertical is low, " + seldomShare + " where high", oftenShare > seldomShare * 1.3D); + } + + private ValueField columnShares(String name) { + return ValueField.inColumns(TestSettings.of(CaveValue.class, range(0, 1)), new CaveNoise(noise, SEED), name, UNUSED_CHANGE_BLOCKS); + } + + private static void assertNoMoreLooseRockThanEitherEnd(CarvedArea varying, CarvedArea first, CarvedArea second) { + int floating = varying.floatingRockSmallerThan(200); + int fragments = varying.carvedPiecesSmallerThan(30); + int mostFloating = Math.max(first.floatingRockSmallerThan(200), second.floatingRockSmallerThan(200)); + int mostFragments = Math.max(first.carvedPiecesSmallerThan(30), second.carvedPiecesSmallerThan(30)); + + assertTrue("floating rock " + floating + " against at most " + mostFloating + " at either end", floating <= mostFloating + 2); + assertTrue("small air pockets " + fragments + " against at most " + mostFragments + " at either end", fragments <= (mostFragments * 2) + 5); + } + + private static void assertWithin(String what, double actual, double expected, double share) { + assertTrue(what + ": " + actual + " against " + expected, Math.abs(actual - expected) <= expected * share); + } + + /** Share of the blocks the open cavern carves where {@code where} holds that pillars keep as rock. */ + private static double keptShare(CarvedArea open, CarvedArea pillared, IntPredicate where) { + long openBlocks = 0; + long kept = 0; + for (int block = open.carved.nextSetBit(0); block >= 0; block = open.carved.nextSetBit(block + 1)) { + if (!where.test(block)) { + continue; + } + openBlocks++; + if (!pillared.carved.get(block)) { + kept++; + } + } + return kept / (double) Math.max(1, openBlocks); + } + + @FunctionalInterface + private interface ColumnTest { + boolean holds(int x, int z); + } + + private static int columns(CarvedArea open, ColumnTest where) { + int count = 0; + for (int x = 0; x < open.size; x++) { + for (int z = 0; z < open.size; z++) { + if (where.holds(x, z) && openColumn(open, x, z) > 0) { + count++; + } + } + } + return Math.max(1, count); + } + + private static int openColumn(CarvedArea open, int x, int z) { + int carved = 0; + for (int y = 0; y < CarvedArea.LAYERS; y++) { + if (open.carved.get(open.index(x, y, z))) { + carved++; + } + } + return carved; + } + + /** Columns where pillars keep some, but not all, of the blocks the open cavern carves. */ + private static int partlyKeptColumns(CarvedArea open, CarvedArea pillared, ColumnTest where) { + int partly = 0; + for (int x = 0; x < open.size; x++) { + for (int z = 0; z < open.size; z++) { + if (!where.holds(x, z)) { + continue; + } + int kept = 0; + int carvedOpen = 0; + for (int y = 0; y < CarvedArea.LAYERS; y++) { + int block = open.index(x, y, z); + if (!open.carved.get(block)) { + continue; + } + carvedOpen++; + if (!pillared.carved.get(block)) { + kept++; + } + } + if (kept > 0 && kept < carvedOpen) { + partly++; + } + } + } + return partly; + } + + /** Share of carved blocks with rock beside them: rougher walls have more. */ + private static double wallShare(CarvedArea area) { + long walls = 0; + for (int block = area.carved.nextSetBit(0); block >= 0; block = area.carved.nextSetBit(block + 1)) { + int x = area.x(block); + int y = area.y(block); + int z = area.z(block); + if (x == 0 || z == 0 || y == 0 || x == area.size - 1 || z == area.size - 1 || y == CarvedArea.LAYERS - 1) { + continue; + } + if (!area.carved.get(area.index(x + 1, y, z)) || !area.carved.get(area.index(x - 1, y, z)) + || !area.carved.get(area.index(x, y + 1, z)) || !area.carved.get(area.index(x, y - 1, z)) + || !area.carved.get(area.index(x, y, z + 1)) || !area.carved.get(area.index(x, y, z - 1))) { + walls++; + } + } + return walls / (double) Math.max(1, area.carved.cardinality()); + } +} diff --git a/core/src/test/java/art/arcane/iris/modules/carve/field/NaturePlanetCavesTest.java b/core/src/test/java/art/arcane/iris/modules/carve/field/NaturePlanetCavesTest.java new file mode 100644 index 000000000..61bfad9ec --- /dev/null +++ b/core/src/test/java/art/arcane/iris/modules/carve/field/NaturePlanetCavesTest.java @@ -0,0 +1,87 @@ +package art.arcane.iris.modules.carve.field; + +import art.arcane.iris.core.modules.CarveTestWorld; +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.modules.carve.Cave; +import com.volmit.noise.NoiseFactory; +import org.junit.Test; + +import java.util.Arrays; +import java.util.BitSet; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * The four caves of piexel's natureplanet pack, as their files are written, carve block for block what they carved + * when every cave key was one number for the whole world. Carved in a world from Y -64 to 320 under a flat surface. + */ +public class NaturePlanetCavesTest { + private static final int CHUNKS = 8; + private static final int SIZE = CHUNKS * 16; + private static final int WORLD_BOTTOM_Y = -64; + private static final int WORLD_HEIGHT = 384; + private static final int SURFACE_WORLD_Y = 100; + private static final int SURFACE_Y = SURFACE_WORLD_Y - WORLD_BOTTOM_Y; + private static final long SEED = 91_277L; + + private record Pinned(String name, String cave, int carved, int hash) { + } + + private static final List NATUREPLANET = List.of( + new Pinned("caverns", """ + {"cavern": {"size": 56, "height": 22, "coverage": 0.07}, + "depth": {"min": -20, "max": 200}, "fade": 16, "surfaceClearance": 12} + """, 96_055, -382_152_706), + new Pinned("crawlways", """ + {"tunnel": { + "width": {"min": 2, "max": 3, "style": {"style": "SIMPLEX", "zoom": 1.2}}, + "spacing": {"horizontal": 64, "vertical": 53}, + "warp": {"style": "SIMPLEX", "zoom": 0.25, "multiplier": 8}, + "coverage": {"share": 0.4, "style": {"style": "SIMPLEX", "zoom": 2.4}}}, + "surfaceClearance": 6} + """, 8_329, 1_344_334_684), + new Pinned("deep-halls", """ + {"cavern": {"size": 110, "height": 40, "coverage": 0.18, "pillars": {"spacing": 26, "thickness": 5}}, + "depth": {"min": -64, "max": 10}, "fade": 14, "surfaceClearance": 16} + """, 273_203, 1_962_467_619), + new Pinned("tunnels", """ + {"tunnel": { + "width": {"min": 4, "max": 7, "style": {"style": "SIMPLEX", "zoom": 1.8}}, + "spacing": {"horizontal": 96, "vertical": 69}, + "warp": {"style": "SIMPLEX", "zoom": 0.4, "multiplier": 11.5}, + "coverage": {"share": 0.8, "style": {"style": "SIMPLEX", "zoom": 3.6}}}, + "opensToSurface": true} + """, 76_608, -1_422_091_570)); + + private final NoiseFactory noise = new CarveTestWorld().resources().noise(); + + @Test + public void natureplanetCavesCarveWhatTheyCarvedWithOneNumberPerKey() { + for (Pinned pinned : NATUREPLANET) { + BitSet carved = carve(pinned.cave(), 0, 0); + + assertEquals(pinned.name(), pinned.carved(), carved.cardinality()); + assertEquals(pinned.name(), pinned.hash(), carved.hashCode()); + } + } + + private BitSet carve(String caveJson, int offsetX, int offsetZ) { + CaveCarver carver = new CaveCarver(TestSettings.of(Cave.class, caveJson), noise, SEED, WORLD_BOTTOM_Y, WORLD_HEIGHT); + int[] surfaceY = new int[256]; + Arrays.fill(surfaceY, SURFACE_Y); + double[] weight = new double[256]; + Arrays.fill(weight, 1D); + boolean[] sealed = new boolean[256]; + BitSet carved = new BitSet(SIZE * SIZE * (SURFACE_Y + 1)); + for (int chunkX = 0; chunkX < CHUNKS; chunkX++) { + for (int chunkZ = 0; chunkZ < CHUNKS; chunkZ++) { + int originX = chunkX * 16; + int originZ = chunkZ * 16; + carver.carve(offsetX + originX, offsetZ + originZ, surfaceY, weight, sealed, + (localX, y, localZ) -> carved.set((y * SIZE * SIZE) + ((originZ + localZ) * SIZE) + originX + localX)); + } + } + return carved; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 63695431b..ace97fd43 100644 --- a/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -28,6 +28,7 @@ import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.modules.carve.CaveList; import art.arcane.iris.modules.carve.CaveResources; import art.arcane.iris.modules.carve.CaveScenes; +import art.arcane.iris.modules.carve.CaveValidator; import art.arcane.iris.modules.carve.UpperDimensionCarvingSettings; import art.arcane.iris.modules.terrain.TerrainPalettes; import art.arcane.iris.engine.mantle.components.CarveWorld; @@ -77,6 +78,7 @@ public final class CarveModule implements IrisModule { log = setup.log(); var registry = setup.registry(); registry.registerResourceKind(CaveResources.CAVES); + registry.registerValidator(new CaveValidator()); setup.tooling().registerView(new CaveScenes()); List.of(CaveList.class, CarvingSettings.class, CarvingEnabledSettings.class, CarvingBiomeSettings.class, CaveDepthSettings.class, CaveLavaHeightSettings.class, UpperDimensionCarvingSettings.class) diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java index 1aa8688be..2bf3c83db 100644 --- a/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java @@ -224,7 +224,7 @@ public final class ProceduralValue { private static final double DEFAULT_TO = 1; @Override - public ProceduralValue read(Object json) { + public ProceduralValue read(Object json, JsonForms.Parts parts) { return new ProceduralValue(json, formOf(json)); } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/Cave.java b/module/src/main/java/art/arcane/iris/modules/carve/Cave.java index 40195a6cc..43176faa8 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/Cave.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/Cave.java @@ -18,21 +18,28 @@ package art.arcane.iris.modules.carve; +import art.arcane.iris.modules.carve.CaveValue.Bounds; import com.volmit.config.Desc; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import com.volmit.config.Range; import com.volmit.config.ResourceRef; import com.volmit.world.PackBiome; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; /** * One kind of cave, a file of a pack's {@code caves/} folder that dimensions, regions and biomes list under {@code caves}. - * It carves tunnels, caverns or both, within a depth range and under the surface rules it sets. + * It carves tunnels, caverns or both, within a depth range and under the surface rules it sets. Every number that + * shapes the cave is a {@link CaveValue}, so it may vary across the world. */ @Desc("One kind of cave: tunnels, caverns or both, with where they may occur.") public final class Cave { + /** Without a style, a value of the whole cave changes over about this many blocks. */ + public static final int VALUE_CHANGE_BLOCKS = 256; + private static final Bounds FADE_BLOCKS = new Bounds(0, 128); + private static final Bounds SURFACE_CLEARANCE_BLOCKS = new Bounds(0, 128); + private static final Bounds CEILING_FADE_BLOCKS = new Bounds(0, 128); + @Desc("Winding tunnels. Leave out for a cave without tunnels.") private CaveTunnel tunnel; @@ -40,17 +47,19 @@ public final class Cave { private CaveCavern cavern; @Desc("World Y range this cave occurs in. Leave out to allow every height.") - private Range depth; + private CaveDepth depth; - @MinNumber(0) - @MaxNumber(128) - @Desc("Blocks over which the cave narrows to nothing at both ends of its depth range.") - private int fade = 12; + @Desc("Blocks over which the cave narrows to nothing at both ends of its depth range, 0 to 128. A range changes over about " + + VALUE_CHANGE_BLOCKS + " blocks.") + private CaveValue fade = CaveValue.of(12); - @MinNumber(0) - @MaxNumber(128) - @Desc("Blocks of rock kept between the cave and the surface. Ignored when opensToSurface is set.") - private int surfaceClearance = 8; + @Desc("Blocks of rock kept between the cave and the surface, 0 to 128. Ignored when opensToSurface is set. A range changes over about " + + VALUE_CHANGE_BLOCKS + " blocks.") + private CaveValue surfaceClearance = CaveValue.of(8); + + @Desc("Blocks over which the cave closes under the rock it keeps, instead of ending in a flat ceiling, 0 to 128. Ignored where it opens to the surface. A range changes over about " + + VALUE_CHANGE_BLOCKS + " blocks.") + private CaveValue ceilingFade = CaveValue.of(8); @Desc("Let the cave cut through the surface, which makes entrances wherever it reaches the top.") private boolean opensToSurface = false; @@ -70,18 +79,22 @@ public final class Cave { return Optional.ofNullable(cavern); } - public Optional depth() { + public Optional depth() { return Optional.ofNullable(depth); } - public int fade() { + public CaveValue fade() { return fade; } - public int surfaceClearance() { + public CaveValue surfaceClearance() { return surfaceClearance; } + public CaveValue ceilingFade() { + return ceilingFade; + } + public boolean opensToSurface() { return opensToSurface; } @@ -89,4 +102,15 @@ public final class Cave { public String biome() { return biome == null ? "" : biome; } + + /** Each value of the cave outside the numbers its key allows, such as {@code fade is 200; it must be at most 128}. */ + public List valuesOutOfBounds() { + List problems = new ArrayList<>(); + fade.requireWithin(FADE_BLOCKS, "fade", problems); + surfaceClearance.requireWithin(SURFACE_CLEARANCE_BLOCKS, "surfaceClearance", problems); + ceilingFade.requireWithin(CEILING_FADE_BLOCKS, "ceilingFade", problems); + tunnel().ifPresent(caveTunnel -> caveTunnel.requireValuesWithinBounds("tunnel", problems)); + cavern().ifPresent(caveCavern -> caveCavern.requireValuesWithinBounds("cavern", problems)); + return problems; + } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveCavern.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveCavern.java index 4d96bb56c..150953355 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/CaveCavern.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveCavern.java @@ -18,30 +18,36 @@ package art.arcane.iris.modules.carve; +import art.arcane.iris.modules.carve.CaveValue.Bounds; import com.volmit.config.Desc; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; import com.volmit.noise.NoiseStyle; +import java.util.List; import java.util.Optional; /** The caverns of a {@link Cave}: large open rooms, with pillars left standing in them where the cave asks for some. */ @Desc("Large open rooms.") public final class CaveCavern { - @MinNumber(16) - @MaxNumber(512) - @Desc("Rough span of a room in blocks.") - private int size = 56; + /** Without a style, a value of the caverns or their pillars changes over this many room sizes. */ + public static final int VALUE_CHANGE_SIZES = 4; + private static final Bounds SIZE_BLOCKS = new Bounds(16, 512); + private static final Bounds HEIGHT_BLOCKS = new Bounds(8, 256); + private static final Bounds COVERAGE_SHARE = new Bounds(0, 0.6); + private static final Bounds ROUGHNESS = new Bounds(0, 1); - @MinNumber(8) - @MaxNumber(256) - @Desc("Rough height of a room in blocks.") - private int height = 22; + @Desc("Rough span of a room in blocks, 16 to 512. A range changes over about " + VALUE_CHANGE_SIZES + " room sizes.") + private CaveValue size = CaveValue.of(56); - @MinNumber(0) - @MaxNumber(0.6) - @Desc("Share of the underground that is cavern. 0.1 gives scattered rooms, 0.3 joins them into halls.") - private double coverage = 0.1; + @Desc("Rough height of a room in blocks, 8 to 256. A range changes over about " + VALUE_CHANGE_SIZES + " room sizes.") + private CaveValue height = CaveValue.of(22); + + @Desc("Share of the underground that is cavern, 0 to 0.6. 0.1 gives scattered rooms, 0.3 joins them into halls. A range changes over about " + + VALUE_CHANGE_SIZES + " room sizes; a min of 0 leaves areas without rooms. A range in size, height or roughness makes the share approximate.") + private CaveValue coverage = CaveValue.of(0.1); + + @Desc("Strength of the finer noise on room walls, 0 to 1. 0 gives smooth bubbles. Ignored with a style, and in rooms under about 20 blocks tall or across. A range changes over about " + + VALUE_CHANGE_SIZES + " room sizes.") + private CaveValue roughness = CaveValue.of(0.3); @Desc("Noise that shapes the rooms. Scaled to size and height, so its zoom has no effect; a fracture stays in blocks. Detail under about 12 blocks is lost. Leave out for smooth rooms with rough walls.") private NoiseStyle style; @@ -57,19 +63,31 @@ public final class CaveCavern { return Optional.ofNullable(style); } - public int size() { + public CaveValue size() { return size; } - public int height() { + public CaveValue height() { return height; } - public double coverage() { + public CaveValue coverage() { return coverage; } + public CaveValue roughness() { + return roughness; + } + public Optional pillars() { return Optional.ofNullable(pillars); } + + void requireValuesWithinBounds(String path, List problems) { + size.requireWithin(SIZE_BLOCKS, path + ".size", problems); + height.requireWithin(HEIGHT_BLOCKS, path + ".height", problems); + coverage.requireWithin(COVERAGE_SHARE, path + ".coverage", problems); + roughness.requireWithin(ROUGHNESS, path + ".roughness", problems); + pillars().ifPresent(cavernPillars -> cavernPillars.requireValuesWithinBounds(path + ".pillars", problems)); + } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveDepth.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveDepth.java new file mode 100644 index 000000000..d6e3e0217 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveDepth.java @@ -0,0 +1,42 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import com.volmit.config.Desc; + +/** The world Y range a {@link Cave} occurs in. Either end may vary across the world. */ +@Desc("World Y range a cave occurs in.") +public final class CaveDepth { + @Desc("Lowest world Y. A range changes over about " + Cave.VALUE_CHANGE_BLOCKS + " blocks.") + private CaveValue min = CaveValue.of(16); + + @Desc("Highest world Y. A range changes over about " + Cave.VALUE_CHANGE_BLOCKS + " blocks.") + private CaveValue max = CaveValue.of(32); + + public CaveDepth() { + } + + public CaveValue min() { + return min; + } + + public CaveValue max() { + return max; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CavePillars.java b/module/src/main/java/art/arcane/iris/modules/carve/CavePillars.java index 4d3104718..01e0ef2b7 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/CavePillars.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/CavePillars.java @@ -18,36 +18,35 @@ package art.arcane.iris.modules.carve; +import art.arcane.iris.modules.carve.CaveValue.Bounds; import com.volmit.config.Desc; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; import com.volmit.noise.NoiseStyle; +import java.util.List; import java.util.Optional; -import java.util.OptionalInt; /** The pillars of a {@link CaveCavern}: columns of rock left standing from floor to ceiling. */ @Desc("Rock columns left standing inside caverns.") public final class CavePillars { - @MinNumber(6) - @MaxNumber(256) - @Desc("Rough distance between pillars in blocks.") - private int spacing = 22; + private static final Bounds SPACING_BLOCKS = new Bounds(6, 256); + private static final Bounds THICKNESS_BLOCKS = new Bounds(1, 64); + private static final Bounds FLARE = new Bounds(1, 16); + private static final Bounds VERTICAL_BLOCKS = new Bounds(8, 512); - @MinNumber(1) - @MaxNumber(64) - @Desc("Rough thickness of a pillar at its middle, in blocks. Pillars widen towards floor and ceiling.") - private int thickness = 4; + @Desc("Rough distance between pillars in blocks, 6 to 256. A range changes over about " + CaveCavern.VALUE_CHANGE_SIZES + " room sizes.") + private CaveValue spacing = CaveValue.of(22); - @MinNumber(1) - @MaxNumber(16) - @Desc("How many times more ground a pillar covers at floor and ceiling than at its middle. 1 gives straight columns.") - private double flare = 4; + @Desc("Rough thickness of a pillar at its middle, in blocks, 1 to 64. Pillars widen towards floor and ceiling. A range changes over about " + + CaveCavern.VALUE_CHANGE_SIZES + " room sizes.") + private CaveValue thickness = CaveValue.of(4); - @MinNumber(8) - @MaxNumber(512) - @Desc("Blocks over which the pillars change with height, so they lean, pinch and break off. Detail under about 12 blocks is lost. Leave out for columns that run straight from floor to ceiling.") - private Integer vertical; + @Desc("How many times more ground a pillar covers at floor and ceiling than at its middle, 1 to 16. 1 gives straight columns. A range changes over about " + + CaveCavern.VALUE_CHANGE_SIZES + " room sizes.") + private CaveValue flare = CaveValue.of(4); + + @Desc("Blocks over which the pillars change with height, 8 to 512, so they lean, pinch and break off. Detail under about 12 blocks is lost. A range changes over about " + + CaveCavern.VALUE_CHANGE_SIZES + " room sizes. Leave out for columns that run straight from floor to ceiling.") + private CaveValue vertical; @Desc("Noise that places the pillars. Scaled to spacing, so its zoom has no effect; a fracture stays in blocks. Leave out for evenly scattered pillars.") private NoiseStyle style; @@ -55,13 +54,13 @@ public final class CavePillars { public CavePillars() { } - public double flare() { + public CaveValue flare() { return flare; } /** Blocks over which the pillars change with height; empty for pillars that run straight. */ - public OptionalInt vertical() { - return vertical == null ? OptionalInt.empty() : OptionalInt.of(vertical); + public Optional vertical() { + return Optional.ofNullable(vertical); } /** The noise that places the pillars; empty where the pack wrote none. */ @@ -69,11 +68,18 @@ public final class CavePillars { return Optional.ofNullable(style); } - public int spacing() { + public CaveValue spacing() { return spacing; } - public int thickness() { + public CaveValue thickness() { return thickness; } + + void requireValuesWithinBounds(String path, List problems) { + spacing.requireWithin(SPACING_BLOCKS, path + ".spacing", problems); + thickness.requireWithin(THICKNESS_BLOCKS, path + ".thickness", problems); + flare.requireWithin(FLARE, path + ".flare", problems); + vertical().ifPresent(blocks -> blocks.requireWithin(VERTICAL_BLOCKS, path + ".vertical", problems)); + } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnel.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnel.java index 132cc357d..0609edef2 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnel.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnel.java @@ -18,29 +18,30 @@ package art.arcane.iris.modules.carve; +import art.arcane.iris.modules.carve.CaveValue.Bounds; import com.volmit.config.Desc; -import com.volmit.config.Range; import com.volmit.config.Required; import com.volmit.noise.NoiseStyle; -import com.volmit.noise.StyledRange; +import java.util.List; import java.util.Optional; /** The tunnels of a {@link Cave}: long winding passages. Thin ones link other caves together. */ @Desc("Long winding passages.") public final class CaveTunnel { - private static final Range DEFAULT_WIDTH = Range.of(4, 7); - /** - * The style a styled range gets when the pack writes none: white noise, which would make a tunnel's width jump - * block by block. A width with this style follows the default width noise instead. - */ - private static final NoiseStyle STYLE_OF_A_RANGE_WRITTEN_WITHOUT_ONE = NoiseStyle.of("STATIC"); + /** Without a style, the width changes over this many horizontal spacings. */ + public static final double WIDTH_CHANGE_SPACINGS = 1.5D; + /** Without a style, any other value of the tunnels changes over this many horizontal spacings. */ + public static final int VALUE_CHANGE_SPACINGS = 6; + private static final Bounds WIDTH_BLOCKS = new Bounds(1, 64); + private static final Bounds HEIGHT_BLOCKS = new Bounds(1, 64); + private static final Bounds VERTICAL_WARP_SHARE = new Bounds(0, 1); - @Desc("Tunnel width in blocks. The style picks where a tunnel is narrow or wide; leave it out for a slow change that scales with spacing.") - private StyledRange width; + @Desc("Tunnel width in blocks, 1 to 64. A range changes over about " + WIDTH_CHANGE_SPACINGS + " horizontal spacings.") + private CaveValue width = CaveValue.between(4, 7); - @Desc("Tunnel height in blocks, low where the tunnel is narrow and tall where it is wide. Leave out for round tunnels.") - private Range height; + @Desc("Tunnel height in blocks, 1 to 64. A range without a style follows the width: low where the tunnel is narrow, tall where it is wide. Leave out for round tunnels.") + private CaveValue height; @Required @Desc("Blocks between neighbouring tunnels.") @@ -49,26 +50,23 @@ public final class CaveTunnel { @Desc("Noise that bends the tunnels: zoom sets how often they turn, multiplier how many blocks they swing. A flat style keeps them straight. Leave out for a gentle bend that scales with spacing.") private NoiseStyle warp; - @Desc("Where tunnels occur. Leave out to put them everywhere.") + @Desc("How far the warp moves tunnels up and down, as a share of how far it swings them sideways, 0 to 1. 0 adds no rise and fall. A range changes over about " + + VALUE_CHANGE_SPACINGS + " horizontal spacings.") + private CaveValue verticalWarp = CaveValue.of(0.5); + + @Desc("Where tunnels occur: a share of the underground from 0 to 1, or {share, softness, style}. Softness, 0 to 1, is how gradually tunnels thin out at the edge of an area, from abrupt dead ends to long tails; style is the noise that shapes the areas. Share and softness change over about " + + VALUE_CHANGE_SPACINGS + " horizontal spacings as a range. Leave out to put tunnels everywhere.") private CaveTunnelCoverage coverage; public CaveTunnel() { } - public Range width() { - return width == null ? DEFAULT_WIDTH : Range.of(width.min(), width.max()); + public CaveValue width() { + return width; } - /** The noise that picks the width along a tunnel; empty where the pack wrote none. */ - public Optional widthStyle() { - if (width == null || width.style().equals(STYLE_OF_A_RANGE_WRITTEN_WITHOUT_ONE)) { - return Optional.empty(); - } - return Optional.of(width.style()); - } - - /** The height range of an oval tunnel; empty for a round one. */ - public Optional height() { + /** The height of an oval tunnel; empty for a round one. */ + public Optional height() { return Optional.ofNullable(height); } @@ -81,7 +79,18 @@ public final class CaveTunnel { return Optional.ofNullable(warp); } + public CaveValue verticalWarp() { + return verticalWarp; + } + public CaveTunnelCoverage coverage() { - return coverage == null ? new CaveTunnelCoverage() : coverage; + return coverage == null ? CaveTunnelCoverage.EVERYWHERE : coverage; + } + + void requireValuesWithinBounds(String path, List problems) { + width.requireWithin(WIDTH_BLOCKS, path + ".width", problems); + height().ifPresent(tunnelHeight -> tunnelHeight.requireWithin(HEIGHT_BLOCKS, path + ".height", problems)); + verticalWarp.requireWithin(VERTICAL_WARP_SHARE, path + ".verticalWarp", problems); + coverage().requireValuesWithinBounds(path + ".coverage", problems); } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnelCoverage.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnelCoverage.java index d9284db8d..13a49521a 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnelCoverage.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnelCoverage.java @@ -18,33 +18,103 @@ package art.arcane.iris.modules.carve; +import art.arcane.iris.modules.carve.CaveValue.Bounds; import com.volmit.config.Desc; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; +import com.volmit.config.JsonForms; import com.volmit.noise.NoiseStyle; +import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; -/** Where the tunnels of a {@link CaveTunnel} occur: the share of the underground that has them, in patches a noise shapes. */ -@Desc("Where tunnels occur.") +/** + * Where the tunnels of a {@link CaveTunnel} occur: the share of the underground that has them, in areas a noise shapes, + * and how gradually they thin out at the edge of an area. Written as the share alone, {@code 0.4}, or as + * {@code {"share": 0.4, "softness": 0.3, "style": {...}}} with each member optional. + */ +@Desc("Where tunnels occur: a share, or {share, softness, style}.") +@JsonForms(CaveTunnelCoverage.Forms.class) public final class CaveTunnelCoverage { - @MinNumber(0) - @MaxNumber(1) - @Desc("Share of the underground that has tunnels. 1 puts them everywhere, lower leaves areas without any.") - private double share = 1; + /** The softness that thins tunnels out over the same stretch they always did before softness was a key. */ + public static final double DEFAULT_SOFTNESS = 0.3D; + static final CaveTunnelCoverage EVERYWHERE = new CaveTunnelCoverage(1D, CaveValue.of(1), CaveValue.of(DEFAULT_SOFTNESS), null); + private static final Bounds SHARE = new Bounds(0, 1); + private static final Bounds SOFTNESS = new Bounds(0, 1); - @Desc("Noise that shapes the areas with tunnels. Leave out for patches that scale with spacing.") - private NoiseStyle style; + private final Object written; + private final CaveValue share; + private final CaveValue softness; + private final NoiseStyle style; - public CaveTunnelCoverage() { + private CaveTunnelCoverage(Object written, CaveValue share, CaveValue softness, NoiseStyle style) { + this.written = written; + this.share = share; + this.softness = softness; + this.style = style; } - public double share() { + /** Share of the underground that has tunnels, from 0 to 1. */ + public CaveValue share() { return share; } + /** How gradually tunnels thin out at the edge of an area, from 0 for abrupt ends to 1 for long tails. */ + public CaveValue softness() { + return softness; + } + /** The noise that shapes the areas with tunnels; empty where the pack wrote none. */ public Optional style() { return Optional.ofNullable(style); } + + void requireValuesWithinBounds(String path, List problems) { + share.requireWithin(SHARE, path + "." + Forms.SHARE, problems); + softness.requireWithin(SOFTNESS, path + "." + Forms.SOFTNESS, problems); + } + + @Override + public String toString() { + return String.valueOf(written); + } + + /** Reads the forms a pack writes and writes a coverage back exactly as it was read. */ + static final class Forms implements JsonForms.Codec { + static final String SHARE = "share"; + static final String SOFTNESS = "softness"; + static final String STYLE = "style"; + private static final Set MEMBERS = Set.of(SHARE, SOFTNESS, STYLE); + + @Override + public CaveTunnelCoverage read(Object json, JsonForms.Parts parts) { + return switch (json) { + case Number number -> new CaveTunnelCoverage(json, CaveValue.of(number.doubleValue()), EVERYWHERE.softness, null); + case Map object -> spelledOut(object, parts); + default -> throw new IllegalArgumentException("A tunnel coverage is a share or {share, softness, style}, not " + json); + }; + } + + @Override + public Object write(CaveTunnelCoverage value) { + return value.written; + } + + private static CaveTunnelCoverage spelledOut(Map object, JsonForms.Parts parts) { + for (Object member : object.keySet()) { + if (!MEMBERS.contains(member)) { + throw new IllegalArgumentException("A tunnel coverage has share, softness and style, not " + member); + } + } + CaveValue share = valueOrDefault(object.get(SHARE), EVERYWHERE.share, parts); + CaveValue softness = valueOrDefault(object.get(SOFTNESS), EVERYWHERE.softness, parts); + Object writtenStyle = object.get(STYLE); + NoiseStyle style = writtenStyle == null ? null : parts.read(writtenStyle, NoiseStyle.class); + return new CaveTunnelCoverage(object, share, softness, style); + } + + private static CaveValue valueOrDefault(Object written, CaveValue fallback, JsonForms.Parts parts) { + return written == null ? fallback : parts.read(written, CaveValue.class); + } + } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveValidator.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveValidator.java new file mode 100644 index 000000000..0fed9cfc7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveValidator.java @@ -0,0 +1,45 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import com.volmit.resource.ResourceId; +import com.volmit.validation.Problem; +import com.volmit.validation.Subject; +import com.volmit.validation.ValidationContext; +import com.volmit.validation.Validator; + +/** + * Module {@code iris:carve}'s check of a pack's caves: every value lies within the numbers its key allows. A + * {@link CaveValue} is not a plain number, so the host's own bounds check cannot see it. + */ +public final class CaveValidator implements Validator { + private static final String JSON_EXTENSION = ".json"; + + @Override + public void validate(ValidationContext pack) { + for (ResourceId id : pack.resources().ids(CaveResources.CAVES)) { + Cave cave = CaveResources.cave(pack.resources(), id); + if (cave == null) { + continue; + } + Subject file = Subject.file(CaveResources.CAVES.folder() + "/" + id.path() + JSON_EXTENSION); + cave.valuesOutOfBounds().forEach(problem -> pack.report(Problem.error(file, problem))); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveValue.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveValue.java new file mode 100644 index 000000000..12f5095a4 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveValue.java @@ -0,0 +1,164 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import com.volmit.config.Desc; +import com.volmit.config.JsonForms; +import com.volmit.noise.NoiseStyle; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * A number that shapes how a cave looks, which may vary across the world: {@code 5} everywhere, + * {@code {"min": 3, "max": 9}} picked by a smooth noise the cave chooses for the key, or + * {@code {"min": 3, "max": 9, "style": {...}}} picked by that style, its zoom as written. The noise's low end gives + * min and its high end max. + */ +@Desc("A number, or {min, max} that varies across the world; add a style to decide where.") +@JsonForms(CaveValue.Forms.class) +public final class CaveValue { + private final Object written; + private final double min; + private final double max; + private final NoiseStyle style; + + private CaveValue(Object written, double min, double max, NoiseStyle style) { + this.written = written; + this.min = min; + this.max = max; + this.style = style; + } + + public static CaveValue of(double value) { + return new CaveValue(value, value, value, null); + } + + public static CaveValue between(double min, double max) { + return new CaveValue(Map.of(Forms.MIN, min, Forms.MAX, max), min, max, null); + } + + /** Whether the value differs from place to place; a plain number, or a min equal to max, does not. */ + public boolean varies() { + return min != max; + } + + /** The value where the noise is lowest; the value everywhere when it does not vary. */ + public double min() { + return min; + } + + /** The value where the noise is highest. */ + public double max() { + return max; + } + + public double middle() { + return (min + max) / 2D; + } + + public double lowest() { + return Math.min(min, max); + } + + public double highest() { + return Math.max(min, max); + } + + /** The noise the pack chose to pick the value; empty where it wrote none and the cave picks a smooth one. */ + public Optional style() { + return Optional.ofNullable(style); + } + + /** Adds to {@code problems} each end of the value outside {@code bounds}, naming it {@code path} as written. */ + void requireWithin(Bounds bounds, String path, List problems) { + if (!varies()) { + requireWithin(bounds, path, min, problems); + return; + } + requireWithin(bounds, path + "." + Forms.MIN, min, problems); + requireWithin(bounds, path + "." + Forms.MAX, max, problems); + } + + private static void requireWithin(Bounds bounds, String path, double value, List problems) { + if (value < bounds.least()) { + problems.add(path + " is " + shortNumber(value) + "; it must be at least " + shortNumber(bounds.least())); + } else if (value > bounds.most()) { + problems.add(path + " is " + shortNumber(value) + "; it must be at most " + shortNumber(bounds.most())); + } + } + + private static String shortNumber(double value) { + return value == Math.rint(value) ? Long.toString((long) value) : Double.toString(value); + } + + @Override + public String toString() { + return String.valueOf(written); + } + + /** The numbers a key allows, both included. */ + record Bounds(double least, double most) { + } + + /** Reads the forms a pack writes and writes a value back exactly as it was read. */ + static final class Forms implements JsonForms.Codec { + static final String MIN = "min"; + static final String MAX = "max"; + static final String STYLE = "style"; + private static final Set MEMBERS = Set.of(MIN, MAX, STYLE); + + @Override + public CaveValue read(Object json, JsonForms.Parts parts) { + return switch (json) { + case Number number -> new CaveValue(json, number.doubleValue(), number.doubleValue(), null); + case Map object -> varying(object, parts); + default -> throw new IllegalArgumentException("A cave value is a number or {min, max} with an optional style, not " + json); + }; + } + + @Override + public Object write(CaveValue value) { + return value.written; + } + + private static CaveValue varying(Map object, JsonForms.Parts parts) { + for (Object member : object.keySet()) { + if (!MEMBERS.contains(member)) { + throw new IllegalArgumentException("A varying cave value has min, max and style, not " + member); + } + } + if (!object.containsKey(MIN) || !object.containsKey(MAX)) { + throw new IllegalArgumentException("A varying cave value needs both min and max: " + object); + } + Object writtenStyle = object.get(STYLE); + NoiseStyle style = writtenStyle == null ? null : parts.read(writtenStyle, NoiseStyle.class); + return new CaveValue(object, number(object.get(MIN), MIN), number(object.get(MAX), MAX), style); + } + + private static double number(Object written, String name) { + if (written instanceof Number number) { + return number.doubleValue(); + } + throw new IllegalArgumentException(name + " needs a number, not " + written); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CaveCarver.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveCarver.java index 0cf611006..800857ffe 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/field/CaveCarver.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveCarver.java @@ -19,11 +19,14 @@ package art.arcane.iris.modules.carve.field; import art.arcane.iris.modules.carve.Cave; -import com.volmit.config.Range; +import art.arcane.iris.modules.carve.CaveDepth; +import art.arcane.iris.modules.carve.CaveValue; +import art.arcane.iris.modules.carve.field.CaveLimits.Columns; import com.volmit.noise.NoiseFactory; import com.volmit.resource.ResourceId; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -31,15 +34,17 @@ import java.util.List; * the heights it may carve at. Heights count from the dimension's bottom. Safe to use from several threads at once. */ public final class CaveCarver { - private static final int CHUNK_COLUMNS = 256; /** Caves stay this far above the dimension's bottom, clear of the bedrock floor. */ private static final int ROCK_KEPT_ABOVE_BOTTOM_BLOCKS = 5; private final List shapes = new ArrayList<>(); - private final int depthMinY; - private final int depthMaxY; - private final int fadeBlocks; - private final int surfaceClearance; + private final int worldBottomY; + private final int worldHeight; + private final ValueField depthMin; + private final ValueField depthMax; + private final ValueField fade; + private final ValueField surfaceClearance; + private final ValueField ceilingFade; private final boolean opensToSurface; /** @@ -49,16 +54,21 @@ public final class CaveCarver { */ public CaveCarver(Cave cave, NoiseFactory noise, long seed, int worldBottomY, int worldHeight) { CaveNoise caveNoise = new CaveNoise(noise, seed); + this.worldBottomY = worldBottomY; + this.worldHeight = worldHeight; + CaveDepth depth = cave.depth().orElse(null); + this.depthMin = depth == null ? ValueField.constant(worldBottomY) : caveValue(depth.min(), caveNoise, "depth.min"); + this.depthMax = depth == null ? ValueField.constant(worldBottomY + worldHeight - 1) : caveValue(depth.max(), caveNoise, "depth.max"); + this.fade = caveValue(cave.fade(), caveNoise, "fade"); + this.surfaceClearance = caveValue(cave.surfaceClearance(), caveNoise, "surfaceClearance"); + this.ceilingFade = caveValue(cave.ceilingFade(), caveNoise, "ceilingFade"); + this.opensToSurface = cave.opensToSurface(); cave.tunnel().ifPresent(tunnel -> shapes.add(new PartShape(CavePart.TUNNEL, new TunnelShape(caveNoise, tunnel)))); cave.cavern().ifPresent(cavern -> shapes.add(new PartShape(CavePart.CAVERN, new CavernShape(caveNoise, cavern)))); - Range depth = cave.depth().orElse(null); - int lowest = depth == null ? 0 : (int) Math.floor(Math.min(depth.min(), depth.max())) - worldBottomY; - int highest = depth == null ? worldHeight - 1 : (int) Math.ceil(Math.max(depth.min(), depth.max())) - worldBottomY; - this.depthMinY = Math.max(ROCK_KEPT_ABOVE_BOTTOM_BLOCKS, lowest); - this.depthMaxY = Math.min(worldHeight - 1, highest); - this.fadeBlocks = Math.max(0, cave.fade()); - this.surfaceClearance = Math.max(0, cave.surfaceClearance()); - this.opensToSurface = cave.opensToSurface(); + } + + private static ValueField caveValue(CaveValue value, CaveNoise caveNoise, String name) { + return ValueField.inColumns(value, caveNoise, name, Cave.VALUE_CHANGE_BLOCKS); } /** The seed the cave with id {@code cave} carves with in a world whose carve seed is {@code carveSeed}. */ @@ -77,10 +87,10 @@ public final class CaveCarver { /** {@link #carve}, telling the sink which part carved each block. A block two parts carve is reported for each. */ public void carveByPart(int originX, int originZ, int[] surfaceY, double[] columnWeight, boolean[] sealed, PartSink sink) { - if (shapes.isEmpty() || depthMaxY < depthMinY) { + if (shapes.isEmpty()) { return; } - CaveLimits limits = limitsOf(surfaceY, columnWeight, sealed); + CaveLimits limits = limitsOf(originX, originZ, surfaceY, columnWeight, sealed); if (limits.carvesNothing()) { return; } @@ -111,13 +121,49 @@ public final class CaveCarver { carveByPart(originX, originZ, surfaceY, columnWeight, sealed, (part, localX, y, localZ) -> sink.carve(localX, y, localZ)); } - private CaveLimits limitsOf(int[] surfaceY, double[] columnWeight, boolean[] sealed) { - int[] columnTopY = new int[CHUNK_COLUMNS]; - boolean[] columnOpens = new boolean[CHUNK_COLUMNS]; - for (int column = 0; column < CHUNK_COLUMNS; column++) { - columnOpens[column] = opensToSurface && !sealed[column]; - columnTopY[column] = columnOpens[column] ? surfaceY[column] : surfaceY[column] - surfaceClearance; + private CaveLimits limitsOf(int originX, int originZ, int[] surfaceY, double[] columnWeight, boolean[] sealed) { + Columns columns = Columns.of(columnWeight); + fillBlocks(fade, originX, originZ, columns.fadeBlocks()); + fillBlocks(ceilingFade, originX, originZ, columns.ceilingFadeBlocks()); + boolean depthVaries = depthMin.varies() || depthMax.varies(); + int constantClearance = surfaceClearanceAt(originX, originZ); + int constantDepthMinY = depthMinYAt(originX, originZ); + int constantDepthMaxY = depthMaxYAt(originX, originZ); + for (int column = 0; column < CaveLimits.CHUNK_COLUMNS; column++) { + double x = originX + (column >> 4); + double z = originZ + (column & 15); + columns.depthMinY()[column] = depthVaries ? depthMinYAt(x, z) : constantDepthMinY; + columns.depthMaxY()[column] = depthVaries ? depthMaxYAt(x, z) : constantDepthMaxY; + boolean opens = opensToSurface && !sealed[column]; + columns.opensToSurface()[column] = opens; + int clearance = surfaceClearance.varies() ? surfaceClearanceAt(x, z) : constantClearance; + columns.topY()[column] = opens ? surfaceY[column] : surfaceY[column] - clearance; } - return new CaveLimits(depthMinY, depthMaxY, fadeBlocks, columnTopY, columnOpens, columnWeight); + return new CaveLimits(columns); + } + + /** Fills {@code blocks} with the value in each column of the chunk, at least 0. */ + private static void fillBlocks(ValueField value, int originX, int originZ, double[] blocks) { + if (!value.varies()) { + Arrays.fill(blocks, Math.max(0D, value.min())); + return; + } + for (int column = 0; column < CaveLimits.CHUNK_COLUMNS; column++) { + blocks[column] = Math.max(0D, value.at(originX + (column >> 4), originZ + (column & 15))); + } + } + + private int depthMinYAt(double x, double z) { + double lowest = Math.min(depthMin.at(x, z), depthMax.at(x, z)); + return Math.max(ROCK_KEPT_ABOVE_BOTTOM_BLOCKS, (int) Math.floor(lowest) - worldBottomY); + } + + private int depthMaxYAt(double x, double z) { + double highest = Math.max(depthMin.at(x, z), depthMax.at(x, z)); + return Math.min(worldHeight - 1, (int) Math.ceil(highest) - worldBottomY); + } + + private int surfaceClearanceAt(double x, double z) { + return (int) Math.round(Math.max(0D, surfaceClearance.at(x, z))); } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CaveLimits.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveLimits.java index ea6a6cda5..73add625d 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/field/CaveLimits.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveLimits.java @@ -18,72 +18,99 @@ package art.arcane.iris.modules.carve.field; +import java.util.Arrays; + /** * Where one cave may carve in one chunk, and how freely: fully inside its depth range and well under the surface, * narrowing to nothing towards the ends of the range, towards the rock it keeps under the surface and towards columns * that do not list it. Columns are indexed as {@code (localX << 4) | localZ}; heights count from the dimension's bottom. */ -public final class CaveLimits { - private static final int CHUNK_COLUMNS = 256; +final class CaveLimits { + static final int CHUNK_COLUMNS = 256; private static final int CELL_COLUMNS = ChunkLattice.CELLS_PER_CHUNK_AXIS * ChunkLattice.CELLS_PER_CHUNK_AXIS; - /** A cave that keeps rock above it closes over this many blocks instead of ending in a flat ceiling. */ - private static final int CEILING_FADE_BLOCKS = 8; - private final int lowestY; - private final int highestY; + private final int[] depthMinYs; + private final int[] depthMaxYs; + private final double[] fadeBlocks; + private final double[] ceilingFadeBlocks; + private final int[] topY; + private final boolean[] opensToSurface; + private final double[] weight; + /** Whether depth and fades are the same in every column, as they are for plain numbers; then they are read once. */ + private final boolean sameRangeInEveryColumn; private final int depthMinY; private final int depthMaxY; - private final int fadeBlocks; - private final int[] columnTopY; - private final boolean[] columnOpensToSurface; - private final double[] columnWeight; + private final double fade; + private final double ceilingFade; + private final int lowestY; + private final int highestY; private final int[] cellTopY = new int[CELL_COLUMNS]; private final boolean[] cellHasWeight = new boolean[CELL_COLUMNS]; /** - * @param depthMinY lowest height of the cave's depth range - * @param depthMaxY highest height of the cave's depth range - * @param fadeBlocks blocks over which the cave narrows at both ends of the range - * @param columnTopY highest height the cave may carve in each column - * @param columnOpensToSurface whether the cave reaches its top at full width in each column, instead of closing under it - * @param columnWeight how much each column lists the cave, from 0 to 1 + * What the cave allows in each column of the chunk. + * + * @param depthMinY lowest height of the cave's depth range + * @param depthMaxY highest height of the cave's depth range + * @param fadeBlocks blocks over which the cave narrows at both ends of the range + * @param topY highest height the cave may carve + * @param opensToSurface whether the cave reaches its top at full width, instead of closing under it + * @param ceilingFadeBlocks blocks over which a cave that does not open to the surface closes under its top + * @param weight how much the column lists the cave, from 0 to 1 */ - public CaveLimits(int depthMinY, int depthMaxY, int fadeBlocks, int[] columnTopY, boolean[] columnOpensToSurface, double[] columnWeight) { - this.depthMinY = depthMinY; - this.depthMaxY = depthMaxY; - this.fadeBlocks = fadeBlocks; - this.columnTopY = columnTopY; - this.columnOpensToSurface = columnOpensToSurface; - this.columnWeight = columnWeight; - java.util.Arrays.fill(cellTopY, Integer.MIN_VALUE); - int highestTopY = Integer.MIN_VALUE; + record Columns(int[] depthMinY, int[] depthMaxY, double[] fadeBlocks, int[] topY, boolean[] opensToSurface, + double[] ceilingFadeBlocks, double[] weight) { + static Columns of(double[] weight) { + return new Columns(new int[CHUNK_COLUMNS], new int[CHUNK_COLUMNS], new double[CHUNK_COLUMNS], new int[CHUNK_COLUMNS], + new boolean[CHUNK_COLUMNS], new double[CHUNK_COLUMNS], weight); + } + } + + CaveLimits(Columns columns) { + this.depthMinYs = columns.depthMinY(); + this.depthMaxYs = columns.depthMaxY(); + this.fadeBlocks = columns.fadeBlocks(); + this.ceilingFadeBlocks = columns.ceilingFadeBlocks(); + this.topY = columns.topY(); + this.opensToSurface = columns.opensToSurface(); + this.weight = columns.weight(); + this.sameRangeInEveryColumn = isTheSameInEveryColumn(depthMinYs) && isTheSameInEveryColumn(depthMaxYs) + && isTheSameInEveryColumn(fadeBlocks) && isTheSameInEveryColumn(ceilingFadeBlocks); + this.depthMinY = depthMinYs[0]; + this.depthMaxY = depthMaxYs[0]; + this.fade = fadeBlocks[0]; + this.ceilingFade = ceilingFadeBlocks[0]; + Arrays.fill(cellTopY, Integer.MIN_VALUE); + int lowest = Integer.MAX_VALUE; + int highest = Integer.MIN_VALUE; for (int column = 0; column < CHUNK_COLUMNS; column++) { - if (columnWeight[column] <= 0D) { + if (columns.weight()[column] <= 0D) { continue; } int cell = cellOf(column >> 4, column & 15); cellHasWeight[cell] = true; - cellTopY[cell] = Math.max(cellTopY[cell], columnTopY[column]); - highestTopY = Math.max(highestTopY, columnTopY[column]); + cellTopY[cell] = Math.max(cellTopY[cell], topY[column]); + lowest = Math.min(lowest, depthMinYs[column]); + highest = Math.max(highest, Math.min(depthMaxYs[column], topY[column])); } - this.lowestY = depthMinY; - this.highestY = Math.min(depthMaxY, highestTopY); + this.lowestY = lowest; + this.highestY = highest; } private static int cellOf(int localX, int localZ) { return ((localX / ChunkLattice.CELL_BLOCKS) * ChunkLattice.CELLS_PER_CHUNK_AXIS) + (localZ / ChunkLattice.CELL_BLOCKS); } - public int lowestY() { + int lowestY() { return lowestY; } - public int highestY() { + int highestY() { return highestY; } /** Whether the cave carves nothing in this chunk. */ - public boolean carvesNothing() { + boolean carvesNothing() { return highestY < lowestY; } @@ -95,26 +122,51 @@ public final class CaveLimits { /** How freely the cave carves the block, from 0 (not at all) to 1 (at its full size). */ double openness(int column, int y) { - double weight = columnWeight[column]; - if (weight <= 0D || y < depthMinY || y > depthMaxY) { + if (sameRangeInEveryColumn) { + return openness(column, y, depthMinY, depthMaxY, fade, ceilingFade); + } + return openness(column, y, depthMinYs[column], depthMaxYs[column], fadeBlocks[column], ceilingFadeBlocks[column]); + } + + private double openness(int column, int y, int columnDepthMinY, int columnDepthMaxY, double columnFade, double columnCeilingFade) { + double columnWeight = weight[column]; + if (columnWeight <= 0D || y < columnDepthMinY || y > columnDepthMaxY) { return 0D; } - int belowTop = columnTopY[column] - y; + int belowTop = topY[column] - y; if (belowTop < 0) { return 0D; } - double openness = weight * easeIn(Math.min(y - depthMinY, depthMaxY - y), fadeBlocks); - if (!columnOpensToSurface[column]) { - openness *= easeIn(belowTop, CEILING_FADE_BLOCKS); + double openness = columnWeight * easeIn(Math.min(y - columnDepthMinY, columnDepthMaxY - y), columnFade); + if (!opensToSurface[column]) { + openness *= easeIn(belowTop, columnCeilingFade); } return openness; } - private static double easeIn(int distance, int fadeBlocks) { - if (fadeBlocks <= 0 || distance >= fadeBlocks) { + private static boolean isTheSameInEveryColumn(int[] values) { + for (int column = 1; column < values.length; column++) { + if (values[column] != values[0]) { + return false; + } + } + return true; + } + + private static boolean isTheSameInEveryColumn(double[] values) { + for (int column = 1; column < values.length; column++) { + if (values[column] != values[0]) { + return false; + } + } + return true; + } + + private static double easeIn(int distance, double fadeBlocks) { + if (fadeBlocks <= 0D || distance >= fadeBlocks) { return 1D; } - double share = distance / (double) fadeBlocks; + double share = distance / fadeBlocks; return share * share * (3D - (2D * share)); } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CaveNoise.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveNoise.java index c3491aa9a..dd302adc0 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/field/CaveNoise.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveNoise.java @@ -40,6 +40,7 @@ final class CaveNoise { /** A pack style is rescaled until its measured feature spacing is within this share of the one asked for. */ private static final double SCALING_TOLERANCE = 0.1D; private static final int MOST_SCALING_ROUNDS = 6; + private static final long NAME_SEED_MIX = 0x9E3779B97F4A7C15L; private static final Field3 LEVEL = (x, y, z) -> 0D; private final NoiseFactory noise; @@ -51,6 +52,14 @@ final class CaveNoise { this.seed = seed; } + /** + * The fields of one named value of the cave, seeded by the name: a value that varies takes no seed from the + * cave's own fields, so writing a range anywhere leaves every other field of the cave where it was. + */ + CaveNoise named(String name) { + return new CaveNoise(noise, seed ^ (name.hashCode() * NAME_SEED_MIX)); + } + /** How much a field with this spacing typically changes over one block. */ static double typicalSlope(double spacing) { return SIMPLEX_SLOPE_TIMES_SPACING / spacing; @@ -77,6 +86,24 @@ final class CaveNoise { return (x, y, z) -> (base.at(x, y, z) + (detail.at(x, y, z) * detailWeight)) * normalization; } + /** {@link #detailed} with a detail weight that may vary from place to place. */ + Field3 detailed(double spacing, double verticalSpacing, ValueField detailWeight) { + if (!detailWeight.varies()) { + return detailed(spacing, verticalSpacing, detailWeight.min()); + } + Field3 base = smooth(spacing, verticalSpacing); + double detailSpacing = spacing / DETAIL_SHRINK; + double detailVerticalSpacing = verticalSpacing / DETAIL_SHRINK; + if (Math.min(detailSpacing, detailVerticalSpacing) < MIN_DETAIL_SPACING_BLOCKS) { + return base; + } + Field3 detail = smooth(detailSpacing, detailVerticalSpacing); + return (x, y, z) -> { + double weight = detailWeight.at(x, y, z); + return (base.at(x, y, z) + (detail.at(x, y, z) * weight)) / (1D + weight); + }; + } + /** A field that only varies over X and Z, changing sign about every {@code spacing} blocks. */ Field3 columns(double spacing) { NoiseSampler sampler = nextSampler(NoiseStyle.of(STYLE)); @@ -94,6 +121,16 @@ final class CaveNoise { return sampler::signed; } + /** {@link #inBlocks} for a field that only varies over X and Z. */ + Field3 columnsInBlocks(NoiseStyle style) { + if (style.isFlat()) { + nextSeed(); + return LEVEL; + } + NoiseSampler sampler = nextSampler(style); + return (x, y, z) -> sampler.signed(x, z); + } + /** A pack's style rescaled so its features lie about {@code spacing} blocks apart horizontally and {@code verticalSpacing} vertically. */ Field3 scaledTo(NoiseStyle style, double spacing, double verticalSpacing) { if (style.isFlat()) { diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CavernShape.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CavernShape.java index ac6b61308..17f43ad43 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/field/CavernShape.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CavernShape.java @@ -28,14 +28,15 @@ import com.volmit.noise.NoiseStyle; * The pillar field varies only across X and Z unless the pack lets pillars change with height; then it is read in 3D * on the lattice, and a pillar whose field fades out mid-room narrows and breaks off, leaving stubs that flare into * floor and ceiling. + * + *

A value that varies moves the threshold it sets point by point: the lattice then carries the room field less its + * threshold, and the pillar thresholds, so blocks interpolate them like any field. A plain number keeps them constant. */ final class CavernShape extends LatticeShape { private static final int ROOMS = 0; - private static final int PILLARS = 1; + private static final int NOT_READ = -1; /** A room is the part of a feature above the threshold, which is narrower than the feature itself. */ private static final double FEATURE_BLOCKS_PER_ROOM_BLOCK = 1.6D; - /** A finer layer keeps room walls from looking like smooth bubbles. */ - private static final double WALL_DETAIL = 0.3D; /** Closing a cavern takes a little more than its most open spot, so nothing is left at the very edge of its limits. */ private static final double CLOSING_MARGIN = 1.1D; /** Pillars are two features apart: one peak, one trough. */ @@ -43,65 +44,135 @@ final class CavernShape extends LatticeShape { private static final double LARGEST_PILLAR_AREA_SHARE = 0.3D; private static final double NO_PILLAR = 0D; private static final double FULL_PILLAR = 1D; + /** Where the threshold is worked out at the lattice points, a block subtracts nothing more. */ + private static final double THRESHOLD_WORKED_OUT_AT_POINTS = 0D; private final Field3 rooms; + private final FieldStats roomStats; + private final ValueField coverage; private final double threshold; private final double mostOpen; private final Field3 pillars; private final boolean pillarsChangeWithHeight; + private final FieldStats pillarStats; + private final ValueField pillarSpacing; + private final ValueField pillarThickness; + private final ValueField pillarFlare; + private final boolean pillarSizeVaries; private final double pillarMiddle; private final double pillarFoot; + private final int mostOpenField; + private final int pillarField; + private final int pillarMiddleField; + private final int pillarFootField; + private final int fieldCount; CavernShape(CaveNoise noise, CaveCavern cavern) { - double span = cavern.size() * FEATURE_BLOCKS_PER_ROOM_BLOCK; - double height = cavern.height() * FEATURE_BLOCKS_PER_ROOM_BLOCK; - this.rooms = cavern.style() - .map(style -> noise.scaledTo(style, span, height)) - .orElseGet(() -> noise.detailed(span, height, WALL_DETAIL)); - FieldStats stats = FieldStats.measure(rooms, span); - this.threshold = stats.valueAboveShare(cavern.coverage()); - this.mostOpen = Math.max(0D, stats.highest() - threshold); + double valueChangeBlocks = cavern.size().middle() * CaveCavern.VALUE_CHANGE_SIZES; + ValueField size = ValueField.inBlocks(cavern.size(), noise, "cavern.size", valueChangeBlocks); + ValueField height = ValueField.inColumns(cavern.height(), noise, "cavern.height", valueChangeBlocks); + ValueField roughness = ValueField.inBlocks(cavern.roughness(), noise, "cavern.roughness", valueChangeBlocks); + this.coverage = ValueField.inBlocks(cavern.coverage(), noise, "cavern.coverage", valueChangeBlocks); + this.rooms = roomField(noise, cavern, size, height, roughness); + this.roomStats = FieldStats.measure(rooms, size.middle() * FEATURE_BLOCKS_PER_ROOM_BLOCK); + this.threshold = coverage.varies() ? THRESHOLD_WORKED_OUT_AT_POINTS : roomStats.valueAboveShare(coverage.min()); + this.mostOpen = Math.max(0D, roomStats.highest() - threshold); + int nextField = ROOMS + 1; + this.mostOpenField = coverage.varies() ? nextField++ : NOT_READ; if (cavern.pillars().isEmpty()) { this.pillars = null; this.pillarsChangeWithHeight = false; + this.pillarStats = null; + this.pillarSpacing = null; + this.pillarThickness = null; + this.pillarFlare = null; + this.pillarSizeVaries = false; this.pillarMiddle = Double.POSITIVE_INFINITY; this.pillarFoot = Double.POSITIVE_INFINITY; + this.pillarField = NOT_READ; + this.pillarMiddleField = NOT_READ; + this.pillarFootField = NOT_READ; + this.fieldCount = nextField; return; } CavePillars settings = cavern.pillars().get(); - double featureBlocks = settings.spacing() * PILLAR_FEATURES_PER_SPACING; + this.pillarSpacing = ValueField.inColumns(settings.spacing(), noise, "cavern.pillars.spacing", valueChangeBlocks); + this.pillarThickness = ValueField.inColumns(settings.thickness(), noise, "cavern.pillars.thickness", valueChangeBlocks); + this.pillarFlare = ValueField.inColumns(settings.flare(), noise, "cavern.pillars.flare", valueChangeBlocks); + this.pillarSizeVaries = pillarSpacing.varies() || pillarThickness.varies() || pillarFlare.varies(); this.pillarsChangeWithHeight = settings.vertical().isPresent(); - this.pillars = pillarField(noise, settings, featureBlocks); - FieldStats pillarStats = FieldStats.measure(pillars, featureBlocks); - double middleAreaShare = Math.min(LARGEST_PILLAR_AREA_SHARE, pillarAreaShare(settings)); - this.pillarMiddle = pillarStats.valueAboveShare(middleAreaShare); - this.pillarFoot = pillarStats.valueAboveShare(Math.min(1D, middleAreaShare * settings.flare())); + ValueField vertical = settings.vertical() + .map(value -> ValueField.inColumns(value, noise, "cavern.pillars.vertical", valueChangeBlocks)) + .orElseGet(() -> ValueField.constant(0D)); + this.pillars = pillarField(noise, settings, pillarSpacing, vertical); + this.pillarStats = FieldStats.measure(pillars, pillarSpacing.middle() * PILLAR_FEATURES_PER_SPACING); + this.pillarMiddle = pillarSizeVaries ? Double.NaN : pillarMiddleAt(0D, 0D); + this.pillarFoot = pillarSizeVaries ? Double.NaN : pillarFootAt(0D, 0D); + this.pillarField = pillarsChangeWithHeight ? nextField++ : NOT_READ; + boolean thresholdsAtPoints = pillarsChangeWithHeight && pillarSizeVaries; + this.pillarMiddleField = thresholdsAtPoints ? nextField++ : NOT_READ; + this.pillarFootField = thresholdsAtPoints ? nextField++ : NOT_READ; + this.fieldCount = nextField; } - private static Field3 pillarField(CaveNoise noise, CavePillars settings, double featureBlocks) { + private static Field3 roomField(CaveNoise noise, CaveCavern cavern, ValueField size, ValueField height, ValueField roughness) { + NoiseStyle style = cavern.style().orElse(null); + return VaryingScale.of(noise, size, height, "cavern.rooms", (fieldNoise, roomSize, roomHeight) -> { + double span = roomSize * FEATURE_BLOCKS_PER_ROOM_BLOCK; + double featureHeight = roomHeight * FEATURE_BLOCKS_PER_ROOM_BLOCK; + return style == null ? fieldNoise.detailed(span, featureHeight, roughness) : fieldNoise.scaledTo(style, span, featureHeight); + }); + } + + private static Field3 pillarField(CaveNoise noise, CavePillars settings, ValueField spacing, ValueField vertical) { NoiseStyle style = settings.style().orElse(null); - if (settings.vertical().isEmpty()) { - return style == null ? noise.columns(featureBlocks) : noise.columnsScaledTo(style, featureBlocks); - } - double vertical = settings.vertical().getAsInt(); - return style == null ? noise.smooth(featureBlocks, vertical) : noise.scaledTo(style, featureBlocks, vertical); + boolean straight = settings.vertical().isEmpty(); + return VaryingScale.of(noise, spacing, vertical, "cavern.pillars", (fieldNoise, pillarSpacing, verticalBlocks) -> { + double featureBlocks = pillarSpacing * PILLAR_FEATURES_PER_SPACING; + if (straight) { + return style == null ? fieldNoise.columns(featureBlocks) : fieldNoise.columnsScaledTo(style, featureBlocks); + } + return style == null ? fieldNoise.smooth(featureBlocks, verticalBlocks) : fieldNoise.scaledTo(style, featureBlocks, verticalBlocks); + }); } - private static double pillarAreaShare(CavePillars pillars) { - double radius = pillars.thickness() / 2D; - return (Math.PI * radius * radius) / ((double) pillars.spacing() * pillars.spacing()); + /** The pillar field value above which a column is the middle of a pillar. */ + private double pillarMiddleAt(double x, double z) { + return pillarStats.valueAboveShare(middleAreaShareAt(x, z)); + } + + /** The pillar field value above which a column is on the foot a pillar widens into towards floor and ceiling. */ + private double pillarFootAt(double x, double z) { + return pillarStats.valueAboveShare(Math.min(1D, middleAreaShareAt(x, z) * pillarFlare.at(x, z))); + } + + private double middleAreaShareAt(double x, double z) { + double radius = pillarThickness.at(x, z) / 2D; + double spacing = pillarSpacing.at(x, z); + return Math.min(LARGEST_PILLAR_AREA_SHARE, (Math.PI * radius * radius) / (spacing * spacing)); } @Override protected int fieldCount() { - return pillarsChangeWithHeight ? 2 : 1; + return fieldCount; } @Override protected void readFields(int x, int y, int z, double[] values) { - values[ROOMS] = rooms.at(x, y, z); - if (pillarsChangeWithHeight) { - values[PILLARS] = pillars.at(x, y, z); + double room = rooms.at(x, y, z); + if (mostOpenField == NOT_READ) { + values[ROOMS] = room; + } else { + double pointThreshold = roomStats.valueAboveShare(coverage.at(x, y, z)); + values[ROOMS] = room - pointThreshold; + values[mostOpenField] = Math.max(0D, roomStats.highest() - pointThreshold); + } + if (pillarField != NOT_READ) { + values[pillarField] = pillars.at(x, y, z); + } + if (pillarMiddleField != NOT_READ) { + values[pillarMiddleField] = pillarMiddleAt(x, z); + values[pillarFootField] = pillarFootAt(x, z); } } @@ -112,7 +183,8 @@ final class CavernShape extends LatticeShape { @Override protected boolean carvesAt(Pass pass, double shareX, double shareY, double shareZ, double openness, int column) { - double open = pass.cell(ROOMS).at(shareX, shareY, shareZ) - threshold - ((1D - openness) * mostOpen * CLOSING_MARGIN); + double mostOpenHere = mostOpenField == NOT_READ ? mostOpen : pass.cell(mostOpenField).at(shareX, shareY, shareZ); + double open = pass.cell(ROOMS).at(shareX, shareY, shareZ) - threshold - ((1D - openness) * mostOpenHere * CLOSING_MARGIN); if (open <= 0D) { return false; } @@ -120,9 +192,17 @@ final class CavernShape extends LatticeShape { return true; } double strength = pillarsChangeWithHeight - ? pillarStrength(pass.cell(PILLARS).at(shareX, shareY, shareZ)) + ? pointPillarStrength(pass, shareX, shareY, shareZ) : columnPillarStrength(pass, column); - return open > strength * mostOpen; + return open > strength * mostOpenHere; + } + + private double pointPillarStrength(Pass pass, double shareX, double shareY, double shareZ) { + double value = pass.cell(pillarField).at(shareX, shareY, shareZ); + if (pillarMiddleField == NOT_READ) { + return pillarStrength(value, pillarMiddle, pillarFoot); + } + return pillarStrength(value, pass.cell(pillarMiddleField).at(shareX, shareY, shareZ), pass.cell(pillarFootField).at(shareX, shareY, shareZ)); } /** {@link #pillarStrength} of a straight pillar, read once per column of the chunk. */ @@ -132,22 +212,26 @@ final class CavernShape extends LatticeShape { if (!Double.isNaN(known)) { return known; } - double value = pillars.at(pass.lattice().originX() + (column >> 4), 0D, pass.lattice().originZ() + (column & 15)); - double strength = pillarStrength(value); + double x = pass.lattice().originX() + (column >> 4); + double z = pass.lattice().originZ() + (column & 15); + double value = pillars.at(x, 0D, z); + double strength = pillarSizeVaries + ? pillarStrength(value, pillarMiddleAt(x, z), pillarFootAt(x, z)) + : pillarStrength(value, pillarMiddle, pillarFoot); strengths[column] = strength; return strength; } /** How strongly a pillar field value is a pillar: 0 outside one, 1 in its middle, in between on the foot it widens into. */ - private double pillarStrength(double value) { - if (value >= pillarMiddle) { + private static double pillarStrength(double value, double middle, double foot) { + if (value >= middle) { return FULL_PILLAR; } - double footWidth = pillarMiddle - pillarFoot; + double footWidth = middle - foot; if (footWidth <= 0D) { return NO_PILLAR; } - double intoPillar = Math.max(0D, Math.min(1D, (value - pillarFoot) / footWidth)); + double intoPillar = Math.max(0D, Math.min(1D, (value - foot) / footWidth)); return intoPillar * intoPillar; } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/TunnelShape.java b/module/src/main/java/art/arcane/iris/modules/carve/field/TunnelShape.java index 105d25abd..5002bbc47 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/field/TunnelShape.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/TunnelShape.java @@ -20,7 +20,7 @@ package art.arcane.iris.modules.carve.field; import art.arcane.iris.modules.carve.CaveTunnel; import art.arcane.iris.modules.carve.CaveTunnelCoverage; -import com.volmit.config.Range; +import art.arcane.iris.modules.carve.CaveValue; import com.volmit.noise.NoiseStyle; /** @@ -37,8 +37,7 @@ import com.volmit.noise.NoiseStyle; */ final class TunnelShape extends LatticeShape { private static final int SHEETS = 3; - private static final int WIDTH = SHEETS; - private static final int PRESENCE = SHEETS + 1; + private static final int NOT_READ = -1; private static final int[] PAIR_FIRST = {0, 0, 1}; private static final int[] PAIR_SECOND = {1, 2, 2}; private static final int PAIRS = PAIR_FIRST.length; @@ -63,15 +62,17 @@ final class TunnelShape extends LatticeShape { private static final double DEFAULT_WARP_SHARE_OF_SPACING = 0.06D; private static final double DEFAULT_WARPS_PER_SPACING = 3D; private static final double SMALLEST_DEFAULT_WARP_SPACING_BLOCKS = 16D; - /** A warp moves a path up and down this share of how far it moves it sideways. */ - private static final double VERTICAL_WARP_SHARE = 0.5D; - /** Without a width style, the width changes over this many horizontal spacings. */ - private static final double DEFAULT_WIDTH_CHANGE_SPACINGS = 1.5D; - private static final double WIDTH_SPREAD = 1D; /** Without a coverage style, the areas with tunnels are this many horizontal spacings across. */ private static final double DEFAULT_PRESENCE_SPACINGS = 3D; - /** Field value over which tunnels widen from nothing to full size at the edge of an area that has them. */ - private static final double PRESENCE_EDGE = 0.15D; + /** + * Field value over which tunnels widen from nothing to full size at the edge of an area that has them, at a + * softness of 1. A softness of 0 still keeps the least edge, so the share never divides by zero. + */ + private static final double SOFTEST_PRESENCE_EDGE = 0.5D; + private static final double LEAST_PRESENCE_EDGE = 0.005D; + /** Where the share of an area's tunnels is worked out at the lattice points, a block divides by nothing and subtracts nothing. */ + private static final double PRESENCE_WORKED_OUT_AT_POINTS = 0D; + private static final double EDGE_WORKED_OUT_AT_POINTS = 1D; /** A tunnel narrower or lower than this is not a passage any more, so it ends instead. */ private static final double NARROWEST_RADIUS_BLOCKS = 1D; /** A cell's slope is an average, so a cell is only ruled out when the line is clearly further than the widest tunnel. */ @@ -89,22 +90,46 @@ final class TunnelShape extends LatticeShape { private final Field3 warpY; private final Field3 warpZ; private final double warpBlocks; + private final ValueField verticalWarp; private final Field3 width; - private final Field3 presence; - private final double presenceThreshold; private final double narrowRadius; private final double wideRadius; + private final TunnelHeight heightKind; private final boolean oval; private final double lowRadius; private final double tallRadius; + private final ValueField height; + private final Field3 presence; + private final FieldStats presenceStats; + private final ValueField presenceShare; + private final ValueField presenceSoftness; + private final boolean presenceWorkedOutAtPoints; + private final double presenceThreshold; + private final double presenceEdge; + private final int widthField; + private final int heightField; + private final int presenceField; + private final int fieldCount; private final double leastSteepness; + /** How tall a tunnel is against how wide. */ + private enum TunnelHeight { + /** As tall as it is wide. */ + ROUND, + /** Between its low and tall height, as far as it is between its narrow and wide width. */ + FOLLOWS_WIDTH, + /** The height its own noise picks. */ + OWN_NOISE + } + TunnelShape(CaveNoise noise, CaveTunnel tunnel) { double spacing = tunnel.spacing().horizontal(); double verticalSpacing = tunnel.spacing().vertical(); + double valueChangeBlocks = spacing * CaveTunnel.VALUE_CHANGE_SPACINGS; for (int sheet = 0; sheet < SHEETS; sheet++) { sheets[sheet] = noise.smooth(spacing, verticalSpacing); } + this.verticalWarp = ValueField.inBlocks(tunnel.verticalWarp(), noise, "tunnel.verticalWarp", valueChangeBlocks); NoiseStyle warp = tunnel.warp().orElse(null); if (warp == null) { double warpSpacing = Math.max(SMALLEST_DEFAULT_WARP_SPACING_BLOCKS, spacing / DEFAULT_WARPS_PER_SPACING); @@ -118,42 +143,91 @@ final class TunnelShape extends LatticeShape { this.warpZ = noise.inBlocks(warp); this.warpBlocks = warp.isFlat() ? 0D : warp.multiplier() / 2D; } - double widthChangeSpacing = spacing * DEFAULT_WIDTH_CHANGE_SPACINGS; - this.width = tunnel.widthStyle().map(noise::inBlocks).orElseGet(() -> noise.smooth(widthChangeSpacing, widthChangeSpacing)); - Range widthRange = tunnel.width(); - this.narrowRadius = Math.min(widthRange.min(), widthRange.max()) / 2D; - this.wideRadius = Math.max(widthRange.min(), widthRange.max()) / 2D; - Range height = tunnel.height().orElse(null); - this.oval = height != null; - this.lowRadius = oval ? Math.min(height.min(), height.max()) / 2D : 0D; - this.tallRadius = oval ? Math.max(height.min(), height.max()) / 2D : 0D; + CaveValue widthValue = tunnel.width(); + double widthChangeBlocks = spacing * CaveTunnel.WIDTH_CHANGE_SPACINGS; + this.width = widthValue.style().map(noise::inBlocks).orElseGet(() -> noise.smooth(widthChangeBlocks, widthChangeBlocks)); + this.narrowRadius = widthValue.lowest() / 2D; + this.wideRadius = widthValue.highest() / 2D; + CaveValue heightValue = tunnel.height().orElse(null); + this.heightKind = heightKindOf(heightValue); + this.oval = heightKind != TunnelHeight.ROUND; + this.lowRadius = heightValue == null ? 0D : heightValue.lowest() / 2D; + this.tallRadius = heightValue == null ? 0D : heightValue.highest() / 2D; + this.height = heightKind == TunnelHeight.OWN_NOISE + ? ValueField.inBlocks(heightValue, noise, "tunnel.height", widthChangeBlocks) + : null; double leastSlope = CaveNoise.typicalSlope(spacing) * LEAST_SLOPE_SHARE; this.leastSteepness = leastSlope * leastSlope; CaveTunnelCoverage coverage = tunnel.coverage(); - if (coverage.share() >= 1D) { + this.presenceShare = ValueField.inBlocks(coverage.share(), noise, "tunnel.coverage.share", valueChangeBlocks); + this.presenceSoftness = ValueField.inBlocks(coverage.softness(), noise, "tunnel.coverage.softness", valueChangeBlocks); + this.presenceWorkedOutAtPoints = presenceShare.varies() || presenceSoftness.varies(); + boolean heightReadsTheWidthNoise = heightKind == TunnelHeight.FOLLOWS_WIDTH && heightValue.varies(); + boolean readsWidth = widthValue.varies() || heightReadsTheWidthNoise; + this.widthField = readsWidth ? SHEETS : NOT_READ; + int nextField = readsWidth ? SHEETS + 1 : SHEETS; + this.heightField = height == null ? NOT_READ : nextField++; + if (presenceShare.lowest() >= 1D) { this.presence = null; + this.presenceStats = null; this.presenceThreshold = Double.NEGATIVE_INFINITY; + this.presenceEdge = EDGE_WORKED_OUT_AT_POINTS; + this.presenceField = NOT_READ; + this.fieldCount = nextField; return; } double presenceSpacing = spacing * DEFAULT_PRESENCE_SPACINGS; NoiseStyle presenceStyle = coverage.style().orElse(null); this.presence = presenceStyle == null ? noise.smooth(presenceSpacing, presenceSpacing) : noise.inBlocks(presenceStyle); double presenceFeatureBlocks = presenceStyle == null ? presenceSpacing : CaveNoise.featureBlocks(presence, presenceStyle); - this.presenceThreshold = FieldStats.measure(presence, presenceFeatureBlocks).valueAboveShare(coverage.share()); + this.presenceStats = FieldStats.measure(presence, presenceFeatureBlocks); + this.presenceThreshold = presenceWorkedOutAtPoints ? PRESENCE_WORKED_OUT_AT_POINTS : presenceStats.valueAboveShare(presenceShare.min()); + this.presenceEdge = presenceWorkedOutAtPoints ? EDGE_WORKED_OUT_AT_POINTS : presenceEdgeOf(presenceSoftness.min()); + this.presenceField = nextField++; + this.fieldCount = nextField; + } + + private static TunnelHeight heightKindOf(CaveValue height) { + if (height == null) { + return TunnelHeight.ROUND; + } + return height.varies() && height.style().isPresent() ? TunnelHeight.OWN_NOISE : TunnelHeight.FOLLOWS_WIDTH; + } + + private static double presenceEdgeOf(double softness) { + return Math.max(LEAST_PRESENCE_EDGE, softness * SOFTEST_PRESENCE_EDGE); } @Override protected int fieldCount() { - return presence == null ? SHEETS + 1 : SHEETS + 2; + return fieldCount; } @Override protected void readFields(int x, int y, int z, double[] values) { readSheets(x, y, z, values); - values[WIDTH] = width.at(x, y, z); - if (presence != null) { - values[PRESENCE] = presence.at(x, y, z); + if (widthField != NOT_READ) { + values[widthField] = width.at(x, y, z); } + if (heightField != NOT_READ) { + values[heightField] = height.at(x, y, z); + } + if (presenceField != NOT_READ) { + values[presenceField] = presenceAt(x, y, z); + } + } + + /** + * The presence field, or where share or softness vary, how far into an area with tunnels the point lies in + * edges: the threshold and edge are only known point by point then. + */ + private double presenceAt(int x, int y, int z) { + double value = presence.at(x, y, z); + if (!presenceWorkedOutAtPoints) { + return value; + } + double threshold = presenceStats.valueAboveShare(presenceShare.at(x, y, z)); + return (value - threshold) / presenceEdgeOf(presenceSoftness.at(x, y, z)); } private void readSheets(int x, int y, int z, double[] values) { @@ -164,7 +238,7 @@ final class TunnelShape extends LatticeShape { return; } double warpedX = x + (warpX.at(x, y, z) * warpBlocks); - double warpedY = y + (warpY.at(x, y, z) * warpBlocks * VERTICAL_WARP_SHARE); + double warpedY = y + (warpY.at(x, y, z) * warpBlocks * verticalWarp.at(x, y, z)); double warpedZ = z + (warpZ.at(x, y, z) * warpBlocks); for (int sheet = 0; sheet < SHEETS; sheet++) { values[sheet] = sheets[sheet].at(warpedX, warpedY, warpedZ); @@ -173,7 +247,7 @@ final class TunnelShape extends LatticeShape { @Override protected boolean mayCarveIn(Pass pass) { - if (presence != null && pass.cell(PRESENCE).highest() <= presenceThreshold) { + if (presence != null && pass.cell(presenceField).highest() <= presenceThreshold) { return false; } double reach = Math.max(wideRadius, tallRadius) * CELL_REACH_SLACK; @@ -252,7 +326,7 @@ final class TunnelShape extends LatticeShape { if (!oval) { return isWithinRoundTunnel(pass, shareX, shareY, shareZ, radius); } - double heightRadius = ((lowRadius + ((tallRadius - lowRadius) * widthShare)) * sizeShare) * openness; + double heightRadius = (fullHeightRadiusAt(pass, shareX, shareY, shareZ, widthShare) * sizeShare) * openness; if (heightRadius < NARROWEST_RADIUS_BLOCKS) { return false; } @@ -307,8 +381,20 @@ final class TunnelShape extends LatticeShape { + (terms[offset + SECOND_SQUARED] * second * second); } + /** How far between its narrow and its wide width the tunnel is at the block, from 0 to 1; 0 where the width is fixed. */ private double widthShareAt(Pass pass, double shareX, double shareY, double shareZ) { - return clampToShare(0.5D + (pass.cell(WIDTH).at(shareX, shareY, shareZ) * WIDTH_SPREAD)); + if (widthField == NOT_READ) { + return 0D; + } + return ValueField.shareAt(pass.cell(widthField).at(shareX, shareY, shareZ)); + } + + /** Half the height of an oval tunnel at the block, before it narrows at the edges of its areas and limits. */ + private double fullHeightRadiusAt(Pass pass, double shareX, double shareY, double shareZ, double widthShare) { + if (heightKind == TunnelHeight.OWN_NOISE) { + return pass.cell(heightField).at(shareX, shareY, shareZ) / 2D; + } + return lowRadius + ((tallRadius - lowRadius) * widthShare); } /** How far the block lies into an area with tunnels: 1 inside, falling to 0 over the edge. */ @@ -316,7 +402,7 @@ final class TunnelShape extends LatticeShape { if (presence == null) { return 1D; } - return clampToShare((pass.cell(PRESENCE).at(shareX, shareY, shareZ) - presenceThreshold) / PRESENCE_EDGE); + return clampToShare((pass.cell(presenceField).at(shareX, shareY, shareZ) - presenceThreshold) / presenceEdge); } private static double clampToShare(double value) { diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/ValueField.java b/module/src/main/java/art/arcane/iris/modules/carve/field/ValueField.java new file mode 100644 index 000000000..24b75cfbd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/ValueField.java @@ -0,0 +1,113 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve.field; + +import art.arcane.iris.modules.carve.CaveValue; + +/** + * A {@link CaveValue} ready to read at a place: the same number everywhere, or the number its noise picks there. The + * noise's middle picks the middle of the range and the value reaches min and max half a unit either side of it, so a + * range has stretches at each end as well as the slopes between them. + */ +final class ValueField { + private static final double MIDDLE_SHARE = 0.5D; + + private final double min; + private final double max; + private final Field3 noise; + + private ValueField(double min, double max, Field3 noise) { + this.min = min; + this.max = max; + this.noise = noise; + } + + static ValueField constant(double value) { + return new ValueField(value, value, null); + } + + /** + * {@code value} read in 3D, under its own seed of {@code name}. Without a style it changes over about + * {@code changeBlocks} blocks in every direction. + */ + static ValueField inBlocks(CaveValue value, CaveNoise caveNoise, String name, double changeBlocks) { + if (!value.varies()) { + return constant(value.min()); + } + CaveNoise noise = caveNoise.named(name); + Field3 field = value.style().map(noise::inBlocks).orElseGet(() -> noise.smooth(changeBlocks, changeBlocks)); + return new ValueField(value.min(), value.max(), field); + } + + /** {@link #inBlocks} for a value that only varies over X and Z. */ + static ValueField inColumns(CaveValue value, CaveNoise caveNoise, String name, double changeBlocks) { + if (!value.varies()) { + return constant(value.min()); + } + CaveNoise noise = caveNoise.named(name); + Field3 field = value.style().map(noise::columnsInBlocks).orElseGet(() -> noise.columns(changeBlocks)); + return new ValueField(value.min(), value.max(), field); + } + + /** The share of the way from min to max that a noise value picks, from 0 to 1. */ + static double shareAt(double signedNoise) { + return Math.max(0D, Math.min(1D, MIDDLE_SHARE + signedNoise)); + } + + boolean varies() { + return noise != null; + } + + double min() { + return min; + } + + double max() { + return max; + } + + double middle() { + return (min + max) / 2D; + } + + double lowest() { + return Math.min(min, max); + } + + double highest() { + return Math.max(min, max); + } + + double at(double x, double y, double z) { + if (noise == null) { + return min; + } + return min + ((max - min) * shareAt(noise.at(x, y, z))); + } + + /** How far from min towards max the value is here, from 0 to 1; 0 where it does not vary. */ + double share(double x, double y, double z) { + return noise == null ? 0D : shareAt(noise.at(x, y, z)); + } + + /** {@link #at} for a value read in columns. */ + double at(double x, double z) { + return at(x, 0D, z); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/VaryingScale.java b/module/src/main/java/art/arcane/iris/modules/carve/field/VaryingScale.java new file mode 100644 index 000000000..64eaa7463 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/VaryingScale.java @@ -0,0 +1,71 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve.field; + +/** + * A field whose features' size varies from place to place. A noise read at a scale that changes along the way shears + * and tears, so the scale a field is read at never changes: a field is built at the smallest and at the largest size + * and the two are blended, horizontal and vertical sizes alike. Each size that varies doubles the fields read. + */ +final class VaryingScale { + /** Builds a field whose features lie about {@code horizontal} blocks apart sideways and {@code vertical} blocks apart upwards. */ + @FunctionalInterface + interface Builder { + Field3 build(CaveNoise noise, double horizontal, double vertical); + } + + private VaryingScale() { + } + + /** + * The field {@code builder} makes at the sizes {@code horizontal} and {@code vertical} pick. The smallest field + * takes the seeds of {@code noise}, so a field whose sizes are plain numbers is exactly the one the builder makes; + * the others are seeded by {@code name}. + */ + static Field3 of(CaveNoise noise, ValueField horizontal, ValueField vertical, String name, Builder builder) { + Field3 lowest = alongHorizontal(noise, horizontal, vertical.min(), name, builder); + if (!vertical.varies()) { + return lowest; + } + Field3 tallest = alongHorizontal(noise.named(name + ".tallest"), horizontal, vertical.max(), name, builder); + return blended(lowest, tallest, vertical); + } + + private static Field3 alongHorizontal(CaveNoise noise, ValueField horizontal, double vertical, String name, Builder builder) { + Field3 smallest = builder.build(noise, horizontal.min(), vertical); + if (!horizontal.varies()) { + return smallest; + } + Field3 largest = builder.build(noise.named(name + ".largest"), horizontal.max(), vertical); + return blended(smallest, largest, horizontal); + } + + /** + * {@code atMin} where {@code scale} is at its min, {@code atMax} where it is at its max, and both in between, + * weighted so the blend spreads as far as either field alone and a threshold keeps its share. + */ + private static Field3 blended(Field3 atMin, Field3 atMax, ValueField scale) { + return (x, y, z) -> { + double towardsMax = scale.share(x, y, z); + double towardsMin = 1D - towardsMax; + double spread = Math.sqrt((towardsMin * towardsMin) + (towardsMax * towardsMax)); + return ((atMin.at(x, y, z) * towardsMin) + (atMax.at(x, y, z) * towardsMax)) / spread; + }; + } +}