From 55f6a06f9f2c5bceade98c0dfaa48d23d7fd60ba Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 12 Nov 2026 04:09:20 +0100 Subject: [PATCH] Show decorators, snippets and ground cover in the studio Decorators get their own pattern view from the decorant module: each biome's decorators from above, placed where their own noise allows. The Palettes and Decorators views list the pack's snippet files in a Snippets group, with the biomes that use each one, and mark entries read from a snippet. PackResources gains snippetOf and snippets so a module can tell where a settings value came from. The 3D world draws what stands on the ground, such as grass and flowers, as the block's own model. A plugin block that is solid on the server but shown to players as a plant no longer counts as ground. --- api/README.md | 4 +- .../com/volmit/resource/PackResources.java | 15 + .../java/com/volmit/resource/PackSnippet.java | 32 +++ .../iris/core/modules/IrisPackResources.java | 11 + .../core/modules/ModuleSettingsDecoder.java | 107 +++++++- .../iris/core/studio/map/GeneratedChunks.java | 77 ++++-- .../modules/DecorantSettingsDecodingTest.java | 42 +++ .../core/studio/map/GeneratedChunksTest.java | 52 ++++ .../decorator/DecoratorPatternsTest.java | 150 ++++++++++ .../iris/builtin/tooling/SnippetUses.java | 123 +++++++++ .../iris/engine/actuator/DecorantModule.java | 2 + .../engine/decorator/BiomeDecorators.java | 22 ++ .../engine/decorator/DecoratorPatterns.java | 259 ++++++++++++++++++ .../iris/modules/terrain/BiomePalettes.java | 79 +++++- .../src/renderer/src/bridge/tileDecoding.ts | 2 +- studio/src/renderer/src/bridge/types.ts | 3 + studio/src/renderer/src/map/map.test.ts | 2 +- studio/src/renderer/src/scene/blockArt.ts | 17 +- studio/src/renderer/src/scene/blockLooks.ts | 21 ++ studio/src/renderer/src/scene/columnField.ts | 5 + studio/src/renderer/src/scene/coverFaces.ts | 45 +++ studio/src/renderer/src/scene/coverLooks.ts | 44 +++ studio/src/renderer/src/scene/mapTerrain.ts | 9 + .../renderer/src/scene/savedTerrain.test.ts | 2 +- studio/src/renderer/src/scene/sceneMesh.ts | 3 +- studio/src/renderer/src/scene/terrainAtlas.ts | 49 +++- studio/src/renderer/src/scene/terrainMesh.ts | 26 +- .../src/scene/texturedTerrain.test.ts | 33 ++- .../src/renderer/src/studio/PatternStudio.tsx | 6 +- studio/src/renderer/src/studio/ViewList.tsx | 1 + 30 files changed, 1172 insertions(+), 71 deletions(-) create mode 100644 api/api/src/main/java/com/volmit/resource/PackSnippet.java create mode 100644 core/src/test/java/art/arcane/iris/core/studio/map/GeneratedChunksTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/decorator/DecoratorPatternsTest.java create mode 100644 module/src/main/java/art/arcane/iris/builtin/tooling/SnippetUses.java create mode 100644 module/src/main/java/art/arcane/iris/engine/decorator/DecoratorPatterns.java create mode 100644 studio/src/renderer/src/scene/coverFaces.ts create mode 100644 studio/src/renderer/src/scene/coverLooks.ts diff --git a/api/README.md b/api/README.md index c5493fb30..c4862e2f4 100644 --- a/api/README.md +++ b/api/README.md @@ -806,7 +806,9 @@ public final class FloraSettings implements IrisFeature { `List`, `Set` and arrays of these, `Map`, `Object` for any JSON value, and concrete classes, which are described the same way, IrisApi's value types among them (see Values in settings). `@Snippet("example/flora/patch")` on a class lets packs write it as a file under `snippet/example/flora/patch/`. A pack module's snippet names start with its module id as a folder - path (`example/flora` for `example:flora`). + path (`example/flora` for `example:flora`). A tool that lists what a pack shares asks + `PackResources.snippetOf(value)` for the file a settings value was read from, and + `PackResources.snippets(Patch.class)` for every file of the type, used or not. Anything else fails the pack load: `char`, other JDK classes such as `UUID` or `Optional`, interfaces and abstract classes, inner (non-static) classes, collections without type arguments, concrete collections such as `ArrayList`, and maps with other keys. diff --git a/api/api/src/main/java/com/volmit/resource/PackResources.java b/api/api/src/main/java/com/volmit/resource/PackResources.java index 8ebc774de..55ff20285 100644 --- a/api/api/src/main/java/com/volmit/resource/PackResources.java +++ b/api/api/src/main/java/com/volmit/resource/PackResources.java @@ -76,6 +76,21 @@ public interface PackResources { return List.of(); } + /** The snippet file the pack's settings read {@code value} from, and which of its entries; empty for a value + * the pack wrote in place. {@code value} is the very object the settings hold, such as one entry of a list option + * whose type has {@link com.volmit.config.Snippet}. Empty by default. + */ + default Optional snippetOf(Object value) { + return Optional.empty(); + } + + /** The pack's snippet files for {@code type}, a class with {@link com.volmit.config.Snippet}, in path order, used by + * the pack's settings or not, so that a tool can list them all. Empty by default. + */ + default List> snippets(Class type) { + return List.of(); + } + /** {@link #find} for a resource that must exist: a missing one throws NoSuchElementException naming kind and id. */ default T require(ResourceKind kind, ResourceId id) { return find(kind, id).orElseThrow(() -> new NoSuchElementException("Missing " + kind.id() + " resource: " + id)); diff --git a/api/api/src/main/java/com/volmit/resource/PackSnippet.java b/api/api/src/main/java/com/volmit/resource/PackSnippet.java new file mode 100644 index 000000000..8f69c121d --- /dev/null +++ b/api/api/src/main/java/com/volmit/resource/PackSnippet.java @@ -0,0 +1,32 @@ +package com.volmit.resource; + +import java.util.List; +import java.util.Objects; + +/** + * One snippet file of a pack, read as the type its folder holds. + * + * @param path the file below the type's snippet folder, without {@code .json}, such as {@code meadow/flowers} + * @param entries what the file holds: one entry, or several when it holds a list; none when it could not be read + */ +public record PackSnippet(String path, List entries) { + public PackSnippet { + Objects.requireNonNull(path, "path"); + entries = List.copyOf(entries); + } + + /** + * Where in the pack's snippet files a settings value was read from. + * + * @param path the file, as {@link PackSnippet#path()} + * @param entry which of the file's {@link PackSnippet#entries()} the value is, from 0 + */ + public record Source(String path, int entry) { + public Source { + Objects.requireNonNull(path, "path"); + if (entry < 0) { + throw new IllegalArgumentException("A snippet file's entries count from 0, not " + entry); + } + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java index b1afa6f37..17c9b7a0b 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java @@ -36,6 +36,7 @@ import com.volmit.noise.PackExpression; import com.volmit.noise.PackImageMap; import com.volmit.object.GeneratedObject; import com.volmit.resource.PackResources; +import com.volmit.resource.PackSnippet; import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; import com.volmit.world.PackBiome; @@ -172,6 +173,16 @@ public final class IrisPackResources implements PackResources { return PackServices.of(data).providers(service); } + @Override + public Optional snippetOf(Object value) { + return data.getModules().settings().snippetOf(value); + } + + @Override + public List> snippets(Class type) { + return data.getModules().settings().snippets(type); + } + /** * The ids of the resources of the kind {@code kindId} names, for Iris's own tools that list a module's resources * without the module's class for them, which the plugin's classes cannot reach when the kind ships in a module jar. diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java index e12f2b769..d9d5186a4 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java @@ -42,27 +42,35 @@ import com.volmit.config.Snippet; import com.volmit.host.FeatureCatalog; import com.volmit.host.FeatureDescriptor; import com.volmit.host.OptionsMetadata; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.volmit.resource.PackSnippet; import com.volmit.resource.ResourceId; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.spi.IrisLogging; +import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.UnaryOperator; +import java.util.stream.Stream; /** * Reads the module settings a dimension, region or biome declares: each settings feature of the pack at @@ -87,6 +95,8 @@ public final class ModuleSettingsDecoder { private final Map>> settings = new EnumMap<>(Level.class); private final Map> keys = new EnumMap<>(Level.class); private final Map placementSettings = new ConcurrentHashMap<>(); + // Weak keys compare by identity, and let go of the settings of a pack that was reloaded since. + private final Cache snippetByValue = Caffeine.newBuilder().weakKeys().build(); private final Path packFolder; private final Gson gson; private final Supplier irisGson; @@ -373,7 +383,9 @@ public final class ModuleSettingsDecoder { if (entry.isJsonArray()) { throw new JsonParseException("Snippet " + reference + " holds several entries, which only a list can take"); } - return delegate.fromJsonTree(entry); + T value = delegate.fromJsonTree(entry); + rememberSnippetOf(value, new PackSnippet.Source(snippetName(snippet.value(), reference), 0)); + return value; } }; } @@ -392,12 +404,88 @@ public final class ModuleSettingsDecoder { return delegate.read(in); } JsonArray entries = gson.getAdapter(JsonArray.class).read(in); - return delegate.fromJsonTree(withSnippetsInlined(entries, snippet.value())); + InlinedEntries inlined = withSnippetsInlined(entries, snippet.value()); + T list = delegate.fromJsonTree(inlined.entries()); + rememberSnippetsOf((Collection) list, inlined.snippets()); + return list; } }; } } + /** + * The entries of a list with its snippet references replaced by what their files hold. + * + * @param snippets the snippet each entry came from, null for one written in place + */ + private record InlinedEntries(JsonArray entries, List snippets) { + } + + // A list type that drops entries while it is read can't be matched to them again. + private void rememberSnippetsOf(Collection decoded, List snippets) { + if (decoded == null || decoded.size() != snippets.size()) { + return; + } + int index = 0; + for (Object value : decoded) { + rememberSnippetOf(value, snippets.get(index++)); + } + } + + private void rememberSnippetOf(Object value, PackSnippet.Source snippet) { + if (value != null && snippet != null) { + snippetByValue.put(value, snippet); + } + } + + /** The snippet file {@code value} was read from and which of its entries it is; empty for a value written in place. */ + Optional snippetOf(Object value) { + return value == null ? Optional.empty() : Optional.ofNullable(snippetByValue.getIfPresent(value)); + } + + /** Every snippet file the pack has for {@code type}, in path order; a file that can't be read is logged and has no entries. */ + List> snippets(Class type) { + Snippet snippet = type.getAnnotation(Snippet.class); + if (snippet == null) { + throw new IllegalArgumentException(type.getName() + " has no @Snippet, so packs keep no snippet files of it"); + } + Path folder = packFolder.resolve(SNIPPET_FOLDER).resolve(snippet.value()); + if (!Files.isDirectory(folder)) { + return List.of(); + } + try (Stream files = Files.walk(folder)) { + return files.filter(file -> Files.isRegularFile(file) && file.getFileName().toString().endsWith(JSON_EXTENSION)) + .map(file -> snippetPath(folder, file)) + .sorted() + .map(path -> new PackSnippet<>(path, entriesOfSnippet(type, snippet.value(), path))) + .toList(); + } catch (IOException failure) { + throw new UncheckedIOException("Cannot list the snippets in " + packFolder.relativize(folder), failure); + } + } + + private static String snippetPath(Path folder, Path file) { + String relative = folder.relativize(file).toString().replace(File.separatorChar, '/'); + return relative.substring(0, relative.length() - JSON_EXTENSION.length()); + } + + private List entriesOfSnippet(Class type, String snippetFolder, String path) { + try { + JsonElement file = readSnippet(snippetFolder, SNIPPET_PREFIX + snippetFolder + "/" + path); + List written = file.isJsonArray() ? IrisData.entriesOfSnippet(file.getAsJsonArray()) : List.of(file); + List entries = new ArrayList<>(); + for (JsonElement entry : written) { + T value = gson.fromJson(entry, type); + rememberSnippetOf(value, new PackSnippet.Source(path, entries.size())); + entries.add(value); + } + return entries; + } catch (JsonParseException | UncheckedIOException unreadable) { + IrisLogging.warn("Cannot read snippet " + SNIPPET_FOLDER + "/" + snippetFolder + "/" + path + JSON_EXTENSION + ": " + unreadable.getMessage()); + return List.of(); + } + } + private static Snippet snippetListedBy(TypeToken type) { if (!Collection.class.isAssignableFrom(type.getRawType()) || !(type.getType() instanceof ParameterizedType listType)) { return null; @@ -409,21 +497,24 @@ public final class ModuleSettingsDecoder { return elementType.getAnnotation(Snippet.class); } - private JsonArray withSnippetsInlined(JsonArray entries, String snippetFolder) { + private InlinedEntries withSnippetsInlined(JsonArray entries, String snippetFolder) { JsonArray inlined = new JsonArray(); + List snippets = new ArrayList<>(); for (JsonElement entry : entries) { if (!entry.isJsonPrimitive() || !entry.getAsJsonPrimitive().isString()) { inlined.add(entry); + snippets.add(null); continue; } JsonElement snippet = readSnippet(snippetFolder, entry.getAsString()); - if (snippet.isJsonArray()) { - IrisData.entriesOfSnippet(snippet.getAsJsonArray()).forEach(inlined::add); - } else { - inlined.add(snippet); + List held = snippet.isJsonArray() ? IrisData.entriesOfSnippet(snippet.getAsJsonArray()) : List.of(snippet); + String name = snippetName(snippetFolder, entry.getAsString()); + for (int heldIndex = 0; heldIndex < held.size(); heldIndex++) { + inlined.add(held.get(heldIndex)); + snippets.add(new PackSnippet.Source(name, heldIndex)); } } - return inlined; + return new InlinedEntries(inlined, snippets); } /** The file name below the snippet folder: {@code snippet/} and {@code snippet//} name the same file. */ diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java b/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java index 6c2a741e9..9e05bd338 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java @@ -18,7 +18,10 @@ package art.arcane.iris.core.studio.map; +import art.arcane.iris.core.link.CustomBlockSource; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.util.common.data.B; import art.arcane.iris.engine.framework.GenerationSessionLease; import art.arcane.iris.spi.PlatformBiome; import art.arcane.iris.spi.PlatformBlockState; @@ -27,6 +30,11 @@ import art.arcane.iris.util.project.hunk.Hunk; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.UnaryOperator; + /** * The tops of chunks generated for the studio alone: each chunk runs through the world's own stages into memory, so its * columns hold what the world would, trees and structures included, and nothing is placed in the world. Generating @@ -43,6 +51,7 @@ final class GeneratedChunks implements ColumnTops { private final Engine engine; private final LoadingCache tops; + private final Map seenByKey = new ConcurrentHashMap<>(); GeneratedChunks(Engine engine) { this.engine = engine; @@ -65,7 +74,18 @@ final class GeneratedChunks implements ColumnTops { IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) { engine.getGeneration().generate(chunkX << CHUNK_SHIFT, chunkZ << CHUNK_SHIFT, blocks, biomes, false, lease.sessionId()); } - return ChunkTop.of(blocks); + return new ChunkTop(topsOf(blocks, this::seenByPlayers)); + } + + // A plugin's block can be solid on the server where players see grass they walk through. + private PlatformBlockState seenByPlayers(PlatformBlockState block) { + return seenByKey.computeIfAbsent(block.key(), key -> { + CustomBlockSource plugins = IrisServices.getOrNull(CustomBlockSource.class); + Optional shown = plugins == null + ? Optional.empty() + : plugins.lookOf(key).map(look -> B.getStateOrNull(look.shownAs(), false)); + return shown.orElse(block); + }); } private static long keyOf(int chunkX, int chunkZ) { @@ -73,36 +93,43 @@ final class GeneratedChunks implements ColumnTops { } private record ChunkTop(ColumnTop[] columns) { - static ChunkTop of(Hunk blocks) { - ColumnTop[] columns = new ColumnTop[BLOCKS_ACROSS * BLOCKS_ACROSS]; - for (int z = 0; z < BLOCKS_ACROSS; z++) { - for (int x = 0; x < BLOCKS_ACROSS; x++) { - columns[z * BLOCKS_ACROSS + x] = topOf(blocks, x, z); - } + } + + /** + * The top of each column of a chunk's blocks, row by row from the north west. + * + * @param seenByPlayers the state players see in place of a block, which decides whether it is ground; the block + * itself for all but a plugin's + */ + static ColumnTop[] topsOf(Hunk blocks, UnaryOperator seenByPlayers) { + ColumnTop[] columns = new ColumnTop[BLOCKS_ACROSS * BLOCKS_ACROSS]; + for (int z = 0; z < BLOCKS_ACROSS; z++) { + for (int x = 0; x < BLOCKS_ACROSS; x++) { + columns[z * BLOCKS_ACROSS + x] = topOf(blocks, x, z, seenByPlayers); } - return new ChunkTop(columns); } + return columns; + } - // The ground is the highest block something can stand on, so a tree's leaves and a roof count; what stands on it - // without being ground, such as grass or a layer of snow, is its cover. - private static ColumnTop topOf(Hunk blocks, int x, int z) { - for (int y = blocks.getHeight() - 1; y >= 0; y--) { - PlatformBlockState block = blocks.get(x, y, z); - if (!isGround(block)) { - continue; - } - PlatformBlockState above = y + 1 < blocks.getHeight() ? blocks.get(x, y + 1, z) : null; - return new ColumnTop(y, block.key(), isCover(above) ? above.key() : null); + // The ground is the highest block something can stand on, so a tree's leaves and a roof count; what stands on it + // without being ground, such as grass or a layer of snow, is its cover. + private static ColumnTop topOf(Hunk blocks, int x, int z, UnaryOperator seenByPlayers) { + for (int y = blocks.getHeight() - 1; y >= 0; y--) { + PlatformBlockState block = blocks.get(x, y, z); + if (block == null || !isGround(seenByPlayers.apply(block))) { + continue; } - return ColumnTop.NOTHING; + PlatformBlockState above = y + 1 < blocks.getHeight() ? blocks.get(x, y + 1, z) : null; + return new ColumnTop(y, block.key(), isCover(above) ? above.key() : null); } + return ColumnTop.NOTHING; + } - private static boolean isGround(PlatformBlockState block) { - return block != null && !block.isAir() && !block.isFluid() && block.isSolid(); - } + private static boolean isGround(PlatformBlockState block) { + return !block.isAir() && !block.isFluid() && block.isSolid(); + } - private static boolean isCover(PlatformBlockState block) { - return block != null && !block.isAir() && !block.isFluid(); - } + private static boolean isCover(PlatformBlockState block) { + return block != null && !block.isAir() && !block.isFluid(); } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java index c6fc1c229..a2ae2acbf 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java @@ -9,6 +9,7 @@ import com.volmit.config.Level; import com.volmit.block.BlockSpec; import com.volmit.host.LoadedPack; import com.volmit.host.ModuleHost; +import com.volmit.resource.PackSnippet; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -19,6 +20,7 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.Optional; import java.util.Set; import static org.junit.Assert.assertEquals; @@ -112,6 +114,46 @@ public class DecorantSettingsDecodingTest { } } + @Test + public void aDecoratorReadFromASnippetKnowsItsFileAndOneWrittenInPlaceHasNone() { + List decorators = decorators(BIOME_DECORATORS); + + assertEquals(Optional.of(new PackSnippet.Source("bush", 0)), decoder.snippetOf(decorators.get(2))); + assertEquals(Optional.of(new PackSnippet.Source("bush", 0)), decoder.snippetOf(decorators.get(3))); + assertEquals(Optional.empty(), decoder.snippetOf(decorators.getFirst())); + } + + @Test + public void everySnippetFileIsListedWhetherABiomeUsesItOrNot() throws IOException { + Path snippets = folder.getRoot().toPath().resolve("pack/snippet/iris/decorant/decorator"); + Files.createDirectories(snippets.resolve("flowers")); + Files.writeString(snippets.resolve("flowers/pair.json"), + "[{\"palette\": [{\"block\": \"minecraft:poppy\"}]}, {\"palette\": [{\"block\": \"minecraft:dandelion\"}]}]"); + Files.writeString(snippets.resolve("broken.json"), "{\"palette\": "); + + List> listed = decoder.snippets(Decorator.class); + + assertEquals(List.of("broken", "bush", "flowers/pair"), listed.stream().map(PackSnippet::path).toList()); + assertEquals("a file that can't be read is listed without entries", List.of(), listed.getFirst().entries()); + assertEquals(List.of(BlockSpec.of("minecraft:fern")), listed.get(1).entries().getFirst().palette()); + assertEquals(2, listed.get(2).entries().size()); + assertEquals(Optional.of(new PackSnippet.Source("flowers/pair", 1)), decoder.snippetOf(listed.get(2).entries().get(1))); + } + + @Test + public void aListTakingAFileOfSeveralKnowsWhichOfThemEachEntryIs() throws IOException { + Path snippets = folder.getRoot().toPath().resolve("pack/snippet/iris/decorant/decorator"); + Files.writeString(snippets.resolve("pair.json"), + "[{\"palette\": [{\"block\": \"minecraft:poppy\"}]}, {\"palette\": [{\"block\": \"minecraft:dandelion\"}]}]"); + + List decorators = decorators("{\"decorators\": [{\"chance\": 1}, \"snippet/pair\"]}"); + + assertEquals(3, decorators.size()); + assertEquals(Optional.empty(), decoder.snippetOf(decorators.getFirst())); + assertEquals(Optional.of(new PackSnippet.Source("pair", 0)), decoder.snippetOf(decorators.get(1))); + assertEquals(Optional.of(new PackSnippet.Source("pair", 1)), decoder.snippetOf(decorators.get(2))); + } + @Test public void anEmptyDecoratorHasIrisDefaults() { Decorator defaults = decorators(BIOME_DECORATORS).get(4); diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/GeneratedChunksTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/GeneratedChunksTest.java new file mode 100644 index 000000000..b21ec1b50 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/map/GeneratedChunksTest.java @@ -0,0 +1,52 @@ +package art.arcane.iris.core.studio.map; + +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.hunk.Hunk; +import org.junit.Test; + +import java.util.function.UnaryOperator; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class GeneratedChunksTest { + private static final int HEIGHT = 8; + private static final PlatformBlockState STONE = block("minecraft:stone", true); + private static final PlatformBlockState POPPY = block("minecraft:poppy", false); + private static final PlatformBlockState TRIPWIRE = block("minecraft:tripwire", false); + // A plugin's grass: solid on the server, a tripwire to players. + private static final PlatformBlockState PLUGIN_GRASS = block("craftengine:custom_7", true); + + @Test + public void theGroundIsTheHighestSolidBlockAndWhatStandsOnItItsCover() { + Hunk blocks = Hunk.newArrayHunk(16, HEIGHT, 16); + blocks.set(0, 3, 0, STONE); + blocks.set(0, 4, 0, POPPY); + blocks.set(1, 2, 0, STONE); + + ColumnTops.ColumnTop[] tops = GeneratedChunks.topsOf(blocks, UnaryOperator.identity()); + + assertEquals(new ColumnTops.ColumnTop(3, "minecraft:stone", "minecraft:poppy"), tops[0]); + assertEquals(new ColumnTops.ColumnTop(2, "minecraft:stone", null), tops[1]); + assertEquals(ColumnTops.ColumnTop.NOTHING, tops[2]); + } + + @Test + public void aPluginBlockPlayersWalkThroughIsCoverThoughTheServerHoldsItSolid() { + Hunk blocks = Hunk.newArrayHunk(16, HEIGHT, 16); + blocks.set(0, 3, 0, STONE); + blocks.set(0, 4, 0, PLUGIN_GRASS); + + ColumnTops.ColumnTop[] tops = GeneratedChunks.topsOf(blocks, block -> block == PLUGIN_GRASS ? TRIPWIRE : block); + + assertEquals(new ColumnTops.ColumnTop(3, "minecraft:stone", "craftengine:custom_7"), tops[0]); + } + + private static PlatformBlockState block(String key, boolean solid) { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(key); + when(block.isSolid()).thenReturn(solid); + return block; + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/decorator/DecoratorPatternsTest.java b/core/src/test/java/art/arcane/iris/engine/decorator/DecoratorPatternsTest.java new file mode 100644 index 000000000..c87c49955 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/decorator/DecoratorPatternsTest.java @@ -0,0 +1,150 @@ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.Decorator; +import art.arcane.iris.engine.modifier.ApiChunk; +import com.google.gson.Gson; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.host.ModuleLogs; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.resource.PackSnippet; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.BlockPattern; +import com.volmit.tooling.PatternArea; +import com.volmit.tooling.PatternEntry; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DecoratorPatternsTest { + private static final ResourceId MEADOW = ResourceId.parse("pack:meadow"); + private static final double NOISE_EVERYWHERE = 0.3; + private static final String POPPIES = "{\"chance\": 0.5, \"palette\": [{\"block\": \"minecraft:poppy\"}]}"; + private static final String RARE_FERNS = "{\"chance\": 0.1, \"palette\": [{\"block\": \"minecraft:fern\"}]}"; + private static final String CANE = "{\"chance\": 1, \"stackMin\": 3, \"stackMax\": 3, \"palette\": [{\"block\": \"minecraft:sugar_cane\"}]," + + " \"topPalette\": [{\"block\": \"minecraft:bamboo\"}]}"; + private static final String UNUSED_TULIPS = "{\"chance\": 1, \"palette\": [{\"block\": \"minecraft:red_tulip\"}]}"; + + private final DecoratorPatterns view = new DecoratorPatterns(); + private final PatternArea area = new PatternArea(0, 0, 4, 1); + private PackWorld world; + + @Before + public void createWorld() { + Gson gson = new Gson(); + Decorator poppies = gson.fromJson(POPPIES, Decorator.class); + Decorator tulips = gson.fromJson(UNUSED_TULIPS, Decorator.class); + DecorantSettings meadow = new DecorantSettings(List.of(poppies, gson.fromJson(RARE_FERNS, Decorator.class), gson.fromJson(CANE, Decorator.class))); + + PackResources resources = mock(PackResources.class); + when(resources.ids(PackResources.BIOMES)).thenReturn(List.of(MEADOW)); + when(resources.find(PackResources.BIOMES, MEADOW)) + .thenReturn(Optional.of(new PackBiome(MEADOW, "Meadow", ResourceId.parse("minecraft:plains"), List.of()))); + when(resources.blocks()).thenReturn(ApiChunk.blockRegistry()); + when(resources.noise()).thenReturn((style, seed) -> constant(NOISE_EVERYWHERE)); + when(resources.snippetOf(any())).thenReturn(Optional.empty()); + when(resources.snippetOf(poppies)).thenReturn(Optional.of(new PackSnippet.Source("flowers/poppies", 0))); + when(resources.snippets(Decorator.class)).thenReturn(List.of( + new PackSnippet<>("flowers/broken", List.of()), + new PackSnippet<>("flowers/poppies", List.of(poppies)), + new PackSnippet<>("flowers/tulips", List.of(gson.fromJson(RARE_FERNS, Decorator.class), tulips)))); + + FeatureSettings settings = mock(FeatureSettings.class); + when(settings.declaredBy(MEADOW, DecorantSettings.class)).thenReturn(Optional.of(meadow)); + RunningWorld running = mock(RunningWorld.class); + when(running.settings()).thenReturn(settings); + + world = mock(PackWorld.class); + when(world.running()).thenReturn(Optional.of(running)); + when(world.resources()).thenReturn(resources); + when(world.log()).thenReturn(ModuleLogs.discarding()); + when(world.state(eq(BiomeDecorators.class), any())).thenAnswer(asked -> asked.>getArgument(1).apply(world)); + } + + @Test + public void listsEachDecoratorUnderItsBiomeAndEachSnippetFileAfterThem() { + List entries = view.entries(world); + + assertEquals(List.of("pack:meadow#0", "pack:meadow#1", "pack:meadow#2", "snippet:flowers/broken#0", "snippet:flowers/poppies#0", + "snippet:flowers/tulips#0", "snippet:flowers/tulips#1"), entries.stream().map(PatternEntry::key).toList()); + assertEquals(Optional.of("Meadow"), entries.getFirst().group()); + assertTrue(entries.getFirst().facts().contains("Snippet flowers/poppies")); + assertFalse(entries.get(1).facts().stream().anyMatch(fact -> fact.startsWith("Snippet"))); + assertEquals("a stack is stepped through block by block", 3, entries.get(2).depths()); + assertEquals(List.of("Could not be read; the server log says why"), entries.get(3).facts()); + assertEquals("flowers/poppies", entries.get(4).name()); + assertTrue(entries.get(4).facts().contains("Meadow · Decorator 1")); + assertEquals("a file holding several is listed entry by entry", "flowers/tulips · 2", entries.get(6).name()); + assertTrue(entries.get(6).facts().contains("Not used by any biome")); + } + + @Test + public void placesOnlyWhereTheDecoratorsNoiseStaysUnderItsChance() { + assertEquals(List.of("minecraft:poppy"), blocksOf("pack:meadow#0", 0)); + assertTrue(placesEverywhere("pack:meadow#0", 0)); + assertEquals(List.of(), blocksOf("pack:meadow#1", 0)); + } + + @Test + public void aStackHasItsTopPaletteOnTopAndEndsAtItsHeight() { + assertEquals(List.of("minecraft:bamboo"), blocksOf("pack:meadow#2", 0)); + assertEquals(List.of("minecraft:sugar_cane"), blocksOf("pack:meadow#2", 2)); + assertEquals(List.of(), blocksOf("pack:meadow#2", 3)); + } + + @Test + public void aSnippetFileShowsWhatItsFirstUsePlacesOrItsOwnBlocksWhenUnused() { + assertEquals(List.of("minecraft:poppy"), blocksOf("snippet:flowers/poppies#0", 0)); + assertEquals(List.of("minecraft:red_tulip"), blocksOf("snippet:flowers/tulips#1", 0)); + assertEquals("a file that can't be read places nothing", List.of(), blocksOf("snippet:flowers/broken#0", 0)); + assertTrue(view.pattern(world, "snippet:flowers/none#0", 0, area).isEmpty()); + assertTrue(view.pattern(world, "snippet:flowers/tulips#2", 0, area).isEmpty()); + assertTrue(view.pattern(world, "pack:meadow#7", 0, area).isEmpty()); + } + + private List blocksOf(String key, int depth) { + return view.pattern(world, key, depth, area).orElseThrow().blocks().stream().map(BlockState::key).toList(); + } + + private boolean placesEverywhere(String key, int depth) { + BlockPattern pattern = view.pattern(world, key, depth, area).orElseThrow(); + for (int row = 0; row < area.columns(); row++) { + for (int column = 0; column < area.columns(); column++) { + if (pattern.pickAt(column, row).isEmpty()) { + return false; + } + } + } + return true; + } + + private static NoiseSampler constant(double value) { + return new NoiseSampler() { + @Override + public double sample(double worldX, double worldZ) { + return value; + } + + @Override + public double sample(double worldX, double y, double worldZ) { + return value; + } + }; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/tooling/SnippetUses.java b/module/src/main/java/art/arcane/iris/builtin/tooling/SnippetUses.java new file mode 100644 index 000000000..525c20b17 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/tooling/SnippetUses.java @@ -0,0 +1,123 @@ +/* + * 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.builtin.tooling; + +import com.volmit.resource.PackSnippet; +import com.volmit.tooling.PatternEntry; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; + +/** + * The snippet files a pattern view lists after its biomes' entries (v3e's snippet folders): each of a file's entries + * once, with the biome entries that use it, so a shared palette is found in one place and a file nothing uses yet + * still shows. + */ +public final class SnippetUses { + private static final String GROUP = "Snippets"; + private static final String KEY_PREFIX = "snippet:"; + private static final char ENTRY_SEPARATOR = '#'; + private static final int MOST_USES_LISTED = 8; + private static final int UNUSED_DEPTHS = 1; + + private final Map> usesBySource = new LinkedHashMap<>(); + + /** Whether {@code key} names an entry of a snippet file, not a biome's. */ + public static boolean isSnippetKey(String key) { + return key.startsWith(KEY_PREFIX); + } + + /** The entry of a snippet file that {@code key} names; empty for a key that names none. */ + public static Optional sourceOf(String key) { + int entryStart = key.lastIndexOf(ENTRY_SEPARATOR); + if (!isSnippetKey(key) || entryStart <= KEY_PREFIX.length()) { + return Optional.empty(); + } + try { + return Optional.of(new PackSnippet.Source(key.substring(KEY_PREFIX.length(), entryStart), Integer.parseInt(key.substring(entryStart + 1)))); + } catch (IllegalArgumentException notAnEntry) { + return Optional.empty(); + } + } + + /** The line an entry read from a snippet file says so with. */ + public static String factOf(PackSnippet.Source source) { + return "Snippet " + source.path(); + } + + /** Notes that the entry {@code user} places what {@code source} holds. */ + public void use(PackSnippet.Source source, PatternEntry user) { + usesBySource.computeIfAbsent(source, unused -> new ArrayList<>()).add(user); + } + + /** The first entry that uses {@code source}, which it is shown as; empty when nothing uses it. */ + public Optional firstUseOf(PackSnippet.Source source) { + return Optional.ofNullable(usesBySource.get(source)).map(List::getFirst); + } + + /** + * One entry for each thing the snippet files hold, in the order given; a file that could not be read is listed once. + * + * @param blocksOf the line naming the blocks a snippet's entry places + */ + public List entries(List> snippets, Function blocksOf) { + List entries = new ArrayList<>(); + for (PackSnippet snippet : snippets) { + if (snippet.entries().isEmpty()) { + entries.add(entryOf(new PackSnippet.Source(snippet.path(), 0), snippet.path(), List.of("Could not be read; the server log says why"))); + continue; + } + for (int held = 0; held < snippet.entries().size(); held++) { + PackSnippet.Source source = new PackSnippet.Source(snippet.path(), held); + String name = snippet.entries().size() == 1 ? snippet.path() : snippet.path() + " · " + (held + 1); + List facts = new ArrayList<>(List.of(blocksOf.apply(snippet.entries().get(held)))); + facts.addAll(usesOf(source)); + entries.add(entryOf(source, name, facts)); + } + } + return entries; + } + + private PatternEntry entryOf(PackSnippet.Source source, String name, List facts) { + int depths = firstUseOf(source).map(PatternEntry::depths).orElse(UNUSED_DEPTHS); + return new PatternEntry(KEY_PREFIX + source.path() + ENTRY_SEPARATOR + source.entry(), name, Optional.of(GROUP), depths, facts); + } + + private List usesOf(PackSnippet.Source source) { + List uses = usesBySource.getOrDefault(source, List.of()); + if (uses.isEmpty()) { + return List.of("Not used by any biome"); + } + List lines = new ArrayList<>(); + lines.add(uses.size() == 1 ? "Used once, shown as placed there:" : "Used " + uses.size() + " times, shown as the first places it:"); + uses.stream().limit(MOST_USES_LISTED).map(SnippetUses::nameOf).forEach(lines::add); + if (uses.size() > MOST_USES_LISTED) { + lines.add("and " + (uses.size() - MOST_USES_LISTED) + " more"); + } + return lines; + } + + private static String nameOf(PatternEntry user) { + return user.group().map(group -> group + " · " + user.name()).orElse(user.name()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/module/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 4b7bf5f28..2fd3afb09 100644 --- a/module/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/module/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -24,6 +24,7 @@ import art.arcane.iris.modules.decorant.DecorateSettings; import art.arcane.iris.engine.decorator.BiomeDecorators; import art.arcane.iris.engine.decorator.DecoratedBiome; import art.arcane.iris.engine.decorator.DecorationScene; +import art.arcane.iris.engine.decorator.DecoratorPatterns; import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; @@ -61,6 +62,7 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { registry.registerSettings(DecorantSettings.class); registry.registerSettings(DecorateSettings.class); registry.registerLifecycle(this); + setup.tooling().registerView(new DecoratorPatterns()); } @Override diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java b/module/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java index 67888f7ca..20404459c 100644 --- a/module/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java +++ b/module/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java @@ -101,6 +101,28 @@ public final class BiomeDecorators { return decorators.computeIfAbsent(biome.settings(), declared -> resolve(biome.key(), declared)).getOrDefault(part, NO_DECORATORS); } + /** The decorator the biome lists at {@code index}, made ready as generation has it; null when it lists none there. */ + ResolvedDecorator decoratorAt(DecoratedBiome biome, int index) { + if (biome == null || biome.settings() == null || index < 0 || index >= biome.settings().decorators().size()) { + return null; + } + Decorator declared = biome.settings().decorators().get(index); + if (declared == null) { + return null; + } + for (ResolvedDecorator resolved : decorators(biome, declared.partOf())) { + if (resolved.settings() == declared) { + return resolved; + } + } + return null; + } + + /** A decorator no biome lists, made ready with a seed of its own, which {@code name} decides. */ + ResolvedDecorator unlisted(String name, Decorator decorator) { + return ResolvedDecorator.of(decorator, resources, seedOf(name, 0), log, name); + } + /** Whether the biome has a decorator for {@code part}. */ public boolean hasDecorators(DecoratedBiome biome, DecorationPart part) { return decorators(biome, part).length > 0; diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/DecoratorPatterns.java b/module/src/main/java/art/arcane/iris/engine/decorator/DecoratorPatterns.java new file mode 100644 index 000000000..0c376bdd8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/DecoratorPatterns.java @@ -0,0 +1,259 @@ +/* + * 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.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.builtin.decorant.Decorator; +import art.arcane.iris.builtin.tooling.SnippetUses; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.resource.PackResources; +import com.volmit.resource.PackSnippet; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.BlockPattern; +import com.volmit.tooling.PatternArea; +import com.volmit.tooling.PatternEntry; +import com.volmit.tooling.PatternView; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * The studio's Decorators view (v3e's palette explorer showed them beside the layers): each biome's decorators from + * above, the columns a decorator's own noise lets it place on and the block it picks there. A decorator is shown alone: + * in the world the biome's other decorators, the surface block and the slope decide between them. + */ +public final class DecoratorPatterns implements PatternView { + private static final ResourceId ID = ResourceId.parse("iris:decorant/decorators"); + private static final char INDEX_SEPARATOR = '#'; + private static final char ENTRY_SEED_SEPARATOR = '#'; + private static final String MINECRAFT_PREFIX = "minecraft:"; + private static final int ONE_BLOCK = 1; + private static final Map PLACES = Map.of( + DecorationPart.SHORE_LINE, "On the shore line", + DecorationPart.SEA_SURFACE, "On the sea's surface", + DecorationPart.SEA_FLOOR, "On the sea floor", + DecorationPart.CEILING, "On cave ceilings"); + + @Override + public ResourceId id() { + return ID; + } + + @Override + public String label() { + return "Decorators"; + } + + @Override + public String description() { + return "Each biome's decorators from above, where they place and the blocks they pick"; + } + + @Override + public List entries(PackWorld world) { + Optional running = world.running(); + if (running.isEmpty()) { + return List.of(); + } + SnippetUses snippetUses = new SnippetUses(); + List entries = new ArrayList<>(biomeEntries(world.resources(), running.get().settings(), snippetUses)); + entries.addAll(snippetUses.entries(world.resources().snippets(Decorator.class), decorator -> blocksOf(decorator.palette()))); + return entries; + } + + @Override + public Optional pattern(PackWorld world, String key, int depth, PatternArea area) { + Optional running = world.running(); + if (running.isEmpty() || depth < 0) { + return Optional.empty(); + } + FeatureSettings settings = running.get().settings(); + Optional decorator = SnippetUses.isSnippetKey(key) + ? SnippetUses.sourceOf(key).flatMap(source -> snippetDecorator(world, settings, source)) + : biomeDecorator(world, settings, key); + if (decorator.isEmpty() && isUnreadableSnippet(world.resources(), key)) { + return Optional.of(BlockPattern.of(area.columns(), new BlockState[area.columns() * area.columns()])); + } + return decorator.map(placed -> patternOf(placed, depth, area)); + } + + // A file that could not be read is listed too, and places nothing. + private static boolean isUnreadableSnippet(PackResources resources, String key) { + return SnippetUses.sourceOf(key).stream().anyMatch(source -> resources.snippets(Decorator.class).stream() + .anyMatch(snippet -> snippet.path().equals(source.path()) && snippet.entries().isEmpty())); + } + + private static List biomeEntries(PackResources resources, FeatureSettings settings, SnippetUses snippetUses) { + List biomes = biomesByName(resources); + Map biomesByShownName = biomes.stream().collect(Collectors.groupingBy(PackBiome::name, Collectors.counting())); + List entries = new ArrayList<>(); + for (PackBiome biome : biomes) { + String group = biomesByShownName.get(biome.name()) > 1 ? biome.name() + " (" + biome.id().path() + ")" : biome.name(); + List decorators = settings.declaredBy(biome.id(), DecorantSettings.class).map(DecorantSettings::decorators).orElse(List.of()); + for (int index = 0; index < decorators.size(); index++) { + Decorator decorator = decorators.get(index); + if (decorator == null || decorator.palette().isEmpty()) { + continue; + } + Optional snippet = resources.snippetOf(decorator); + PatternEntry entry = entryOf(biome, index, decorator, group, snippet); + entries.add(entry); + snippet.ifPresent(source -> snippetUses.use(source, entry)); + } + } + return entries; + } + + private static List biomesByName(PackResources resources) { + return resources.ids(PackResources.BIOMES).stream() + .map(id -> resources.find(PackResources.BIOMES, id)) + .flatMap(Optional::stream) + .sorted(Comparator.comparing(PackBiome::name).thenComparing(biome -> biome.id().toString())) + .toList(); + } + + private static PatternEntry entryOf(PackBiome biome, int index, Decorator decorator, String group, Optional snippet) { + String key = biome.id().toString() + INDEX_SEPARATOR + index; + List facts = factsOf(decorator); + snippet.map(SnippetUses::factOf).ifPresent(facts::add); + return new PatternEntry(key, "Decorator " + (index + 1), Optional.of(group).filter(shown -> !shown.isBlank()), depthsOf(decorator), facts); + } + + // A stack scaled to its cave has no height of its own to step through. + private static int depthsOf(Decorator decorator) { + return decorator.isStacking() && !decorator.scaleStack() ? decorator.stackMax() : ONE_BLOCK; + } + + private static List factsOf(Decorator decorator) { + List facts = new ArrayList<>(); + facts.add(blocksOf(decorator.palette())); + if (!decorator.topPalette().isEmpty()) { + facts.add("Topped with " + blocksOf(decorator.topPalette())); + } + facts.add("Chance " + decorator.chance() + ", " + decorator.style().style().toLowerCase(Locale.ROOT).replace('_', ' ') + + " noise, zoom " + decorator.style().zoom()); + if (decorator.isStacking()) { + facts.add(stackOf(decorator)); + } + if (PLACES.containsKey(decorator.partOf())) { + facts.add(PLACES.get(decorator.partOf())); + } + if (!decorator.slopeCondition().isDefault()) { + facts.add("Only on slopes from " + decorator.slopeCondition().minimumSlope() + " to " + decorator.slopeCondition().maximumSlope() + + "; shown everywhere here"); + } + facts.add("Shown alone, without the biome's other decorators"); + return facts; + } + + private static String stackOf(Decorator decorator) { + String unit = decorator.scaleStack() ? "% of the cave's height" : " blocks"; + if (decorator.stackMin() == decorator.stackMax()) { + return "Stacks " + decorator.stackMax() + unit; + } + return "Stacks " + decorator.stackMin() + " to " + decorator.stackMax() + unit; + } + + private static String blocksOf(List palette) { + Map weights = palette.stream() + .collect(Collectors.groupingBy(spec -> shortName(spec.block()), LinkedHashMap::new, Collectors.summingInt(BlockSpec::weight))); + return weights.entrySet().stream() + .map(entry -> entry.getValue() > 1 ? entry.getKey() + " ×" + entry.getValue() : entry.getKey()) + .collect(Collectors.joining(", ")); + } + + private static String shortName(String block) { + return block.startsWith(MINECRAFT_PREFIX) ? block.substring(MINECRAFT_PREFIX.length()) : block; + } + + private static Optional biomeDecorator(PackWorld world, FeatureSettings settings, String key) { + int indexStart = key.lastIndexOf(INDEX_SEPARATOR); + if (indexStart < 1) { + return Optional.empty(); + } + Optional index = wholeNumber(key.substring(indexStart + 1)); + Optional biome = world.resources().ids(PackResources.BIOMES).stream() + .filter(id -> id.toString().equals(key.substring(0, indexStart))) + .findFirst(); + if (index.isEmpty() || biome.isEmpty()) { + return Optional.empty(); + } + Optional declared = settings.declaredBy(biome.get(), DecorantSettings.class); + return declared.map(decorators -> BiomeDecorators.of(world) + .decoratorAt(new DecoratedBiome(BiomeDecorators.biomeKey(biome.get()), decorators, null), index.get())); + } + + // A snippet's decorator is shown as the first biome that uses it places it; one nothing uses gets noise of its own. + private static Optional snippetDecorator(PackWorld world, FeatureSettings settings, PackSnippet.Source source) { + SnippetUses snippetUses = new SnippetUses(); + biomeEntries(world.resources(), settings, snippetUses); + Optional firstUse = snippetUses.firstUseOf(source); + if (firstUse.isPresent()) { + return biomeDecorator(world, settings, firstUse.get().key()); + } + return world.resources().snippets(Decorator.class).stream() + .filter(snippet -> snippet.path().equals(source.path())) + .map(PackSnippet::entries) + .filter(held -> source.entry() < held.size()) + .findFirst() + .map(held -> BiomeDecorators.of(world).unlisted(source.path() + ENTRY_SEED_SEPARATOR + source.entry(), held.get(source.entry()))); + } + + private static Optional wholeNumber(String text) { + try { + return Optional.of(Integer.parseInt(text)).filter(number -> number >= 0); + } catch (NumberFormatException notANumber) { + return Optional.empty(); + } + } + + private static BlockPattern patternOf(ResolvedDecorator decorator, int depth, PatternArea area) { + BlockState[] blocks = new BlockState[area.columns() * area.columns()]; + for (int row = 0; row < area.columns(); row++) { + for (int column = 0; column < area.columns(); column++) { + blocks[row * area.columns() + column] = blockAt(decorator, area.blockX(column), area.blockZ(row), depth); + } + } + return BlockPattern.of(area.columns(), blocks); + } + + // The top of a stack takes the top palette, as generation gives it, and the rest the palette. + private static BlockState blockAt(ResolvedDecorator decorator, int x, int z, int depth) { + if (!decorator.passesChanceGate(x, z) || depth >= heightAt(decorator, x, z)) { + return null; + } + return depth == 0 && decorator.isStacking() ? decorator.pickTopBlock(x, z) : decorator.pickBlock(x, z); + } + + private static int heightAt(ResolvedDecorator decorator, int x, int z) { + return decorator.isStacking() && !decorator.isScaleStack() ? decorator.stackHeight(x, z) : ONE_BLOCK; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java b/module/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java index b3acc26a7..b3a71c74a 100644 --- a/module/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java +++ b/module/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java @@ -20,11 +20,13 @@ package art.arcane.iris.modules.terrain; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.iris.builtin.tooling.SnippetUses; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockSpec; import com.volmit.block.BlockState; import com.volmit.config.FeatureSettings; import com.volmit.resource.PackResources; +import com.volmit.resource.PackSnippet; import com.volmit.resource.ResourceId; import com.volmit.tooling.BlockPattern; import com.volmit.tooling.PatternArea; @@ -78,8 +80,14 @@ public final class BiomePalettes implements PatternView { if (running.isEmpty()) { return List.of(); } + SnippetUses snippetUses = new SnippetUses(); + List entries = new ArrayList<>(biomeEntries(world, running.get().settings(), snippetUses)); + entries.addAll(snippetUses.entries(world.resources().snippets(PaletteLayer.class), BiomePalettes::blocksOf)); + return entries; + } + + private static List biomeEntries(PackWorld world, FeatureSettings settings, SnippetUses snippetUses) { BiomeLayers layers = BiomeLayers.of(world); - FeatureSettings settings = running.get().settings(); List biomes = biomesByName(world.resources()); Map biomesByShownName = biomes.stream().collect(Collectors.groupingBy(PackBiome::name, Collectors.counting())); List entries = new ArrayList<>(); @@ -89,7 +97,10 @@ public final class BiomePalettes implements PatternView { for (Kind kind : Kind.values()) { List palettes = kind.palettesOf(layers, layered, settings, biome.id()); for (int index = 0; index < palettes.size(); index++) { - entries.add(entryOf(biome, layered, kind, index, palettes.get(index), group)); + Optional snippet = world.resources().snippetOf(palettes.get(index)); + PatternEntry entry = entryOf(biome, layered, kind, index, palettes.get(index), group, snippet); + entries.add(entry); + snippet.ifPresent(source -> snippetUses.use(source, entry)); } } } @@ -98,6 +109,52 @@ public final class BiomePalettes implements PatternView { @Override public Optional pattern(PackWorld world, String key, int depth, PatternArea area) { + if (SnippetUses.isSnippetKey(key)) { + return SnippetUses.sourceOf(key).flatMap(source -> snippetPattern(world, source, depth, area)); + } + return biomePattern(world, key, depth, area); + } + + // A snippet's palette is shown as the first biome that uses it places it; one nothing uses has no place in a + // biome's stack, so it is picked block by block, as a wall is. + private Optional snippetPattern(PackWorld world, PackSnippet.Source source, int depth, PatternArea area) { + Optional running = world.running(); + if (running.isEmpty()) { + return Optional.empty(); + } + SnippetUses snippetUses = new SnippetUses(); + biomeEntries(world, running.get().settings(), snippetUses); + Optional firstUse = snippetUses.firstUseOf(source); + if (firstUse.isPresent()) { + return biomePattern(world, firstUse.get().key(), depth, area); + } + return world.resources().snippets(PaletteLayer.class).stream() + .filter(snippet -> snippet.path().equals(source.path())) + .findFirst() + .map(snippet -> unusedSnippetPattern(world, snippet, source.entry(), depth, area, running.get().layout().fluidHeight())); + } + + // A file that could not be read is listed too, and places nothing. + private static BlockPattern unusedSnippetPattern(PackWorld world, PackSnippet snippet, int entry, int depth, PatternArea area, + int fluidHeight) { + if (entry >= snippet.entries().size()) { + return patternOf(area, (x, z, atDepth) -> null, depth); + } + ResolvedLayer layer = BiomeLayers.of(world).resolve(snippet.entries().get(entry)); + return patternOf(area, Kind.singleBlocks(layer, new RNG(world.seed(IrisSeedPurposes.TERRAIN)), fluidHeight), depth); + } + + private static BlockPattern patternOf(PatternArea area, ColumnPick pick, int depth) { + BlockState[] blocks = new BlockState[area.columns() * area.columns()]; + for (int row = 0; row < area.columns(); row++) { + for (int column = 0; column < area.columns(); column++) { + blocks[row * area.columns() + column] = pick.at(area.blockX(column), area.blockZ(row), depth); + } + } + return BlockPattern.of(area.columns(), blocks); + } + + private Optional biomePattern(PackWorld world, String key, int depth, PatternArea area) { Optional running = world.running(); Optional ref = PaletteRef.parse(key, world.resources()); if (running.isEmpty() || ref.isEmpty()) { @@ -113,13 +170,7 @@ public final class BiomePalettes implements PatternView { } ColumnPick pick = palette.kind().picker(world, layers, biome, palettes.get(palette.index()), palette.index(), running.get().layout().fluidHeight()); - BlockState[] blocks = new BlockState[area.columns() * area.columns()]; - for (int row = 0; row < area.columns(); row++) { - for (int column = 0; column < area.columns(); column++) { - blocks[row * area.columns() + column] = pick.at(area.blockX(column), area.blockZ(row), depth); - } - } - return Optional.of(BlockPattern.of(area.columns(), blocks)); + return Optional.of(patternOf(area, pick, depth)); } private static List biomesByName(PackResources resources) { @@ -130,11 +181,13 @@ public final class BiomePalettes implements PatternView { .toList(); } - private static PatternEntry entryOf(PackBiome biome, LayeredBiome layered, Kind kind, int index, PaletteLayer palette, String group) { + private static PatternEntry entryOf(PackBiome biome, LayeredBiome layered, Kind kind, int index, PaletteLayer palette, String group, + Optional snippet) { String key = biome.id() + String.valueOf(KIND_SEPARATOR) + kind.keyName + INDEX_SEPARATOR + index; String name = kind.numbered ? kind.label + " " + (index + 1) : kind.label; - return new PatternEntry(key, name, Optional.of(group).filter(shown -> !shown.isBlank()), kind.depthsOf(palette), - kind.factsOf(palette, layered)); + List facts = kind.factsOf(palette, layered); + snippet.map(SnippetUses::factOf).ifPresent(facts::add); + return new PatternEntry(key, name, Optional.of(group).filter(shown -> !shown.isBlank()), kind.depthsOf(palette), facts); } private static String blocksOf(PaletteLayer palette) { @@ -246,7 +299,7 @@ public final class BiomePalettes implements PatternView { }; } - private static ColumnPick singleBlocks(ResolvedLayer layer, RNG random, int height) { + static ColumnPick singleBlocks(ResolvedLayer layer, RNG random, int height) { return (x, z, depth) -> depth == 0 ? layer.get(random, SINGLE_BLOCK_SIGNATURE, x, height, z) : null; } } diff --git a/studio/src/renderer/src/bridge/tileDecoding.ts b/studio/src/renderer/src/bridge/tileDecoding.ts index b306c42c6..7f52ce186 100644 --- a/studio/src/renderer/src/bridge/tileDecoding.ts +++ b/studio/src/renderer/src/bridge/tileDecoding.ts @@ -46,7 +46,7 @@ export function decodeTile(buffer: ArrayBuffer): MapTile { blocks: header.blocks == null ? null - : { names: header.blocks, ground: new Int16Array(buffer, groundAt, cells), cover: new Int16Array(buffer, coverAt, cells), colors: [], looks: [] } + : { names: header.blocks, ground: new Int16Array(buffer, groundAt, cells), cover: new Int16Array(buffer, coverAt, cells), colors: [], looks: [], covers: [] } } } diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index 19f5ea227..a99beb039 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -1,6 +1,7 @@ /** The shapes the Iris bridge answers with (Iris core, art.arcane.iris.core.studio). */ import type { BlockLook } from '../scene/blockLooks' +import type { CoverLook } from '../scene/coverLooks' export type LabelKind = 'BIOME' | 'REGION' @@ -355,6 +356,8 @@ export interface TileBlocks { colors: number[] /** What each named block looks like on a column, where the tile is fine enough to show textures; else empty. */ looks: (BlockLook | null)[] + /** What each named block looks like standing on the ground, for the blocks {@link cover} names, on a tile that shows textures; else empty. */ + covers: (CoverLook | null)[] } export const NO_BLOCK = -1 diff --git a/studio/src/renderer/src/map/map.test.ts b/studio/src/renderer/src/map/map.test.ts index f68185225..b092de102 100644 --- a/studio/src/renderer/src/map/map.test.ts +++ b/studio/src/renderer/src/map/map.test.ts @@ -138,7 +138,7 @@ describe('tile style', () => { const cells = tile.subjects.length const cover = new Int16Array(cells).fill(-1) cover[gridIndex(tile, 3, 3)] = 1 - const blocks = { names: ['stone', 'poppy'], ground: new Int16Array(cells).fill(0), cover, colors: [0x808080, 0xff0000], looks: [] } + const blocks = { names: ['stone', 'poppy'], ground: new Int16Array(cells).fill(0), cover, colors: [0x808080, 0xff0000], looks: [], covers: [] } const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true }) expect(pixel(pixels, 4, 0, 0)).toBe(0x808080) diff --git a/studio/src/renderer/src/scene/blockArt.ts b/studio/src/renderer/src/scene/blockArt.ts index 009bd8b66..6bdf5038d 100644 --- a/studio/src/renderer/src/scene/blockArt.ts +++ b/studio/src/renderer/src/scene/blockArt.ts @@ -1,5 +1,5 @@ import type { BridgeClient } from '../bridge/BridgeClient' -import type { TileBlocks } from '../bridge/types' +import { NO_BLOCK, type TileBlocks } from '../bridge/types' import { BlockColors } from './blockColors' import { BlockLooks } from './blockLooks' import { BlockModels } from './blockModels' @@ -15,6 +15,13 @@ export interface BlockArt { dispose(): void } +// Only these have their whole model's pictures placed, so the ground's blocks take no room in the atlas for faces a column never shows. +function namesStandingOnGround(blocks: TileBlocks): string[] { + const standing = new Set(blocks.cover) + standing.delete(NO_BLOCK) + return [...standing].map((index) => blocks.names[index]) +} + /** Block art read from the Minecraft client's assets through the bridge; {@code textured} art can also show textures. */ export function blockArt(client: BridgeClient, textured: boolean): BlockArt { const images = new BridgeAssets(client, () => {}) @@ -25,9 +32,15 @@ export function blockArt(client: BridgeClient, textured: boolean): BlockArt { return { atlas, paint: async (blocks, withLooks) => { - const [colorOf, lookOf] = await Promise.all([colors.colorsOf(blocks.names), withLooks && looks !== null ? looks.looksOf(blocks.names) : null]) + const shownLooks = withLooks ? looks : null + const [colorOf, lookOf, coverOf] = await Promise.all([ + colors.colorsOf(blocks.names), + shownLooks?.looksOf(blocks.names) ?? null, + shownLooks?.coversOf(namesStandingOnGround(blocks)) ?? null + ]) blocks.colors = blocks.names.map((name) => colorOf.get(name)!) blocks.looks = lookOf === null ? [] : blocks.names.map((name) => lookOf.get(name) ?? null) + blocks.covers = coverOf === null ? [] : blocks.names.map((name) => coverOf.get(name) ?? null) }, dispose: () => atlas?.dispose() } diff --git a/studio/src/renderer/src/scene/blockLooks.ts b/studio/src/renderer/src/scene/blockLooks.ts index 867d20c9f..496a00b3f 100644 --- a/studio/src/renderer/src/scene/blockLooks.ts +++ b/studio/src/renderer/src/scene/blockLooks.ts @@ -1,5 +1,6 @@ import { parseState, type BlockModel, type Direction, type ParsedState } from './blockModels' import { blockTint } from './blockTints' +import { coverLookOf, type CoverLook } from './coverLooks' import type { PictureSource, UvCell } from './terrainAtlas' const NO_TINT_INDEX = -1 @@ -68,6 +69,7 @@ function untintedFacing(model: BlockModel, facing: Direction): FaceTexture | nul /** The look of each block state the terrain draws, read once. */ export class BlockLooks { private readonly looks = new Map>() + private readonly covers = new Map>() private dirtBottom: Promise | null = null constructor( @@ -85,6 +87,25 @@ export class BlockLooks { return look } + /** What each block looks like standing on the ground, by name; null for one that is not drawn there. */ + async coversOf(blocks: Iterable): Promise> { + const names = [...new Set(blocks)] + const looks = await Promise.all(names.map((name) => this.coverOf(name))) + return new Map(names.map((name, index) => [name, looks[index]])) + } + + private coverOf(block: string): Promise { + let cover = this.covers.get(block) + if (cover === undefined) { + cover = this.models + .model(block) + .then((model) => coverLookOf(block, model, this.pictures)) + .catch(() => null) + this.covers.set(block, cover) + } + return cover + } + /** Every block's look, by name. */ async looksOf(blocks: Iterable): Promise> { const names = [...new Set(blocks)] diff --git a/studio/src/renderer/src/scene/columnField.ts b/studio/src/renderer/src/scene/columnField.ts index 65fe9f4cd..33907e977 100644 --- a/studio/src/renderer/src/scene/columnField.ts +++ b/studio/src/renderer/src/scene/columnField.ts @@ -1,4 +1,5 @@ import type { BlockLook } from './blockLooks' +import type { CoverLook } from './coverLooks' import type { TerrainPictures } from './terrainAtlas' import type { TerrainSurface } from './terrainMesh' import type { ColumnArea } from './terrainTiles' @@ -21,6 +22,8 @@ export class ColumnField { readonly color: Int32Array /** What each column's block looks like, or null to show its colour. */ readonly looks: (BlockLook | null)[] + /** What stands on each column's ground, or null for nothing that is drawn. */ + readonly covers: (CoverLook | null)[] /** The atlas of the looks, or null where no column has one. */ readonly pictures: TerrainPictures | null /** How low and high the top faces stand, ground and water alike; null where no column has ground. */ @@ -37,6 +40,7 @@ export class ColumnField { this.waterTop = new Float32Array(count).fill(NO_VALUE) this.color = new Int32Array(count) this.looks = new Array(count).fill(null) + this.covers = new Array(count).fill(null) const hasPictures = surface.pictures !== undefined let anyLook = false let [lowestTop, highestTop] = [Infinity, -Infinity] @@ -54,6 +58,7 @@ export class ColumnField { this.color[index] = surface.colorAt(column, row) const look = hasPictures ? (surface.lookAt?.(column, row) ?? null) : null this.looks[index] = look + this.covers[index] = hasPictures ? (surface.coverAt?.(column, row) ?? null) : null anyLook ||= look !== null lowestTop = Math.min(lowestTop, ground + 1) highestTop = Math.max(highestTop, ground + 1, water === null ? ground : water + 1) diff --git a/studio/src/renderer/src/scene/coverFaces.ts b/studio/src/renderer/src/scene/coverFaces.ts new file mode 100644 index 000000000..9d5e1b3ab --- /dev/null +++ b/studio/src/renderer/src/scene/coverFaces.ts @@ -0,0 +1,45 @@ +import { BufferAttribute, BufferGeometry } from 'three' +import type { ColumnField } from './columnField' + +const CORNERS_PER_FACE = 4 +const INDICES_PER_FACE = 6 + +/** + * What stands on the ground, such as grass, flowers and layers of snow: each column's cover as its block's own model, + * set on the column's top face. Null where no column has a cover. + */ +export function coverGeometry(field: ColumnField): BufferGeometry | null { + const faces = field.covers.reduce((count, cover) => count + (cover?.faces.length ?? 0), 0) + if (faces === 0) { + return null + } + const positions = new Float32Array(faces * CORNERS_PER_FACE * 3) + const uvs = new Float32Array(faces * CORNERS_PER_FACE * 2) + const colors = new Float32Array(faces * CORNERS_PER_FACE * 3) + const indices = new Uint32Array(faces * INDICES_PER_FACE) + const step = field.blocksPerColumn + let face = 0 + for (let row = 0; row < field.rows; row++) { + for (let column = 0; column < field.columns; column++) { + const index = field.indexOf(column, row) + const [x, y, z] = [field.originX + column * step, field.groundTop[index], field.originZ + row * step] + for (const { corners, uvs: faceUvs, cell, color } of field.covers[index]?.faces ?? []) { + const first = face * CORNERS_PER_FACE + for (let corner = 0; corner < CORNERS_PER_FACE; corner++) { + const [cornerX, cornerY, cornerZ] = corners[corner] + positions.set([x + cornerX * step, y + cornerY, z + cornerZ * step], (first + corner) * 3) + uvs.set([cell.u + faceUvs[corner][0] * cell.width, cell.v + faceUvs[corner][1] * cell.height], (first + corner) * 2) + colors.set(color, (first + corner) * 3) + } + indices.set([first, first + 1, first + 2, first, first + 2, first + 3], face * INDICES_PER_FACE) + face++ + } + } + } + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(positions, 3)) + geometry.setAttribute('uv', new BufferAttribute(uvs, 2)) + geometry.setAttribute('color', new BufferAttribute(colors, 3)) + geometry.setIndex(new BufferAttribute(indices, 1)) + return geometry +} diff --git a/studio/src/renderer/src/scene/coverLooks.ts b/studio/src/renderer/src/scene/coverLooks.ts new file mode 100644 index 000000000..2c4da5344 --- /dev/null +++ b/studio/src/renderer/src/scene/coverLooks.ts @@ -0,0 +1,44 @@ +import { parseState, type BlockModel, type Direction, type Quad } from './blockModels' +import { blockTint } from './blockTints' +import type { PictureSource, UvCell } from './terrainAtlas' + +/** The light Minecraft gives each side of a block without shadows: the top brightest, the bottom darkest. */ +export const FACE_LIGHT: Record = { up: 1, down: 0.5, north: 0.8, south: 0.8, west: 0.6, east: 0.6 } + +/** One face of a block that stands on the ground, in block units from the block's lowest corner. */ +export interface CoverFace { + corners: Quad['corners'] + uvs: Quad['uvs'] + cell: UvCell + /** The face's tint in its light, as red, green and blue from 0 to 1. */ + color: readonly [number, number, number] +} + +/** A block standing on a column's ground, such as grass, a flower or a layer of snow, as the faces of its model. */ +export interface CoverLook { + faces: CoverFace[] +} + +/** + * The block's model with its pictures placed; null for a block the client draws without a model, such as a chest, or + * when one of its pictures cannot be placed, so a cover is drawn whole or not at all. + */ +export async function coverLookOf(block: string, model: BlockModel | null, pictures: PictureSource): Promise { + if (model === null || model.quads.length === 0) { + return null + } + const state = parseState(block) + const faces = await Promise.all( + model.quads.map(async (quad): Promise => { + const cell = await pictures.cellOf(quad.texture) + if (cell === null) { + return null + } + const tint = blockTint(state.name, state.properties, quad.tintIndex) + const light = quad.shade ? FACE_LIGHT[quad.facing] : 1 + const color = [(((tint >> 16) & 0xff) / 255) * light, (((tint >> 8) & 0xff) / 255) * light, ((tint & 0xff) / 255) * light] as const + return { corners: quad.corners, uvs: quad.uvs, cell, color } + }) + ) + return faces.includes(null) ? null : { faces: faces as CoverFace[] } +} diff --git a/studio/src/renderer/src/scene/mapTerrain.ts b/studio/src/renderer/src/scene/mapTerrain.ts index 68bad36a7..190b1e113 100644 --- a/studio/src/renderer/src/scene/mapTerrain.ts +++ b/studio/src/renderer/src/scene/mapTerrain.ts @@ -1,6 +1,7 @@ import { NO_BLOCK, NO_LABEL, type MapTile } from '../bridge/types' import { heightColor } from '../map/heightColors' import type { BlockLook } from './blockLooks' +import type { CoverLook } from './coverLooks' import type { TerrainPictures } from './terrainAtlas' import type { TerrainSurface } from './terrainMesh' import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles' @@ -48,6 +49,14 @@ export class MapTerrain implements TerrainSurface { return ground === NO_BLOCK ? null : (this.tile.blocks!.looks[ground] ?? null) } + coverAt(column: number, row: number): CoverLook | null { + if (this.groundBlockAt(column, row) === NO_BLOCK) { + return null + } + const cover = this.tile.blocks!.cover[this.cellAt(column, row)] + return cover === NO_BLOCK ? null : (this.tile.blocks!.covers[cover] ?? null) + } + colorAt(column: number, row: number): number { if (this.coloring === 'height') { return heightColor(this.heightAt(column, row), this.fluidHeight) diff --git a/studio/src/renderer/src/scene/savedTerrain.test.ts b/studio/src/renderer/src/scene/savedTerrain.test.ts index 9925506c0..4387f1167 100644 --- a/studio/src/renderer/src/scene/savedTerrain.test.ts +++ b/studio/src/renderer/src/scene/savedTerrain.test.ts @@ -9,7 +9,7 @@ const GRASS = 'minecraft:grass_block[snowy=false]' const STONE = 'minecraft:stone' const FACE = { cell: cellAt(1, 0x808080), tint: 0xffffff, color: 0x808080 } const LOOK: BlockLook = { top: FACE, side: FACE, below: FACE } -const pictures: TerrainPictures = { texture: new Texture(), plain: cellAt(0, 0xffffff) } +const pictures: TerrainPictures = { texture: new Texture(), cutouts: new Texture(), plain: cellAt(0, 0xffffff) } // Two by two columns: grass, stone, then two of stone. const tile = { diff --git a/studio/src/renderer/src/scene/sceneMesh.ts b/studio/src/renderer/src/scene/sceneMesh.ts index 8a77c3575..6c96c4259 100644 --- a/studio/src/renderer/src/scene/sceneMesh.ts +++ b/studio/src/renderer/src/scene/sceneMesh.ts @@ -2,6 +2,7 @@ import { Box3, BufferAttribute, BufferGeometry, Group, Mesh, MeshBasicMaterial } import type { ViewportContent } from '../studio/SceneViewport' import { cubeModel, parseState, type BlockModels, type BlockModel, type Direction, type Quad } from './blockModels' import { blockTint } from './blockTints' +import { FACE_LIGHT } from './coverLooks' import { countFarLeaves, isFarLeaf } from './farLeaves' import { INTS_PER_BLOCK, type BlockScene } from './sceneDecoding' import { TextureAtlas, type ImageSource } from './textureAtlas' @@ -18,8 +19,6 @@ const CUTOUT_ALPHA = 0.1 /** How much of a faint block shows, from 0 for none to 1 for all. */ const FAINT_OPACITY = 0.12 -/** The light Minecraft gives each side of a block without shadows: the top brightest, the bottom darkest. */ -const FACE_LIGHT: Record = { up: 1, down: 0.5, north: 0.8, south: 0.8, west: 0.6, east: 0.6 } const MISSING_TEXTURE = 'iris:missing' const NEIGHBOUR_OFFSETS: Record = { down: [0, -1, 0], diff --git a/studio/src/renderer/src/scene/terrainAtlas.ts b/studio/src/renderer/src/scene/terrainAtlas.ts index 6f71deed4..8097a5221 100644 --- a/studio/src/renderer/src/scene/terrainAtlas.ts +++ b/studio/src/renderer/src/scene/terrainAtlas.ts @@ -14,6 +14,8 @@ export interface UvCell { /** The atlas as the terrain draws it. */ export interface TerrainPictures { readonly texture: Texture + /** Laid out as {@link texture}: white where a picture is drawn and black where it is open, for faces that are cut out. */ + readonly cutouts: Texture /** A cell of plain white, for faces that show only their colour. */ readonly plain: UvCell } @@ -55,25 +57,21 @@ export const MOST_CELLS = CELLS_PER_SIDE * CELLS_PER_SIDE */ export class TerrainAtlas implements TerrainPictures, PictureSource { readonly texture: CanvasTexture + readonly cutouts: CanvasTexture readonly plain = cellAt(PLAIN_CELL, WHITE_COLOR) private readonly drawing: CanvasRenderingContext2D + private readonly cutoutDrawing: CanvasRenderingContext2D private readonly cells = new Map>() private used = PLAIN_CELL + 1 constructor(private readonly images: ImageSource) { - const canvas = document.createElement('canvas') - canvas.width = ATLAS_PIXELS - canvas.height = ATLAS_PIXELS - this.drawing = canvas.getContext('2d', { willReadFrequently: true })! - this.drawing.imageSmoothingEnabled = false - this.drawing.fillStyle = WHITE - this.drawing.fillRect(0, 0, CELL_PIXELS, CELL_PIXELS) - this.texture = new CanvasTexture(canvas) - this.texture.magFilter = NearestFilter - this.texture.minFilter = NearestFilter - this.texture.generateMipmaps = false - this.texture.flipY = false + ;[this.drawing, this.texture] = sheet() + ;[this.cutoutDrawing, this.cutouts] = sheet() + for (const drawing of [this.drawing, this.cutoutDrawing]) { + drawing.fillStyle = WHITE + drawing.fillRect(0, 0, CELL_PIXELS, CELL_PIXELS) + } } cellOf(textureId: string): Promise { @@ -87,6 +85,7 @@ export class TerrainAtlas implements TerrainPictures, PictureSource { dispose(): void { this.texture.dispose() + this.cutouts.dispose() } private async place(textureId: string): Promise { @@ -101,12 +100,38 @@ export class TerrainAtlas implements TerrainPictures, PictureSource { this.drawing.drawImage(bitmap, 0, 0, bitmap.width, Math.min(bitmap.width, bitmap.height), left, top, CELL_PIXELS, CELL_PIXELS) const picture = this.drawing.getImageData(left, top, CELL_PIXELS, CELL_PIXELS) const average = averageColor(picture) + this.cutoutDrawing.putImageData(cutoutOf(picture), left, top) this.drawing.putImageData(withGapsFilled(picture, average), left, top) this.texture.needsUpdate = true + this.cutouts.needsUpdate = true return { ...placed, average } } } +function sheet(): [CanvasRenderingContext2D, CanvasTexture] { + const canvas = document.createElement('canvas') + canvas.width = ATLAS_PIXELS + canvas.height = ATLAS_PIXELS + const drawing = canvas.getContext('2d', { willReadFrequently: true })! + drawing.imageSmoothingEnabled = false + const texture = new CanvasTexture(canvas) + texture.magFilter = NearestFilter + texture.minFilter = NearestFilter + texture.generateMipmaps = false + texture.flipY = false + return [drawing, texture] +} + +// A canvas keeps no colour under a transparent pixel, so the picture cannot carry both its filled gaps and where they were. +function cutoutOf(picture: ImageData): ImageData { + const cutout = new ImageData(picture.width, picture.height) + for (let offset = 0; offset < picture.data.length; offset += 4) { + const shade = picture.data[offset + 3] < OPAQUE_ENOUGH_ALPHA ? 0 : 255 + cutout.data.set([shade, shade, shade, OPAQUE_ALPHA], offset) + } + return cutout +} + // The terrain draws whole faces, so what a picture leaves open, as leaves do between their twigs, would show as black: // it takes the picture's own colour instead, darker, as the shade seen through the gaps. function withGapsFilled(picture: ImageData, average: number): ImageData { diff --git a/studio/src/renderer/src/scene/terrainMesh.ts b/studio/src/renderer/src/scene/terrainMesh.ts index 2cff31522..0a9525279 100644 --- a/studio/src/renderer/src/scene/terrainMesh.ts +++ b/studio/src/renderer/src/scene/terrainMesh.ts @@ -2,6 +2,8 @@ import { DoubleSide, FrontSide, Group, Mesh, MeshBasicMaterial } from 'three' import type { BlockLook } from './blockLooks' import { groundFaces, waterFaces } from './columnFaces' import { ColumnField } from './columnField' +import { coverGeometry } from './coverFaces' +import type { CoverLook } from './coverLooks' import type { TerrainPictures } from './terrainAtlas' import type { ColumnArea } from './terrainTiles' import { WATER_SURFACE_COLOR, WATER_SURFACE_OPACITY } from './waterTint' @@ -27,8 +29,12 @@ export interface TerrainSurface { readonly pictures?: TerrainPictures /** What the block of the column looks like, or null to show the column in its colour. */ lookAt?(column: number, row: number): BlockLook | null + /** What stands on the column's ground, such as grass or a flower, or null for nothing that is drawn. */ + coverAt?(column: number, row: number): CoverLook | null } +const CUTOUT_ALPHA = 0.5 + export interface TerrainMesh { object: Group field: ColumnField @@ -51,7 +57,9 @@ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: r const water = waterFaces(field).geometry() const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: FrontSide, map: field.pictures?.texture ?? null }) const waterMaterial = new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide }) - group.add(new Mesh(ground, groundMaterial), new Mesh(water, waterMaterial)) + const cover = field.pictures === null ? null : coverMesh(field, field.pictures) + // The water is drawn last, over what stands under it. + group.add(new Mesh(ground, groundMaterial), ...(cover === null ? [] : [cover.mesh]), new Mesh(water, waterMaterial)) return { object: group, field, @@ -60,6 +68,22 @@ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: r water.dispose() groundMaterial.dispose() waterMaterial.dispose() + cover?.dispose() + } + } +} + +function coverMesh(field: ColumnField, pictures: TerrainPictures): { mesh: Mesh; dispose(): void } | null { + const geometry = coverGeometry(field) + if (geometry === null) { + return null + } + const material = new MeshBasicMaterial({ vertexColors: true, map: pictures.texture, alphaMap: pictures.cutouts, alphaTest: CUTOUT_ALPHA, side: FrontSide }) + return { + mesh: new Mesh(geometry, material), + dispose: () => { + geometry.dispose() + material.dispose() } } } diff --git a/studio/src/renderer/src/scene/texturedTerrain.test.ts b/studio/src/renderer/src/scene/texturedTerrain.test.ts index 4e37b708f..714ab015f 100644 --- a/studio/src/renderer/src/scene/texturedTerrain.test.ts +++ b/studio/src/renderer/src/scene/texturedTerrain.test.ts @@ -1,6 +1,7 @@ import { Texture, Vector3, type BufferGeometry, type Mesh, type MeshBasicMaterial } from 'three' import { describe, expect, it } from 'vitest' import type { BlockLook, FaceLook } from './blockLooks' +import type { CoverLook } from './coverLooks' import { cellAt, type TerrainPictures } from './terrainAtlas' import { buildTerrainMesh, type TerrainSurface } from './terrainMesh' @@ -16,7 +17,7 @@ const GRASS_TINT = 0x91bd59 const WHITE = 0xffffff const plain = cellAt(0, WHITE) -const pictures: TerrainPictures = { texture: new Texture(), plain } +const pictures: TerrainPictures = { texture: new Texture(), cutouts: new Texture(), plain } const cellWidth = plain.width function face(index: number, tint = WHITE): FaceLook { @@ -143,6 +144,36 @@ describe('textured terrain', () => { expect((ground.material as MeshBasicMaterial).map).toBeNull() }) + it('stands a cover on the top face of its column, cut out along its picture', () => { + const blade: CoverLook = { + faces: [ + { + corners: [[0, 1, 0], [0, 0, 0], [1, 0, 1], [1, 1, 1]], + uvs: [[0, 0], [0, 1], [1, 1], [1, 0]], + cell: cellAt(4, WHITE), + color: [0.5, 0.75, 0.25] + } + ] + } + const terrain = { ...surfaceOf(() => grass), coverAt: (column: number, row: number) => (column === PEAK_COLUMN && row === PEAK_COLUMN ? blade : null) } + const [, cover, water] = buildTerrainMesh(terrain, FLOOR).object.children as Mesh[] + const positions = cover.geometry.getAttribute('position') + const material = cover.material as MeshBasicMaterial + + expect(water).toBeDefined() + expect(positions.count).toBe(4) + expect([positions.getX(1), positions.getY(1), positions.getZ(1)]).toEqual([ORIGIN_X + PEAK_COLUMN, PEAK_GROUND + 1, ORIGIN_Z + PEAK_COLUMN]) + expect([positions.getX(3), positions.getY(3), positions.getZ(3)]).toEqual([ORIGIN_X + PEAK_COLUMN + 1, PEAK_GROUND + 2, ORIGIN_Z + PEAK_COLUMN + 1]) + expect(uvOf(cover.geometry, 0, 2)).toEqual([blade.faces[0].cell.u + cellWidth, blade.faces[0].cell.v + cellWidth]) + expect(cover.geometry.getAttribute('color').getY(0)).toBeCloseTo(0.75) + expect(material.alphaMap).toBe(pictures.cutouts) + expect(material.alphaTest).toBeGreaterThan(0) + }) + + it('draws no cover mesh where nothing stands on the ground', () => { + expect(buildTerrainMesh(surfaceOf(() => grass), FLOOR).object.children).toHaveLength(2) + }) + it('draws a surface without an atlas in its colour alone', () => { const ground = groundOf(surfaceOf(() => grass, LOW_GROUND, false)) diff --git a/studio/src/renderer/src/studio/PatternStudio.tsx b/studio/src/renderer/src/studio/PatternStudio.tsx index f33e114a7..764fc9fa2 100644 --- a/studio/src/renderer/src/studio/PatternStudio.tsx +++ b/studio/src/renderer/src/studio/PatternStudio.tsx @@ -15,8 +15,8 @@ import { Panel, SidebarPanel, Stepper, ViewIsland } from './Sidebar' import { TiledCanvas } from './TiledCanvas' const DEFAULT_NAMESPACE_PREFIX = 'minecraft:' -// A layer thinner than the depth shown, or a palette with no block for the spot. -const NONE_LABEL = 'nothing at this depth' +// A layer thinner than the depth shown, a palette with no block for the spot, or a spot a decorator leaves bare. +const NONE_LABEL = 'nothing placed' /** The blocks the shown layer's tiles placed so far by name, each with one state to draw its icon as, and whether some spots got none. */ interface LegendBlocks { @@ -196,7 +196,7 @@ function Legend({ blocks, looks }: { blocks: LegendBlocks; looks: BlockColors }) {blocks.someNone && (
- Nothing at this depth + Nothing placed
)} diff --git a/studio/src/renderer/src/studio/ViewList.tsx b/studio/src/renderer/src/studio/ViewList.tsx index e0f85a623..6b7f3becc 100644 --- a/studio/src/renderer/src/studio/ViewList.tsx +++ b/studio/src/renderer/src/studio/ViewList.tsx @@ -14,6 +14,7 @@ const VIEW_ICONS: Record = { world3d: 'views/world-3d', savedWorld: 'views/saved-world', 'iris:terrain/palettes': 'views/palettes', + 'iris:decorant/decorators': 'decoration', 'iris:objects': 'views/objects', 'iris:objects/procedural': 'views/procedural', noise: 'views/noise'