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 d9d3db3eb..ad3b4ced1 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 @@ -40,16 +40,18 @@ import java.util.function.Function; * | 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 + * i16 runCounts[grid²] | padding to 4 | i16 runBottoms[runs] | padding to 4 | i16 runTops[runs] | padding to 4 + * | i16 runBlocks[runs] | padding to 4, when the header counts runs * * {@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. + * blocks seen from the open air, and {@code runs}, the sum of the run counts, each -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 static final int NONE = -1; private MapTileEncoding() { } @@ -64,9 +66,11 @@ final class MapTileEncoding { 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(); + int voxelCount = voxels == null ? NONE : voxels.count(); + MapTile.Runs runs = blocks == null ? null : blocks.runs(); + int runCount = runs == null ? NONE : runs.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, voxelCount)) + hasHeights, hasPickNoise, blocks == null ? null : statesPlayersSee(blocks.names(), pluginLooks), raised, voxelCount, runCount)) .getBytes(StandardCharsets.UTF_8); int cells = tile.gridSize() * tile.gridSize(); int length = aligned(Integer.BYTES + header.length) @@ -74,7 +78,8 @@ final class MapTileEncoding { + (hasHeights ? cells * Float.BYTES : 0) + (hasPickNoise ? cells * Float.BYTES : 0) + (blocks == null ? 0 : aligned(cells * Short.BYTES) * 3 + aligned(raised * Short.BYTES) * 2) - + (voxels == null ? 0 : aligned(voxelCount) * 3 + aligned(voxelCount * Short.BYTES) * 2); + + (voxels == null ? 0 : aligned(voxelCount) * 3 + aligned(voxelCount * Short.BYTES) * 2) + + (runs == null ? 0 : aligned(cells * Short.BYTES) + aligned(runCount * Short.BYTES) * 3); ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(header.length).put(header); align(buffer); @@ -102,6 +107,12 @@ final class MapTileEncoding { putShorts(buffer, voxels.blocks()); putBytes(buffer, voxels.faces()); } + if (runs != null) { + putShorts(buffer, runs.counts()); + putShorts(buffer, runs.bottoms()); + putShorts(buffer, runs.tops()); + putShorts(buffer, runs.blocks()); + } return buffer.array(); } @@ -130,6 +141,6 @@ final class MapTileEncoding { } private record Header(int size, double blocksPerPixel, MapLabel.Kind subjectKind, List labels, - boolean heights, boolean pickNoise, List blocks, int raised, int voxels) { + boolean heights, boolean pickNoise, List blocks, int raised, int voxels, int runs) { } } 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 1f5e1d56a..c3f972a52 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), query.flag("voxels"), cancelled); + tile = withBlocks(session, tile, startX, startZ, blockSource(query), query.flag("shape"), 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, - boolean withVoxels, BooleanSupplier cancelled) { + boolean withShape, BooleanSupplier cancelled) { try { - return session.renderer().withBlocks(tile, startX, startZ, source, withVoxels, cancelled); + return session.renderer().withBlocks(tile, startX, startZ, source, withShape, 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/ColumnRuns.java b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java new file mode 100644 index 000000000..12ebfaded --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java @@ -0,0 +1,217 @@ +/* + * 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.shorts.ShortArrayList; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.IntBinaryOperator; +import java.util.function.UnaryOperator; + +/** + * A chunk seen from afar: its blocks in square areas {@code 2^level} blocks across, each area a column of runs of + * solid blocks, highest first, as Distant Horizons draws far terrain. A height of an area counts as solid where at least + * a quarter of its blocks are, so a tree is a canopy on a trunk with air beneath, not a pillar down to the ground. The + * runs go down to the area's ground and no further; the last of each area is that ground, solid all the way down. + * Plants and water fill no run, as they are drawn their own way. + * + * @param counts how many runs each area has, the areas row by row from the north west + * @param bottoms the lowest height of each run, area after area + * @param tops the highest height of each run + * @param blocks the key of the block most of each run's top shows + */ +record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks) { + static final int MOST_LEVEL = 4; + private static final int ACROSS = 16; + private static final int SOLID_SHARE_DIVISOR = 4; + + int areasAcross() { + return (int) Math.round(Math.sqrt(counts.length)); + } + + /** Where the runs of the area at {@code index} start in {@link #bottoms}. */ + int firstRunOf(int index) { + int first = 0; + for (int area = 0; area < index; area++) { + first += counts[area]; + } + return first; + } + + /** + * @param level the areas are {@code 2^level} blocks across, 1 to {@link #MOST_LEVEL} + * @param terrainY the terrain's top in a column by its x and z in the chunk + * @param seenByPlayers the state players see in place of a block, which decides whether it is solid + */ + static ColumnRuns of(Hunk chunk, int level, IntBinaryOperator terrainY, UnaryOperator seenByPlayers) { + int areaBlocks = 1 << level; + int areasAcross = ACROSS / areaBlocks; + int fewestSolid = Math.max(1, areaBlocks * areaBlocks / SOLID_SHARE_DIVISOR); + short[] counts = new short[areasAcross * areasAcross]; + ShortArrayList bottoms = new ShortArrayList(); + ShortArrayList tops = new ShortArrayList(); + List blocks = new ArrayList<>(); + for (int areaZ = 0; areaZ < areasAcross; areaZ++) { + for (int areaX = 0; areaX < areasAcross; areaX++) { + Area area = new Area(chunk, areaX * areaBlocks, areaZ * areaBlocks, areaBlocks, seenByPlayers); + int groundY = area.lowestOf(terrainY); + int found = area.addRuns(fewestSolid, groundY, bottoms, tops, blocks); + counts[areaZ * areasAcross + areaX] = (short) found; + } + } + return new ColumnRuns(counts, bottoms.toShortArray(), tops.toShortArray(), blocks.toArray(String[]::new)); + } + + @Override + public boolean equals(Object other) { + return other instanceof ColumnRuns runs && Arrays.equals(counts, runs.counts) && Arrays.equals(bottoms, runs.bottoms) + && Arrays.equals(tops, runs.tops) && Arrays.equals(blocks, runs.blocks); + } + + @Override + public int hashCode() { + return Arrays.hashCode(counts) * 31 + Arrays.hashCode(tops); + } + + @Override + public String toString() { + return "ColumnRuns" + Arrays.toString(counts) + Arrays.toString(bottoms) + Arrays.toString(tops) + Arrays.toString(blocks); + } + + /** The runs of one area as they are found from the top down. */ + private static final class Runs { + private static final int NONE = -1; + private final ShortArrayList bottoms; + private final ShortArrayList tops; + private final List blocks; + private int top = NONE; + private int bottom; + private String block; + private int found; + + Runs(ShortArrayList bottoms, ShortArrayList tops, List blocks) { + this.bottoms = bottoms; + this.tops = tops; + this.blocks = blocks; + } + + void extendTo(int y, String shown) { + if (top != NONE && !shown.equals(block)) { + end(bottom); + } + if (top == NONE) { + top = y; + block = shown; + } + bottom = y; + } + + void endAbove(int y) { + if (top != NONE) { + end(y + 1); + } + } + + // The ground reaches down out of sight, so its run has no bottom to draw. + void endAsGround() { + if (top != NONE) { + end(0); + } + } + + private void end(int runBottom) { + bottoms.add((short) runBottom); + tops.add((short) top); + blocks.add(block); + found++; + top = NONE; + } + } + + /** One square area of a chunk, read a height at a time. */ + private record Area(Hunk chunk, int minX, int minZ, int across, UnaryOperator seenByPlayers) { + int lowestOf(IntBinaryOperator terrainY) { + int lowest = Integer.MAX_VALUE; + for (int z = minZ; z < minZ + across; z++) { + for (int x = minX; x < minX + across; x++) { + lowest = Math.min(lowest, terrainY.applyAsInt(x, z)); + } + } + return lowest; + } + + // From the top down, a run holds the solid heights in a row that mostly show one block, so a canopy, the trunk + // under it and the ground are runs of their own. Once a run reaches the ground, it is the ground and the last. + int addRuns(int fewestSolid, int groundY, ShortArrayList bottoms, ShortArrayList tops, List blocks) { + Runs runs = new Runs(bottoms, tops, blocks); + for (int y = chunk.getHeight() - 1; y >= 0; y--) { + if (solidCountAt(y) < fewestSolid) { + runs.endAbove(y); + continue; + } + runs.extendTo(y, mostShownAt(y)); + if (y <= groundY) { + runs.endAsGround(); + return runs.found; + } + } + runs.endAsGround(); + return runs.found; + } + + private int solidCountAt(int y) { + int solid = 0; + for (int z = minZ; z < minZ + across; z++) { + for (int x = minX; x < minX + across; x++) { + if (isSolid(chunk.get(x, y, z))) { + solid++; + } + } + } + return solid; + } + + private String mostShownAt(int y) { + Map shown = new HashMap<>(); + for (int z = minZ; z < minZ + across; z++) { + for (int x = minX; x < minX + across; x++) { + PlatformBlockState block = chunk.get(x, y, z); + if (isSolid(block)) { + shown.merge(block.key(), 1, Integer::sum); + } + } + } + return shown.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElseThrow(); + } + + private boolean isSolid(PlatformBlockState block) { + if (block == null || block.isAir()) { + return false; + } + PlatformBlockState seen = seenByPlayers.apply(block); + return !seen.isAir() && !seen.isFluid() && seen.isSolid(); + } + } +} 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 b14bac190..6ed243fc1 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 @@ -43,6 +43,18 @@ interface ColumnTops { return null; } + /** + * The runs of solid blocks of the area a column of a coarser tile stands for, highest first, as {@link ColumnRuns} + * finds them; null where the source knows only the tops of its columns. + */ + default AreaRuns runsAt(int worldX, int worldZ) { + return null; + } + + /** One area's runs of solid blocks, highest first, the last being the ground. */ + record AreaRuns(short[] bottoms, short[] tops, String[] blocks) { + } + /** * Blocks seen in a square of columns, each with the sides that face the open air. * 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 3d3c8e0e3..cfc4700ec 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 @@ -37,6 +37,7 @@ import it.unimi.dsi.fastutil.longs.LongList; import it.unimi.dsi.fastutil.shorts.ShortArrayList; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; @@ -72,6 +73,8 @@ final class GeneratedChunks implements ColumnTops { 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; + // Its bottom, its top and a shared key. + private static final int RUN_BYTES = Short.BYTES + Short.BYTES + Integer.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. @@ -105,20 +108,21 @@ final class GeneratedChunks implements ColumnTops { @Override public ColumnTops prepared(TileGrid grid) { boolean keepsChunks = grid.step() < BLOCKS_ACROSS; + int runLevel = runLevelOf(grid.step()); Long2ObjectMap columnsByChunk = columnsByChunkOf(grid); - Map found = new ConcurrentHashMap<>(); + 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) { - read(key, known, keepsChunks, chunk.getValue(), found, chunks); + read(key, known, keepsChunks, runLevel, chunk.getValue(), found, chunks); continue; } Runnable generation = () -> { if (!grid.cancelled().getAsBoolean()) { - read(key, keepsChunks ? tops.get(key) : topWithoutKeeping(key), keepsChunks, chunk.getValue(), found, chunks); + read(key, keepsChunks ? tops.get(key) : topWithoutKeeping(key), keepsChunks, runLevel, chunk.getValue(), found, chunks); } }; ChunkTask task = new ChunkTask(generation, grid.step()); @@ -136,20 +140,36 @@ final class GeneratedChunks implements ColumnTops { return new PreparedTile(found, chunks); } + // A tile a block a column has no runs; a coarser one has those of its columns' areas, or of the largest a chunk has. + private static int runLevelOf(double blocksPerColumn) { + int level = (int) Math.round(Math.log(blocksPerColumn) / Math.log(2)); + return blocksPerColumn < 2D ? 0 : Math.min(level, ColumnRuns.MOST_LEVEL); + } + + /** One column of a tile as read from its chunk: its top, and the runs of the area it stands for, if any. */ + private record ColumnSample(ColumnTop top, AreaRuns runs) { + } + /** 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 columns; private final Map chunks; - PreparedTile(Map columns, 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); + ColumnSample column = columns.get(keyOf(worldX, worldZ)); + return column != null ? column.top() : GeneratedChunks.this.at(worldX, worldZ); + } + + @Override + public AreaRuns runsAt(int worldX, int worldZ) { + ColumnSample column = columns.get(keyOf(worldX, worldZ)); + return column == null ? null : column.runs(); } @Override @@ -208,8 +228,9 @@ final class GeneratedChunks implements ColumnTops { return columnsByChunk; } - private static void read(long key, ChunkTop chunk, boolean keepsChunk, LongList columns, Map found, Map chunks) { - readColumns(chunk, columns, found); + private static void read(long key, ChunkTop chunk, boolean keepsChunk, int runLevel, LongList columns, Map found, + Map chunks) { + readColumns(chunk, runLevel, columns, found); if (keepsChunk) { chunks.put(key, chunk); } @@ -227,14 +248,25 @@ final class GeneratedChunks implements ColumnTops { } } - private static void readColumns(ChunkTop chunk, LongList columns, Map found) { + private static void readColumns(ChunkTop chunk, int runLevel, LongList columns, Map found) { for (long column : columns) { int worldX = (int) (column >> Integer.SIZE); int worldZ = (int) column; - found.put(column, chunk.columns[(worldZ & CHUNK_MASK) * BLOCKS_ACROSS + (worldX & CHUNK_MASK)]); + ColumnTop top = chunk.columns[(worldZ & CHUNK_MASK) * BLOCKS_ACROSS + (worldX & CHUNK_MASK)]; + AreaRuns runs = runLevel == 0 ? null : runsOf(chunk.runs[runLevel - 1], worldX & CHUNK_MASK, worldZ & CHUNK_MASK, runLevel); + found.put(column, new ColumnSample(top, runs)); } } + private static AreaRuns runsOf(ColumnRuns runs, int x, int z, int level) { + int areasAcross = BLOCKS_ACROSS >> level; + int area = (z >> level) * areasAcross + (x >> level); + int first = runs.firstRunOf(area); + int last = first + runs.counts()[area]; + return new AreaRuns(Arrays.copyOfRange(runs.bottoms(), first, last), Arrays.copyOfRange(runs.tops(), first, last), + Arrays.copyOfRange(runs.blocks(), first, last)); + } + private static void awaitUnlessCancelled(Future chunk, BooleanSupplier cancelled) { while (true) { MapTileRenderer.checkCancelled(cancelled); @@ -296,7 +328,11 @@ final class GeneratedChunks implements ColumnTops { } IntBinaryOperator terrainY = (x, z) -> engine.getHeight((chunkX << CHUNK_SHIFT) + x, (chunkZ << CHUNK_SHIFT) + z, true); int fluidHeight = engine.getDimension().getFluidHeight(); - return new ChunkTop(topsOf(blocks, terrainY, this::seenByPlayers), VisibleBlocks.of(blocks, terrainY, fluidHeight, this::seenByPlayers)); + ColumnRuns[] runs = new ColumnRuns[ColumnRuns.MOST_LEVEL]; + for (int level = 1; level <= ColumnRuns.MOST_LEVEL; level++) { + runs[level - 1] = ColumnRuns.of(blocks, level, terrainY, this::seenByPlayers); + } + return new ChunkTop(topsOf(blocks, terrainY, this::seenByPlayers), VisibleBlocks.of(blocks, terrainY, fluidHeight, this::seenByPlayers), runs); } // A plugin's block can be solid on the server where players see grass they walk through. @@ -314,13 +350,20 @@ final class GeneratedChunks implements ColumnTops { return ((long) chunkX << Integer.SIZE) | (chunkZ & 0xFFFFFFFFL); } - private record ChunkTop(ColumnTop[] columns, VisibleBlocks visible) { + /** + * @param runs the chunk's runs of solid blocks in areas 2, 4, 8 and 16 blocks across, for coarser tiles + */ + private record ChunkTop(ColumnTop[] columns, VisibleBlocks visible, ColumnRuns[] runs) { int bytes() { int raisedBlocks = 0; for (ColumnTop column : columns) { raisedBlocks += column.raised().count(); } - return CHUNK_TOP_BYTES + raisedBlocks * RAISED_BLOCK_BYTES + visible.count() * VISIBLE_BLOCK_BYTES; + int runs = 0; + for (ColumnRuns level : this.runs) { + runs += level.tops().length; + } + return CHUNK_TOP_BYTES + raisedBlocks * RAISED_BLOCK_BYTES + visible.count() * VISIBLE_BLOCK_BYTES + runs * RUN_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 51ed83098..37654eb16 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 @@ -47,12 +47,28 @@ public record MapTile(int size, double blocksPerPixel, MapLabel.Kind subjectKind * @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 + * @param runs the runs of solid blocks of the area each cell stands for, in a coarser tile; else null */ public record Blocks(List names, short[] ground, short[] cover, short[] raisedCounts, short[] raisedY, short[] raised, - Voxels voxels) { + Voxels voxels, Runs runs) { public static final short NO_BLOCK = -1; } + /** + * The ground of a coarser tile in 3D: for each cell, the runs of solid blocks of the area it stands for, highest + * first, the last being the ground, which reaches down out of sight. + * + * @param counts how many runs each cell has + * @param bottoms the lowest height of each run, cell after cell + * @param tops the highest height of each run + * @param blocks the index in the tile's block names of the block most of each run's top shows + */ + public record Runs(short[] counts, short[] bottoms, short[] tops, short[] blocks) { + public int count() { + return tops.length; + } + } + /** * 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. * 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 c3614e7f1..872008020 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,12 +77,13 @@ 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 + * @param withShape whether the tile also carries the ground's shape in 3D, where the source knows it: every block + * seen from the open air in a tile of a block a pixel, the runs of solid blocks of each cell's area + * in a coarser one * @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, boolean withVoxels, BooleanSupplier cancelled) { + public MapTile withBlocks(MapTile tile, double startX, double startZ, BlockSource source, boolean withShape, BooleanSupplier cancelled) { double step = tile.blocksPerPixel(); if (step > source.largestBlocksPerPixel()) { throw new IllegalArgumentException("Blocks from " + source.id() + " are drawn at " + source.largestBlocksPerPixel() @@ -117,11 +118,36 @@ public final class MapTileRenderer { } } } - 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); + MapTile.Voxels voxels = withShape && step == 1D ? voxelsOf(tops, startX, startZ, tile.size(), names) : null; + MapTile.Runs runs = withShape && step > 1D ? runsOf(tops, grid, names) : null; + MapTile.Blocks blocks = new MapTile.Blocks(names.names(), ground, cover, raisedCounts, raisedY.toShortArray(), raised.toShortArray(), + voxels, runs); return tile.withBlocks(blocks, heights); } + private static MapTile.Runs runsOf(ColumnTops tops, TileGrid grid, BlockNames names) { + short[] counts = new short[grid.size() * grid.size()]; + ShortArrayList bottoms = new ShortArrayList(); + ShortArrayList runTops = new ShortArrayList(); + ShortArrayList blocks = new ShortArrayList(); + for (int gridZ = 0; gridZ < grid.size(); gridZ++) { + int worldZ = (int) Math.floor(grid.worldZ(gridZ)); + for (int gridX = 0; gridX < grid.size(); gridX++) { + ColumnTops.AreaRuns area = tops.runsAt((int) Math.floor(grid.worldX(gridX)), worldZ); + if (area == null) { + return null; + } + counts[gridZ * grid.size() + gridX] = (short) area.tops().length; + bottoms.addElements(bottoms.size(), area.bottoms()); + runTops.addElements(runTops.size(), area.tops()); + for (String block : area.blocks()) { + blocks.add(names.indexOf(block)); + } + } + } + return new MapTile.Runs(counts, bottoms.toShortArray(), runTops.toShortArray(), blocks.toShortArray()); + } + // 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); diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java new file mode 100644 index 000000000..2688b413f --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java @@ -0,0 +1,88 @@ +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.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ColumnRunsTest { + private static final int HEIGHT = 16; + private static final int GROUND_Y = 3; + private static final PlatformBlockState GRASS = block("minecraft:grass_block"); + private static final PlatformBlockState LOG = block("minecraft:oak_log"); + private static final PlatformBlockState LEAVES = block("minecraft:oak_leaves"); + + @Test + public void flatGroundIsOneRunPerArea() { + ColumnRuns runs = ColumnRuns.of(groundUpTo(GROUND_Y), 1, (x, z) -> GROUND_Y, UnaryOperator.identity()); + + assertEquals(64, runs.counts().length); + assertEquals(1, runs.counts()[0]); + assertEquals(GROUND_Y, runs.tops()[0]); + assertEquals("minecraft:grass_block", runs.blocks()[0]); + } + + @Test + public void aTreeIsACanopyOnATrunkOnTheGroundNotAPillar() { + Hunk chunk = groundUpTo(GROUND_Y); + for (int y = GROUND_Y + 1; y <= GROUND_Y + 4; y++) { + chunk.set(0, y, 0, LOG); + } + for (int z = 0; z < 2; z++) { + for (int x = 0; x < 2; x++) { + chunk.set(x, GROUND_Y + 5, z, LEAVES); + chunk.set(x, GROUND_Y + 6, z, LEAVES); + } + } + + ColumnRuns runs = ColumnRuns.of(chunk, 1, (x, z) -> GROUND_Y, UnaryOperator.identity()); + + assertEquals(3, runs.counts()[0]); + assertArrayEquals(new short[]{GROUND_Y + 6, GROUND_Y + 4, GROUND_Y}, new short[]{runs.tops()[0], runs.tops()[1], runs.tops()[2]}); + assertArrayEquals(new short[]{GROUND_Y + 5, GROUND_Y + 1, 0}, new short[]{runs.bottoms()[0], runs.bottoms()[1], runs.bottoms()[2]}); + assertArrayEquals(new String[]{"minecraft:oak_leaves", "minecraft:oak_log", "minecraft:grass_block"}, new String[]{runs.blocks()[0], runs.blocks()[1], runs.blocks()[2]}); + } + + @Test + public void aCanopyOverOpenGroundFloatsWithAirUnderIt() { + Hunk chunk = groundUpTo(GROUND_Y); + for (int z = 2; z < 4; z++) { + for (int x = 2; x < 4; x++) { + chunk.set(x, GROUND_Y + 5, z, LEAVES); + } + } + + ColumnRuns runs = ColumnRuns.of(chunk, 1, (x, z) -> GROUND_Y, UnaryOperator.identity()); + int area = 1 * 8 + 1; + int first = runs.firstRunOf(area); + + assertEquals(2, runs.counts()[area]); + assertEquals(GROUND_Y + 5, runs.bottoms()[first]); + assertEquals(GROUND_Y, runs.tops()[first + 1]); + } + + 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, GRASS); + } + } + } + return chunk; + } + + private static PlatformBlockState block(String key) { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(key); + when(block.isSolid()).thenReturn(true); + return block; + } +} diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index d44f75e10..f39111745 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -52,8 +52,11 @@ 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 + /** + * Whether a tile with blocks also carries the ground's shape in 3D: every block seen from the open air at a block a + * pixel, the runs of solid blocks of each cell's area when coarser. + */ + shape?: boolean } /** One tile of a pattern: tile (x, z) covers columns × blocksPerColumn blocks from x × that, z × that. */ @@ -143,8 +146,8 @@ export class BridgeClient { }) if (request.blocks !== null) { query.set('blocks', request.blocks) - if (request.voxels === true) { - query.set('voxels', '1') + if (request.shape === true) { + query.set('shape', '1') } this.cancelOnAbort(query, signal) } diff --git a/studio/src/renderer/src/bridge/tileDecoding.ts b/studio/src/renderer/src/bridge/tileDecoding.ts index c860b6dd2..efcb5b5c6 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, TileVoxels } from './types' +import type { LabelKind, MapLabel, MapTile, TileBlocks, TileRuns, TileVoxels } from './types' const ALIGNMENT_BYTES = 4 @@ -15,9 +15,11 @@ interface TileHeader { raised?: number /** How many blocks can be seen from the open air, or -1 on a tile without them. */ voxels?: number + /** How many runs of solid blocks the cells have together, or -1 on a tile without them. */ + runs?: number } -const NO_VOXELS = -1 +const NONE = -1 function aligned(bytes: number): number { return Math.ceil(bytes / ALIGNMENT_BYTES) * ALIGNMENT_BYTES @@ -48,17 +50,18 @@ 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, header.voxels ?? NO_VOXELS) + blocks: header.blocks == null ? null : decodeBlocks(buffer, groundAt, cells, header.blocks, header.raised ?? 0, header.voxels ?? NONE, header.runs ?? NONE) } } -function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, names: string[], raisedCount: number, voxelCount: number): TileBlocks { +function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, names: string[], raisedCount: number, voxelCount: number, runCount: 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) + const runsAt = voxelsAt + (voxelCount === NONE ? 0 : voxelBytes(voxelCount)) return { names, ground: new Int16Array(buffer, groundAt, cells), @@ -66,7 +69,8 @@ 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), + voxels: voxelCount === NONE ? null : decodeVoxels(buffer, voxelsAt, voxelCount), + runs: runCount === NONE ? null : decodeRuns(buffer, runsAt, cells, runCount), colors: [], looks: [], covers: [], @@ -74,6 +78,22 @@ function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, name } } +function voxelBytes(count: number): number { + return aligned(count) * 3 + aligned(count * Int16Array.BYTES_PER_ELEMENT) * 2 +} + +function decodeRuns(buffer: ArrayBuffer, countsAt: number, cells: number, count: number): TileRuns { + const bottomsAt = countsAt + aligned(cells * Int16Array.BYTES_PER_ELEMENT) + const topsAt = bottomsAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const blocksAt = topsAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + return { + starts: startsOf(new Int16Array(buffer, countsAt, cells)), + bottoms: new Int16Array(buffer, bottomsAt, count), + tops: new Int16Array(buffer, topsAt, count), + blocks: new Int16Array(buffer, blocksAt, count) + } +} + function decodeVoxels(buffer: ArrayBuffer, xAt: number, count: number): TileVoxels { const zAt = xAt + aligned(count) const yAt = zAt + aligned(count) diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index c126f40e3..f81fbc88c 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -363,6 +363,8 @@ export interface TileBlocks { 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 + /** The runs of solid blocks of the area each cell stands for, where the tile is coarser and they were asked for; else null. */ + runs: TileRuns | 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. */ @@ -389,6 +391,19 @@ export interface TileVoxels { faces: Uint8Array } +/** + * The ground of a coarser tile in 3D, as Distant Horizons draws far terrain: for each cell, the runs of solid blocks of + * the area it stands for, highest first. The last run of a cell is its ground, which reaches down out of sight. + */ +export interface TileRuns { + /** Where each cell's runs start in the arrays below, with one more entry for where the last cell's end. */ + starts: Int32Array + bottoms: Int16Array + tops: Int16Array + /** The index in the tile's block names of the block most of each run's top shows. */ + blocks: Int16Array +} + /** The order of the sides in {@link TileVoxels.faces}. */ export const VOXEL_SIDES = ['down', 'up', 'north', 'south', 'west', 'east'] as const diff --git a/studio/src/renderer/src/map/map.test.ts b/studio/src/renderer/src/map/map.test.ts index d1346f158..4ad7b8a0c 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), voxels: null, models: [] } +function nothingRaised(cells: number): Pick { + return { raisedStart: new Int32Array(cells + 1), raisedY: new Int16Array(0), raised: new Int16Array(0), voxels: null, runs: 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. */ @@ -193,6 +193,7 @@ describe('tile style', () => { raisedY: Int16Array.of(70, 69), raised: Int16Array.of(1, 2), voxels: null, + runs: null, colors: [0x808080, 0x00ff00, 0x654321], looks: [], covers: [], diff --git a/studio/src/renderer/src/map/mapTileSource.ts b/studio/src/renderer/src/map/mapTileSource.ts index 2d09c189c..d887cb1f0 100644 --- a/studio/src/renderer/src/map/mapTileSource.ts +++ b/studio/src/renderer/src/map/mapTileSource.ts @@ -13,8 +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 + /** Whether tiles with blocks also carry the ground's shape in 3D, to draw it as blocks and runs of blocks. */ + shape?: boolean /** Bumped when the pack is hotloaded, so older tiles are not used again. */ revision: number } @@ -43,12 +43,13 @@ 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 ?? '', layer.voxels === true].join('/'), + layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? '', layer.shape === 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) if (tile.blocks !== null) { - await art.paint(tile.blocks, address.blocksPerPixel === TEXTURED_BLOCKS_PER_PIXEL) + // Runs show each block's sides in the colours of its pictures, so their looks are read too. + await art.paint(tile.blocks, address.blocksPerPixel === TEXTURED_BLOCKS_PER_PIXEL || tile.blocks.runs !== null) } return tile }, diff --git a/studio/src/renderer/src/scene/mapTerrain.test.ts b/studio/src/renderer/src/scene/mapTerrain.test.ts index cfa39b655..b3c4aa734 100644 --- a/studio/src/renderer/src/scene/mapTerrain.test.ts +++ b/studio/src/renderer/src/scene/mapTerrain.test.ts @@ -23,6 +23,7 @@ function tileWithALeaf(): MapTile { raisedY: Int16Array.of(LEAF_Y), raised: Int16Array.of(1), voxels: null, + runs: null, colors: [STONE, LEAVES], looks: [], covers: [], diff --git a/studio/src/renderer/src/scene/mapTerrain.ts b/studio/src/renderer/src/scene/mapTerrain.ts index 1f899a2fc..9e87cf105 100644 --- a/studio/src/renderer/src/scene/mapTerrain.ts +++ b/studio/src/renderer/src/scene/mapTerrain.ts @@ -4,6 +4,7 @@ import type { BlockLook } from './blockLooks' import type { CoverLook } from './coverLooks' import type { TerrainPictures } from './terrainAtlas' import type { RaisedBlock, TerrainSurface } from './terrainMesh' +import type { SurfaceRuns } from './runFaces' import type { SurfaceVoxels } from './voxelMesh' import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles' @@ -93,6 +94,14 @@ export class MapTerrain implements TerrainSurface { } } + runs(): SurfaceRuns | null { + const blocks = this.coloring === 'blocks' ? this.tile.blocks : null + if (blocks === null || blocks.runs === null) { + return null + } + return { runs: blocks.runs, cellAt: (column, row) => this.cellAt(column, row), looks: blocks.looks, colors: blocks.colors } + } + 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/runFaces.test.ts b/studio/src/renderer/src/scene/runFaces.test.ts new file mode 100644 index 000000000..70fe66394 --- /dev/null +++ b/studio/src/renderer/src/scene/runFaces.test.ts @@ -0,0 +1,71 @@ +import { Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import { ColumnField } from './columnField' +import { runFaces, uncovered, type SurfaceRuns } from './runFaces' +import type { TerrainSurface } from './terrainMesh' + +const GROUND = 10 +const BASE = 0 +const CANOPY_BOTTOM = 14 +const CANOPY_TOP = 15 + +// Two columns side by side, a block each: plain ground on the west, ground with a canopy floating over it on the east. +const surface: TerrainSurface = { + columns: 2, + rows: 1, + originX: 0, + originZ: 0, + blocksPerColumn: 1, + groundAt: () => GROUND, + waterAt: () => null, + colorAt: () => 0x808080 +} + +const runs: SurfaceRuns = { + runs: { + starts: Int32Array.of(0, 1, 3), + bottoms: Int16Array.of(0, CANOPY_BOTTOM, 0), + tops: Int16Array.of(GROUND, CANOPY_TOP, GROUND), + blocks: Int16Array.of(0, 1, 0) + }, + cellAt: (column) => column, + looks: [null, null], + colors: [0x808080, 0x00ff00] +} + +function faces(): { middle: Vector3; normal: Vector3 }[] { + const geometry = runFaces(new ColumnField(surface), runs, BASE).geometry() + const positions = geometry.getAttribute('position') + const found: { middle: Vector3; normal: Vector3 }[] = [] + for (let first = 0; first < positions.count; first += 4) { + const corner = (index: number): Vector3 => new Vector3().fromBufferAttribute(positions, first + index) + const [origin, up, along, far] = [corner(0), corner(1), corner(2), corner(3)] + found.push({ middle: origin.clone().add(far).multiplyScalar(0.5), normal: up.clone().sub(origin).cross(along.clone().sub(origin)).normalize() }) + } + return found +} + +describe('run faces', () => { + it('finds the parts of a span its neighbours leave open', () => { + expect(uncovered({ bottom: 0, top: 10 }, [{ bottom: 3, top: 5 }])).toEqual([{ bottom: 0, top: 2 }, { bottom: 6, top: 10 }]) + expect(uncovered({ bottom: -Infinity, top: 10 }, [{ bottom: -Infinity, top: 12 }])).toEqual([]) + }) + + it('floats a canopy over the ground with its underside showing', () => { + const drawn = faces() + + expect(drawn.some((face) => face.normal.y === -1 && face.middle.y === CANOPY_BOTTOM && face.middle.x === 1.5)).toBe(true) + expect(drawn.some((face) => face.normal.y === 1 && face.middle.y === CANOPY_TOP + 1 && face.middle.x === 1.5)).toBe(true) + }) + + it('shows the side of a run toward a neighbour where the neighbour leaves it open, and walls the field edge down to the base', () => { + const drawn = faces() + const canopyWest = drawn.filter((face) => face.normal.x === -1 && face.middle.x === 1) + const groundBetween = drawn.filter((face) => face.normal.x !== 0 && face.middle.x === 1 && face.middle.y <= GROUND + 1) + + expect(canopyWest.map((face) => face.middle.y).sort()).toEqual([CANOPY_BOTTOM + 0.5, CANOPY_TOP + 0.5]) + expect(groundBetween).toEqual([]) + // Under the top block's side, the wall at the field's edge reaches from the base to the ground's top block. + expect(drawn.some((face) => face.normal.x === -1 && face.middle.x === 0 && face.middle.y === (BASE + GROUND) / 2)).toBe(true) + }) +}) diff --git a/studio/src/renderer/src/scene/runFaces.ts b/studio/src/renderer/src/scene/runFaces.ts new file mode 100644 index 000000000..68ff288e9 --- /dev/null +++ b/studio/src/renderer/src/scene/runFaces.ts @@ -0,0 +1,169 @@ +import type { TileRuns } from '../bridge/types' +import type { Direction } from './blockModels' +import type { BlockLook } from './blockLooks' +import type { ColumnField } from './columnField' +import { shaded } from './columnFaces' +import { FACE_LIGHT } from './coverLooks' +import { QuadBatch, type Vec3 } from './quadBatch' +import { sunk, tintAt } from './waterTint' + +/** A coarser tile's runs of solid blocks, and how to colour the blocks they name. */ +export interface SurfaceRuns { + runs: TileRuns + /** Where a column's runs lie in {@link runs}, by its column and row. */ + cellAt(column: number, row: number): number + looks: readonly (BlockLook | null)[] + colors: readonly number[] +} + +interface Side { + direction: Direction + columnStep: number + rowStep: number +} + +const SIDES: readonly Side[] = [ + { direction: 'north', columnStep: 0, rowStep: -1 }, + { direction: 'south', columnStep: 0, rowStep: 1 }, + { direction: 'west', columnStep: -1, rowStep: 0 }, + { direction: 'east', columnStep: 1, rowStep: 0 } +] + +/** A span of heights, both ends included. */ +interface Span { + bottom: number + top: number +} + +/** + * A coarser tile's ground in 3D: each run of solid blocks of each column as a box as wide as the column, with its top, + * its underside where it floats, and its sides where the columns beside it leave them in the open. The ground reaches + * down to the run under its neighbours' tops, or to {@code base} at the field's edge and beside holes, so tiles next to + * each other leave no cracks. Each face takes the average colour of its block's picture on that side, as the textures of + * finer ground fade to it with distance, so the change from one to the other cannot be seen. + */ +export function runFaces(field: ColumnField, surface: SurfaceRuns, base: number): QuadBatch { + const batch = new QuadBatch(true) + for (let row = 0; row < field.rows; row++) { + for (let column = 0; column < field.columns; column++) { + if (field.hasGround(column, row)) { + addColumn(batch, field, surface, column, row, base) + } + } + } + return batch +} + +function addColumn(batch: QuadBatch, field: ColumnField, surface: SurfaceRuns, column: number, row: number, base: number): void { + const { runs } = surface + const cell = surface.cellAt(column, row) + const first = runs.starts[cell] + const last = runs.starts[cell + 1] - 1 + const water = field.waterTopAt(column, row) + for (let run = first; run <= last; run++) { + const isGround = run === last + const top = runs.tops[run] + const bottom = runs.bottoms[run] + const block = runs.blocks[run] + if (run === first || runs.bottoms[run - 1] !== top + 1) { + addTop(batch, field, column, row, top + 1, colorOf(surface, block, 'top', FACE_LIGHT.up), water) + } + if (!isGround && (run === last || runs.tops[run + 1] !== bottom - 1)) { + addBottom(batch, field, column, row, bottom, colorOf(surface, block, 'top', FACE_LIGHT.down), water) + } + for (const side of SIDES) { + const neighbour = [column + side.columnStep, row + side.rowStep] as const + const known = field.hasGround(...neighbour) && hasRuns(surface, surface.cellAt(...neighbour)) + const lowest = isGround ? (known ? -Infinity : base) : bottom + const covered = known ? spansOf(surface, surface.cellAt(...neighbour)) : [] + for (const open of uncovered({ bottom: lowest, top }, covered)) { + addSide(batch, field, surface, column, row, side, open, top, block, water) + } + } + } +} + +function hasRuns(surface: SurfaceRuns, cell: number): boolean { + return surface.runs.starts[cell + 1] > surface.runs.starts[cell] +} + +// The heights of a column its runs fill, the ground's reaching all the way down. +function spansOf(surface: SurfaceRuns, cell: number): Span[] { + const { runs } = surface + const spans: Span[] = [] + const last = runs.starts[cell + 1] - 1 + for (let run = runs.starts[cell]; run <= last; run++) { + spans.push({ bottom: run === last ? -Infinity : runs.bottoms[run], top: runs.tops[run] }) + } + return spans +} + +/** The parts of {@code span} none of {@code covered} fills, lowest first. */ +export function uncovered(span: Span, covered: readonly Span[]): Span[] { + let open: Span[] = [span] + for (const cover of covered) { + open = open.flatMap((part) => { + if (cover.top < part.bottom || cover.bottom > part.top) { + return [part] + } + const left: Span[] = [] + if (cover.bottom > part.bottom) { + left.push({ bottom: part.bottom, top: cover.bottom - 1 }) + } + if (cover.top < part.top) { + left.push({ bottom: cover.top + 1, top: part.top }) + } + return left + }) + } + return open.filter((part) => part.top >= part.bottom).sort((first, second) => first.bottom - second.bottom) +} + +// The top block of a run shows its side picture; the blocks under it, the picture of the blocks under a column's top. +function addSide(batch: QuadBatch, field: ColumnField, surface: SurfaceRuns, column: number, row: number, side: Side, open: Span, runTop: number, block: number, water: number | null): void { + const light = side.direction === 'north' || side.direction === 'south' ? FACE_LIGHT.north : FACE_LIGHT.west + if (open.top === runTop) { + addSideQuad(batch, field, column, row, side, runTop, runTop + 1, colorOf(surface, block, 'side', light), water) + } + const belowTop = open.top === runTop ? runTop - 1 : open.top + if (belowTop >= open.bottom) { + addSideQuad(batch, field, column, row, side, open.bottom, belowTop + 1, colorOf(surface, block, 'below', light), water) + } +} + +function addSideQuad(batch: QuadBatch, field: ColumnField, column: number, row: number, side: Side, from: number, to: number, color: Vec3, water: number | null): void { + const step = field.blocksPerColumn + const x = field.originX + column * step + const z = field.originZ + row * step + const up: Vec3 = [0, to - from, 0] + const [origin, along]: [Vec3, Vec3] = + side.rowStep < 0 + ? [[x, from, z], [step, 0, 0]] + : side.rowStep > 0 + ? [[x + step, from, z + step], [-step, 0, 0]] + : side.columnStep < 0 + ? [[x, from, z + step], [0, 0, -step]] + : [[x + step, from, z], [0, 0, step]] + batch.add(origin, along, up, underWater(color, from, water), underWater(color, to, water)) +} + +function addTop(batch: QuadBatch, field: ColumnField, column: number, row: number, y: number, color: Vec3, water: number | null): void { + const step = field.blocksPerColumn + const shown = underWater(color, y, water) + batch.add([field.originX + column * step, y, field.originZ + row * step], [step, 0, 0], [0, 0, step], shown, shown) +} + +function addBottom(batch: QuadBatch, field: ColumnField, column: number, row: number, y: number, color: Vec3, water: number | null): void { + const step = field.blocksPerColumn + const shown = underWater(color, y, water) + batch.add([field.originX + column * step, y, field.originZ + row * step], [0, 0, step], [step, 0, 0], shown, shown) +} + +function colorOf(surface: SurfaceRuns, block: number, face: 'top' | 'side' | 'below', light: number): Vec3 { + const look = surface.looks[block] + return shaded(look === null || look === undefined ? surface.colors[block] : look[face].color, light) +} + +function underWater(color: Vec3, y: number, water: number | null): Vec3 { + return water === null ? color : sunk(color, tintAt(water - y)) +} diff --git a/studio/src/renderer/src/scene/terrainMesh.ts b/studio/src/renderer/src/scene/terrainMesh.ts index 66c23b768..ee9c8e404 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 { runFaces, type SurfaceRuns } from './runFaces' import { voxelGeometries, type SurfaceVoxels } from './voxelMesh' import type { TerrainPictures } from './terrainAtlas' import type { ColumnArea } from './terrainTiles' @@ -41,6 +42,8 @@ export interface TerrainSurface { * ground lies; null to draw the columns. */ voxels?(): SurfaceVoxels | null + /** The runs of solid blocks of each column's area, to draw in place of the columns' tops; null to draw the columns. */ + runs?(): SurfaceRuns | null } /** A solid block above a column's ground, drawn as a whole block. */ @@ -76,6 +79,10 @@ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: r if (voxels !== null && field.pictures !== null) { return voxelMesh(field, voxels, field.pictures) } + const runs = surface.runs?.() ?? null + if (runs !== null) { + return runMesh(field, runs, base) + } const groundBatch = groundFaces(field, base) const seeThroughBatch = new QuadBatch(true, field.pictures?.plain ?? null) addRaisedFaces(field, groundBatch, seeThroughBatch) @@ -119,6 +126,15 @@ function voxelMesh(field: ColumnField, voxels: SurfaceVoxels, pictures: TerrainP return { object: group, field, dispose: () => parts.forEach((part) => part.dispose()) } } +function runMesh(field: ColumnField, runs: SurfaceRuns, base: number): TerrainMesh { + const batch = runFaces(field, runs, base) + const parts = [meshOf(batch.geometry(), new MeshBasicMaterial({ vertexColors: true, side: FrontSide })), meshOf(waterFaces(field).geometry(), waterMaterial())] + const group = new Group() + // The water is drawn last, over what stands under it. + 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), diff --git a/studio/src/renderer/src/studio/WorldStudio3D.tsx b/studio/src/renderer/src/studio/WorldStudio3D.tsx index 83d8aab27..d1330989f 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, voxels: false } + return layer.blocks === null ? null : { ...layer, blocks: null, shape: 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, voxels: showsBlocks, revision: packRevision }), + () => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, blocks: showsBlocks ? 'generated' : null, shape: showsBlocks, revision: packRevision }), [packRevision, showsBlocks] ) const style = useMemo>(