Studio bridge: scene views and Minecraft assets

The bridge lists the scene views the pack's modules registered, their
entries, and encodes a scene as a palette of block states and their
positions from the anchor. Assets come from the Minecraft client jar of
the server's version, fetched from Mojang the first time the studio asks,
checked against Mojang's SHA-1 and cached; until then the route answers
503 with Retry-After.
This commit is contained in:
piexel committed 2026-11-06 01:18:52 +01:00
1 parent 13c0705d44
commit c753a1a7fe
7 files changed
+532

No files matched your search

@@ -0,0 +1,104 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.studio.assets;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.HexFormat;
/** Fetches a Minecraft client jar from Mojang, the way the launcher finds it, and keeps it only when its SHA-1 matches. */
final class ClientJarDownload {
private static final URI VERSION_MANIFEST = URI.create("https://piston-meta.mojang.com/mc/game/version_manifest_v2.json");
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(15);
private static final Duration DOWNLOAD_TIMEOUT = Duration.ofMinutes(10);
private static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(CONNECT_TIMEOUT)
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
private ClientJarDownload() {
}
static void download(String version, Path destination) throws IOException, InterruptedException {
JsonObject client = fetchJson(versionUrl(version)).getAsJsonObject("downloads").getAsJsonObject("client");
URI clientUrl = URI.create(client.get("url").getAsString());
String expectedSha1 = client.get("sha1").getAsString();
Files.createDirectories(destination.getParent());
Path partial = destination.resolveSibling(destination.getFileName() + ".part");
HttpResponse<InputStream> response = HTTP.send(HttpRequest.newBuilder(clientUrl).timeout(DOWNLOAD_TIMEOUT).build(),
HttpResponse.BodyHandlers.ofInputStream());
requireSuccess(response.statusCode(), clientUrl);
String actualSha1;
try (DigestInputStream body = new DigestInputStream(response.body(), sha1())) {
Files.copy(body, partial, StandardCopyOption.REPLACE_EXISTING);
actualSha1 = HexFormat.of().formatHex(body.getMessageDigest().digest());
}
if (!actualSha1.equalsIgnoreCase(expectedSha1)) {
Files.deleteIfExists(partial);
throw new IOException("the downloaded client jar was damaged (checksum mismatch)");
}
Files.move(partial, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
}
private static URI versionUrl(String version) throws IOException, InterruptedException {
for (JsonElement entry : fetchJson(VERSION_MANIFEST).getAsJsonArray("versions")) {
JsonObject candidate = entry.getAsJsonObject();
if (candidate.get("id").getAsString().equals(version)) {
return URI.create(candidate.get("url").getAsString());
}
}
throw new IOException("Mojang does not list Minecraft " + version);
}
private static JsonObject fetchJson(URI url) throws IOException, InterruptedException {
HttpResponse<String> response = HTTP.send(HttpRequest.newBuilder(url).timeout(CONNECT_TIMEOUT).build(),
HttpResponse.BodyHandlers.ofString());
requireSuccess(response.statusCode(), url);
return JsonParser.parseString(response.body()).getAsJsonObject();
}
private static void requireSuccess(int statusCode, URI url) throws IOException {
if (statusCode / 100 != 2) {
throw new IOException(url.getHost() + " answered HTTP " + statusCode);
}
}
private static MessageDigest sha1() {
try {
return MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException missing) {
throw new IllegalStateException(missing);
}
}
}
@@ -0,0 +1,134 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.studio.assets;
import art.arcane.iris.spi.IrisPlatforms;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* The block models, block states and textures of the Minecraft client the server runs, which the studio draws blocks
* with. The server has none of them, so the client jar is fetched from Mojang the first time the studio asks, checked
* against Mojang's checksum, and kept in Iris's cache for later runs. One per server: every world shares it.
*/
public final class MinecraftAssets {
private static final String ASSET_FOLDER = "assets/";
private static final MinecraftAssets SHARED = new MinecraftAssets();
private CompletableFuture<ZipFile> clientJar;
private MinecraftAssets() {
}
public static MinecraftAssets shared() {
return SHARED;
}
/**
* The asset file at {@code path} in the client jar, such as {@code assets/minecraft/textures/block/stone.png};
* empty when the client has no such file or the path leaves its asset folder.
*
* @throws NotReadyException while the client jar is still being fetched, or when fetching it failed; the next call
* after a failure tries again
*/
public Optional<byte[]> read(String path) throws IOException {
if (!isAssetPath(path)) {
return Optional.empty();
}
ZipFile jar = openedJar();
ZipEntry entry = jar.getEntry(path);
if (entry == null || entry.isDirectory()) {
return Optional.empty();
}
try (InputStream content = jar.getInputStream(entry)) {
return Optional.of(content.readAllBytes());
}
}
static boolean isAssetPath(String path) {
return path.startsWith(ASSET_FOLDER) && !path.contains("..") && !path.contains("\\") && !path.contains("//");
}
private synchronized ZipFile openedJar() {
if (clientJar == null) {
clientJar = CompletableFuture.supplyAsync(MinecraftAssets::fetchAndOpen, MinecraftAssets::runInBackground);
}
if (!clientJar.isDone()) {
throw new NotReadyException("Fetching the Minecraft " + minecraftVersion() + " client for its textures");
}
if (clientJar.isCompletedExceptionally()) {
String reason = clientJar.handle((jar, failure) -> readableReason(failure)).join();
clientJar = null;
throw new NotReadyException("Could not fetch the Minecraft client: " + reason);
}
return clientJar.join();
}
private static ZipFile fetchAndOpen() {
try {
Path jar = cachedJar().toPath();
if (!jar.toFile().exists()) {
ClientJarDownload.download(minecraftVersion(), jar);
}
return new ZipFile(jar.toFile());
} catch (IOException failure) {
throw new IllegalStateException(readableReason(failure), failure);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", interrupted);
}
}
private static File cachedJar() {
return new File(IrisPlatforms.get().dataFolder(), "cache/minecraft-client/" + minecraftVersion() + ".jar");
}
private static String minecraftVersion() {
return IrisPlatforms.get().minecraftVersion();
}
private static void runInBackground(Runnable task) {
Thread thread = new Thread(task, "Iris Minecraft Client Download");
thread.setDaemon(true);
thread.start();
}
private static String readableReason(Throwable failure) {
Throwable cause = failure;
while (cause.getCause() != null && (cause.getMessage() == null || cause instanceof java.util.concurrent.CompletionException)) {
cause = cause.getCause();
}
String message = cause.getMessage();
return message == null || message.isBlank() ? cause.getClass().getSimpleName() : message;
}
/** The assets cannot be read yet; the message says why, in a few words for the studio to show. */
public static final class NotReadyException extends RuntimeException {
NotReadyException(String message) {
super(message);
}
}
}
@@ -0,0 +1,94 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.studio.bridge;
import com.google.gson.Gson;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A block scene as the studio reads it, little endian:
* <pre>
* u32 header length | header, UTF-8 JSON | padding to 4 bytes
* i32 blocks[blockCount * 4]: x, y, z from the anchor, then the index of the block's state in the palette
* </pre>
* The header holds the block states the scene uses, once each, and its bounds from the anchor. Air is left out: the
* studio draws nothing there either.
*/
final class SceneEncoding {
private static final int ALIGNMENT_BYTES = 4;
private static final int INTS_PER_BLOCK = 4;
private static final Set<String> AIR = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
private SceneEncoding() {
}
static byte[] encode(GeneratedObject scene, Gson gson) {
BlockPosition anchor = scene.anchor();
Map<String, Integer> palette = new LinkedHashMap<>();
List<int[]> blocks = new ArrayList<>();
for (ObjectBlock block : scene.blocks()) {
if (isAir(block.state())) {
continue;
}
int paletteIndex = palette.computeIfAbsent(block.state().key(), ignored -> palette.size());
BlockPosition position = block.position();
blocks.add(new int[]{position.x() - anchor.x(), position.y() - anchor.y(), position.z() - anchor.z(), paletteIndex});
}
BlockBox bounds = scene.bounds();
Header header = new Header(List.copyOf(palette.keySet()), blocks.size(),
new int[]{bounds.minX() - anchor.x(), bounds.minY() - anchor.y(), bounds.minZ() - anchor.z()},
new int[]{bounds.maxX() - anchor.x(), bounds.maxY() - anchor.y(), bounds.maxZ() - anchor.z()});
byte[] headerBytes = gson.toJson(header).getBytes(StandardCharsets.UTF_8);
int blocksAt = aligned(Integer.BYTES + headerBytes.length);
ByteBuffer buffer = ByteBuffer.allocate(blocksAt + blocks.size() * INTS_PER_BLOCK * Integer.BYTES)
.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(headerBytes.length).put(headerBytes).position(blocksAt);
for (int[] block : blocks) {
for (int value : block) {
buffer.putInt(value);
}
}
return buffer.array();
}
private static boolean isAir(BlockState state) {
return AIR.contains(state.material().toString());
}
private static int aligned(int bytes) {
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
}
/** @param min the lowest corner from the anchor, inclusive; {@code max} the highest, exclusive */
private record Header(List<String> palette, int blockCount, int[] min, int[] max) {
}
}
@@ -26,6 +26,8 @@ import art.arcane.iris.core.studio.map.MapLayer;
import art.arcane.iris.core.studio.map.MapPickInspection;
import art.arcane.iris.core.studio.map.MapTile;
import art.arcane.iris.core.studio.map.MapView;
import art.arcane.iris.core.studio.assets.MinecraftAssets;
import art.arcane.iris.core.studio.scene.StudioScenes;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.render.RenderType;
import art.arcane.iris.engine.object.world.region.IrisRegion;
@@ -35,6 +37,8 @@ import com.google.gson.GsonBuilder;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.volmit.object.GeneratedObject;
import com.volmit.tooling.SceneEntry;
import java.io.IOException;
import java.io.OutputStream;
@@ -51,6 +55,8 @@ import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
@@ -71,6 +77,9 @@ import java.util.concurrent.atomic.AtomicInteger;
*/
public final class StudioBridge implements AutoCloseable {
private static final String API = "/v1/";
private static final String ASSETS_ENDPOINT = "assets/";
private static final String ASSET_RETRY_SECONDS = "2";
private static final long ASSET_CACHE_SECONDS = 86_400L;
private static final int TOKEN_BYTES = 24;
private static final int DEFAULT_TILE_SIZE = 128;
private static final int LARGEST_TILE_SIZE = 512;
@@ -184,6 +193,10 @@ public final class StudioBridge implements AutoCloseable {
private void route(HttpExchange exchange) throws IOException {
String endpoint = exchange.getRequestURI().getPath().substring(API.length());
Query query = Query.of(exchange.getRequestURI());
if (endpoint.startsWith(ASSETS_ENDPOINT)) {
sendAsset(exchange, endpoint);
return;
}
switch (endpoint) {
case "world" -> sendJson(exchange, STATUS_OK, worldInfo(get(exchange)));
case "tile" -> sendBytes(exchange, "application/octet-stream", tile(get(exchange), query));
@@ -191,6 +204,9 @@ public final class StudioBridge implements AutoCloseable {
case "picks" -> sendJson(exchange, STATUS_OK, picks(get(exchange).engine(), query));
case "regions" -> sendJson(exchange, STATUS_OK, regions(get(exchange).engine()));
case "entities" -> sendJson(exchange, STATUS_OK, entities(get(exchange)));
case "scenes" -> sendJson(exchange, STATUS_OK, StudioScenes.of(get(exchange).engine()).views());
case "scene-entries" -> sendJson(exchange, STATUS_OK, sceneEntries(get(exchange).engine(), query));
case "scene" -> sendBytes(exchange, "application/octet-stream", scene(get(exchange).engine(), query));
case "events" -> streamEvents(exchange);
case "teleport" -> teleport(exchange, query);
case "open" -> openInEditor(exchange, query);
@@ -280,6 +296,40 @@ public final class StudioBridge implements AutoCloseable {
}
}
private static List<SceneEntry> sceneEntries(Engine engine, Query query) {
try {
return StudioScenes.of(engine).entries(query.text("view"));
} catch (NoSuchElementException unknown) {
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
}
}
private byte[] scene(Engine engine, Query query) {
String key = query.text("key");
Optional<GeneratedObject> scene;
try {
scene = StudioScenes.of(engine).scene(query.text("view"), key, query.whole("variant", 0));
} catch (NoSuchElementException unknown) {
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
}
return SceneEncoding.encode(scene.orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No scene " + key)), gson);
}
// Asset paths name one file of one Minecraft version, so a studio may keep what it fetched for as long as it runs.
private static void sendAsset(HttpExchange exchange, String endpoint) throws IOException {
requireMethod(exchange, "GET");
byte[] asset;
try {
asset = MinecraftAssets.shared().read(endpoint)
.orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No asset " + endpoint));
} catch (MinecraftAssets.NotReadyException notReady) {
exchange.getResponseHeaders().set("Retry-After", ASSET_RETRY_SECONDS);
throw new RequestError(STATUS_UNAVAILABLE, notReady.getMessage());
}
exchange.getResponseHeaders().set("Cache-Control", "max-age=" + ASSET_CACHE_SECONDS + ", immutable");
sendBytes(exchange, endpoint.endsWith(".png") ? "image/png" : "application/json", asset);
}
private static List<MapLabel> regions(Engine engine) {
return engine.getComplex().preparedRegions().stream().map(region -> MapLabel.of(engine, region)).toList();
}
@@ -0,0 +1,90 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.studio.scene;
import art.arcane.iris.engine.framework.Engine;
import com.volmit.host.SceneViewRegistration;
import com.volmit.object.GeneratedObject;
import com.volmit.tooling.SceneEntry;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
/** The studio scene views the modules of an engine's pack registered, asked for that engine's world. */
public final class StudioScenes {
private final List<SceneViewRegistration> registrations;
private final PackWorld world;
private StudioScenes(List<SceneViewRegistration> registrations, PackWorld world) {
this.registrations = registrations;
this.world = world;
}
public static StudioScenes of(Engine engine) {
return new StudioScenes(engine.getData().getModules().pack().catalog().sceneViews(), engine.getGeneration().world());
}
public List<SceneViewInfo> views() {
return registrations.stream()
.map(registration -> new SceneViewInfo(registration.view().id().toString(), registration.view().label(),
registration.view().description()))
.toList();
}
/** @throws NoSuchElementException when no module registered a view {@code viewId} */
public List<SceneEntry> entries(String viewId) {
SceneViewRegistration registration = registration(viewId);
try {
return registration.view().entries(world);
} catch (RuntimeException failure) {
throw new IllegalStateException(failureOf(registration, "list its entries"), failure);
}
}
/**
* The blocks of one variant of an entry; empty when the view has no such entry or variant.
*
* @throws NoSuchElementException when no module registered a view {@code viewId}
*/
public Optional<GeneratedObject> scene(String viewId, String key, int variant) {
SceneViewRegistration registration = registration(viewId);
try {
return registration.view().scene(world, key, variant);
} catch (RuntimeException failure) {
throw new IllegalStateException(failureOf(registration, "build " + key), failure);
}
}
private SceneViewRegistration registration(String viewId) {
return registrations.stream()
.filter(registration -> registration.view().id().toString().equals(viewId))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("No module shows a scene view " + viewId));
}
private static String failureOf(SceneViewRegistration registration, String task) {
return "The " + registration + " could not " + task;
}
/** A scene view as the studio lists it. */
public record SceneViewInfo(String id, String label, String description) {
}
}
@@ -0,0 +1,17 @@
package art.arcane.iris.core.studio.assets;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class MinecraftAssetsTest {
@Test
public void onlyFilesInTheClientsAssetFolderAreServed() {
assertTrue(MinecraftAssets.isAssetPath("assets/minecraft/textures/block/stone.png"));
assertFalse(MinecraftAssets.isAssetPath("net/minecraft/client/Main.class"));
assertFalse(MinecraftAssets.isAssetPath("assets/../META-INF/MANIFEST.MF"));
assertFalse(MinecraftAssets.isAssetPath("assets//minecraft/models/block/stone.json"));
assertFalse(MinecraftAssets.isAssetPath("assets\\minecraft\\x.json"));
}
}
@@ -0,0 +1,43 @@
package art.arcane.iris.core.studio.bridge;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SceneEncodingTest {
@Test
public void blocksCountFromTheAnchorIndexOnePaletteAndLeaveAirOut() {
GeneratedObject tree = new GeneratedObject(new BlockBox(0, 0, 0, 3, 3, 3), new BlockPosition(1, 0, 1), List.of(
new ObjectBlock(new BlockPosition(1, 0, 1), BlockState.parse("minecraft:oak_log[axis=y]")),
new ObjectBlock(new BlockPosition(1, 1, 1), BlockState.parse("minecraft:oak_log[axis=y]")),
new ObjectBlock(new BlockPosition(0, 2, 1), BlockState.parse("minecraft:air")),
new ObjectBlock(new BlockPosition(1, 2, 1), BlockState.parse("minecraft:oak_leaves"))), List.of());
byte[] encoded = SceneEncoding.encode(tree, new Gson());
ByteBuffer body = ByteBuffer.wrap(encoded).order(ByteOrder.LITTLE_ENDIAN);
int headerLength = body.getInt();
JsonObject header = JsonParser.parseString(new String(encoded, 4, headerLength, StandardCharsets.UTF_8)).getAsJsonObject();
assertEquals("[\"minecraft:oak_log[axis=y]\",\"minecraft:oak_leaves\"]", header.get("palette").toString());
assertEquals(3, header.get("blockCount").getAsInt());
assertEquals("[-1,0,-1]", header.get("min").toString());
assertEquals("[2,3,2]", header.get("max").toString());
int blocksAt = (4 + headerLength + 3) / 4 * 4;
assertEquals(blocksAt + 3 * 16, encoded.length);
body.position(blocksAt + 2 * 16);
assertEquals(List.of(0, 2, 0, 1), List.of(body.getInt(), body.getInt(), body.getInt(), body.getInt()));
}
}