diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java index 5befe9cb3..d9d3db3eb 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java @@ -38,14 +38,18 @@ import java.util.function.Function; * f32 heights[grid²], when the header says so | f32 pickNoise[grid²], when the header says so * i16 ground[grid²] | padding to 4 | i16 cover[grid²] | padding to 4 | i16 raisedCounts[grid²] | padding to 4 * | i16 raisedY[raised] | padding to 4 | i16 raised[raised] | padding to 4, when the header names blocks + * u8 voxelX[voxels] | padding to 4 | u8 voxelZ[voxels] | padding to 4 | i16 voxelY[voxels] | padding to 4 + * | i16 voxelBlock[voxels] | padding to 4 | u8 voxelFaces[voxels] | padding to 4, when the header counts voxels * - * {@code raised} is the sum of the raised counts, which the header also holds. + * {@code raised} is the sum of the raised counts, which the header also holds, as it holds {@code voxels}, the count of + * blocks seen from the open air, or -1 for a tile without them. * The header holds the size, the scale, the subject kind, the labels the grids index, and the blocks the ground and * cover grids index when the tile carries the tops of its columns, each as the state players see. Every array starts on a * multiple of 4 bytes, so the studio views them in place. */ final class MapTileEncoding { private static final int ALIGNMENT_BYTES = 4; + private static final int NO_VOXELS = -1; private MapTileEncoding() { } @@ -59,15 +63,18 @@ final class MapTileEncoding { boolean hasPickNoise = tile.pickNoise() != null; MapTile.Blocks blocks = tile.blocks(); int raised = blocks == null ? 0 : blocks.raised().length; + MapTile.Voxels voxels = blocks == null ? null : blocks.voxels(); + int voxelCount = voxels == null ? NO_VOXELS : voxels.count(); byte[] header = gson.toJson(new Header(tile.size(), tile.blocksPerPixel(), tile.subjectKind(), tile.labels(), - hasHeights, hasPickNoise, blocks == null ? null : statesPlayersSee(blocks.names(), pluginLooks), raised)) + hasHeights, hasPickNoise, blocks == null ? null : statesPlayersSee(blocks.names(), pluginLooks), raised, voxelCount)) .getBytes(StandardCharsets.UTF_8); int cells = tile.gridSize() * tile.gridSize(); int length = aligned(Integer.BYTES + header.length) + aligned(cells * Short.BYTES) * 2 + (hasHeights ? cells * Float.BYTES : 0) + (hasPickNoise ? cells * Float.BYTES : 0) - + (blocks == null ? 0 : aligned(cells * Short.BYTES) * 3 + aligned(raised * Short.BYTES) * 2); + + (blocks == null ? 0 : aligned(cells * Short.BYTES) * 3 + aligned(raised * Short.BYTES) * 2) + + (voxels == null ? 0 : aligned(voxelCount) * 3 + aligned(voxelCount * Short.BYTES) * 2); ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(header.length).put(header); align(buffer); @@ -88,9 +95,21 @@ final class MapTileEncoding { putShorts(buffer, blocks.raisedY()); putShorts(buffer, blocks.raised()); } + if (voxels != null) { + putBytes(buffer, voxels.x()); + putBytes(buffer, voxels.z()); + putShorts(buffer, voxels.y()); + putShorts(buffer, voxels.blocks()); + putBytes(buffer, voxels.faces()); + } return buffer.array(); } + private static void putBytes(ByteBuffer buffer, byte[] values) { + buffer.put(values); + align(buffer); + } + private static void putShorts(ByteBuffer buffer, short[] grid) { buffer.asShortBuffer().put(grid); buffer.position(aligned(buffer.position() + grid.length * Short.BYTES)); @@ -111,6 +130,6 @@ final class MapTileEncoding { } private record Header(int size, double blocksPerPixel, MapLabel.Kind subjectKind, List labels, - boolean heights, boolean pickNoise, List blocks, int raised) { + boolean heights, boolean pickNoise, List blocks, int raised, int voxels) { } } diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java index 8c394524d..1f5e1d56a 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java @@ -632,7 +632,7 @@ public final class StudioBridge implements AutoCloseable { BooleanSupplier cancelled = () -> dropped.get() || closed || engine.isClosing() || engine.isClosed(); MapTile tile = session.renderer().render(layer, startX, startZ, blocksPerPixel, size, tileExtras(query), cancelled); if (query.has("blocks")) { - tile = withBlocks(session, tile, startX, startZ, blockSource(query), cancelled); + tile = withBlocks(session, tile, startX, startZ, blockSource(query), query.flag("voxels"), cancelled); } return MapTileEncoding.encode(tile, gson, StudioBridge::pluginLookOf); } @@ -661,9 +661,9 @@ public final class StudioBridge implements AutoCloseable { } private static MapTile withBlocks(StudioWorld.Session session, MapTile tile, double startX, double startZ, BlockSource source, - BooleanSupplier cancelled) { + boolean withVoxels, BooleanSupplier cancelled) { try { - return session.renderer().withBlocks(tile, startX, startZ, source, cancelled); + return session.renderer().withBlocks(tile, startX, startZ, source, withVoxels, cancelled); } catch (IllegalArgumentException tooCoarse) { throw new RequestError(STATUS_BAD_REQUEST, tooCoarse.getMessage()); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java index e51017a19..b14bac190 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java @@ -35,6 +35,26 @@ interface ColumnTops { return this; } + /** + * The blocks seen in the square of columns {@code size} across from ({@code minX}, {@code minZ}), or null where the + * source knows only the tops of its columns. + */ + default TileVoxels voxelsIn(int minX, int minZ, int size) { + return null; + } + + /** + * Blocks seen in a square of columns, each with the sides that face the open air. + * + * @param x each block's column from the square's west edge + * @param z each block's column from the square's north edge + * @param y each block's height above the dimension's bottom + * @param blocks each block's key + * @param faces the sides of each block that face the open air, in {@link VisibleBlocks#SIDES}' order + */ + record TileVoxels(byte[] x, byte[] z, short[] y, String[] blocks, byte[] faces) { + } + /** * The top of one column. * 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 b9e7db602..3d3c8e0e3 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 @@ -29,6 +29,7 @@ import art.arcane.iris.util.project.context.IrisContext; import art.arcane.iris.util.project.hunk.Hunk; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; +import it.unimi.dsi.fastutil.bytes.ByteArrayList; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.LongArrayList; @@ -69,6 +70,8 @@ final class GeneratedChunks implements ColumnTops { // blocks out to the horizon holds tens of thousands of chunks. private static final int CHUNK_TOP_BYTES = 5 * 1024; private static final int RAISED_BLOCK_BYTES = Short.BYTES + Integer.BYTES; + // Its place, a shared key and the sides it shows. + private static final int VISIBLE_BLOCK_BYTES = Integer.BYTES + Integer.BYTES + Byte.BYTES; private static final long MOST_BYTES_KEPT = 512L * 1024 * 1024; private static final String LEASE_NAME = "studio_block_preview"; // Half the cores, as the bridge does, so a studio filling its view leaves the server room to run. @@ -104,15 +107,21 @@ final class GeneratedChunks implements ColumnTops { boolean keepsChunks = grid.step() < BLOCKS_ACROSS; Long2ObjectMap columnsByChunk = columnsByChunkOf(grid); Map found = new ConcurrentHashMap<>(); + Map chunks = new ConcurrentHashMap<>(); List> generating = new ArrayList<>(); for (Long2ObjectMap.Entry chunk : columnsByChunk.long2ObjectEntrySet()) { long key = chunk.getLongKey(); ChunkTop known = tops.getIfPresent(key); if (known != null) { - readColumns(known, chunk.getValue(), found); + read(key, known, keepsChunks, chunk.getValue(), found, chunks); continue; } - ChunkTask task = new ChunkTask(() -> readGenerated(key, keepsChunks, chunk.getValue(), found, grid.cancelled()), grid.step()); + Runnable generation = () -> { + if (!grid.cancelled().getAsBoolean()) { + read(key, keepsChunks ? tops.get(key) : topWithoutKeeping(key), keepsChunks, chunk.getValue(), found, chunks); + } + }; + ChunkTask task = new ChunkTask(generation, grid.step()); GENERATORS.execute(task); generating.add(task); } @@ -124,10 +133,66 @@ final class GeneratedChunks implements ColumnTops { generating.forEach(task -> task.cancel(false)); throw cancelled; } - return (worldX, worldZ) -> { - ColumnTop column = found.get(keyOf(worldX, worldZ)); - return column != null ? column : at(worldX, worldZ); - }; + return new PreparedTile(found, chunks); + } + + /** A tile's columns, and the chunks it keeps, read as its chunks were generated. */ + private final class PreparedTile implements ColumnTops { + private final Map columns; + private final Map chunks; + + PreparedTile(Map columns, Map chunks) { + this.columns = columns; + this.chunks = chunks; + } + + @Override + public ColumnTop at(int worldX, int worldZ) { + ColumnTop column = columns.get(keyOf(worldX, worldZ)); + return column != null ? column : GeneratedChunks.this.at(worldX, worldZ); + } + + @Override + public TileVoxels voxelsIn(int minX, int minZ, int size) { + TileVoxelsBuilder voxels = new TileVoxelsBuilder(); + for (int chunkZ = minZ >> CHUNK_SHIFT; chunkZ <= (minZ + size - 1) >> CHUNK_SHIFT; chunkZ++) { + for (int chunkX = minX >> CHUNK_SHIFT; chunkX <= (minX + size - 1) >> CHUNK_SHIFT; chunkX++) { + long key = keyOf(chunkX, chunkZ); + ChunkTop chunk = chunks.get(key); + voxels.addInside(chunk != null ? chunk : tops.get(key), chunkX << CHUNK_SHIFT, chunkZ << CHUNK_SHIFT, minX, minZ, size); + } + } + return voxels.build(); + } + } + + private static final class TileVoxelsBuilder { + private final ByteArrayList x = new ByteArrayList(); + private final ByteArrayList z = new ByteArrayList(); + private final ShortArrayList y = new ShortArrayList(); + private final List blocks = new ArrayList<>(); + private final ByteArrayList faces = new ByteArrayList(); + + void addInside(ChunkTop chunk, int chunkMinX, int chunkMinZ, int minX, int minZ, int size) { + VisibleBlocks visible = chunk.visible(); + for (int at = 0; at < visible.count(); at++) { + int position = visible.positions()[at]; + int squareX = chunkMinX + (position & CHUNK_MASK) - minX; + int squareZ = chunkMinZ + ((position >> CHUNK_SHIFT) & CHUNK_MASK) - minZ; + if (squareX < 0 || squareZ < 0 || squareX >= size || squareZ >= size) { + continue; + } + x.add((byte) squareX); + z.add((byte) squareZ); + y.add((short) (position >> VisibleBlocks.POSITION_Y_SHIFT)); + blocks.add(visible.blocks()[at]); + faces.add(visible.faces()[at]); + } + } + + TileVoxels build() { + return new TileVoxels(x.toByteArray(), z.toByteArray(), y.toShortArray(), blocks.toArray(String[]::new), faces.toByteArray()); + } } private static Long2ObjectMap columnsByChunkOf(TileGrid grid) { @@ -143,11 +208,11 @@ final class GeneratedChunks implements ColumnTops { return columnsByChunk; } - private void readGenerated(long key, boolean keepsChunk, LongList columns, Map found, BooleanSupplier cancelled) { - if (cancelled.getAsBoolean()) { - return; + private static void read(long key, ChunkTop chunk, boolean keepsChunk, LongList columns, Map found, Map chunks) { + readColumns(chunk, columns, found); + if (keepsChunk) { + chunks.put(key, chunk); } - readColumns(keepsChunk ? tops.get(key) : topWithoutKeeping(key), columns, found); } private ChunkTop topWithoutKeeping(long key) { @@ -230,7 +295,8 @@ final class GeneratedChunks implements ColumnTops { engine.getGeneration().generate(chunkX << CHUNK_SHIFT, chunkZ << CHUNK_SHIFT, blocks, biomes, false, lease.sessionId()); } IntBinaryOperator terrainY = (x, z) -> engine.getHeight((chunkX << CHUNK_SHIFT) + x, (chunkZ << CHUNK_SHIFT) + z, true); - return new ChunkTop(topsOf(blocks, terrainY, this::seenByPlayers)); + int fluidHeight = engine.getDimension().getFluidHeight(); + return new ChunkTop(topsOf(blocks, terrainY, this::seenByPlayers), VisibleBlocks.of(blocks, terrainY, fluidHeight, this::seenByPlayers)); } // A plugin's block can be solid on the server where players see grass they walk through. @@ -248,13 +314,13 @@ final class GeneratedChunks implements ColumnTops { return ((long) chunkX << Integer.SIZE) | (chunkZ & 0xFFFFFFFFL); } - private record ChunkTop(ColumnTop[] columns) { + private record ChunkTop(ColumnTop[] columns, VisibleBlocks visible) { int bytes() { int raisedBlocks = 0; for (ColumnTop column : columns) { raisedBlocks += column.raised().count(); } - return CHUNK_TOP_BYTES + raisedBlocks * RAISED_BLOCK_BYTES; + return CHUNK_TOP_BYTES + raisedBlocks * RAISED_BLOCK_BYTES + visible.count() * VISIBLE_BLOCK_BYTES; } } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java index 72a6ce81a..51ed83098 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java @@ -46,11 +46,28 @@ public record MapTile(int size, double blocksPerPixel, MapLabel.Kind subjectKind * @param raisedCounts how many solid blocks stand above each cell's ground, such as a tree's wood and leaves * @param raisedY the height of each raised block, cell after cell and each cell's highest first * @param raised each raised block, in the order of {@code raisedY} + * @param voxels the blocks seen in the tile's own pixels, a block a pixel, or null for a tile at another scale */ - public record Blocks(List names, short[] ground, short[] cover, short[] raisedCounts, short[] raisedY, short[] raised) { + public record Blocks(List names, short[] ground, short[] cover, short[] raisedCounts, short[] raisedY, short[] raised, + Voxels voxels) { public static final short NO_BLOCK = -1; } + /** + * The blocks that can be seen from the open air in a tile a block a pixel, with the sides of each that face it. + * + * @param x each block's pixel from the tile's west edge + * @param z each block's pixel from the tile's north edge + * @param y each block's height above the dimension's bottom + * @param blocks the index of each block in the tile's block names + * @param faces the sides of each block that face the open air, a bit each: down, up, north, south, west, east + */ + public record Voxels(byte[] x, byte[] z, short[] y, short[] blocks, byte[] faces) { + public int count() { + return x.length; + } + } + /** This tile with {@code blocks} on top of its columns, at {@code heights} where it carries heights. */ MapTile withBlocks(Blocks blocks, float[] heights) { return new MapTile(size, blocksPerPixel, subjectKind, labels, subjects, regions, heights, pickNoise, blocks); diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java index 4320dafa9..c3614e7f1 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java @@ -77,10 +77,12 @@ public final class MapTileRenderer { * {@code source}, and the solid blocks raised above it. Where the tile carries heights they become the heights of * that ground: the terrain's top as generated, under what stands on it. * + * @param withVoxels whether a tile of a block a pixel also carries every block seen from the open air, where the + * source knows them * @throws IllegalArgumentException when the tile is coarser than the source is drawn at * @throws CancellationException as soon as {@code cancelled} answers true */ - public MapTile withBlocks(MapTile tile, double startX, double startZ, BlockSource source, BooleanSupplier cancelled) { + public MapTile withBlocks(MapTile tile, double startX, double startZ, BlockSource source, boolean withVoxels, BooleanSupplier cancelled) { double step = tile.blocksPerPixel(); if (step > source.largestBlocksPerPixel()) { throw new IllegalArgumentException("Blocks from " + source.id() + " are drawn at " + source.largestBlocksPerPixel() @@ -115,10 +117,24 @@ public final class MapTileRenderer { } } } - MapTile.Blocks blocks = new MapTile.Blocks(names.names(), ground, cover, raisedCounts, raisedY.toShortArray(), raised.toShortArray()); + MapTile.Voxels voxels = withVoxels && step == 1D ? voxelsOf(tops, startX, startZ, tile.size(), names) : null; + MapTile.Blocks blocks = new MapTile.Blocks(names.names(), ground, cover, raisedCounts, raisedY.toShortArray(), raised.toShortArray(), voxels); return tile.withBlocks(blocks, heights); } + // Only a tile of a block a pixel shows its blocks one by one; coarser ones show the tops of their columns. + private static MapTile.Voxels voxelsOf(ColumnTops tops, double startX, double startZ, int size, BlockNames names) { + ColumnTops.TileVoxels found = tops.voxelsIn((int) Math.floor(startX), (int) Math.floor(startZ), size); + if (found == null) { + return null; + } + short[] blocks = new short[found.blocks().length]; + for (int at = 0; at < blocks.length; at++) { + blocks[at] = names.indexOf(found.blocks()[at]); + } + return new MapTile.Voxels(found.x(), found.z(), found.y(), blocks, found.faces()); + } + private ColumnTops topsOf(BlockSource source) { return switch (source) { case GENERATED -> generated; diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/VisibleBlocks.java b/core/src/main/java/art/arcane/iris/core/studio/map/VisibleBlocks.java new file mode 100644 index 000000000..9dd012b22 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/VisibleBlocks.java @@ -0,0 +1,250 @@ +/* + * 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.core.studio.map; + +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.hunk.Hunk; +import it.unimi.dsi.fastutil.bytes.ByteArrayList; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.function.IntBinaryOperator; +import java.util.function.UnaryOperator; + +/** + * The blocks of a chunk that can be seen from the open air above it, each with the sides that face that air. The open + * air is every cell no opaque block fills that the sky reaches, through water and leaves too, so the ground, cliffs, + * overhangs, the wood inside a tree and the floor of a lake are seen, and a cave closed to the sky is not. + * + * @param positions each block's place in the chunk: x in the lowest 4 bits, z in the next 4, then its height above the + * dimension's bottom + * @param blocks each block's key + * @param faces the sides of each block that face the open air, a bit each in {@link #SIDES}' order + */ +record VisibleBlocks(int[] positions, String[] blocks, byte[] faces) { + static final VisibleBlocks NONE = new VisibleBlocks(new int[0], new String[0], new byte[0]); + /** The order of the sides in {@link #faces}: down, up, north, south, west, east. */ + static final int[][] SIDES = {{0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}, {-1, 0, 0}, {1, 0, 0}}; + static final int POSITION_Y_SHIFT = 8; + private static final int ACROSS = 16; + private static final Set ALWAYS_IN_WATER = Set.of("minecraft:kelp", "minecraft:kelp_plant", "minecraft:seagrass", + "minecraft:tall_seagrass", "minecraft:bubble_column"); + private static final int Z_SHIFT = 4; + + int count() { + return positions.length; + } + + /** + * @param terrainY the terrain's top in a column by its x and z from the chunk's corner, which reaches into the + * chunks around it; beside the chunk, what lies above it counts as open air, or water below the + * fluid's height + * @param fluidHeight the height the sea fills to + * @param seenByPlayers the state players see in place of a block, which decides what hides what + */ + static VisibleBlocks of(Hunk chunk, IntBinaryOperator terrainY, int fluidHeight, UnaryOperator seenByPlayers) { + return new Finder(chunk, terrainY, fluidHeight, seenByPlayers).find(); + } + + @Override + public boolean equals(Object other) { + return other instanceof VisibleBlocks visible && Arrays.equals(positions, visible.positions) + && Arrays.equals(blocks, visible.blocks) && Arrays.equals(faces, visible.faces); + } + + @Override + public int hashCode() { + return 31 * (31 * Arrays.hashCode(positions) + Arrays.hashCode(blocks)) + Arrays.hashCode(faces); + } + + @Override + public String toString() { + return "VisibleBlocks" + Arrays.toString(positions) + Arrays.toString(blocks) + Arrays.toString(faces); + } + + private static final class Finder { + private final Hunk chunk; + private final IntBinaryOperator terrainY; + private final int fluidHeight; + private final int height; + private final PlatformBlockState[] seen; + private final boolean[] open; + private final boolean[] fluid; + private final boolean[] skyReaches; + + Finder(Hunk chunk, IntBinaryOperator terrainY, int fluidHeight, UnaryOperator seenByPlayers) { + this.chunk = chunk; + this.terrainY = terrainY; + this.fluidHeight = fluidHeight; + this.height = chunk.getHeight(); + int cells = ACROSS * height * ACROSS; + this.seen = new PlatformBlockState[cells]; + this.open = new boolean[cells]; + this.fluid = new boolean[cells]; + this.skyReaches = new boolean[cells]; + for (int y = 0; y < height; y++) { + for (int z = 0; z < ACROSS; z++) { + for (int x = 0; x < ACROSS; x++) { + PlatformBlockState block = chunk.get(x, y, z); + int cell = cellOf(x, y, z); + seen[cell] = block == null || block.isAir() ? null : seenByPlayers.apply(block); + open[cell] = seen[cell] == null || !seen[cell].isOccluding(); + fluid[cell] = seen[cell] != null && holdsFluid(seen[cell]); + } + } + } + } + + // Water around a waterlogged block, or one that only grows in water, has no side against it. + private static boolean holdsFluid(PlatformBlockState block) { + return block.isFluid() || block.isWaterLogged() || ALWAYS_IN_WATER.contains(materialOf(block.key())); + } + + private static String materialOf(String key) { + int properties = key.indexOf('['); + return properties < 0 ? key : key.substring(0, properties); + } + + VisibleBlocks find() { + spreadTheSky(); + IntArrayList positions = new IntArrayList(); + List blocks = new ArrayList<>(); + ByteArrayList faces = new ByteArrayList(); + for (int y = 0; y < height; y++) { + for (int z = 0; z < ACROSS; z++) { + for (int x = 0; x < ACROSS; x++) { + int cell = cellOf(x, y, z); + if (seen[cell] == null) { + continue; + } + int sides = sidesFacingTheSky(x, y, z); + // A plant or a leaf the sky reaches shows whatever it touches; its model may have faces no side hides. + if (sides == 0 && !(open[cell] && skyReaches[cell])) { + continue; + } + positions.add(x | z << Z_SHIFT | y << POSITION_Y_SHIFT); + blocks.add(chunk.get(x, y, z).key()); + faces.add((byte) sides); + } + } + } + return positions.isEmpty() ? NONE : new VisibleBlocks(positions.toIntArray(), blocks.toArray(String[]::new), faces.toByteArray()); + } + + // Fills every open cell the sky reaches, from the top of the chunk and from beside it where the ground around + // lies lower. + private void spreadTheSky() { + int[] queue = new int[skyReaches.length]; + int queued = 0; + for (int y = 0; y < height; y++) { + for (int z = 0; z < ACROSS; z++) { + for (int x = 0; x < ACROSS; x++) { + int cell = cellOf(x, y, z); + if (open[cell] && touchesOpenOutside(x, y, z)) { + skyReaches[cell] = true; + queue[queued++] = cell; + } + } + } + } + for (int next = 0; next < queued; next++) { + int cell = queue[next]; + int x = cell % ACROSS; + int z = (cell / ACROSS) % ACROSS; + int y = cell / (ACROSS * ACROSS); + for (int[] side : SIDES) { + int nx = x + side[0]; + int ny = y + side[1]; + int nz = z + side[2]; + if (!isInside(nx, ny, nz)) { + continue; + } + int neighbour = cellOf(nx, ny, nz); + if (open[neighbour] && !skyReaches[neighbour]) { + skyReaches[neighbour] = true; + queue[queued++] = neighbour; + } + } + } + } + + private boolean touchesOpenOutside(int x, int y, int z) { + for (int[] side : SIDES) { + int nx = x + side[0]; + int ny = y + side[1]; + int nz = z + side[2]; + if (!isInside(nx, ny, nz) && outsideAt(nx, ny, nz) != Outside.SOLID) { + return true; + } + } + return false; + } + + // A side faces the sky where the cell beside it is open air the sky reaches; water hides the sides of water. + private int sidesFacingTheSky(int x, int y, int z) { + boolean isFluid = fluid[cellOf(x, y, z)]; + int sides = 0; + for (int side = 0; side < SIDES.length; side++) { + int nx = x + SIDES[side][0]; + int ny = y + SIDES[side][1]; + int nz = z + SIDES[side][2]; + boolean faces; + if (isInside(nx, ny, nz)) { + int neighbour = cellOf(nx, ny, nz); + faces = skyReaches[neighbour] && !(isFluid && fluid[neighbour]); + } else { + Outside outside = outsideAt(nx, ny, nz); + faces = outside == Outside.AIR || (outside == Outside.FLUID && !isFluid); + } + if (faces) { + sides |= 1 << side; + } + } + return sides; + } + + private Outside outsideAt(int x, int y, int z) { + if (y >= height) { + return Outside.AIR; + } + if (y < 0 || y <= terrainY.applyAsInt(x, z)) { + return Outside.SOLID; + } + return y <= fluidHeight ? Outside.FLUID : Outside.AIR; + } + + private boolean isInside(int x, int y, int z) { + return x >= 0 && x < ACROSS && z >= 0 && z < ACROSS && y >= 0 && y < height; + } + + private static int cellOf(int x, int y, int z) { + return (y * ACROSS + z) * ACROSS + x; + } + } + + /** What lies beside the chunk, judged by the terrain's height there alone. */ + private enum Outside { + SOLID, + FLUID, + AIR + } +} diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/VisibleBlocksTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/VisibleBlocksTest.java new file mode 100644 index 000000000..7dd1599d8 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/map/VisibleBlocksTest.java @@ -0,0 +1,144 @@ +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.HashMap; +import java.util.Map; +import java.util.function.UnaryOperator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class VisibleBlocksTest { + private static final int HEIGHT = 12; + private static final int GROUND_Y = 3; + private static final int NO_FLUID = -1; + private static final int DOWN = 1; + private static final int UP = 1 << 1; + private static final int NORTH = 1 << 2; + private static final int SOUTH = 1 << 3; + private static final int WEST = 1 << 4; + private static final int EAST = 1 << 5; + private static final PlatformBlockState STONE = block("minecraft:stone", true, false); + private static final PlatformBlockState LOG = block("minecraft:oak_log", true, false); + private static final PlatformBlockState LEAVES = block("minecraft:oak_leaves", false, false); + private static final PlatformBlockState WATER = block("minecraft:water", false, true); + private static final PlatformBlockState KELP = block("minecraft:kelp_plant", false, false); + + @Test + public void flatGroundShowsOnlyTheTopOfItsHighestLayer() { + Map seen = facesByPlace(VisibleBlocks.of(groundUpTo(GROUND_Y), (x, z) -> GROUND_Y, NO_FLUID, UnaryOperator.identity())); + + assertEquals(16 * 16, seen.size()); + assertEquals(UP, (int) seen.get(place(7, GROUND_Y, 7))); + } + + @Test + public void aTreeShowsTheSidesOfItsWoodAndEveryLeafFaceThatTouchesTheOpenAir() { + Hunk chunk = groundUpTo(GROUND_Y); + chunk.set(5, 4, 5, LOG); + chunk.set(5, 5, 5, LOG); + chunk.set(5, 6, 5, LEAVES); + chunk.set(6, 6, 5, LEAVES); + + Map seen = facesByPlace(VisibleBlocks.of(chunk, (x, z) -> GROUND_Y, NO_FLUID, UnaryOperator.identity())); + + assertEquals(NORTH | SOUTH | WEST | EAST, (int) seen.get(place(5, 4, 5))); + // The leaf on the trunk shows its side on the other leaf, as leaves are seen through. + assertEquals(UP | NORTH | SOUTH | WEST | EAST, (int) seen.get(place(5, 6, 5))); + assertEquals(DOWN | UP | NORTH | SOUTH | WEST | EAST, (int) seen.get(place(6, 6, 5))); + assertFalse(seen.containsKey(place(5, GROUND_Y, 5))); + } + + @Test + public void aCaveClosedToTheSkyIsNotSeen() { + Hunk chunk = groundUpTo(GROUND_Y); + chunk.set(8, 1, 8, null); + + Map seen = facesByPlace(VisibleBlocks.of(chunk, (x, z) -> GROUND_Y, NO_FLUID, UnaryOperator.identity())); + + assertFalse(seen.containsKey(place(8, 0, 8))); + assertFalse(seen.containsKey(place(8, 2, 8))); + } + + @Test + public void groundStandingAboveTheTerrainBesideTheChunkShowsItsSideThere() { + Hunk chunk = groundUpTo(GROUND_Y); + + Map seen = facesByPlace(VisibleBlocks.of(chunk, (x, z) -> x < 0 ? GROUND_Y - 2 : GROUND_Y, NO_FLUID, UnaryOperator.identity())); + + assertEquals(UP | WEST, (int) seen.get(place(0, GROUND_Y, 7))); + assertEquals(WEST, (int) seen.get(place(0, GROUND_Y - 1, 7))); + assertFalse(seen.containsKey(place(0, GROUND_Y - 2, 7))); + } + + @Test + public void theFloorOfALakeShowsThroughItsWaterWhichShowsOnlyItsSurface() { + Hunk chunk = groundUpTo(GROUND_Y); + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + chunk.set(x, GROUND_Y + 1, z, WATER); + } + } + + Map seen = facesByPlace(VisibleBlocks.of(chunk, (x, z) -> GROUND_Y, GROUND_Y + 1, UnaryOperator.identity())); + + assertEquals(UP, (int) seen.get(place(7, GROUND_Y, 7))); + assertEquals(UP, (int) seen.get(place(7, GROUND_Y + 1, 7))); + assertEquals(UP, (int) seen.get(place(0, GROUND_Y + 1, 7))); + } + + @Test + public void waterShowsNoSideAgainstAPlantThatGrowsInIt() { + Hunk chunk = groundUpTo(GROUND_Y); + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + chunk.set(x, GROUND_Y + 1, z, WATER); + chunk.set(x, GROUND_Y + 2, z, WATER); + } + } + chunk.set(7, GROUND_Y + 1, 7, KELP); + + Map seen = facesByPlace(VisibleBlocks.of(chunk, (x, z) -> GROUND_Y, GROUND_Y + 2, UnaryOperator.identity())); + + assertEquals(0, (int) seen.get(place(6, GROUND_Y + 1, 7))); + } + + private static Hunk groundUpTo(int topY) { + Hunk chunk = Hunk.newArrayHunk(16, HEIGHT, 16); + for (int y = 0; y <= topY; y++) { + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + chunk.set(x, y, z, STONE); + } + } + } + return chunk; + } + + private static Map facesByPlace(VisibleBlocks visible) { + Map faces = new HashMap<>(); + for (int at = 0; at < visible.count(); at++) { + int position = visible.positions()[at]; + faces.put(place(position & 15, position >> VisibleBlocks.POSITION_Y_SHIFT, (position >> 4) & 15), visible.faces()[at] & 0xFF); + } + return faces; + } + + private static long place(int x, int y, int z) { + return ((long) y << 16) | (z << 8) | x; + } + + private static PlatformBlockState block(String key, boolean occluding, boolean fluid) { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(key); + when(block.isOccluding()).thenReturn(occluding); + when(block.isSolid()).thenReturn(!fluid); + when(block.isFluid()).thenReturn(fluid); + return block; + } +} diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index 5e08d1ab7..d44f75e10 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -52,6 +52,8 @@ export interface TileRequest { pickNoise: boolean /** Where the tile's blocks come from, or null for a tile without them. */ blocks: BlockSource | null + /** Whether a tile of a block a pixel with blocks also carries every block seen from the open air. */ + voxels?: boolean } /** One tile of a pattern: tile (x, z) covers columns × blocksPerColumn blocks from x × that, z × that. */ @@ -141,6 +143,9 @@ export class BridgeClient { }) if (request.blocks !== null) { query.set('blocks', request.blocks) + if (request.voxels === true) { + query.set('voxels', '1') + } this.cancelOnAbort(query, signal) } const response = await this.fetch(`tile?${query}`, { signal }) diff --git a/studio/src/renderer/src/bridge/tileDecoding.ts b/studio/src/renderer/src/bridge/tileDecoding.ts index 79d8b75e9..c860b6dd2 100644 --- a/studio/src/renderer/src/bridge/tileDecoding.ts +++ b/studio/src/renderer/src/bridge/tileDecoding.ts @@ -1,4 +1,4 @@ -import type { LabelKind, MapLabel, MapTile, TileBlocks } from './types' +import type { LabelKind, MapLabel, MapTile, TileBlocks, TileVoxels } from './types' const ALIGNMENT_BYTES = 4 @@ -13,8 +13,12 @@ interface TileHeader { blocks?: string[] | null /** How many blocks are raised over the ground of all cells together. */ raised?: number + /** How many blocks can be seen from the open air, or -1 on a tile without them. */ + voxels?: number } +const NO_VOXELS = -1 + function aligned(bytes: number): number { return Math.ceil(bytes / ALIGNMENT_BYTES) * ALIGNMENT_BYTES } @@ -44,16 +48,17 @@ export function decodeTile(buffer: ArrayBuffer): MapTile { regions: new Int16Array(buffer, regionsAt, cells), heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null, pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null, - blocks: header.blocks == null ? null : decodeBlocks(buffer, groundAt, cells, header.blocks, header.raised ?? 0) + blocks: header.blocks == null ? null : decodeBlocks(buffer, groundAt, cells, header.blocks, header.raised ?? 0, header.voxels ?? NO_VOXELS) } } -function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, names: string[], raisedCount: number): TileBlocks { +function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, names: string[], raisedCount: number, voxelCount: number): TileBlocks { const gridBytes = aligned(cells * Int16Array.BYTES_PER_ELEMENT) const coverAt = groundAt + gridBytes const raisedCountsAt = coverAt + gridBytes const raisedYAt = raisedCountsAt + gridBytes const raisedAt = aligned(raisedYAt + raisedCount * Int16Array.BYTES_PER_ELEMENT) + const voxelsAt = aligned(raisedAt + raisedCount * Int16Array.BYTES_PER_ELEMENT) return { names, ground: new Int16Array(buffer, groundAt, cells), @@ -61,9 +66,25 @@ function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, name raisedStart: startsOf(new Int16Array(buffer, raisedCountsAt, cells)), raisedY: new Int16Array(buffer, raisedYAt, raisedCount), raised: new Int16Array(buffer, raisedAt, raisedCount), + voxels: voxelCount === NO_VOXELS ? null : decodeVoxels(buffer, voxelsAt, voxelCount), colors: [], looks: [], - covers: [] + covers: [], + models: [] + } +} + +function decodeVoxels(buffer: ArrayBuffer, xAt: number, count: number): TileVoxels { + const zAt = xAt + aligned(count) + const yAt = zAt + aligned(count) + const blocksAt = yAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const facesAt = blocksAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + return { + x: new Uint8Array(buffer, xAt, count), + z: new Uint8Array(buffer, zAt, count), + y: new Int16Array(buffer, yAt, count), + blocks: new Int16Array(buffer, blocksAt, count), + faces: new Uint8Array(buffer, facesAt, count) } } diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index 85079149a..c126f40e3 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -361,6 +361,10 @@ export interface TileBlocks { raisedY: Int16Array /** Each raised block, in the order of {@link raisedY}. */ raised: Int16Array + /** The blocks seen from the open air, where the tile is a block a column and they were asked for; else null. */ + voxels: TileVoxels | null + /** Each named block's model with its pictures placed, for the blocks {@link voxels} names; the tile source fills it in. */ + models: (CoverLook | null)[] /** The colour of each named block from above, as 0xRRGGBB; the tile source fills it in. */ colors: number[] /** What each named block looks like on a column, where the tile is fine enough to show textures; else empty. */ @@ -369,5 +373,24 @@ export interface TileBlocks { covers: (CoverLook | null)[] } +/** + * The blocks of a tile that can be seen from the open air, as the server found them in the chunks it generated, with + * the sides of each that face that air. + */ +export interface TileVoxels { + /** Each block's column from the tile's west edge. */ + x: Uint8Array + /** Each block's column from the tile's north edge. */ + z: Uint8Array + y: Int16Array + /** Each block's index in the tile's block names. */ + blocks: Int16Array + /** The sides of each block that face the open air, a bit each in {@link VOXEL_SIDES}' order. */ + faces: Uint8Array +} + +/** The order of the sides in {@link TileVoxels.faces}. */ +export const VOXEL_SIDES = ['down', 'up', 'north', 'south', 'west', 'east'] as const + export const NO_BLOCK = -1 export const NO_LABEL = -1 diff --git a/studio/src/renderer/src/map/map.test.ts b/studio/src/renderer/src/map/map.test.ts index b8b633619..d1346f158 100644 --- a/studio/src/renderer/src/map/map.test.ts +++ b/studio/src/renderer/src/map/map.test.ts @@ -57,8 +57,8 @@ function encode(size: number, withHeights: boolean, withPickNoise = false): Arra return buffer } -function nothingRaised(cells: number): Pick { - return { raisedStart: new Int32Array(cells + 1), raisedY: new Int16Array(0), raised: new Int16Array(0) } +function nothingRaised(cells: number): Pick { + return { raisedStart: new Int32Array(cells + 1), raisedY: new Int16Array(0), raised: new Int16Array(0), voxels: null, models: [] } } /** A tile of one pixel with its blocks as the bridge sends them: ground, cover and the raised blocks' counts, heights and blocks. */ @@ -192,9 +192,11 @@ describe('tile style', () => { raisedStart, raisedY: Int16Array.of(70, 69), raised: Int16Array.of(1, 2), + voxels: null, colors: [0x808080, 0x00ff00, 0x654321], looks: [], - covers: [] + covers: [], + models: [] } const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true }) diff --git a/studio/src/renderer/src/map/mapTileSource.ts b/studio/src/renderer/src/map/mapTileSource.ts index ffbbae921..2d09c189c 100644 --- a/studio/src/renderer/src/map/mapTileSource.ts +++ b/studio/src/renderer/src/map/mapTileSource.ts @@ -13,6 +13,8 @@ export interface TileLayer { pickNoise: boolean /** Where the tiles' blocks come from, or null for tiles without them. */ blocks: BlockSource | null + /** Whether tiles of a block a pixel with blocks also carry every block seen from the open air, to draw one by one. */ + voxels?: boolean /** Bumped when the pack is hotloaded, so older tiles are not used again. */ revision: number } @@ -24,6 +26,11 @@ export interface TileLayer { const MAP_MOST_BLOCKS_PER_PIXEL = 1 const TEXTURED_BLOCKS_PER_PIXEL = 1 +function voxelBytesOf(tile: MapTile): number { + const voxels = tile.blocks?.voxels + return voxels === null || voxels === undefined ? 0 : voxels.x.byteLength * 3 + voxels.y.byteLength * 2 +} + /** Whether the map's tiles this coarse carry blocks. */ export function hasBlocksAt(blocksPerPixel: number): boolean { return blocksPerPixel <= MAP_MOST_BLOCKS_PER_PIXEL @@ -36,7 +43,7 @@ export function hasBlocksAt(blocksPerPixel: number): boolean { */ export function mapTileSource(client: BridgeClient, tileSize: number, art: BlockArt, mostBlocksPerPixel = MAP_MOST_BLOCKS_PER_PIXEL): TileSource { return { - layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? ''].join('/'), + layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? '', layer.voxels === true].join('/'), fetch: async (address, layer, signal) => { const blocks = layer.blocks !== null && address.blocksPerPixel <= mostBlocksPerPixel ? layer.blocks : null const tile = await client.tile({ ...layer, ...address, size: tileSize, blocks }, signal) @@ -46,7 +53,7 @@ export function mapTileSource(client: BridgeClient, tileSize: number, art: Block return tile }, bytesOf: (tile) => - tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + (tile.blocks?.ground.byteLength ?? 0) * 2 + (tile.blocks?.raisedStart.byteLength ?? 0) + (tile.blocks?.raised.byteLength ?? 0) * 2 + tile.size * tile.size * 4, + tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + (tile.blocks?.ground.byteLength ?? 0) * 2 + (tile.blocks?.raisedStart.byteLength ?? 0) + (tile.blocks?.raised.byteLength ?? 0) * 2 + voxelBytesOf(tile) + tile.size * tile.size * 4, styleKey, pixels: (tile, style) => new ImageData(stylePixels(tile, style), tile.size, tile.size) } diff --git a/studio/src/renderer/src/scene/blockArt.ts b/studio/src/renderer/src/scene/blockArt.ts index 6bdf5038d..f9b2948dd 100644 --- a/studio/src/renderer/src/scene/blockArt.ts +++ b/studio/src/renderer/src/scene/blockArt.ts @@ -22,6 +22,14 @@ function namesStandingOnGround(blocks: TileBlocks): string[] { return [...standing].map((index) => blocks.names[index]) } +// A tile drawn block by block places the whole models of the blocks it shows. +function namesSeenOneByOne(blocks: TileBlocks): string[] { + if (blocks.voxels === null) { + return [] + } + return [...new Set(blocks.voxels.blocks)].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, () => {}) @@ -33,14 +41,16 @@ export function blockArt(client: BridgeClient, textured: boolean): BlockArt { atlas, paint: async (blocks, withLooks) => { const shownLooks = withLooks ? looks : null - const [colorOf, lookOf, coverOf] = await Promise.all([ + const [colorOf, lookOf, coverOf, modelOf] = await Promise.all([ colors.colorsOf(blocks.names), shownLooks?.looksOf(blocks.names) ?? null, - shownLooks?.coversOf(namesStandingOnGround(blocks)) ?? null + shownLooks?.coversOf(namesStandingOnGround(blocks)) ?? null, + shownLooks?.coversOf(namesSeenOneByOne(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) + blocks.models = modelOf === null ? [] : blocks.names.map((name) => modelOf.get(name) ?? null) }, dispose: () => atlas?.dispose() } diff --git a/studio/src/renderer/src/scene/coverLooks.ts b/studio/src/renderer/src/scene/coverLooks.ts index 2c4da5344..ab929f01d 100644 --- a/studio/src/renderer/src/scene/coverLooks.ts +++ b/studio/src/renderer/src/scene/coverLooks.ts @@ -12,6 +12,8 @@ export interface CoverFace { cell: UvCell /** The face's tint in its light, as red, green and blue from 0 to 1. */ color: readonly [number, number, number] + /** The side whose neighbour, when it is a solid block, hides the face; null when nothing hides it. */ + cullFace: Direction | null } /** A block standing on a column's ground, such as grass, a flower or a layer of snow, as the faces of its model. */ @@ -37,7 +39,7 @@ export async function coverLookOf(block: string, model: BlockModel | null, pictu 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 { corners: quad.corners, uvs: quad.uvs, cell, color, cullFace: quad.cullFace } }) ) return faces.includes(null) ? null : { faces: faces as CoverFace[] } diff --git a/studio/src/renderer/src/scene/mapTerrain.test.ts b/studio/src/renderer/src/scene/mapTerrain.test.ts index 48dbfc179..cfa39b655 100644 --- a/studio/src/renderer/src/scene/mapTerrain.test.ts +++ b/studio/src/renderer/src/scene/mapTerrain.test.ts @@ -22,9 +22,11 @@ function tileWithALeaf(): MapTile { raisedStart, raisedY: Int16Array.of(LEAF_Y), raised: Int16Array.of(1), + voxels: null, colors: [STONE, LEAVES], looks: [], - covers: [] + covers: [], + models: [] } return { size: SIZE, diff --git a/studio/src/renderer/src/scene/mapTerrain.ts b/studio/src/renderer/src/scene/mapTerrain.ts index 72ae9a671..1f899a2fc 100644 --- a/studio/src/renderer/src/scene/mapTerrain.ts +++ b/studio/src/renderer/src/scene/mapTerrain.ts @@ -4,11 +4,17 @@ import type { BlockLook } from './blockLooks' import type { CoverLook } from './coverLooks' import type { TerrainPictures } from './terrainAtlas' import type { RaisedBlock, TerrainSurface } from './terrainMesh' +import type { SurfaceVoxels } from './voxelMesh' import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles' export type MapTerrainColoring = 'biomes' | 'regions' | 'height' | 'blocks' const UNLABELLED_COLOR = 0x5a5f6b +const WATER_NAME = 'minecraft:water' + +function isWater(block: string): boolean { + return block === WATER_NAME || block.startsWith(`${WATER_NAME}[`) +} /** * One map tile with heights as a surface, a column to a pixel, without the ring the tile carries for its neighbours; the @@ -73,6 +79,20 @@ export class MapTerrain implements TerrainSurface { return raised } + voxels(): SurfaceVoxels | null { + const blocks = this.coloring === 'blocks' && this.blocksPerColumn === 1 ? this.tile.blocks : null + if (blocks === null || blocks.voxels === null || blocks.models.length === 0) { + return null + } + return { + voxels: blocks.voxels, + models: blocks.models, + looks: blocks.looks, + colors: blocks.colors, + isWater: blocks.names.map(isWater) + } + } + 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/terrainMesh.ts b/studio/src/renderer/src/scene/terrainMesh.ts index 8323aeb2e..66c23b768 100644 --- a/studio/src/renderer/src/scene/terrainMesh.ts +++ b/studio/src/renderer/src/scene/terrainMesh.ts @@ -6,6 +6,7 @@ import { coverGeometry } from './coverFaces' import type { CoverLook } from './coverLooks' import { QuadBatch } from './quadBatch' import { addRaisedFaces } from './raisedFaces' +import { voxelGeometries, type SurfaceVoxels } from './voxelMesh' import type { TerrainPictures } from './terrainAtlas' import type { ColumnArea } from './terrainTiles' import { WATER_SURFACE_COLOR, WATER_SURFACE_OPACITY } from './waterTint' @@ -35,6 +36,11 @@ export interface TerrainSurface { coverAt?(column: number, row: number): CoverLook | null /** The solid blocks above the column's ground, such as a tree's wood and leaves, highest first. */ raisedAt?(column: number, row: number): readonly RaisedBlock[] + /** + * Every block seen from the open air, to draw one by one in place of the columns, which then only answer where the + * ground lies; null to draw the columns. + */ + voxels?(): SurfaceVoxels | null } /** A solid block above a column's ground, drawn as a whole block. */ @@ -66,17 +72,21 @@ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: r if (!field.hasAnyGround()) { return { object: group, field, dispose: () => {} } } + const voxels = field.pictures === null ? null : (surface.voxels?.() ?? null) + if (voxels !== null && field.pictures !== null) { + return voxelMesh(field, voxels, field.pictures) + } const groundBatch = groundFaces(field, base) const seeThroughBatch = new QuadBatch(true, field.pictures?.plain ?? null) addRaisedFaces(field, groundBatch, seeThroughBatch) const ground = groundBatch.geometry() 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 }) + const columnWaterMaterial = waterMaterial() const cutOut = field.pictures === null ? [] : [cutOutMesh(coverGeometry(field), field.pictures), cutOutMesh(seeThroughGeometry(seeThroughBatch), field.pictures)] const shownCutOut = cutOut.filter((mesh) => mesh !== null) // The water is drawn last, over what stands under it. - group.add(new Mesh(ground, groundMaterial), ...shownCutOut.map((mesh) => mesh.mesh), new Mesh(water, waterMaterial)) + group.add(new Mesh(ground, groundMaterial), ...shownCutOut.map((mesh) => mesh.mesh), new Mesh(water, columnWaterMaterial)) return { object: group, field, @@ -84,12 +94,45 @@ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: r ground.dispose() water.dispose() groundMaterial.dispose() - waterMaterial.dispose() + columnWaterMaterial.dispose() shownCutOut.forEach((mesh) => mesh.dispose()) } } } +function voxelMesh(field: ColumnField, voxels: SurfaceVoxels, pictures: TerrainPictures): TerrainMesh { + const { opaque, cutOut, water } = voxelGeometries(field, voxels, pictures.plain) + const parts: { mesh: Mesh; dispose(): void }[] = [] + if (opaque !== null) { + parts.push(meshOf(opaque, new MeshBasicMaterial({ vertexColors: true, side: FrontSide, map: pictures.texture }))) + } + const cutOutPart = cutOutMesh(cutOut, pictures) + if (cutOutPart !== null) { + parts.push(cutOutPart) + } + // The water is drawn last, over what stands under it. + if (water !== null) { + parts.push(meshOf(water, waterMaterial())) + } + const group = new Group() + group.add(...parts.map((part) => part.mesh)) + return { object: group, field, dispose: () => parts.forEach((part) => part.dispose()) } +} + +function meshOf(geometry: BufferGeometry, material: MeshBasicMaterial): { mesh: Mesh; dispose(): void } { + return { + mesh: new Mesh(geometry, material), + dispose: () => { + geometry.dispose() + material.dispose() + } + } +} + +function waterMaterial(): MeshBasicMaterial { + return new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide }) +} + function seeThroughGeometry(batch: QuadBatch): BufferGeometry | null { return batch.count === 0 ? null : batch.geometry() } diff --git a/studio/src/renderer/src/scene/texturedTerrain.test.ts b/studio/src/renderer/src/scene/texturedTerrain.test.ts index a1a505579..bb1e48982 100644 --- a/studio/src/renderer/src/scene/texturedTerrain.test.ts +++ b/studio/src/renderer/src/scene/texturedTerrain.test.ts @@ -155,7 +155,8 @@ describe('textured terrain', () => { 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] + color: [0.5, 0.75, 0.25], + cullFace: null } ] } diff --git a/studio/src/renderer/src/scene/voxelMesh.test.ts b/studio/src/renderer/src/scene/voxelMesh.test.ts new file mode 100644 index 000000000..0f1cb98a0 --- /dev/null +++ b/studio/src/renderer/src/scene/voxelMesh.test.ts @@ -0,0 +1,87 @@ +import type { BufferGeometry } from 'three' +import { describe, expect, it } from 'vitest' +import type { TileVoxels } from '../bridge/types' +import type { Direction } from './blockModels' +import type { BlockLook } from './blockLooks' +import { ColumnField } from './columnField' +import type { CoverFace, CoverLook } from './coverLooks' +import { cellAt } from './terrainAtlas' +import type { TerrainSurface } from './terrainMesh' +import { voxelGeometries, type SurfaceVoxels } from './voxelMesh' + +const GROUND = 10 +const DOWN = 1 +const UP = 1 << 1 +const NORTH = 1 << 2 +const STONE = 0 +const LEAVES = 1 +const GRASS = 2 +const WATER = 3 +const plain = cellAt(0, 0xffffff) +const stoneLook: BlockLook = { + top: { cell: cellAt(1, 0x808080), tint: 0xffffff, color: 0x808080 }, + side: { cell: cellAt(2, 0x808080), tint: 0xffffff, color: 0x808080 }, + below: { cell: cellAt(2, 0x808080), tint: 0xffffff, color: 0x808080 } +} + +function face(cullFace: Direction | null, gappy: boolean): CoverFace { + return { corners: [[0, 1, 0], [0, 0, 0], [1, 0, 0], [1, 1, 0]], uvs: [[0, 0], [0, 1], [1, 1], [1, 0]], cell: cellAt(3, 0x00ff00, gappy), color: [0, 1, 0], cullFace } +} + +const leaves: CoverLook = { faces: (['down', 'up', 'north', 'south', 'west', 'east'] as const).map((side) => face(side, true)) } +const grass: CoverLook = { faces: [face(null, true), face(null, true)] } + +const surface: TerrainSurface = { + columns: 4, + rows: 4, + originX: 100, + originZ: 200, + blocksPerColumn: 1, + groundAt: () => GROUND, + waterAt: () => null, + colorAt: () => 0x808080 +} + +function voxelsOf(blocks: number[], faces: number[]): SurfaceVoxels { + const voxels: TileVoxels = { + x: Uint8Array.from(blocks.map((_, at) => at)), + z: new Uint8Array(blocks.length), + y: new Int16Array(blocks.length).fill(GROUND), + blocks: Int16Array.from(blocks), + faces: Uint8Array.from(faces) + } + return { voxels, models: [null, leaves, grass, null], looks: [stoneLook, null, null, null], colors: [0x808080, 0, 0, 0], isWater: [false, false, false, true] } +} + +const faceCount = (geometry: BufferGeometry | null): number => (geometry === null ? 0 : geometry.getIndex()!.count / 6) + +describe('voxel mesh', () => { + it('draws a block without a model as a cube of its look, on the sides that face the open air', () => { + const { opaque, cutOut } = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP]), plain) + + expect(faceCount(opaque)).toBe(1) + expect(faceCount(cutOut)).toBe(0) + expect(opaque!.getAttribute('position').getY(0)).toBe(GROUND + 1) + expect(opaque!.getAttribute('position').getX(0)).toBe(100) + }) + + it('leaves out the faces of a model a neighbour hides, and cuts out the faces of a picture with gaps', () => { + const { opaque, cutOut } = voxelGeometries(new ColumnField(surface), voxelsOf([LEAVES], [UP | NORTH]), plain) + + expect(faceCount(opaque)).toBe(0) + expect(faceCount(cutOut)).toBe(2) + }) + + it('draws every face of a model that nothing hides, such as a plant, whatever sides face the air', () => { + const { cutOut } = voxelGeometries(new ColumnField(surface), voxelsOf([GRASS], [0]), plain) + + expect(faceCount(cutOut)).toBe(2) + }) + + it('draws water as the sides of its sheet that face the air', () => { + const { water, opaque } = voxelGeometries(new ColumnField(surface), voxelsOf([WATER], [UP | DOWN]), plain) + + expect(faceCount(water)).toBe(2) + expect(faceCount(opaque)).toBe(0) + }) +}) diff --git a/studio/src/renderer/src/scene/voxelMesh.ts b/studio/src/renderer/src/scene/voxelMesh.ts new file mode 100644 index 000000000..ace7585fa --- /dev/null +++ b/studio/src/renderer/src/scene/voxelMesh.ts @@ -0,0 +1,178 @@ +import { BufferAttribute, BufferGeometry } from 'three' +import { VOXEL_SIDES, type TileVoxels } from '../bridge/types' +import type { Direction } from './blockModels' +import type { BlockLook, FaceLook } from './blockLooks' +import type { ColumnField } from './columnField' +import { shaded } from './columnFaces' +import { FACE_LIGHT, type CoverFace, type CoverLook } from './coverLooks' +import type { UvCell } from './terrainAtlas' +import { sunk, tintAt } from './waterTint' + +type Corners = CoverFace['corners'] +type Uvs = CoverFace['uvs'] +type Color = readonly [number, number, number] + +/** The blocks of a tile seen from the open air, and how to draw each of the blocks they name. */ +export interface SurfaceVoxels { + voxels: TileVoxels + /** Each named block's model with its pictures placed, or null to draw it as a cube of its look or colour. */ + models: readonly (CoverLook | null)[] + looks: readonly (BlockLook | null)[] + colors: readonly number[] + /** Whether each named block is water, drawn as the water's sheet. */ + isWater: readonly boolean[] +} + +/** The faces of a tile's blocks: opaque ones, ones cut out along their pictures, and the water's. Null where there are none. */ +export interface VoxelGeometries { + opaque: BufferGeometry | null + cutOut: BufferGeometry | null + water: BufferGeometry | null +} + +const SIDE_BITS: Record = Object.fromEntries(VOXEL_SIDES.map((side, bit) => [side, 1 << bit])) as Record +const WHOLE_PICTURE: Uvs = [[0, 0], [0, 1], [1, 1], [1, 0]] +// A whole block's face on each side, top left, bottom left, bottom right and top right as seen from outside. +const CUBE_FACES: Record = { + down: [[0, 0, 1], [0, 0, 0], [1, 0, 0], [1, 0, 1]], + up: [[0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 1, 0]], + north: [[1, 1, 0], [1, 0, 0], [0, 0, 0], [0, 1, 0]], + south: [[0, 1, 1], [0, 0, 1], [1, 0, 1], [1, 1, 1]], + west: [[0, 1, 0], [0, 0, 0], [0, 0, 1], [0, 1, 1]], + east: [[1, 1, 1], [1, 0, 1], [1, 0, 0], [1, 1, 0]] +} + +/** + * Each block seen from the open air drawn as Minecraft draws it: the faces of its model, leaving out a face its model + * lets a neighbour hide unless that side faces the open air. A block without a model is a cube of its look, or of its + * colour; water shows the sides that face the air. What lies under water sinks toward its deep colour as the ground does. + */ +export function voxelGeometries(field: ColumnField, surface: SurfaceVoxels, plain: UvCell): VoxelGeometries { + const opaque = new FaceSoup(true) + const cutOut = new FaceSoup(true) + const water = new FaceSoup(false) + const { voxels } = surface + for (let at = 0; at < voxels.x.length; at++) { + const column = voxels.x[at] + const row = voxels.z[at] + const corner: Color = [field.originX + column, voxels.y[at], field.originZ + row] + const block = voxels.blocks[at] + const sides = voxels.faces[at] + const waterTop = field.waterTopAt(column, row) + if (surface.isWater[block]) { + addCubeFaces(sides, (_side, corners) => water.add(corner, corners, null, null)) + continue + } + const model = surface.models[block] + if (model !== null) { + for (const face of model.faces) { + if (face.cullFace !== null && (sides & SIDE_BITS[face.cullFace]) === 0) { + continue + } + const color = underWater(face.color, corner[1] + middleY(face.corners), waterTop) + ;(face.cell.hasGaps ? cutOut : opaque).add(corner, face.corners, pictureUvs(face.cell, face.uvs), color) + } + continue + } + const look = surface.looks[block] + addCubeFaces(sides, (side, corners) => { + const face: FaceLook | null = look === null ? null : side === 'up' || side === 'down' ? look.top : look.side + const light = shaded(face === null ? surface.colors[block] : face.tint, FACE_LIGHT[side]) + const color = underWater(light, corner[1] + middleY(corners), waterTop) + const cell = face === null ? plain : face.cell + ;(cell.hasGaps ? cutOut : opaque).add(corner, corners, pictureUvs(cell, WHOLE_PICTURE), color) + }) + } + return { opaque: opaque.geometry(), cutOut: cutOut.geometry(), water: water.geometry() } +} + +function addCubeFaces(sides: number, add: (side: Direction, corners: Corners) => void): void { + for (const side of VOXEL_SIDES) { + if ((sides & SIDE_BITS[side]) !== 0) { + add(side, CUBE_FACES[side]) + } + } +} + +function middleY(corners: Corners): number { + return (corners[0][1] + corners[2][1]) / 2 +} + +function underWater(color: Color, y: number, waterTop: number | null): Color { + return waterTop === null ? color : sunk(color, tintAt(waterTop - y)) +} + +function pictureUvs(cell: UvCell, uvs: Uvs): Uvs { + return uvs.map(([u, v]) => [cell.u + u * cell.width, cell.v + v * cell.height]) as unknown as Uvs +} + +const CORNERS = 4 +const FIRST_CAPACITY_FACES = 4096 + +/** Faces gathered for one geometry, each with its own corners, so every face keeps its own colour. */ +class FaceSoup { + private positions: Float32Array = new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3) + private uvs: Float32Array | null + private colors: Float32Array | null + private faces = 0 + + constructor(textured: boolean) { + this.uvs = textured ? new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 2) : null + this.colors = textured ? new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3) : null + } + + add(origin: Color, corners: Corners, uvs: Uvs | null, color: Color | null): void { + this.reserveOne() + const first = this.faces * CORNERS + for (let corner = 0; corner < CORNERS; corner++) { + const vertex = first + corner + this.positions[vertex * 3] = origin[0] + corners[corner][0] + this.positions[vertex * 3 + 1] = origin[1] + corners[corner][1] + this.positions[vertex * 3 + 2] = origin[2] + corners[corner][2] + if (this.uvs !== null && uvs !== null) { + this.uvs[vertex * 2] = uvs[corner][0] + this.uvs[vertex * 2 + 1] = uvs[corner][1] + } + if (this.colors !== null && color !== null) { + this.colors.set(color, vertex * 3) + } + } + this.faces++ + } + + geometry(): BufferGeometry | null { + if (this.faces === 0) { + return null + } + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(this.positions.slice(0, this.faces * CORNERS * 3), 3)) + if (this.uvs !== null) { + geometry.setAttribute('uv', new BufferAttribute(this.uvs.slice(0, this.faces * CORNERS * 2), 2)) + } + if (this.colors !== null) { + geometry.setAttribute('color', new BufferAttribute(this.colors.slice(0, this.faces * CORNERS * 3), 3)) + } + const indices = new Uint32Array(this.faces * 6) + for (let face = 0; face < this.faces; face++) { + const first = face * CORNERS + indices.set([first, first + 1, first + 2, first, first + 2, first + 3], face * 6) + } + geometry.setIndex(new BufferAttribute(indices, 1)) + return geometry + } + + private reserveOne(): void { + if ((this.faces + 1) * CORNERS * 3 <= this.positions.length) { + return + } + this.positions = grown(this.positions) + this.uvs = this.uvs === null ? null : grown(this.uvs) + this.colors = this.colors === null ? null : grown(this.colors) + } +} + +function grown(values: Float32Array): Float32Array { + const bigger = new Float32Array(values.length * 2) + bigger.set(values) + return bigger +} diff --git a/studio/src/renderer/src/studio/WorldStudio3D.tsx b/studio/src/renderer/src/studio/WorldStudio3D.tsx index c27255940..83d8aab27 100644 --- a/studio/src/renderer/src/studio/WorldStudio3D.tsx +++ b/studio/src/renderer/src/studio/WorldStudio3D.tsx @@ -29,7 +29,7 @@ const MOST_BLOCKS_PER_COLUMN = 2 ** COARSEST_LEVEL // Tiles with generated blocks take seconds to minutes each. The same tiles without them stand in, but only on ground // where no tile with blocks of any level is known yet. function withoutBlocks(layer: TileLayer): TileLayer | null { - return layer.blocks === null ? null : { ...layer, blocks: null } + return layer.blocks === null ? null : { ...layer, blocks: null, voxels: false } } interface WorldStudio3DProps { @@ -59,7 +59,7 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS ) const showsBlocks = coloring === 'blocks' const layer = useMemo( - () => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, blocks: showsBlocks ? 'generated' : null, revision: packRevision }), + () => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, blocks: showsBlocks ? 'generated' : null, voxels: showsBlocks, revision: packRevision }), [packRevision, showsBlocks] ) const style = useMemo>(