diff --git a/api/api/src/main/java/com/volmit/tooling/BlockParts.java b/api/api/src/main/java/com/volmit/tooling/BlockParts.java index fe2ff1ec5..c0916fe69 100644 --- a/api/api/src/main/java/com/volmit/tooling/BlockParts.java +++ b/api/api/src/main/java/com/volmit/tooling/BlockParts.java @@ -2,6 +2,8 @@ package com.volmit.tooling; import com.volmit.geometry.BlockPosition; +import java.util.Collections; +import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -18,8 +20,12 @@ public record BlockParts(Map partsByBlock) { public BlockParts { Objects.requireNonNull(partsByBlock, "partsByBlock"); - partsByBlock = Map.copyOf(partsByBlock); + // Not Map.copyOf: positions of a dense scene share hash codes, which its open addressing handles in quadratic + // time (a million blocks take minutes), while a HashMap falls back to a tree for keys that collide. + partsByBlock = Collections.unmodifiableMap(new HashMap<>(partsByBlock)); partsByBlock.forEach((position, part) -> { + Objects.requireNonNull(position, "position"); + Objects.requireNonNull(part, "part"); if (part < 0) { throw new IllegalArgumentException("Block " + position + " is in part " + part + "; parts are numbered from 0"); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioEvents.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioEvents.java index 8c07e12ae..289bc4332 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioEvents.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioEvents.java @@ -45,6 +45,8 @@ final class StudioEvents { private final StudioWorld world; private final Gson gson; private final List listeners = new CopyOnWriteArrayList<>(); + /** Listeners not yet told the world's state. */ + private final List joining = new CopyOnWriteArrayList<>(); private final AtomicBoolean listenerJoined = new AtomicBoolean(); private final AtomicBoolean usageWanted = new AtomicBoolean(); private final AtomicBoolean hotloaded = new AtomicBoolean(); @@ -60,6 +62,7 @@ final class StudioEvents { void listen(OutputStream stream) { listeners.add(stream); + joining.add(stream); listenerJoined.set(true); usageWanted.set(true); } @@ -76,10 +79,14 @@ final class StudioEvents { } StudioWorld.Session session = world.session(); Engine engine = session == null ? null : session.engine(); + List joined = List.copyOf(joining); if (engine != lastEngine || hotloaded.getAndSet(false)) { lastEngine = engine; send("world", new WorldChange(engine != null)); + } else { + greet(joined, engine != null); } + joining.removeAll(joined); List players = session == null || session.overlay() == null ? List.of() : session.overlay().players(); if (listenerJoined.getAndSet(false) || !Objects.equals(players, lastPlayers)) { lastPlayers = players; @@ -100,22 +107,46 @@ final class StudioEvents { closeQuietly(listener); } listeners.clear(); + joining.clear(); + } + + /** + * Tells studios that just connected what state the world is in, them alone. A studio takes its first world event as + * the state it connected to, so without one of its own it would take the next hotload for it and not redraw. + */ + private void greet(List joined, boolean running) { + if (joined.isEmpty()) { + return; + } + byte[] message = eventOf("world", new WorldChange(running)); + for (OutputStream listener : joined) { + sendTo(listener, message); + } } private void send(String event, Object data) { - sendToAll(("event: " + event + "\ndata: " + gson.toJson(data) + "\n\n").getBytes(StandardCharsets.UTF_8)); + sendToAll(eventOf(event, data)); + } + + private byte[] eventOf(String event, Object data) { + return ("event: " + event + "\ndata: " + gson.toJson(data) + "\n\n").getBytes(StandardCharsets.UTF_8); } private void sendToAll(byte[] message) { lastSentMillis = System.currentTimeMillis(); for (OutputStream listener : listeners) { - try { - listener.write(message); - listener.flush(); - } catch (IOException gone) { - listeners.remove(listener); - closeQuietly(listener); - } + sendTo(listener, message); + } + } + + private void sendTo(OutputStream listener, byte[] message) { + try { + listener.write(message); + listener.flush(); + } catch (IOException gone) { + listeners.remove(listener); + joining.remove(listener); + closeQuietly(listener); } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java index cba6a7358..4d66e3443 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java @@ -248,6 +248,9 @@ public final class CarveTestWorld implements PackWorld { @Override public List ids(ResourceKind kind) { + if (kind.equals(CaveResources.CAVES)) { + return caves.keySet().stream().sorted().toList(); + } return kind.equals(BIOMES) ? biomes.keySet().stream().sorted().toList() : List.of(); } } diff --git a/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioEventsTest.java b/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioEventsTest.java new file mode 100644 index 000000000..906bbfef6 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioEventsTest.java @@ -0,0 +1,61 @@ +package art.arcane.iris.core.studio.bridge; + +import com.google.gson.Gson; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertEquals; + +public class StudioEventsTest { + private static final String WORLD_EVENT = "event: world\n"; + + private final StudioEvents events = new StudioEvents(new StudioWorld("studio", () -> null, null), new Gson()); + + @Test + public void aStudioThatConnectsGetsTheWorldStateFirst() { + ByteArrayOutputStream studio = new ByteArrayOutputStream(); + + events.listen(studio); + events.poll(); + + assertEquals(1, worldEvents(studio)); + } + + // A studio skips its first world event as the state it connected to, so without one of its own a later window + // would take the first hotload for that state and not redraw. + @Test + public void aStudioThatConnectsLaterGetsItsOwnWorldStateAndTheOthersAreNotRedrawn() { + ByteArrayOutputStream first = new ByteArrayOutputStream(); + ByteArrayOutputStream later = new ByteArrayOutputStream(); + events.listen(first); + events.poll(); + + events.listen(later); + events.poll(); + + assertEquals(1, worldEvents(first)); + assertEquals(1, worldEvents(later)); + } + + @Test + public void everyStudioHearsOfAHotloadAfterItsWorldState() { + ByteArrayOutputStream first = new ByteArrayOutputStream(); + ByteArrayOutputStream later = new ByteArrayOutputStream(); + events.listen(first); + events.poll(); + events.listen(later); + events.poll(); + + events.hotloaded(); + events.poll(); + + assertEquals(2, worldEvents(first)); + assertEquals(2, worldEvents(later)); + } + + private static int worldEvents(ByteArrayOutputStream stream) { + return stream.toString(StandardCharsets.UTF_8).split(WORLD_EVENT, -1).length - 1; + } +} diff --git a/core/src/test/java/art/arcane/iris/modules/carve/CaveScenesTest.java b/core/src/test/java/art/arcane/iris/modules/carve/CaveScenesTest.java new file mode 100644 index 000000000..5f3ce7abd --- /dev/null +++ b/core/src/test/java/art/arcane/iris/modules/carve/CaveScenesTest.java @@ -0,0 +1,94 @@ +package art.arcane.iris.modules.carve; + +import art.arcane.iris.core.modules.CarveTestWorld; +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.modules.carve.field.CavePart; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import com.volmit.tooling.BlockParts; +import com.volmit.tooling.GraphNode; +import com.volmit.tooling.JsonText; +import com.volmit.tooling.NodeGraph; +import com.volmit.tooling.SceneEntry; +import org.junit.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class CaveScenesTest { + private static final String MIXED = """ + {"tunnel": {"width": {"min": 4, "max": 6}, "stretch": 48}, + "cavern": {"size": 40, "height": 18, "coverage": 0.2, "pillars": {"spacing": 14, "thickness": 4}}} + """; + private static final String TUNNELS_ONLY = "{\"tunnel\": {\"width\": {\"min\": 4, \"max\": 6}, \"stretch\": 48}}"; + + private final CaveScenes view = new CaveScenes(); + private final CarveTestWorld world = new CarveTestWorld() + .cave("deep/mixed", TestSettings.of(Cave.class, MIXED)) + .cave("tunnels", TestSettings.of(Cave.class, TUNNELS_ONLY)); + + @Test + public void everyCaveFileIsAnEntryUnderItsFolder() { + List entries = view.entries(world); + + assertEquals(List.of("deep/mixed", "tunnels"), entries.stream().map(SceneEntry::key).toList()); + assertEquals(Optional.of("deep"), entries.getFirst().group()); + assertEquals("mixed", entries.getFirst().name()); + assertEquals(Optional.empty(), entries.get(1).group()); + } + + @Test + public void theSceneIsTheCarvedSpaceAndEveryBlockBelongsToAPart() { + GeneratedObject scene = view.scene(world, "deep/mixed", 0).orElseThrow(); + BlockParts parts = view.parts(world, "deep/mixed", 0).orElseThrow(); + + assertFalse(scene.blocks().isEmpty()); + Set partsSeen = new HashSet<>(); + for (ObjectBlock block : scene.blocks()) { + int part = parts.partAt(block.position()); + assertNotEquals(BlockParts.NO_PART, part); + partsSeen.add(part); + } + assertEquals(Set.of(CavePart.TUNNEL.ordinal(), CavePart.CAVERN.ordinal()), partsSeen); + } + + @Test + public void eachVariantIsTheCaveSomewhereElse() { + GeneratedObject first = view.scene(world, "tunnels", 0).orElseThrow(); + + assertEquals(first.blocks(), view.scene(world, "tunnels", 0).orElseThrow().blocks()); + assertNotEquals(first.blocks(), view.scene(world, "tunnels", 1).orElseThrow().blocks()); + assertTrue(view.scene(world, "tunnels", CavePreview.VARIANTS).isEmpty()); + assertTrue(view.scene(world, "missing", 0).isEmpty()); + } + + @Test + public void aCaveFileReadsAsACaveWithItsTunnelAndCavernAndPillars() { + NodeGraph graph = view.graph(world, "deep/mixed", JsonText.parse(MIXED)); + + GraphNode cave = graph.roots().getFirst(); + assertEquals("mixed", cave.title()); + GraphNode tunnel = cave.children().get(0).node(); + GraphNode cavern = cave.children().get(1).node(); + assertEquals("Tunnel", tunnel.title()); + assertEquals(CavePart.TUNNEL.ordinal(), tunnel.part().getAsInt()); + assertEquals(CavePart.CAVERN.ordinal(), cavern.part().getAsInt()); + assertEquals("Pillars", cavern.children().getFirst().node().title()); + } + + @Test + public void anUnwrittenPartIsShownSoSettingItWritesIt() { + NodeGraph graph = view.graph(world, "tunnels", JsonText.parse(TUNNELS_ONLY)); + + GraphNode cavern = graph.roots().getFirst().children().get(1).node(); + assertEquals("Cavern (unset)", cavern.title()); + assertTrue("a cavern the cave does not have draws nothing", cavern.part().isEmpty()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 57241329a..14527cef2 100644 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -285,7 +285,7 @@ public class CaveCarving { return Optional.empty(); } CarvedVoid carvedVoid = cave.biome().isBlank() ? CarvedVoid.OPEN : CarvedVoid.OPEN.withBiome(resources.idOf(cave.biome())); - long seed = world.carveSeed() + (31L * id.toString().hashCode()); + long seed = CaveCarver.seedOf(world.carveSeed(), id); return Optional.of(new ListedCave(new CaveCarver(cave, world.noise(), seed, world.minHeight(), world.height()), carvedVoid)); } 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 b3ca05162..63695431b 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 @@ -27,6 +27,7 @@ import art.arcane.iris.modules.carve.CaveDepthSettings; 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.UpperDimensionCarvingSettings; import art.arcane.iris.modules.terrain.TerrainPalettes; import art.arcane.iris.engine.mantle.components.CarveWorld; @@ -76,6 +77,7 @@ public final class CarveModule implements IrisModule { log = setup.log(); var registry = setup.registry(); registry.registerResourceKind(CaveResources.CAVES); + setup.tooling().registerView(new CaveScenes()); List.of(CaveList.class, CarvingSettings.class, CarvingEnabledSettings.class, CarvingBiomeSettings.class, CaveDepthSettings.class, CaveLavaHeightSettings.class, UpperDimensionCarvingSettings.class) .forEach(registry::registerSettings); diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveGraph.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveGraph.java new file mode 100644 index 000000000..ab49e3c2c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveGraph.java @@ -0,0 +1,84 @@ +/* + * 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 art.arcane.iris.modules.carve.field.CavePart; +import com.volmit.tooling.GraphNode; +import com.volmit.tooling.GraphNode.Edits; +import com.volmit.tooling.GraphNode.Link; +import com.volmit.tooling.GraphNode.NodeSettings; +import com.volmit.tooling.JsonPath; +import com.volmit.tooling.JsonText; +import com.volmit.tooling.NodeGraph; + +import java.util.List; +import java.util.OptionalInt; +import java.util.Set; + +/** + * A cave file as nodes: the cave with its depth and surface rules, its tunnels, and its caverns with their pillars. + * Tunnels and caverns always have a node, written or not, since setting a value of one writes it into the file. + */ +final class CaveGraph { + private static final String TUNNEL = "tunnel"; + private static final String CAVERN = "cavern"; + private static final String PILLARS = "pillars"; + private static final String UNWRITTEN = " (unset)"; + private static final String HOLDS = ""; + private static final Set NO_NODES = Set.of(); + + private CaveGraph() { + } + + /** + * @param read what the pack read from the file, which tells which parts the scene draws; it may be older than {@code text} + * @throws IllegalArgumentException when the file does not hold an object + */ + static NodeGraph of(String name, JsonText text, Cave read) { + if (!(text.root() instanceof JsonText.Obj root)) { + throw new IllegalArgumentException("The file does not hold an object"); + } + JsonPath cavernPath = JsonPath.ROOT.member(CAVERN); + GraphNode tunnel = partNode("Tunnel", JsonPath.ROOT.member(TUNNEL), root.get(TUNNEL).isPresent(), read.tunnel().isPresent(), + CavePart.TUNNEL, new NodeSettings("Tunnel", JsonPath.ROOT.member(TUNNEL), CaveTunnel.class, NO_NODES), List.of()); + GraphNode pillars = new GraphNode("Pillars", titled("Pillars", hasMember(root, CAVERN, PILLARS)), cavernPath.member(PILLARS), + OptionalInt.empty(), List.of(), List.of(new NodeSettings("Pillars", cavernPath.member(PILLARS), CavePillars.class, NO_NODES)), + List.of(), Edits.NONE); + GraphNode cavern = partNode("Cavern", cavernPath, root.get(CAVERN).isPresent(), read.cavern().isPresent(), CavePart.CAVERN, + new NodeSettings("Cavern", cavernPath, CaveCavern.class, Set.of(PILLARS)), List.of(new Link(HOLDS, pillars))); + GraphNode cave = new GraphNode("Cave", name, JsonPath.ROOT, OptionalInt.empty(), List.of(), + List.of(new NodeSettings("Cave", JsonPath.ROOT, Cave.class, Set.of(TUNNEL, CAVERN))), + List.of(new Link(HOLDS, tunnel), new Link(HOLDS, cavern)), Edits.NONE); + return new NodeGraph(List.of(cave)); + } + + private static GraphNode partNode(String kind, JsonPath path, boolean written, boolean drawn, CavePart part, + NodeSettings settings, List children) { + OptionalInt drawnPart = drawn ? OptionalInt.of(part.ordinal()) : OptionalInt.empty(); + return new GraphNode(kind, titled(kind, written), path, drawnPart, List.of(), List.of(settings), children, Edits.NONE); + } + + private static String titled(String kind, boolean written) { + return written ? kind : kind + UNWRITTEN; + } + + private static boolean hasMember(JsonText.Obj root, String member, String inner) { + return root.get(member).orElse(null) instanceof JsonText.Obj object && object.get(inner).isPresent(); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CavePreview.java b/module/src/main/java/art/arcane/iris/modules/carve/CavePreview.java new file mode 100644 index 000000000..9ac278218 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CavePreview.java @@ -0,0 +1,116 @@ +/* + * 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 art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.modules.carve.field.CaveCarver; +import art.arcane.iris.modules.carve.field.CavePart; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.BlockParts; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * One cave carved over a square of the world under a flat surface, with the seed the world carves it with: the carved + * space drawn as blocks, a colour per part, so the studio shows the shape of the cave instead of the rock around it. + * A variant is the same cave somewhere else in the world. + */ +final class CavePreview { + static final int VARIANTS = 4; + private static final int AREA_CHUNKS = 8; + private static final int AREA_BLOCKS = AREA_CHUNKS * 16; + private static final int CHUNK_COLUMNS = 256; + /** The surface the preview carves under, in world Y. */ + static final int SURFACE_WORLD_Y = 96; + /** A cave deeper than this under the surface is cut off at the bottom of the preview. */ + private static final int MAX_DEPTH_BLOCKS = 256; + private static final int VARIANT_SPACING_BLOCKS = 4096; + private static final BlockState TUNNEL_BLOCK = new BlockState("minecraft:light_blue_concrete"); + private static final BlockState CAVERN_BLOCK = new BlockState("minecraft:orange_concrete"); + private static final int[] FLAT_SURFACE = new int[CHUNK_COLUMNS]; + private static final double[] LISTED_EVERYWHERE = new double[CHUNK_COLUMNS]; + private static final boolean[] NOTHING_SEALED = new boolean[CHUNK_COLUMNS]; + + static { + Arrays.fill(LISTED_EVERYWHERE, 1D); + } + + private final GeneratedObject scene; + private final BlockParts parts; + + private CavePreview(GeneratedObject scene, BlockParts parts) { + this.scene = scene; + this.parts = parts; + } + + static CavePreview of(PackWorld world, ResourceId id, Cave cave, int variant) { + int bottomWorldY = Math.max(world.minWorldY(), SURFACE_WORLD_Y - MAX_DEPTH_BLOCKS); + int surfaceHeight = SURFACE_WORLD_Y - world.minWorldY(); + int lowestHeight = bottomWorldY - world.minWorldY(); + long seed = CaveCarver.seedOf(world.seed(IrisSeedPurposes.CARVE), id); + CaveCarver carver = new CaveCarver(cave, world.resources().noise(), seed, world.minWorldY(), surfaceHeight + 1); + int[] surface = FLAT_SURFACE.clone(); + Arrays.fill(surface, surfaceHeight); + int originX = variant * VARIANT_SPACING_BLOCKS; + Map carved = new HashMap<>(); + for (int chunkX = 0; chunkX < AREA_CHUNKS; chunkX++) { + for (int chunkZ = 0; chunkZ < AREA_CHUNKS; chunkZ++) { + int sceneX = chunkX * 16; + int sceneZ = chunkZ * 16; + carver.carveByPart(originX + sceneX, sceneZ, surface, LISTED_EVERYWHERE, NOTHING_SEALED, (part, localX, y, localZ) -> { + if (y >= lowestHeight) { + carved.putIfAbsent(new BlockPosition(sceneX + localX, y - lowestHeight, sceneZ + localZ), part); + } + }); + } + } + return new CavePreview(sceneOf(carved, surfaceHeight - lowestHeight + 1), partsOf(carved)); + } + + private static GeneratedObject sceneOf(Map carved, int height) { + List blocks = new ArrayList<>(carved.size()); + carved.forEach((position, part) -> blocks.add(new ObjectBlock(position, part == CavePart.TUNNEL ? TUNNEL_BLOCK : CAVERN_BLOCK))); + BlockBox bounds = new BlockBox(0, 0, 0, AREA_BLOCKS, height, AREA_BLOCKS); + return new GeneratedObject(bounds, new BlockPosition(AREA_BLOCKS / 2, 0, AREA_BLOCKS / 2), blocks, List.of()); + } + + private static BlockParts partsOf(Map carved) { + Map parts = new HashMap<>(carved.size()); + carved.forEach((position, part) -> parts.put(position, part.ordinal())); + return new BlockParts(parts); + } + + GeneratedObject scene() { + return scene; + } + + BlockParts parts() { + return parts; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveScenes.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveScenes.java new file mode 100644 index 000000000..25bc66d43 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveScenes.java @@ -0,0 +1,163 @@ +/* + * 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.object.GeneratedObject; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.BlockParts; +import com.volmit.tooling.EditableSceneView; +import com.volmit.tooling.JsonText; +import com.volmit.tooling.NodeGraph; +import com.volmit.tooling.SceneCreation; +import com.volmit.tooling.SceneEntry; +import com.volmit.tooling.SceneFile; +import com.volmit.world.PackWorld; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * The studio's Caves view: every cave of the pack's {@code caves/} folder carved over 128 by 128 blocks under a flat + * surface, the carved space drawn as blocks so its shape shows. Each variant is the same cave elsewhere in the world. + * Each cave's file can be edited as nodes, and the studio redraws the cave as it changes. + */ +public final class CaveScenes implements EditableSceneView { + private static final ResourceId ID = ResourceId.parse("iris:carve/caves"); + private static final char FOLDER_SEPARATOR = '/'; + /** Other files name a cave by its bare key, in a {@code caves} list. */ + private static final String REFERENCE_PREFIX = ""; + private static final String STARTER = """ + { + "tunnel": {"width": {"min": 4, "max": 7}, "stretch": 96} + } + """; + private static final SceneCreation CREATION = new SceneCreation(CaveResources.CAVES, STARTER, REFERENCE_PREFIX); + + @Override + public ResourceId id() { + return ID; + } + + @Override + public String label() { + return "Caves"; + } + + @Override + public String description() { + return "Each cave carved under a flat surface at Y " + CavePreview.SURFACE_WORLD_Y + ", tunnels blue, caverns orange"; + } + + @Override + public List entries(PackWorld world) { + return world.resources().ids(CaveResources.CAVES).stream().map(CaveScenes::entryOf).toList(); + } + + @Override + public Optional scene(PackWorld world, String key, int variant) { + return preview(world, key, variant).map(CavePreview::scene); + } + + @Override + public boolean hasParts() { + return true; + } + + @Override + public Optional parts(PackWorld world, String key, int variant) { + return preview(world, key, variant).map(CavePreview::parts); + } + + @Override + public Optional fileOf(PackWorld world, String key) { + ResourceId id = world.resources().idOf(key); + return world.resources().ids(CaveResources.CAVES).contains(id) + ? Optional.of(new SceneFile(CaveResources.CAVES, id)) + : Optional.empty(); + } + + // A file the pack could not read yet draws no parts, so its nodes are shown without part ids. + @Override + public NodeGraph graph(PackWorld world, String key, JsonText text) { + Cave read = Optional.ofNullable(CaveResources.cave(world.resources(), key)).orElseGet(Cave::new); + return CaveGraph.of(key.substring(key.lastIndexOf(FOLDER_SEPARATOR) + 1), text, read); + } + + @Override + public Optional creation() { + return Optional.of(CREATION); + } + + private static Optional preview(PackWorld world, String key, int variant) { + if (variant < 0 || variant >= CavePreview.VARIANTS) { + return Optional.empty(); + } + ResourceId id = world.resources().idOf(key); + Cave cave = CaveResources.cave(world.resources(), id); + if (cave == null) { + return Optional.empty(); + } + return Optional.of(world.state(Previews.class, ignored -> new Previews()).of(world, id, cave, variant)); + } + + private static SceneEntry entryOf(ResourceId id) { + String path = id.path(); + int lastSeparator = path.lastIndexOf(FOLDER_SEPARATOR); + Optional folder = lastSeparator < 0 ? Optional.empty() : Optional.of(path.substring(0, lastSeparator)); + return new SceneEntry(path, path.substring(lastSeparator + 1), folder, CavePreview.VARIANTS); + } + + /** + * The previews the studio asked for last. It asks for a scene and then its parts, so both come from one carve. A + * reload reads the cave into a new object, which keys a new preview. + */ + private static final class Previews { + private static final int KEPT = 8; + + private final Map recent = new LinkedHashMap<>(KEPT, 0.75F, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > KEPT; + } + }; + + CavePreview of(PackWorld world, ResourceId id, Cave cave, int variant) { + Place place = new Place(id, variant); + synchronized (recent) { + Built known = recent.get(place); + if (known != null && known.from == cave) { + return known.preview; + } + } + CavePreview preview = CavePreview.of(world, id, cave, variant); + synchronized (recent) { + recent.put(place, new Built(cave, preview)); + } + return preview; + } + } + + private record Place(ResourceId cave, int variant) { + } + + private record Built(Cave from, CavePreview preview) { + } +} 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 a3e74b741..0cf611006 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 @@ -21,6 +21,7 @@ package art.arcane.iris.modules.carve.field; import art.arcane.iris.modules.carve.Cave; import com.volmit.config.Range; import com.volmit.noise.NoiseFactory; +import com.volmit.resource.ResourceId; import java.util.ArrayList; import java.util.List; @@ -34,7 +35,7 @@ public final class CaveCarver { /** 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 List shapes = new ArrayList<>(); private final int depthMinY; private final int depthMaxY; private final int fadeBlocks; @@ -48,8 +49,8 @@ public final class CaveCarver { */ public CaveCarver(Cave cave, NoiseFactory noise, long seed, int worldBottomY, int worldHeight) { CaveNoise caveNoise = new CaveNoise(noise, seed); - cave.tunnel().ifPresent(tunnel -> shapes.add(new TunnelShape(caveNoise, tunnel))); - cave.cavern().ifPresent(cavern -> shapes.add(new CavernShape(caveNoise, cavern))); + 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; @@ -60,10 +61,44 @@ public final class CaveCarver { this.opensToSurface = cave.opensToSurface(); } + /** The seed the cave with id {@code cave} carves with in a world whose carve seed is {@code carveSeed}. */ + public static long seedOf(long carveSeed, ResourceId cave) { + return carveSeed + (31L * cave.toString().hashCode()); + } + public boolean opensToSurface() { return opensToSurface; } + /** Which parts the cave has, in the order it carves them. */ + public List parts() { + return shapes.stream().map(PartShape::part).toList(); + } + + /** {@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) { + return; + } + CaveLimits limits = limitsOf(surfaceY, columnWeight, sealed); + if (limits.carvesNothing()) { + return; + } + ChunkLattice lattice = ChunkLattice.covering(originX, originZ, limits.lowestY(), limits.highestY()); + for (PartShape shape : shapes) { + shape.shape().carve(lattice, limits, (localX, y, localZ) -> sink.carve(shape.part(), localX, y, localZ)); + } + } + + /** Takes the blocks a cave carves, with the part that carved each. */ + @FunctionalInterface + public interface PartSink { + void carve(CavePart part, int localX, int y, int localZ); + } + + private record PartShape(CavePart part, LatticeShape shape) { + } + /** * Carves the chunk whose first block is {@code originX}, {@code originZ}. Columns are indexed as * {@code (localX << 4) | localZ}. @@ -73,22 +108,16 @@ public final class CaveCarver { * @param sealed columns whose surface the cave must not cut through, even if it opens to the surface */ public void carve(int originX, int originZ, int[] surfaceY, double[] columnWeight, boolean[] sealed, CarveSink sink) { - if (shapes.isEmpty() || depthMaxY < depthMinY) { - return; - } + 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; } - CaveLimits limits = new CaveLimits(depthMinY, depthMaxY, fadeBlocks, columnTopY, columnOpens, columnWeight); - if (limits.carvesNothing()) { - return; - } - ChunkLattice lattice = ChunkLattice.covering(originX, originZ, limits.lowestY(), limits.highestY()); - for (LatticeShape shape : shapes) { - shape.carve(lattice, limits, sink); - } + return new CaveLimits(depthMinY, depthMaxY, fadeBlocks, columnTopY, columnOpens, columnWeight); } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CavePart.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CavePart.java new file mode 100644 index 000000000..2d6101c0f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CavePart.java @@ -0,0 +1,25 @@ +/* + * 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; + +/** The shapes a cave is made of, in the order a cave carves them. */ +public enum CavePart { + TUNNEL, + CAVERN +}