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 6760d23f8..59492e137 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,10 +21,11 @@ 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.studio.map.MapWindow; -import art.arcane.iris.studio.map.PaletteExplorerStart; -import art.arcane.iris.studio.view.GuiHost; import art.arcane.iris.pack.PackDownloader; +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.pack.loading.IrisData; import art.arcane.iris.studio.workspace.IrisProject; import art.arcane.iris.studio.workspace.IrisCodeWorkspace; @@ -293,16 +294,12 @@ public class CommandStudio implements DirectorExecutor { @Director(description = "Open the noise explorer (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_noise_explorer_external_gui", aliases = {"nmap"}) public void noise( - @Param(description = "Optional pack generator to preview", descriptionKey = "iris.director.commandstudio.param.optional_pack_generator_preview", defaultValue = "null", contextual = true, contextualOverride = true) - IrisGenerator generator, - @Param(description = "The seed to preview the generator with", descriptionKey = "iris.director.commandstudio.param.seed_preview_generator_with", defaultValue = "12345") - long seed + @Param(name = "world", description = "The Iris world whose pack the noise explorer reads", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true) + World world ) { - if (noGUI()) return; - VolmitSender commandSender = sender(); - UUID openerId = commandSender.isPlayer() ? commandSender.player().getUniqueId() : null; - MapWindow.NoiseSelection selection = new MapWindow.NoiseSelection(generator == null ? null : generator.getLoadKey(), generator, seed); - withPlayerContext(opener -> openNoiseAtPlayer(commandSender, openerId, opener, selection)); + if (openStudioApp(world)) { + sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER)); + } } @Director(description = "Open the image-map studio (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_image_map_studio_external_gui", aliases = {"imap"}) @@ -310,16 +307,9 @@ public class CommandStudio implements DirectorExecutor { @Param(name = "world", description = "The Iris world whose active pack receives image-map exports", descriptionKey = "iris.director.commandstudio.param.world_open_image_map_studio", contextual = true, contextualOverride = true) World world ) { - if (noGUI()) { - return; + if (openStudioApp(world)) { + sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO)); } - if (!IrisToolbelt.isIrisWorld(world)) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD)); - return; - } - - requestMapStart(world, MapWindow::openImageMaps); - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO)); } @Director(description = "Show loot if a chest were right here", descriptionKey = "iris.director.commandstudio.director.show_loot_if_chest_were_right_here", origin = DirectorOrigin.PLAYER, sync = true) @@ -451,65 +441,38 @@ public class CommandStudio implements DirectorExecutor { @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 (noGUI()) return; + if (openStudioApp(world)) { + 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 (openStudioApp(world)) { + sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP)); + } + } + + /** Opens the app on the world, or logs its link when no app is set up; false, after telling the sender why, when it could not. */ + private boolean openStudioApp(World world) { if (!IrisToolbelt.isIrisWorld(world)) { sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD)); - return; + return false; } - - requestMapStart(world, MapWindow::openMap); - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP)); - } - - // 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; - return new PaletteExplorerStart( - IrisToolbelt.access(world).getEngine(), - world.getUID(), - openerId, - null, - center == null ? 0D : center.getX(), - center == null ? 0D : center.getZ() - ); - } - - private void requestMapStart(World world, Consumer launch) { UUID openerId = sender().isPlayer() ? player().getUniqueId() : null; - withPlayerContext(opener -> launch.accept(mapStartIn(world, opener, openerId))); - } - - private void openNoiseAtPlayer(VolmitSender commandSender, UUID openerId, Player opener, MapWindow.NoiseSelection selection) { - World world = opener == null ? null : opener.getWorld(); - PlatformChunkGenerator worldGenerator = world == null ? null : IrisToolbelt.access(world); - Engine engine = worldGenerator == null ? GuiHost.get().findActiveEngine() : worldGenerator.getEngine(); - if (engine == null) { - commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD)); - return; - } - PaletteExplorerStart start = worldGenerator == null - ? new PaletteExplorerStart(engine, null, openerId, null, 0D, 0D) - : mapStartIn(world, opener, openerId); - MapWindow.openNoise(start, selection); - commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER)); - } - - private void withPlayerContext(Consumer action) { - Player opener = sender().isPlayer() ? player() : null; - if (opener == null) { - action.accept(null); - return; - } - AtomicBoolean completed = new AtomicBoolean(); - Consumer complete = player -> { - if (completed.compareAndSet(false, true)) { - action.accept(player); + 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()); } - }; - Runnable retired = () -> complete.accept(null); - if (!J.runEntity(opener, () -> complete.accept(opener.isOnline() ? opener : null), 0, retired)) { - retired.run(); + return true; + } catch (IOException error) { + IrisLogging.warn("Could not open the studio bridge: %s", error.getMessage()); + return false; } } @@ -979,21 +942,6 @@ public class CommandStudio implements DirectorExecutor { } } - /** - * @return true if server GUIs are not enabled - */ - private boolean noGUI() { - if (!IrisSettings.get().getGui().isUseServerLaunchedGuis()) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_MUST_HAVE_SERVER_LAUNCHED_GUIS_ENABLED_SETTINGS)); - return true; - } - if (!GuiHost.isAvailable()) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_DESKTOP_UNAVAILABLE)); - return true; - } - return false; - } - /** * @return true if no studio is open or the player is not in one */ diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandStudioDesktopTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandStudioDesktopTest.java deleted file mode 100644 index 3744b6042..000000000 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandStudioDesktopTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package art.arcane.iris.command; - -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.platform.bukkit.plugin.VolmitSender; -import art.arcane.iris.studio.view.GuiHost; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class CommandStudioDesktopTest { - private IrisSettings previousSettings; - private boolean previousSuppressed; - private RecordingSender sender; - private CommandStudio command; - - @Before - public void setup() { - previousSettings = IrisSettings.settings; - previousSuppressed = GuiHost.isDesktopSuppressed(); - IrisSettings.settings = new IrisSettings(); - IrisSettings.settings.getGui().setUseServerLaunchedGuis(true); - GuiHost.suppressDesktop(true); - sender = new RecordingSender(); - command = new TestCommand(sender); - } - - @After - public void restore() { - IrisSettings.settings = previousSettings; - GuiHost.suppressDesktop(previousSuppressed); - } - - @Test - public void mapReportsMissingDisplayBeforeAccessingWorld() { - command.map(null); - - assertDisplayMessage(); - } - - @Test - public void imageMapReportsMissingDisplayInsteadOfDisabledSetting() { - command.imagemap(null); - - assertDisplayMessage(); - } - - private void assertDisplayMessage() { - assertEquals(1, sender.messages.size()); - assertTrue(sender.messages.getFirst(), sender.messages.getFirst().contains("display")); - } - - private static final class TestCommand extends CommandStudio { - private final VolmitSender sender; - - private TestCommand(VolmitSender sender) { - this.sender = sender; - } - - @Override - public VolmitSender sender() { - return sender; - } - } - - private static final class RecordingSender extends VolmitSender { - private final List messages = new ArrayList<>(); - - private RecordingSender() { - super(null); - } - - @Override - public void sendMessage(String message) { - messages.add(message); - } - } -} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/StudioMapPositionTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/StudioMapPositionTest.java deleted file mode 100644 index 4879a9495..000000000 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/StudioMapPositionTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package art.arcane.iris.command; - -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.platform.bukkit.plugin.VolmitSender; -import art.arcane.iris.platform.generation.PlatformChunkGenerator; -import art.arcane.iris.studio.map.MapWindow; -import art.arcane.iris.studio.map.PaletteExplorerStart; -import art.arcane.iris.studio.view.GuiHost; -import art.arcane.iris.world.IrisToolbelt; -import art.arcane.iris.world.task.J; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.junit.Test; -import org.mockito.MockedStatic; - -import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.when; - -public class StudioMapPositionTest { - @Test - public void mapCapturesItsStartingPositionOnThePlayerScheduler() { - IrisSettings previous = IrisSettings.settings; - IrisSettings.settings = new IrisSettings(); - IrisSettings.settings.getGui().setUseServerLaunchedGuis(true); - World world = mock(World.class); - Player player = mock(Player.class); - VolmitSender sender = mock(VolmitSender.class); - PlatformChunkGenerator generator = mock(PlatformChunkGenerator.class); - Engine engine = mock(Engine.class); - UUID playerId = UUID.randomUUID(); - UUID worldId = UUID.randomUUID(); - AtomicBoolean owned = new AtomicBoolean(); - AtomicReference task = new AtomicReference<>(); - AtomicReference start = new AtomicReference<>(); - when(world.getUID()).thenReturn(worldId); - when(player.getUniqueId()).thenReturn(playerId); - when(player.isOnline()).thenReturn(true); - when(player.getWorld()).thenAnswer(invocation -> { - assertTrue("world read must use the player scheduler", owned.get()); - return world; - }); - when(player.getLocation()).thenAnswer(invocation -> { - assertTrue("location read must use the player scheduler", owned.get()); - return new Location(world, 33.25D, 91D, -72.5D); - }); - when(sender.isPlayer()).thenReturn(true); - when(sender.player()).thenReturn(player); - when(generator.getEngine()).thenReturn(engine); - CommandStudio command = new CommandStudio() { - @Override - public VolmitSender sender() { - return sender; - } - }; - try (MockedStatic host = mockStatic(GuiHost.class); - MockedStatic toolbelt = mockStatic(IrisToolbelt.class); - MockedStatic scheduling = mockStatic(J.class); - MockedStatic windows = mockStatic(MapWindow.class)) { - host.when(GuiHost::isAvailable).thenReturn(true); - toolbelt.when(() -> IrisToolbelt.isIrisWorld(world)).thenReturn(true); - toolbelt.when(() -> IrisToolbelt.access(world)).thenReturn(generator); - scheduling.when(() -> J.runEntity(same(player), any(Runnable.class), eq(0), any(Runnable.class))) - .thenAnswer(invocation -> { - task.set(invocation.getArgument(1)); - return true; - }); - windows.when(() -> MapWindow.openMap(any(PaletteExplorerStart.class))).thenAnswer(invocation -> { - start.set(invocation.getArgument(0)); - return null; - }); - - command.map(world); - assertNull(start.get()); - owned.set(true); - task.get().run(); - - assertEquals(engine, start.get().engine()); - assertEquals(playerId, start.get().playerId()); - assertEquals(worldId, start.get().worldId()); - assertEquals(33.25D, start.get().centerX(), 0D); - assertEquals(-72.5D, start.get().centerZ(), 0D); - } finally { - IrisSettings.settings = previous; - } - } -} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedEditCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedEditCommands.java index 635067bf0..19dfb64a6 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedEditCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedEditCommands.java @@ -31,7 +31,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandSource; import art.arcane.volmlib.nativelib.terrain.NativeBlockPoint; import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeEditPlayer; -import java.awt.Desktop; +import art.arcane.iris.studio.workspace.FileOpener; import java.io.File; final class ModdedEditCommands { @@ -110,7 +110,7 @@ final class ModdedEditCommands { } private static int openJson(NativeCommandSource source, IrisRegistrant registrant) { - if (!GuiHost.isAvailable() || !Desktop.isDesktopSupported()) { + if (!GuiHost.isAvailable() || !FileOpener.isDesktopAvailable()) { IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_CANNOT_OPEN_FILES_HERE, MessageArgument.untrusted("value", ModdedGuiHost.guiUnavailableReason()))); return 0; } @@ -120,7 +120,7 @@ final class ModdedEditCommands { } File file = registrant.getLoadFile(); try { - Desktop.getDesktop().open(file); + FileOpener.open(file); } catch (Throwable e) { ModdedIrisLog.error("Iris edit failed to open {}", file, e); IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_COULD_NOT_OPEN, MessageArgument.untrusted("value", file.getName()), MessageArgument.untrusted("value2", e.getClass().getSimpleName()))); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java index ea415b719..9d35af35a 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java @@ -23,8 +23,10 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeWorldView; import art.arcane.iris.modded.ModdedIrisLog; import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.studio.map.MapWindow; -import art.arcane.iris.studio.map.PaletteExplorerStart; +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.view.GuiHost; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.StructurePackageClosure; @@ -74,7 +76,7 @@ import art.arcane.volmlib.nativelib.terrain.NativeWorld; import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeProtocolPlayer; import org.zeroturnaround.zip.ZipUtil; -import java.awt.Desktop; +import art.arcane.iris.studio.workspace.FileOpener; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -226,11 +228,7 @@ public final class ModdedStudioCommands { private static LiteralArgumentBuilder noiseTree(String name) { return NativeCommandRegistration.literal(name) - .executes(ModdedCommandTree.localized((CommandContext context) -> noise(context.getSource(), null, 12345L))) - .then(NativeCommandRegistration.argument("generator", StringArgumentType.word()).suggests(GENERATOR_KEYS) - .executes(ModdedCommandTree.localized((CommandContext context) -> noise(context.getSource(), StringArgumentType.getString(context, "generator"), 12345L))) - .then(NativeCommandRegistration.argument("seed", LongArgumentType.longArg()) - .executes(ModdedCommandTree.localized((CommandContext context) -> noise(context.getSource(), StringArgumentType.getString(context, "generator"), LongArgumentType.getLong(context, "seed")))))); + .executes(ModdedCommandTree.localized((CommandContext context) -> noise(context.getSource()))); } private static LiteralArgumentBuilder mapTree(String name) { @@ -243,85 +241,58 @@ public final class ModdedStudioCommands { .executes(ModdedCommandTree.localized((CommandContext context) -> imageMap(context.getSource()))); } - private static int noise(NativeCommandSource source, String generatorKey, long seed) { - NativeWorld level = source.world(); - Engine engine = IrisModdedCommands.engineFor(level); - if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) { - IrisModdedCommands.fail(source, guiUnavailableMessage()); - return 0; - } - if (engine != null) { - NativeProtocolPlayer player = source.player(); - ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id()); - } - Engine mapEngine = engine != null ? engine : GuiHost.get().findActiveEngine(); - if ((generatorKey == null || generatorKey.isBlank()) && mapEngine != null) { - MapWindow.openNoise(mapStart(mapEngine, source.player()), new MapWindow.NoiseSelection(null, null, seed)); - IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_ON_SERVER_DISPLAY)); - return 1; - } + private static int noise(NativeCommandSource source) { + Engine engine = IrisModdedCommands.engineFor(source.world()); if (engine == null) { IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_RUN_IRIS_STUDIO)); return 0; } - IrisGenerator generator = engine.getData().getGeneratorLoader().load(generatorKey.trim()); - if (generator == null) { - IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_UNKNOWN_GENERATOR_PACK, MessageArgument.untrusted("generatorKey", generatorKey), MessageArgument.untrusted("value", engine.getDimension().getLoadKey()))); - return 0; - } - String selectedGeneratorKey = generatorKey.trim(); - MapWindow.openNoise(mapStart(engine, source.player()), new MapWindow.NoiseSelection(selectedGeneratorKey, generator, seed)); - IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_GENERATOR_SEED, MessageArgument.untrusted("value", generatorKey.trim()), MessageArgument.untrusted("seed", seed))); - return 1; + return openStudioApp(source, engine, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_ON_SERVER_DISPLAY)); } private static int map(NativeCommandSource source) { - NativeWorld level = source.world(); - Engine engine = IrisModdedCommands.engineFor(level); + Engine engine = IrisModdedCommands.engineFor(source.world()); if (engine == null) { IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_STAND_IRIS_STUDIO)); return 0; } - if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) { - IrisModdedCommands.fail(source, guiUnavailableMessage()); - return 0; - } - NativeProtocolPlayer player = source.player(); - ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id()); - MapWindow.openMap(mapStart(engine, player)); - IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_VISION_MAP_ON_SERVER_DISPLAY, MessageArgument.untrusted("value", level.name()))); - return 1; - } - - // Modded worlds have no Bukkit world id; the map finds the engine again through the bound GUI context. - private static PaletteExplorerStart mapStart(Engine engine, NativeProtocolPlayer player) { - IrisWorld world = engine.getWorld(); - NativeWorld level = world == null ? null : world.platformWorld(); - boolean inWorld = player != null && player.connected() && level != null && player.inWorld(level); - return new PaletteExplorerStart(engine, null, player == null ? null : player.id(), null, - inWorld ? player.x() : 0D, inWorld ? player.z() : 0D); + return openStudioApp(source, engine, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_VISION_MAP_ON_SERVER_DISPLAY, MessageArgument.untrusted("value", source.world().name()))); } private static int imageMap(NativeCommandSource source) { - NativeWorld level = source.world(); - Engine engine = IrisModdedCommands.engineFor(level); + Engine engine = IrisModdedCommands.engineFor(source.world()); if (engine == null) { IrisModdedCommands.fail(source, IrisLanguage.plain( ModdedCommandMessages.MODDED_STUDIO_COMMANDS_IMAGE_MAP_REQUIRES_IRIS_DIMENSION )); return 0; } - if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) { + return openStudioApp(source, engine, IrisLanguage.plain( + ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_IMAGE_MAP_STUDIO_ON_SERVER_DISPLAY, + MessageArgument.untrusted("value", source.world().name()) + )); + } + + /** Opens the studio app on the source's world, or logs its link when no app is set up. */ + private static int openStudioApp(NativeCommandSource source, Engine engine, String openedMessage) { + if (GuiHost.isDesktopSuppressed()) { IrisModdedCommands.fail(source, guiUnavailableMessage()); return 0; } + NativeWorld level = source.world(); NativeProtocolPlayer player = source.player(); - ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id()); - MapWindow.openImageMaps(mapStart(engine, player)); - IrisModdedCommands.ok(source, IrisLanguage.plain( - ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_IMAGE_MAP_STUDIO_ON_SERVER_DISPLAY, - MessageArgument.untrusted("value", level.name()) - )); + UUID openerId = player == null ? null : player.id(); + ModdedGuiHost.bindContext(worldView(source.server(), level), engine, openerId); + try { + StudioBridge bridge = StudioBridges.open(level.name(), () -> engine, openerId); + if (!StudioWindow.show(bridge)) { + IrisLogging.info("Iris Studio link for %s: %s", level.name(), bridge.link()); + } + } catch (IOException error) { + IrisModdedCommands.fail(source, "Could not open the studio bridge: " + error.getMessage()); + return 0; + } + IrisModdedCommands.ok(source, openedMessage); return 1; } @@ -349,12 +320,12 @@ public final class ModdedStudioCommands { if (!open) { return 1; } - if (!GuiHost.isAvailable() || !Desktop.isDesktopSupported()) { + if (!GuiHost.isAvailable() || !FileOpener.isDesktopAvailable()) { IrisModdedCommands.fail(source, guiUnavailableMessage()); return 0; } try { - Desktop.getDesktop().open(workspace); + FileOpener.open(workspace); } catch (Throwable e) { ModdedIrisLog.error("Iris workspace open failed for {}", workspace, e); IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_COULD_NOT_OPEN, MessageArgument.untrusted("value", workspace.getName()), MessageArgument.untrusted("value2", e.getClass().getSimpleName()))); 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 c2825a970..b375e570b 100644 --- a/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java +++ b/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java @@ -417,6 +417,8 @@ public class IrisSettings { public boolean disableTimeAndWeather = true; public boolean entitySpawning = true; public boolean autoStartDefaultStudio = false; + public String studioApp = ""; + public String electron = "electron"; public StudioEditor getEditor() { return editor == null ? StudioEditor.VSCODE : editor; 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/pack/schema/SchemaRegistryCatalog.java b/core/src/main/java/art/arcane/iris/pack/schema/SchemaRegistryCatalog.java index 2f9992f8d..17b3a8d16 100644 --- a/core/src/main/java/art/arcane/iris/pack/schema/SchemaRegistryCatalog.java +++ b/core/src/main/java/art/arcane/iris/pack/schema/SchemaRegistryCatalog.java @@ -24,7 +24,6 @@ import art.arcane.iris.spi.IrisPlatforms; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; -import java.awt.GraphicsEnvironment; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; @@ -35,6 +34,7 @@ final class SchemaRegistryCatalog { /** Namespaced key or family/namespace prefix: "minecraft:village_plains", "minecraft:village", "nova_structures:". */ static final String VANILLA_STRUCTURE_PREFIX_PATTERN = "^[a-z0-9_.-]+:[a-z0-9_./-]*$"; private static final String MINECRAFT_NAMESPACE = "minecraft:"; + private static final String[] LOGICAL_FONT_FAMILIES = {"Dialog", "DialogInput", "Monospaced", "SansSerif", "Serif"}; private static volatile JSONArray fontTypes; private final SchemaBuilder builder; private JSONArray potionTypes; @@ -44,18 +44,13 @@ final class SchemaRegistryCatalog { this.builder = builder; } - /** - * Font families are only used for schema completion. Enumerating them touches AWT, which can fail outright on a - * headless or mod-loader JVM - a failure degrades to no completion, never to a broken schema. - */ + /** The logical font families every Java runtime has; listing the installed ones would need AWT, which headless and mod-loader JVMs may lack. */ static JSONArray fontTypes() { JSONArray cached = fontTypes; if (cached != null) { return cached; } - JSONArray built = CapabilityProbe.attempt("java.awt font families", - () -> new JSONArray(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()), - new JSONArray()); + JSONArray built = new JSONArray(LOGICAL_FONT_FAMILIES); fontTypes = built; return built; } 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 a9dc9c70d..983cd633c 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/PatternEncoding.java b/core/src/main/java/art/arcane/iris/studio/bridge/PatternEncoding.java new file mode 100644 index 000000000..393bf4e1c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/PatternEncoding.java @@ -0,0 +1,59 @@ +/* + * 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.studio.map.PalettePatterns; +import com.google.gson.Gson; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; + +/** + * A palette's pattern as the studio reads it, little endian: + *
+ * u32 header length | header, UTF-8 JSON | padding to 4 bytes | i16 picks[columns²]
+ * 
+ * The header holds the columns across, the blocks between columns, the block states the picks index, and the pick + * ({@code noBlock}) of a column the palette places nothing at. + */ +final class PatternEncoding { + private static final int ALIGNMENT_BYTES = 4; + + private PatternEncoding() { + } + + static byte[] encode(PalettePatterns.Pattern pattern, int blocksPerColumn, Gson gson) { + byte[] header = gson.toJson(new Header(pattern.columns(), blocksPerColumn, pattern.blocks(), pattern.blocks(), PalettePatterns.NO_BLOCK)) + .getBytes(StandardCharsets.UTF_8); + ByteBuffer buffer = ByteBuffer.allocate(aligned(Integer.BYTES + header.length) + pattern.picks().length * Short.BYTES) + .order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(header.length).put(header); + buffer.position(aligned(buffer.position())); + buffer.asShortBuffer().put(pattern.picks()); + return buffer.array(); + } + + private static int aligned(int bytes) { + return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES; + } + + private record Header(int columns, int blocksPerColumn, java.util.List blocks, java.util.List drawnAs, int noBlock) { + } +} 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) 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/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..92aaeb5bb --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java @@ -0,0 +1,727 @@ +/* + * 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.StudioAssets; +import art.arcane.iris.studio.map.StudioHover; +import art.arcane.iris.studio.imagemap.ImageMapPreviews; +import art.arcane.iris.studio.map.PalettePatterns; +import art.arcane.iris.studio.noise.NoiseSources; +import art.arcane.iris.studio.noise.NoiseTile; +import art.arcane.iris.studio.view.GuiHost; +import art.arcane.iris.studio.view.GuiMarker; +import art.arcane.iris.studio.view.PregenRenderSnapshot; +import art.arcane.iris.studio.view.PregeneratorJob; +import art.arcane.volmlib.util.function.NoiseProvider; +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.NoSuchElementException; +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 double SMALLEST_NOISE_BLOCKS_PER_PIXEL = 1D / 64D; + private static final int LARGEST_PATTERN_BLOCKS_PER_COLUMN = 64; + private static final int DEFAULT_IMAGE_MAP_PREVIEW_PIXELS = 768; + private static final ModuleViewInfo PALETTES_VIEW = new ModuleViewInfo("iris:terrain/palettes", "Palettes", + "The blocks each biome's palette layers place"); + 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"; + 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_UNPROCESSABLE = 422; + static final int STATUS_SERVER_ERROR = 500; + static final int STATUS_UNAVAILABLE = 503; + + private static final String VIEW_HEIGHT = "height"; + private static final String GROUP_WORLD = "WORLD"; + private static final String GROUP_BIOME_LAYERS = "BIOME_LAYERS"; + private static final String GROUP_DIAGNOSTICS = "DIAGNOSTICS"; + + private static final List VIEWS = List.of( + new ViewInfo(VIEW_BIOMES, "Biomes", "The biome at each spot, in the biome's colour", GROUP_WORLD, "World"), + new ViewInfo(VIEW_REGIONS, "Regions", "The region each spot belongs to", GROUP_WORLD, "World"), + new ViewInfo(VIEW_HEIGHT, "Height", "Terrain height, from deep water to snowy peaks", GROUP_WORLD, "World"), + new ViewInfo(VIEW_RIVERS, "Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets, grottos and cave pools from the hydrology", + GROUP_WORLD, "World"), + new ViewInfo("land-biomes", "Land biomes", "The land biome each spot would get, also where the sea is", GROUP_BIOME_LAYERS, "Biome layers"), + new ViewInfo("sea-biomes", "Sea biomes", "The sea biome each spot would get, also where the land is", GROUP_BIOME_LAYERS, "Biome layers"), + new ViewInfo("cave-biomes", "Cave biomes", "The cave biome under each spot", GROUP_BIOME_LAYERS, "Biome layers"), + new ViewInfo("object-load", "Object load", "Configuration estimate of object density and chance, not measured performance", + GROUP_DIAGNOSTICS, "Diagnostics"), + new ViewInfo("decorator-load", "Decorator load", "Configuration estimate of decorator chance and stacks, not measured performance", + GROUP_DIAGNOSTICS, "Diagnostics"), + new ViewInfo("layer-load", "Layer load", "Configuration estimate of biome layer count, not measured performance", + GROUP_DIAGNOSTICS, "Diagnostics"), + new ViewInfo("noise", "Noise", "The pack's generators and the built-in noise styles, from above or as terrain", + "GENERATORS", "Generators"), + new ViewInfo("pregen", "Pregeneration", "The chunks of the running pregeneration as they are generated, with its progress", GROUP_WORLD, "World"), + new ViewInfo("imageMaps","Image maps", "Terrain height, biomes or masks painted from a PNG, previewed over the world area they cover", + "GENERATORS", "Generators")); + + 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()); + 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)); + 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" -> 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 "scene-bake" -> sendJson(exchange, STATUS_OK, sceneBake(get(exchange).engine(), query)); + case "profile-form" -> sendJson(exchange, STATUS_OK, profileForm(get(exchange).engine(), query)); + case "noise-sources" -> sendJson(exchange, STATUS_OK, NoiseSources.of(get(exchange).engine()).list()); + case "noise-tile" -> sendBytes(exchange, "application/octet-stream", noiseTile(get(exchange).engine(), query)); + case "patterns" -> sendJson(exchange, STATUS_OK, List.of(PALETTES_VIEW)); + case "pattern-entries" -> sendJson(exchange, STATUS_OK, patternEntries(get(exchange).engine(), query)); + case "pattern" -> sendBytes(exchange, "application/octet-stream", pattern(get(exchange).engine(), query)); + case "pregen" -> sendJson(exchange, STATUS_OK, pregenStatus(exchange)); + case "pregen-map" -> sendBytes(exchange, "image/png", pregenMap(exchange)); + case "pregen-pause" -> sendJson(exchange, STATUS_OK, pregenPause(exchange)); + case "image-maps" -> sendJson(exchange, STATUS_OK, ImageMapPreviews.entries(get(exchange).engine())); + case "image-map" -> sendJson(exchange, STATUS_OK, profiling(() -> ImageMapPreviews.details(get(exchange).engine(), query.text("key")))); + case "image-map-preview" -> sendBytes(exchange, "image/png", imageMapPreview(get(exchange).engine(), query)); + case "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 static PregenStatus pregenStatus(HttpExchange exchange) { + requireMethod(exchange, "GET"); + PregeneratorJob job = PregeneratorJob.getInstance(); + if (job == null) { + return new PregenStatus(false, null); + } + return new PregenStatus(true, job.renderSnapshot()); + } + + private static byte[] pregenMap(HttpExchange exchange) { + requireMethod(exchange, "GET"); + PregeneratorJob job = PregeneratorJob.getInstance(); + if (job == null) { + throw new RequestError(STATUS_NOT_FOUND, "No pregeneration is running"); + } + return job.renderMapState().png(); + } + + private static MessageBody pregenPause(HttpExchange exchange) { + requireMethod(exchange, "POST"); + if (!PregeneratorJob.pauseResume()) { + throw new RequestError(STATUS_NOT_FOUND, "No pregeneration to pause or resume"); + } + return new MessageBody(PregeneratorJob.isPaused() ? "Paused" : "Running"); + } + + private static byte[] imageMapPreview(Engine engine, Query query) { + try { + return profiling(() -> ImageMapPreviews.preview(engine, query.text("key"), query.whole("size", DEFAULT_IMAGE_MAP_PREVIEW_PIXELS))); + } catch (IllegalArgumentException refused) { + throw new RequestError(STATUS_BAD_REQUEST, refused.getMessage()); + } + } + + private static List patternEntries(Engine engine, Query query) { + requirePalettesView(query); + return PalettePatterns.entries(engine); + } + + private byte[] pattern(Engine engine, Query query) { + requirePalettesView(query); + int columns = query.whole("size", DEFAULT_TILE_SIZE); + int blocksPerColumn = query.whole("scale", 1); + if (columns < 1 || columns > LARGEST_TILE_SIZE) { + throw new RequestError(STATUS_BAD_REQUEST, "A pattern is 1 to " + LARGEST_TILE_SIZE + " columns across"); + } + if (blocksPerColumn < 1 || blocksPerColumn > LARGEST_PATTERN_BLOCKS_PER_COLUMN) { + throw new RequestError(STATUS_BAD_REQUEST, "The scale is 1 to " + LARGEST_PATTERN_BLOCKS_PER_COLUMN + " whole blocks per column"); + } + String key = query.text("key"); + int tileBlocks = columns * blocksPerColumn; + PalettePatterns.Pattern pattern = PalettePatterns.pattern(engine, key, query.whole("depth", 0), + query.whole("x", 0) * tileBlocks, query.whole("z", 0) * tileBlocks, columns, blocksPerColumn) + .orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No palette " + key)); + return PatternEncoding.encode(pattern, blocksPerColumn, gson); + } + + private static void requirePalettesView(Query query) { + if (!PALETTES_VIEW.id().equals(query.text("view"))) { + throw new RequestError(STATUS_NOT_FOUND, "No pattern view " + query.text("view")); + } + } + + private byte[] noiseTile(Engine engine, Query 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_NOISE_BLOCKS_PER_PIXEL && blocksPerPixel <= LARGEST_BLOCKS_PER_PIXEL)) { + throw new RequestError(STATUS_BAD_REQUEST, "The scale is " + SMALLEST_NOISE_BLOCKS_PER_PIXEL + " to " + LARGEST_BLOCKS_PER_PIXEL + " blocks per pixel"); + } + NoiseSources sources = NoiseSources.of(engine); + String source = query.text("source"); + NoiseProvider noise = noiseSampler(sources, source, query.longNumber("seed")); + return NoiseTile.sample(noise, query.whole("x", 0), query.whole("z", 0), blocksPerPixel, size, sources.isSmooth(source), + () -> closed || engine.isClosing() || engine.isClosed()).encode(); + } + + // A source that cannot be sampled fails every tile alike, so it is told once to the studio rather than logged per tile. + private static NoiseProvider noiseSampler(NoiseSources sources, String source, long seed) { + try { + return sources.sampler(source, seed); + } catch (NoSuchElementException unknown) { + throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage()); + } catch (IllegalStateException unsampleable) { + throw new RequestError(STATUS_UNPROCESSABLE, unsampleable.getMessage()); + } + } + + // 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, view.isBaked(), false, view.sizes(), view.hasForm())) + .toList(); + } + + private static List profileEntries(Engine engine, Query query) { + return profileView(query).entries(engine); + } + + private static StudioObjects.BakeTiming sceneBake(Engine engine, Query query) { + StudioProfiles.ProfileView view = profileView(query); + if (!view.isBaked()) { + throw new RequestError(STATUS_BAD_REQUEST, "View " + view.id() + " is not baked"); + } + return profiling(() -> view.timeBake(engine, query.text("key"))); + } + + 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); + 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"); + } + } + + /** 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; + } + + long longNumber(String name) { + try { + return Long.parseLong(text(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) { + } + + /** 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) { + } + + /** @param snapshot null while no pregeneration runs */ + private record PregenStatus(boolean active, PregenRenderSnapshot snapshot) { + } + + /** A view the studio lists beside the scene and pattern views. */ + private record ModuleViewInfo(String id, String label, String description) { + } + + 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/StudioObjects.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioObjects.java new file mode 100644 index 000000000..902c0c65e --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioObjects.java @@ -0,0 +1,146 @@ +/* + * 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.pack.loading.IrisData; +import art.arcane.iris.structure.object.IrisObject; +import art.arcane.iris.studio.map.BakeRun; +import art.arcane.iris.studio.map.ObjectSource; +import art.arcane.iris.studio.map.PackObjectSource; +import art.arcane.iris.studio.map.ProceduralObjectSource; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.OptionalLong; + +/** The studio's views of the pack's object files and of the procedural objects its biomes and regions bake, as block scenes. */ +final class StudioObjects implements StudioProfiles.ProfileView { + static final String OBJECTS = "iris:objects"; + static final String PROCEDURAL = "iris:objects/procedural"; + private static final String BAKE_STAGE = "Bake"; + + private final String id; + private final String label; + private final String description; + private final ObjectSource source; + + private StudioObjects(String id, String label, String description, ObjectSource source) { + this.id = id; + this.label = label; + this.description = description; + this.source = source; + } + + static StudioObjects packObjects() { + return new StudioObjects(OBJECTS, "Objects", "Every object in the pack in 3D, with the blocks it is made of", new PackObjectSource()); + } + + static StudioObjects proceduralObjects() { + return new StudioObjects(PROCEDURAL, "Procedural", + "Trees, rock formations and more that Iris generates from settings, every variant in 3D", new ProceduralObjectSource()); + } + + /** One timed bake of a procedural entry, as the studio's bake meter reads it. */ + record BakeTiming(int variantCount, List stages) { + record Stage(String label, long nanos) { + } + } + + @Override + public String id() { + return id; + } + + @Override + public String label() { + return label; + } + + @Override + public String description() { + return description; + } + + @Override + public StudioProfiles.Sizes sizes() { + return null; + } + + @Override + public boolean hasForm() { + return false; + } + + @Override + public boolean isBaked() { + return source.isBaked(); + } + + @Override + public List entries(Engine engine) { + IrisData data = engine.getData(); + return source.keys(data).stream() + .sorted(Comparator.naturalOrder()) + .map(key -> new StudioProfiles.Entry(key, nameOf(key), folderOf(key), Math.max(1, source.variants(data, key).size()))) + .toList(); + } + + @Override + public ProfileForm.Form form(Engine engine, String key, Map overrides) { + throw new NoSuchElementException(id + " has no settings form"); + } + + @Override + public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) { + IrisData data = engine.getData(); + source.keys(data); + List variants = source.variants(data, key); + if (variants.isEmpty()) { + throw new NoSuchElementException("No object " + key); + } + return StudioProfiles.sceneOf(variants.get(Math.floorMod(variant, variants.size()))); + } + + @Override + public BakeTiming timeBake(Engine engine, String key) { + IrisData data = engine.getData(); + source.keys(data); + OptionalLong seed = source.seed(key); + if (seed.isEmpty()) { + throw new NoSuchElementException("No baked entry " + key); + } + BakeRun run = source.timeBake(data, key, seed.getAsLong()); + if (run == null) { + throw new NoSuchElementException("No baked entry " + key); + } + return new BakeTiming(run.variantCount(), List.of(new BakeTiming.Stage(BAKE_STAGE, run.totalNanos()))); + } + + private static String nameOf(String key) { + return key.substring(key.lastIndexOf('/') + 1); + } + + private static String folderOf(String key) { + int slash = key.lastIndexOf('/'); + return slash < 0 ? "" : key.substring(0, slash); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioProfiles.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioProfiles.java new file mode 100644 index 000000000..12a44d969 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioProfiles.java @@ -0,0 +1,461 @@ +/* + * 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.biome.IrisBiome; +import art.arcane.iris.generation.cave.IrisCaveProfile; +import art.arcane.iris.generation.decoration.formation.IrisFormation; +import art.arcane.iris.generation.decoration.formation.IrisFormationProfile; +import art.arcane.iris.generation.decoration.tree.IrisProceduralTree; +import art.arcane.iris.generation.decoration.tree.IrisTreeProfile; +import art.arcane.iris.generation.hydrology.config.IrisFluidProfile; +import art.arcane.iris.generation.mantle.CaveProfilePreview; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.structure.object.IrisObject; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.documentation.Description; +import art.arcane.volmlib.util.math.RNG; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; + +/** + * The views of the config profiles Iris v4 has: cave profiles, tree profiles, formation profiles and fluid profiles. + * Each lists what the pack has of its kind, shows its settings as a form and draws it as blocks, so the studio's scene + * viewer can show them. Values typed into a form only change the preview. + */ +final class StudioProfiles { + static final String CAVES = "caveProfiles"; + static final String TREES = "treeProfiles"; + static final String FORMATIONS = "formationProfiles"; + static final String FLUIDS = "fluidProfiles"; + + private static final List VIEWS = List.of(new CaveView(), new TreeView(), new FormationView(), new FluidView(), + StudioObjects.packObjects(), StudioObjects.proceduralObjects()); + + private StudioProfiles() { + } + + static List views() { + return VIEWS; + } + + static ProfileView view(String id) { + return VIEWS.stream().filter(view -> view.id().equals(id)).findFirst() + .orElseThrow(() -> new NoSuchElementException("No profile view " + id)); + } + + record Entry(String key, String name, String group, int variants) { + } + + /** @param blocksAcross the sizes the scene can be built at, smallest first */ + record Sizes(List blocksAcross, int opening) { + } + + interface ProfileView { + String id(); + + String label(); + + String description(); + + /** Null when each entry draws one size. */ + Sizes sizes(); + + List entries(Engine engine); + + ProfileForm.Form form(Engine engine, String key, Map overrides); + + /** Whether each entry has a settings form; the object views have none. */ + default boolean hasForm() { + return true; + } + + /** Whether the entries are baked from settings, so their bake can be timed. */ + default boolean isBaked() { + return false; + } + + /** One timed bake of the entry; only asked of baked views. */ + default StudioObjects.BakeTiming timeBake(Engine engine, String key) { + throw new UnsupportedOperationException(id() + " is not baked"); + } + + SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) throws IOException; + } + + private static String readable(String constantName) { + String lower = constantName.toLowerCase(Locale.ROOT).replace('_', ' '); + return Character.toUpperCase(lower.charAt(0)) + lower.substring(1); + } + + /** What the pack says about an enum constant, or its readable name when it says nothing. */ + private static String describe(Enum constant) { + try { + Description description = constant.getDeclaringClass().getField(constant.name()).getAnnotation(Description.class); + return description == null ? readable(constant.name()) : description.value(); + } catch (NoSuchFieldException undocumented) { + return readable(constant.name()); + } + } + + private static Entry presetEntry(String key, int variants) { + return new Entry(key, readable(key), "Presets", variants); + } + + static SceneBlocks sceneOf(IrisObject object) { + SceneBlocks scene = new SceneBlocks(); + object.getBlocks().forEach((position, state) -> scene.add(position.getBlockX(), position.getBlockY(), position.getBlockZ(), state.key())); + return scene; + } + + private static IrisObject variantOf(List variants, int variant, String what) { + if (variants.isEmpty()) { + throw new NoSuchElementException("This " + what + " bakes nothing"); + } + return variants.get(Math.floorMod(variant, variants.size())); + } + + // Caves ------------------------------------------------------------------------------------------------------ + + private static final class CaveView implements ProfileView { + private static final Sizes SIZES = new Sizes(List.of(64, 128, 256), 128); + private static final int VARIANTS = 4; + private static final int VARIANT_SPACING_BLOCKS = 4096; + private static final int SURFACE_ABOVE_SEA_BLOCKS = 48; + private static final int MAX_DEPTH_BLOCKS = 160; + private static final String DIMENSION_KEY = "dimension"; + private static final String REGION_PREFIX = "region/"; + private static final String BIOME_PREFIX = "biome/"; + private static final String[] DEPTH_BANDS = {"minecraft:yellow_concrete", "minecraft:lime_concrete", "minecraft:light_blue_concrete", + "minecraft:purple_concrete"}; + private static final int[][] NEIGHBOURS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + + @Override + public String id() { + return CAVES; + } + + @Override + public String label() { + return "Cave profiles"; + } + + @Override + public String description() { + return "The carved space of each enabled cave profile of the dimension, its regions and its biomes"; + } + + @Override + public Sizes sizes() { + return SIZES; + } + + @Override + public List entries(Engine engine) { + IrisData data = engine.getData(); + IrisDimension dimension = engine.getDimension(); + List entries = new ArrayList<>(); + if (dimension.getCaveProfile().isEnabled()) { + entries.add(new Entry(DIMENSION_KEY, dimension.getName(), "Dimension", VARIANTS)); + } + for (IrisRegion region : data.getRegionLoader().loadAll(data.getRegionLoader().getPossibleKeys())) { + if (region != null && region.getCaveProfile().isEnabled()) { + entries.add(new Entry(REGION_PREFIX + region.getLoadKey(), region.getName(), "Regions", VARIANTS)); + } + } + for (IrisBiome biome : data.getBiomeLoader().loadAll(data.getBiomeLoader().getPossibleKeys())) { + if (biome != null && biome.getCaveProfile().isEnabled()) { + entries.add(new Entry(BIOME_PREFIX + biome.getLoadKey(), biome.getName(), "Biomes", VARIANTS)); + } + } + return entries; + } + + @Override + public ProfileForm.Form form(Engine engine, String key, Map overrides) { + IrisCaveProfile profile = ProfileForm.withOverrides(profileOf(engine, key), overrides); + return ProfileForm.of("Cave profile", profile, Set.of(), overrides, List.of("Values typed here change the preview only")); + } + + @Override + public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) throws IOException { + IrisCaveProfile profile = ProfileForm.withOverrides(profileOf(engine, key), overrides); + int surfaceY = Math.min(engine.getHeight() - 1, engine.getDimension().getFluidHeight() + SURFACE_ABOVE_SEA_BLOCKS); + int bottomY = Math.max(0, Math.max((int) Math.floor(profile.getVerticalRange().getMin()), surfaceY - MAX_DEPTH_BLOCKS)); + boolean[] carved = CaveProfilePreview.carve(engine, profile, Math.floorMod(variant, VARIANTS) * VARIANT_SPACING_BLOCKS, size, bottomY, surfaceY); + return outsideOf(carved, size, surfaceY - bottomY + 1); + } + + private static IrisCaveProfile profileOf(Engine engine, String key) { + IrisData data = engine.getData(); + IrisCaveProfile profile = null; + if (DIMENSION_KEY.equals(key)) { + profile = engine.getDimension().getCaveProfile(); + } else if (key.startsWith(REGION_PREFIX)) { + IrisRegion region = data.getRegionLoader().load(key.substring(REGION_PREFIX.length())); + profile = region == null ? null : region.getCaveProfile(); + } else if (key.startsWith(BIOME_PREFIX)) { + IrisBiome biome = data.getBiomeLoader().load(key.substring(BIOME_PREFIX.length())); + profile = biome == null ? null : biome.getCaveProfile(); + } + if (profile == null) { + throw new NoSuchElementException("No cave profile " + key); + } + return profile; + } + + // Only the carved blocks on the outside of the space are kept, as the inside could not be seen. + private static SceneBlocks outsideOf(boolean[] carved, int size, int height) { + SceneBlocks scene = new SceneBlocks(); + for (int y = 0; y < height; y++) { + String band = DEPTH_BANDS[Math.min(DEPTH_BANDS.length - 1, (height - 1 - y) * DEPTH_BANDS.length / height)]; + for (int z = 0; z < size; z++) { + for (int x = 0; x < size; x++) { + if (carved[cellOf(x, y, z, size)] && touchesRock(carved, x, y, z, size, height)) { + scene.add(x, y, z, band); + } + } + } + } + return scene; + } + + private static boolean touchesRock(boolean[] carved, int x, int y, int z, int size, int height) { + for (int[] step : NEIGHBOURS) { + int nx = x + step[0]; + int ny = y + step[1]; + int nz = z + step[2]; + boolean inside = nx >= 0 && ny >= 0 && nz >= 0 && nx < size && ny < height && nz < size; + if (!inside || !carved[cellOf(nx, ny, nz, size)]) { + return true; + } + } + return false; + } + + private static int cellOf(int x, int y, int z, int size) { + return (y * size + z) * size + x; + } + } + + // Trees ------------------------------------------------------------------------------------------------------ + + private static final class TreeView implements ProfileView { + private static final Set HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "plausible", "mode", + "carvingSupport", "underwater", "profile"); + + @Override + public String id() { + return TREES; + } + + @Override + public String label() { + return "Tree profiles"; + } + + @Override + public String description() { + return "The canopy shape each tree profile gives a procedural tree"; + } + + @Override + public Sizes sizes() { + return null; + } + + @Override + public List entries(Engine engine) { + int variants = new IrisProceduralTree().getVariants(); + return Arrays.stream(IrisTreeProfile.values()).map(profile -> presetEntry(profile.name(), variants)).toList(); + } + + @Override + public ProfileForm.Form form(Engine engine, String key, Map overrides) { + return ProfileForm.of("Tree", treeOf(key, overrides), HIDDEN, overrides, + List.of(describe(profileOf(key)), "Values typed here change the preview only")); + } + + @Override + public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) { + return sceneOf(variantOf(treeOf(key, overrides).getVariantObjects(engine.getData()), variant, "tree")); + } + + private static IrisProceduralTree treeOf(String key, Map overrides) { + IrisProceduralTree tree = ProfileForm.withOverrides(new IrisProceduralTree(), overrides); + tree.setProfile(profileOf(key)); + return tree; + } + + private static IrisTreeProfile profileOf(String key) { + try { + return IrisTreeProfile.valueOf(key); + } catch (IllegalArgumentException unknown) { + throw new NoSuchElementException("No tree profile " + key); + } + } + + } + + // Formations ------------------------------------------------------------------------------------------------- + + private static final class FormationView implements ProfileView { + private static final Set HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "mode", "carvingSupport", + "surfaceSupportBuffer", "underwater", "profile"); + + @Override + public String id() { + return FORMATIONS; + } + + @Override + public String label() { + return "Formation profiles"; + } + + @Override + public String description() { + return "How each formation profile shapes a formation's width from base to top"; + } + + @Override + public Sizes sizes() { + return null; + } + + @Override + public List entries(Engine engine) { + int variants = new IrisFormation().getVariants(); + return Arrays.stream(IrisFormationProfile.values()).map(profile -> presetEntry(profile.name(), variants)).toList(); + } + + @Override + public ProfileForm.Form form(Engine engine, String key, Map overrides) { + return ProfileForm.of("Formation", formationOf(key, overrides), HIDDEN, overrides, + List.of(describe(profileOf(key)), "Values typed here change the preview only")); + } + + @Override + public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) { + return sceneOf(variantOf(formationOf(key, overrides).getVariantObjects(engine.getData()), variant, "formation")); + } + + private static IrisFormation formationOf(String key, Map overrides) { + IrisFormation formation = ProfileForm.withOverrides(new IrisFormation(), overrides); + formation.setProfile(profileOf(key)); + return formation; + } + + private static IrisFormationProfile profileOf(String key) { + try { + return IrisFormationProfile.valueOf(key); + } catch (IllegalArgumentException unknown) { + throw new NoSuchElementException("No formation profile " + key); + } + } + + } + + // Fluids ----------------------------------------------------------------------------------------------------- + + private static final class FluidView implements ProfileView { + private static final Sizes SIZES = new Sizes(List.of(16, 32, 64), 32); + private static final int VARIANTS = 4; + private static final int VARIANT_SPACING_BLOCKS = 1024; + private static final int DEPTH_BLOCKS = 3; + private static final String BASIN_BLOCK = "minecraft:stone"; + + @Override + public String id() { + return FLUIDS; + } + + @Override + public String label() { + return "Fluid profiles"; + } + + @Override + public String description() { + return "The blocks of each named fluid of the dimension's hydrology, in a pool lined with its seam"; + } + + @Override + public Sizes sizes() { + return SIZES; + } + + @Override + public List entries(Engine engine) { + return fluids(engine).stream().map(fluid -> new Entry(fluid.getName(), fluid.getName(), "Fluids", VARIANTS)).toList(); + } + + @Override + public ProfileForm.Form form(Engine engine, String key, Map overrides) { + IrisFluidProfile fluid = fluidOf(engine, key); + IrisData data = engine.getData(); + List notes = new ArrayList<>(); + notes.add("Blocks: " + String.join(", ", fluid.getPalette().getBlockData(data).stream().map(state -> state.key()).toList())); + notes.add("Seam: " + (fluid.getSeam() == null ? "none" : fluid.getSeam())); + return new ProfileForm.Form("Fluid", List.of(), notes); + } + + @Override + public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) { + IrisData data = engine.getData(); + IrisFluidProfile fluid = fluidOf(engine, key); + IrisFluidProfile seam = fluid.getSeam() == null ? null : fluidOf(engine, fluid.getSeam()); + int offset = Math.floorMod(variant, VARIANTS) * VARIANT_SPACING_BLOCKS; + RNG rng = new RNG(offset + 1L); + SceneBlocks scene = new SceneBlocks(); + for (int z = 0; z < size; z++) { + for (int x = 0; x < size; x++) { + scene.add(x, 0, z, BASIN_BLOCK); + boolean wall = x == 0 || z == 0 || x == size - 1 || z == size - 1; + boolean seamRing = seam != null && (x == 1 || z == 1 || x == size - 2 || z == size - 2); + for (int y = 1; y <= DEPTH_BLOCKS; y++) { + IrisFluidProfile filling = seamRing ? seam : fluid; + scene.add(x, y, z, wall ? BASIN_BLOCK : filling.getPalette().get(rng, x + offset, y, z, data).key()); + } + } + } + return scene; + } + + private static KList fluids(Engine engine) { + return engine.getDimension().getHydrology().getFluids(); + } + + private static IrisFluidProfile fluidOf(Engine engine, String key) { + Optional found = fluids(engine).stream().filter(fluid -> key.equals(fluid.getName())).findFirst(); + return found.orElseThrow(() -> new NoSuchElementException("No fluid profile " + key)); + } + } +} 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