Show generated blocks in the 3D world out to the horizon

Blocks came only on tiles of one block a column, so most of the view
showed biome colours, and zooming out swapped the blocks already seen
for them.

Every tile now carries blocks. The server generates a tile's chunks on
a pool of their own, finer tiles first, keeps up to 512 MB of chunk
tops, and stops a tile the studio cancels. A tile's quick biome version
is drawn only where no tile with blocks of any level is known, so
ground once sampled stays in sight until its replacement has blocks
too. Wider columns take their highest raised block as their top. The
planner now splits columns down to half a pixel and draws up to 192
tiles.
This commit is contained in:
piexel committed 2026-11-12 07:34:49 +01:00
1 parent 6de53ee898
commit e759edadfe
17 files changed
+425 -62

No files matched your search

@@ -19,6 +19,8 @@
package art.arcane.iris.core.studio.bridge;
import art.arcane.iris.core.gui.GuiHost;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import art.arcane.iris.core.link.CustomBlockLook;
import art.arcane.iris.core.link.CustomBlockSource;
import art.arcane.iris.spi.IrisServices;
@@ -89,6 +91,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
@@ -110,6 +113,7 @@ public final class StudioBridge implements AutoCloseable {
private static final int LARGEST_BODY_BYTES = 4 * 1024 * 1024;
private static final double SMALLEST_BLOCKS_PER_PIXEL = 1D / 16D;
private static final double LARGEST_BLOCKS_PER_PIXEL = 4_096D;
private static final long DROPPED_TILE_KEPT_MINUTES = 10;
// Each pixel reads the chunk it lands in, so a saved world is shown no farther out than a pixel per chunk.
private static final int LARGEST_SAVED_BLOCKS_PER_PIXEL = 16;
// A palette is picked block by block, so far out a column stands for the blocks around it; past this it says little.
@@ -139,6 +143,9 @@ public final class StudioBridge implements AutoCloseable {
private final ScheduledExecutorService ticker;
private final StudioEvents events;
private final Runnable hotloadHook;
// Whether the studio stopped waiting for each tile, by the id it gave the request. A cancel can arrive before its tile
// does, so each is kept a while rather than for its tile alone.
private final Cache<String, AtomicBoolean> droppedTiles = Caffeine.newBuilder().expireAfterWrite(DROPPED_TILE_KEPT_MINUTES, TimeUnit.MINUTES).build();
private volatile boolean closed;
private StudioBridge(StudioWorld world) throws IOException {
@@ -234,6 +241,7 @@ public final class StudioBridge implements AutoCloseable {
switch (endpoint) {
case "world" -> sendJson(exchange, STATUS_OK, worldInfo(get(exchange)));
case "tile" -> sendBytes(exchange, "application/octet-stream", tile(get(exchange), query));
case "tile-cancel" -> cancelTile(exchange, query);
case "hover" -> sendJson(exchange, STATUS_OK, hover(get(exchange).engine(), query));
case "picks" -> sendJson(exchange, STATUS_OK, picks(get(exchange).engine(), query));
case "regions" -> sendJson(exchange, STATUS_OK, regions(get(exchange).engine()));
@@ -601,7 +609,8 @@ public final class StudioBridge implements AutoCloseable {
double tileBlocks = size * blocksPerPixel;
double startX = query.whole("x", 0) * tileBlocks;
double startZ = query.whole("z", 0) * tileBlocks;
BooleanSupplier cancelled = () -> closed || engine.isClosing() || engine.isClosed();
AtomicBoolean dropped = query.has("request") ? droppedFlagOf(query.text("request")) : new AtomicBoolean();
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);
@@ -609,6 +618,17 @@ public final class StudioBridge implements AutoCloseable {
return MapTileEncoding.encode(tile, gson, StudioBridge::pluginLookOf);
}
// A tile with blocks may generate thousands of chunks, so one the studio stopped waiting for is let go of.
private void cancelTile(HttpExchange exchange, Query query) throws IOException {
requireMethod(exchange, "POST");
droppedFlagOf(query.text("request")).set(true);
sendJson(exchange, STATUS_OK, new MessageBody(null));
}
private AtomicBoolean droppedFlagOf(String requestId) {
return droppedTiles.get(requestId, id -> new AtomicBoolean());
}
private static MapTile withBlocks(StudioWorld.Session session, MapTile tile, double startX, double startZ, BlockSource source,
BooleanSupplier cancelled) {
try {
@@ -23,8 +23,11 @@ import java.util.Optional;
/** Where a tile's blocks come from. */
public enum BlockSource {
/** The chunks generated in memory: what the world would hold, at a block a pixel or finer. */
GENERATED("generated", 1D);
/**
* The chunks generated in memory: what the world would hold, at any scale. A tile generates every chunk its pixels
* fall in, so one coarser than a chunk a pixel costs a chunk for each pixel, up to about a minute's work.
*/
GENERATED("generated", 4_096D);
private final String id;
private final double largestBlocksPerPixel;
@@ -25,6 +25,15 @@ import java.util.Arrays;
interface ColumnTops {
ColumnTop at(int worldX, int worldZ);
/**
* Readies the tops of the grid's columns at once, so asking for them one by one after is quick. Nothing to do for a
* source whose tops are quick to find.
*
* @throws java.util.concurrent.CancellationException as soon as the grid's request is cancelled
*/
default void prepare(TileGrid grid) {
}
/**
* The top of one column.
*
@@ -35,25 +35,44 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BooleanSupplier;
import java.util.function.IntBinaryOperator;
import java.util.function.IntToDoubleFunction;
import java.util.function.UnaryOperator;
import java.util.stream.IntStream;
/**
* The tops of chunks generated for the studio alone: each chunk runs through the world's own stages into memory, so its
* columns hold what the world would, trees and structures included, and nothing is placed in the world. Generating
* plans the chunk's surroundings in the world's mantle, as generating it in the world would. A chunk is generated once
* and its top kept; asked for from several bridge threads at once.
* and its top kept; asked for from several bridge threads at once. A tile's chunks are generated side by side on threads
* of their own, which end once the studio has asked for none for a while.
*/
final class GeneratedChunks implements ColumnTops {
private static final int CHUNK_SHIFT = 4;
private static final int BLOCKS_ACROSS = 1 << CHUNK_SHIFT;
private static final int CHUNK_MASK = BLOCKS_ACROSS - 1;
// A chunk's top is about 5 KB, and each block raised over its ground adds a height and a shared key.
// A chunk's top is about 5 KB, and each block raised over its ground adds a height and a shared key. A view with
// 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;
private static final long MOST_BYTES_KEPT = 64L * 1024 * 1024;
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.
private static final int GENERATING_THREADS = Math.max(2, Runtime.getRuntime().availableProcessors() / 2);
private static final long IDLE_THREAD_SECONDS = 30;
private static final long CANCEL_CHECK_MILLIS = 250;
private static final ThreadPoolExecutor GENERATORS = idleEndingThreads();
private final Engine engine;
private final LoadingCache<Long, ChunkTop> tops;
@@ -73,6 +92,93 @@ final class GeneratedChunks implements ColumnTops {
return chunk.columns[(worldZ & CHUNK_MASK) * BLOCKS_ACROSS + (worldX & CHUNK_MASK)];
}
// A chunk that fails to generate is left for at() to fail on, as it would without this.
@Override
public void prepare(TileGrid grid) {
List<Future<?>> generating = new ArrayList<>();
for (int chunkZ : chunksAlong(grid, grid::worldZ)) {
for (int chunkX : chunksAlong(grid, grid::worldX)) {
long key = keyOf(chunkX, chunkZ);
if (tops.getIfPresent(key) == null) {
ChunkTask chunk = new ChunkTask(() -> generateUnlessCancelled(key, grid.cancelled()), grid.step());
GENERATORS.execute(chunk);
generating.add(chunk);
}
}
}
try {
for (Future<?> chunk : generating) {
awaitUnlessCancelled(chunk, grid.cancelled());
}
} catch (CancellationException cancelled) {
generating.forEach(chunk -> chunk.cancel(false));
throw cancelled;
}
}
private void generateUnlessCancelled(long key, BooleanSupplier cancelled) {
if (!cancelled.getAsBoolean()) {
tops.get(key);
}
}
private static void awaitUnlessCancelled(Future<?> chunk, BooleanSupplier cancelled) {
while (true) {
MapTileRenderer.checkCancelled(cancelled);
try {
chunk.get(CANCEL_CHECK_MILLIS, TimeUnit.MILLISECONDS);
return;
} catch (TimeoutException stillGenerating) {
// checked for cancelling again
} catch (ExecutionException failed) {
return;
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new CancellationException("Map tile render interrupted");
}
}
}
// The distinct chunks the grid's columns fall in along one axis, in order.
private static int[] chunksAlong(TileGrid grid, IntToDoubleFunction worldAt) {
return IntStream.range(0, grid.size())
.map(cell -> (int) Math.floor(worldAt.applyAsDouble(cell)) >> CHUNK_SHIFT)
.distinct()
.toArray();
}
/**
* One chunk to generate for a tile. The chunks of finer tiles go first, then those asked for first: a tile far out
* spreads over thousands of chunks, and the ground near the camera, in finer tiles, is not kept waiting behind it.
*/
private static final class ChunkTask extends FutureTask<Void> implements Comparable<ChunkTask> {
private static final AtomicLong ASKED = new AtomicLong();
private final double blocksPerColumn;
private final long asked = ASKED.getAndIncrement();
ChunkTask(Runnable generation, double blocksPerColumn) {
super(generation, null);
this.blocksPerColumn = blocksPerColumn;
}
@Override
public int compareTo(ChunkTask other) {
int byFineness = Double.compare(blocksPerColumn, other.blocksPerColumn);
return byFineness != 0 ? byFineness : Long.compare(asked, other.asked);
}
}
private static ThreadPoolExecutor idleEndingThreads() {
ThreadPoolExecutor threads = new ThreadPoolExecutor(GENERATING_THREADS, GENERATING_THREADS, IDLE_THREAD_SECONDS, TimeUnit.SECONDS,
new PriorityBlockingQueue<>(), runnable -> {
Thread thread = new Thread(runnable, "Iris Studio Chunks");
thread.setDaemon(true);
return thread;
});
threads.allowCoreThreadTimeOut(true);
return threads;
}
private ChunkTop generate(long key) throws Exception {
int chunkX = (int) (key >> Integer.SIZE);
int chunkZ = (int) key;
@@ -88,6 +88,7 @@ public final class MapTileRenderer {
}
TileGrid grid = new TileGrid(tile.gridSize(), startX - step, startZ - step, step, cancelled);
ColumnTops tops = topsOf(source);
tops.prepare(grid);
int cells = grid.size() * grid.size();
short[] ground = new short[cells];
short[] cover = new short[cells];