diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java index 7bc889a94..1ce50089d 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java @@ -21,6 +21,10 @@ package art.arcane.iris.command; import art.arcane.iris.Iris; import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.configuration.IrisSettings; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.studio.bridge.StudioBridge; +import art.arcane.iris.studio.bridge.StudioBridges; +import art.arcane.iris.studio.bridge.StudioWindow; import art.arcane.iris.studio.map.MapWindow; import art.arcane.iris.studio.map.PaletteExplorerStart; import art.arcane.iris.studio.view.GuiHost; @@ -436,6 +440,28 @@ public class CommandStudio implements DirectorExecutor { sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP)); } + @Director(description = "Open the Iris Studio app on a world", descriptionKey = "iris.director.commandstudio.director.render_world_map_external_gui", aliases = "app") + public void studioApp( + @Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true) + World world + ) { + if (!IrisToolbelt.isIrisWorld(world)) { + sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD)); + return; + } + UUID openerId = sender().isPlayer() ? player().getUniqueId() : null; + PlatformChunkGenerator generator = IrisToolbelt.access(world); + try { + StudioBridge bridge = StudioBridges.open(world.getName(), generator::getEngine, openerId); + if (!StudioWindow.show(bridge)) { + IrisLogging.info("Iris Studio link for %s: %s", world.getName(), bridge.link()); + } + sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP)); + } catch (IOException error) { + IrisLogging.warn("Could not open the studio bridge: %s", error.getMessage()); + } + } + // The map opens where the player stands when they are in that world, otherwise at the world origin. private PaletteExplorerStart mapStartIn(World world, Player opener, UUID openerId) { Location center = opener != null && opener.getWorld().equals(world) ? opener.getLocation() : null; diff --git a/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java b/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java index 78d41ba1e..efd8d9523 100644 --- a/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java +++ b/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java @@ -404,6 +404,8 @@ public class IrisSettings { public boolean disableTimeAndWeather = true; public boolean entitySpawning = true; public boolean autoStartDefaultStudio = false; + public String studioApp = ""; + public String electron = "electron"; } @Data diff --git a/core/src/main/java/art/arcane/iris/studio/StudioSVC.java b/core/src/main/java/art/arcane/iris/studio/StudioSVC.java index 149cac3fd..5d31d923b 100644 --- a/core/src/main/java/art/arcane/iris/studio/StudioSVC.java +++ b/core/src/main/java/art/arcane/iris/studio/StudioSVC.java @@ -42,6 +42,7 @@ import art.arcane.iris.pack.PackValidationRegistry; import art.arcane.iris.pack.PackValidationCache; import art.arcane.iris.pack.PackValidationResult; import art.arcane.iris.pack.PackValidator; +import art.arcane.iris.studio.bridge.StudioBridges; import art.arcane.iris.studio.workspace.IrisProject; import art.arcane.iris.studio.workspace.IrisPackageCompiler; import art.arcane.iris.studio.workspace.IrisCodeWorkspace; @@ -161,6 +162,7 @@ public class StudioSVC implements IrisService { @Override public void onDisable() { quiesceDownloadsForShutdown(); + StudioBridges.closeAll(); IrisLogging.debug("Studio Mode Active: Closing Projects"); boolean stopping = IrisToolbelt.isServerStopping(); LinkedHashSet worldNamesToDelete = new LinkedHashSet<>(TransientWorldCleanupSupport.collectTransientStudioWorldNames(IrisWorldStorage.levelRoot())); diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/ServerUsage.java b/core/src/main/java/art/arcane/iris/studio/bridge/ServerUsage.java new file mode 100644 index 000000000..fcddf4e23 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/ServerUsage.java @@ -0,0 +1,51 @@ +/* + * 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.studio.bridge; + +import java.lang.management.ManagementFactory; +import java.lang.management.OperatingSystemMXBean; + +/** + * What the server asks of its machine: CPU counted like {@code top}, where 100 is one thread kept busy, and the Java + * heap in use. + * + * @param cpuPercent the process's CPU use with 100 per busy thread, or null when the JVM cannot tell + * @param threads the threads the server's CPU has, so the studio can show the most {@code cpuPercent} can reach + * @param heapUsedBytes the Java heap in use + * @param heapMaxBytes the most the Java heap can grow to + */ +record ServerUsage(Double cpuPercent, int threads, long heapUsedBytes, long heapMaxBytes) { + private static final double PERCENT_PER_THREAD = 100D; + + static ServerUsage sample() { + Runtime runtime = Runtime.getRuntime(); + OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean(); + return of(processCpuLoad(system), runtime.availableProcessors(), runtime.totalMemory() - runtime.freeMemory(), runtime.maxMemory()); + } + + /** @param processCpuLoad the share of every core the process uses, or below zero when unknown */ + static ServerUsage of(double processCpuLoad, int threads, long heapUsedBytes, long heapMaxBytes) { + Double cpuPercent = processCpuLoad < 0D ? null : processCpuLoad * threads * PERCENT_PER_THREAD; + return new ServerUsage(cpuPercent, threads, heapUsedBytes, heapMaxBytes); + } + + private static double processCpuLoad(OperatingSystemMXBean system) { + return system instanceof com.sun.management.OperatingSystemMXBean hotspot ? hotspot.getProcessCpuLoad() : -1D; + } +} 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 new file mode 100644 index 000000000..5583ed35e --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java @@ -0,0 +1,481 @@ +/* + * 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.generation.runtime.Engine; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.studio.map.StudioHover; +import art.arcane.iris.studio.view.GuiHost; +import art.arcane.iris.studio.view.GuiMarker; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +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; + +/** + * An Iris Studio app's connection to one world: HTTP on the loopback interface, on a free port, each request carrying + * the bridge's token as {@code Authorization: Bearer }. JSON for the world, hovers and players; tiles in + * {@link StudioTile}; {@code /v1/events} streams {@link StudioEvents}. Requests run on a small pool of daemon threads, + * so a busy studio cannot hold up the server. + */ +public final class StudioBridge implements AutoCloseable { + private static final String API = "/v1/"; + private static final int TOKEN_BYTES = 24; + private static final int DEFAULT_TILE_SIZE = 128; + private static final int LARGEST_TILE_SIZE = 512; + 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; + private static final long ENTITY_WAIT_MILLIS = 3_000L; + private static final String VIEW_BIOMES = "biomes"; + private static final String VIEW_REGIONS = "regions"; + private static final String VIEW_RIVERS = "rivers"; + static final int STATUS_OK = 200; + static final int STATUS_NO_CONTENT = 204; + static final int STATUS_BAD_REQUEST = 400; + static final int STATUS_UNAUTHORIZED = 401; + static final int STATUS_NOT_FOUND = 404; + static final int STATUS_METHOD_NOT_ALLOWED = 405; + static final int STATUS_SERVER_ERROR = 500; + static final int STATUS_UNAVAILABLE = 503; + + private static final List VIEWS = List.of( + new ViewInfo(VIEW_BIOMES, "Biomes", "The biome at each spot, in the biome's colour", "WORLD", "World"), + new ViewInfo(VIEW_REGIONS, "Regions", "The region each spot belongs to", "WORLD", "World"), + new ViewInfo(VIEW_RIVERS, "Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets, grottos and cave pools from the hydrology", + "WORLD", "World")); + + private final StudioWorld world; + private final String token; + private final Gson gson = new GsonBuilder().serializeNulls().create(); + private final HttpServer server; + private final int port; + private final ExecutorService workers; + private final ScheduledExecutorService ticker; + private final StudioEvents events; + private final Runnable hotloadHook; + private final Cache droppedTiles = Caffeine.newBuilder().expireAfterWrite(DROPPED_TILE_KEPT_MINUTES, TimeUnit.MINUTES).build(); + private volatile boolean closed; + + private StudioBridge(StudioWorld world) throws IOException { + this.world = world; + this.token = newToken(); + this.events = new StudioEvents(world, gson); + this.server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + this.port = server.getAddress().getPort(); + this.workers = Executors.newFixedThreadPool(workerCount(), daemonThreads("Iris Studio Bridge")); + this.ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("Iris Studio Events")); + this.hotloadHook = events::hotloaded; + server.setExecutor(workers); + server.createContext(API, this::handle); + } + + static StudioBridge start(StudioWorld world) throws IOException { + StudioBridge bridge = new StudioBridge(world); + bridge.server.start(); + bridge.ticker.scheduleWithFixedDelay(bridge::pollEvents, 0L, StudioEvents.POLL_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); + GuiHost.get().registerHotloadHook(bridge.hotloadHook); + return bridge; + } + + public String worldName() { + return world.name(); + } + + public int port() { + return port; + } + + public String token() { + return token; + } + + /** What the studio app opens to connect. */ + public String link() { + return "iris-studio://127.0.0.1:" + port() + "/?token=" + token; + } + + @Override + public void close() { + if (closed) { + return; + } + closed = true; + GuiHost.get().unregisterHotloadHook(hotloadHook); + ticker.shutdownNow(); + events.closeAll(); + server.stop(0); + workers.shutdownNow(); + } + + private void pollEvents() { + try { + events.poll(); + } catch (Throwable error) { + IrisLogging.debug("Studio events failed: " + error); + } + } + + private void handle(HttpExchange exchange) throws IOException { + try { + allowAnyOrigin(exchange.getResponseHeaders()); + if ("OPTIONS".equals(exchange.getRequestMethod())) { + exchange.sendResponseHeaders(STATUS_NO_CONTENT, -1); + exchange.close(); + return; + } + if (!isAuthorized(exchange)) { + throw new RequestError(STATUS_UNAUTHORIZED, "Missing or wrong token"); + } + route(exchange); + } catch (RequestError error) { + sendJson(exchange, error.status, new ErrorBody(error.getMessage())); + } catch (CancellationException stopped) { + sendJson(exchange, STATUS_UNAVAILABLE, new ErrorBody("The world stopped")); + } catch (IOException clientHungUp) { + exchange.close(); + } catch (Throwable error) { + IrisLogging.reportError("Studio bridge request " + exchange.getRequestURI().getPath(), error); + sendJson(exchange, STATUS_SERVER_ERROR, new ErrorBody(String.valueOf(error.getMessage()))); + } + } + + private void route(HttpExchange exchange) throws IOException { + String endpoint = exchange.getRequestURI().getPath().substring(API.length()); + Query query = Query.of(exchange.getRequestURI()); + 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, 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 "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"); + default -> throw new RequestError(STATUS_NOT_FOUND, "No such endpoint: " + endpoint); + } + } + + private StudioWorld.Session get(HttpExchange exchange) { + requireMethod(exchange, "GET"); + return runningSession(); + } + + private StudioWorld.Session post(HttpExchange exchange) { + requireMethod(exchange, "POST"); + return runningSession(); + } + + private StudioWorld.Session runningSession() { + StudioWorld.Session session = world.session(); + if (session == null) { + throw new RequestError(STATUS_UNAVAILABLE, "The world " + world.name() + " has no running engine"); + } + return session; + } + + private static void requireMethod(HttpExchange exchange, String method) { + if (!method.equals(exchange.getRequestMethod())) { + throw new RequestError(STATUS_METHOD_NOT_ALLOWED, "Use " + method); + } + } + + private WorldInfo worldInfo(StudioWorld.Session session) { + Engine engine = session.engine(); + return new WorldInfo( + world.name(), + engine.getDimension().getLoadKey(), + engine.getDimension().getName(), + Long.toString(engine.getWorld().getRawWorldSeed()), + engine.getMinHeight(), + engine.getHeight(), + engine.getDimension().getFluidHeight(), + DEFAULT_TILE_SIZE, + session.overlay() != null, + session.tiles().hydrologyEnabled(), + VIEWS + ); + } + + private static String viewOf(Query query) { + String view = query.text("view"); + if (VIEWS.stream().noneMatch(known -> known.id().equals(view))) { + throw new RequestError(STATUS_BAD_REQUEST, "Unknown view: " + view); + } + return view; + } + + private static String previewOf(Query query) { + if (!query.has("preview")) { + return null; + } + if (!VIEW_REGIONS.equals(viewOf(query))) { + throw new RequestError(STATUS_BAD_REQUEST, "Only the region view previews a region"); + } + return query.text("preview"); + } + + private static StudioHover.Hover hover(Engine engine, Query query) { + String view = viewOf(query); + String preview = previewOf(query); + if (preview != null && engine.getData().getRegionLoader().load(preview) == null) { + throw new RequestError(STATUS_BAD_REQUEST, "This world has no region " + preview); + } + return StudioHover.sample(engine, query.number("x"), query.number("z"), preview, !VIEW_REGIONS.equals(view) || preview != null); + } + + private byte[] tile(StudioWorld.Session session, Query query) { + Engine engine = session.engine(); + String view = viewOf(query); + String preview = previewOf(query); + int size = query.whole("size", DEFAULT_TILE_SIZE); + double blocksPerPixel = query.number("scale"); + if (size < 1 || size > LARGEST_TILE_SIZE) { + throw new RequestError(STATUS_BAD_REQUEST, "A tile is 1 to " + LARGEST_TILE_SIZE + " pixels"); + } + if (!(blocksPerPixel >= SMALLEST_BLOCKS_PER_PIXEL && blocksPerPixel <= LARGEST_BLOCKS_PER_PIXEL)) { + throw new RequestError(STATUS_BAD_REQUEST, "The scale is " + SMALLEST_BLOCKS_PER_PIXEL + " to " + LARGEST_BLOCKS_PER_PIXEL + " blocks per pixel"); + } + double tileBlocks = size * blocksPerPixel; + double startX = query.whole("x", 0) * tileBlocks; + double startZ = query.whole("z", 0) * tileBlocks; + AtomicBoolean dropped = query.has("request") ? droppedFlagOf(query.text("request")) : new AtomicBoolean(); + BooleanSupplier cancelled = () -> dropped.get() || closed || engine.isClosing() || engine.isClosed(); + StudioTile tile = VIEW_RIVERS.equals(view) + ? session.tiles().rivers(startX, startZ, blocksPerPixel, size, cancelled) + : session.tiles().biomesOrRegions(view, preview, startX, startZ, blocksPerPixel, size, query.flag("heights"), cancelled); + return tile.encode(gson); + } + + 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 List entities(StudioWorld.Session session) { + if (session.overlay() == null) { + return List.of(); + } + CompletableFuture> found = new CompletableFuture<>(); + session.overlay().requestEntities(found::complete); + try { + return found.get(ENTITY_WAIT_MILLIS, TimeUnit.MILLISECONDS); + } catch (TimeoutException slow) { + throw new RequestError(STATUS_UNAVAILABLE, "The server did not list its entities in time"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new CancellationException("Bridge closing"); + } catch (ExecutionException failed) { + throw new IllegalStateException(failed.getCause()); + } + } + + private void teleport(HttpExchange exchange, Query query) throws IOException { + StudioWorld.Session session = post(exchange); + if (session.overlay() == null) { + throw new RequestError(STATUS_NOT_FOUND, "This server cannot do that from the studio"); + } + session.overlay().teleport(query.number("x"), query.number("z")); + sendJson(exchange, STATUS_OK, new MessageBody(null)); + } + + private void streamEvents(HttpExchange exchange) throws IOException { + requireMethod(exchange, "GET"); + Headers headers = exchange.getResponseHeaders(); + headers.set("Content-Type", "text/event-stream; charset=utf-8"); + headers.set("Cache-Control", "no-cache"); + exchange.sendResponseHeaders(STATUS_OK, 0); + OutputStream body = exchange.getResponseBody(); + body.flush(); + events.listen(body); + } + + private boolean isAuthorized(HttpExchange exchange) { + String header = exchange.getRequestHeaders().getFirst("Authorization"); + String expected = "Bearer " + token; + return header != null && MessageDigest.isEqual( + header.getBytes(StandardCharsets.UTF_8), expected.getBytes(StandardCharsets.UTF_8)); + } + + private static void allowAnyOrigin(Headers headers) { + headers.set("Access-Control-Allow-Origin", "*"); + headers.set("Access-Control-Allow-Headers", "Authorization"); + headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); + } + + private void sendJson(HttpExchange exchange, int status, Object body) throws IOException { + exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); + send(exchange, status, gson.toJson(body).getBytes(StandardCharsets.UTF_8)); + } + + private static void sendBytes(HttpExchange exchange, String contentType, byte[] body) throws IOException { + exchange.getResponseHeaders().set("Content-Type", contentType); + send(exchange, STATUS_OK, body); + } + + private static void send(HttpExchange exchange, int status, byte[] body) throws IOException { + try (exchange) { + exchange.sendResponseHeaders(status, body.length); + exchange.getResponseBody().write(body); + } + } + + private static String newToken() { + byte[] bytes = new byte[TOKEN_BYTES]; + new SecureRandom().nextBytes(bytes); + return HexFormat.of().formatHex(bytes); + } + + private static int workerCount() { + return Math.max(2, Runtime.getRuntime().availableProcessors() / 2); + } + + private static ThreadFactory daemonThreads(String name) { + AtomicInteger count = new AtomicInteger(); + return task -> { + Thread thread = new Thread(task, name + " " + count.incrementAndGet()); + thread.setDaemon(true); + return thread; + }; + } + + static final class RequestError extends RuntimeException { + final int status; + + RequestError(int status, String message) { + super(message); + this.status = status; + } + } + + /** A request's query parameters; a missing or malformed one is a bad request. */ + record Query(Map values) { + static Query of(URI uri) { + Map values = new HashMap<>(); + String raw = uri.getRawQuery(); + if (raw != null) { + for (String pair : raw.split("&")) { + int equals = pair.indexOf('='); + String name = equals < 0 ? pair : pair.substring(0, equals); + String value = equals < 0 ? "" : pair.substring(equals + 1); + values.put(decode(name), decode(value)); + } + } + return new Query(values); + } + + private static String decode(String text) { + return URLDecoder.decode(text, StandardCharsets.UTF_8); + } + + String text(String name) { + String value = values.get(name); + if (value == null) { + throw new RequestError(STATUS_BAD_REQUEST, "Missing " + name); + } + return value; + } + + double number(String name) { + try { + double value = Double.parseDouble(text(name)); + if (!Double.isFinite(value)) { + throw new NumberFormatException(); + } + return value; + } catch (NumberFormatException malformed) { + throw new RequestError(STATUS_BAD_REQUEST, name + " must be a number"); + } + } + + int whole(String name, int fallback) { + if (!values.containsKey(name)) { + return fallback; + } + try { + return Integer.parseInt(values.get(name)); + } catch (NumberFormatException malformed) { + throw new RequestError(STATUS_BAD_REQUEST, name + " must be a whole number"); + } + } + + boolean has(String name) { + return values.containsKey(name); + } + + boolean flag(String name) { + String value = values.get(name); + return "1".equals(value) || "true".equals(value); + } + } + + private record ErrorBody(String error) { + } + + private record MessageBody(String message) { + } + + private record PickInspection(String detail, List sections) { + } + + /** @param seed as text, as JavaScript numbers cannot hold every long */ + private record WorldInfo(String world, String dimension, String dimensionName, String seed, int minY, int height, + int fluidHeight, int tileSize, boolean hasPlayers, boolean hydrology, List views) { + } + + private record ViewInfo(String id, String label, String description, String group, String groupLabel) { + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridges.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridges.java new file mode 100644 index 000000000..72faf966c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridges.java @@ -0,0 +1,111 @@ +/* + * 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.studio.bridge; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.spi.IrisLogging; +import com.google.gson.Gson; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** + * The open bridges, one per world. Each is announced in a connection file under {@code ~/.iris/studio/bridges}, which + * a studio app on the same machine lists to connect without a pasted link; the file goes when the bridge closes. + */ +public final class StudioBridges { + private static final Path CONNECTION_FOLDER = Path.of(System.getProperty("user.home"), ".iris", "studio", "bridges"); + private static final String OWNER_ONLY = "rw-------"; + private static final Map OPEN = new ConcurrentHashMap<>(); + + private StudioBridges() { + } + + /** + * The bridge to {@code worldName}, started when it has none yet. + * + * @param engines the world's engine now, or null while it has none + * @param openerId the player the studio's teleports move, or null for the console + */ + public static synchronized StudioBridge open(String worldName, Supplier engines, UUID openerId) throws IOException { + StudioBridge open = OPEN.get(worldName); + if (open != null) { + return open; + } + StudioBridge bridge = StudioBridge.start(new StudioWorld(worldName, engines, openerId)); + OPEN.put(worldName, bridge); + announce(bridge); + return bridge; + } + + public static synchronized void closeAll() { + StudioWindow.closeAll(); + for (StudioBridge bridge : OPEN.values()) { + bridge.close(); + withdraw(bridge); + } + OPEN.clear(); + } + + private static void announce(StudioBridge bridge) { + try { + Files.createDirectories(CONNECTION_FOLDER); + Path file = connectionFile(bridge); + Connection connection = new Connection(bridge.worldName(), bridge.port(), bridge.token(), bridge.link(), + ProcessHandle.current().pid(), System.currentTimeMillis()); + Files.deleteIfExists(file); + createReadableByOwnerOnly(file); + Files.writeString(file, new Gson().toJson(connection), StandardCharsets.UTF_8); + } catch (IOException error) { + IrisLogging.warn("Could not write the studio connection file: %s", error.getMessage()); + } + } + + // The file holds the token, so other users of the machine must not read it, not even before it is written. + private static void createReadableByOwnerOnly(Path file) throws IOException { + if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) { + Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(OWNER_ONLY))); + return; + } + Files.createFile(file); + } + + private static void withdraw(StudioBridge bridge) { + try { + Files.deleteIfExists(connectionFile(bridge)); + } catch (IOException error) { + IrisLogging.debug("Could not remove the studio connection file: " + error.getMessage()); + } + } + + private static Path connectionFile(StudioBridge bridge) { + return CONNECTION_FOLDER.resolve(bridge.port() + ".json"); + } + + /** @param pid the server's process, so the studio can skip files a crashed server left */ + private record Connection(String world, int port, String token, String link, long pid, long startedMillis) { + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioEvents.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioEvents.java new file mode 100644 index 000000000..a5a33aa0f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioEvents.java @@ -0,0 +1,163 @@ +/* + * 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.studio.bridge; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.studio.view.GuiMarker; +import com.google.gson.Gson; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Server-sent events to every connected studio: {@code players} when a player moves, {@code world} when the world's + * engine changes (a hotload), {@code usage} with the server's CPU and heap every second, and a comment now and then so + * a dead connection is noticed. A studio that stops + * reading is dropped. + */ +final class StudioEvents { + private static final byte[] KEEP_ALIVE = ": alive\n\n".getBytes(StandardCharsets.UTF_8); + static final long POLL_INTERVAL_MILLIS = 250L; + private static final long KEEP_ALIVE_INTERVAL_MILLIS = 10_000L; + private static final long USAGE_INTERVAL_MILLIS = 1_000L; + + private final StudioWorld world; + private final Gson gson; + private final List listeners = new CopyOnWriteArrayList<>(); + /** Listeners not yet told the world's state. */ + private final List joining = new CopyOnWriteArrayList<>(); + private final AtomicBoolean listenerJoined = new AtomicBoolean(); + private final AtomicBoolean usageWanted = new AtomicBoolean(); + private final AtomicBoolean hotloaded = new AtomicBoolean(); + private List lastPlayers; + private Engine lastEngine; + private long lastSentMillis; + private long lastUsageMillis; + + StudioEvents(StudioWorld world, Gson gson) { + this.world = world; + this.gson = gson; + } + + void listen(OutputStream stream) { + listeners.add(stream); + joining.add(stream); + listenerJoined.set(true); + usageWanted.set(true); + } + + /** The pack was hotloaded; the engine may be the same, its streams are not. */ + void hotloaded() { + hotloaded.set(true); + } + + /** Sends what changed since the last poll; called every {@link #POLL_INTERVAL_MILLIS} from one thread. */ + void poll() { + if (listeners.isEmpty()) { + return; + } + StudioWorld.Session session = world.session(); + Engine engine = session == null ? null : session.engine(); + List joined = List.copyOf(joining); + if (engine != lastEngine || hotloaded.getAndSet(false)) { + lastEngine = engine; + send("world", new WorldChange(engine != null)); + } else { + greet(joined, engine != null); + } + joining.removeAll(joined); + List players = session == null || session.overlay() == null ? List.of() : session.overlay().players(); + if (listenerJoined.getAndSet(false) || !Objects.equals(players, lastPlayers)) { + lastPlayers = players; + send("players", players); + } + long now = System.currentTimeMillis(); + if (usageWanted.getAndSet(false) || now - lastUsageMillis >= USAGE_INTERVAL_MILLIS) { + lastUsageMillis = now; + send("usage", ServerUsage.sample()); + } + if (now - lastSentMillis > KEEP_ALIVE_INTERVAL_MILLIS) { + sendToAll(KEEP_ALIVE); + } + } + + void closeAll() { + for (OutputStream listener : listeners) { + closeQuietly(listener); + } + listeners.clear(); + joining.clear(); + } + + /** + * Tells studios that just connected what state the world is in, them alone. A studio takes its first world event as + * the state it connected to, so without one of its own it would take the next hotload for it and not redraw. + */ + private void greet(List joined, boolean running) { + if (joined.isEmpty()) { + return; + } + byte[] message = eventOf("world", new WorldChange(running)); + for (OutputStream listener : joined) { + sendTo(listener, message); + } + } + + private void send(String event, Object data) { + sendToAll(eventOf(event, data)); + } + + private byte[] eventOf(String event, Object data) { + return ("event: " + event + "\ndata: " + gson.toJson(data) + "\n\n").getBytes(StandardCharsets.UTF_8); + } + + private void sendToAll(byte[] message) { + lastSentMillis = System.currentTimeMillis(); + for (OutputStream listener : listeners) { + sendTo(listener, message); + } + } + + private void sendTo(OutputStream listener, byte[] message) { + try { + listener.write(message); + listener.flush(); + } catch (IOException gone) { + listeners.remove(listener); + joining.remove(listener); + closeQuietly(listener); + } + } + + private static void closeQuietly(OutputStream stream) { + try { + stream.close(); + } catch (IOException ignored) { + } + } + + /** @param running whether the world has an engine again; the studio redraws either way */ + private record WorldChange(boolean running) { + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioTile.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioTile.java new file mode 100644 index 000000000..81a56f753 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioTile.java @@ -0,0 +1,78 @@ +/* + * 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.List; + +/** + * A square of the map as the Iris Studio app reads it, little endian: + *
+ * u32 header length | header, UTF-8 JSON | padding to 4 bytes
+ * i16 subjects[grid²] | padding to 4 | i16 regions[grid²] | padding to 4 | f32 heights[grid²], when the header says so
+ * 
+ * The grids hold {@code (size + 2)²} cells row by row: the tile's pixels inside a ring of the neighbouring tiles' edge + * pixels, so edges and slopes continue across tiles. Subjects and regions index the header's labels. + * + * @param subjectKind BIOME, REGION or WATER: what the subjects are + * @param heights null when the tile carries none + */ +record StudioTile(int size, double blocksPerPixel, String subjectKind, List