Merge branch 't3/port-studio-v4' into feat/zed-editor-support

This commit is contained in:
piexel committed 2026-11-25 10:17:09 +01:00
commit 2455359550
207 files changed
+4308 -1820

No files matched your search

@@ -21,6 +21,7 @@ package art.arcane.iris;
import art.arcane.iris.api.terrain.IrisTerrainService;
import art.arcane.iris.command.CommandSVC;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.studio.app.StudioAppInstaller;
import art.arcane.iris.configuration.SettingsHotloadWatch;
import art.arcane.iris.diagnostics.LogFilterSVC;
import art.arcane.iris.diagnostics.splash.IrisSplashComposer;
@@ -976,6 +977,7 @@ public final class IrisRuntime implements IrisPluginRuntime {
return;
}
BukkitGuiHost.install();
StudioAppInstaller.installInBackground();
// super.onEnable() already registers this instance as a listener.
plugin.enablePlugin();
if (IrisStartupValidation.isRestartRequired()) {
@@ -25,6 +25,7 @@ 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.StudioLaunch;
import art.arcane.iris.studio.bridge.StudioWindow;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.workspace.IrisProject;
@@ -108,6 +109,7 @@ import java.util.function.Consumer;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.BukkitCommandMessages;
import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.volmlib.util.localization.TextKey;
import art.arcane.volmlib.util.localization.LanguageAudience;
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
@Director(name = "studio", aliases = {"std", "s"}, description = "Studio Commands", descriptionKey = "iris.director.commandstudio.director.studio_commands")
@@ -297,9 +299,7 @@ public class CommandStudio implements DirectorExecutor {
@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 (openStudioApp(world)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER));
}
openStudioApp(world, 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"})
@@ -307,9 +307,7 @@ 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 (openStudioApp(world)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO));
}
openStudioApp(world, 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)
@@ -441,9 +439,7 @@ 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 (openStudioApp(world)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
}
openStudioApp(world, 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")
@@ -451,29 +447,37 @@ 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 (openStudioApp(world)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
}
openStudioApp(world, 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) {
/** Opens the app on the world; when it can't, tells the sender why and hands over the link to connect by hand. */
private void openStudioApp(World world, TextKey openedMessage) {
if (!IrisToolbelt.isIrisWorld(world)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
return false;
return;
}
UUID openerId = sender().isPlayer() ? player().getUniqueId() : null;
PlatformChunkGenerator generator = IrisToolbelt.access(world);
StudioBridge bridge;
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());
}
return true;
bridge = StudioBridges.open(world.getName(), generator::getEngine, openerId);
} catch (IOException error) {
IrisLogging.warn("Could not open the studio bridge: %s", error.getMessage());
return false;
return;
}
StudioLaunch launch = StudioWindow.show(bridge);
if (launch.opened()) {
sender().sendMessage(IrisLanguage.text(openedMessage));
return;
}
IrisLogging.info("Iris Studio link for %s: %s", world.getName(), bridge.link());
sendStudioLink(launch, bridge.link());
}
private void sendStudioLink(StudioLaunch launch, String link) {
sender().sendMessage(C.RED + IrisLanguage.text(launch.failureMessage()));
sender().sendCopyButton(IrisLanguage.text(RuntimeUiMessages.STUDIO_LINK_COPY_BUTTON),
IrisLanguage.text(RuntimeUiMessages.STUDIO_LINK_COPY_HOVER), link);
}
@Director(description = "Profiles the performance of a dimension", descriptionKey = "iris.director.commandstudio.director.profiles_performance_dimension", origin = DirectorOrigin.PLAYER)
@@ -46,6 +46,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeEntityBehavior;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeStateMerger;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.ModdedServerAccess;
import art.arcane.iris.studio.app.StudioAppInstaller;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.generation.decoration.DecoratorPlatformHooks;
@@ -492,6 +493,7 @@ public final class ModdedEngineBootstrap {
GuiHost.Provider previousGuiHost = GuiHost.get();
ModdedGuiHost.install();
rollback.add(() -> GuiHost.set(previousGuiHost));
StudioAppInstaller.installInBackground();
ModdedDecoratorHooks decoratorHooks = new ModdedDecoratorHooks();
DecoratorPlatformHooks.Bindings previousDecoratorBindings = DecoratorPlatformHooks.bind(decoratorHooks, decoratorHooks);
@@ -26,6 +26,7 @@ import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.studio.bridge.StudioBridge;
import art.arcane.iris.studio.bridge.StudioBridges;
import art.arcane.iris.studio.bridge.StudioLaunch;
import art.arcane.iris.studio.bridge.StudioWindow;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.pack.loading.IrisData;
@@ -95,6 +96,9 @@ import java.util.regex.Pattern;
import java.util.stream.Stream;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.RuntimeUiMessages;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandText;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandText.Format;
import art.arcane.iris.modded.localization.ModdedCommandMessages;
import art.arcane.volmlib.util.localization.LanguageAudience;
import art.arcane.volmlib.util.localization.MessageArgument;
@@ -273,7 +277,7 @@ public final class ModdedStudioCommands {
));
}
/** Opens the studio app on the source's world, or logs its link when no app is set up. */
/** Opens the studio app on the source's world; when it can't, tells the source why and hands over the link to connect by hand. */
private static int openStudioApp(NativeCommandSource source, Engine engine, String openedMessage) {
if (GuiHost.isDesktopSuppressed()) {
IrisModdedCommands.fail(source, guiUnavailableMessage());
@@ -283,19 +287,35 @@ public final class ModdedStudioCommands {
NativeProtocolPlayer player = source.player();
UUID openerId = player == null ? null : player.id();
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, openerId);
StudioBridge bridge;
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());
}
bridge = StudioBridges.open(level.name(), () -> engine, openerId);
} catch (IOException error) {
IrisModdedCommands.fail(source, "Could not open the studio bridge: " + error.getMessage());
return 0;
}
StudioLaunch launch = StudioWindow.show(bridge);
if (!launch.opened()) {
IrisLogging.info("Iris Studio link for %s: %s", level.name(), bridge.link());
sendStudioLink(source, launch, bridge.link());
return 0;
}
IrisModdedCommands.ok(source, openedMessage);
return 1;
}
private static void sendStudioLink(NativeCommandSource source, StudioLaunch launch, String link) {
IrisModdedCommands.fail(source, IrisLanguage.plain(launch.failureMessage()));
if (source.player() == null) {
return;
}
NativeCommandText hover = NativeCommandText.literal(IrisLanguage.plain(RuntimeUiMessages.STUDIO_LINK_COPY_HOVER));
NativeCommandText button = NativeCommandText.literal(IrisLanguage.plain(RuntimeUiMessages.STUDIO_LINK_COPY_BUTTON))
.withStyle(Format.GREEN)
.withStyle(style -> style.copyToClipboard(link).hover(hover));
IrisModdedCommands.ok(source, button);
}
private static LiteralArgumentBuilder<NativeCommandSource> workspaceTree(String name, boolean open) {
return NativeCommandRegistration.literal(name)
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> workspace(context.getSource(), null, open)))
+65
View File
@@ -190,6 +190,63 @@ def generateNoiseNatives = tasks.register('generateNoiseNatives') {
}
}
}
// The studio app ships inside the Bukkit jar. The Electron build it runs on is 100+ MB per platform, so it stays out
// and is pinned instead: StudioAppInstaller downloads the host's archive from Electron's release at startup and
// checks it against these checksums.
File studioAppDirectory = file('studio')
List<String> electronPlatforms = ['linux-x64', 'linux-arm64', 'win32-x64', 'win32-arm64', 'darwin-x64', 'darwin-arm64']
Provider<String> electronVersion = providers.fileContents(layout.projectDirectory.file('studio/package-lock.json')).asText.map { String lock ->
(String) ((Map) ((Map) new groovy.json.JsonSlurper().parseText(lock)).packages).get('node_modules/electron').version
}
List<String> npmCommand = System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('win') ? ['cmd', '/c', 'npm'] : ['npm']
def installStudioDependencies = tasks.register('installStudioDependencies', Exec) {
inputs.files('studio/package.json', 'studio/package-lock.json')
outputs.file('studio/node_modules/.package-lock.json')
workingDir(studioAppDirectory)
commandLine(npmCommand + ['ci', '--no-audit', '--no-fund'])
}
def buildStudioApp = tasks.register('buildStudioApp', Exec) {
dependsOn(installStudioDependencies)
inputs.dir('studio/src')
inputs.files('studio/package.json', 'studio/package-lock.json', 'studio/electron.vite.config.ts', 'studio/tsconfig.json', 'studio/components.json')
outputs.dir('studio/out')
workingDir(studioAppDirectory)
commandLine(npmCommand + ['run', 'build'])
}
def bundleStudioApp = tasks.register('bundleStudioApp', Zip) {
from(buildStudioApp) {
into('out')
}
from('studio/package.json')
archiveFileName.set('studio-app.zip')
destinationDirectory.set(layout.buildDirectory.dir('generated/studio-app'))
preserveFileTimestamps = false
reproducibleFileOrder = true
}
def pinElectronRuntime = tasks.register('pinElectronRuntime') {
inputs.property('electronVersion', electronVersion)
inputs.property('platforms', electronPlatforms)
def pins = layout.buildDirectory.file('generated/studio-app-pins/studio-app.properties')
outputs.file(pins)
doLast {
String version = electronVersion.get()
String checksums = URI.create("https://github.com/electron/electron/releases/download/v${version}/SHASUMS256.txt")
.toURL().getText('UTF-8')
Map<String, String> checksumByArchive = checksums.readLines().collectEntries { String line ->
def match = line.trim() =~ /^([0-9a-f]{64}) \*?(\S+)$/
match.matches() ? [(match.group(2)): match.group(1)] : [:]
}
List<String> lines = ["electron.version=${version}".toString()]
electronPlatforms.each { String platform ->
String checksum = checksumByArchive.get("electron-v${version}-${platform}.zip".toString())
if (checksum == null) {
throw new GradleException("Electron ${version} publishes no ${platform} archive")
}
lines.add("${platform}.sha256=${checksum}".toString())
}
pins.get().asFile.setText(lines.join('\n') + '\n', 'UTF-8')
}
}
def jarJar = configurations.create('jarJar')
dependencies {
add('included', project(path: ':core', configuration: 'shadow'))
@@ -208,6 +265,12 @@ tasks.named('jar', Jar).configure {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
includeEmptyDirs = false
from(jarJar)
from(bundleStudioApp) {
into('META-INF/iris')
}
from(pinElectronRuntime) {
into('META-INF/iris')
}
from(provider { included.resolve().collect { zipTree(it) } }) {
exclude('META-INF/INDEX.LIST')
exclude('languages/**')
@@ -529,6 +592,8 @@ List<String> requiredBukkitArtifactEntries = [
'slimjar-resolutions.dat',
'META-INF/iris/native-runtime.properties',
NoiseNativeArtifacts.MANIFEST,
'META-INF/iris/studio-app.zip',
'META-INF/iris/studio-app.properties',
'META-INF/volmit/volmlib.properties',
'iris-language-source.properties',
'agent.jar',
@@ -28,6 +28,7 @@ import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
@@ -35,6 +36,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import java.util.List;
import java.util.Map;
@@ -196,6 +198,68 @@ public class CraftEngineDataProviderTest {
}
}
@Test
public void decayingCustomLeavesAreMadePersistentAndKeepTheirCustomIdentity() {
BooleanProperty persistent = BooleanProperty.create("persistent", false);
BlockDefinition definition = mock(BlockDefinition.class);
ImmutableBlockState decaying = blockState(definition, "test:leaves[persistent=false]");
ImmutableBlockState kept = blockState(definition, "test:leaves[persistent=true]");
BlockData base = mock(BlockData.class);
BlockData keptBase = mock(BlockData.class);
doReturn(persistent).when(decaying).getProperty("persistent");
doReturn(false).when(decaying).get(persistent);
when(decaying.with(persistent, true)).thenReturn(kept);
try (MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class)) {
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(base)).thenReturn(decaying);
blocks.when(() -> CraftEngineBlocks.getBukkitBlockData(kept)).thenReturn(keptBase);
IrisCustomData result = (IrisCustomData) new CraftEngineDataProvider()
.withoutDecay(IrisCustomData.of(base, new Identifier("craftengine", "test/leaves[persistent=false]")));
assertSame(keptBase, result.getBase());
assertEquals(new Identifier("test", "leaves[persistent=true]"), result.getCustom());
}
}
@Test
public void persistentOrDecaylessCustomBlocksAreKeptAsTheyAre() {
BooleanProperty persistent = BooleanProperty.create("persistent", false);
BlockDefinition definition = mock(BlockDefinition.class);
ImmutableBlockState alreadyPersistent = blockState(definition, "test:leaves[persistent=true]");
ImmutableBlockState withoutProperty = blockState(definition, "test:log");
BlockData persistentData = mock(BlockData.class);
BlockData logData = mock(BlockData.class);
BlockData vanilla = mock(BlockData.class);
doReturn(persistent).when(alreadyPersistent).getProperty("persistent");
doReturn(true).when(alreadyPersistent).get(persistent);
try (MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class)) {
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(persistentData)).thenReturn(alreadyPersistent);
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(logData)).thenReturn(withoutProperty);
CraftEngineDataProvider provider = new CraftEngineDataProvider();
assertSame(persistentData, provider.withoutDecay(persistentData));
assertSame(logData, provider.withoutDecay(logData));
assertSame(vanilla, provider.withoutDecay(vanilla));
}
}
@Test
public void customBlocksCarryTheTagsTheirSettingsListEvenWhenWrapped() {
ImmutableBlockState state = mock(ImmutableBlockState.class, Mockito.RETURNS_DEEP_STUBS);
BlockData base = mock(BlockData.class);
BlockData vanilla = mock(BlockData.class);
when(state.settings().tags()).thenReturn(Set.of(Key.of("minecraft:logs")));
try (MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class)) {
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(base)).thenReturn(state);
CraftEngineDataProvider provider = new CraftEngineDataProvider();
BlockData wrapped = IrisCustomData.of(base, new Identifier("craftengine", "test/log"));
assertTrue(provider.hasBlockTag(wrapped, NamespacedKey.minecraft("logs")));
assertFalse(provider.hasBlockTag(wrapped, NamespacedKey.minecraft("leaves")));
assertFalse(provider.hasBlockTag(vanilla, NamespacedKey.minecraft("logs")));
}
}
@Test
public void unknownOrInvalidBlockPropertiesFailBeforeNativeConversion() {
Identifier id = new Identifier("test", "lamp");
@@ -417,6 +417,7 @@ public class IrisSettings {
public boolean disableTimeAndWeather = true;
public boolean entitySpawning = true;
public boolean autoStartDefaultStudio = false;
public boolean downloadApp = true;
public String studioApp = "";
public String electron = "electron";
@@ -84,6 +84,14 @@ public class B {
return state != null && state.isTreeBlock();
}
public static boolean isLog(NativeBlockState state) {
return state != null && state.isLog();
}
public static boolean isLeaves(NativeBlockState state) {
return state != null && state.isLeaves();
}
public static boolean isFoliagePlantable(NativeBlockState state) {
return state != null && state.isFoliagePlantable();
}
@@ -62,6 +62,9 @@ public class IrisNoiseGenerator {
private static final long GENERATOR_SEED_SALT = 33_955_677L;
private static final int MINIMUM_FRACTURE_DEPTH = 4;
private static final int MAXIMUM_FRACTURE_NODES = 32;
// Fracture axes as CNG.reseededForAxis numbers them for a 2D read: x is axis 0, z is axis 1.
static final int X_AXIS = 0;
static final int Z_AXIS = 1;
private static final ThreadLocal<FractureSamples> FRACTURE_SAMPLES = ThreadLocal.withInitial(FractureSamples::new);
@Getter(AccessLevel.NONE)
@@ -144,6 +147,14 @@ public class IrisNoiseGenerator {
}
double getNoise(long superSeed, double xv, double zv, IrisData data, Engine engine) {
return getNoiseForAxis(superSeed, xv, zv, data, engine, X_AXIS);
}
/**
* This layer read as the fracture of one axis. Each axis samples this layer's generator reseeded for that axis at
* the same coordinates, so the x and z warps are uncorrelated instead of mirror images of each other.
*/
private double getNoiseForAxis(long superSeed, double xv, double zv, IrisData data, Engine engine, int axis) {
if (!enabled) {
return offsetY;
}
@@ -154,7 +165,7 @@ public class IrisNoiseGenerator {
samples.active = true;
try {
if (samples.prepare(this, superSeed, data, engine)) {
return samples.sample(xv, zv);
return samples.sample(xv, zv, axis);
}
} finally {
samples.clear();
@@ -169,13 +180,13 @@ public class IrisNoiseGenerator {
for (IrisNoiseGenerator i : fracture) {
if (i.isEnabled()) {
double fractureOffset = i.getOpacity() / 2D;
x += i.getNoise(superSeed + seed + g, xv, zv, data, engine) - fractureOffset;
z += i.getNoise(superSeed + seed + g, zv, xv, data, engine) - fractureOffset;
x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, X_AXIS) - fractureOffset;
z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, Z_AXIS) - fractureOffset;
}
g += 819;
}
return sample(getGenerator(superSeed, data, engine), x, z);
return sample(getGenerator(superSeed, data, engine).reseededForAxis(axis), x, z);
}
boolean supportsBatch() {
@@ -200,6 +211,10 @@ public class IrisNoiseGenerator {
}
NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine) {
return compileProgram(superSeed, data, engine, false);
}
private NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine, boolean readAsFracture) {
if (!enabled) {
return NoiseLayerProgram.disabled(this);
}
@@ -215,13 +230,14 @@ public class IrisNoiseGenerator {
int compiled = 0;
for (IrisNoiseGenerator child : fracture) {
if (child.isEnabled()) {
children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine);
children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine, true);
offsets[compiled++] = child.getOpacity() / 2D;
}
salt += 819;
}
CNG generator = Objects.requireNonNull(getGenerator(superSeed, data, engine), "Noise layer generator");
return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), children, offsets);
NoiseProgram zAxisProgram = readAsFracture ? NoiseProgram.compile2D(generator.reseededForAxis(Z_AXIS)) : null;
return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), zAxisProgram, children, offsets);
}
public KList<IrisNoiseGenerator> getAllComposites() {
@@ -357,20 +373,26 @@ public class IrisNoiseGenerator {
return false;
}
private double sample(double x, double z) {
/**
* Both axes of a fracture node read the same warped coordinates, since a reseeded generator shares the
* node's own fracture, so each level samples its generator once per axis.
*/
private double sample(double x, double z, int rootAxis) {
int leaf = size - 1;
double forward = nodes[leaf].sample(generators[leaf], x, z);
double reverse = nodes[leaf].sample(generators[leaf], z, x);
for (int index = leaf - 1; index >= 0; index--) {
double offset = nodes[index + 1].opacity / 2D;
double forwardX = x + (forward - offset);
double forwardZ = z + (reverse - offset);
forward = nodes[index].sample(generators[index], forwardX, forwardZ);
if (index > 0) {
reverse = nodes[index].sample(generators[index], forwardZ, forwardX);
}
if (leaf == 0) {
return nodes[0].sample(generators[0].reseededForAxis(rootAxis), x, z);
}
return forward;
double warpX = nodes[leaf].sample(generators[leaf], x, z);
double warpZ = nodes[leaf].sample(generators[leaf].reseededForAxis(Z_AXIS), x, z);
for (int index = leaf - 1; index > 0; index--) {
double offset = nodes[index + 1].opacity / 2D;
double warpedX = x + (warpX - offset);
double warpedZ = z + (warpZ - offset);
warpX = nodes[index].sample(generators[index], warpedX, warpedZ);
warpZ = nodes[index].sample(generators[index].reseededForAxis(Z_AXIS), warpedX, warpedZ);
}
double offset = nodes[1].opacity / 2D;
return nodes[0].sample(generators[0].reseededForAxis(rootAxis), x + (warpX - offset), z + (warpZ - offset));
}
private void clear() {
@@ -9,6 +9,7 @@ public final class NoiseLayerProgram {
private final boolean enabled;
private final double offsetY;
private final NoiseProgram program;
private final NoiseProgram zAxisProgram;
private final double zoom;
private final double opacity;
private final double offsetX;
@@ -21,10 +22,12 @@ public final class NoiseLayerProgram {
private final NoiseLayerProgram[] children;
private final double[] childOffsets;
private NoiseLayerProgram(IrisNoiseGenerator layer, NoiseProgram program, NoiseLayerProgram[] children, double[] childOffsets) {
private NoiseLayerProgram(IrisNoiseGenerator layer, NoiseProgram program, NoiseProgram zAxisProgram,
NoiseLayerProgram[] children, double[] childOffsets) {
this.enabled = program != null;
this.offsetY = layer.getOffsetY();
this.program = program;
this.zAxisProgram = zAxisProgram;
this.zoom = layer.getZoom();
this.opacity = layer.getOpacity();
this.offsetX = layer.getOffsetX();
@@ -39,11 +42,16 @@ public final class NoiseLayerProgram {
}
static NoiseLayerProgram disabled(IrisNoiseGenerator layer) {
return new NoiseLayerProgram(layer, null, new NoiseLayerProgram[0], new double[0]);
return new NoiseLayerProgram(layer, null, null, new NoiseLayerProgram[0], new double[0]);
}
static NoiseLayerProgram of(IrisNoiseGenerator layer, NoiseProgram program, NoiseLayerProgram[] children, double[] childOffsets) {
return new NoiseLayerProgram(layer, program, children, childOffsets);
/**
* zAxisProgram is the layer's generator reseeded for the z axis; only a layer read as a fracture needs it, and the
* root layer passes null.
*/
static NoiseLayerProgram of(IrisNoiseGenerator layer, NoiseProgram program, NoiseProgram zAxisProgram,
NoiseLayerProgram[] children, double[] childOffsets) {
return new NoiseLayerProgram(layer, program, zAxisProgram, children, childOffsets);
}
public void evaluate(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) {
@@ -53,143 +61,110 @@ public final class NoiseLayerProgram {
}
int mark = scratch.mark();
try {
fill(scratch, xs, zs, count, out);
double[] sampleX = scratch.buffer(count);
double[] sampleZ = scratch.buffer(count);
warpedSampleCoordinates(scratch, xs, zs, count, sampleX, sampleZ);
program.fill2D(scratch.noise(), sampleX, sampleZ, count, out);
applyPost(out, count);
} finally {
scratch.reset(mark);
}
}
private void fill(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) {
double[] sampleX = scratch.buffer(count);
double[] sampleZ = scratch.buffer(count);
if (children.length == 0) {
for (int index = 0; index < count; index++) {
sampleX[index] = (xs[index] / zoom) + offsetX;
sampleZ[index] = (zs[index] / zoom) + offsetZ;
}
} else {
System.arraycopy(xs, 0, sampleX, 0, count);
System.arraycopy(zs, 0, sampleZ, 0, count);
double[] forward = scratch.buffer(count);
double[] reverse = scratch.buffer(count);
for (int child = 0; child < children.length; child++) {
children[child].evaluatePair(scratch, xs, zs, count, forward, reverse);
double offset = childOffsets[child];
for (int index = 0; index < count; index++) {
sampleX[index] += forward[index] - offset;
sampleZ[index] += reverse[index] - offset;
}
}
for (int index = 0; index < count; index++) {
sampleX[index] = (sampleX[index] / zoom) + offsetX;
sampleZ[index] = (sampleZ[index] / zoom) + offsetZ;
}
}
program.fill2D(scratch.noise(), sampleX, sampleZ, count, out);
for (int index = 0; index < count; index++) {
out[index] = post(out[index]);
}
}
void evaluatePair(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] forward, double[] reverse) {
/** Fills this layer read as a fracture: the x warp from its generator, the z warp from its z-axis generator. */
void evaluateAxes(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] xWarp, double[] zWarp) {
if (!enabled) {
Arrays.fill(forward, 0, count, offsetY);
Arrays.fill(reverse, 0, count, offsetY);
Arrays.fill(xWarp, 0, count, offsetY);
Arrays.fill(zWarp, 0, count, offsetY);
return;
}
int mark = scratch.mark();
try {
fillPair(scratch, xs, zs, count, forward, reverse);
double[] sampleX = scratch.buffer(count);
double[] sampleZ = scratch.buffer(count);
warpedSampleCoordinates(scratch, xs, zs, count, sampleX, sampleZ);
program.fill2D(scratch.noise(), sampleX, sampleZ, count, xWarp);
zAxisProgram.fill2D(scratch.noise(), sampleX, sampleZ, count, zWarp);
applyPost(xWarp, count);
applyPost(zWarp, count);
} finally {
scratch.reset(mark);
}
}
private void fillPair(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] forward, double[] reverse) {
int pairs = count * 2;
double[] sampleX = scratch.buffer(pairs);
double[] sampleZ = scratch.buffer(pairs);
private void warpedSampleCoordinates(TerrainBatchScratch scratch, double[] xs, double[] zs, int count,
double[] sampleX, double[] sampleZ) {
System.arraycopy(xs, 0, sampleX, 0, count);
System.arraycopy(zs, 0, sampleZ, 0, count);
System.arraycopy(zs, 0, sampleX, count, count);
System.arraycopy(xs, 0, sampleZ, count, count);
if (children.length > 0) {
double[] childForward = scratch.buffer(count);
double[] childReverse = scratch.buffer(count);
double[] childX = scratch.buffer(count);
double[] childZ = scratch.buffer(count);
for (int child = 0; child < children.length; child++) {
children[child].evaluatePair(scratch, xs, zs, count, childForward, childReverse);
children[child].evaluateAxes(scratch, xs, zs, count, childX, childZ);
double offset = childOffsets[child];
for (int index = 0; index < count; index++) {
sampleX[index] += childForward[index] - offset;
sampleZ[index] += childReverse[index] - offset;
sampleX[count + index] += childReverse[index] - offset;
sampleZ[count + index] += childForward[index] - offset;
sampleX[index] += childX[index] - offset;
sampleZ[index] += childZ[index] - offset;
}
}
}
for (int index = 0; index < pairs; index++) {
for (int index = 0; index < count; index++) {
sampleX[index] = (sampleX[index] / zoom) + offsetX;
sampleZ[index] = (sampleZ[index] / zoom) + offsetZ;
}
double[] values = scratch.buffer(pairs);
program.fill2D(scratch.noise(), sampleX, sampleZ, pairs, values);
for (int index = 0; index < count; index++) {
forward[index] = post(values[index]);
reverse[index] = post(values[count + index]);
}
}
public double sample(TerrainBatchScratch scratch, double x, double z) {
if (!enabled) {
return offsetY;
}
double sampleX = x;
double sampleZ = z;
if (children.length > 0) {
int mark = scratch.mark();
try {
double[] pair = scratch.buffer(2);
for (int child = 0; child < children.length; child++) {
children[child].samplePair(scratch, x, z, pair);
double offset = childOffsets[child];
sampleX += pair[0] - offset;
sampleZ += pair[1] - offset;
}
} finally {
scratch.reset(mark);
}
int mark = scratch.mark();
try {
double[] sampleCoordinates = scratch.buffer(2);
warpedSampleCoordinate(scratch, x, z, sampleCoordinates);
return post(program.sample2D(sampleCoordinates[0], sampleCoordinates[1]));
} finally {
scratch.reset(mark);
}
return post(program.sample2D((sampleX / zoom) + offsetX, (sampleZ / zoom) + offsetZ));
}
private void samplePair(TerrainBatchScratch scratch, double x, double z, double[] out) {
private void sampleAxes(TerrainBatchScratch scratch, double x, double z, double[] out) {
if (!enabled) {
out[0] = offsetY;
out[1] = offsetY;
return;
}
double forwardX = x;
double forwardZ = z;
double reverseX = z;
double reverseZ = x;
int mark = scratch.mark();
try {
double[] sampleCoordinates = scratch.buffer(2);
warpedSampleCoordinate(scratch, x, z, sampleCoordinates);
out[0] = post(program.sample2D(sampleCoordinates[0], sampleCoordinates[1]));
out[1] = post(zAxisProgram.sample2D(sampleCoordinates[0], sampleCoordinates[1]));
} finally {
scratch.reset(mark);
}
}
private void warpedSampleCoordinate(TerrainBatchScratch scratch, double x, double z, double[] out) {
double sampleX = x;
double sampleZ = z;
if (children.length > 0) {
int mark = scratch.mark();
try {
double[] pair = scratch.buffer(2);
for (int child = 0; child < children.length; child++) {
children[child].samplePair(scratch, x, z, pair);
double offset = childOffsets[child];
forwardX += pair[0] - offset;
forwardZ += pair[1] - offset;
reverseX += pair[1] - offset;
reverseZ += pair[0] - offset;
}
} finally {
scratch.reset(mark);
double[] warp = scratch.buffer(2);
for (int child = 0; child < children.length; child++) {
children[child].sampleAxes(scratch, x, z, warp);
double offset = childOffsets[child];
sampleX += warp[0] - offset;
sampleZ += warp[1] - offset;
}
}
out[0] = post(program.sample2D((forwardX / zoom) + offsetX, (forwardZ / zoom) + offsetZ));
out[1] = post(program.sample2D((reverseX / zoom) + offsetX, (reverseZ / zoom) + offsetZ));
out[0] = (sampleX / zoom) + offsetX;
out[1] = (sampleZ / zoom) + offsetZ;
}
private void applyPost(double[] values, int count) {
for (int index = 0; index < count; index++) {
values[index] = post(values[index]);
}
}
private double post(double raw) {
@@ -14,6 +14,7 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
@@ -128,6 +129,25 @@ public abstract class ExternalDataProvider {
return false;
}
/**
* @param data The block to keep, possibly an {@link IrisCustomData} this provider returned from {@link #getBlockData}
* @return The block made to never decay, like custom leaves, or {@code data} itself when it is not one of the
* provider's decaying blocks
*/
@NotNull
public BlockData withoutDecay(@NotNull BlockData data) {
return data;
}
/**
* @param data The block to check, possibly an {@link IrisCustomData} this provider returned from {@link #getBlockData}
* @param tag A block tag, like {@code minecraft:logs}
* @return Whether the block is one of the provider's blocks and carries that tag
*/
public boolean hasBlockTag(@NotNull BlockData data, @NotNull NamespacedKey tag) {
return false;
}
/**
* Spawns a mob in the specified location using the given engine and entity identifier.
*
@@ -30,6 +30,7 @@ import art.arcane.volmlib.util.collection.KMap;
import art.arcane.iris.platform.bukkit.plugin.IrisService;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
@@ -193,6 +194,26 @@ public class ExternalDataSVC implements IrisService {
return blockData;
}
/** The block made to never decay by the provider it belongs to, or {@code data} itself. */
public BlockData withoutDecay(BlockData data) {
for (ExternalDataProvider provider : activeProviders) {
BlockData kept = provider.withoutDecay(data);
if (kept == data) {
continue;
}
if (kept instanceof IrisCustomData custom && data instanceof IrisCustomData) {
return IrisCustomData.of(custom.getBase(), qualifyBlockId(provider, custom.getCustom()));
}
return kept;
}
return data;
}
/** Whether {@code data} is a provider's block carrying {@code tag}. */
public boolean hasBlockTag(BlockData data, NamespacedKey tag) {
return activeProviders.stream().anyMatch(provider -> provider.hasBlockTag(data, tag));
}
public Optional<BlockData> getBlockData(final Identifier key) {
Pair<Identifier, KMap<String, String>> pair;
try {
@@ -30,6 +30,7 @@ import net.momirealms.craftengine.core.util.Key;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
@@ -57,6 +58,7 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
BlockProperty.ofBoolean("randomPitch", false),
BlockProperty.ofDouble("pitch", 0, 0, 360f, false, true)
);
private static final String PERSISTENT_PROPERTY = "persistent";
private static final ContentRegistry EMPTY_CONTENT = new ContentRegistry(Set.of(), Set.of(), false);
private volatile ContentRegistry content = EMPTY_CONTENT;
@@ -131,6 +133,32 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
return state == null || state.isEmpty() ? Optional.empty() : Optional.of(Identifier.fromString(state.toString()));
}
@Override
public @NotNull BlockData withoutDecay(@NotNull BlockData data) {
ImmutableBlockState state = customStateOf(data);
if (state == null) {
return data;
}
Property<Boolean> persistent = state.getProperty(PERSISTENT_PROPERTY);
if (persistent == null || persistent.valueClass() != Boolean.class || state.get(persistent)) {
return data;
}
ImmutableBlockState kept = state.with(persistent, true);
return IrisCustomData.of(CraftEngineBlocks.getBukkitBlockData(kept), Identifier.fromString(kept.toString()));
}
@Override
public boolean hasBlockTag(@NotNull BlockData data, @NotNull NamespacedKey tag) {
ImmutableBlockState state = customStateOf(data);
return state != null && state.settings().tags().contains(Key.of(tag.getNamespace(), tag.getKey()));
}
private static ImmutableBlockState customStateOf(BlockData data) {
BlockData nativeData = data instanceof IrisCustomData custom ? custom.getBase() : data;
ImmutableBlockState state = CraftEngineBlocks.getCustomBlockState(nativeData);
return state == null || state.isEmpty() ? null : state;
}
@Override
public boolean placeBlock(@NotNull Block block, @NotNull Identifier blockId) {
Pair<Identifier, KMap<String, String>> parsed = ExternalDataSVC.parseState(blockId);
@@ -78,6 +78,14 @@ public final class RuntimeUiMessages {
public static final TextKey DUST_OBJECTS_IN_CHUNK = TextKey.of("iris.runtime.dust.objects_in_chunk", "Objects in chunk: {objects}");
public static final TextKey DUST_COPY_BUTTON = TextKey.of("iris.runtime.dust.copy_button", "[Click to copy these stats]");
public static final TextKey DUST_COPY_HOVER = TextKey.of("iris.runtime.dust.copy_hover", "Copy block stats to clipboard");
public static final TextKey STUDIO_APP_DOWNLOAD_OFF = TextKey.of("iris.runtime.studio.app_download_off", "Studio app download is off: set studio.downloadApp to true in iris.json.");
public static final TextKey STUDIO_APP_NO_DISPLAY = TextKey.of("iris.runtime.studio.app_no_display", "This server has no display to open the studio app on.");
public static final TextKey STUDIO_APP_DOWNLOADING = TextKey.of("iris.runtime.studio.app_downloading", "Studio app is still downloading; try again in a moment.");
public static final TextKey STUDIO_APP_UNAVAILABLE = TextKey.of("iris.runtime.studio.app_unavailable", "Studio app unavailable; see the console.");
public static final TextKey STUDIO_APP_NOT_BUILT = TextKey.of("iris.runtime.studio.app_not_built", "Studio app not built: run npm run build in its folder.");
public static final TextKey STUDIO_APP_FAILED_TO_START = TextKey.of("iris.runtime.studio.app_failed_to_start", "Studio app failed to start; see the console.");
public static final TextKey STUDIO_LINK_COPY_BUTTON = TextKey.of("iris.runtime.studio.link_copy_button", "[Copy studio link]");
public static final TextKey STUDIO_LINK_COPY_HOVER = TextKey.of("iris.runtime.studio.link_copy_hover", "Paste it into the studio app's connect screen");
public static final TextKey DUST_REVEAL_FAILED = TextKey.of("iris.runtime.dust.reveal_failed", "Object reveal failed; see the console for details.");
public static final TextKey DUST_BIOME_LOADING = TextKey.of("iris.runtime.dust.biome_loading", "Saved biome information is loading. Try revealing this block again shortly.");
public static final TextKey WHAT_MATERIAL = TextKey.of("iris.runtime.what.material", "Material: {material}");
@@ -196,6 +204,14 @@ public final class RuntimeUiMessages {
DUST_OBJECTS_IN_CHUNK,
DUST_COPY_BUTTON,
DUST_COPY_HOVER,
STUDIO_APP_DOWNLOAD_OFF,
STUDIO_APP_NO_DISPLAY,
STUDIO_APP_DOWNLOADING,
STUDIO_APP_UNAVAILABLE,
STUDIO_APP_NOT_BUILT,
STUDIO_APP_FAILED_TO_START,
STUDIO_LINK_COPY_BUTTON,
STUDIO_LINK_COPY_HOVER,
DUST_REVEAL_FAILED,
DUST_BIOME_LOADING,
WHAT_MATERIAL,
@@ -143,7 +143,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
Field center = new Field.Const(-child.getOpacity() / 2.0);
String childPath = path + "/f" + index + "_" + child.getSeed();
warpX = sum(warpX, binary(Field.BinaryOp.ADD, layer(child, domain, emit, childPath + "x"), center));
warpZ = sum(warpZ, binary(Field.BinaryOp.ADD, layer(child, domain.swapped(), emit, childPath + "z"), center));
warpZ = sum(warpZ, binary(Field.BinaryOp.ADD, layer(child, domain, emit, childPath + "z"), center));
}
Domain sampled = domain.layer(positive(layer.getZoom(), "layer zoom"), layer.getOffsetX(), layer.getOffsetZ(), warpX, warpZ);
Field value = style(layer.getStyle(), layer.getOctaves(), sampled, emit, path);
@@ -208,7 +208,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
Displacement leafDisplacement = displacement;
if (warped(cng)) {
Field warpX = displacement(node(cng.getFracture(), displacement, emit, path + "/x"), cng.getFscale());
Field warpZ = displacement(node(cng.getFracture(), displacement.swapped(), emit, path + "/z"), cng.getFscale());
Field warpZ = displacement(node(cng.getFracture(), displacement, emit, path + "/z"), cng.getFscale());
leafDisplacement = displacement.warped(warpX, warpZ);
}
value = leaf(type, cng.getOct(), cng.getEffectiveScale() * multiplier, leafDisplacement, emit, path);
@@ -483,19 +483,11 @@ public final class NoiseStyleCompiler implements StyleCompiler {
sum(warpX, layerWarpX == null ? null : scaled(layerWarpX, zoom)),
sum(warpZ, layerWarpZ == null ? null : scaled(layerWarpZ, zoom)));
}
private Domain swapped() {
return new Domain(zoom, offsetZ, offsetX, warpZ, warpX);
}
}
private record Displacement(double offsetX, double offsetZ, Field warpX, Field warpZ) {
private static final Displacement NONE = new Displacement(0.0, 0.0, null, null);
private Displacement swapped() {
return new Displacement(offsetZ, offsetX, warpZ, warpX);
}
private Displacement warped(Field addedX, Field addedZ) {
return new Displacement(offsetX, offsetZ, sum(warpX, addedX), sum(warpZ, addedZ));
}
@@ -129,6 +129,16 @@ public final class MissingBlockState implements NativeBlockState {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -100,8 +100,12 @@ public final class BukkitBlockResolution {
}
Identifier key = Identifier.fromString(ix);
Optional<BlockData> bd = IrisServices.get(ExternalDataSVC.class).getBlockData(key);
ExternalDataSVC external = IrisServices.get(ExternalDataSVC.class);
Optional<BlockData> bd = external.getBlockData(key);
debug("Loading block data " + key);
if (bd.isPresent() && shouldPreventLeafDecay()) {
return external.withoutDecay(bd.get());
}
return bd.orElse(null);
}
@@ -27,9 +27,11 @@ import art.arcane.volmlib.nativelib.terrain.BlockStateKey;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.iris.generation.block.IrisCustomData;
import art.arcane.iris.generation.geometry.IrisBlockVector;
import art.arcane.iris.spi.IrisServices;
import art.arcane.volmlib.util.collection.KMap;
import org.bukkit.Axis;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
@@ -75,6 +77,8 @@ public final class BukkitBlockState implements NativeBlockState {
private byte updatable;
private byte foliage;
private byte treeBlock;
private byte log;
private byte leaves;
private byte foliagePlantable;
private byte decorant;
private byte storage;
@@ -318,12 +322,41 @@ public final class BukkitBlockState implements NativeBlockState {
public boolean isTreeBlock() {
byte cached = treeBlock;
if (cached == UNKNOWN) {
cached = flag(Tag.LOGS.isTagged(data.getMaterial()) || Tag.LEAVES.isTagged(data.getMaterial()));
cached = flag(isLog() || isLeaves());
treeBlock = cached;
}
return cached == TRUE;
}
@Override
public boolean isLog() {
byte cached = log;
if (cached == UNKNOWN) {
cached = flag(hasTag(Tag.LOGS));
log = cached;
}
return cached == TRUE;
}
@Override
public boolean isLeaves() {
byte cached = leaves;
if (cached == UNKNOWN) {
cached = flag(hasTag(Tag.LEAVES));
leaves = cached;
}
return cached == TRUE;
}
// A plugin's custom block shows up as some other material, so the plugin is asked for its own tags too.
private boolean hasTag(Tag<Material> tag) {
if (tag.isTagged(data.getMaterial())) {
return true;
}
ExternalDataSVC external = IrisServices.getOrNull(ExternalDataSVC.class);
return external != null && external.hasBlockTag(data, tag.getKey());
}
@Override
public boolean isFoliagePlantable() {
byte cached = foliagePlantable;
@@ -32,6 +32,9 @@ import art.arcane.volmlib.util.math.M;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Server;
import org.bukkit.Sound;
@@ -326,6 +329,17 @@ public class VolmitSender implements CommandSender {
deliver(ComponentText.component(component));
}
/** A green line that copies {@code payload} to a player's clipboard when clicked; a console gets nothing. */
public void sendCopyButton(String label, String hover, String payload) {
if (!isPlayer()) {
return;
}
sendComponent(Component.text(label)
.color(NamedTextColor.GREEN)
.clickEvent(ClickEvent.copyToClipboard(payload))
.hoverEvent(HoverEvent.showText(Component.text(hover))));
}
private void deliver(ComponentText message) {
ComponentMessenger.send(s, message);
}
@@ -141,8 +141,9 @@ final class ObjectBlockPass {
private boolean handleCustomData(NativeBlockState data, boolean air, TileData tile, String marker, int xx, int yy, int zz) {
// Short-circuit order matters for cost only: the mantle read is paid solely
// for vine blocks. Both operands are pure, so the value is unchanged.
boolean wouldReplace = !is(ObjectPlaceMode.STRUCTURE_PIECE) && B.isVineBlock(data) && B.isSolid(state.placer.get(xx, yy, zz));
// for vine blocks and leaves. Both operands are pure, so the value is unchanged.
boolean wouldReplace = !is(ObjectPlaceMode.STRUCTURE_PIECE) && readsExistingBlock(data)
&& keepsExisting(data, state.placer.get(xx, yy, zz));
boolean place = shouldPlaceObjectBlock(is(ObjectPlaceMode.STRUCTURE_PIECE), air, wouldReplace);
if (data.isCustom() || place) {
state.placer.set(xx, yy, zz, data);
@@ -160,6 +161,15 @@ final class ObjectBlockPass {
return false;
}
private static boolean readsExistingBlock(NativeBlockState data) {
return B.isVineBlock(data) || B.isLeaves(data);
}
/** Vines never replace solid blocks, and leaves never cut a log: the trunk above the cut would float. */
static boolean keepsExisting(NativeBlockState data, NativeBlockState existing) {
return B.isVineBlock(data) ? B.isSolid(existing) : B.isLeaves(data) && B.isLog(existing);
}
private EditResult applyEdits(double[] exact, int index, NativeBlockState data, TileData tile) {
double exactX = exact[index * 3];
double exactY = exact[index * 3 + 1];
@@ -70,8 +70,7 @@ final class PlacementPalette {
NativeBlockState resolved = decayed[entry];
if (resolved == null) {
NativeBlockState data = source(entry);
resolved = preventingDecay && IrisProceduralBlocks.hasProperty(data, "distance")
&& "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent"))
resolved = preventingDecay && "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent"))
? data.withProperty("persistent", "true") : data;
decayed[entry] = resolved;
}
@@ -0,0 +1,63 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
/** The studio app the jar carries, unpacked into a folder named by its checksum so each build gets its own copy. */
final class BundledStudioApp {
static final String RESOURCE = "META-INF/iris/studio-app.zip";
private static final String FOLDER_PREFIX = "app-";
private static final int FOLDER_CHECKSUM_LENGTH = 12;
private BundledStudioApp() {
}
static Path install(Path root, ClassLoader resources) throws IOException {
Path archive = root.resolve("studio-app.zip.part");
try {
copyResource(resources, archive);
Path folder = root.resolve(FOLDER_PREFIX + ElectronRuntime.sha256(archive).substring(0, FOLDER_CHECKSUM_LENGTH));
if (!Files.isRegularFile(folder.resolve("package.json"))) {
ZipArchives.extract(archive, folder);
}
return folder;
} finally {
Files.deleteIfExists(archive);
}
}
static boolean isAppFolder(Path folder) {
return folder.getFileName().toString().startsWith(FOLDER_PREFIX);
}
private static void copyResource(ClassLoader resources, Path archive) throws IOException {
try (InputStream input = resources.getResourceAsStream(RESOURCE)) {
if (input == null) {
throw new IOException("this build does not bundle the studio app; point studio.studioApp at a studio checkout");
}
Files.createDirectories(archive.getParent());
Files.copy(input, archive, StandardCopyOption.REPLACE_EXISTING);
}
}
}
@@ -0,0 +1,179 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Properties;
/**
* The Electron build the studio app runs on. The build pins its version and each platform's SHA-256 in the studio app
* manifest; the archive comes from Electron's own GitHub release and is unpacked once into the studio folder.
*/
final class ElectronRuntime {
private static final String RELEASE_ROOT = "https://github.com/electron/electron/releases/download/";
private static final String VERSION_KEY = "electron.version";
private static final String CHECKSUM_SUFFIX = ".sha256";
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
private static final Duration DOWNLOAD_TIMEOUT = Duration.ofMinutes(15);
private final String version;
private final Platform platform;
private final String sha256;
private ElectronRuntime(String version, Platform platform, String sha256) {
this.version = version;
this.platform = platform;
this.sha256 = sha256;
}
static ElectronRuntime pinned(Properties manifest, Platform platform) throws IOException {
String version = manifest.getProperty(VERSION_KEY);
String sha256 = manifest.getProperty(platform.name() + CHECKSUM_SUFFIX);
if (version == null || sha256 == null) {
throw new IOException("no Electron build is pinned for " + platform.name());
}
return new ElectronRuntime(version, platform, sha256.toLowerCase(Locale.ROOT));
}
String folderName() {
return "electron-v" + version + "-" + platform.name();
}
URI source() {
return URI.create(RELEASE_ROOT + "v" + version + "/" + folderName() + ".zip");
}
/** The Electron executable under {@code root}, downloaded, checked and unpacked first when it is not there yet. */
Path install(Path root, Downloader downloader) throws IOException {
Path executable = root.resolve(folderName()).resolve(platform.executable());
if (Files.isRegularFile(executable)) {
return executable;
}
Path archive = root.resolve(folderName() + ".zip.part");
try {
downloader.download(source(), archive);
requireChecksum(archive);
if (platform.macOS()) {
ZipArchives.extractWithDitto(archive, root.resolve(folderName()));
} else {
ZipArchives.extract(archive, root.resolve(folderName()));
}
} finally {
Files.deleteIfExists(archive);
}
if (!Files.isRegularFile(executable)) {
throw new IOException(source() + " has no " + platform.executable());
}
return executable;
}
private void requireChecksum(Path archive) throws IOException {
String actual = sha256(archive);
if (!actual.equals(sha256)) {
throw new IOException(source() + " failed its checksum (expected " + sha256 + ", got " + actual + ")");
}
}
static String sha256(Path file) throws IOException {
try (InputStream input = Files.newInputStream(file)) {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[1 << 16];
int read;
while ((read = input.read(buffer)) >= 0) {
digest.update(buffer, 0, read);
}
return HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException missing) {
throw new IllegalStateException(missing);
}
}
@FunctionalInterface
interface Downloader {
void download(URI source, Path target) throws IOException;
static Downloader http() {
return (source, target) -> {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(CONNECT_TIMEOUT)
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder(source)
.timeout(DOWNLOAD_TIMEOUT)
.header("User-Agent", "Iris")
.build();
try {
HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(target));
if (response.statusCode() != 200) {
throw new IOException(source + " answered HTTP " + response.statusCode());
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IOException("download of " + source + " was interrupted", interrupted);
}
};
}
}
/** An Electron release platform, named as its archives are, and where the executable sits inside them. */
record Platform(String name, String executable) {
static Platform current() {
return of(System.getProperty("os.name", ""), System.getProperty("os.arch", ""));
}
/** Null for a system Electron publishes no build for. */
static Platform of(String operatingSystem, String architecture) {
String os = operatingSystem.toLowerCase(Locale.ROOT);
String arch = switch (architecture) {
case "aarch64", "arm64" -> "arm64";
case "amd64", "x86_64" -> "x64";
default -> null;
};
if (arch == null) {
return null;
}
if (os.contains("linux")) {
return new Platform("linux-" + arch, "electron");
}
if (os.contains("win")) {
return new Platform("win32-" + arch, "electron.exe");
}
if (os.contains("mac")) {
return new Platform("darwin-" + arch, "Electron.app/Contents/MacOS/Electron");
}
return null;
}
boolean macOS() {
return name.startsWith("darwin");
}
}
}
@@ -0,0 +1,25 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import java.nio.file.Path;
/** A studio app ready to start: the Electron executable and the app folder it runs. */
public record StudioAppInstall(Path electron, Path app) {
}
@@ -0,0 +1,168 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.studio.view.GuiHost;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Stream;
/**
* Installs the studio app into the Iris data folder in the background at startup: the app from the jar, and the
* Electron build it runs on from Electron's release. Servers without a display skip it, since the window could not
* open there anyway.
*/
public final class StudioAppInstaller {
static final String MANIFEST = "META-INF/iris/studio-app.properties";
private static final String DATA_FOLDER = "studio";
private static final String STAGING_SUFFIX = ".part";
private static StudioAppState state = StudioAppState.NOT_STARTED;
private static StudioAppInstall installed;
private static String unavailableReason = "";
private StudioAppInstaller() {
}
/** Starts the install unless it is done, running, or off; the state it leaves, for a caller about to open the app. */
public static synchronized StudioAppState installInBackground() {
if (state == StudioAppState.DOWNLOADING || state == StudioAppState.READY || state == StudioAppState.UNAVAILABLE) {
return state;
}
state = blockedState();
if (state != StudioAppState.DOWNLOADING) {
return state;
}
Thread.ofPlatform().daemon().name("Iris Studio install").start(StudioAppInstaller::install);
return state;
}
public static synchronized StudioAppInstall installed() {
return installed;
}
public static synchronized String unavailableReason() {
return unavailableReason;
}
static boolean hasDisplay(String operatingSystem, Map<String, String> environment) {
String os = operatingSystem.toLowerCase(Locale.ROOT);
if (os.contains("win") || os.contains("mac")) {
return true;
}
return isSet(environment.get("DISPLAY")) || isSet(environment.get("WAYLAND_DISPLAY"));
}
private static StudioAppState blockedState() {
if (!IrisSettings.get().getStudio().isDownloadApp()) {
return StudioAppState.DOWNLOAD_OFF;
}
if (GuiHost.isDesktopSuppressed() || !hasDisplay(System.getProperty("os.name", ""), System.getenv())) {
return StudioAppState.NO_DISPLAY;
}
return StudioAppState.DOWNLOADING;
}
private static void install() {
long startedNanos = System.nanoTime();
try {
ElectronRuntime.Platform platform = ElectronRuntime.Platform.current();
if (platform == null) {
throw new IOException("Electron has no build for " + System.getProperty("os.name") + " " + System.getProperty("os.arch"));
}
ElectronRuntime electron = ElectronRuntime.pinned(manifest(), platform);
Path root = IrisPlatforms.get().dataFolder(DATA_FOLDER).toPath();
Path executable = installElectron(electron, root);
Path app = BundledStudioApp.install(root, StudioAppInstaller.class.getClassLoader());
removeStaleInstalls(root, List.of(app, root.resolve(electron.folderName())));
ready(new StudioAppInstall(executable, app), (System.nanoTime() - startedNanos) / 1_000_000L);
} catch (IOException | RuntimeException error) {
unavailable(error.getMessage() == null ? error.getClass().getSimpleName() : error.getMessage());
}
}
private static Path installElectron(ElectronRuntime electron, Path root) throws IOException {
if (!Files.isDirectory(root.resolve(electron.folderName()))) {
IrisLogging.info("Downloading the studio app runtime from %s", electron.source());
}
return electron.install(root, ElectronRuntime.Downloader.http());
}
private static Properties manifest() throws IOException {
Properties manifest = new Properties();
try (InputStream input = StudioAppInstaller.class.getClassLoader().getResourceAsStream(MANIFEST)) {
if (input == null) {
throw new IOException("this build does not bundle the studio app; point studio.studioApp at a studio checkout");
}
manifest.load(input);
}
return manifest;
}
/** Drops the Electron builds and app copies earlier versions left, and any half-finished download or unpack. */
private static void removeStaleInstalls(Path root, List<Path> current) {
try (Stream<Path> children = Files.list(root)) {
for (Path child : children.toList()) {
if (current.contains(child) || !isInstallArtifact(child)) {
continue;
}
try {
ZipArchives.deleteRecursively(child);
} catch (IOException error) {
IrisLogging.debug("Could not remove the old studio install %s: %s", child, error.getMessage());
}
}
} catch (IOException error) {
IrisLogging.debug("Could not list the studio folder %s: %s", root, error.getMessage());
}
}
private static boolean isInstallArtifact(Path child) {
String name = child.getFileName().toString();
return name.startsWith("electron-v") || BundledStudioApp.isAppFolder(child) || name.endsWith(STAGING_SUFFIX);
}
private static synchronized void ready(StudioAppInstall install, long elapsedMillis) {
installed = install;
unavailableReason = "";
state = StudioAppState.READY;
IrisLogging.info("Studio app ready in %d ms", elapsedMillis);
}
private static synchronized void unavailable(String reason) {
installed = null;
unavailableReason = reason;
state = StudioAppState.UNAVAILABLE;
IrisLogging.warn("Studio app unavailable: %s", reason);
}
private static boolean isSet(String value) {
return value != null && !value.isBlank();
}
}
@@ -0,0 +1,29 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
/** Where the downloaded studio app stands on this server. */
public enum StudioAppState {
NOT_STARTED,
DOWNLOAD_OFF,
NO_DISPLAY,
DOWNLOADING,
READY,
UNAVAILABLE
}
@@ -0,0 +1,247 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Unpacks archives into a folder that only appears once it is complete: everything lands in a staging folder first,
* which is then moved into place, so a crash halfway never leaves a folder that looks installed.
*/
final class ZipArchives {
private static final long DITTO_TIMEOUT_MINUTES = 5;
private static final int FILE_TYPE_MASK = 0170000;
private static final int SYMLINK_TYPE = 0120000;
private static final int PERMISSION_MASK = 0777;
private static final List<PosixFilePermission> PERMISSION_BITS = List.of(
PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_READ,
PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_WRITE, PosixFilePermission.GROUP_READ,
PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_READ);
private ZipArchives() {
}
/** Keeps each entry's Unix mode and symlinks, so executables stay executable. */
static void extract(Path archive, Path folder) throws IOException {
Path staging = staging(folder);
boolean posix = staging.getFileSystem().supportedFileAttributeViews().contains("posix");
Map<String, Integer> modes = posix ? unixModes(archive) : Map.of();
try (ZipFile zip = new ZipFile(archive.toFile())) {
for (ZipEntry entry : Collections.list(zip.entries())) {
extractEntry(zip, entry, staging, modes.getOrDefault(entry.getName(), 0), posix);
}
}
moveIntoPlace(staging, folder);
}
/** Unpacks with macOS's ditto, which keeps everything an app bundle relies on. */
static void extractWithDitto(Path archive, Path folder) throws IOException {
Path staging = staging(folder);
Process ditto = new ProcessBuilder("ditto", "-x", "-k", archive.toString(), staging.toString())
.redirectErrorStream(true)
.start();
try {
if (!ditto.waitFor(DITTO_TIMEOUT_MINUTES, TimeUnit.MINUTES)) {
ditto.destroyForcibly();
throw new IOException("ditto did not finish unpacking " + archive);
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IOException("unpacking " + archive + " was interrupted", interrupted);
}
if (ditto.exitValue() != 0) {
throw new IOException("ditto could not unpack " + archive + ": "
+ new String(ditto.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim());
}
moveIntoPlace(staging, folder);
}
static void deleteRecursively(Path path) throws IOException {
if (!Files.exists(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
return;
}
try (Stream<Path> walk = Files.walk(path)) {
for (Path entry : walk.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(entry);
}
}
}
private static void extractEntry(ZipFile zip, ZipEntry entry, Path staging, int mode, boolean posix) throws IOException {
Path target = insideStaging(staging, staging.resolve(entry.getName()));
if (entry.isDirectory()) {
Files.createDirectories(target);
return;
}
Files.createDirectories(target.getParent());
try (InputStream input = zip.getInputStream(entry)) {
if (posix && (mode & FILE_TYPE_MASK) == SYMLINK_TYPE) {
Path linkTarget = Path.of(new String(input.readAllBytes(), StandardCharsets.UTF_8));
insideStaging(staging, target.getParent().resolve(linkTarget));
Files.createSymbolicLink(target, linkTarget);
return;
}
Files.copy(input, target);
}
if (posix && mode != 0) {
Files.setPosixFilePermissions(target, permissions(mode));
}
}
private static Path insideStaging(Path staging, Path path) throws IOException {
Path normalized = path.normalize();
if (!normalized.startsWith(staging)) {
throw new IOException("archive entry " + path + " points outside its folder");
}
return normalized;
}
private static Set<PosixFilePermission> permissions(int mode) {
Set<PosixFilePermission> permissions = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE);
int bits = mode & PERMISSION_MASK;
for (int bit = 0; bit < PERMISSION_BITS.size(); bit++) {
if ((bits & (1 << bit)) != 0) {
permissions.add(PERMISSION_BITS.get(bit));
}
}
return permissions;
}
/**
* Each entry's Unix mode, read from the archive's central directory, where zip tools made on Unix keep it in the
* high half of the external attributes. {@link ZipFile} reads the entries but not this field.
*/
static Map<String, Integer> unixModes(Path archive) throws IOException {
try (FileChannel channel = FileChannel.open(archive)) {
CentralDirectory directory = CentralDirectory.locate(channel);
ByteBuffer records = read(channel, directory.offset(), directory.size());
Map<String, Integer> modes = new HashMap<>();
int position = 0;
for (long index = 0; index < directory.entries(); index++) {
if (records.getInt(position) != CentralDirectory.ENTRY_SIGNATURE) {
throw new IOException(archive + " has a damaged central directory");
}
int madeBySystem = (records.getShort(position + 4) >> 8) & 0xFF;
int nameLength = records.getShort(position + 28) & 0xFFFF;
int extraLength = records.getShort(position + 30) & 0xFFFF;
int commentLength = records.getShort(position + 32) & 0xFFFF;
int externalAttributes = records.getInt(position + 38);
byte[] name = new byte[nameLength];
records.get(position + 46, name);
if (madeBySystem == CentralDirectory.MADE_ON_UNIX) {
modes.put(new String(name, StandardCharsets.UTF_8), externalAttributes >>> 16);
}
position += 46 + nameLength + extraLength + commentLength;
}
return modes;
}
}
private static ByteBuffer read(FileChannel channel, long offset, long length) throws IOException {
if (length > Integer.MAX_VALUE - 8 || offset < 0 || offset + length > channel.size()) {
throw new IOException("zip structure points outside the archive");
}
ByteBuffer buffer = ByteBuffer.allocate((int) length).order(ByteOrder.LITTLE_ENDIAN);
while (buffer.hasRemaining()) {
if (channel.read(buffer, offset + buffer.position()) < 0) {
throw new IOException("archive ended early");
}
}
return buffer.flip();
}
private record CentralDirectory(long offset, long size, long entries) {
static final int ENTRY_SIGNATURE = 0x02014b50;
static final int MADE_ON_UNIX = 3;
private static final int END_SIGNATURE = 0x06054b50;
private static final int ZIP64_LOCATOR_SIGNATURE = 0x07064b50;
private static final int ZIP64_END_SIGNATURE = 0x06064b50;
private static final int END_RECORD_LENGTH = 22;
private static final int ZIP64_LOCATOR_LENGTH = 20;
private static final int MAX_COMMENT_LENGTH = 0xFFFF;
static CentralDirectory locate(FileChannel channel) throws IOException {
long size = channel.size();
int tailLength = (int) Math.min(size, END_RECORD_LENGTH + MAX_COMMENT_LENGTH);
long tailOffset = size - tailLength;
ByteBuffer tail = read(channel, tailOffset, tailLength);
for (int end = tailLength - END_RECORD_LENGTH; end >= 0; end--) {
if (tail.getInt(end) == END_SIGNATURE) {
return fromEndRecord(channel, tail, end, tailOffset + end);
}
}
throw new IOException("not a zip archive");
}
private static CentralDirectory fromEndRecord(FileChannel channel, ByteBuffer tail, int end, long endOffset) throws IOException {
long entries = tail.getShort(end + 10) & 0xFFFFL;
long size = tail.getInt(end + 12) & 0xFFFFFFFFL;
long offset = tail.getInt(end + 16) & 0xFFFFFFFFL;
if (entries != 0xFFFFL && size != 0xFFFFFFFFL && offset != 0xFFFFFFFFL) {
return new CentralDirectory(offset, size, entries);
}
ByteBuffer locator = read(channel, endOffset - ZIP64_LOCATOR_LENGTH, ZIP64_LOCATOR_LENGTH);
if (locator.getInt(0) != ZIP64_LOCATOR_SIGNATURE) {
throw new IOException("zip64 archive without its locator");
}
ByteBuffer zip64End = read(channel, locator.getLong(8), 56);
if (zip64End.getInt(0) != ZIP64_END_SIGNATURE) {
throw new IOException("zip64 archive without its end record");
}
return new CentralDirectory(zip64End.getLong(48), zip64End.getLong(40), zip64End.getLong(32));
}
}
private static Path staging(Path folder) throws IOException {
Path staging = folder.resolveSibling(folder.getFileName() + ".part");
deleteRecursively(staging);
Files.createDirectories(staging);
return staging;
}
private static void moveIntoPlace(Path staging, Path folder) throws IOException {
deleteRecursively(folder);
try {
Files.move(staging, folder, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException unsupported) {
Files.move(staging, folder);
}
}
}
@@ -0,0 +1,47 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.localization.RuntimeUiMessages;
import art.arcane.volmlib.util.localization.TextKey;
/** How a request to show the studio window ended; every outcome but {@link #OPENED} leaves the bridge link as the only way in. */
public enum StudioLaunch {
OPENED(null),
DOWNLOAD_OFF(RuntimeUiMessages.STUDIO_APP_DOWNLOAD_OFF),
NO_DISPLAY(RuntimeUiMessages.STUDIO_APP_NO_DISPLAY),
DOWNLOADING(RuntimeUiMessages.STUDIO_APP_DOWNLOADING),
UNAVAILABLE(RuntimeUiMessages.STUDIO_APP_UNAVAILABLE),
NOT_BUILT(RuntimeUiMessages.STUDIO_APP_NOT_BUILT),
FAILED_TO_START(RuntimeUiMessages.STUDIO_APP_FAILED_TO_START);
private final TextKey failureMessage;
StudioLaunch(TextKey failureMessage) {
this.failureMessage = failureMessage;
}
public boolean opened() {
return this == OPENED;
}
public TextKey failureMessage() {
return failureMessage;
}
}
@@ -20,6 +20,8 @@ package art.arcane.iris.studio.bridge;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.studio.app.StudioAppInstall;
import art.arcane.iris.studio.app.StudioAppInstaller;
import java.io.IOException;
import java.nio.file.Files;
@@ -28,7 +30,8 @@ import java.util.ArrayList;
import java.util.List;
/**
* Opens the Iris Studio window on a bridge, from the app folder the studio settings name. The app keeps one window:
* Opens the Iris Studio window on a bridge, from the studio checkout the settings name or else from the app the
* server downloaded at startup. The app keeps one window:
* a second start hands its link to the open window and exits. Windows the server started close when it stops, as
* their bridges go with it.
*/
@@ -43,25 +46,47 @@ public final class StudioWindow {
private StudioWindow() {
}
/** False when no app is set or it could not start, so the caller's printed link is the only way in. */
public static synchronized boolean show(StudioBridge bridge) {
public static synchronized StudioLaunch show(StudioBridge bridge) {
IrisSettings.IrisSettingsStudio settings = IrisSettings.get().getStudio();
String appFolder = settings.getStudioApp();
if (appFolder == null || appFolder.isBlank()) {
return false;
String checkout = settings.getStudioApp();
if (checkout != null && !checkout.isBlank()) {
return showCheckout(Path.of(checkout), electronBinary(settings), bridge.link());
}
Path app = Path.of(appFolder);
return showDownloaded(bridge.link());
}
private static StudioLaunch showCheckout(Path app, String electron, String link) {
if (!Files.isRegularFile(app.resolve(BUILT_MAIN))) {
IrisLogging.warn("Iris Studio is not built in %s; run npm run build there.", app);
return false;
return StudioLaunch.NOT_BUILT;
}
return launch(electron, app, link);
}
private static StudioLaunch showDownloaded(String link) {
return switch (StudioAppInstaller.installInBackground()) {
case READY -> {
StudioAppInstall install = StudioAppInstaller.installed();
yield launch(install.electron().toString(), install.app(), link);
}
case NOT_STARTED, DOWNLOADING -> StudioLaunch.DOWNLOADING;
case DOWNLOAD_OFF -> StudioLaunch.DOWNLOAD_OFF;
case NO_DISPLAY -> StudioLaunch.NO_DISPLAY;
case UNAVAILABLE -> {
IrisLogging.warn("Studio app unavailable: %s", StudioAppInstaller.unavailableReason());
yield StudioLaunch.UNAVAILABLE;
}
};
}
private static StudioLaunch launch(String electron, Path app, String link) {
try {
STARTED.removeIf(process -> !process.isAlive());
STARTED.add(start(electronBinary(settings), app, bridge.link()));
return true;
STARTED.add(start(electron, app, link));
return StudioLaunch.OPENED;
} catch (IOException error) {
IrisLogging.warn("Could not open Iris Studio: %s", error.getMessage());
return false;
return StudioLaunch.FAILED_TO_START;
}
}
@@ -420,7 +420,7 @@ public class PregeneratorJob implements PregenListener, PregenRenderSource {
try {
StudioBridge bridge = StudioBridges.open(engine.getWorld().name(), () -> engine, null);
studioWatching = true;
if (!StudioWindow.show(bridge)) {
if (!StudioWindow.show(bridge).opened()) {
IrisLogging.info("Iris Studio link for the pregeneration of %s: %s", engine.getWorld().name(), bridge.link());
}
} catch (IOException error) {
@@ -1581,6 +1581,14 @@ failed_fragment = " fehlgeschlagen {failed}"
"commandpack.update_world_unchanged" = "§aWelt '{world}' verwendet bereits {pack} v{version} mit denselben Generierungseinstellungen. Kein Neustart erforderlich."
[iris.runtime.studio]
app_download_off = "Studio-App-Download ist aus: Setze studio.downloadApp in iris.json auf true."
app_no_display = "Dieser Server hat keine Anzeige, auf der sich die Studio-App öffnen kann."
app_downloading = "Die Studio-App wird noch heruntergeladen; versuche es gleich noch einmal."
app_unavailable = "Studio-App nicht verfügbar; siehe Konsole."
app_not_built = "Studio-App nicht gebaut: Führe npm run build in ihrem Ordner aus."
app_failed_to_start = "Studio-App konnte nicht starten; siehe Konsole."
link_copy_button = "[Studio-Link kopieren]"
link_copy_hover = "In den Verbindungsbildschirm der Studio-App einfügen"
opening = "§6Studio §bÖFFNET"
opening_progress = "§6Studio §bÖFFNET§7 {percent}%"
failed_progress = "§6Studio §cFEHLGESCHLAGEN§7 {percent}%"
@@ -1581,6 +1581,14 @@ failed_fragment = " fallidos {failed}"
"commandpack.update_world_unchanged" = "§aEl mundo '{world}' ya usa {pack} v{version} con los mismos ajustes de generación. No hace falta reiniciar."
[iris.runtime.studio]
app_download_off = "La descarga de la app de Studio está desactivada: pon studio.downloadApp a true en iris.json."
app_no_display = "Este servidor no tiene pantalla donde abrir la app de Studio."
app_downloading = "La app de Studio aún se está descargando; vuelve a intentarlo en un momento."
app_unavailable = "La app de Studio no está disponible; consulta la consola."
app_not_built = "La app de Studio no está compilada: ejecuta npm run build en su carpeta."
app_failed_to_start = "La app de Studio no pudo iniciarse; consulta la consola."
link_copy_button = "[Copiar enlace de Studio]"
link_copy_hover = "Pégalo en la pantalla de conexión de la app de Studio"
opening = "§6Studio §bABRIENDO"
opening_progress = "§6Studio §bABRIENDO§7 {percent}%"
failed_progress = "§6Studio §cFALLÓ§7 {percent}%"
@@ -1586,6 +1586,14 @@ failed_fragment = " epäonnistui {failed}"
"commandpack.update_world_unchanged" = "§aMaailma '{world}' käyttää jo pakettia {pack} v{version} samoilla generointiasetuksilla. Uudelleenkäynnistystä ei tarvita."
[iris.runtime.studio]
app_download_off = "Studio-sovelluksen lataus on pois päältä: aseta studio.downloadApp arvoon true tiedostossa iris.json."
app_no_display = "Tällä palvelimella ei ole näyttöä, jolla Studio-sovelluksen voisi avata."
app_downloading = "Studio-sovellusta ladataan vielä; yritä hetken päästä uudelleen."
app_unavailable = "Studio-sovellus ei ole käytettävissä; katso konsoli."
app_not_built = "Studio-sovellusta ei ole käännetty: suorita npm run build sen kansiossa."
app_failed_to_start = "Studio-sovelluksen käynnistys epäonnistui; katso konsoli."
link_copy_button = "[Kopioi Studio-linkki]"
link_copy_hover = "Liitä se Studio-sovelluksen yhdistämisnäkymään"
opening = "§6Studio §bAVATAAN"
opening_progress = "§6Studio §bAVATAAN§7 {percent}%"
failed_progress = "§6Studio §cEPÄONNISTUI§7 {percent}%"
@@ -1581,6 +1581,14 @@ failed_fragment = " échecs {failed}"
"commandpack.update_world_unchanged" = "§aLe monde '{world}' utilise déjà {pack} v{version} avec les mêmes paramètres de génération. Aucun redémarrage nécessaire."
[iris.runtime.studio]
app_download_off = "Le téléchargement de l'application Studio est désactivé : mettez studio.downloadApp à true dans iris.json."
app_no_display = "Ce serveur n'a pas d'écran pour ouvrir l'application Studio."
app_downloading = "L'application Studio est encore en téléchargement ; réessayez dans un instant."
app_unavailable = "Application Studio indisponible ; consultez la console."
app_not_built = "Application Studio non compilée : lancez npm run build dans son dossier."
app_failed_to_start = "L'application Studio n'a pas pu démarrer ; consultez la console."
link_copy_button = "[Copier le lien Studio]"
link_copy_hover = "Collez-le dans l'écran de connexion de l'application Studio"
opening = "§6Studio §bOUVERTURE"
opening_progress = "§6Studio §bOUVERTURE§7 {percent}%"
failed_progress = "§6Studio §cÉCHEC§7 {percent}%"
@@ -1586,6 +1586,14 @@ failed_fragment = " נכשל {failed}"
"commandpack.update_world_unchanged" = "§aהעולם '{world}' כבר משתמש בחבילה {pack} v{version} עם אותן הגדרות יצירה. אין צורך בהפעלה מחדש."
[iris.runtime.studio]
app_download_off = "הורדת אפליקציית Studio כבויה: הגדר את studio.downloadApp ל-true בקובץ iris.json."
app_no_display = "לשרת הזה אין מסך שבו אפשר לפתוח את אפליקציית Studio."
app_downloading = "אפליקציית Studio עדיין יורדת; נסה שוב בעוד רגע."
app_unavailable = "אפליקציית Studio אינה זמינה; ראה את הקונסולה."
app_not_built = "אפליקציית Studio לא נבנתה: הרץ npm run build בתיקייה שלה."
app_failed_to_start = "אפליקציית Studio לא הצליחה לעלות; ראה את הקונסולה."
link_copy_button = "[העתק קישור Studio]"
link_copy_hover = "הדבק אותו במסך החיבור של אפליקציית Studio"
opening = "§6Studio §bנפתח"
opening_progress = "§6Studio §bנפתח§7 {percent}%"
failed_progress = "§6Studio §cנכשל§7 {percent}%"
@@ -1581,6 +1581,14 @@ failed_fragment = " non riusciti {failed}"
"commandpack.update_world_unchanged" = "§aIl mondo '{world}' usa già {pack} v{version} con le stesse impostazioni di generazione. Non serve riavviare."
[iris.runtime.studio]
app_download_off = "Il download dell'app Studio è disattivato: imposta studio.downloadApp su true in iris.json."
app_no_display = "Questo server non ha uno schermo su cui aprire l'app Studio."
app_downloading = "L'app Studio è ancora in download; riprova tra un momento."
app_unavailable = "App Studio non disponibile; controlla la console."
app_not_built = "App Studio non compilata: esegui npm run build nella sua cartella."
app_failed_to_start = "Impossibile avviare l'app Studio; controlla la console."
link_copy_button = "[Copia link Studio]"
link_copy_hover = "Incollalo nella schermata di connessione dell'app Studio"
opening = "§6Studio §bAPERTURA"
opening_progress = "§6Studio §bAPERTURA§7 {percent}%"
failed_progress = "§6Studio §cNON RIUSCITO§7 {percent}%"
@@ -1584,6 +1584,14 @@ failed_fragment = " 失敗 {failed}"
"commandpack.update_world_unchanged" = "§aワールド '{world}' は同じ生成設定の {pack} v{version} を使用しています。再起動は不要です。"
[iris.runtime.studio]
app_download_off = "Studio アプリのダウンロードがオフです: iris.json の studio.downloadApp を true にしてください。"
app_no_display = "このサーバーには Studio アプリを開くディスプレイがありません。"
app_downloading = "Studio アプリはまだダウンロード中です。少し待ってから再試行してください。"
app_unavailable = "Studio アプリを利用できません。コンソールを確認してください。"
app_not_built = "Studio アプリがビルドされていません: そのフォルダで npm run build を実行してください。"
app_failed_to_start = "Studio アプリを起動できませんでした。コンソールを確認してください。"
link_copy_button = "[Studio リンクをコピー]"
link_copy_hover = "Studio アプリの接続画面に貼り付けてください"
opening = "§6Studio §bオープン中"
opening_progress = "§6Studio §bオープン中§7 {percent}%"
failed_progress = "§6Studio §c失敗§7 {percent}%"
@@ -1584,6 +1584,14 @@ failed_fragment = " 실패 {failed}"
"commandpack.update_world_unchanged" = "§a월드 '{world}'는 이미 같은 생성 설정으로 {pack} v{version}을 사용 중입니다. 재시작할 필요가 없습니다."
[iris.runtime.studio]
app_download_off = "Studio 앱 다운로드가 꺼져 있습니다: iris.json에서 studio.downloadApp을 true로 설정하세요."
app_no_display = "이 서버에는 Studio 앱을 열 디스플레이가 없습니다."
app_downloading = "Studio 앱을 아직 다운로드하는 중입니다. 잠시 후 다시 시도하세요."
app_unavailable = "Studio 앱을 사용할 수 없습니다. 콘솔을 확인하세요."
app_not_built = "Studio 앱이 빌드되지 않았습니다: 해당 폴더에서 npm run build를 실행하세요."
app_failed_to_start = "Studio 앱을 시작하지 못했습니다. 콘솔을 확인하세요."
link_copy_button = "[Studio 링크 복사]"
link_copy_hover = "Studio 앱의 연결 화면에 붙여 넣으세요"
opening = "§6Studio §b여는 중"
opening_progress = "§6Studio §b여는 중§7 {percent}%"
failed_progress = "§6Studio §c실패§7 {percent}%"
@@ -1586,6 +1586,14 @@ failed_fragment = " nepavyko {failed}"
"commandpack.update_world_unchanged" = "§aPasaulis '{world}' jau naudoja {pack} v{version} su tais pačiais generavimo nustatymais. Paleisti iš naujo nereikia."
[iris.runtime.studio]
app_download_off = "Studio programos atsisiuntimas išjungtas: iris.json faile nustatykite studio.downloadApp į true."
app_no_display = "Šis serveris neturi ekrano, kuriame būtų galima atidaryti Studio programą."
app_downloading = "Studio programa dar atsisiunčiama; netrukus bandykite dar kartą."
app_unavailable = "Studio programa nepasiekiama; žr. konsolę."
app_not_built = "Studio programa nesukompiliuota: jos aplanke paleiskite npm run build."
app_failed_to_start = "Nepavyko paleisti Studio programos; žr. konsolę."
link_copy_button = "[Kopijuoti Studio nuorodą]"
link_copy_hover = "Įklijuokite ją Studio programos prisijungimo ekrane"
opening = "§6Studio §bATIDAROMA"
opening_progress = "§6Studio §bATIDAROMA§7 {percent}%"
failed_progress = "§6Studio §cNEPAVYKO§7 {percent}%"
@@ -1581,6 +1581,14 @@ failed_fragment = " mislukt {failed}"
"commandpack.update_world_unchanged" = "§aWereld '{world}' gebruikt al {pack} v{version} met dezelfde generatie-instellingen. Herstarten is niet nodig."
[iris.runtime.studio]
app_download_off = "Download van de Studio-app staat uit: zet studio.downloadApp op true in iris.json."
app_no_display = "Deze server heeft geen scherm om de Studio-app op te openen."
app_downloading = "De Studio-app wordt nog gedownload; probeer het zo opnieuw."
app_unavailable = "Studio-app niet beschikbaar; zie de console."
app_not_built = "Studio-app niet gebouwd: voer npm run build uit in de map."
app_failed_to_start = "Studio-app kon niet starten; zie de console."
link_copy_button = "[Studio-link kopiëren]"
link_copy_hover = "Plak hem in het verbindingsscherm van de Studio-app"
opening = "§6Studio §bOPENEN"
opening_progress = "§6Studio §bOPENEN§7 {percent}%"
failed_progress = "§6Studio §cMISLUKT§7 {percent}%"
@@ -1586,6 +1586,14 @@ failed_fragment = " nieudane {failed}"
"commandpack.update_world_unchanged" = "§aŚwiat '{world}' już używa {pack} v{version} z tymi samymi ustawieniami generowania. Restart nie jest potrzebny."
[iris.runtime.studio]
app_download_off = "Pobieranie aplikacji Studio jest wyłączone: ustaw studio.downloadApp na true w iris.json."
app_no_display = "Ten serwer nie ma ekranu, na którym można otworzyć aplikację Studio."
app_downloading = "Aplikacja Studio wciąż się pobiera; spróbuj ponownie za chwilę."
app_unavailable = "Aplikacja Studio jest niedostępna; sprawdź konsolę."
app_not_built = "Aplikacja Studio nie jest zbudowana: uruchom npm run build w jej folderze."
app_failed_to_start = "Nie udało się uruchomić aplikacji Studio; sprawdź konsolę."
link_copy_button = "[Kopiuj link Studio]"
link_copy_hover = "Wklej go na ekranie połączenia aplikacji Studio"
opening = "§6Studio §bOTWIERANIE"
opening_progress = "§6Studio §bOTWIERANIE§7 {percent}%"
failed_progress = "§6Studio §cNIEPOWODZENIE§7 {percent}%"
@@ -1581,6 +1581,14 @@ failed_fragment = " falhou {failed}"
"commandpack.update_world_unchanged" = "§aO mundo '{world}' já utiliza {pack} v{version} com as mesmas definições de geração. Não é necessário reiniciar."
[iris.runtime.studio]
app_download_off = "A transferência da app Studio está desligada: define studio.downloadApp como true no iris.json."
app_no_display = "Este servidor não tem ecrã onde abrir a app Studio."
app_downloading = "A app Studio ainda está a ser transferida; tenta novamente daqui a pouco."
app_unavailable = "A app Studio não está disponível; vê a consola."
app_not_built = "A app Studio não está compilada: executa npm run build na pasta dela."
app_failed_to_start = "Não foi possível iniciar a app Studio; vê a consola."
link_copy_button = "[Copiar link do Studio]"
link_copy_hover = "Cola-o no ecrã de ligação da app Studio"
opening = "§6Studio §bA ABRIR"
opening_progress = "§6Studio §bA ABRIR§7 {percent}%"
failed_progress = "§6Studio §cFALHOU§7 {percent}%"
@@ -1586,6 +1586,14 @@ failed_fragment = " ошибок {failed}"
"commandpack.update_world_unchanged" = "§aМир '{world}' уже использует {pack} v{version} с теми же настройками генерации. Перезапуск не требуется."
[iris.runtime.studio]
app_download_off = "Загрузка приложения Studio отключена: установите studio.downloadApp в true в iris.json."
app_no_display = "У этого сервера нет дисплея, на котором можно открыть приложение Studio."
app_downloading = "Приложение Studio ещё загружается; попробуйте снова через минуту."
app_unavailable = "Приложение Studio недоступно; см. консоль."
app_not_built = "Приложение Studio не собрано: выполните npm run build в его папке."
app_failed_to_start = "Не удалось запустить приложение Studio; см. консоль."
link_copy_button = "[Копировать ссылку Studio]"
link_copy_hover = "Вставьте её на экране подключения приложения Studio"
opening = "§6Studio §bОТКРЫТИЕ"
opening_progress = "§6Studio §bОТКРЫТИЕ§7 {percent}%"
failed_progress = "§6Studio §cОШИБКА§7 {percent}%"
@@ -1586,6 +1586,14 @@ failed_fragment = " başarısız {failed}"
"commandpack.update_world_unchanged" = "§a'{world}' dünyası aynı üretim ayarlarıyla zaten {pack} v{version} kullanıyor. Yeniden başlatma gerekmiyor."
[iris.runtime.studio]
app_download_off = "Studio uygulaması indirmesi kapalı: iris.json içinde studio.downloadApp değerini true yap."
app_no_display = "Bu sunucuda Studio uygulamasını açacak bir ekran yok."
app_downloading = "Studio uygulaması hâlâ indiriliyor; birazdan tekrar dene."
app_unavailable = "Studio uygulaması kullanılamıyor; konsola bak."
app_not_built = "Studio uygulaması derlenmemiş: klasöründe npm run build çalıştır."
app_failed_to_start = "Studio uygulaması başlatılamadı; konsola bak."
link_copy_button = "[Studio bağlantısını kopyala]"
link_copy_hover = "Studio uygulamasının bağlantı ekranına yapıştır"
opening = "§6Studio §bAÇILIYOR"
opening_progress = "§6Studio §bAÇILIYOR§7 {percent}%"
failed_progress = "§6Studio §cBAŞARISIZ§7 {percent}%"
@@ -1584,6 +1584,14 @@ failed_fragment = " lỗi {failed}"
"commandpack.update_world_unchanged" = "§aThế giới '{world}' đã dùng {pack} v{version} với cùng thiết lập tạo địa hình. Không cần khởi động lại."
[iris.runtime.studio]
app_download_off = "Tải ứng dụng Studio đang tắt: đặt studio.downloadApp thành true trong iris.json."
app_no_display = "Máy chủ này không có màn hình để mở ứng dụng Studio."
app_downloading = "Ứng dụng Studio vẫn đang tải; hãy thử lại sau giây lát."
app_unavailable = "Ứng dụng Studio không khả dụng; xem console."
app_not_built = "Ứng dụng Studio chưa được build: chạy npm run build trong thư mục của nó."
app_failed_to_start = "Không khởi động được ứng dụng Studio; xem console."
link_copy_button = "[Sao chép liên kết Studio]"
link_copy_hover = "Dán vào màn hình kết nối của ứng dụng Studio"
opening = "§6Studio §bĐANG MỞ"
opening_progress = "§6Studio §bĐANG MỞ§7 {percent}%"
failed_progress = "§6Studio §cTHẤT BẠI§7 {percent}%"
@@ -1584,6 +1584,14 @@ failed_fragment = " 失败 {failed}"
"commandpack.update_world_unchanged" = "§a世界 '{world}' 已使用 {pack} v{version},且生成设置相同。无需重启。"
[iris.runtime.studio]
app_download_off = "Studio 应用下载已关闭:请在 iris.json 中将 studio.downloadApp 设为 true。"
app_no_display = "此服务器没有可打开 Studio 应用的显示器。"
app_downloading = "Studio 应用仍在下载;请稍后再试。"
app_unavailable = "Studio 应用不可用;请查看控制台。"
app_not_built = "Studio 应用未构建:请在其文件夹中运行 npm run build。"
app_failed_to_start = "Studio 应用启动失败;请查看控制台。"
link_copy_button = "[复制 Studio 链接]"
link_copy_hover = "粘贴到 Studio 应用的连接界面"
opening = "§6Studio §b正在打开"
opening_progress = "§6Studio §b正在打开§7 {percent}%"
failed_progress = "§6Studio §c失败§7 {percent}%"
@@ -1584,6 +1584,14 @@ failed_fragment = " 失敗 {failed}"
"commandpack.update_world_unchanged" = "§a世界 '{world}' 已使用 {pack} v{version},且生成設定相同。無需重新啟動。"
[iris.runtime.studio]
app_download_off = "Studio 應用程式下載已關閉:請在 iris.json 中將 studio.downloadApp 設為 true。"
app_no_display = "此伺服器沒有可開啟 Studio 應用程式的顯示器。"
app_downloading = "Studio 應用程式仍在下載;請稍後再試。"
app_unavailable = "Studio 應用程式無法使用;請查看主控台。"
app_not_built = "Studio 應用程式未建置:請在其資料夾中執行 npm run build。"
app_failed_to_start = "Studio 應用程式無法啟動;請查看主控台。"
link_copy_button = "[複製 Studio 連結]"
link_copy_hover = "貼到 Studio 應用程式的連線畫面"
opening = "§6Studio §b正在開啟"
opening_progress = "§6Studio §b正在開啟§7 {percent}%"
failed_progress = "§6Studio §c失敗§7 {percent}%"
@@ -85,7 +85,7 @@ public class IrisCaveCarver3DCellKernelTest {
@Test
public void packStyleProfilesSharingFieldsMatchGoldenWriteSequence() throws Exception {
assertScenario(Scenario.PACK_SHARED, 0xdbe20a1ca87f9cc7L, 269035);
assertScenario(Scenario.PACK_SHARED, 0xb464b50d050e766dL, 288720);
}
@Test
@@ -0,0 +1,68 @@
package art.arcane.iris.generation.noise;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.noise.NoiseGenerator;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public final class IrisNoiseGeneratorFractureMirrorTest {
private static final long SEED = 71L;
private static final int GRID_SIZE = 40;
private static final double GRID_STEP = 7.3D;
private static final double MIRRORED = 1.0E-12D;
private static final int ALLOWED_MIRRORED_SAMPLES = 2;
@Test
public void aCompositeFractureIsNotMirroredAcrossTheDiagonal() {
IrisNoiseGenerator fractured = diagonalSymmetricRoot().setFracture(new KList<>(fracture()));
assertTrue(mirroredSamples(fractured) <= ALLOWED_MIRRORED_SAMPLES);
}
@Test
public void theDiagonalSymmetricRootIsMirroredWithoutAFracture() {
assertTrue(mirroredSamples(diagonalSymmetricRoot()) > ALLOWED_MIRRORED_SAMPLES);
}
private static int mirroredSamples(IrisNoiseGenerator noise) {
int mirroredSamples = 0;
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = i + 1; j < GRID_SIZE; j++) {
double a = i * GRID_STEP;
double b = j * GRID_STEP + 0.5D;
if (Math.abs(noise.getNoise(SEED, a, b, null) - noise.getNoise(SEED, b, a, null)) < MIRRORED) {
mirroredSamples++;
}
}
}
return mirroredSamples;
}
private static IrisNoiseGenerator diagonalSymmetricRoot() {
IrisNoiseGenerator root = new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()).setSeed(5L);
root.getGenerator(SEED, null, null).setGenerator(new DiagonalSymmetricGenerator());
return root;
}
private static IrisNoiseGenerator fracture() {
return new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()).setSeed(9L).setZoom(40D).setOpacity(40D);
}
private static final class DiagonalSymmetricGenerator implements NoiseGenerator {
@Override
public double noise(double x) {
return noise(x, 0D, 0D);
}
@Override
public double noise(double x, double z) {
return noise(x, z, 0D);
}
@Override
public double noise(double x, double y, double z) {
return 0.5D + (Math.sin(x * 0.11D) + Math.sin(y * 0.11D) + Math.sin(z * 0.11D)) / 6D;
}
}
}
@@ -225,6 +225,11 @@ public final class IrisNoiseGeneratorFractureTest {
private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv,
IrisData data, Engine engine) {
return reference(node, superSeed, xv, zv, data, engine, IrisNoiseGenerator.X_AXIS);
}
private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv,
IrisData data, Engine engine, int axis) {
if (!node.isEnabled()) {
return node.getOffsetY();
}
@@ -234,14 +239,16 @@ public final class IrisNoiseGeneratorFractureTest {
for (IrisNoiseGenerator child : node.getFracture()) {
if (child.isEnabled()) {
double offset = child.getOpacity() / 2D;
x += reference(child, superSeed + node.getSeed() + salt, xv, zv, data, engine) - offset;
z += reference(child, superSeed + node.getSeed() + salt, zv, xv, data, engine) - offset;
long childSeed = superSeed + node.getSeed() + salt;
x += reference(child, childSeed, xv, zv, data, engine, IrisNoiseGenerator.X_AXIS) - offset;
z += reference(child, childSeed, xv, zv, data, engine, IrisNoiseGenerator.Z_AXIS) - offset;
}
salt += 819;
}
double sampleX = (x / node.getZoom()) + node.getOffsetX();
double sampleZ = (z / node.getZoom()) + node.getOffsetZ();
double result = node.getGenerator(superSeed, data, engine).noiseFast2D(sampleX, sampleZ) * node.getOpacity();
CNG generator = node.getGenerator(superSeed, data, engine).reseededForAxis(axis);
double result = generator.noiseFast2D(sampleX, sampleZ) * node.getOpacity();
result = node.isNegative() ? -result + node.getOpacity() : result;
result = (node.getExponent() != 1D ? result < 0D ? -Math.pow(-result, node.getExponent())
: Math.pow(result, node.getExponent()) : result) + node.getOffsetY();
@@ -18,7 +18,7 @@ public class NoiseSeedCohesionTest {
private static final long[] SEEDS = {813753L, -935731L, Long.MIN_VALUE};
private static final double[] COORDINATES = {-29_999_983.25D, -513D, -64D, -1D, 0D, 0.125D, 17D, 64D, 8192D, 29_999_983.25D};
private static final double PINNED_SAMPLE_SCALE = 1.0E9D;
private static final long PINNED_HASH_WINDOWS = 2597318414939754011L;
private static final long PINNED_HASH_WINDOWS = 6074446696529759284L;
private static final long PINNED_HASH_MAC = -602781966673993721L;
@Test
@@ -208,6 +208,16 @@ public class IrisDepositModifierOrderingTest {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -466,6 +466,16 @@ public class IrisDepositModifierParityTest {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -339,6 +339,16 @@ public class IrisPerfectionModifierColumnTest {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -252,6 +252,16 @@ final class CompatFixtures {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -38,17 +38,17 @@ public class IrisMathNoiseHotPathParityTest {
.setStyle(NoiseStyle.PERLIN_IRIS.style())
.setExponent(1.15D);
assertEquals(0.5084984235498856D, noiseGenerator.getNoise(9988L, 31.25D, -17.5D, null), 0D);
assertEquals(0.4646529061250786D, noiseGenerator.getNoise(9988L, 31.25D, -17.5D, null), 0D);
IrisGeneratorStyle style = NoiseStyle.IRIS_DOUBLE.style();
assertEquals(0.6224926166486215D, style.createNoCache(new RNG(112233L), null).noiseFast2D(42.5D, -19.75D), 0D);
assertEquals(0.6855680984398492D, style.createNoCache(new RNG(112233L), null).noiseFast2D(42.5D, -19.75D), 0D);
IrisGenerator generator = new IrisGenerator()
.setZoom(9.5D)
.setOpacity(0.91D)
.setComposite(new KList<IrisNoiseGenerator>().qadd(noiseGenerator));
assertEquals(0.43997118860461754D, generator.getHeight(63.0D, -27.0D, 445566L), 0D);
assertEquals(0.5023367573389593D, generator.getHeight(63.0D, -27.0D, 445566L), 0D);
}
@Test
@@ -119,8 +119,12 @@ public class BukkitPersistedBlockStateTest {
IrisCustomData custom = IrisCustomData.of(carrier, Identifier.fromString(key));
ExternalDataSVC provider = mock(ExternalDataSVC.class);
when(provider.getBlockData(Identifier.fromString(key))).thenReturn(Optional.of(custom));
try (MockedStatic<IrisServices> services = mockStatic(IrisServices.class)) {
when(provider.withoutDecay(custom)).thenReturn(custom);
IrisSettings configuration = new IrisSettings();
try (MockedStatic<IrisServices> services = mockStatic(IrisServices.class);
MockedStatic<IrisSettings> settings = mockStatic(IrisSettings.class)) {
services.when(() -> IrisServices.get(ExternalDataSVC.class)).thenReturn(provider);
settings.when(IrisSettings::get).thenReturn(configuration);
NativeBlockState decoded = registries.decodeBlockState(key);
assertEquals(key, decoded.key());
assertEquals(key, decoded.deferredPlacementKey());
@@ -172,6 +172,16 @@ public class IrisObjectTransformsNearestBlockIndexTest {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -0,0 +1,92 @@
package art.arcane.iris.structure.object;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ObjectLeafAndLogRulesTest {
@Test
public void leavesNeverCutALog() {
assertTrue(ObjectBlockPass.keepsExisting(leaves(), log()));
}
@Test
public void leavesReplaceOtherLeavesAndAir() {
assertFalse(ObjectBlockPass.keepsExisting(leaves(), leaves()));
assertFalse(ObjectBlockPass.keepsExisting(leaves(), null));
}
@Test
public void logsStillReplaceLeaves() {
assertFalse(ObjectBlockPass.keepsExisting(log(), leaves()));
}
@Test
public void vinesStillKeepSolidBlocks() {
NativeBlockState vine = mock(NativeBlockState.class);
when(vine.isVineBlock()).thenReturn(true);
NativeBlockState solid = mock(NativeBlockState.class);
when(solid.isSolid()).thenReturn(true);
assertTrue(ObjectBlockPass.keepsExisting(vine, solid));
assertFalse(ObjectBlockPass.keepsExisting(vine, leaves()));
}
@Test
public void customLeavesLosingTheirDecayAreMadePersistent() {
NativeBlockState persistent = mock(NativeBlockState.class);
NativeBlockState decaying = mock(NativeBlockState.class);
when(decaying.key()).thenReturn("craftengine:test/leaves[persistent=false,distance=7]");
when(decaying.withProperty("persistent", "true")).thenReturn(persistent);
assertSame(persistent, paletteOf(true, decaying).decayed(0));
}
@Test
public void customLeavesWithoutADistanceAreMadePersistentToo() {
NativeBlockState persistent = mock(NativeBlockState.class);
NativeBlockState decaying = mock(NativeBlockState.class);
when(decaying.key()).thenReturn("craftengine:test/leaves[persistent=false]");
when(decaying.withProperty("persistent", "true")).thenReturn(persistent);
assertSame(persistent, paletteOf(true, decaying).decayed(0));
}
@Test
public void decayIsLeftAloneWhenItIsNotPrevented() {
NativeBlockState decaying = mock(NativeBlockState.class);
when(decaying.key()).thenReturn("minecraft:oak_leaves[distance=3,persistent=false]");
assertSame(decaying, paletteOf(false, decaying).decayed(0));
}
@Test
public void blocksWithoutAPersistentPropertyAreLeftAlone() {
NativeBlockState stone = mock(NativeBlockState.class);
when(stone.key()).thenReturn("minecraft:stone");
assertSame(stone, paletteOf(true, stone).decayed(0));
}
private static PlacementPalette paletteOf(boolean preventingDecay, NativeBlockState state) {
return new PlacementPalette(new NativeBlockState[]{state}, new IrisObjectRotation(), 0, 0, 0,
preventingDecay, false, java.util.Set.of());
}
private static NativeBlockState leaves() {
NativeBlockState state = mock(NativeBlockState.class);
when(state.isLeaves()).thenReturn(true);
return state;
}
private static NativeBlockState log() {
NativeBlockState state = mock(NativeBlockState.class);
when(state.isLog()).thenReturn(true);
return state;
}
}
@@ -583,7 +583,17 @@ public class ObjectPlacementGoldenTest {
@Override
public boolean isTreeBlock() {
return material.endsWith("_log") || material.endsWith("_leaves");
return isLog() || isLeaves();
}
@Override
public boolean isLog() {
return material.endsWith("_log");
}
@Override
public boolean isLeaves() {
return material.endsWith("_leaves");
}
@Override
@@ -0,0 +1,97 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class BundledStudioAppTest {
@Rule
public TemporaryFolder temporary = new TemporaryFolder();
@Test
public void unpacksTheBundledAppIntoAFolderNamedByItsChecksum() throws IOException {
Path root = temporary.newFolder("studio").toPath();
try (URLClassLoader resources = jarResources(appArchive("out/main/index.js"))) {
Path app = BundledStudioApp.install(root, resources);
assertTrue(app.getFileName().toString().matches("app-[0-9a-f]{12}"));
assertTrue(Files.isRegularFile(app.resolve("package.json")));
assertTrue(Files.isRegularFile(app.resolve("out/main/index.js")));
assertEquals(app, BundledStudioApp.install(root, resources));
assertFalse(Files.exists(root.resolve("studio-app.zip.part")));
}
}
@Test
public void refusesAnArchiveEntryThatLeavesItsFolder() throws IOException {
Path root = temporary.newFolder("studio").toPath();
try (URLClassLoader resources = jarResources(appArchive("../../escaped.js"))) {
assertThrows(IOException.class, () -> BundledStudioApp.install(root, resources));
}
assertFalse(Files.exists(root.getParent().resolve("escaped.js")));
}
@Test
public void reportsABuildWithoutTheApp() throws IOException {
Path root = temporary.newFolder("studio").toPath();
try (URLClassLoader resources = new URLClassLoader(new URL[0], null)) {
assertThrows(IOException.class, () -> BundledStudioApp.install(root, resources));
}
}
private Path appArchive(String scriptEntry) throws IOException {
Path archive = temporary.newFolder().toPath().resolve("studio-app.zip");
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(archive))) {
zip.putNextEntry(new ZipEntry("package.json"));
zip.write("{\"main\":\"out/main/index.js\"}".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
zip.putNextEntry(new ZipEntry(scriptEntry));
zip.write("export {}".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return archive;
}
private URLClassLoader jarResources(Path archive) throws IOException {
Path classpath = temporary.newFolder().toPath();
Path resource = classpath.resolve(BundledStudioApp.RESOURCE);
Files.createDirectories(resource.getParent());
Files.copy(archive, resource);
return new URLClassLoader(new URL[]{classpath.toUri().toURL()}, null);
}
}
@@ -0,0 +1,124 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class ElectronRuntimeTest {
private static final ElectronRuntime.Platform LINUX = new ElectronRuntime.Platform("linux-x64", "electron");
private static final String ELECTRON_FIXTURE = "/studio-app/electron-fixture.zip";
@Rule
public TemporaryFolder temporary = new TemporaryFolder();
@Test
public void namesPlatformsTheWayElectronReleasesDo() {
assertEquals("linux-x64", ElectronRuntime.Platform.of("Linux", "amd64").name());
assertEquals("linux-arm64", ElectronRuntime.Platform.of("Linux", "aarch64").name());
assertEquals("electron.exe", ElectronRuntime.Platform.of("Windows 11", "amd64").executable());
assertEquals("Electron.app/Contents/MacOS/Electron", ElectronRuntime.Platform.of("Mac OS X", "aarch64").executable());
assertNull(ElectronRuntime.Platform.of("FreeBSD", "amd64"));
assertNull(ElectronRuntime.Platform.of("Linux", "riscv64"));
}
@Test
public void downloadsFromTheElectronReleaseOfThePinnedVersion() throws IOException {
ElectronRuntime electron = ElectronRuntime.pinned(pins("45.2.3", "0".repeat(64)), LINUX);
assertEquals(URI.create("https://github.com/electron/electron/releases/download/v45.2.3/electron-v45.2.3-linux-x64.zip"),
electron.source());
}
@Test
public void refusesAPlatformTheBuildDidNotPin() {
assertThrows(IOException.class, () -> ElectronRuntime.pinned(pins("45.2.3", "0".repeat(64)),
new ElectronRuntime.Platform("darwin-arm64", "Electron.app/Contents/MacOS/Electron")));
}
@Test
public void unpacksAVerifiedArchiveWithItsExecutableBitOnce() throws IOException {
Path archive = electronArchive();
Path root = temporary.newFolder("studio").toPath();
ElectronRuntime electron = ElectronRuntime.pinned(pins("45.2.3", ElectronRuntime.sha256(archive)), LINUX);
List<URI> downloads = new ArrayList<>();
ElectronRuntime.Downloader downloader = (source, target) -> {
downloads.add(source);
Files.copy(archive, target);
};
Path executable = electron.install(root, downloader);
electron.install(root, downloader);
assertEquals(root.resolve("electron-v45.2.3-linux-x64/electron"), executable);
Path lib = root.resolve("electron-v45.2.3-linux-x64/lib");
assertTrue(Files.getPosixFilePermissions(executable).contains(PosixFilePermission.OWNER_EXECUTE));
assertFalse(Files.getPosixFilePermissions(lib.resolve("libffmpeg.so")).contains(PosixFilePermission.OWNER_EXECUTE));
assertEquals(Path.of("libffmpeg.so"), Files.readSymbolicLink(lib.resolve("libffmpeg.so.1")));
assertEquals("library", Files.readString(lib.resolve("libffmpeg.so.1")));
assertEquals(1, downloads.size());
assertFalse(Files.exists(root.resolve("electron-v45.2.3-linux-x64.zip.part")));
}
@Test
public void leavesNothingInstalledWhenTheChecksumIsWrong() throws IOException {
Path archive = electronArchive();
Path root = temporary.newFolder("studio").toPath();
ElectronRuntime electron = ElectronRuntime.pinned(pins("45.2.3", "0".repeat(64)), LINUX);
assertThrows(IOException.class, () -> electron.install(root, (source, target) -> Files.copy(archive, target)));
try (var children = Files.list(root)) {
assertEquals(List.of(), children.toList());
}
}
/** Made by Info-ZIP, as Electron's archives are: an executable, a plain file and a symlink to it. */
private Path electronArchive() throws IOException {
Path archive = temporary.getRoot().toPath().resolve("electron.zip");
try (InputStream fixture = ElectronRuntimeTest.class.getResourceAsStream(ELECTRON_FIXTURE)) {
Files.copy(fixture, archive);
}
return archive;
}
private static Properties pins(String version, String linuxChecksum) {
Properties pins = new Properties();
pins.setProperty("electron.version", version);
pins.setProperty("linux-x64.sha256", linuxChecksum);
return pins;
}
}
@@ -0,0 +1,38 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class StudioAppInstallerTest {
@Test
public void seesADisplayOnlyWhenLinuxHasOne() {
assertTrue(StudioAppInstaller.hasDisplay("Linux", Map.of("WAYLAND_DISPLAY", "wayland-1")));
assertTrue(StudioAppInstaller.hasDisplay("Linux", Map.of("DISPLAY", ":0")));
assertFalse(StudioAppInstaller.hasDisplay("Linux", Map.of()));
assertFalse(StudioAppInstaller.hasDisplay("Linux", Map.of("DISPLAY", " ")));
assertTrue(StudioAppInstaller.hasDisplay("Windows 11", Map.of()));
assertTrue(StudioAppInstaller.hasDisplay("Mac OS X", Map.of()));
}
}
@@ -183,6 +183,16 @@ public class TreePlausibilizerTest {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -89,6 +89,16 @@ public final class KeyedBlockState implements NativeBlockState {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -136,6 +136,16 @@ public final class PlantBlockState implements NativeBlockState {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -208,12 +208,21 @@ public final class StubPlatform implements IrisPlatform {
@Override
public boolean isTreeBlock() {
return isLog() || isLeaves();
}
@Override
public boolean isLog() {
String blockKey = blockKey();
return blockKey.endsWith("_log")
|| blockKey.endsWith("_wood")
|| blockKey.endsWith("_stem")
|| blockKey.endsWith("_hyphae")
|| blockKey.endsWith("_leaves");
|| blockKey.endsWith("_hyphae");
}
@Override
public boolean isLeaves() {
return blockKey().endsWith("_leaves");
}
@Override
+16
View File
@@ -11,6 +11,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cn": "^0.5.2",
"lucide-react": "^1.73.0",
"radix-ui": "^1.8.1",
"react": "^19.3.1",
"react-dom": "^19.3.1",
@@ -3806,6 +3807,21 @@
"yallist": "^3.0.2"
}
},
"node_modules/lucide-react": {
"version": "1.73.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.73.0.tgz",
"integrity": "sha512-fVOzGviL9mTfHenG1PbCfIceavyGlnpYNSYr+aGZHLRymAJ7DTP6KHuqt0uBkCKAoenr1UVkwSbDIYt2xIesEQ==",
"license": "ISC",
"peerDependencies": {
"@types/react": "*",
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/magic-string": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
+1
View File
@@ -31,6 +31,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cn": "^0.5.2",
"lucide-react": "^1.73.0",
"radix-ui": "^1.8.1",
"react": "^19.3.1",
"react-dom": "^19.3.1",
@@ -1,69 +0,0 @@
import { cn } from '@/lib/utils'
// IntelliJ's expui icons and the studio's own drawn to match (see icons/NOTICE.txt): each has a light file and a "_dark" twin in its own colours.
const ICON_URLS = import.meta.glob<string>('../icons/**/*.svg', { eager: true, query: '?url', import: 'default' })
const DARK_SUFFIX = '_dark'
export type IdeIconName =
| 'actualZoom'
| 'add'
| 'blocks'
| 'borders'
| 'checked'
| 'closeSmall'
| 'chevronLeft'
| 'chevronRight'
| 'decoration'
| 'delete'
| 'exit'
| 'grid'
| 'groups'
| 'help'
| 'lightning'
| 'locate'
| 'locked'
| 'memory'
| 'mob'
| 'redo'
| 'refresh'
| 'reset'
| 'search'
| 'settings'
| 'shading'
| 'stopWatch'
| 'symlink'
| 'theme'
| 'undo'
| 'web'
| 'views/biomes'
| 'views/cave-profiles'
| 'views/fluid-profiles'
| 'views/formation-profiles'
| 'views/tree-profiles'
| 'views/noise'
| 'views/objects'
| 'views/palettes'
| 'views/procedural'
| 'views/regions'
| 'views/rivers'
| 'views/saved-world'
| 'views/world-3d'
function iconUrl(name: string): string {
const url = ICON_URLS[`../icons/${name}.svg`]
if (url === undefined) {
throw new Error(`No icon named ${name}`)
}
return url
}
/** An IntelliJ icon, 16 px unless sized, in the light or dark colours the window shows. */
export function IdeIcon({ name, className }: { name: IdeIconName; className?: string }): React.JSX.Element {
const size = cn('size-4 shrink-0', className)
return (
<>
<img src={iconUrl(name)} alt="" draggable={false} className={cn(size, 'dark:hidden')} />
<img src={iconUrl(name + DARK_SUFFIX)} alt="" draggable={false} className={cn(size, 'hidden dark:block')} />
</>
)
}
@@ -1,6 +1,6 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { IdeIcon } from "@/components/IdeIcon"
import { Check, ChevronRight } from "lucide-react"
import { ContextMenu as ContextMenuPrimitive } from "radix-ui"
function ContextMenu({
@@ -70,7 +70,7 @@ function ContextMenuSubTrigger({
>
{children}
<span className="ml-auto">
<IdeIcon name="chevronRight" />
<ChevronRight />
</span>
</ContextMenuPrimitive.SubTrigger>
)
@@ -154,7 +154,7 @@ function ContextMenuCheckboxItem({
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<IdeIcon name="checked" />
<Check />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
@@ -2,7 +2,7 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { IdeIcon } from "@/components/IdeIcon"
import { X } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { Button } from "@/components/ui/button"
@@ -72,7 +72,7 @@ function DialogContent({
data-slot="dialog-close"
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<IdeIcon name="closeSmall" />
<X />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
@@ -0,0 +1,61 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { ChevronRight } from "lucide-react"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
const MENU_SURFACE =
"z-50 min-w-[8rem] overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md backdrop-blur-sm data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0"
const MENU_ROW =
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
function DropdownMenu(props: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuTrigger(props: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
}
function DropdownMenuContent({ className, sideOffset = 2, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(MENU_SURFACE, "max-h-(--radix-dropdown-menu-content-available-height)", className)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuItem({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Item>) {
return <DropdownMenuPrimitive.Item data-slot="dropdown-menu-item" className={cn(MENU_ROW, className)} {...props} />
}
function DropdownMenuSub(props: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({ className, children, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger>) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
className={cn(MENU_ROW, "data-[state=open]:bg-accent data-[state=open]:text-accent-foreground", className)}
{...props}
>
{children}
<ChevronRight className="ml-auto size-3.5" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.SubContent data-slot="dropdown-menu-sub-content" className={cn(MENU_SURFACE, "shadow-lg", className)} {...props} />
</DropdownMenuPrimitive.Portal>
)
}
export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent }
@@ -0,0 +1,30 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { Popover as PopoverPrimitive } from "radix-ui"
function Popover(props: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverAnchor(props: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
function PopoverContent({ className, align = "start", sideOffset = 4, ...props }: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 rounded-md border bg-popover p-2 text-popover-foreground shadow-md outline-hidden data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
export { Popover, PopoverAnchor, PopoverContent }
+25 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { canBecomeCurve, curveAt, curveFrom, isCurve, keyframesFrom, samplesOf, shapeFrom, withAddedKeyframe, withKeyframe, withoutKeyframe, withSetting, withShape } from './curves'
import { canBecomeCurve, curveAt, curveFrom, curveLiteral, isCurve, keyframesFrom, plotRange, roundedNumber, samplesOf, shapeFrom, withAddedKeyframe, withKeyframe, withoutKeyframe, withSetting, withShape } from './curves'
describe('isCurve', () => {
it('holds only for keyframes and named shapes', () => {
@@ -82,3 +82,27 @@ describe('editing keyframes', () => {
expect(withoutKeyframe([[1, 3]], 0)).toEqual([[1, 3]])
})
})
describe('plotRange', () => {
it('spans 0 to 1 at least, a tenth past the highest, and below 0 only when the curve goes there', () => {
const rounded = (range: [number, number]): number[] => range.map((end) => Math.round(end * 100) / 100)
expect(rounded(plotRange([0.2, 0.5]))).toEqual([0, 1.1])
expect(rounded(plotRange([0, 3]))).toEqual([0, 3.3])
expect(rounded(plotRange([-1, 1]))).toEqual([-1.2, 1.2])
})
})
describe('curveLiteral', () => {
it('writes keyframes and shapes spaced like hand-written JSON', () => {
expect(curveLiteral([[0, 1.4], [1, 0.4]])).toBe('[[0, 1.4], [1, 0.4]]')
expect(curveLiteral({ shape: 'power', from: 0, to: 2 })).toBe('{"shape": "power", "from": 0, "to": 2}')
})
})
describe('roundedNumber', () => {
it('reads a number with two decimals at most', () => {
expect(roundedNumber(1.3333)).toBe('1.33')
expect(roundedNumber(2)).toBe('2')
})
})
+23
View File
@@ -21,6 +21,8 @@ const NARROWEST_BELL = 1e-6
const SHAPE_STOPS = 5
const FIRST_STOP = 0
const LAST_STOP = 1
const PLOT_MARGIN = 0.1
const READ_PRECISION = 100
export const CURVE_SHAPES: CurveShape[] = [
{ key: 'linear', parameters: [], at: (t) => t },
@@ -157,6 +159,27 @@ export function samplesOf(value: unknown, count: number): number[] | null {
return Array.from({ length: count }, (_, index) => curveAt(value, count === 1 ? 0 : index / (count - 1)))
}
/**
* The values a plot of the curve with {@code samples} spans: from 0 to 1 at least and a tenth past its highest. It goes
* below 0 only when the curve already does, since most values along a part, like a radius, can't be negative.
*/
export function plotRange(samples: number[]): [number, number] {
const low = Math.min(0, ...samples)
const high = Math.max(1, ...samples)
const margin = (high - low) * PLOT_MARGIN
return [low < 0 ? low - margin : 0, high + margin]
}
/** The curve as the JSON written to the file, spaced like hand-written JSON: {@code [[0, 1.4], [1, 0.4]]}. */
export function curveLiteral(curve: unknown): string {
return JSON.stringify(curve).replaceAll(',', ', ').replaceAll('":', '": ')
}
/** A number only to be read, never typed back: two decimals at most, like 1.3 or 0.25. */
export function roundedNumber(value: number): string {
return String(Math.round(value * READ_PRECISION) / READ_PRECISION)
}
/** The curve as keyframes, such as to move a named curve's shape by hand: its values at evenly spaced points. */
export function keyframesFrom(value: unknown): Keyframe[] {
if (isKeyframes(value)) {
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { GraphNode, JsonPath } from '../bridge/types'
import { NO_PART } from '../bridge/types'
import { isWithin, layoutNodes, nodeDrawingPart, NODE_WIDTH } from './nodeLayout'
import { canRegrow, GRID, isWithin, layoutNodes, nodeAt, nodeDrawingPart, NODE_WIDTH, type PlacedNode } from './nodeLayout'
function node(path: JsonPath, children: GraphNode[] = []): GraphNode {
return {
@@ -20,21 +20,65 @@ function node(path: JsonPath, children: GraphNode[] = []): GraphNode {
}
describe('layoutNodes', () => {
it('sets a parent level with the middle of its children, a column to their left', () => {
const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1]), node(['parts', 2])])])
const [first, , last, parent] = layout.nodes
const height = (): number => 50
const placedAt = (layout: ReturnType<typeof layoutNodes>, path: JsonPath): PlacedNode => layout.nodes.find((placed) => placed.id === JSON.stringify(path))!
expect(parent.y).toBe((first.y + last.y) / 2)
expect(first.x - parent.x).toBeGreaterThan(NODE_WIDTH)
expect(layout.wires).toHaveLength(3)
it('sets a node level with its first child, a column to its left, and each next child on the rows below', () => {
const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1])])], height)
const [parent, first, second] = [placedAt(layout, []), placedAt(layout, ['parts', 0]), placedAt(layout, ['parts', 1])]
expect(first.y).toBe(parent.y)
expect(first.x - parent.x).toBe(NODE_WIDTH + 2 * GRID)
expect(second.y).toBeGreaterThanOrEqual(first.y + 50 + 10)
expect(layout.wires).toHaveLength(2)
})
it('lays the next root out under the tree before it', () => {
const layout = layoutNodes([node([], [node(['parts', 0])]), node(['materials', 0])])
const material = layout.nodes.find((placed) => placed.id === JSON.stringify(['materials', 0]))!
it('stacks the other roots under the first, in its column, and starts every node on a grid point', () => {
const layout = layoutNodes([node([], [node(['parts', 0])]), node(['materials', 0])], height)
const [object, material] = [placedAt(layout, []), placedAt(layout, ['materials', 0])]
expect(material.x).toBe(0)
expect(material.y).toBeGreaterThan(Math.max(...layout.nodes.filter((placed) => placed !== material).map((placed) => placed.y)))
expect(material.x).toBe(object.x)
expect(material.y).toBeGreaterThan(object.y + 50)
expect(layout.nodes.every((placed) => placed.x % GRID === 0 && placed.y % GRID === 0)).toBe(true)
})
it('makes room below a tall node before its next sibling', () => {
const tall = (graphNode: GraphNode): number => (graphNode.path.length === 2 && graphNode.path[1] === 0 ? 300 : 50)
const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1])])], tall)
expect(placedAt(layout, ['parts', 1]).y).toBeGreaterThan(placedAt(layout, ['parts', 0]).y + 300)
})
it('puts a node where it was dragged, and marks which nodes have sockets', () => {
const layout = layoutNodes([node([], [node(['parts', 0])])], height, new Map([[JSON.stringify(['parts', 0]), { x: 500, y: 44 }]]))
const part = placedAt(layout, ['parts', 0])
expect([part.x, part.y]).toEqual([500, 44])
expect([part.grown, part.growing]).toEqual([true, false])
expect([placedAt(layout, []).grown, placedAt(layout, []).growing]).toEqual([false, true])
})
})
describe('nodeAt', () => {
it('finds the node under a point by its own height', () => {
const layout = layoutNodes([node([], [node(['parts', 0])])], () => 50)
const part = layout.nodes[1]
expect(nodeAt(layout.nodes, { x: part.x + 5, y: part.y + 49 })?.id).toBe(part.id)
expect(nodeAt(layout.nodes, { x: part.x + 5, y: part.y + 51 })).toBeNull()
})
})
describe('canRegrow', () => {
const withList = (path: JsonPath, children: GraphNode[] = []): GraphNode => ({ ...node(path, children), childList: [...path, 'children'] })
it('lets a part grow from another that takes children, but not from inside itself or where it already grows', () => {
const part = withList(['parts', 0])
expect(canRegrow(part, withList(['parts', 1]))).toBe(true)
expect(canRegrow(part, withList(['parts', 0, 'children', 0]))).toBe(false)
expect(canRegrow(withList(['parts', 1, 'children', 0]), withList(['parts', 1]))).toBe(false)
expect(canRegrow({ ...part, movable: false }, withList(['parts', 1]))).toBe(false)
})
})
+103 -30
View File
@@ -1,10 +1,16 @@
import type { GraphNode, JsonPath } from '../bridge/types'
export const NODE_WIDTH = 168
export const NODE_HEIGHT = 46
const COLUMN_GAP = 64
const ROW_GAP = 10
const TREE_GAP = 26
/** The spacing nodes snap to, and the dots of the canvas mark. */
export const GRID = 22
export const NODE_WIDTH = 12 * GRID
const MARGIN = GRID
const COLUMN_GAP = 2 * GRID
const MIN_ROW_GAP = 10
export interface Point {
x: number
y: number
}
/** A node where the canvas draws it, by its top left corner; `id` tells it from every other node of the file. */
export interface PlacedNode {
@@ -12,6 +18,11 @@ export interface PlacedNode {
node: GraphNode
x: number
y: number
height: number
/** Whether it grows from another node, so it has an input socket. */
grown: boolean
/** Whether other nodes grow from it, so it has an output socket. */
growing: boolean
}
export interface PlacedWire {
@@ -23,8 +34,13 @@ export interface PlacedWire {
export interface NodeLayout {
nodes: PlacedNode[]
wires: PlacedWire[]
width: number
height: number
}
export interface Bounds {
left: number
top: number
right: number
bottom: number
}
export function idOf(path: JsonPath): string {
@@ -71,38 +87,95 @@ export function isWithin(path: JsonPath, ancestor: JsonPath): boolean {
return ancestor.length <= path.length && ancestor.every((step, index) => path[index] === step)
}
export function snappedToGrid(coordinate: number): number {
return Math.round(coordinate / GRID) * GRID
}
function nextRowBelow(bottom: number): number {
return Math.ceil((bottom + MIN_ROW_GAP) / GRID) * GRID
}
function columnLeft(column: number): number {
return MARGIN + column * (NODE_WIDTH + COLUMN_GAP)
}
/**
* Lays each root's tree out from left to right, a column per generation, one tree under the other. Leaves take a row
* each and a parent sits level with the middle of its children, so wires never cross.
* Lays the nodes out on the grid: the roots, such as the object, its materials and its decorations, stacked in the
* first column, and what grows from them to the right, a column per generation. Each subtree takes the rows below the
* last, and a node sits level with its first child, so it is read beside what grows from it. A node in
* {@code placed}, by its id, sits where it was dragged instead.
*/
export function layoutNodes(roots: GraphNode[]): NodeLayout {
export function layoutNodes(roots: GraphNode[], heightOf: (node: GraphNode) => number, placed: ReadonlyMap<string, Point> = new Map()): NodeLayout {
const nodes: PlacedNode[] = []
const wires: PlacedWire[] = []
let nextTop = 0
let width = 0
const place = (node: GraphNode, depth: number): PlacedNode => {
const x = depth * (NODE_WIDTH + COLUMN_GAP)
width = Math.max(width, x + NODE_WIDTH)
const children = node.children.map((link) => ({ label: link.wire, placed: place(link.node, depth + 1) }))
const y = children.length === 0 ? takeRow() : (children[0].placed.y + children[children.length - 1].placed.y) / 2
const placed: PlacedNode = { id: idOf(node.path), node, x, y }
nodes.push(placed)
for (const child of children) {
wires.push({ from: placed, to: child.placed, label: child.label })
const add = (node: GraphNode, x: number, y: number, grown: boolean): PlacedNode => {
const id = idOf(node.path)
const at = placed.get(id) ?? { x, y }
const box: PlacedNode = { id, node, x: at.x, y: at.y, height: heightOf(node), grown, growing: node.children.length > 0 }
nodes.push(box)
return box
}
// Returns the bottom of the subtree as laid out, which a node dragged elsewhere does not change.
const placeTree = (link: GraphNode['children'][number], parent: PlacedNode, column: number, top: number): number => {
const box = add(link.node, columnLeft(column), top, true)
wires.push({ from: parent, to: box, label: link.wire })
let bottom = top + box.height
let childTop = top
for (const child of link.node.children) {
const childBottom = placeTree(child, box, column + 1, childTop)
bottom = Math.max(bottom, childBottom)
childTop = nextRowBelow(childBottom)
}
return placed
return bottom
}
const takeRow = (): number => {
const top = nextTop
nextTop += NODE_HEIGHT + ROW_GAP
return top
let firstColumnTop = MARGIN
const rootBoxes = roots.map((root) => {
const box = add(root, MARGIN, firstColumnTop, false)
firstColumnTop = nextRowBelow(firstColumnTop + box.height)
return box
})
let treeTop = MARGIN
roots.forEach((root, index) => {
for (const link of root.children) {
treeTop = nextRowBelow(placeTree(link, rootBoxes[index], 1, treeTop))
}
})
return { nodes, wires }
}
/** The smallest rectangle around every node; null when there are none. */
export function boundsOf(nodes: PlacedNode[]): Bounds | null {
if (nodes.length === 0) {
return null
}
return {
left: Math.min(...nodes.map((node) => node.x)),
top: Math.min(...nodes.map((node) => node.y)),
right: Math.max(...nodes.map((node) => node.x + NODE_WIDTH)),
bottom: Math.max(...nodes.map((node) => node.y + node.height))
}
}
/** The node under {@code point}, the one drawn last when they overlap; null over the background. */
export function nodeAt(nodes: PlacedNode[], point: Point): PlacedNode | null {
for (let index = nodes.length - 1; index >= 0; index--) {
const box = nodes[index]
if (point.x >= box.x && point.x <= box.x + NODE_WIDTH && point.y >= box.y && point.y <= box.y + box.height) {
return box
}
}
return null
}
for (const root of roots) {
place(root, 0)
nextTop += TREE_GAP
/** Whether {@code dragged} may grow from {@code over}: it takes children, and is neither inside it nor already its parent. */
export function canRegrow(dragged: GraphNode, over: GraphNode): boolean {
const toList = over.childList
if (!dragged.movable || toList === null || isWithin(toList, dragged.path)) {
return false
}
return { nodes, wires, width, height: Math.max(0, nextTop - ROW_GAP - TREE_GAP) }
const alreadyThere = dragged.path.length === toList.length + 1 && isWithin(dragged.path, toList)
return !alreadyThere
}
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest'
import { idOf } from './nodeLayout'
import { pathAfterRemoval, positionsAfterEdit } from './nodePositions'
const at = { x: 44, y: 88 }
describe('pathAfterRemoval', () => {
it('moves an element after the removed one, and what it holds, up an index', () => {
expect(pathAfterRemoval(['parts', 2, 'children', 0], ['parts', 1])).toEqual(['parts', 1, 'children', 0])
})
it('leaves an element before it and one of another array alone', () => {
expect(pathAfterRemoval(['parts', 0], ['parts', 1])).toEqual(['parts', 0])
expect(pathAfterRemoval(['materials', 3], ['parts', 1])).toEqual(['materials', 3])
})
})
describe('positionsAfterEdit', () => {
it('drops a deleted node and what grows from it, and moves the later ones up', () => {
const positions = { [idOf(['parts', 0])]: at, [idOf(['parts', 0, 'children', 0])]: at, [idOf(['parts', 1])]: at }
expect(positionsAfterEdit(positions, { op: 'delete', path: ['parts', 0] }, {})).toEqual({ [idOf(['parts', 0])]: at })
})
it('keeps a moved node where it was, under the path it gets at the end of the list it joins', () => {
const values = { parts: [{}, { children: [{}] }] }
const positions = { [idOf(['parts', 0])]: at, [idOf(['parts', 0, 'children', 0])]: { x: 0, y: 0 } }
expect(positionsAfterEdit(positions, { op: 'move', path: ['parts', 0], toList: ['parts', 1, 'children'] }, values)).toEqual({
[idOf(['parts', 0, 'children', 1])]: at,
[idOf(['parts', 0, 'children', 1, 'children', 0])]: { x: 0, y: 0 }
})
})
it('leaves the positions as they were for an edit that moves no node', () => {
const positions = { [idOf(['parts', 0])]: at }
expect(positionsAfterEdit(positions, { op: 'set', object: ['parts', 0], key: 'role', literal: '"a"' }, {})).toBe(positions)
})
})
@@ -0,0 +1,45 @@
import type { GraphEdit, JsonPath } from '../bridge/types'
import { valueAt } from './jsonValues'
import { idOf, isWithin, type Point } from './nodeLayout'
/** Where nodes were dragged to, by the id of their path in the file. */
export type NodePositions = Readonly<Record<string, Point>>
/**
* The positions after {@code edit} changed the file {@code values} holds. A deleted node's position goes; the
* elements after a removed one move up an index, and so do the positions named by them. A moved node keeps its
* position under its new path, at the end of the list it joins.
*/
export function positionsAfterEdit(positions: NodePositions, edit: GraphEdit, values: unknown): NodePositions {
if (edit.op === 'delete') {
return remapped(positions, (path) => (isWithin(path, edit.path) ? null : pathAfterRemoval(path, edit.path)))
}
if (edit.op !== 'move') {
return positions
}
const joined = valueAt(values, edit.toList)
const newPath = [...pathAfterRemoval(edit.toList, edit.path), Array.isArray(joined) ? joined.length : 0]
return remapped(positions, (path) => (isWithin(path, edit.path) ? [...newPath, ...path.slice(edit.path.length)] : pathAfterRemoval(path, edit.path)))
}
/** {@code path} once the array element at {@code removed} is gone: one index lower when it is after it in that array. */
export function pathAfterRemoval(path: JsonPath, removed: JsonPath): JsonPath {
const index = removed.at(-1)
const array = removed.slice(0, -1)
const step = path[array.length]
if (typeof index !== 'number' || path.length <= array.length || !isWithin(path, array) || typeof step !== 'number' || step <= index) {
return path
}
return [...array, step - 1, ...path.slice(array.length + 1)]
}
function remapped(positions: NodePositions, newPathOf: (path: JsonPath) => JsonPath | null): NodePositions {
const next: Record<string, Point> = {}
for (const [id, position] of Object.entries(positions)) {
const newPath = newPathOf(JSON.parse(id) as JsonPath)
if (newPath !== null) {
next[idOf(newPath)] = position
}
}
return next
}
@@ -0,0 +1,69 @@
import { describe, expect, it } from 'vitest'
import type { GraphNode, SettingOption, SettingsType, ValueKind } from '../bridge/types'
import { NODE_HEADER, NODE_HEADING, NODE_PADDING, NODE_ROW, NODE_STRIPE, nodeRows } from './nodeRows'
function option(name: string, kind: ValueKind): SettingOption {
return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind }
}
const any: ValueKind = { kind: 'any' }
const types: Record<string, SettingsType> = {
Part: { description: '', options: [option('role', { kind: 'text', format: 'PLAIN' }), option('offset', { kind: 'object', type: 'Offset' })] },
Stem: { description: '', options: [option('length', any), option('taper', any)] },
Offset: { description: '', options: [option('x', any), option('y', any)] }
}
const stem: GraphNode = {
kind: 'Stem',
title: 'Stem',
path: ['parts', 0],
partId: 0,
roles: ['wood'],
settings: [
{ title: 'Part', path: ['parts', 0], type: 'Part', shownAsNodes: [] },
{ title: 'Stem', path: ['parts', 0, 'stem'], type: 'Stem', shownAsNodes: [] }
],
children: [],
childList: null,
movable: true,
duplicable: true,
additions: []
}
const file = { parts: [{ role: 'wood', offset: { x: 2 }, stem: { length: 6 } }] }
describe('nodeRows', () => {
it('lists the first section plainly, a later one under its heading, and a folded section as one row', () => {
const { rows } = nodeRows(stem, types, file, new Set(), true)
expect(rows.map((row) => row.kind)).toEqual(['setting', 'fold', 'heading', 'setting', 'addSetting'])
expect(rows.flatMap((row) => (row.kind === 'setting' ? [row.option.name, row.value] : []))).toEqual(['role', 'wood', 'length', 6])
})
it('lists what an unfolded section holds right under it', () => {
const { rows } = nodeRows(stem, types, file, new Set([JSON.stringify(['parts', 0, 'offset'])]), true)
expect(rows.map((row) => (row.kind === 'setting' ? row.option.name : row.kind))).toEqual(['role', 'fold', 'x', 'heading', 'length', 'addSetting'])
})
it('adds up its height from its rows', () => {
const { height } = nodeRows(stem, types, file, new Set(), true)
expect(height).toBe(NODE_STRIPE + NODE_HEADER + 4 * NODE_ROW + NODE_HEADING + NODE_PADDING)
})
it('offers the sections with settings left to add, but no row to add them while the file is read only', () => {
const editable = nodeRows(stem, types, file, new Set(), true)
const readOnly = nodeRows(stem, types, file, new Set(), false)
expect(editable.addable.map((fold) => fold.title)).toEqual(['offset', 'Stem'])
expect(readOnly.rows.some((row) => row.kind === 'addSetting')).toBe(false)
})
it('draws a node without settings, such as a shared part, as its header alone', () => {
const { rows, height } = nodeRows({ ...stem, settings: [] }, types, file, new Set(), true)
expect(rows).toEqual([])
expect(height).toBe(NODE_STRIPE + NODE_HEADER + NODE_PADDING)
})
})
@@ -0,0 +1,67 @@
import type { GraphNode, SettingOption, SettingsType } from '../bridge/types'
import { valueAt } from './jsonValues'
import { idOf } from './nodeLayout'
import { foldedSections, idOfFold, visibleFolds, type SettingsFold } from './settingFolds'
export const NODE_STRIPE = 3
export const NODE_HEADER = 28
export const NODE_ROW = 24
export const NODE_HEADING = 20
export const NODE_PADDING = 8
export type NodeRow =
| { kind: 'heading'; id: string; fold: SettingsFold }
| { kind: 'fold'; id: string; fold: SettingsFold; open: boolean }
| { kind: 'setting'; id: string; fold: SettingsFold; option: SettingOption; value: unknown }
| { kind: 'addSetting'; id: string }
/** What a node lists below its header, how tall that makes it, and the sections that have settings left to add. */
export interface NodeRows {
rows: NodeRow[]
height: number
addable: SettingsFold[]
}
const ADD_SETTING_ID = 'add-setting'
export function heightOfRow(row: NodeRow): number {
return row.kind === 'heading' ? NODE_HEADING : NODE_ROW
}
/**
* The rows of {@code node}: each of its sections' settings, the first section's plainly, a later one's under its
* heading, and a folding section's only while it is in {@code open}. An editable node with settings left to add ends
* in a row to add one.
*/
export function nodeRows(node: GraphNode, types: Record<string, SettingsType>, values: unknown, open: ReadonlySet<string>, editable: boolean): NodeRows {
const rows: NodeRow[] = []
const addable: SettingsFold[] = []
let ownSections = 0
for (const section of node.settings) {
const folds = foldedSections(section, types, values)
addable.push(...folds.filter((fold) => fold.unset.length > 0))
for (const fold of visibleFolds(folds, open)) {
const id = idOfFold(fold)
if (fold.kind !== 'own') {
rows.push({ kind: 'fold', id: `fold:${id}`, fold, open: open.has(id) })
} else if (ownSections++ > 0) {
rows.push({ kind: 'heading', id: `heading:${id}`, fold })
}
if (fold.kind === 'own' || open.has(id)) {
rows.push(...settingRows(fold, values))
}
}
}
if (editable && addable.length > 0) {
rows.push({ kind: 'addSetting', id: ADD_SETTING_ID })
}
const height = NODE_STRIPE + NODE_HEADER + rows.reduce((sum, row) => sum + heightOfRow(row), 0) + NODE_PADDING
return { rows, height, addable }
}
function settingRows(fold: SettingsFold, values: unknown): NodeRow[] {
return fold.settings.map((option) => {
const path = [...fold.path, option.name]
return { kind: 'setting', id: idOf(path), fold, option, value: valueAt(values, path) }
})
}
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { NodeSettings, SettingOption, SettingsType, ValueKind } from '../bridge/types'
import { foldedSections, idOfFold, visibleFolds } from './settingFolds'
import { SPAN_TYPE } from './settingText'
function option(name: string, kind: ValueKind): SettingOption {
return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind }
@@ -47,10 +48,34 @@ describe('foldedSections', () => {
expect(folds[2].holder).toEqual({ object: ['materials', 0], key: 'rules' })
})
it('leaves the folded settings and the ones shown as nodes out of the fields of the section that holds them', () => {
it('leaves the folded settings and the ones shown as nodes out of the rows of the section that holds them', () => {
const [own] = foldedSections(material, types, file)
expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block'])
expect(own.settings.map((setting) => setting.name)).toEqual(['role', 'block'])
})
it('lists only what is written, and keeps the rest to add', () => {
const [own] = foldedSections(material, types, { materials: [{ block: 'minecraft:stone' }] })
expect(own.settings.map((setting) => setting.name)).toEqual(['block'])
expect(own.unset.map((setting) => setting.name)).toEqual(['role', 'offset', 'rules'])
})
it('lists a plain setting the type requires even while it is unset, so its default shows', () => {
const required: Record<string, SettingsType> = { ...types, Material: { ...types.Material, options: [{ ...option('role', text), required: true }] } }
const [own] = foldedSections(material, required, { materials: [{}] })
expect(own.settings.map((setting) => setting.name)).toEqual(['role'])
expect(own.unset).toEqual([])
})
it('keeps a span a row rather than a section, since it is typed as a range', () => {
const spanned: Record<string, SettingsType> = { ...types, Material: { description: '', options: [option('along', { kind: 'object', type: SPAN_TYPE })] }, [SPAN_TYPE]: { description: '', options: [option('from', any), option('to', any)] } }
const folds = foldedSections(material, spanned, { materials: [{ along: { from: 0.2, to: 0.8 } }] })
expect(folds).toHaveLength(1)
expect(folds[0].settings.map((setting) => setting.name)).toEqual(['along'])
expect(folds[0].summary).toBe('along 0.2 – 0.8')
})
it('sums a section up by what it holds, a curve as curve and the default namespace left off', () => {
@@ -61,11 +86,11 @@ describe('foldedSections', () => {
expect(folds[2].summary).toBe('2 items')
})
it('keeps a setting that is not written as an object a field', () => {
const [own, ...inside] = foldedSections(material, types, { materials: [{ role: 'wood' }] })
it('keeps an object setting that is not written as an object a row', () => {
const [own, ...inside] = foldedSections(material, types, { materials: [{ offset: 3 }] })
expect(inside).toEqual([])
expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block', 'offset', 'rules'])
expect(own.settings.map((setting) => setting.name)).toEqual(['offset'])
})
})
+37 -18
View File
@@ -1,7 +1,7 @@
import type { JsonPath, NodeSettings, SettingOption, SettingsType } from '../bridge/types'
import type { JsonPath, NodeSettings, SettingOption, SettingsType, ValueKind } from '../bridge/types'
import { isCurve } from './curves'
import { isWithin } from './nodeLayout'
import { textOf } from './settingText'
import { isSpan, textOf } from './settingText'
import { valueAt } from './jsonValues'
const SUMMARY_SETTINGS = 3
@@ -14,7 +14,7 @@ const DEFAULT_NAMESPACE = 'minecraft:'
*/
export type FoldKind = 'own' | 'group' | 'list' | 'item'
/** One object of the file whose settings the inspector shows, below the ones that hold it. */
/** One object of the file whose settings a node lists, below the ones that hold it. */
export interface SettingsFold {
title: string
path: JsonPath
@@ -26,8 +26,10 @@ export interface SettingsFold {
summary: string
/** The object and member that hold a group or list, to unset it; null for the rest. */
holder: { object: JsonPath; key: string } | null
/** The settings written plainly in it, as fields; those that are folds of their own are not among them. */
options: SettingOption[]
/** The settings listed as rows: those written plainly in it, and the plain ones it requires but leaves unset. */
settings: SettingOption[]
/** What it could set but leaves at the default, to add. */
unset: SettingOption[]
}
function isObject(value: unknown): value is Record<string, unknown> {
@@ -42,10 +44,19 @@ export function idOfFold(fold: SettingsFold): string {
return JSON.stringify(fold.path)
}
/** The schema type of a setting that folds open as a section of its own when written; null for one that is a row. */
function groupTypeOf(kind: ValueKind): string | null {
return kind.kind === 'object' && !isSpan(kind) ? kind.type : null
}
function itemTypeOf(kind: ValueKind): string | null {
return kind.kind === 'list' && kind.element.kind === 'object' ? kind.element.type : null
}
/**
* The sections of one object of a node and the objects inside it, in file order, each followed by those inside it. A
* setting that is itself an object whose type the schema describes is a section of its own one level deeper, and so is
* each element of a list of objects; one that is not written stays a field.
* setting written as an object whose type the schema describes is a section of its own one level deeper, and so is
* each element of a list of objects. Only what is written is listed; the rest can be added.
*/
export function foldedSections(section: NodeSettings, types: Record<string, SettingsType>, values: unknown): SettingsFold[] {
const folds: SettingsFold[] = []
@@ -56,7 +67,8 @@ export function foldedSections(section: NodeSettings, types: Record<string, Sett
type FoldHead = Pick<SettingsFold, 'title' | 'path' | 'type' | 'kind' | 'depth' | 'holder'>
function addFold(into: SettingsFold[], types: Record<string, SettingsType>, values: unknown, head: FoldHead, shownAsNodes: Set<string>): void {
const options: SettingOption[] = []
const settings: SettingOption[] = []
const unset: SettingOption[] = []
const inside: SettingsFold[] = []
const summary: string[] = []
for (const option of types[head.type]?.options ?? []) {
@@ -66,10 +78,18 @@ function addFold(into: SettingsFold[], types: Record<string, SettingsType>, valu
const path = [...head.path, option.name]
const value = valueAt(values, path)
const holder = { object: head.path, key: option.name }
const objectType = option.kind.kind === 'object' ? option.kind.type : null
const itemType = option.kind.kind === 'list' && option.kind.element.kind === 'object' ? option.kind.element.type : null
if (objectType !== null && isObject(value) && types[objectType] !== undefined) {
addFold(inside, types, values, { title: option.name, path, type: objectType, kind: 'group', depth: head.depth + 1, holder }, new Set())
const groupType = groupTypeOf(option.kind)
const itemType = itemTypeOf(option.kind)
if (value === undefined) {
if (option.required && groupType === null && itemType === null) {
settings.push(option)
} else {
unset.push(option)
}
continue
}
if (groupType !== null && isObject(value) && types[groupType] !== undefined) {
addFold(inside, types, values, { title: option.name, path, type: groupType, kind: 'group', depth: head.depth + 1, holder }, new Set())
continue
}
if (itemType !== null && isObjects(value) && types[itemType] !== undefined) {
@@ -77,12 +97,10 @@ function addFold(into: SettingsFold[], types: Record<string, SettingsType>, valu
summary.push(`${option.name} ${value.length}`)
continue
}
options.push(option)
if (value !== undefined) {
summary.push(`${option.name} ${shortText(option, value)}`)
}
settings.push(option)
summary.push(`${option.name} ${shortText(option, value)}`)
}
into.push({ ...head, summary: summary.slice(0, SUMMARY_SETTINGS).join(SUMMARY_SEPARATOR), options })
into.push({ ...head, summary: summary.slice(0, SUMMARY_SETTINGS).join(SUMMARY_SEPARATOR), settings, unset })
into.push(...inside)
}
@@ -104,7 +122,8 @@ function addList(into: SettingsFold[], types: Record<string, SettingsType>, valu
depth: list.depth,
summary: `${list.count} ${list.count === 1 ? 'item' : 'items'}`,
holder: list.holder,
options: []
settings: [],
unset: []
})
for (let index = 0; index < list.count; index++) {
addFold(
@@ -1,8 +1,14 @@
import { describe, expect, it } from 'vitest'
import type { ValueKind } from '../bridge/types'
import { literalOf, textOf } from './settingText'
import type { SettingOption, ValueKind } from '../bridge/types'
import { defaultLiteral, defaultText, literalOf, problemWith, SPAN_TYPE, textOf } from './settingText'
const roles: ValueKind = { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false }
const any: ValueKind = { kind: 'any' }
const span: ValueKind = { kind: 'object', type: SPAN_TYPE }
function option(kind: ValueKind, changes: Partial<SettingOption> = {}): SettingOption {
return { name: 'radius', description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind, ...changes }
}
describe('string lists', () => {
it('read as commas and are written back quoted', () => {
@@ -25,3 +31,61 @@ describe('text', () => {
expect(literalOf(text, 'wood "a"')).toBe('"wood \\"a\\""')
})
})
describe('ranges', () => {
it('show a [min, max] value and a span with a dash', () => {
expect(textOf(any, [5, 7])).toBe('5 – 7')
expect(textOf(span, { from: 0.45, to: 0.95 })).toBe('0.45 – 0.95')
expect(textOf(span, { to: 0.5 })).toBe('0 – 0.5')
})
it('are read back however the dash is typed', () => {
expect(literalOf(any, '2 – 4')).toBe('[2, 4]')
expect(literalOf(any, '2-4')).toBe('[2, 4]')
expect(literalOf(any, '2 to 4')).toBe('[2, 4]')
expect(literalOf(any, '-1, 3.5')).toBe('[-1, 3.5]')
expect(literalOf(span, '0.2 – 0.8')).toBe('{"from": 0.2, "to": 0.8}')
})
it('leave a plain number and a curve as typed', () => {
expect(literalOf(any, ' 3 ')).toBe('3')
expect(literalOf(any, '[[0, 1], [1, 0]]')).toBe('[[0, 1], [1, 0]]')
})
})
describe('defaults', () => {
it('start an added setting at its default, or at an empty value of its kind', () => {
expect(defaultLiteral(option(any, { defaultValue: 2 }))).toBe('2')
expect(defaultLiteral(option({ kind: 'boolean' }))).toBe('false')
expect(defaultLiteral(option({ kind: 'enum', constants: [{ name: 'ROUND', description: '' }] }))).toBe('"ROUND"')
expect(defaultLiteral(option(roles))).toBe('[]')
expect(defaultLiteral(option({ kind: 'object', type: 'Offset' }))).toBe('{}')
})
it('show what an unset setting falls back to, or nothing', () => {
expect(defaultText(option({ kind: 'text', format: 'PLAIN' }, { defaultValue: 'main' }))).toBe('main')
expect(defaultText(option(any))).toBe('')
})
})
describe('problemWith', () => {
it('holds a number to its kind and limits', () => {
const count = option({ kind: 'integer' }, { minimum: 1, maximum: 64 })
expect(problemWith(count, 'a')).toBe('Not a number')
expect(problemWith(count, '2.5')).toBe('Not a whole number')
expect(problemWith(count, '0')).toBe('At least 1')
expect(problemWith(count, '65')).toBe('At most 64')
expect(problemWith(count, '6')).toBeNull()
})
it('takes a number, a range or JSON for a value that may be a curve', () => {
expect(problemWith(option(any), '4 – 6')).toBeNull()
expect(problemWith(option(any), '[[0, 1]]')).toBeNull()
expect(problemWith(option(any), 'tall')).toBe('Takes a number, or a range like 4 – 6')
})
it('lets an empty draft through, since it unsets the setting', () => {
expect(problemWith(option({ kind: 'integer' }), ' ')).toBeNull()
})
})
+138 -8
View File
@@ -1,30 +1,71 @@
import type { ValueKind } from '../bridge/types'
import type { SettingOption, ValueKind } from '../bridge/types'
export const NOT_SET = ''
export const LIST_SEPARATOR = ', '
export const RANGE_DASH = ' – '
/** The schema type of a stretch along a part from 0 to 1, shown and typed as a range rather than folded open. */
export const SPAN_TYPE = 'art.arcane.iris.generation.procedural.part.ProceduralSpan'
const NUMBER = '(-?\\d+(?:\\.\\d+)?)'
const RANGE = new RegExp(`^\\s*${NUMBER}\\s*(?:–|—|\\.\\.|to|,|-)\\s*${NUMBER}\\s*$`)
const RANGE_SIZE = 2
const SPAN_FROM = 'from'
const SPAN_TO = 'to'
const SPAN_DEFAULT_FROM = 0
const SPAN_DEFAULT_TO = 1
/** Whether {@code kind} is a string naming something, typed as text. */
export function isText(kind: ValueKind): boolean {
return kind.kind === 'text' || kind.kind === 'reference' || kind.kind === 'resource'
}
export function isNumber(kind: ValueKind): boolean {
return kind.kind === 'integer' || kind.kind === 'decimal'
}
/** Whether {@code kind} is a list of strings, such as the roles a decoration goes on, which is typed as {@code a, b}. */
export function isStringList(kind: ValueKind): boolean {
return kind.kind === 'list' && isText(kind.element)
}
/** Whether {@code kind} is a stretch from 0 to 1, written {@code {"from": a, "to": b}} and typed {@code a – b}. */
export function isSpan(kind: ValueKind): boolean {
return kind.kind === 'object' && kind.type === SPAN_TYPE
}
function isStrings(value: unknown): value is string[] {
return Array.isArray(value) && value.every((element) => typeof element === 'string')
}
/** What the field shows for the value the file holds. */
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/** The two ends of a {@code [min, max]} value, or of a span; null for anything else. */
export function rangeOf(kind: ValueKind, value: unknown): [number, number] | null {
if (kind.kind === 'any' && Array.isArray(value) && value.length === RANGE_SIZE && value.every((end) => typeof end === 'number')) {
return [value[0], value[1]]
}
if (!isSpan(kind) || !isRecord(value)) {
return null
}
const from = value[SPAN_FROM] ?? SPAN_DEFAULT_FROM
const to = value[SPAN_TO] ?? SPAN_DEFAULT_TO
return typeof from === 'number' && typeof to === 'number' ? [from, to] : null
}
/** What the node shows for the value the file holds: strings unquoted, ranges as {@code 2 – 4}, anything else as JSON. */
export function textOf(kind: ValueKind, value: unknown): string {
if (value === undefined) {
return NOT_SET
}
if (isText(kind) && typeof value === 'string') {
if ((isText(kind) || kind.kind === 'enum') && typeof value === 'string') {
return value
}
const range = rangeOf(kind, value)
if (range !== null) {
return range.join(RANGE_DASH)
}
return isStringList(kind) && isStrings(value) ? value.join(LIST_SEPARATOR) : JSON.stringify(value)
}
@@ -36,13 +77,102 @@ export function itemsOf(draft: string): string[] {
.filter((item) => item !== '')
}
/** What the field holds as JSON to write; a list typed as {@code a, b} is written as an array unless it already is one. */
/**
* What was typed as JSON to write. A range may be typed {@code 2 – 4}, {@code 2-4}, {@code 2 to 4} or {@code 2, 4}; a
* list typed as {@code a, b} or without its brackets gets them.
*/
export function literalOf(kind: ValueKind, draft: string): string {
if (isText(kind)) {
if (isText(kind) || kind.kind === 'enum') {
return JSON.stringify(draft)
}
if (isStringList(kind) && !draft.trim().startsWith('[')) {
return JSON.stringify(itemsOf(draft))
const typed = draft.trim()
if (isStringList(kind) && !typed.startsWith('[')) {
return JSON.stringify(itemsOf(typed))
}
const range = RANGE.exec(typed)
if (range !== null && kind.kind === 'any') {
return `[${range[1]}, ${range[2]}]`
}
if (range !== null && isSpan(kind)) {
return `{"${SPAN_FROM}": ${range[1]}, "${SPAN_TO}": ${range[2]}}`
}
return !isJson(typed) && isJson(`[${typed}]`) ? `[${typed}]` : typed
}
/** What a setting added from the node starts at: its default, or an empty value of its kind when it has none. */
export function defaultLiteral(option: SettingOption): string {
if (option.defaultValue !== null && option.defaultValue !== undefined) {
return JSON.stringify(option.defaultValue)
}
return placeholderOf(option.kind)
}
function placeholderOf(kind: ValueKind): string {
switch (kind.kind) {
case 'boolean':
return 'false'
case 'text':
case 'reference':
case 'resource':
return '""'
case 'enum':
return JSON.stringify(kind.constants[0]?.name ?? '')
case 'list':
return '[]'
case 'integer':
case 'decimal':
case 'any':
return '0'
default:
return '{}'
}
}
/** What an unset setting falls back to, as the node shows it; empty when it has no default. */
export function defaultText(option: SettingOption): string {
return option.defaultValue === null || option.defaultValue === undefined ? NOT_SET : textOf(option.kind, option.defaultValue)
}
/** Why {@code draft} can't be written as the value of {@code option}, or null when it can; an empty draft unsets it. */
export function problemWith(option: SettingOption, draft: string): string | null {
const { kind } = option
if (draft.trim() === NOT_SET || isText(kind) || kind.kind === 'enum') {
return null
}
if (isNumber(kind)) {
return numberProblem(option, draft)
}
if (isJson(literalOf(kind, draft))) {
return null
}
if (kind.kind === 'any') {
return `Takes a number, or a range like 4${RANGE_DASH}6`
}
return isSpan(kind) ? `Takes a stretch from 0 to 1, like 0.2${RANGE_DASH}0.8` : 'Not JSON'
}
function numberProblem(option: SettingOption, draft: string): string | null {
const number = Number(draft)
if (!Number.isFinite(number)) {
return 'Not a number'
}
if (option.kind.kind === 'integer' && !Number.isInteger(number)) {
return 'Not a whole number'
}
if (option.minimum !== null && number < option.minimum) {
return `At least ${option.minimum}`
}
if (option.maximum !== null && number > option.maximum) {
return `At most ${option.maximum}`
}
return null
}
function isJson(text: string): boolean {
try {
JSON.parse(text)
return true
} catch {
return false
}
return draft.trim()
}
@@ -32,8 +32,8 @@ describe('suggestionSourceOf', () => {
it('takes the roles for the settings that name one', () => {
const on = option('on', { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false })
expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', on)).toEqual({ from: 'roles' })
expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', option('at', { kind: 'text', format: 'PLAIN' }))).toBeNull()
expect(suggestionSourceOf('art.arcane.iris.generation.procedural.part.ProceduralDecoration', on)).toEqual({ from: 'roles' })
expect(suggestionSourceOf('art.arcane.iris.generation.procedural.part.ProceduralDecoration', option('at', { kind: 'text', format: 'PLAIN' }))).toBeNull()
})
it('takes the elements of a list of references, and nothing for free text', () => {
@@ -6,9 +6,9 @@ export type SuggestionSource = { from: 'reference'; reference: string } | { from
/** Settings that name a role of the object being edited, by the schema type and option (ProceduralPart, ProceduralMaterial and ProceduralDecoration). */
const ROLE_OPTIONS: ReadonlySet<string> = new Set([
'art.arcane.iris.engine.procedural.part.ProceduralPart.role',
'art.arcane.iris.engine.procedural.part.ProceduralMaterial.role',
'art.arcane.iris.engine.procedural.part.ProceduralDecoration.on'
'art.arcane.iris.generation.procedural.part.ProceduralPart.role',
'art.arcane.iris.generation.procedural.part.ProceduralMaterial.role',
'art.arcane.iris.generation.procedural.part.ProceduralDecoration.on'
])
/** A source the server lists, as opposed to the roles, which the studio reads from the nodes. */
@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-6
View File
@@ -1,6 +0,0 @@
The icons in this folder and its subfolders come from the IntelliJ Platform (https://github.com/JetBrains/intellij-community),
platform/icons/src/expui, Copyright 2000-2023 JetBrains s.r.o. and contributors,
used under the Apache License 2.0 (LICENSE-APACHE-2.0.txt).
memory.svg is profileMemory.svg with its profiling badge removed.
theme.svg, blocks.svg, borders.svg, shading.svg, mob.svg, actualZoom.svg, decoration.svg, and in views/ biomes.svg, regions.svg,
world-3d.svg, saved-world.svg, noise.svg and objects.svg are the studio's own, drawn to match.
@@ -1,5 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.5 5.5L4.5 4V12M10.5 5.5L12.5 4V12" stroke="#6C707E" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="7.75" cy="6.5" r="0.75" fill="#6C707E"/>
<circle cx="7.75" cy="10.5" r="0.75" fill="#6C707E"/>
</svg>

Before

Width:  |  Height:  |  Size: 323 B

@@ -1,5 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.5 5.5L4.5 4V12M10.5 5.5L12.5 4V12" stroke="#CED0D6" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="7.75" cy="6.5" r="0.75" fill="#CED0D6"/>
<circle cx="7.75" cy="10.5" r="0.75" fill="#CED0D6"/>
</svg>

Before

Width:  |  Height:  |  Size: 323 B

-4
View File
@@ -1,4 +0,0 @@
<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.5 1C7.77614 1 8 1.22386 8 1.5V7H13.5C13.7761 7 14 7.22386 14 7.5C14 7.77614 13.7761 8 13.5 8H8V13.5C8 13.7761 7.77614 14 7.5 14C7.22386 14 7 13.7761 7 13.5V8H1.5C1.22386 8 1 7.77614 1 7.5C1 7.22386 1.22386 7 1.5 7H7V1.5C7 1.22386 7.22386 1 7.5 1Z" fill="#6C707E"/>
</svg>

Before

Width:  |  Height:  |  Size: 547 B

@@ -1,4 +0,0 @@
<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.5 1C7.77614 1 8 1.22386 8 1.5V7H13.5C13.7761 7 14 7.22386 14 7.5C14 7.77614 13.7761 8 13.5 8H8V13.5C8 13.7761 7.77614 14 7.5 14C7.22386 14 7 13.7761 7 13.5V8H1.5C1.22386 8 1 7.77614 1 7.5C1 7.22386 1.22386 7 1.5 7H7V1.5C7 1.22386 7.22386 1 7.5 1Z" fill="#CED0D6"/>
</svg>

Before

Width:  |  Height:  |  Size: 547 B

-4
View File
@@ -1,4 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 1.5L13.5 4.5V11.5L8 14.5L2.5 11.5V4.5L8 1.5Z" stroke="#6C707E" stroke-linejoin="round"/>
<path d="M2.5 4.5L8 7.5L13.5 4.5M8 7.5V14.5" stroke="#6C707E" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 292 B

@@ -1,4 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 1.5L13.5 4.5V11.5L8 14.5L2.5 11.5V4.5L8 1.5Z" stroke="#CED0D6" stroke-linejoin="round"/>
<path d="M2.5 4.5L8 7.5L13.5 4.5M8 7.5V14.5" stroke="#CED0D6" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 292 B

@@ -1,3 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.5 5V3.5C2.5 2.95 2.95 2.5 3.5 2.5H5M7 2.5H9M11 2.5H12.5C13.05 2.5 13.5 2.95 13.5 3.5V5M13.5 7V9M13.5 11V12.5C13.5 13.05 13.05 13.5 12.5 13.5H11M9 13.5H7M5 13.5H3.5C2.95 13.5 2.5 13.05 2.5 12.5V11M2.5 9V7" stroke="#6C707E" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 362 B

@@ -1,3 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.5 5V3.5C2.5 2.95 2.95 2.5 3.5 2.5H5M7 2.5H9M11 2.5H12.5C13.05 2.5 13.5 2.95 13.5 3.5V5M13.5 7V9M13.5 11V12.5C13.5 13.05 13.05 13.5 12.5 13.5H11M9 13.5H7M5 13.5H3.5C2.95 13.5 2.5 13.05 2.5 12.5V11M2.5 9V7" stroke="#CED0D6" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 362 B

@@ -1,4 +0,0 @@
<!-- Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.5 8.25L6 11.75L13.5 4.25" stroke="#6C707E" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 353 B

Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff. Show more