diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveProfilePreview.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveProfilePreview.java
new file mode 100644
index 000000000..8ec4000c4
--- /dev/null
+++ b/core/src/main/java/art/arcane/iris/generation/mantle/CaveProfilePreview.java
@@ -0,0 +1,106 @@
+/*
+ * Iris is a World Generator for Minecraft Bukkit Servers
+ * Copyright (c) 2022 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.generation.mantle;
+
+import art.arcane.iris.generation.cave.IrisCaveProfile;
+import art.arcane.iris.generation.runtime.Engine;
+import art.arcane.iris.generation.runtime.IrisEngineMantle;
+import art.arcane.volmlib.util.mantle.runtime.Mantle;
+import art.arcane.volmlib.util.matter.Matter;
+import art.arcane.volmlib.util.matter.MatterCavern;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.stream.Stream;
+
+/**
+ * Carves one cave profile with the engine's own carver over a square of flat ground, in a mantle of its own so the
+ * world's is left alone, and says which blocks it opened.
+ */
+public final class CaveProfilePreview {
+ private static final int CHUNK_BLOCKS = 16;
+ private static final int CHUNK_COLUMNS = CHUNK_BLOCKS * CHUNK_BLOCKS;
+ private static final int PREFETCH_CHUNKS = 0;
+ private static final int ACCESS_CHUNKS = 1;
+
+ private CaveProfilePreview() {
+ }
+
+ /**
+ * The carved space of a square, {@code size} blocks across and a whole number of chunks, from {@code bottomY} up to
+ * and including {@code surfaceY}, both in engine-local Y (0 is the bottom of the dimension).
+ *
+ * @return one flag per block, {@code (y - bottomY) * size² + z * size + x}
+ */
+ public static boolean[] carve(Engine engine, IrisCaveProfile profile, int originX, int size, int bottomY, int surfaceY)
+ throws IOException {
+ int height = surfaceY - bottomY + 1;
+ boolean[] carved = new boolean[height * size * size];
+ Path folder = Files.createTempDirectory("iris-cave-preview");
+ Mantle mantle = IrisEngineMantle.createMantle(engine, folder, engine::getData);
+ try {
+ IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile);
+ int[] surface = new int[CHUNK_COLUMNS];
+ Arrays.fill(surface, surfaceY);
+ double[] weights = new double[CHUNK_COLUMNS];
+ Arrays.fill(weights, 1D);
+ int firstChunkX = Math.floorDiv(originX, CHUNK_BLOCKS);
+ int chunks = size / CHUNK_BLOCKS;
+ for (int chunkZ = 0; chunkZ < chunks; chunkZ++) {
+ for (int chunkX = 0; chunkX < chunks; chunkX++) {
+ int worldChunkX = firstChunkX + chunkX;
+ try (MantleWriter writer = new MantleWriter(engine.getMantle(), mantle, worldChunkX, chunkZ, PREFETCH_CHUNKS, ACCESS_CHUNKS, false)) {
+ carver.carve(writer, worldChunkX, chunkZ, weights, 0D, 0D, null, surface);
+ }
+ readCarved(mantle, carved, worldChunkX, chunkZ, chunkX, chunkZ, size, bottomY, surfaceY);
+ }
+ }
+ } finally {
+ mantle.close();
+ deleteQuietly(folder);
+ }
+ return carved;
+ }
+
+ private static void readCarved(Mantle mantle, boolean[] carved, int worldChunkX, int worldChunkZ, int chunkX, int chunkZ,
+ int size, int bottomY, int surfaceY) {
+ for (int y = bottomY; y <= surfaceY; y++) {
+ for (int z = 0; z < CHUNK_BLOCKS; z++) {
+ for (int x = 0; x < CHUNK_BLOCKS; x++) {
+ MatterCavern cavern = mantle.get(worldChunkX * CHUNK_BLOCKS + x, y, worldChunkZ * CHUNK_BLOCKS + z, MatterCavern.class);
+ if (cavern == null) {
+ continue;
+ }
+ int cell = (y - bottomY) * size * size + (chunkZ * CHUNK_BLOCKS + z) * size + chunkX * CHUNK_BLOCKS + x;
+ carved[cell] = true;
+ }
+ }
+ }
+ }
+
+ private static void deleteQuietly(Path folder) {
+ try (Stream paths = Files.walk(folder)) {
+ paths.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete());
+ } catch (IOException ignored) {
+ }
+ }
+}
diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/ProfileForm.java b/core/src/main/java/art/arcane/iris/studio/bridge/ProfileForm.java
new file mode 100644
index 000000000..9a9aa14cb
--- /dev/null
+++ b/core/src/main/java/art/arcane/iris/studio/bridge/ProfileForm.java
@@ -0,0 +1,151 @@
+/*
+ * Iris is a World Generator for Minecraft Bukkit Servers
+ * Copyright (c) 2022 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.studio.bridge;
+
+import art.arcane.iris.pack.schema.annotation.MaxNumber;
+import art.arcane.iris.pack.schema.annotation.MinNumber;
+import art.arcane.volmlib.util.documentation.Description;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * The settings of a profile object as a form: each plain number, switch and choice it has, with the value it holds, what
+ * the pack says about it and its limits. A value typed into the form is carried by a request and applied to a copy, so
+ * the pack's files stay as they are.
+ */
+final class ProfileForm {
+ private ProfileForm() {
+ }
+
+ /** @param kind boolean, integer, decimal or enum; {@code choices} lists an enum's names */
+ record Field(String name, String description, String kind, Object value, Object defaultValue, Double minimum, Double maximum,
+ List choices, boolean changed) {
+ }
+
+ record Form(String title, List fields, List notes) {
+ }
+
+ static Form of(String title, Object bean, Set hidden, Map overrides, List notes) {
+ Object fresh = newInstance(bean.getClass());
+ List fields = new ArrayList<>();
+ for (java.lang.reflect.Field field : bean.getClass().getDeclaredFields()) {
+ String kind = kindOf(field);
+ if (kind == null || hidden.contains(field.getName())) {
+ continue;
+ }
+ fields.add(fieldOf(field, kind, bean, fresh, overrides.containsKey(field.getName())));
+ }
+ return new Form(title, fields, notes);
+ }
+
+ /** A copy of the bean with the typed values set; a value that does not read as its field's type is ignored. */
+ @SuppressWarnings("unchecked")
+ static T withOverrides(T bean, Map overrides) {
+ T copy = (T) newInstance(bean.getClass());
+ for (java.lang.reflect.Field field : bean.getClass().getDeclaredFields()) {
+ if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
+ continue;
+ }
+ field.setAccessible(true);
+ try {
+ field.set(copy, field.get(bean));
+ String typed = overrides.get(field.getName());
+ if (typed != null && kindOf(field) != null) {
+ field.set(copy, parse(field.getType(), typed));
+ }
+ } catch (IllegalAccessException | IllegalArgumentException unreadable) {
+ continue;
+ }
+ }
+ return copy;
+ }
+
+ private static Field fieldOf(java.lang.reflect.Field field, String kind, Object bean, Object fresh, boolean changed) {
+ field.setAccessible(true);
+ try {
+ Description description = field.getAnnotation(Description.class);
+ MinNumber minimum = field.getAnnotation(MinNumber.class);
+ MaxNumber maximum = field.getAnnotation(MaxNumber.class);
+ List choices = field.getType().isEnum()
+ ? Arrays.stream(field.getType().getEnumConstants()).map(constant -> ((Enum>) constant).name()).toList()
+ : List.of();
+ return new Field(field.getName(), description == null ? "" : description.value(), kind, plain(field.get(bean)),
+ plain(field.get(fresh)), minimum == null ? null : minimum.value(), maximum == null ? null : maximum.value(), choices, changed);
+ } catch (IllegalAccessException unreadable) {
+ throw new IllegalStateException(unreadable);
+ }
+ }
+
+ private static Object plain(Object value) {
+ return value instanceof Enum> constant ? constant.name() : value;
+ }
+
+ private static String kindOf(java.lang.reflect.Field field) {
+ if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
+ return null;
+ }
+ Class> type = field.getType();
+ if (type == boolean.class) {
+ return "boolean";
+ }
+ if (type == int.class || type == long.class) {
+ return "integer";
+ }
+ if (type == double.class || type == float.class) {
+ return "decimal";
+ }
+ return type.isEnum() ? "enum" : null;
+ }
+
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ private static Object parse(Class> type, String text) {
+ if (type == boolean.class) {
+ return Boolean.parseBoolean(text);
+ }
+ if (type == int.class) {
+ return (int) Math.round(Double.parseDouble(text));
+ }
+ if (type == long.class) {
+ return Math.round(Double.parseDouble(text));
+ }
+ if (type == double.class) {
+ return Double.parseDouble(text);
+ }
+ if (type == float.class) {
+ return (float) Double.parseDouble(text);
+ }
+ return Enum.valueOf((Class extends Enum>) type, text);
+ }
+
+ private static Object newInstance(Class> type) {
+ try {
+ var constructor = type.getDeclaredConstructor();
+ constructor.setAccessible(true);
+ return constructor.newInstance();
+ } catch (ReflectiveOperationException noPlainConstructor) {
+ throw new IllegalStateException(type.getSimpleName() + " has no plain constructor", noPlainConstructor);
+ }
+ }
+}
diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/SceneBlocks.java b/core/src/main/java/art/arcane/iris/studio/bridge/SceneBlocks.java
new file mode 100644
index 000000000..358133b04
--- /dev/null
+++ b/core/src/main/java/art/arcane/iris/studio/bridge/SceneBlocks.java
@@ -0,0 +1,90 @@
+/*
+ * Iris is a World Generator for Minecraft Bukkit Servers
+ * Copyright (c) 2022 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.studio.bridge;
+
+import com.google.gson.Gson;
+
+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;
+
+/**
+ * Blocks collected for the studio's 3D scene, which it reads little endian:
+ *
+ * u32 header length | header, UTF-8 JSON | padding to 4 bytes
+ * i32 blocks[blockCount * 4]: x, y, z, then the index of the block's state in the palette
+ *
+ * The header holds the block states used once each and the scene's bounds. Air is left out: the studio draws nothing
+ * there either. Positions are from the scene's lowest corner.
+ */
+final class SceneBlocks {
+ private static final int ALIGNMENT_BYTES = 4;
+ private static final int INTS_PER_BLOCK = 4;
+ private static final Set AIR = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
+
+ private final Map palette = new LinkedHashMap<>();
+ private final List blocks = new ArrayList<>();
+ private final int[] min = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE};
+ private final int[] max = {Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};
+
+ void add(int x, int y, int z, String state) {
+ if (AIR.contains(state)) {
+ return;
+ }
+ int paletteIndex = palette.computeIfAbsent(state, ignored -> palette.size());
+ blocks.add(new int[]{x, y, z, paletteIndex});
+ int[] at = {x, y, z};
+ for (int axis = 0; axis < 3; axis++) {
+ min[axis] = Math.min(min[axis], at[axis]);
+ max[axis] = Math.max(max[axis], at[axis] + 1);
+ }
+ }
+
+ int count() {
+ return blocks.size();
+ }
+
+ /** The scene with its lowest corner at the origin; an empty scene is one block across. */
+ byte[] encode(Gson gson) {
+ boolean empty = blocks.isEmpty();
+ int[] origin = empty ? new int[]{0, 0, 0} : min;
+ int[] top = empty ? new int[]{1, 1, 1} : max;
+ byte[] header = gson.toJson(new Header(List.copyOf(palette.keySet()), blocks.size(),
+ new int[]{0, 0, 0}, new int[]{top[0] - origin[0], top[1] - origin[1], top[2] - origin[2]})).getBytes(StandardCharsets.UTF_8);
+ int blocksAt = aligned(Integer.BYTES + header.length);
+ ByteBuffer buffer = ByteBuffer.allocate(blocksAt + blocks.size() * INTS_PER_BLOCK * Integer.BYTES).order(ByteOrder.LITTLE_ENDIAN);
+ buffer.putInt(header.length).put(header).position(blocksAt);
+ for (int[] block : blocks) {
+ buffer.putInt(block[0] - origin[0]).putInt(block[1] - origin[1]).putInt(block[2] - origin[2]).putInt(block[3]);
+ }
+ return buffer.array();
+ }
+
+ private static int aligned(int bytes) {
+ return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
+ }
+
+ private record Header(List palette, int blockCount, int[] min, int[] max) {
+ }
+}
diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java
index 5583ed35e..e59862c23 100644
--- a/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java
+++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java
@@ -20,6 +20,7 @@ package art.arcane.iris.studio.bridge;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.spi.IrisLogging;
+import art.arcane.iris.studio.map.StudioAssets;
import art.arcane.iris.studio.map.StudioHover;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.studio.view.GuiMarker;
@@ -44,6 +45,7 @@ import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
+import java.util.NoSuchElementException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@@ -72,6 +74,10 @@ public final class StudioBridge implements AutoCloseable {
private static final double LARGEST_BLOCKS_PER_PIXEL = 4_096D;
private static final long DROPPED_TILE_KEPT_MINUTES = 10;
private static final long ENTITY_WAIT_MILLIS = 3_000L;
+ 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 String OVERRIDE_PREFIX = "set.";
private static final String VIEW_BIOMES = "biomes";
private static final String VIEW_REGIONS = "regions";
private static final String VIEW_RIVERS = "rivers";
@@ -188,6 +194,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));
@@ -196,7 +206,11 @@ public final class StudioBridge implements AutoCloseable {
case "picks" -> sendJson(exchange, STATUS_OK, new PickInspection("", List.of()));
case "regions" -> sendJson(exchange, STATUS_OK, StudioHover.previewableRegions(get(exchange).engine()));
case "entities" -> sendJson(exchange, STATUS_OK, entities(get(exchange)));
- case "scenes", "patterns", "noise-sources", "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of());
+ case "scenes" -> sendJson(exchange, STATUS_OK, profileViews());
+ case "scene-entries" -> sendJson(exchange, STATUS_OK, profileEntries(get(exchange).engine(), query));
+ case "scene" -> sendBytes(exchange, "application/octet-stream", profileScene(get(exchange).engine(), query));
+ case "profile-form" -> sendJson(exchange, STATUS_OK, profileForm(get(exchange).engine(), query));
+ case "patterns", "noise-sources", "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of());
case "events" -> streamEvents(exchange);
case "teleport" -> teleport(exchange, query);
case "open" -> throw new RequestError(STATUS_NOT_FOUND, "Opening a pack file from the studio is not available in Iris v4");
@@ -295,6 +309,63 @@ public final class StudioBridge implements AutoCloseable {
return tile.encode(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 = StudioAssets.read(endpoint).orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No asset " + endpoint));
+ } catch (StudioAssets.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 profileViews() {
+ return StudioProfiles.views().stream()
+ .map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), false, false, false, false, view.sizes(), true))
+ .toList();
+ }
+
+ private static List profileEntries(Engine engine, Query query) {
+ return profileView(query).entries(engine);
+ }
+
+ private static ProfileForm.Form profileForm(Engine engine, Query query) {
+ return profiling(() -> profileView(query).form(engine, query.text("key"), query.prefixed(OVERRIDE_PREFIX)));
+ }
+
+ private byte[] profileScene(Engine engine, Query query) {
+ StudioProfiles.ProfileView view = profileView(query);
+ int size = query.whole("size", view.sizes() == null ? 0 : view.sizes().opening());
+ if (view.sizes() != null && !view.sizes().blocksAcross().contains(size)) {
+ throw new RequestError(STATUS_BAD_REQUEST, "View " + view.id() + " builds scenes " + view.sizes().blocksAcross() + " blocks across, not " + size);
+ }
+ return profiling(() -> view.scene(engine, query.text("key"), query.whole("variant", 0), size, query.prefixed(OVERRIDE_PREFIX)).encode(gson));
+ }
+
+ private static StudioProfiles.ProfileView profileView(Query query) {
+ return profiling(() -> StudioProfiles.view(query.text("view")));
+ }
+
+ // A profile the pack does not have is the studio's to be told about, not a failure of the bridge.
+ private static T profiling(ProfileTask task) {
+ try {
+ return task.run();
+ } catch (NoSuchElementException unknown) {
+ throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
+ } catch (IOException failed) {
+ throw new IllegalStateException(failed);
+ }
+ }
+
+ @FunctionalInterface
+ private interface ProfileTask {
+ T run() throws IOException;
+ }
+
private void cancelTile(HttpExchange exchange, Query query) throws IOException {
requireMethod(exchange, "POST");
droppedFlagOf(query.text("request")).set(true);
@@ -452,6 +523,17 @@ public final class StudioBridge implements AutoCloseable {
}
}
+ /** The parameters that start with {@code prefix}, by the rest of their names. */
+ Map prefixed(String prefix) {
+ Map found = new HashMap<>();
+ values.forEach((name, value) -> {
+ if (name.startsWith(prefix)) {
+ found.put(name.substring(prefix.length()), value);
+ }
+ });
+ return found;
+ }
+
boolean has(String name) {
return values.containsKey(name);
}
@@ -468,6 +550,11 @@ public final class StudioBridge implements AutoCloseable {
private record MessageBody(String message) {
}
+ /** A profile view as the studio lists its scene views; {@code form} when its entries have a settings form. */
+ private record SceneViewInfo(String id, String label, String description, boolean editable, boolean creatable, boolean baked,
+ boolean parts, StudioProfiles.Sizes sizes, boolean form) {
+ }
+
private record PickInspection(String detail, List