diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/PatternEncoding.java b/core/src/main/java/art/arcane/iris/studio/bridge/PatternEncoding.java new file mode 100644 index 000000000..393bf4e1c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/PatternEncoding.java @@ -0,0 +1,59 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.studio.map.PalettePatterns; +import com.google.gson.Gson; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; + +/** + * A palette's pattern as the studio reads it, little endian: + *
+ * u32 header length | header, UTF-8 JSON | padding to 4 bytes | i16 picks[columns²]
+ * 
+ * The header holds the columns across, the blocks between columns, the block states the picks index, and the pick + * ({@code noBlock}) of a column the palette places nothing at. + */ +final class PatternEncoding { + private static final int ALIGNMENT_BYTES = 4; + + private PatternEncoding() { + } + + static byte[] encode(PalettePatterns.Pattern pattern, int blocksPerColumn, Gson gson) { + byte[] header = gson.toJson(new Header(pattern.columns(), blocksPerColumn, pattern.blocks(), pattern.blocks(), PalettePatterns.NO_BLOCK)) + .getBytes(StandardCharsets.UTF_8); + ByteBuffer buffer = ByteBuffer.allocate(aligned(Integer.BYTES + header.length) + pattern.picks().length * Short.BYTES) + .order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(header.length).put(header); + buffer.position(aligned(buffer.position())); + buffer.asShortBuffer().put(pattern.picks()); + return buffer.array(); + } + + private static int aligned(int bytes) { + return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES; + } + + private record Header(int columns, int blocksPerColumn, java.util.List blocks, java.util.List drawnAs, int noBlock) { + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java index 9d2bf4bb2..8b7d7c426 100644 --- a/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java @@ -22,8 +22,12 @@ import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.studio.map.StudioAssets; import art.arcane.iris.studio.map.StudioHover; +import art.arcane.iris.studio.map.PalettePatterns; +import art.arcane.iris.studio.noise.NoiseSources; +import art.arcane.iris.studio.noise.NoiseTile; import art.arcane.iris.studio.view.GuiHost; import art.arcane.iris.studio.view.GuiMarker; +import art.arcane.volmlib.util.function.NoiseProvider; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.google.gson.Gson; @@ -72,6 +76,10 @@ public final class StudioBridge implements AutoCloseable { private static final int LARGEST_TILE_SIZE = 512; private static final double SMALLEST_BLOCKS_PER_PIXEL = 1D / 16D; private static final double LARGEST_BLOCKS_PER_PIXEL = 4_096D; + private static final double SMALLEST_NOISE_BLOCKS_PER_PIXEL = 1D / 64D; + private static final int LARGEST_PATTERN_BLOCKS_PER_COLUMN = 64; + private static final ModuleViewInfo PALETTES_VIEW = new ModuleViewInfo("iris:terrain/palettes", "Palettes", + "The blocks each biome's palette layers place"); private static final long DROPPED_TILE_KEPT_MINUTES = 10; private static final long ENTITY_WAIT_MILLIS = 3_000L; private static final String ASSETS_ENDPOINT = "assets/"; @@ -87,6 +95,7 @@ public final class StudioBridge implements AutoCloseable { static final int STATUS_UNAUTHORIZED = 401; static final int STATUS_NOT_FOUND = 404; static final int STATUS_METHOD_NOT_ALLOWED = 405; + static final int STATUS_UNPROCESSABLE = 422; static final int STATUS_SERVER_ERROR = 500; static final int STATUS_UNAVAILABLE = 503; @@ -225,7 +234,12 @@ public final class StudioBridge implements AutoCloseable { case "scene-entries" -> sendJson(exchange, STATUS_OK, profileEntries(get(exchange).engine(), query)); case "scene" -> sendBytes(exchange, "application/octet-stream", profileScene(get(exchange).engine(), query)); case "profile-form" -> sendJson(exchange, STATUS_OK, profileForm(get(exchange).engine(), query)); - case "patterns", "noise-sources", "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of()); + case "noise-sources" -> sendJson(exchange, STATUS_OK, NoiseSources.of(get(exchange).engine()).list()); + case "noise-tile" -> sendBytes(exchange, "application/octet-stream", noiseTile(get(exchange).engine(), query)); + case "patterns" -> sendJson(exchange, STATUS_OK, List.of(PALETTES_VIEW)); + case "pattern-entries" -> sendJson(exchange, STATUS_OK, patternEntries(get(exchange).engine(), query)); + case "pattern" -> sendBytes(exchange, "application/octet-stream", pattern(get(exchange).engine(), query)); + case "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of()); case "events" -> streamEvents(exchange); case "teleport" -> teleport(exchange, query); case "open" -> throw new RequestError(STATUS_NOT_FOUND, "Opening a pack file from the studio is not available in Iris v4"); @@ -324,6 +338,62 @@ public final class StudioBridge implements AutoCloseable { return tile.encode(gson); } + private static List patternEntries(Engine engine, Query query) { + requirePalettesView(query); + return PalettePatterns.entries(engine); + } + + private byte[] pattern(Engine engine, Query query) { + requirePalettesView(query); + int columns = query.whole("size", DEFAULT_TILE_SIZE); + int blocksPerColumn = query.whole("scale", 1); + if (columns < 1 || columns > LARGEST_TILE_SIZE) { + throw new RequestError(STATUS_BAD_REQUEST, "A pattern is 1 to " + LARGEST_TILE_SIZE + " columns across"); + } + if (blocksPerColumn < 1 || blocksPerColumn > LARGEST_PATTERN_BLOCKS_PER_COLUMN) { + throw new RequestError(STATUS_BAD_REQUEST, "The scale is 1 to " + LARGEST_PATTERN_BLOCKS_PER_COLUMN + " whole blocks per column"); + } + String key = query.text("key"); + int tileBlocks = columns * blocksPerColumn; + PalettePatterns.Pattern pattern = PalettePatterns.pattern(engine, key, query.whole("depth", 0), + query.whole("x", 0) * tileBlocks, query.whole("z", 0) * tileBlocks, columns, blocksPerColumn) + .orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No palette " + key)); + return PatternEncoding.encode(pattern, blocksPerColumn, gson); + } + + private static void requirePalettesView(Query query) { + if (!PALETTES_VIEW.id().equals(query.text("view"))) { + throw new RequestError(STATUS_NOT_FOUND, "No pattern view " + query.text("view")); + } + } + + private byte[] noiseTile(Engine engine, Query query) { + int size = query.whole("size", DEFAULT_TILE_SIZE); + double blocksPerPixel = query.number("scale"); + if (size < 1 || size > LARGEST_TILE_SIZE) { + throw new RequestError(STATUS_BAD_REQUEST, "A tile is 1 to " + LARGEST_TILE_SIZE + " pixels"); + } + if (!(blocksPerPixel >= SMALLEST_NOISE_BLOCKS_PER_PIXEL && blocksPerPixel <= LARGEST_BLOCKS_PER_PIXEL)) { + throw new RequestError(STATUS_BAD_REQUEST, "The scale is " + SMALLEST_NOISE_BLOCKS_PER_PIXEL + " to " + LARGEST_BLOCKS_PER_PIXEL + " blocks per pixel"); + } + NoiseSources sources = NoiseSources.of(engine); + String source = query.text("source"); + NoiseProvider noise = noiseSampler(sources, source, query.longNumber("seed")); + return NoiseTile.sample(noise, query.whole("x", 0), query.whole("z", 0), blocksPerPixel, size, sources.isSmooth(source), + () -> closed || engine.isClosing() || engine.isClosed()).encode(); + } + + // A source that cannot be sampled fails every tile alike, so it is told once to the studio rather than logged per tile. + private static NoiseProvider noiseSampler(NoiseSources sources, String source, long seed) { + try { + return sources.sampler(source, seed); + } catch (NoSuchElementException unknown) { + throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage()); + } catch (IllegalStateException unsampleable) { + throw new RequestError(STATUS_UNPROCESSABLE, unsampleable.getMessage()); + } + } + // Asset paths name one file of one Minecraft version, so a studio may keep what it fetched for as long as it runs. private static void sendAsset(HttpExchange exchange, String endpoint) throws IOException { requireMethod(exchange, "GET"); @@ -549,6 +619,14 @@ public final class StudioBridge implements AutoCloseable { return found; } + long longNumber(String name) { + try { + return Long.parseLong(text(name)); + } catch (NumberFormatException malformed) { + throw new RequestError(STATUS_BAD_REQUEST, name + " must be a whole number"); + } + } + boolean has(String name) { return values.containsKey(name); } @@ -570,6 +648,10 @@ public final class StudioBridge implements AutoCloseable { boolean parts, StudioProfiles.Sizes sizes, boolean form) { } + /** A view the studio lists beside the scene and pattern views. */ + private record ModuleViewInfo(String id, String label, String description) { + } + private record PickInspection(String detail, List sections) { } diff --git a/core/src/main/java/art/arcane/iris/studio/map/PalettePatterns.java b/core/src/main/java/art/arcane/iris/studio/map/PalettePatterns.java new file mode 100644 index 000000000..912c4a157 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/map/PalettePatterns.java @@ -0,0 +1,114 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.map; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.block.IrisBlockData; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.volmlib.util.collection.KList; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** + * The blocks every biome palette places, as the studio's pattern view lists and lays them out: one entry per palette, + * and for a square of columns the block each column gets at a depth. + */ +public final class PalettePatterns { + public static final short NO_BLOCK = -1; + + private PalettePatterns() { + } + + /** + * @param key names the palette in {@link #pattern} + * @param group the biome the palette belongs to + * @param depths how many blocks deep it can stack, at least 1 + * @param facts short lines about it, such as its blocks + */ + public record Entry(String key, String name, String group, int depths, List facts) { + } + + /** + * @param blocks the block states the picks index + * @param picks each column's block, row by row from the north west, or {@link #NO_BLOCK} + */ + public record Pattern(int columns, List blocks, short[] picks) { + } + + public static List entries(Engine engine) { + IrisData data = engine.getData(); + String[] biomeKeys = data.getBiomeLoader().getPossibleKeys(); + if (biomeKeys == null) { + return List.of(); + } + Arrays.sort(biomeKeys); + List entries = new ArrayList<>(); + for (String biomeKey : biomeKeys) { + IrisBiome biome = data.getBiomeLoader().load(biomeKey); + if (biome != null) { + PaletteCatalog.summarizePalettes(biomeKey, biome).forEach(summary -> entries.add(entryOf(biome, summary))); + } + } + return entries; + } + + /** Empty when the palette no longer exists, such as after a hotload removed it. */ + public static Optional pattern(Engine engine, String key, int depth, int originX, int originZ, int columns, int blocksPerColumn) { + BiomePalette palette = BiomePalette.fromId(key); + IrisData data = engine.getData(); + IrisBiome biome = palette == null ? null : data.getBiomeLoader().load(palette.biomeKey()); + KList blocks = biome == null ? null : palette.blocksIn(biome); + if (blocks == null) { + return Optional.empty(); + } + BiomePalettePlacement placement = BiomePalettePlacement.of(engine, biome, palette); + int[] entryBySlot = PaletteSlots.entryPerSlot(blocks, data); + short[] picks = new short[columns * columns]; + for (int row = 0; row < columns; row++) { + for (int column = 0; column < columns; column++) { + picks[row * columns + column] = pickAt(placement, entryBySlot, depth, + originX + column * blocksPerColumn, originZ + row * blocksPerColumn); + } + } + return Optional.of(new Pattern(columns, blocks.stream().map(IrisBlockData::stateKey).toList(), picks)); + } + + private static short pickAt(BiomePalettePlacement placement, int[] entryBySlot, int depth, int blockX, int blockZ) { + if (entryBySlot.length == 0 || placement.thickness(blockX, blockZ) <= depth) { + return NO_BLOCK; + } + double noise = placement.noise(blockX, blockZ, depth); + return (short) entryBySlot[PaletteSlots.slotForNoise(noise, entryBySlot.length)]; + } + + private static Entry entryOf(IrisBiome biome, PaletteCatalog.PaletteSummary summary) { + BiomePalette palette = summary.palette(); + int depths = palette.kind().isStacked() ? Math.max(1, palette.layerIn(biome).getMaxHeight()) : 1; + List facts = new ArrayList<>(); + facts.add(summary.blocks()); + if (summary.snippet() != null) { + facts.add("From the " + summary.snippet() + " snippet"); + } + return new Entry(palette.id(), palette.label(), palette.biomeKey(), depths, List.copyOf(facts)); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/noise/CatmullRom.java b/core/src/main/java/art/arcane/iris/studio/noise/CatmullRom.java new file mode 100644 index 000000000..3d6221850 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/noise/CatmullRom.java @@ -0,0 +1,35 @@ +/* + * 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.studio.noise; + +/** The curve through four evenly spaced samples that passes through the middle two. */ +public final class CatmullRom { + private CatmullRom() { + } + + /** The curve between {@code start} and {@code end}, {@code fraction} of the way from one to the other. */ + public static double between(double before, double start, double end, double after, double fraction) { + double squared = fraction * fraction; + double cubed = squared * fraction; + return 0.5D * (2D * start + + (end - before) * fraction + + (2D * before - 5D * start + 4D * end - after) * squared + + (3D * start - before - 3D * end + after) * cubed); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/noise/NoiseCategory.java b/core/src/main/java/art/arcane/iris/studio/noise/NoiseCategory.java new file mode 100644 index 000000000..3e99ceb62 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/noise/NoiseCategory.java @@ -0,0 +1,98 @@ +/* + * 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.studio.noise; + +import art.arcane.iris.generation.noise.NoiseStyle; + +/** The groups the noise view lists its sources in, in this order. */ +public enum NoiseCategory { + PACK_GENERATORS("Pack generators"), + SIMPLEX("Simplex"), + PERLIN("Perlin"), + CELLULAR("Cellular"), + IRIS("Iris"), + CLOVER("Clover"), + HEXAGON("Hexagon"), + VASCULAR("Vascular"), + GLOBE("Globe"), + CUBIC("Cubic"), + FRACTAL("Fractal"), + STATIC("Static"), + NOWHERE("Nowhere"), + SIERPINSKI("Sierpinski"), + UTILITY("Utility"), + OTHER("Other"); + + private final String label; + + NoiseCategory(String label) { + this.label = label; + } + + public String label() { + return label; + } + + static NoiseCategory of(NoiseStyle style) { + String name = style.name(); + if (name.startsWith("STATIC")) { + return STATIC; + } + if (name.startsWith("IRIS")) { + return IRIS; + } + if (name.startsWith("CLOVER")) { + return CLOVER; + } + if (name.startsWith("VASCULAR")) { + return VASCULAR; + } + if (name.equals("FLAT")) { + return UTILITY; + } + if (name.startsWith("CELLULAR")) { + return CELLULAR; + } + if (name.startsWith("HEX")) { + return HEXAGON; + } + if (name.startsWith("SIERPINSKI")) { + return SIERPINSKI; + } + if (name.startsWith("NOWHERE")) { + return NOWHERE; + } + if (name.startsWith("GLOB")) { + return GLOBE; + } + if (name.startsWith("PERLIN")) { + return PERLIN; + } + if (name.startsWith("CUBIC") || (name.startsWith("FRACTAL") && name.contains("CUBIC"))) { + return CUBIC; + } + if (name.contains("SIMPLEX") && !name.startsWith("FRACTAL")) { + return SIMPLEX; + } + if (name.startsWith("FRACTAL")) { + return FRACTAL; + } + return OTHER; + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/noise/NoiseLattice.java b/core/src/main/java/art/arcane/iris/studio/noise/NoiseLattice.java new file mode 100644 index 000000000..b5fb98540 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/noise/NoiseLattice.java @@ -0,0 +1,86 @@ +/* + * 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.studio.noise; + +import art.arcane.volmlib.util.function.NoiseProvider; + +import java.util.function.BooleanSupplier; + +/** + * Tile values for noise too slow to sample at every pixel: the noise is sampled on a lattice fixed in the world and + * filled in between along a Catmull-Rom curve. A pixel's value depends only on where it is in the world, so tiles of + * one scale meet without a seam and tiles of nearby scales share their lattice points. + */ +final class NoiseLattice { + static final int LATTICE_PIXELS = 4; + static final double SMALLEST_SPACING_BLOCKS = 1D; + private static final int POINTS_BEFORE_CELL = 1; + private static final int POINTS_AFTER_CELL = 2; + private static final int CURVE_POINTS = 4; + + private NoiseLattice() { + } + + /** A power of two of blocks, at least {@link #LATTICE_PIXELS} pixels wide and at least a block, so a pixel never asks closer than the world's own grain. */ + static double spacingBlocks(double blocksPerPixel) { + double wanted = Math.max(LATTICE_PIXELS * blocksPerPixel, SMALLEST_SPACING_BLOCKS); + double spacing = SMALLEST_SPACING_BLOCKS; + while (spacing < wanted) { + spacing *= 2D; + } + return spacing; + } + + static float[] values(NoiseProvider noise, double originX, double originZ, double blocksPerPixel, int size, BooleanSupplier cancelled) { + double spacing = spacingBlocks(blocksPerPixel); + double reach = (size - 1) * blocksPerPixel; + int firstColumn = (int) Math.floor(originX / spacing) - POINTS_BEFORE_CELL; + int firstRow = (int) Math.floor(originZ / spacing) - POINTS_BEFORE_CELL; + int pointsAcross = (int) Math.floor((originX + reach) / spacing) + POINTS_AFTER_CELL - firstColumn + 1; + int pointsDown = (int) Math.floor((originZ + reach) / spacing) + POINTS_AFTER_CELL - firstRow + 1; + double[] points = new double[pointsAcross * pointsDown]; + for (int row = 0; row < pointsDown; row++) { + NoiseTile.requireWanted(cancelled); + for (int column = 0; column < pointsAcross; column++) { + points[row * pointsAcross + column] = noise.noise((firstColumn + column) * spacing, (firstRow + row) * spacing); + } + } + + float[] values = new float[size * size]; + double[] curveRows = new double[CURVE_POINTS]; + for (int pixelRow = 0; pixelRow < size; pixelRow++) { + NoiseTile.requireWanted(cancelled); + double latticeZ = (originZ + pixelRow * blocksPerPixel) / spacing; + int cellZ = (int) Math.floor(latticeZ); + double fractionZ = latticeZ - cellZ; + for (int pixelColumn = 0; pixelColumn < size; pixelColumn++) { + double latticeX = (originX + pixelColumn * blocksPerPixel) / spacing; + int cellX = (int) Math.floor(latticeX); + double fractionX = latticeX - cellX; + for (int curveRow = 0; curveRow < CURVE_POINTS; curveRow++) { + int offset = (cellZ - firstRow - POINTS_BEFORE_CELL + curveRow) * pointsAcross + + cellX - firstColumn - POINTS_BEFORE_CELL; + curveRows[curveRow] = CatmullRom.between(points[offset], points[offset + 1], points[offset + 2], points[offset + 3], fractionX); + } + values[pixelRow * size + pixelColumn] = (float) CatmullRom.between(curveRows[0], curveRows[1], curveRows[2], curveRows[3], fractionZ); + } + } + return values; + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/noise/NoiseSources.java b/core/src/main/java/art/arcane/iris/studio/noise/NoiseSources.java new file mode 100644 index 000000000..69383da45 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/noise/NoiseSources.java @@ -0,0 +1,161 @@ +/* + * 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.studio.noise; + +import art.arcane.iris.generation.noise.IrisGenerator; +import art.arcane.iris.generation.noise.IrisShapedGeneratorStyle; +import art.arcane.iris.generation.noise.NoiseStyle; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.volmlib.util.function.NoiseProvider; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.noise.CNG; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.NoSuchElementException; + +/** + * Every noise the noise view can show for a world: the dimension's overlay noise, the terrain height, the pack's + * generators, and each built-in noise style. + */ +public final class NoiseSources { + static final String OVERLAY_NOISE_ID = "world:overlay"; + static final String TERRAIN_HEIGHT_ID = "world:height"; + private static final long GENERATOR_SEED_SALT = 3245L; + + private final List entries; + + private NoiseSources(List entries) { + this.entries = entries.stream().sorted(Comparator.comparing(Entry::category)).toList(); + } + + public static NoiseSources of(Engine engine) { + List entries = new ArrayList<>(); + addOverlayNoise(engine, entries); + addTerrainHeight(engine, entries); + addPackGenerators(engine.getData(), entries); + addStyles(entries); + return new NoiseSources(entries); + } + + public List list() { + return entries.stream().map(Entry::source).toList(); + } + + /** The noise of a listed source at a seed, which sources that keep the world's seed ignore. */ + public NoiseProvider sampler(String id, long seed) { + return entryOf(id).factory().create(seed); + } + + /** Whether tiles of a listed source are drawn from samples on a lattice, smoothly in between, because sampling every pixel is too slow. */ + public boolean isSmooth(String id) { + return entryOf(id).source().smooth(); + } + + private Entry entryOf(String id) { + return entries.stream() + .filter(entry -> entry.source().id().equals(id)) + .findFirst() + .orElseThrow(() -> new NoSuchElementException("No noise " + id)); + } + + // The overlay is summed the way the world adds it, with the world's seed, in blocks above the fluid. + private static void addOverlayNoise(Engine engine, List entries) { + List overlay = engine.getDimension().getOverlayNoise(); + if (overlay.isEmpty()) { + return; + } + BlockRange blocks = new BlockRange( + overlay.stream().mapToInt(IrisShapedGeneratorStyle::getMin).sum(), + overlay.stream().mapToInt(IrisShapedGeneratorStyle::getMax).sum()); + Source source = new Source(OVERLAY_NOISE_ID, "Overlay noise", NoiseCategory.PACK_GENERATORS.label(), false, false, blocks); + entries.add(new Entry(source, NoiseCategory.PACK_GENERATORS, seed -> engine.getComplex().getOverlayStream()::get)); + } + + // The terrain the world generates, in blocks above the fluid, so the height colours and the water line match the world. + private static void addTerrainHeight(Engine engine, List entries) { + double fluidHeight = engine.getDimension().getFluidHeight(); + BlockRange blocks = new BlockRange(-fluidHeight, engine.getHeight() - fluidHeight); + Source source = new Source(TERRAIN_HEIGHT_ID, "Terrain height", NoiseCategory.PACK_GENERATORS.label(), false, true, blocks); + entries.add(new Entry(source, NoiseCategory.PACK_GENERATORS, + seed -> (x, z) -> engine.getComplex().getHeightStream().getDouble(x, z) - fluidHeight)); + } + + private static void addPackGenerators(IrisData data, List entries) { + for (String key : sortedKeys(data.getGeneratorLoader().getPossibleKeys())) { + Source source = new Source("pack:" + key, displayName(key), NoiseCategory.PACK_GENERATORS.label(), true, false, null); + entries.add(new Entry(source, NoiseCategory.PACK_GENERATORS, seed -> { + IrisGenerator generator = data.getGeneratorLoader().load(key); + if (generator == null) { + throw new NoSuchElementException("No pack generator " + key); + } + long mixedSeed = new RNG(seed).nextParallelRNG(GENERATOR_SEED_SALT).lmax(); + return (x, z) -> generator.getHeight(x, z, mixedSeed); + })); + } + } + + private static void addStyles(List entries) { + for (NoiseStyle style : NoiseStyle.values()) { + NoiseCategory category = NoiseCategory.of(style); + Source source = new Source("style:" + style.name(), displayName(style.name()), category.label(), true, false, null); + entries.add(new Entry(source, category, seed -> { + CNG noise = style.create(new RNG(seed)); + return noise::noise; + })); + } + } + + private static List sortedKeys(String[] keys) { + if (keys == null) { + return List.of(); + } + return Arrays.stream(keys).sorted().toList(); + } + + private static String displayName(String rawName) { + String spaced = rawName.toLowerCase(Locale.ROOT).replace('_', ' ').replace('-', ' '); + return Character.toUpperCase(spaced.charAt(0)) + spaced.substring(1); + } + + /** + * One noise the view lists. + * + * @param usesSeed whether the view's seed changes it; the overlay keeps the world's + * @param smooth whether tiles are sampled on a world-fixed lattice and smoothed between its points, for noise too slow to ask at every pixel + * @param blockRange where the noise is measured in blocks above the fluid, what it spans; null for noise of 0 to 1 + */ + public record Source(String id, String name, String category, boolean usesSeed, boolean smooth, BlockRange blockRange) { + } + + public record BlockRange(double lowest, double highest) { + } + + @FunctionalInterface + private interface SamplerFactory { + NoiseProvider create(long seed); + } + + private record Entry(Source source, NoiseCategory category, SamplerFactory factory) { + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/noise/NoiseTile.java b/core/src/main/java/art/arcane/iris/studio/noise/NoiseTile.java new file mode 100644 index 000000000..f58a06e8e --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/noise/NoiseTile.java @@ -0,0 +1,65 @@ +/* + * 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.studio.noise; + +import art.arcane.volmlib.util.function.NoiseProvider; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.concurrent.CancellationException; +import java.util.function.BooleanSupplier; + +/** + * A square of noise values, a pixel's value taken at its north west corner, row by row from the north. Tile (0, 0) + * starts at block (0, 0), so tiles at one scale meet without a seam. + */ +public record NoiseTile(int size, float[] values) { + /** @param smooth whether to sample a lattice and fill in between, for noise too slow to ask at every pixel */ + public static NoiseTile sample(NoiseProvider noise, int tileX, int tileZ, double blocksPerPixel, int size, + boolean smooth, BooleanSupplier cancelled) { + double tileBlocks = size * blocksPerPixel; + double originX = tileX * tileBlocks; + double originZ = tileZ * tileBlocks; + if (smooth) { + return new NoiseTile(size, NoiseLattice.values(noise, originX, originZ, blocksPerPixel, size, cancelled)); + } + float[] values = new float[size * size]; + for (int row = 0; row < size; row++) { + requireWanted(cancelled); + double z = originZ + row * blocksPerPixel; + for (int column = 0; column < size; column++) { + values[row * size + column] = (float) noise.noise(originX + column * blocksPerPixel, z); + } + } + return new NoiseTile(size, values); + } + + static void requireWanted(BooleanSupplier cancelled) { + if (cancelled.getAsBoolean()) { + throw new CancellationException("Noise tile no longer wanted"); + } + } + + /** The values as little endian 32 bit floats, an unsampleable value as NaN. */ + public byte[] encode() { + ByteBuffer bytes = ByteBuffer.allocate(values.length * Float.BYTES).order(ByteOrder.LITTLE_ENDIAN); + bytes.asFloatBuffer().put(values); + return bytes.array(); + } +}