diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java index 3beda8396..a2b411f2a 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java @@ -21,6 +21,7 @@ package art.arcane.iris.modded; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.pack.PackValidationRegistry; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.modded.toolworld.ModdedToolPainting; import art.arcane.iris.engine.framework.NativeFeatureGenerationPolicy; import art.arcane.iris.engine.framework.GenerationSessionException; import art.arcane.iris.engine.framework.GenerationSessionLease; @@ -134,6 +135,7 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { private volatile ModdedDimensionMetadata.ConfiguredPack configuredPack; private volatile ModdedDimensionMetadata.DimensionMetadata heightMetadata; private volatile ServerLevel boundLevel; + private volatile ModdedToolPainting toolPainting; public IrisModdedChunkGenerator(BiomeSource biomeSource, String dimensionKey) { this(biomeSource, dimensionKey, new IrisModdedBiomeSource(biomeSource)); @@ -165,6 +167,11 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { this.activeDimensionKey = defaultDimensionKey; } + /** Makes the chunks of this generator whatever {@code painting} paints, and nothing else: no structures, features or mobs. Null gives them back to the pack. */ + public void paintWith(ModdedToolPainting painting) { + this.toolPainting = painting; + } + public synchronized void repoint(String pack, String packDimensionKey, long seed) { ServerLevel level = boundLevel(); if (level != null) { @@ -797,6 +804,10 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public CompletableFuture fillFromNoise(Blender blender, RandomState randomState, StructureManager structureManager, ChunkAccess chunk) { + ModdedToolPainting painting = toolPainting; + if (painting != null) { + return CompletableFuture.completedFuture(painting.paint(chunk, boundLevel())); + } Engine generationEngine = engine(); ChunkPos pos = chunk.getPos(); lastChunkGenAt = System.currentTimeMillis(); @@ -928,6 +939,9 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public void applyBiomeDecoration(WorldGenLevel level, ChunkAccess chunk, StructureManager structureManager) { + if (toolPainting != null) { + return; + } Engine current = engine(); importedFeatures.prepare(current); try (GenerationSessionLease lease = requireGenerationLease(current, "modded_biome_decoration"); @@ -942,6 +956,9 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public void createStructures(RegistryAccess registryAccess, ChunkGeneratorStructureState structureState, StructureManager structureManager, ChunkAccess chunk, StructureTemplateManager templateManager, ResourceKey levelKey) { + if (toolPainting != null) { + return; + } Engine current = engine(levelKey); try (GenerationSessionLease lease = requireGenerationLease(current, "modded_create_structures"); IrisContext.Scope ignored = IrisContext.open(current, lease.sessionId(), null)) { @@ -966,6 +983,9 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public void createReferences(WorldGenLevel level, StructureManager structureManager, ChunkAccess chunk) { + if (toolPainting != null) { + return; + } Engine current = engine(level.getLevel()); try (GenerationSessionLease lease = requireGenerationLease(current, "modded_create_references"); IrisContext.Scope ignored = IrisContext.open(current, lease.sessionId(), null)) { @@ -980,6 +1000,9 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public void spawnOriginalMobs(WorldGenRegion region) { + if (toolPainting != null) { + return; + } Registry registry = region.registryAccess().lookupOrThrow(Registries.BIOME); spawnTables.initializeVanillaSpawnBiomes(registry); ChunkPos center = region.getCenter(); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java index 134939c0a..86c64df1e 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java @@ -21,6 +21,7 @@ package art.arcane.iris.modded; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.modded.toolworld.ModdedToolPainting; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.Registry; @@ -120,7 +121,9 @@ public final class ModdedDimensionManager { return generator.commandEngine(); } - public static Handle create(MinecraftServer server, String dimensionId, String pack, String packDimensionKey, long seed) { + /** Makes the runtime dimension {@code dimensionId} generate {@code pack}, with chunks that come only from {@code painting} when it is not null. */ + public static Handle create(MinecraftServer server, String dimensionId, String pack, String packDimensionKey, long seed, + ModdedToolPainting painting) { ModdedStartup.requirePackForWorldCreation(pack); ModdedServerAccess serverAccess = requireAccess(); synchronized (LOCK) { @@ -145,7 +148,7 @@ public final class ModdedDimensionManager { } try { - Handle handle = inject(server, serverAccess, dimensionId, key, pack, packDimensionKey, seed); + Handle handle = inject(server, serverAccess, dimensionId, key, pack, packDimensionKey, seed, painting); HANDLES.put(dimensionId, handle); ModdedIrisLog.info("Iris injected runtime dimension '{}' (pack={} dim={} seed={})", dimensionId, pack, packDimensionKey, seed); return handle; @@ -156,6 +159,10 @@ public final class ModdedDimensionManager { } } + public static Handle create(MinecraftServer server, String dimensionId, String pack, String packDimensionKey, long seed) { + return create(server, dimensionId, pack, packDimensionKey, seed, null); + } + public static Handle createPersistent(MinecraftServer server, String dimensionId, String pack, String packDimensionKey, long seed) { ModdedDimensionRegistryStore.PersistentDimension previous = ModdedDimensionRegistryStore.get(server, dimensionId); @@ -558,13 +565,15 @@ public final class ModdedDimensionManager { } } - private static Handle inject(MinecraftServer server, ModdedServerAccess serverAccess, String dimensionId, ResourceKey key, String pack, String packDimensionKey, long seed) { + private static Handle inject(MinecraftServer server, ModdedServerAccess serverAccess, String dimensionId, ResourceKey key, String pack, String packDimensionKey, long seed, + ModdedToolPainting painting) { RegistryAccess registryAccess = server.registryAccess(); Holder dimensionType = resolveDimensionType(registryAccess, pack, packDimensionKey); Holder plains = registryAccess.lookupOrThrow(Registries.BIOME).getOrThrow(Biomes.PLAINS); FixedBiomeSource biomeSource = new FixedBiomeSource(plains); String generatorRef = pack.equals(packDimensionKey) ? pack : pack + ":" + packDimensionKey; IrisModdedChunkGenerator generator = new IrisModdedChunkGenerator(biomeSource, generatorRef); + generator.paintWith(painting); generator.repoint(pack, packDimensionKey, seed); LevelStem stem = new LevelStem(dimensionType, generator); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java index 4e7d62496..2c6f8f802 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java @@ -38,6 +38,10 @@ import art.arcane.iris.modded.command.ModdedPregenBossBar; import art.arcane.iris.modded.command.ModdedPregenJob; import art.arcane.iris.modded.command.ModdedStudioCommands; import art.arcane.iris.modded.command.ModdedWandService; +import art.arcane.iris.modded.structure.ModdedPlatformStructures; +import art.arcane.iris.modded.toolworld.ModdedToolWorldService; +import art.arcane.iris.core.tooling.ToolWorldsHost; +import com.volmit.tooling.PlatformStructures; import art.arcane.iris.modded.service.ModdedChunkUpdateService; import art.arcane.iris.modded.service.ModdedEngineMaintenanceService; import art.arcane.iris.modded.service.ModdedEntitySpawnService; @@ -146,6 +150,7 @@ public final class ModdedEngineBootstrap { } public static void levelUnloaded(ServerLevel level) { + ModdedToolWorldService.levelUnloaded(level); if (!(level.getChunkSource().getGenerator() instanceof IrisModdedChunkGenerator generator)) { return; } @@ -383,11 +388,15 @@ public final class ModdedEngineBootstrap { createdServices.register(ModdedChunkUpdateService.class, new ModdedChunkUpdateService()); createdServices.register(ModdedEntitySpawnService.class, new ModdedEntitySpawnService()); createdServices.register(ModdedTreeFellerService.class, new ModdedTreeFellerService()); + ModdedToolWorldService toolWorlds = createdServices.register( + ModdedToolWorldService.class, new ModdedToolWorldService()); bindService(PreservationRegistry.class, preservation, rollback); bindService(EngineEffectsProvider.class, (EngineEffectsProvider) ModdedEngineEffects::new, rollback); bindService(EnginePlatformHooks.class, studioHotloadService, rollback); + bindService(ToolWorldsHost.class, toolWorlds, rollback); + bindService(PlatformStructures.class, new ModdedPlatformStructures(), rollback); bindService(EngineWorldManagerProvider.class, (EngineWorldManagerProvider) (Engine engine) -> new ModdedWorldManager(engine), rollback); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java index 6c88ec510..2bcb5b5ed 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java @@ -34,6 +34,7 @@ import art.arcane.iris.modded.ModdedDimensionManager; import art.arcane.iris.modded.ModdedEngineBootstrap; import art.arcane.iris.modded.ModdedScheduler; import art.arcane.iris.modded.ModdedWorkspaceGenerator; +import art.arcane.iris.modded.toolworld.ModdedToolWorldService; import art.arcane.iris.util.common.parallel.BurstExecutor; import art.arcane.iris.util.common.parallel.MultiBurst; import art.arcane.volmlib.util.collection.KMap; @@ -56,6 +57,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -329,10 +331,16 @@ public final class ModdedStudioCommands { UUID owner = player == null ? CONSOLE_OWNER : player.getUUID(); String dimensionId = player == null ? studioConsoleDimensionId() : studioDimensionId(player); MinecraftServer server = source.getServer(); + Optional toolWorldRefusal = ModdedToolWorldService.studioChangeRefusal(); + if (toolWorldRefusal.isPresent()) { + IrisModdedCommands.fail(source, toolWorldRefusal.get()); + return 0; + } IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_STUDIO_SEED, MessageArgument.untrusted("pack", pack), MessageArgument.untrusted("seed", seed))); CompletableFuture transition = TRANSITIONS.submit( owner, - () -> openTransition(source, server, owner, dimensionId, pack, seed)); + () -> ModdedToolWorldService.closeForStudioChange(Optional.ofNullable(player)) + .thenCompose(ignored -> openTransition(source, server, owner, dimensionId, pack, seed))); reportOpenFailure(source, server, dimensionId, pack, transition); return 1; } @@ -531,7 +539,13 @@ public final class ModdedStudioCommands { ServerPlayer player = source.getPlayer(); MinecraftServer server = source.getServer(); UUID owner = player == null ? CONSOLE_OWNER : player.getUUID(); - TRANSITIONS.submit(owner, () -> closeTransition(source, server, owner)); + Optional toolWorldRefusal = ModdedToolWorldService.studioChangeRefusal(); + if (toolWorldRefusal.isPresent()) { + IrisModdedCommands.fail(source, toolWorldRefusal.get()); + return 0; + } + TRANSITIONS.submit(owner, () -> ModdedToolWorldService.closeForStudioChange(Optional.ofNullable(player)) + .thenCompose(ignored -> closeTransition(source, server, owner))); return 1; } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java index 07d7cb3ae..0e5656549 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java @@ -22,6 +22,7 @@ import art.arcane.iris.core.tooling.SenderWorld; import art.arcane.iris.core.tooling.ServedPack; import art.arcane.iris.core.tooling.ToolingSender; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.modded.toolworld.ModdedToolWorldService; import com.volmit.tooling.world.ToolPlayer; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.Component; @@ -30,14 +31,14 @@ import java.util.Optional; /** * A modded source of a tooling command. It reads the world of the source when it is built, on the server thread that - * received the command, and delivers messages on the server thread. A modded platform has no studio and no tool - * players yet: tool worlds are not supported there, so {@link #player()} is empty. + * received the command, and delivers messages on the server thread. A player sends as a tool player, which is how a + * tool world opens for them; the console is none. */ -final class ModdedToolingSender implements ToolingSender { +public final class ModdedToolingSender implements ToolingSender { private final CommandSourceStack source; private final Optional world; - ModdedToolingSender(CommandSourceStack source) { + public ModdedToolingSender(CommandSourceStack source) { this.source = source; this.world = Optional.ofNullable(IrisModdedCommands.engineFor(source.getLevel())) .filter(engine -> !engine.isClosed()) @@ -74,7 +75,7 @@ final class ModdedToolingSender implements ToolingSender { @Override public Optional player() { - return Optional.empty(); + return Optional.ofNullable(source.getPlayer()).map(ModdedToolWorldService::toolPlayerOf); } @Override diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/AbstractContainerMenuToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/AbstractContainerMenuToolMixin.java new file mode 100644 index 000000000..944e43564 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/AbstractContainerMenuToolMixin.java @@ -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 . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ContainerInput; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** Clicks in the inventory of a container block of a tool world are put to the tool; closing one tells it the contents may have changed. */ +@Mixin(AbstractContainerMenu.class) +public abstract class AbstractContainerMenuToolMixin { + @Inject(method = "clicked", at = @At("HEAD"), cancellable = true) + private void iris$askAboutContainerClick(int slot, int button, ContainerInput input, Player player, CallbackInfo info) { + if (player instanceof ServerPlayer serverPlayer + && !ToolWorldHooks.containerClickAllowed(serverPlayer, (AbstractContainerMenu) (Object) this)) { + info.cancel(); + ((AbstractContainerMenu) (Object) this).sendAllDataToRemote(); + } + } + + @Inject(method = "removed", at = @At("RETURN")) + private void iris$tellAboutClosedContainer(Player player, CallbackInfo info) { + ToolWorldHooks.containerClosed(player, (AbstractContainerMenu) (Object) this); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BlockItemToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BlockItemToolMixin.java new file mode 100644 index 000000000..d8bbdece6 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BlockItemToolMixin.java @@ -0,0 +1,64 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** A player placing a block in a tool world: the tool is asked about the block before it is placed, once. */ +@Mixin(BlockItem.class) +public abstract class BlockItemToolMixin { + @Shadow + public abstract BlockPlaceContext updatePlacementContext(BlockPlaceContext context); + + @Shadow + protected abstract BlockState getPlacementState(BlockPlaceContext context); + + @Inject(method = "place", at = @At("HEAD"), cancellable = true) + private void iris$askAboutPlacement(BlockPlaceContext context, CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(context.getLevel())) { + return; + } + BlockPlaceContext updated = updatePlacementContext(context); + if (updated == null) { + ToolWorldGuard.enter(context.getLevel(), Cause.PLACE, context.getPlayer(), true); + return; + } + if (!ToolWorldHooks.placeAllowed(context.getLevel(), context.getPlayer(), updated.getClickedPos(), getPlacementState(updated))) { + result.setReturnValue(InteractionResult.FAIL); + return; + } + ToolWorldGuard.enter(context.getLevel(), Cause.PLACE, context.getPlayer(), true); + } + + @Inject(method = "place", at = @At("RETURN")) + private void iris$endPlacement(BlockPlaceContext context, CallbackInfoReturnable result) { + ToolWorldGuard.exit(context.getLevel()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BrewingStandToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BrewingStandToolMixin.java new file mode 100644 index 000000000..aa40413ce --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BrewingStandToolMixin.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BrewingStandBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A brewing stand of a tool world works only while the tool lets machines work there. */ +@Mixin(BrewingStandBlockEntity.class) +public abstract class BrewingStandToolMixin { + @Inject(method = "serverTick", at = @At("HEAD"), cancellable = true) + private static void iris$askAboutBrewingStand(Level level, BlockPos position, BlockState state, + BrewingStandBlockEntity stand, CallbackInfo info) { + if (!ToolWorldHooks.machineAllowed(level, position)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BucketItemToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BucketItemToolMixin.java new file mode 100644 index 000000000..165fa6ef4 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BucketItemToolMixin.java @@ -0,0 +1,71 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.BucketItem; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.BlockHitResult; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** + * Buckets in a tool world. Filling a bucket changes the block it is aimed at, so each change in its use is put to the tool as + * a bucket change. Emptying one is put to the tool before the fluid is placed, once. + */ +@Mixin(BucketItem.class) +public abstract class BucketItemToolMixin { + @Inject(method = "use", at = @At("HEAD")) + private void iris$beginBucketUse(Level level, Player player, InteractionHand hand, CallbackInfoReturnable result) { + ToolWorldGuard.enter(level, Cause.BUCKET, player, false); + } + + @Inject(method = "use", at = @At("RETURN")) + private void iris$endBucketUse(Level level, Player player, InteractionHand hand, CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } + + @Inject(method = "emptyContents", at = @At("HEAD"), cancellable = true) + private void iris$askAboutEmptying(LivingEntity user, Level level, BlockPos position, BlockHitResult hit, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(level)) { + return; + } + if (!ToolWorldHooks.bucketEmptyAllowed(level, user, position)) { + result.setReturnValue(false); + return; + } + ToolWorldGuard.enter(level, Cause.BUCKET, user, true); + } + + @Inject(method = "emptyContents", at = @At("RETURN")) + private void iris$endEmptying(LivingEntity user, Level level, BlockPos position, BlockHitResult hit, + CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CommandsToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CommandsToolMixin.java new file mode 100644 index 000000000..fc8ca310a --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CommandsToolMixin.java @@ -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 . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A command a player types in a tool world, or anyone types while one is open, is put to the tool before it runs. */ +@Mixin(Commands.class) +public abstract class CommandsToolMixin { + @Inject(method = "performPrefixedCommand", at = @At("HEAD"), cancellable = true) + private void iris$askAboutCommand(CommandSourceStack source, String command, CallbackInfo info) { + if (!ToolWorldHooks.commandAllowed(source, command)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CrafterToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CrafterToolMixin.java new file mode 100644 index 000000000..d003a82ec --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CrafterToolMixin.java @@ -0,0 +1,40 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.CrafterBlock; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A crafter of a tool world crafts only while the tool lets machines work there. */ +@Mixin(CrafterBlock.class) +public abstract class CrafterToolMixin { + @Inject(method = "dispenseFrom", at = @At("HEAD"), cancellable = true) + private void iris$askAboutCrafter(BlockState state, ServerLevel level, BlockPos position, CallbackInfo info) { + if (!ToolWorldHooks.machineAllowed(level, position)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/DispenserToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/DispenserToolMixin.java new file mode 100644 index 000000000..abb3d029c --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/DispenserToolMixin.java @@ -0,0 +1,40 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.DispenserBlock; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A dispenser or dropper of a tool world fires only while the tool lets machines work there. */ +@Mixin(DispenserBlock.class) +public abstract class DispenserToolMixin { + @Inject(method = "dispenseFrom", at = @At("HEAD"), cancellable = true) + private void iris$askAboutDispenser(ServerLevel level, BlockState state, BlockPos position, CallbackInfo info) { + if (!ToolWorldHooks.machineAllowed(level, position)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/EntityToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/EntityToolMixin.java new file mode 100644 index 000000000..838e2ec67 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/EntityToolMixin.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.Portal; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A tool world has no portals: nothing standing in one is taken anywhere. */ +@Mixin(Entity.class) +public abstract class EntityToolMixin { + @Inject(method = "setAsInsidePortal", at = @At("HEAD"), cancellable = true) + private void iris$keepToolWorldFreeOfPortals(Portal portal, BlockPos position, CallbackInfo info) { + if (ToolWorldGuard.isToolWorld(((Entity) (Object) this).level())) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/FurnaceToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/FurnaceToolMixin.java new file mode 100644 index 000000000..c9fa834b7 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/FurnaceToolMixin.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A furnace of a tool world works only while the tool lets machines work there. */ +@Mixin(AbstractFurnaceBlockEntity.class) +public abstract class FurnaceToolMixin { + @Inject(method = "serverTick", at = @At("HEAD"), cancellable = true) + private static void iris$askAboutFurnace(ServerLevel level, BlockPos position, BlockState state, + AbstractFurnaceBlockEntity furnace, CallbackInfo info) { + if (!ToolWorldHooks.machineAllowed(level, position)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelChunkToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelChunkToolMixin.java new file mode 100644 index 000000000..0549bdd6b --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelChunkToolMixin.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ModdedToolWorldService; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.chunk.LevelChunk; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A chunk that becomes live in a tool world is told to the tool. */ +@Mixin(LevelChunk.class) +public abstract class LevelChunkToolMixin { + @Inject(method = "setLoaded", at = @At("RETURN")) + private void iris$tellAboutLoadedChunk(boolean loaded, CallbackInfo info) { + LevelChunk chunk = (LevelChunk) (Object) this; + if (loaded && chunk.getLevel() instanceof ServerLevel level) { + ModdedToolWorldService.chunkLoaded(level, chunk.getPos().x(), chunk.getPos().z()); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelToolMixin.java new file mode 100644 index 000000000..41cfd3d25 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelToolMixin.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** Every change to a block of a tool world passes the tool world guard, which is where a tool world stays frozen. */ +@Mixin(Level.class) +public abstract class LevelToolMixin { + @Inject( + method = "setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;II)Z", + at = @At("HEAD"), + cancellable = true) + private void iris$guardToolWorldBlock(BlockPos position, BlockState state, int flags, int recursionLeft, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.setBlockAllowed((Level) (Object) this, position, state)) { + result.setReturnValue(false); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/NaturalSpawnerToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/NaturalSpawnerToolMixin.java new file mode 100644 index 000000000..75e8877f4 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/NaturalSpawnerToolMixin.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.NaturalSpawner; +import net.minecraft.world.level.chunk.LevelChunk; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.List; + +/** Nothing spawns naturally in a tool world. */ +@Mixin(NaturalSpawner.class) +public abstract class NaturalSpawnerToolMixin { + @Inject(method = "spawnForChunk", at = @At("HEAD"), cancellable = true) + private static void iris$keepToolWorldFreeOfMobs(ServerLevel level, LevelChunk chunk, NaturalSpawner.SpawnState state, + List categories, CallbackInfo info) { + if (ToolWorldGuard.isToolWorld(level)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/PistonBaseBlockToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/PistonBaseBlockToolMixin.java new file mode 100644 index 000000000..c3dff1779 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/PistonBaseBlockToolMixin.java @@ -0,0 +1,54 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.piston.PistonBaseBlock; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** A piston in a tool world asks the tool about every block it moves before it moves any, so it never moves half a structure. */ +@Mixin(PistonBaseBlock.class) +public abstract class PistonBaseBlockToolMixin { + @Inject(method = "moveBlocks", at = @At("HEAD"), cancellable = true) + private void iris$askAboutPiston(Level level, BlockPos position, Direction direction, boolean extending, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(level)) { + return; + } + if (!ToolWorldHooks.pistonMoveAllowed(level, position, direction, extending)) { + result.setReturnValue(false); + return; + } + ToolWorldGuard.enter(level, Cause.PISTON, null, true); + } + + @Inject(method = "moveBlocks", at = @At("RETURN")) + private void iris$endPiston(Level level, BlockPos position, Direction direction, boolean extending, + CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/SaplingBlockToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/SaplingBlockToolMixin.java new file mode 100644 index 000000000..6ba3a2a8f --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/SaplingBlockToolMixin.java @@ -0,0 +1,45 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.block.SaplingBlock; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A sapling growing into a tree in a tool world changes blocks as growth. */ +@Mixin(SaplingBlock.class) +public abstract class SaplingBlockToolMixin { + @Inject(method = "advanceTree", at = @At("HEAD")) + private void iris$beginTreeGrowth(ServerLevel level, BlockPos position, BlockState state, RandomSource random, CallbackInfo info) { + ToolWorldGuard.enter(level, Cause.GROWTH, null, false); + } + + @Inject(method = "advanceTree", at = @At("RETURN")) + private void iris$endTreeGrowth(ServerLevel level, BlockPos position, BlockState state, RandomSource random, CallbackInfo info) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerExplosionToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerExplosionToolMixin.java new file mode 100644 index 000000000..e8b4ce8c7 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerExplosionToolMixin.java @@ -0,0 +1,48 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.ServerExplosion; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** An explosion in a tool world puts each block it would destroy to the tool as an explosion change. */ +@Mixin(ServerExplosion.class) +public abstract class ServerExplosionToolMixin { + @Shadow + @Final + private ServerLevel level; + + @Inject(method = "explode", at = @At("HEAD")) + private void iris$beginExplosion(CallbackInfoReturnable result) { + ToolWorldGuard.enter(level, Cause.EXPLOSION, null, false); + } + + @Inject(method = "explode", at = @At("RETURN")) + private void iris$endExplosion(CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerGamePacketListenerToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerGamePacketListenerToolMixin.java new file mode 100644 index 000000000..33ebb5f3b --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerGamePacketListenerToolMixin.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A swing of the arm is the left click at nothing the tool hears about, unless it is aimed at a block. */ +@Mixin(ServerGamePacketListenerImpl.class) +public abstract class ServerGamePacketListenerToolMixin { + @Shadow + public ServerPlayer player; + + @Inject(method = "handleAnimate", at = @At("HEAD")) + private void iris$tellAboutSwing(ServerboundSwingPacket packet, CallbackInfo info) { + ToolWorldHooks.leftClickAir(player, packet.getHand()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerLevelToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerLevelToolMixin.java new file mode 100644 index 000000000..832776e24 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerLevelToolMixin.java @@ -0,0 +1,86 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.material.Fluid; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** + * The ticks of a tool world. Each kind of tick names the cause of the block changes inside it, so the tool is asked about + * them as that cause; and the tool world keeps its weather off. + */ +@Mixin(ServerLevel.class) +public abstract class ServerLevelToolMixin { + @Inject(method = "tickFluid", at = @At("HEAD")) + private void iris$beginFluidTick(BlockPos position, Fluid fluid, CallbackInfo info) { + ToolWorldGuard.enter((ServerLevel) (Object) this, Cause.FLUID, null, false); + } + + @Inject(method = "tickFluid", at = @At("RETURN")) + private void iris$endFluidTick(BlockPos position, Fluid fluid, CallbackInfo info) { + ToolWorldGuard.exit((ServerLevel) (Object) this); + } + + @Inject(method = "tickBlock", at = @At("HEAD")) + private void iris$beginBlockTick(BlockPos position, Block block, CallbackInfo info) { + ToolWorldGuard.enter((ServerLevel) (Object) this, null, null, false); + } + + @Inject(method = "tickBlock", at = @At("RETURN")) + private void iris$endBlockTick(BlockPos position, Block block, CallbackInfo info) { + ToolWorldGuard.exit((ServerLevel) (Object) this); + } + + @Inject(method = "tickChunk", at = @At("HEAD")) + private void iris$beginRandomTick(LevelChunk chunk, int randomTickSpeed, CallbackInfo info) { + ToolWorldGuard.enter((ServerLevel) (Object) this, null, null, false); + } + + @Inject(method = "tickChunk", at = @At("RETURN")) + private void iris$endRandomTick(LevelChunk chunk, int randomTickSpeed, CallbackInfo info) { + ToolWorldGuard.exit((ServerLevel) (Object) this); + } + + @Inject(method = "tickNonPassenger", at = @At("HEAD")) + private void iris$beginEntityTick(Entity entity, CallbackInfo info) { + ToolWorldGuard.enter((ServerLevel) (Object) this, Cause.ENTITY, entity, false); + } + + @Inject(method = "tickNonPassenger", at = @At("RETURN")) + private void iris$endEntityTick(Entity entity, CallbackInfo info) { + ToolWorldGuard.exit((ServerLevel) (Object) this); + } + + @Inject(method = "advanceWeatherCycle", at = @At("HEAD"), cancellable = true) + private void iris$keepToolWorldWeatherOff(CallbackInfo info) { + if (ToolWorldGuard.isToolWorld((ServerLevel) (Object) this)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerPlayerGameModeToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerPlayerGameModeToolMixin.java new file mode 100644 index 000000000..b7e3e4de7 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerPlayerGameModeToolMixin.java @@ -0,0 +1,130 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ServerPlayerGameMode; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.BlockHitResult; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** + * What a player does with their hands in a tool world: the tool is asked about a click before it happens, and about a block + * that is broken before it breaks. What a click that the tool allows then changes is let through, since the tool allowed it. + */ +@Mixin(ServerPlayerGameMode.class) +public abstract class ServerPlayerGameModeToolMixin { + @Shadow + protected ServerLevel level; + + @Shadow + @Final + protected ServerPlayer player; + + @Inject(method = "destroyBlock", at = @At("HEAD"), cancellable = true) + private void iris$askAboutBreaking(BlockPos position, CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(level)) { + return; + } + if (!ToolWorldHooks.breakAllowed(level, player, position)) { + result.setReturnValue(false); + return; + } + ToolWorldGuard.enter(level, Cause.BREAK, player, true); + } + + @Inject(method = "destroyBlock", at = @At("RETURN")) + private void iris$endBreaking(BlockPos position, CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } + + @Inject(method = "useItemOn", at = @At("HEAD"), cancellable = true) + private void iris$askAboutUsingOnBlock(ServerPlayer user, Level world, ItemStack stack, InteractionHand hand, BlockHitResult hit, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(world)) { + return; + } + if (!ToolWorldHooks.rightClickBlockAllowed(user, hand, stack, hit)) { + result.setReturnValue(InteractionResult.FAIL); + return; + } + ToolWorldGuard.enter(world, null, user, true); + } + + @Inject(method = "useItemOn", at = @At("RETURN")) + private void iris$endUsingOnBlock(ServerPlayer user, Level world, ItemStack stack, InteractionHand hand, BlockHitResult hit, + CallbackInfoReturnable result) { + ToolWorldGuard.exit(world); + } + + @Inject(method = "useItem", at = @At("HEAD"), cancellable = true) + private void iris$askAboutUsing(ServerPlayer user, Level world, ItemStack stack, InteractionHand hand, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(world)) { + return; + } + if (!ToolWorldHooks.rightClickAirAllowed(user, hand, stack)) { + result.setReturnValue(InteractionResult.FAIL); + return; + } + ToolWorldGuard.enter(world, null, user, true); + } + + @Inject(method = "useItem", at = @At("RETURN")) + private void iris$endUsing(ServerPlayer user, Level world, ItemStack stack, InteractionHand hand, + CallbackInfoReturnable result) { + ToolWorldGuard.exit(world); + } + + @Inject(method = "handleBlockBreakAction", at = @At("HEAD"), cancellable = true) + private void iris$askAboutLeftClick(BlockPos position, ServerboundPlayerActionPacket.Action action, Direction face, + int maxBuildHeight, int sequence, CallbackInfo info) { + if (!ToolWorldGuard.isToolWorld(level)) { + return; + } + boolean startsDigging = action == ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK; + if (startsDigging && !ToolWorldHooks.leftClickBlockAllowed(player, position, face, sequence)) { + info.cancel(); + return; + } + ToolWorldGuard.enter(level, null, player, true); + } + + @Inject(method = "handleBlockBreakAction", at = @At("RETURN")) + private void iris$endLeftClick(BlockPos position, ServerboundPlayerActionPacket.Action action, Direction face, + int maxBuildHeight, int sequence, CallbackInfo info) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedCaptureArea.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedCaptureArea.java new file mode 100644 index 000000000..e84081305 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedCaptureArea.java @@ -0,0 +1,189 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.structure; + +import art.arcane.iris.core.tooling.ToolingSender; +import art.arcane.iris.modded.ModdedDimensionManager; +import art.arcane.iris.modded.ModdedPlatformWorld; +import art.arcane.iris.modded.ModdedStructureHooks; +import art.arcane.iris.modded.command.ModdedPackCommands; +import art.arcane.iris.modded.toolworld.ModdedToolPainting; +import art.arcane.iris.modded.toolworld.ToolBlocks; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.CapturedStructure; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.TemplateBlock; +import net.minecraft.core.BlockPos; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Blocks; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; + +/** + * A scratch level that structures are generated in, one after another: an empty runtime dimension of an installed pack, so + * what is read back is the structure's own blocks. The level lives on the server thread, so each step runs there while + * the caller, a tool's worker, waits. + */ +final class ModdedCaptureArea implements PlatformStructures.CaptureArea { + private static final String DIMENSION_PREFIX = "irisworldgen:capture_"; + private static final long SCRATCH_SEED = 1337L; + private static final long STEP_TIMEOUT_SECONDS = 30L; + private static final long OPEN_TIMEOUT_SECONDS = 120L; + private static final int CELL_STRIDE = 128; + private static final int CELL_COLUMNS = 8; + + private final MinecraftServer server; + private final String dimensionId; + private final ServerLevel level; + private int nextCell; + + private ModdedCaptureArea(MinecraftServer server, String dimensionId, ServerLevel level) { + this.server = server; + this.dimensionId = dimensionId; + this.level = level; + } + + /** Opens the area; empty when the pack to make it from, or the level itself, could not be had, which the sender has been told. */ + static Optional open(MinecraftServer server, Sender sender) { + Optional pack = packFor(sender); + if (pack.isEmpty()) { + sender.error("A structure capture needs an installed pack to make its scratch world from"); + return Optional.empty(); + } + String dimensionId = DIMENSION_PREFIX + UUID.randomUUID().toString().replace("-", ""); + try { + ModdedDimensionManager.Handle handle = onServerThread(server, () -> ModdedDimensionManager.create( + server, dimensionId, pack.get(), pack.get(), SCRATCH_SEED, new ModdedToolPainting((x, z, canvas) -> { })), + OPEN_TIMEOUT_SECONDS); + return Optional.of(new ModdedCaptureArea(server, dimensionId, handle.level())); + } catch (IllegalStateException failure) { + sender.error("The scratch world for structure capture could not be made: " + failure.getMessage()); + return Optional.empty(); + } + } + + private static Optional packFor(Sender sender) { + if (sender instanceof ToolingSender tooling && tooling.world().isPresent()) { + return Optional.of(tooling.world().get().pack().name()); + } + File[] packs = ModdedPackCommands.packsRoot().listFiles(File::isDirectory); + if (packs == null) { + return Optional.empty(); + } + for (File pack : packs) { + if (new File(pack, "dimensions/" + pack.getName() + ".json").isFile()) { + return Optional.of(pack.getName()); + } + } + return Optional.empty(); + } + + @Override + public Optional capture(ResourceId structure, long seed, int maxSpan) { + int cellIndex = nextCell++; + int originX = (cellIndex % CELL_COLUMNS) * CELL_STRIDE; + int originZ = (cellIndex / CELL_COLUMNS) * CELL_STRIDE; + int anchorChunkX = (originX + CELL_STRIDE / 2) >> 4; + int anchorChunkZ = (originZ + CELL_STRIDE / 2) >> 4; + String key = structure.toString(); + try { + return Optional.ofNullable(onServerThread(server, + () -> placeAndRead(key, anchorChunkX, anchorChunkZ, seed, maxSpan), STEP_TIMEOUT_SECONDS)); + } catch (IllegalStateException failure) { + throw new IllegalStateException("Structure capture failed for '" + key + "' at chunk " + anchorChunkX + "," + + anchorChunkZ + ": " + failure.getMessage(), failure); + } + } + + private CapturedStructure placeAndRead(String key, int anchorChunkX, int anchorChunkZ, long seed, int maxSpan) { + int[] box = new ModdedStructureHooks(() -> server) + .placeStructure(new ModdedPlatformWorld(level), anchorChunkX, anchorChunkZ, key, seed, maxSpan); + if (box == null) { + return null; + } + int width = box[3] - box[0] + 1; + int height = box[4] - box[1] + 1; + int depth = box[5] - box[2] + 1; + if (width <= 0 || height <= 0 || depth <= 0) { + return null; + } + List blocks = new ArrayList<>(); + for (int dx = 0; dx < width; dx++) { + for (int dy = 0; dy < height; dy++) { + for (int dz = 0; dz < depth; dz++) { + BlockPos at = new BlockPos(box[0] + dx, box[1] + dy, box[2] + dz); + if (level.getBlockState(at).is(Blocks.AIR)) { + continue; + } + blocks.add(blockOf(at, new BlockPosition(dx, dy, dz))); + } + } + } + return blocks.isEmpty() ? null : new CapturedStructure(new BlockPosition(width, height, depth), blocks); + } + + private TemplateBlock blockOf(BlockPos at, BlockPosition relative) { + BlockState state = ToolBlocks.apiStateOf(level.getBlockState(at)); + return TemplateBlock.of(relative, state, ToolBlocks.blockEntityOf(level, at)); + } + + @Override + public void close() { + try { + onServerThread(server, () -> ModdedDimensionManager.remove(server, dimensionId, true), STEP_TIMEOUT_SECONDS); + } catch (IllegalStateException failure) { + throw new IllegalStateException("The scratch world for structure capture could not be removed: " + failure.getMessage(), failure); + } + } + + private static T onServerThread(MinecraftServer server, Supplier task, long timeoutSeconds) { + CompletableFuture result = new CompletableFuture<>(); + server.execute(() -> { + try { + result.complete(task.get()); + } catch (Throwable failure) { + result.completeExceptionally(failure); + } + }); + try { + return result.get(timeoutSeconds, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while waiting for the server thread", interrupted); + } catch (ExecutionException failed) { + Throwable cause = failed.getCause(); + throw new IllegalStateException(cause.getMessage() == null ? cause.getClass().getSimpleName() : cause.getMessage(), cause); + } catch (TimeoutException timedOut) { + throw new IllegalStateException("the server thread did not finish within " + timeoutSeconds + " seconds", timedOut); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedPlatformStructures.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedPlatformStructures.java new file mode 100644 index 000000000..712affa94 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedPlatformStructures.java @@ -0,0 +1,178 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.structure; + +import art.arcane.iris.modded.ModdedEngineBootstrap; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.JigsawStructureInfo; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.StructureAccessException; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplatePool; +import net.minecraft.core.Holder; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.level.levelgen.structure.Structure; +import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; +import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.TreeSet; + +/** + * The structures of a modded server as the tools read them: templates through the server's template manager, and + * structures, structure sets and template pools through its registries. Vanilla classes, so nothing is reflected. + */ +public final class ModdedPlatformStructures implements PlatformStructures { + private static final String TEMPLATE_FOLDER = "structure"; + private static final String TEMPLATE_FILE_SUFFIX = ".nbt"; + private static final String MAX_DEPTH_FIELD = "maxDepth"; + private static final String MAX_DISTANCE_FIELD = "maxDistanceFromCenter"; + + @Override + public List templates() { + MinecraftServer server = server(); + List found = new ArrayList<>(); + for (Identifier file : server.getResourceManager() + .listResources(TEMPLATE_FOLDER, location -> location.getPath().endsWith(TEMPLATE_FILE_SUFFIX)).keySet()) { + String path = file.getPath().substring(TEMPLATE_FOLDER.length() + 1, + file.getPath().length() - TEMPLATE_FILE_SUFFIX.length()); + if (!path.isEmpty()) { + found.add(Identifier.fromNamespaceAndPath(file.getNamespace(), path)); + } + } + return idsOf(found); + } + + @Override + public Optional template(ResourceId id) { + return server().getStructureManager().get(identifierOf(id)).flatMap(TemplateReading::read); + } + + @Override + public List structures() { + return idsOf(registries().lookupOrThrow(Registries.STRUCTURE).keySet()); + } + + @Override + public List structureSets() { + return idsOf(registries().lookupOrThrow(Registries.STRUCTURE_SET).keySet()); + } + + @Override + public Optional jigsaw(ResourceId structureKey) { + RegistryAccess registries = registries(); + Structure structure = registries.lookupOrThrow(Registries.STRUCTURE).getValue(identifierOf(structureKey)); + if (!(structure instanceof JigsawStructure jigsaw)) { + return Optional.empty(); + } + Identifier startPool = poolKeyOf(registries.lookupOrThrow(Registries.TEMPLATE_POOL), jigsaw.getStartPool()) + .orElseThrow(() -> new StructureAccessException("Could not resolve the start pool key for " + structureKey, false)); + return Optional.of(jigsawInfoOf(structureKey, jigsaw, startPool, ModdedEngineBootstrap.loader().minecraftVersion())); + } + + static JigsawStructureInfo jigsawInfoOf(ResourceId structureKey, JigsawStructure jigsaw, Identifier startPool, String gameVersion) { + return new JigsawStructureInfo( + ResourceId.parse(startPool.toString()), + PrivateFields.readInt(jigsaw, MAX_DEPTH_FIELD), + PrivateFields.read(jigsaw, MAX_DISTANCE_FIELD, JigsawStructure.MaxDistance.class).horizontal(), + gameVersion, + shuffleSeedOf(structureKey)); + } + + /** The hash a key has on Bukkit, so a structure shuffles its pool the same on every platform. */ + static long shuffleSeedOf(ResourceId structureKey) { + return 31 * structureKey.namespace().hashCode() + structureKey.path().hashCode(); + } + + @Override + public Optional pool(ResourceId poolKey) { + MinecraftServer server = server(); + Registry registry = server.registryAccess().lookupOrThrow(Registries.TEMPLATE_POOL); + StructureTemplatePool pool = registry.getValue(identifierOf(poolKey)); + if (pool == null) { + return Optional.empty(); + } + Optional fallback = Optional.empty(); + Optional fallbackFailure = Optional.empty(); + try { + fallback = poolKeyOf(registry, pool.getFallback()).map(key -> ResourceId.parse(key.toString())); + } catch (RuntimeException failure) { + fallbackFailure = Optional.of(PoolReading.failureDetail(failure)); + } + List members = new ArrayList<>(); + pool.getTemplates().forEach(pair -> members.add(PoolReading.memberOf(pair, server.getStructureManager()))); + return Optional.of(new TemplatePool(members, fallback, fallbackFailure)); + } + + private static Optional poolKeyOf(Registry registry, Holder holder) { + Optional> key = holder.unwrapKey(); + if (key.isPresent()) { + return Optional.of(key.get().identifier()); + } + return Optional.ofNullable(registry.getKey(holder.value())); + } + + @Override + public boolean supportsCapture() { + return true; + } + + @Override + public Optional openCaptureArea(Sender sender) { + return ModdedCaptureArea.open(server(), sender); + } + + private static MinecraftServer server() { + MinecraftServer server = ModdedEngineBootstrap.currentServer(); + if (server == null) { + throw new StructureAccessException("No server is running", true); + } + return server; + } + + private static RegistryAccess registries() { + return server().registryAccess(); + } + + private static Identifier identifierOf(ResourceId id) { + return Identifier.fromNamespaceAndPath(id.namespace(), id.path()); + } + + private static List idsOf(Collection keys) { + TreeSet ids = new TreeSet<>(); + for (Identifier key : keys) { + try { + ids.add(ResourceId.parse(key.toString().toLowerCase(Locale.ROOT))); + } catch (IllegalArgumentException invalidKey) { + continue; + } + } + return new ArrayList<>(ids); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PoolReading.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PoolReading.java new file mode 100644 index 000000000..a418a7dd5 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PoolReading.java @@ -0,0 +1,144 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.structure; + +import com.mojang.datafixers.util.Pair; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.StructureAccessException; +import com.volmit.tooling.TemplatePool; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.block.JigsawBlock; +import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.levelgen.structure.pools.ListPoolElement; +import net.minecraft.world.level.levelgen.structure.pools.SinglePoolElement; +import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.function.LongSupplier; + +/** The members of a vanilla template pool: their weights, templates and jigsaw connectors. */ +final class PoolReading { + private static final String ALIGNED_JOINT = "ALIGN"; + private static final String FINAL_STATE_NBT_KEY = "final_state"; + + private PoolReading() { + } + + /** The member of a pool for the pair the pool lists it as: its element and weight. */ + static TemplatePool.Member memberOf(Pair pair, StructureTemplateManager templates) { + StructurePoolElement element = pair.getFirst(); + if (element == null) { + return new TemplatePool.Absent(); + } + int weight = pair.getSecond() == null ? 1 : Math.max(1, pair.getSecond()); + Resolution resolution = resolve(element); + String type = resolution.physical() == null ? element.getClass().getSimpleName() : resolution.physical().getClass().getSimpleName(); + Optional template = resolution.physical() instanceof SinglePoolElement single + ? Optional.of(ResourceId.parse(single.getTemplateLocation().toString().toLowerCase(Locale.ROOT))) + : Optional.empty(); + return new TemplatePool.Element(weight, type, template, resolution.listLevels(), resolution.omittedElements(), + shuffleSeeds -> connectorsOf(element, templates, shuffleSeeds)); + } + + /** The first element that is no list, and how many lists and further elements were passed to reach it. */ + private record Resolution(StructurePoolElement physical, int listLevels, int omittedElements) { + } + + private static Resolution resolve(StructurePoolElement element) { + if (!(element instanceof ListPoolElement list)) { + return new Resolution(element, 0, 0); + } + List elements = list.getElements(); + if (elements.isEmpty()) { + return new Resolution(null, 1, 0); + } + Resolution primary = resolve(elements.getFirst()); + return new Resolution(primary.physical(), primary.listLevels() + 1, primary.omittedElements() + elements.size() - 1); + } + + private static TemplatePool.Connectors connectorsOf(StructurePoolElement element, StructureTemplateManager templates, + LongSupplier shuffleSeeds) { + try { + List blocks = element.getShuffledJigsawBlocks( + templates, BlockPos.ZERO, Rotation.NONE, RandomSource.create(shuffleSeeds.getAsLong())); + if (blocks == null) { + return new TemplatePool.Connectors(TemplatePool.Availability.NO_COLLECTION, List.of()); + } + List connectors = new ArrayList<>(); + for (StructureTemplate.JigsawBlockInfo jigsaw : blocks) { + connectors.add(connectorOf(jigsaw)); + } + return new TemplatePool.Connectors(TemplatePool.Availability.READ, connectors); + } catch (RuntimeException failure) { + throw new StructureAccessException(failureDetail(failure), true, failure); + } + } + + private static TemplatePool.Connector connectorOf(StructureTemplate.JigsawBlockInfo jigsaw) { + try { + return connectorFrom(jigsaw); + } catch (RuntimeException failure) { + return new TemplatePool.UnreadableConnector(failureDetail(failure)); + } + } + + private static TemplatePool.JigsawConnector connectorFrom(StructureTemplate.JigsawBlockInfo jigsaw) { + StructureTemplate.StructureBlockInfo info = jigsaw.info(); + BlockPos at = info.pos(); + String poolId = jigsaw.pool().identifier().toString(); + Optional finalState = info.nbt() == null ? Optional.empty() + : info.nbt().getString(FINAL_STATE_NBT_KEY).filter(state -> !state.isBlank()); + return new TemplatePool.JigsawConnector( + new BlockPosition(at.getX(), at.getY(), at.getZ()), + faceOf(JigsawBlock.getFrontFacing(info.state()).getName()), + faceOf(JigsawBlock.getTopFacing(info.state()).getName()), + poolId.isEmpty() ? Optional.empty() : Optional.of(ResourceId.parse(poolId)), + jigsaw.name().toString(), + jigsaw.target().toString(), + String.valueOf(jigsaw.jointType()).toUpperCase(Locale.ROOT).contains(ALIGNED_JOINT), + finalState, + jigsaw.selectionPriority(), + jigsaw.placementPriority()); + } + + private static BlockFace faceOf(String facing) { + return switch (facing) { + case "up" -> BlockFace.UP; + case "down" -> BlockFace.DOWN; + case "south" -> BlockFace.SOUTH; + case "east" -> BlockFace.EAST; + case "west" -> BlockFace.WEST; + default -> BlockFace.NORTH; + }; + } + + /** The message a failed read shows: the failure's message, else its class name. */ + static String failureDetail(Throwable failure) { + String message = failure.getMessage(); + return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message; + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PrivateFields.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PrivateFields.java new file mode 100644 index 000000000..2f1689af7 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PrivateFields.java @@ -0,0 +1,51 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.structure; + +import com.volmit.tooling.StructureAccessException; + +import java.lang.reflect.Field; +import java.util.List; + +/** + * Reads the few private fields of vanilla classes that the tools need. Minecraft ships with its own names, so the field + * names are the same on every loader; a field that is missing is a reading the platform cannot give, not a bug to hide. + */ +public final class PrivateFields { + private PrivateFields() { + } + + public static T read(Object owner, String name, Class type) { + try { + Field field = owner.getClass().getDeclaredField(name); + field.setAccessible(true); + return type.cast(field.get(owner)); + } catch (ReflectiveOperationException | RuntimeException failure) { + throw new StructureAccessException("Cannot read " + name + " of " + owner.getClass().getSimpleName() + ": " + failure, true, failure); + } + } + + public static List readList(Object owner, String name) { + return read(owner, name, List.class); + } + + public static int readInt(Object owner, String name) { + return read(owner, name, Integer.class); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/TemplateReading.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/TemplateReading.java new file mode 100644 index 000000000..fec03f5fd --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/TemplateReading.java @@ -0,0 +1,99 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.structure; + +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.modded.ModdedBlockState; +import art.arcane.iris.modded.ModdedIrisLog; +import art.arcane.iris.modded.ModdedTileData; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.TemplateBlock; +import net.minecraft.core.Vec3i; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** A vanilla structure template as a {@link com.volmit.tooling.StructureTemplate}: its size, and the blocks of its first palette. */ +final class TemplateReading { + private static final String FINAL_STATE_NBT_KEY = "final_state"; + private static final String PALETTES_FIELD = "palettes"; + private static final String ENTITIES_FIELD = "entityInfoList"; + + private TemplateReading() { + } + + /** The template; empty when it holds no palette. */ + static Optional read(StructureTemplate template) { + List palettes = PrivateFields.readList(template, PALETTES_FIELD); + if (palettes.isEmpty()) { + return Optional.empty(); + } + Vec3i size = template.getSize(); + List blocks = new ArrayList<>(); + for (StructureTemplate.StructureBlockInfo info : ((StructureTemplate.Palette) palettes.getFirst()).blocks()) { + blocks.add(blockOf(info)); + } + return Optional.of(new com.volmit.tooling.StructureTemplate( + new BlockPosition(size.getX(), size.getY(), size.getZ()), + palettes.size(), + PrivateFields.readList(template, ENTITIES_FIELD).size(), + blocks)); + } + + private static TemplateBlock blockOf(StructureTemplate.StructureBlockInfo info) { + BlockPosition position = new BlockPosition(info.pos().getX(), info.pos().getY(), info.pos().getZ()); + BlockState state = BlockState.parse(ModdedBlockState.serialize(info.state())); + if (info.state().is(Blocks.JIGSAW)) { + return new TemplateBlock(position, state, Optional.empty(), finalStateOf(info.nbt())); + } + if (info.state().is(Blocks.STRUCTURE_BLOCK) || info.state().is(Blocks.STRUCTURE_VOID)) { + return TemplateBlock.of(position, state, Optional.empty()); + } + return TemplateBlock.of(position, state, blockEntityOf(info)); + } + + private static Optional blockEntityOf(StructureTemplate.StructureBlockInfo info) { + CompoundTag nbt = info.nbt(); + if (nbt == null || !info.state().hasBlockEntity()) { + return Optional.empty(); + } + try { + String blockKey = BuiltInRegistries.BLOCK.getKey(info.state().getBlock()).toString(); + return Optional.of(BlockEntities.of(ModdedTileData.capture(blockKey, NbtUtils.structureToSnbt(nbt)))); + } catch (java.io.IOException | RuntimeException failure) { + ModdedIrisLog.error("Iris could not read the block entity of a template block at {}.", info.pos(), failure); + return Optional.empty(); + } + } + + private static Optional finalStateOf(CompoundTag nbt) { + if (nbt == null) { + return Optional.empty(); + } + return nbt.getString(FINAL_STATE_NBT_KEY).filter(finalState -> !finalState.isBlank()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ChunkBuffer.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ChunkBuffer.java new file mode 100644 index 000000000..2c37de9d8 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ChunkBuffer.java @@ -0,0 +1,93 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ChunkCanvas; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** What one paint of a tool world chunk asked for, kept until it is written to a chunk. One buffer serves one paint on one thread. */ +final class ChunkBuffer implements ChunkCanvas { + private static final int CHUNK_SIZE = 16; + + /** A block entity asked for at chunk-local {@code x} and {@code z} and world {@code y}. */ + record Painted(int x, int y, int z, BlockEntityData data) { + } + + private final int minY; + private final int height; + private final net.minecraft.world.level.block.state.BlockState[] states; + private final List blockEntities = new ArrayList<>(); + + ChunkBuffer(int minY, int height) { + this.minY = minY; + this.height = height; + this.states = new net.minecraft.world.level.block.state.BlockState[CHUNK_SIZE * CHUNK_SIZE * height]; + } + + @Override + public int minY() { + return minY; + } + + @Override + public int maxY() { + return minY + height; + } + + @Override + public void set(int x, int y, int z, BlockState state) { + requireInside(x, y, z); + states[indexOf(x, y, z)] = ToolBlocks.minecraftStateOf(Objects.requireNonNull(state, "state")); + blockEntities.removeIf(painted -> painted.x() == x && painted.y() == y && painted.z() == z); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData data) { + Objects.requireNonNull(data, "data"); + set(x, y, z, state); + blockEntities.add(new Painted(x, y, z, data)); + } + + /** The state painted at chunk-local {@code x} and {@code z} and world {@code y}; null where nothing was painted. */ + net.minecraft.world.level.block.state.BlockState stateAt(int x, int y, int z) { + return states[indexOf(x, y, z)]; + } + + List blockEntities() { + return List.copyOf(blockEntities); + } + + private int indexOf(int x, int y, int z) { + return ((y - minY) * CHUNK_SIZE + z) * CHUNK_SIZE + x; + } + + private void requireInside(int x, int y, int z) { + if (x < 0 || x >= CHUNK_SIZE || z < 0 || z >= CHUNK_SIZE) { + throw new IllegalArgumentException("Chunk-local x and z are 0 to 15: " + x + ", " + z); + } + if (y < minY || y >= maxY()) { + throw new IllegalArgumentException("Y " + y + " is outside the world, " + minY + " up to " + maxY()); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPainting.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPainting.java new file mode 100644 index 000000000..a553ab990 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPainting.java @@ -0,0 +1,178 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import art.arcane.iris.modded.ModdedIrisLog; +import com.volmit.tooling.world.ChunkPainter; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.levelgen.Heightmap; + +import java.util.EnumSet; +import java.util.Objects; +import java.util.Set; + +/** + * The chunks of a tool world: whatever the tool's painter paints, and nothing else. The chunk generator of the world asks + * it to paint every chunk it generates, and the world asks it to paint again over a chunk that is live. + */ +public final class ModdedToolPainting { + private static final int CHUNK_SIZE = 16; + private static final int SECTION_SIZE = 16; + private static final int REPAINT_FLAGS = Block.UPDATE_CLIENTS | Block.UPDATE_KNOWN_SHAPE | Block.UPDATE_SUPPRESS_DROPS; + private static final Set PRIMED_HEIGHTMAPS = EnumSet.of( + Heightmap.Types.WORLD_SURFACE_WG, + Heightmap.Types.OCEAN_FLOOR_WG, + Heightmap.Types.MOTION_BLOCKING, + Heightmap.Types.MOTION_BLOCKING_NO_LEAVES); + + private final ChunkPainter painter; + + public ModdedToolPainting(ChunkPainter painter) { + this.painter = Objects.requireNonNull(painter, "painter"); + } + + /** Paints {@code chunk}, which the generator is filling and no player can see yet. */ + public ChunkAccess paint(ChunkAccess chunk, ServerLevel level) { + ChunkPos position = chunk.getPos(); + ChunkBuffer buffer = paintBuffer(position.x(), position.z(), chunk.getMinY(), chunk.getHeight()); + writeSections(chunk, buffer); + writeBlockEntities(chunk, level, buffer); + Heightmap.primeHeightmaps(chunk, PRIMED_HEIGHTMAPS); + return chunk; + } + + /** Paints again over a live chunk: changes what differs from the paint and sends it to the players watching. */ + void repaint(ServerLevel level, LevelChunk chunk) { + ChunkPos position = chunk.getPos(); + ChunkBuffer buffer = paintBuffer(position.x(), position.z(), chunk.getMinY(), chunk.getHeight()); + ToolWorldGuard.hostWrite(() -> { + rewriteDifferences(level, chunk, buffer); + rewriteBlockEntities(level, position, buffer); + }); + } + + private ChunkBuffer paintBuffer(int chunkX, int chunkZ, int minY, int height) { + ChunkBuffer buffer = new ChunkBuffer(minY, height); + try { + painter.paint(chunkX, chunkZ, buffer); + } catch (RuntimeException failure) { + ModdedIrisLog.error("A tool world painter failed at chunk {},{}.", chunkX, chunkZ, failure); + } + return buffer; + } + + private void writeSections(ChunkAccess chunk, ChunkBuffer buffer) { + int minY = buffer.minY(); + for (int y = minY; y < buffer.maxY(); ) { + int sectionIndex = chunk.getSectionIndex(y); + LevelChunkSection section = chunk.getSection(sectionIndex); + int sectionEnd = Math.min(minY + (sectionIndex + 1) * SECTION_SIZE, buffer.maxY()); + section.acquire(); + try { + writeSection(section, buffer, y, sectionEnd); + } finally { + section.release(); + } + y = sectionEnd; + } + } + + private void writeSection(LevelChunkSection section, ChunkBuffer buffer, int fromY, int toY) { + for (int y = fromY; y < toY; y++) { + for (int z = 0; z < CHUNK_SIZE; z++) { + for (int x = 0; x < CHUNK_SIZE; x++) { + BlockState state = buffer.stateAt(x, y, z); + if (state != null) { + section.setBlockState(x, y & (SECTION_SIZE - 1), z, state, false); + } + } + } + } + } + + private void writeBlockEntities(ChunkAccess chunk, ServerLevel level, ChunkBuffer buffer) { + ChunkPos position = chunk.getPos(); + for (int y = buffer.minY(); y < buffer.maxY(); y++) { + for (int z = 0; z < CHUNK_SIZE; z++) { + for (int x = 0; x < CHUNK_SIZE; x++) { + BlockState state = buffer.stateAt(x, y, z); + if (state != null && state.hasBlockEntity()) { + createDefaultBlockEntity(chunk, new BlockPos(position.getMinBlockX() + x, y, position.getMinBlockZ() + z), state); + } + } + } + } + for (ChunkBuffer.Painted painted : buffer.blockEntities()) { + BlockPos at = new BlockPos(position.getMinBlockX() + painted.x(), painted.y(), position.getMinBlockZ() + painted.z()); + try { + ToolBlocks.applyPaintedBlockEntity(chunk, level, at, buffer.stateAt(painted.x(), painted.y(), painted.z()), painted.data()); + } catch (RuntimeException failure) { + ModdedIrisLog.error("A tool world could not write a block entity at {}.", at, failure); + } + } + } + + private static void createDefaultBlockEntity(ChunkAccess chunk, BlockPos at, BlockState state) { + if (!(state.getBlock() instanceof EntityBlock entityBlock)) { + return; + } + BlockEntity blockEntity = entityBlock.newBlockEntity(at, state); + if (blockEntity != null) { + chunk.setBlockEntity(blockEntity); + } + } + + private void rewriteDifferences(ServerLevel level, LevelChunk chunk, ChunkBuffer buffer) { + ChunkPos position = chunk.getPos(); + BlockState air = Blocks.AIR.defaultBlockState(); + for (int y = buffer.minY(); y < buffer.maxY(); y++) { + for (int z = 0; z < CHUNK_SIZE; z++) { + for (int x = 0; x < CHUNK_SIZE; x++) { + BlockPos at = new BlockPos(position.getMinBlockX() + x, y, position.getMinBlockZ() + z); + BlockState painted = buffer.stateAt(x, y, z); + BlockState wanted = painted == null ? air : painted; + if (chunk.getBlockState(at) != wanted) { + level.setBlock(at, wanted, REPAINT_FLAGS); + } + } + } + } + } + + private void rewriteBlockEntities(ServerLevel level, ChunkPos position, ChunkBuffer buffer) { + for (ChunkBuffer.Painted painted : buffer.blockEntities()) { + BlockPos at = new BlockPos(position.getMinBlockX() + painted.x(), painted.y(), position.getMinBlockZ() + painted.z()); + try { + ToolBlocks.applyBlockEntity(level, at, painted.data()); + } catch (RuntimeException failure) { + ModdedIrisLog.error("A tool world could not write a block entity at {}.", at, failure); + } + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPlayer.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPlayer.java new file mode 100644 index 000000000..1403a7248 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPlayer.java @@ -0,0 +1,289 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import art.arcane.iris.modded.ModdedDimensionManager; +import art.arcane.iris.modded.ModdedEngineBootstrap; +import art.arcane.iris.modded.command.ModdedToolingSender; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.Particle; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; +import com.volmit.tooling.world.ToolWorld; +import net.minecraft.core.Holder; +import net.minecraft.core.particles.DustParticleOptions; +import net.minecraft.network.protocol.game.ClientboundSoundPacket; +import net.minecraft.resources.Identifier; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.level.GameType; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** One online player as a tool sees them. It finds the player again by id each time, so it outlives a respawn. */ +final class ModdedToolPlayer implements ToolPlayer { + private static final String DEFAULT_SIDEBAR_TITLE = "Iris"; + + private final UUID id; + private final String name; + private final ToolPlayers players; + private final ToolMenus menus; + + ModdedToolPlayer(UUID id, String name, ToolPlayers players, ToolMenus menus) { + this.id = id; + this.name = name; + this.players = players; + this.menus = menus; + } + + private static MinecraftServer server() { + MinecraftServer server = ModdedEngineBootstrap.currentServer(); + if (server == null) { + throw new IllegalStateException("No server is running"); + } + return server; + } + + ServerPlayer player() { + ServerPlayer online = server().getPlayerList().getPlayer(id); + if (online == null) { + throw new IllegalStateException("Player " + name + " is not online"); + } + return online; + } + + private Optional onlinePlayer() { + return Optional.ofNullable(server().getPlayerList().getPlayer(id)); + } + + @Override + public UUID id() { + return id; + } + + @Override + public String name() { + return name; + } + + @Override + public Sender sender() { + return new ModdedToolingSender(player().createCommandSourceStack()); + } + + @Override + public Optional world() { + return onlinePlayer() + .filter(online -> online.level() instanceof ServerLevel) + .flatMap(online -> ToolWorldRegistry.INSTANCE.forLevel((ServerLevel) online.level())) + .map(world -> world); + } + + @Override + public BlockPosition position() { + return ToolBlocks.positionOf(player().blockPosition()); + } + + @Override + public float yaw() { + return player().getYRot(); + } + + @Override + public float pitch() { + return player().getXRot(); + } + + @Override + public boolean sneaking() { + return player().isShiftKeyDown(); + } + + @Override + public Optional targetBlock(int maxDistance) { + HitResult hit = player().pick(maxDistance, 1.0F, false); + if (hit.getType() != HitResult.Type.BLOCK) { + return Optional.empty(); + } + return Optional.of(ToolBlocks.positionOf(((BlockHitResult) hit).getBlockPos())); + } + + @Override + public void run(Runnable task) { + server().execute(task); + } + + @Override + public CompletableFuture teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch) { + if (!(world instanceof ModdedToolWorld target)) { + return CompletableFuture.failedFuture(new IllegalArgumentException("Not a tool world of this platform: " + world)); + } + CompletableFuture arrived = new CompletableFuture<>(); + server().execute(() -> { + Optional online = onlinePlayer(); + if (online.isEmpty()) { + arrived.complete(false); + return; + } + ModdedDimensionManager.teleportAsync(online.get(), server(), target.level(), x, y, z) + .whenComplete((success, failure) -> server().execute(() -> faceAfterArrival(arrived, success, failure, target, yaw, pitch))); + }); + return arrived; + } + + private void faceAfterArrival(CompletableFuture arrived, Boolean success, Throwable failure, + ModdedToolWorld target, float yaw, float pitch) { + if (failure != null) { + arrived.completeExceptionally(failure); + return; + } + Optional online = onlinePlayer(); + if (Boolean.TRUE.equals(success) && online.isPresent()) { + ServerPlayer arrivedPlayer = online.get(); + arrivedPlayer.teleportTo(target.level(), arrivedPlayer.getX(), arrivedPlayer.getY(), arrivedPlayer.getZ(), + Set.of(), yaw, pitch, false); + } + arrived.complete(Boolean.TRUE.equals(success)); + } + + @Override + public void creative(boolean on) { + server().execute(() -> onlinePlayer().ifPresent(online -> { + if (on) { + players.rememberModeBeforeCreative(online); + online.setGameMode(GameType.CREATIVE); + return; + } + players.restoreGameMode(online); + })); + } + + @Override + public void message(ToolText text) { + server().execute(() -> onlinePlayer().ifPresent(online -> online.sendSystemMessage(ToolTexts.component(text)))); + } + + @Override + public void actionBar(ToolText text) { + server().execute(() -> onlinePlayer().ifPresent(online -> online.sendSystemMessage(ToolTexts.component(text), true))); + } + + @Override + public void sound(ResourceId sound, float volume, float pitch) { + server().execute(() -> onlinePlayer().ifPresent(online -> { + Holder event = Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(sound.toString()))); + online.connection.send(new ClientboundSoundPacket(event, SoundSource.MASTER, online.getX(), online.getY(), online.getZ(), + volume, pitch, online.level().getRandom().nextLong())); + })); + } + + @Override + public void sidebar(ToolText title, List lines) { + ToolText shown = title.isEmpty() ? ToolText.plain(DEFAULT_SIDEBAR_TITLE) : title; + server().execute(() -> onlinePlayer().ifPresent(online -> players.sidebars().show(online, shown, lines))); + } + + @Override + public void hideSidebar() { + server().execute(() -> onlinePlayer().ifPresent(online -> players.sidebars().hide(online))); + } + + @Override + public void particles(List dust) { + List specks = List.copyOf(dust); + server().execute(() -> onlinePlayer().ifPresent(online -> specks.forEach(speck -> showDust(online, speck)))); + } + + private static void showDust(ServerPlayer online, Particle speck) { + if (online.level() instanceof ServerLevel level) { + level.sendParticles(online, new DustParticleOptions(speck.rgb(), speck.size()), true, true, + speck.x(), speck.y(), speck.z(), 1, 0.0D, 0.0D, 0.0D, 0.0D); + } + } + + @Override + public boolean give(ToolItem item) { + var stack = ToolItems.create(item); + if (server().isSameThread()) { + return player().getInventory().add(stack); + } + server().execute(() -> onlinePlayer().ifPresent(online -> online.getInventory().add(stack))); + return true; + } + + @Override + public Optional held() { + return ToolItems.read(player().getInventory().getSelectedItem()); + } + + @Override + public void openMenu(ToolMenu menu) { + server().execute(() -> onlinePlayer().ifPresent(online -> menus.open(online, this, menu))); + } + + @Override + public void closeMenu() { + server().execute(() -> onlinePlayer().ifPresent(menus::close)); + } + + /** + * Sends the player to where they were before they entered a tool world, or to the spawn of the main world when that is + * not known any more, and gives back the game mode they had. Completes with whether they arrived. + */ + CompletableFuture returnToOrigin() { + CompletableFuture returned = new CompletableFuture<>(); + server().execute(() -> { + Optional online = onlinePlayer(); + if (online.isEmpty()) { + returned.complete(false); + return; + } + ServerPlayer leaving = online.get(); + menus.close(leaving); + players.sidebars().hide(leaving); + players.restoreGameMode(leaving); + players.destinationAfterToolWorld(leaving).whenComplete((success, failure) -> { + if (failure != null) { + returned.completeExceptionally(failure); + return; + } + returned.complete(Boolean.TRUE.equals(success)); + }); + }); + return returned; + } + + @Override + public String toString() { + return "tool player " + name; + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorld.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorld.java new file mode 100644 index 000000000..f90866159 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorld.java @@ -0,0 +1,322 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import art.arcane.iris.modded.ModdedDimensionManager; +import art.arcane.iris.modded.ModdedEngineBootstrap; +import art.arcane.iris.modded.ModdedIrisLog; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldListener; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.chunk.LevelChunk; + +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * One tool world on a modded server: a runtime dimension of the pack whose chunks come from the tool's painter. It exists, + * registered, from before the level is made until the level is gone; {@link #bind} gives it the level once it exists. + * The server thread owns everything on a modded server, so a position is owned by whoever is on it. + */ +final class ModdedToolWorld implements ToolWorld { + private static final int SET_BLOCK_FLAGS = Block.UPDATE_CLIENTS | Block.UPDATE_KNOWN_SHAPE; + + private final String packName; + private final String name; + private final String dimensionId; + private final ToolWorldListener listener; + private final ModdedToolPainting painting; + private final ToolPlayers players; + private final AtomicBoolean closing = new AtomicBoolean(); + private final AtomicBoolean gone = new AtomicBoolean(); + private final CompletableFuture closed = new CompletableFuture<>(); + private volatile ServerLevel level; + + ModdedToolWorld(String packName, String name, String dimensionId, ToolWorldListener listener, + ModdedToolPainting painting, ToolPlayers players) { + this.packName = packName; + this.name = name; + this.dimensionId = dimensionId; + this.listener = listener; + this.painting = painting; + this.players = players; + } + + String packName() { + return packName; + } + + String dimensionId() { + return dimensionId; + } + + ModdedToolPainting painting() { + return painting; + } + + void bind(ServerLevel created) { + level = Objects.requireNonNull(created, "created"); + } + + boolean isBound() { + return level != null; + } + + ServerLevel level() { + ServerLevel bound = level; + if (bound == null) { + throw new IllegalStateException("The tool world " + name + " is not created yet"); + } + return bound; + } + + private static MinecraftServer server() { + MinecraftServer server = ModdedEngineBootstrap.currentServer(); + if (server == null) { + throw new IllegalStateException("No server is running"); + } + return server; + } + + @Override + public String name() { + return name; + } + + @Override + public int minY() { + return level().getMinY(); + } + + @Override + public int maxY() { + return level().getMinY() + level().getHeight(); + } + + @Override + public List players() { + return level().players().stream().map(players::of).toList(); + } + + @Override + public boolean owns(BlockPosition at) { + return server().isSameThread(); + } + + @Override + public void run(BlockPosition at, Runnable task) { + server().execute(() -> runGuarded(task, "task at " + at)); + } + + @Override + public CompletableFuture call(BlockPosition at, Supplier task) { + CompletableFuture result = new CompletableFuture<>(); + server().execute(() -> { + try { + result.complete(task.get()); + } catch (Throwable failure) { + result.completeExceptionally(failure); + } + }); + return result; + } + + @Override + public BlockState block(BlockPosition at) { + requireOwned(at); + return ToolBlocks.apiStateOf(level().getBlockState(ToolBlocks.blockPosOf(at))); + } + + @Override + public Optional blockEntity(BlockPosition at) { + requireOwned(at); + return ToolBlocks.blockEntityOf(level(), ToolBlocks.blockPosOf(at)); + } + + @Override + public void setBlock(BlockPosition at, BlockState state, Optional data) { + requireOwned(at); + ServerLevel target = level(); + ToolWorldGuard.hostWrite(() -> { + target.setBlock(ToolBlocks.blockPosOf(at), ToolBlocks.minecraftStateOf(state), SET_BLOCK_FLAGS); + data.ifPresent(entity -> ToolBlocks.applyBlockEntity(target, ToolBlocks.blockPosOf(at), entity)); + }); + } + + @Override + public boolean loaded(ChunkPos chunk) { + return level().getChunkSource().hasChunk(chunk.x(), chunk.z()); + } + + @Override + public CompletableFuture repaint(Collection chunks) { + if (isClosed()) { + return CompletableFuture.failedFuture(new IllegalStateException("Tool world " + name + " is closed")); + } + List distinct = chunks.stream().distinct().toList(); + CompletableFuture repainted = new CompletableFuture<>(); + server().execute(() -> { + try { + ServerLevel target = level(); + for (ChunkPos position : distinct) { + LevelChunk chunk = target.getChunk(position.x(), position.z()); + painting.repaint(target, chunk); + } + repainted.complete(null); + } catch (Throwable failure) { + repainted.completeExceptionally(failure); + } + }); + return repainted; + } + + @Override + public CompletableFuture close() { + if (!closing.compareAndSet(false, true)) { + return closed; + } + server().execute(this::sendPlayersBackThenRemove); + return closed; + } + + private void sendPlayersBackThenRemove() { + List> departures = level().players().stream() + .map(player -> players.playerOf(player).returnToOrigin()) + .toList(); + CompletableFuture.allOf(departures.toArray(CompletableFuture[]::new)) + .whenComplete((ignored, failure) -> server().execute(this::removeLevel)); + } + + private void removeLevel() { + try { + ModdedDimensionManager.remove(server(), dimensionId, true); + } catch (Throwable failure) { + unloaded(); + closed.completeExceptionally(failure); + return; + } + unloaded(); + closed.complete(null); + } + + /** Removes the level at once on the server thread, for a server that is stopping; players leave with it. */ + void shutDownNow(MinecraftServer server) { + closing.set(true); + try { + if (isBound()) { + ModdedDimensionManager.remove(server, dimensionId, true); + } + } catch (Throwable failure) { + ModdedIrisLog.error("Tool world {} could not be removed when Iris stopped.", name, failure); + } + unloaded(); + closed.complete(null); + } + + /** Minecraft unloaded the level, whoever asked: it is gone for the tool and for the host. */ + void unloaded() { + if (!gone.compareAndSet(false, true)) { + return; + } + ToolWorldRegistry.INSTANCE.unregister(this); + tell(ToolWorldListener::closed); + } + + /** Called by the opener when creating the level failed: nothing of it is left to unload. */ + void abandon() { + ToolWorldRegistry.INSTANCE.unregister(this); + } + + Optional closeRefusal() { + try { + return listener.closeRefusal(); + } catch (Throwable failure) { + ModdedIrisLog.error("The listener of tool world {} failed.", name, failure); + return Optional.empty(); + } + } + + CompletableFuture prepareReplacement(Optional requestedBy) { + try { + return listener.closing(requestedBy); + } catch (Throwable failure) { + ModdedIrisLog.error("The listener of tool world {} failed.", name, failure); + return CompletableFuture.completedFuture(null); + } + } + + /** The tool's listener asked, with {@code fallback} as the answer when it throws. Runs on the caller's thread. */ + boolean ask(Function question, boolean fallback) { + try { + return question.apply(listener); + } catch (Throwable failure) { + ModdedIrisLog.error("The listener of tool world {} failed.", name, failure); + return fallback; + } + } + + /** Tells the listener something. Runs on the caller's thread. */ + void tell(Consumer news) { + ask(toolListener -> { + news.accept(toolListener); + return true; + }, true); + } + + boolean isClosed() { + return closing.get() || gone.get(); + } + + private void requireOwned(BlockPosition at) { + if (isClosed()) { + throw new IllegalStateException("Tool world " + name + " is closed"); + } + if (!owns(at)) { + throw new IllegalStateException("The calling thread does not own " + at + " in tool world " + name); + } + level(); + } + + private void runGuarded(Runnable task, String what) { + try { + task.run(); + } catch (Throwable failure) { + ModdedIrisLog.error("A task of tool world {} failed: {}.", name, what, failure); + } + } + + @Override + public String toString() { + return "tool world " + name; + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorldService.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorldService.java new file mode 100644 index 000000000..7b165d75d --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorldService.java @@ -0,0 +1,128 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import art.arcane.iris.core.tooling.ToolWorldsHost; +import art.arcane.iris.modded.ModdedIrisLog; +import art.arcane.iris.modded.service.ModdedTickableService; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorlds; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * Tool worlds on a modded server: the platform side of {@code com.volmit.tooling.world}. It hands each pack its + * {@link ToolWorlds} through {@link ToolWorldsHost}, looks at the players once a tick for what the tools hear about them, and + * closes every tool world when it stops. What vanilla code paths tell a tool world arrives through the mixins, which reach + * {@link ToolWorldGuard} and the static hooks here. + */ +public final class ModdedToolWorldService implements ModdedTickableService, ToolWorldsHost { + private static final long CLOSING_WAIT_SECONDS = 30L; + private static final ToolPlayers PLAYERS = new ToolPlayers(); + + static ToolPlayers players() { + return PLAYERS; + } + + /** The tool player for {@code player}, the same object for as long as the player is online. */ + public static ToolPlayer toolPlayerOf(ServerPlayer player) { + return PLAYERS.of(player); + } + + @Override + public ToolWorlds worldsOf(String packName) { + return new ModdedToolWorlds(packName, PLAYERS); + } + + @Override + public void onEnable() { + ToolWorldGuard.resetScopes(); + } + + @Override + public void onServerTick(MinecraftServer server) { + ToolWorldGuard.resetScopes(); + PLAYERS.track(server); + } + + @Override + public void onDisable() { + List open = ToolWorldRegistry.INSTANCE.all(); + awaitClosing(open); + MinecraftServer server = art.arcane.iris.modded.ModdedEngineBootstrap.currentServer(); + open.forEach(world -> world.shutDownNow(server)); + PLAYERS.clear(); + ToolWorldRegistry.INSTANCE.clear(); + } + + /** Lets every tool hear that its world is closing, as a replacement does, so it can save what it holds before the world is gone. */ + private static void awaitClosing(List open) { + CompletableFuture[] closing = open.stream() + .map(world -> world.prepareReplacement(Optional.empty())) + .toArray(CompletableFuture[]::new); + try { + CompletableFuture.allOf(closing).get(CLOSING_WAIT_SECONDS, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } catch (ExecutionException | TimeoutException notReady) { + ModdedIrisLog.error("A tool world was not ready to close when Iris stopped.", notReady); + } + } + + /** Why a studio change must not close the tool worlds now; the first refusal of a tool wins. */ + public static Optional studioChangeRefusal() { + return ToolWorldRegistry.INSTANCE.all().stream() + .map(ModdedToolWorld::closeRefusal) + .flatMap(Optional::stream) + .findFirst(); + } + + /** Closes every tool world for a studio that replaces them or is closed: each tool finishes its work first. */ + public static CompletableFuture closeForStudioChange(Optional by) { + Optional requestedBy = by.map(PLAYERS::of); + List open = ToolWorldRegistry.INSTANCE.all(); + CompletableFuture[] closing = open.stream() + .map(world -> world.prepareReplacement(requestedBy)) + .toArray(CompletableFuture[]::new); + return CompletableFuture.allOf(closing).thenCompose(ignored -> CompletableFuture.allOf( + open.stream().map(ModdedToolWorld::close).toArray(CompletableFuture[]::new))); + } + + /** Minecraft unloaded {@code level}: if it was a tool world, it is gone for the tool. */ + public static void levelUnloaded(ServerLevel level) { + if (ToolWorldRegistry.INSTANCE.hasWorlds()) { + ToolWorldRegistry.INSTANCE.forLevel(level).ifPresent(ModdedToolWorld::unloaded); + } + } + + /** A chunk of {@code level} is live: tells the tool when the level is a tool world. */ + public static void chunkLoaded(ServerLevel level, int chunkX, int chunkZ) { + if (ToolWorldRegistry.INSTANCE.hasWorlds()) { + ToolWorldRegistry.INSTANCE.forLevel(level).ifPresent(world -> world.tell(listener -> listener.chunkLoaded(chunkX, chunkZ))); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorlds.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorlds.java new file mode 100644 index 000000000..040d4edba --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorlds.java @@ -0,0 +1,98 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import art.arcane.iris.modded.ModdedDimensionManager; +import art.arcane.iris.modded.ModdedEngineBootstrap; +import art.arcane.iris.modded.command.ModdedPackCommands; +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldDenied; +import com.volmit.tooling.world.ToolWorldSpec; +import com.volmit.tooling.world.ToolWorlds; +import net.minecraft.server.MinecraftServer; + +import java.io.File; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * The tool worlds of one pack on a modded server. A tool world is made through the runtime dimensions the studio uses, with + * the tool's painter installed before the level exists, so that even the first chunk is the tool's. + */ +final class ModdedToolWorlds implements ToolWorlds { + static final String DIMENSION_NAMESPACE = "irisworldgen"; + private static final String DIMENSION_PREFIX = "tool_"; + private static final long TOOL_WORLD_SEED = 1337L; + + private final String packName; + private final ToolPlayers players; + + ModdedToolWorlds(String packName, ToolPlayers players) { + this.packName = packName; + this.players = players; + } + + @Override + public CompletableFuture open(ToolWorldSpec spec) { + MinecraftServer server = ModdedEngineBootstrap.currentServer(); + if (server == null) { + return CompletableFuture.failedFuture(new IllegalStateException("No server is running")); + } + Optional denial = packDenial(); + if (denial.isPresent()) { + return CompletableFuture.failedFuture(new ToolWorldDenied(denial.get())); + } + String dimensionId = DIMENSION_NAMESPACE + ":" + DIMENSION_PREFIX + UUID.randomUUID().toString().replace("-", ""); + ModdedToolWorld world = new ModdedToolWorld(packName, spec.name(), dimensionId, spec.listener(), + new ModdedToolPainting(spec.painter()), players); + if (!ToolWorldRegistry.INSTANCE.register(world)) { + return CompletableFuture.failedFuture(new IllegalStateException( + "A tool world called " + spec.name() + " is open already in pack " + packName)); + } + CompletableFuture opened = new CompletableFuture<>(); + server.execute(() -> create(server, world, opened)); + return opened; + } + + private void create(MinecraftServer server, ModdedToolWorld world, CompletableFuture opened) { + try { + ModdedDimensionManager.Handle handle = ModdedDimensionManager.create( + server, world.dimensionId(), packName, packName, TOOL_WORLD_SEED, world.painting()); + world.bind(handle.level()); + opened.complete(world); + } catch (Throwable failure) { + world.abandon(); + opened.completeExceptionally(failure); + } + } + + private Optional packDenial() { + File dimension = new File(new File(ModdedPackCommands.packsRoot(), packName), "dimensions/" + packName + ".json"); + if (!dimension.isFile()) { + return Optional.of("Pack " + packName + " is not installed with dimensions/" + packName + ".json"); + } + return Optional.empty(); + } + + @Override + public Optional find(String name) { + return ToolWorldRegistry.INSTANCE.forName(packName, name).filter(ModdedToolWorld::isBound).map(world -> world); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolBlocks.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolBlocks.java new file mode 100644 index 000000000..f48bce566 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolBlocks.java @@ -0,0 +1,160 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.modded.ModdedBlockState; +import art.arcane.iris.modded.ModdedTileData; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; + +import java.util.Optional; + +/** Blocks, positions and block entities between the tool world api and Minecraft. */ +public final class ToolBlocks { + private static final int SILENT_BLOCK_FLAGS = net.minecraft.world.level.block.Block.UPDATE_CLIENTS + | net.minecraft.world.level.block.Block.UPDATE_KNOWN_SHAPE + | net.minecraft.world.level.block.Block.UPDATE_SUPPRESS_DROPS; + private static final PlatformBlockStates PLATFORM_STATES = new PlatformBlockStates(ToolBlocks::platformStateOf); + + private ToolBlocks() { + } + + static BlockPosition positionOf(BlockPos position) { + return new BlockPosition(position.getX(), position.getY(), position.getZ()); + } + + static BlockPos blockPosOf(BlockPosition position) { + return new BlockPos(position.x(), position.y(), position.z()); + } + + /** The complete state of {@code state}, with every property. */ + public static BlockState apiStateOf(net.minecraft.world.level.block.state.BlockState state) { + return BlockState.parse(ModdedBlockState.serialize(state)); + } + + /** + * The platform's state for {@code state}. + * + * @throws IllegalArgumentException when the platform has no such block or property + */ + static net.minecraft.world.level.block.state.BlockState minecraftStateOf(BlockState state) { + return (net.minecraft.world.level.block.state.BlockState) PLATFORM_STATES.toPlatform(state).nativeHandle(); + } + + private static PlatformBlockState platformStateOf(String key) { + PlatformBlockState state = B.getStateOrNull(key, false); + if (state == null) { + throw new IllegalArgumentException("The platform has no block state " + key); + } + return state; + } + + static Optional faceOf(Direction direction) { + return direction == null ? Optional.empty() : Optional.of(BlockFace.valueOf(direction.name())); + } + + /** The block entity at {@code position}, in Iris's tile format; empty for a block without one. */ + public static Optional blockEntityOf(ServerLevel level, BlockPos position) { + BlockEntity blockEntity = level.getBlockEntity(position); + if (blockEntity == null) { + return Optional.empty(); + } + try { + CompoundTag tag = blockEntity.saveWithFullMetadata(level.registryAccess()); + String blockKey = BuiltInRegistries.BLOCK.getKey(blockEntity.getBlockState().getBlock()).toString(); + TileData tile = ModdedTileData.capture(blockKey, NbtUtils.structureToSnbt(tag)); + return Optional.of(BlockEntities.of(tile)); + } catch (java.io.IOException failure) { + throw new java.io.UncheckedIOException("Cannot read the block entity at " + position, failure); + } + } + + /** + * Writes {@code data} into the block entity at {@code position}, which holds the block it was made for already; makes + * the block entity when the block has none yet. + * + * @throws IllegalArgumentException when the block cannot take it, or the data is not in the format Iris stores + */ + static void applyBlockEntity(Level level, BlockPos position, BlockEntityData data) { + ModdedTileData tile = tileOf(data); + net.minecraft.world.level.block.state.BlockState state = level.getBlockState(position); + net.minecraft.world.level.block.state.BlockState adjusted = tile.adjustBlockState(state); + if (adjusted != state) { + level.setBlock(position, adjusted, SILENT_BLOCK_FLAGS); + state = adjusted; + } + BlockEntity blockEntity = level.getBlockEntity(position); + if (blockEntity == null && state.getBlock() instanceof EntityBlock entityBlock) { + blockEntity = entityBlock.newBlockEntity(position, state); + } + if (blockEntity == null || !tile.isApplicable(state, blockEntity)) { + throw new IllegalArgumentException("The block " + state + " at " + position + + " cannot take block entity data of " + tile.getMaterialKey()); + } + level.setBlockEntity(blockEntity); + applyTile(tile, blockEntity, level); + } + + /** Makes the block entity of a block painted into a chunk that is not live yet. */ + static void applyPaintedBlockEntity(net.minecraft.world.level.chunk.ChunkAccess chunk, ServerLevel level, BlockPos position, + net.minecraft.world.level.block.state.BlockState state, BlockEntityData data) { + ModdedTileData tile = tileOf(data); + if (!(state.getBlock() instanceof EntityBlock entityBlock)) { + throw new IllegalArgumentException("The block " + state + " has no block entity for " + tile.getMaterialKey()); + } + BlockEntity blockEntity = entityBlock.newBlockEntity(position, state); + if (blockEntity == null || !tile.isApplicable(state, blockEntity)) { + throw new IllegalArgumentException("The block " + state + " cannot take block entity data of " + tile.getMaterialKey()); + } + chunk.setBlockEntity(blockEntity); + applyTile(tile, blockEntity, level); + } + + private static void applyTile(ModdedTileData tile, BlockEntity blockEntity, Level level) { + try { + tile.apply(blockEntity, (ServerLevel) level); + } catch (Exception failure) { + throw new IllegalArgumentException("The block entity data of " + tile.getMaterialKey() + " was rejected", failure); + } + } + + private static ModdedTileData tileOf(BlockEntityData data) { + TileData tile = BlockEntities.tileOf(data); + if (tile instanceof ModdedTileData moddedTile) { + return moddedTile; + } + throw new IllegalArgumentException("Not block entity data of this platform: " + tile.getMaterialKey()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolItems.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolItems.java new file mode 100644 index 000000000..09e9d7781 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolItems.java @@ -0,0 +1,100 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.CustomData; +import net.minecraft.world.item.component.ItemLore; + +import java.util.List; +import java.util.Optional; + +/** + * {@link ToolItem}s as item stacks. The payload is a string in the custom data component of the stack; its presence is what + * makes a stack a tool item, so an empty payload is stored as an empty string. + */ +final class ToolItems { + static final String PAYLOAD_KEY = "iris_tool_payload"; + + private ToolItems() { + } + + /** + * A new stack of {@code item}. + * + * @throws IllegalArgumentException when the platform has no such item + */ + static ItemStack create(ToolItem item) { + Item type = BuiltInRegistries.ITEM.getOptional(Identifier.parse(item.item().toString())) + .filter(found -> found != Items.AIR) + .orElseThrow(() -> new IllegalArgumentException("The platform has no item " + item.item())); + ItemStack stack = new ItemStack(type); + if (!item.name().isEmpty()) { + stack.set(DataComponents.CUSTOM_NAME, ToolTexts.itemComponent(item.name())); + } + if (!item.lore().isEmpty()) { + stack.set(DataComponents.LORE, new ItemLore(item.lore().stream().map(ToolTexts::itemComponent).toList())); + } + if (item.glowing()) { + stack.set(DataComponents.ENCHANTMENT_GLINT_OVERRIDE, true); + } + CompoundTag data = new CompoundTag(); + data.putString(PAYLOAD_KEY, item.payload()); + stack.set(DataComponents.CUSTOM_DATA, CustomData.of(data)); + return stack; + } + + /** The tool item {@code stack} is; empty for nothing, air or a stack without the tool payload. */ + static Optional read(ItemStack stack) { + if (stack == null || stack.isEmpty()) { + return Optional.empty(); + } + CustomData data = stack.get(DataComponents.CUSTOM_DATA); + if (data == null) { + return Optional.empty(); + } + Optional payload = data.copyTag().getString(PAYLOAD_KEY); + if (payload.isEmpty()) { + return Optional.empty(); + } + Component name = stack.get(DataComponents.CUSTOM_NAME); + ItemLore lore = stack.get(DataComponents.LORE); + return Optional.of(new ToolItem( + ResourceId.parse(BuiltInRegistries.ITEM.getKey(stack.getItem()).toString()), + name == null ? ToolText.EMPTY : plain(name), + lore == null ? List.of() : lore.lines().stream().map(ToolItems::plain).toList(), + Boolean.TRUE.equals(stack.get(DataComponents.ENCHANTMENT_GLINT_OVERRIDE)), + payload.get())); + } + + private static ToolText plain(Component component) { + String text = component.getString(); + return text.isEmpty() ? ToolText.EMPTY : ToolText.plain(text); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolMenus.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolMenus.java new file mode 100644 index 000000000..318632f02 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolMenus.java @@ -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 . + */ + +package art.arcane.iris.modded.toolworld; + +import art.arcane.iris.modded.ModdedIrisLog; +import com.volmit.tooling.world.MenuButton; +import com.volmit.tooling.world.MenuClick; +import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolPlayer; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.Container; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.SimpleMenuProvider; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ChestMenu; +import net.minecraft.world.inventory.ContainerInput; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** The chest menus tools open for players: a server-side chest whose slots are cancelled and routed to the menu's buttons. */ +final class ToolMenus { + private static final int SLOTS_PER_ROW = ToolMenu.SLOTS_PER_ROW; + private static final int RIGHT_BUTTON = 1; + private static final List> TYPES_BY_ROWS = List.of( + MenuType.GENERIC_9x1, MenuType.GENERIC_9x2, MenuType.GENERIC_9x3, + MenuType.GENERIC_9x4, MenuType.GENERIC_9x5, MenuType.GENERIC_9x6); + + private final Map screens = new ConcurrentHashMap<>(); + + /** Opens {@code menu} for {@code viewer}, replacing the one they had. Runs on the server thread. */ + void open(ServerPlayer holder, ToolPlayer viewer, ToolMenu menu) { + Screen open = screens.get(holder.getUUID()); + Component title = ToolTexts.component(menu.title()); + if (open != null && open.showsSameFrame(menu, title) && holder.containerMenu == open) { + open.refill(viewer, menu); + return; + } + close(holder); + holder.openMenu(new SimpleMenuProvider( + (id, inventory, player) -> created(id, inventory, holder, viewer, menu, title), title)); + } + + private ChestMenu created(int id, Inventory inventory, ServerPlayer holder, ToolPlayer viewer, ToolMenu menu, Component title) { + Screen screen = new Screen(id, inventory, menu, title, () -> screens.remove(holder.getUUID())); + screen.refill(viewer, menu); + screens.put(holder.getUUID(), screen); + return screen; + } + + /** Closes the player's menu; does nothing when none is open. Runs on the server thread. */ + void close(ServerPlayer holder) { + Screen open = screens.get(holder.getUUID()); + if (open != null && holder.containerMenu == open) { + holder.closeContainer(); + } + screens.remove(holder.getUUID(), open); + } + + void forget(UUID playerId) { + screens.remove(playerId); + } + + private static final class Screen extends ChestMenu { + private final int rows; + private final Component title; + private final Container container; + private final Runnable forgotten; + private volatile Runnable onClose; + private volatile Map buttons = Map.of(); + private volatile ToolPlayer viewer; + + private Screen(int id, Inventory inventory, ToolMenu menu, Component title, Runnable forgotten) { + this(id, inventory, menu, title, forgotten, new SimpleContainer(menu.rows() * SLOTS_PER_ROW)); + } + + private Screen(int id, Inventory inventory, ToolMenu menu, Component title, Runnable forgotten, Container container) { + super(TYPES_BY_ROWS.get(menu.rows() - 1), id, inventory, container, menu.rows()); + this.rows = menu.rows(); + this.title = title; + this.container = container; + this.forgotten = forgotten; + this.onClose = menu.onClose(); + } + + private boolean showsSameFrame(ToolMenu menu, Component otherTitle) { + return rows == menu.rows() && title.equals(otherTitle); + } + + /** Puts the buttons of {@code menu} in, telling the menu it replaces that it closed. */ + private void refill(ToolPlayer by, ToolMenu menu) { + Runnable replaced = onClose; + onClose = menu.onClose(); + viewer = by; + Map placed = new ConcurrentHashMap<>(); + for (int slot = 0; slot < rows * SLOTS_PER_ROW; slot++) { + container.setItem(slot, filler()); + } + for (MenuButton button : menu.buttons()) { + container.setItem(button.slot(), ToolItems.create(button.icon())); + placed.put(button.slot(), button); + } + buttons = placed; + if (replaced != onClose) { + guarded(replaced, "menu close handler"); + } + broadcastChanges(); + } + + private static ItemStack filler() { + ItemStack pane = new ItemStack(Items.STAINED_GLASS_PANE.black()); + pane.set(DataComponents.CUSTOM_NAME, Component.literal(" ")); + return pane; + } + + @Override + public void clicked(int slot, int button, ContainerInput input, Player player) { + MenuButton pressed = slot >= 0 ? buttons.get(slot) : null; + sendAllDataToRemote(); + if (pressed == null || viewer == null) { + return; + } + MenuClick click = clickOf(input, button); + if (click == null) { + return; + } + guarded(() -> pressed.action().accept(click), "menu button"); + } + + private MenuClick clickOf(ContainerInput input, int button) { + boolean right = button == RIGHT_BUTTON; + return switch (input) { + case PICKUP -> new MenuClick(viewer, right, false); + case QUICK_MOVE -> new MenuClick(viewer, right, true); + case CLONE -> new MenuClick(viewer, false, false, true); + default -> null; + }; + } + + @Override + public void removed(Player player) { + super.removed(player); + forgotten.run(); + guarded(onClose, "menu close handler"); + } + + private static void guarded(Runnable task, String what) { + try { + task.run(); + } catch (RuntimeException failure) { + ModdedIrisLog.error("A tool failed in the {}.", what, failure); + } + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolPlayers.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolPlayers.java new file mode 100644 index 000000000..b91b5dc37 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolPlayers.java @@ -0,0 +1,222 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import art.arcane.iris.modded.ModdedDimensionManager; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.ToolPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.levelgen.Heightmap; + +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.Map; + +/** + * The tool players of a modded server, and what the host remembers about them: where they came from, the game mode they had + * before the tool made them creative, and which tool world they were last seen in. Presence is found by looking at every + * player once a tick, because Minecraft tells loaders nothing common about arrivals, departures and steps. + */ +final class ToolPlayers { + private static final double TELEPORT_DISTANCE_BLOCKS = 10.0D; + + /** Where a player stood before they entered a tool world. */ + private record Origin(ResourceKey dimension, double x, double y, double z, float yaw, float pitch) { + static Origin of(ServerPlayer player) { + return new Origin(player.level().dimension(), player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); + } + } + + /** What the last look at a player saw. */ + private static final class Seen { + private ModdedToolWorld world; + private BlockPosition block; + private boolean sneaking; + private double x; + private double y; + private double z; + private Origin lastOutsideToolWorlds; + } + + private final ToolMenus menus = new ToolMenus(); + private final ToolSidebars sidebars = new ToolSidebars(); + private final Map known = new ConcurrentHashMap<>(); + private final Map origins = new ConcurrentHashMap<>(); + private final Map modesBeforeCreative = new ConcurrentHashMap<>(); + private final Map seen = new ConcurrentHashMap<>(); + + ToolSidebars sidebars() { + return sidebars; + } + + ModdedToolPlayer playerOf(ServerPlayer player) { + return known.computeIfAbsent(player.getUUID(), + id -> new ModdedToolPlayer(id, player.getScoreboardName(), this, menus)); + } + + ToolPlayer of(ServerPlayer player) { + return playerOf(player); + } + + void rememberModeBeforeCreative(ServerPlayer player) { + modesBeforeCreative.putIfAbsent(player.getUUID(), player.gameMode()); + } + + void restoreGameMode(ServerPlayer player) { + GameType before = modesBeforeCreative.remove(player.getUUID()); + if (before != null) { + player.setGameMode(before); + } + } + + /** Sends the player to where they came from, or to the spawn of the main world when that is not known or is a tool world. */ + CompletableFuture destinationAfterToolWorld(ServerPlayer player) { + MinecraftServer server = player.level().getServer(); + Origin origin = origins.remove(player.getUUID()); + ServerLevel back = origin == null ? null : server.getLevel(origin.dimension()); + if (back == null || ToolWorldRegistry.INSTANCE.forLevel(back).isPresent()) { + return teleportToMainSpawn(player, server); + } + return ModdedDimensionManager.teleportAsync(player, server, back, origin.x(), origin.y(), origin.z()) + .thenApply(arrived -> faceAfterReturn(player, back, origin, arrived)); + } + + private static boolean faceAfterReturn(ServerPlayer player, ServerLevel back, Origin origin, Boolean arrived) { + if (Boolean.TRUE.equals(arrived)) { + player.teleportTo(back, player.getX(), player.getY(), player.getZ(), Set.of(), origin.yaw(), origin.pitch(), false); + } + return Boolean.TRUE.equals(arrived); + } + + private static CompletableFuture teleportToMainSpawn(ServerPlayer player, MinecraftServer server) { + ServerLevel main = server.overworld(); + BlockPos spawn = main.getRespawnData().pos(); + int spawnY = main.getHeight(Heightmap.Types.MOTION_BLOCKING, spawn.getX(), spawn.getZ()); + return ModdedDimensionManager.teleportAsync(player, server, main, spawn.getX() + 0.5D, spawnY, spawn.getZ() + 0.5D); + } + + /** Looks at every player once, and tells the tool worlds what changed since the last look. Runs on the server thread. */ + void track(MinecraftServer server) { + if (!ToolWorldRegistry.INSTANCE.hasWorlds() && seen.isEmpty()) { + return; + } + Set online = new java.util.HashSet<>(); + for (ServerPlayer player : server.getPlayerList().getPlayers()) { + online.add(player.getUUID()); + trackOne(player); + } + seen.keySet().removeIf(id -> !online.contains(id) && playerLeftServer(id)); + } + + private boolean playerLeftServer(UUID id) { + Seen last = seen.get(id); + ModdedToolPlayer player = known.remove(id); + if (last != null && last.world != null && player != null) { + last.world.tell(listener -> listener.left(player)); + } + origins.remove(id); + modesBeforeCreative.remove(id); + menus.forget(id); + sidebars.forget(id); + return true; + } + + private void trackOne(ServerPlayer player) { + Seen last = seen.computeIfAbsent(player.getUUID(), id -> new Seen()); + Optional now = player.level() instanceof ServerLevel level + ? ToolWorldRegistry.INSTANCE.forLevel(level) : Optional.empty(); + ModdedToolWorld current = now.orElse(null); + if (last.world != current) { + changedWorld(player, last, current); + } else if (current != null) { + moved(player, last, current); + } + if (current == null) { + last.lastOutsideToolWorlds = Origin.of(player); + } + remember(player, last, current); + } + + private void changedWorld(ServerPlayer player, Seen last, ModdedToolWorld current) { + ModdedToolPlayer toolPlayer = playerOf(player); + ModdedToolWorld before = last.world; + if (before == null) { + origins.put(player.getUUID(), last.lastOutsideToolWorlds != null ? last.lastOutsideToolWorlds : Origin.of(player)); + } + if (before != null) { + before.tell(listener -> listener.left(toolPlayer)); + } + if (current == null) { + restoreGameMode(player); + origins.remove(player.getUUID()); + sidebars.hide(player); + return; + } + BlockPosition arrival = ToolBlocks.positionOf(player.blockPosition()); + current.tell(listener -> listener.entered(toolPlayer)); + current.tell(listener -> listener.teleported(toolPlayer, arrival)); + } + + private void moved(ServerPlayer player, Seen last, ModdedToolWorld current) { + ModdedToolPlayer toolPlayer = playerOf(player); + BlockPosition block = ToolBlocks.positionOf(player.blockPosition()); + if (!block.equals(last.block)) { + double dx = player.getX() - last.x; + double dy = player.getY() - last.y; + double dz = player.getZ() - last.z; + boolean teleport = dx * dx + dy * dy + dz * dz > TELEPORT_DISTANCE_BLOCKS * TELEPORT_DISTANCE_BLOCKS; + current.tell(listener -> { + if (teleport) { + listener.teleported(toolPlayer, block); + } else { + listener.moved(toolPlayer, block); + } + }); + } + if (player.isShiftKeyDown() != last.sneaking) { + boolean sneaking = player.isShiftKeyDown(); + current.tell(listener -> listener.sneakToggled(toolPlayer, sneaking)); + } + } + + private static void remember(ServerPlayer player, Seen last, ModdedToolWorld current) { + last.world = current; + last.block = ToolBlocks.positionOf(player.blockPosition()); + last.sneaking = player.isShiftKeyDown(); + last.x = player.getX(); + last.y = player.getY(); + last.z = player.getZ(); + } + + void clear() { + known.clear(); + origins.clear(); + modesBeforeCreative.clear(); + seen.clear(); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolSidebars.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolSidebars.java new file mode 100644 index 000000000..92a44950d --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolSidebars.java @@ -0,0 +1,84 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import com.volmit.tooling.world.ToolText; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.numbers.BlankFormat; +import net.minecraft.network.protocol.game.ClientboundResetScorePacket; +import net.minecraft.network.protocol.game.ClientboundSetDisplayObjectivePacket; +import net.minecraft.network.protocol.game.ClientboundSetObjectivePacket; +import net.minecraft.network.protocol.game.ClientboundSetScorePacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.scores.DisplaySlot; +import net.minecraft.world.scores.Objective; +import net.minecraft.world.scores.Scoreboard; +import net.minecraft.world.scores.criteria.ObjectiveCriteria; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The sidebar a tool shows one player: a scoreboard objective in the sidebar slot that only that player's client is told + * about, so the server's own scoreboard and other players are left alone. + */ +final class ToolSidebars { + private static final String OBJECTIVE_NAME = "iris_tool"; + private static final String LINE_OWNER_PREFIX = "iris_tool_line_"; + + private final Map shownLines = new ConcurrentHashMap<>(); + + /** Shows {@code title} over {@code lines}, replacing the sidebar the player had. Runs on the server thread. */ + void show(ServerPlayer player, ToolText title, List lines) { + Objective objective = objective(ToolTexts.component(title)); + boolean shownBefore = shownLines.containsKey(player.getUUID()); + player.connection.send(new ClientboundSetObjectivePacket(objective, + shownBefore ? ClientboundSetObjectivePacket.METHOD_CHANGE : ClientboundSetObjectivePacket.METHOD_ADD)); + player.connection.send(new ClientboundSetDisplayObjectivePacket(DisplaySlot.SIDEBAR, objective)); + for (int index = 0; index < lines.size(); index++) { + player.connection.send(new ClientboundSetScorePacket(LINE_OWNER_PREFIX + index, OBJECTIVE_NAME, + lines.size() - index, Optional.of(ToolTexts.component(lines.get(index))), Optional.of(BlankFormat.INSTANCE))); + } + for (int stale = lines.size(); stale < shownLines.getOrDefault(player.getUUID(), 0); stale++) { + player.connection.send(new ClientboundResetScorePacket(LINE_OWNER_PREFIX + stale, OBJECTIVE_NAME)); + } + shownLines.put(player.getUUID(), lines.size()); + } + + /** Takes the sidebar away; does nothing when none is shown. Runs on the server thread. */ + void hide(ServerPlayer player) { + if (shownLines.remove(player.getUUID()) == null) { + return; + } + player.connection.send(new ClientboundSetObjectivePacket(objective(Component.empty()), + ClientboundSetObjectivePacket.METHOD_REMOVE)); + } + + void forget(UUID playerId) { + shownLines.remove(playerId); + } + + private static Objective objective(Component title) { + return new Objective(new Scoreboard(), OBJECTIVE_NAME, ObjectiveCriteria.DUMMY, title, + ObjectiveCriteria.RenderType.INTEGER, false, BlankFormat.INSTANCE); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolTexts.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolTexts.java new file mode 100644 index 000000000..3cf899503 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolTexts.java @@ -0,0 +1,88 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; + +import java.util.EnumMap; +import java.util.Map; + +/** {@link ToolText} as the components Minecraft shows. */ +final class ToolTexts { + private static final Map COLORS = new EnumMap<>(Map.ofEntries( + Map.entry(TextColor.BLACK, ChatFormatting.BLACK), + Map.entry(TextColor.DARK_BLUE, ChatFormatting.DARK_BLUE), + Map.entry(TextColor.DARK_GREEN, ChatFormatting.DARK_GREEN), + Map.entry(TextColor.DARK_AQUA, ChatFormatting.DARK_AQUA), + Map.entry(TextColor.DARK_RED, ChatFormatting.DARK_RED), + Map.entry(TextColor.DARK_PURPLE, ChatFormatting.DARK_PURPLE), + Map.entry(TextColor.GOLD, ChatFormatting.GOLD), + Map.entry(TextColor.GRAY, ChatFormatting.GRAY), + Map.entry(TextColor.DARK_GRAY, ChatFormatting.DARK_GRAY), + Map.entry(TextColor.BLUE, ChatFormatting.BLUE), + Map.entry(TextColor.GREEN, ChatFormatting.GREEN), + Map.entry(TextColor.AQUA, ChatFormatting.AQUA), + Map.entry(TextColor.RED, ChatFormatting.RED), + Map.entry(TextColor.LIGHT_PURPLE, ChatFormatting.LIGHT_PURPLE), + Map.entry(TextColor.YELLOW, ChatFormatting.YELLOW), + Map.entry(TextColor.WHITE, ChatFormatting.WHITE))); + + private ToolTexts() { + } + + /** Chat, action bar, titles and sidebar lines: unstyled spans keep the platform's own look. */ + static Component component(ToolText text) { + return build(text, false); + } + + /** Item names and lore: vanilla shows them in italics unless told not to, so a span is italic only when it asks to be. */ + static Component itemComponent(ToolText text) { + return build(text, true); + } + + private static Component build(ToolText text, boolean explicitItalics) { + MutableComponent whole = Component.empty(); + for (ToolText.Span span : text.spans()) { + whole.append(Component.literal(span.text()).setStyle(styleOf(span, explicitItalics))); + } + return whole; + } + + private static Style styleOf(ToolText.Span span, boolean explicitItalics) { + Style style = Style.EMPTY; + if (span.color() != null) { + style = style.withColor(COLORS.get(span.color())); + } + if (span.bold()) { + style = style.withBold(true); + } + if (span.italic() || explicitItalics) { + style = style.withItalic(span.italic()); + } + if (span.strikethrough()) { + style = style.withStrikethrough(true); + } + return style; + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldGuard.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldGuard.java new file mode 100644 index 000000000..221a4bfdd --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldGuard.java @@ -0,0 +1,187 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.BlockChange; +import com.volmit.tooling.world.BlockChange.Cause; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolUse; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.tags.BlockTags; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BonemealableBlock; + +import java.util.List; +import java.util.Optional; + +/** + * Where the vanilla code paths of a tool world ask the tool. Every change to a block of a tool world passes + * {@link #setBlockAllowed}: the host's own writes pass, a change inside a {@link Scope} that names its cause is put to the + * tool as that cause, and a change nobody named a cause for is refused, so the world stays frozen where Bukkit would not + * have been asked. The scopes are entered by the mixins at the places vanilla starts a kind of change. + */ +public final class ToolWorldGuard { + private static final ThreadLocal CURRENT = new ThreadLocal<>(); + private static final ThreadLocal HOST_WRITES = ThreadLocal.withInitial(() -> 0); + + private ToolWorldGuard() { + } + + /** What a thread is doing to a tool world, which tells its block changes apart. */ + private static final class Scope { + private final Level level; + private final Cause cause; + private final Entity actor; + private final boolean approved; + private final Scope previous; + + private Scope(Level level, Cause cause, Entity actor, boolean approved, Scope previous) { + this.level = level; + this.cause = cause; + this.actor = actor; + this.approved = approved; + this.previous = previous; + } + } + + /** Whether {@code level} is a tool world. Cheap enough to ask for every block change of every world. */ + public static boolean isToolWorld(Level level) { + return ToolWorldRegistry.INSTANCE.hasWorlds() && level instanceof ServerLevel serverLevel + && ToolWorldRegistry.INSTANCE.forLevel(serverLevel).isPresent(); + } + + /** Runs the host's own write to a tool world, which no tool is asked about. */ + static void hostWrite(Runnable write) { + HOST_WRITES.set(HOST_WRITES.get() + 1); + try { + write.run(); + } finally { + HOST_WRITES.set(HOST_WRITES.get() - 1); + } + } + + /** + * Starts a kind of change in {@code level}. A {@code null} cause is told apart per block by what changes, as a random tick + * does. {@code approved} lets everything inside through, for what the tool was asked about already. + * + * @return whether {@code level} is a tool world, which is whether {@link #exit} must follow + */ + public static boolean enter(Level level, Cause cause, Entity actor, boolean approved) { + if (!isToolWorld(level)) { + return false; + } + CURRENT.set(new Scope(level, cause, actor, approved, CURRENT.get())); + return true; + } + + /** Ends the innermost scope of {@code level}; does nothing for a level that is no tool world. */ + public static void exit(Level level) { + Scope scope = CURRENT.get(); + if (scope != null && scope.level == level) { + CURRENT.set(scope.previous); + } + } + + /** Drops scopes a failed call left behind. */ + public static void resetScopes() { + CURRENT.remove(); + HOST_WRITES.remove(); + } + + /** Whether the block at {@code position} of {@code level} may become {@code newState} now. */ + public static boolean setBlockAllowed(Level level, BlockPos position, net.minecraft.world.level.block.state.BlockState newState) { + if (!isToolWorld(level) || HOST_WRITES.get() > 0) { + return true; + } + Scope scope = CURRENT.get(); + if (scope == null || scope.level != level) { + return false; + } + if (scope.approved) { + return true; + } + net.minecraft.world.level.block.state.BlockState old = level.getBlockState(position); + if (old == newState) { + return true; + } + Cause cause = scope.cause != null ? scope.cause : classifyTickChange(old, newState); + Optional placed = cause == Cause.PLACE ? Optional.of(ToolBlocks.apiStateOf(newState)) : Optional.empty(); + return allowed(level, cause, actorPlayer(scope.actor), List.of(ToolBlocks.positionOf(position)), placed); + } + + private static Cause classifyTickChange(net.minecraft.world.level.block.state.BlockState old, + net.minecraft.world.level.block.state.BlockState replacement) { + if (old.is(BlockTags.FIRE) || replacement.is(BlockTags.FIRE)) { + return Cause.FIRE; + } + if (old.getBlock() instanceof BonemealableBlock) { + return Cause.GROWTH; + } + return Cause.PHYSICS; + } + + /** Whether the tool lets a change of {@code cause} to {@code positions} happen; changes outside tool worlds are none of the host's business. */ + public static boolean allowed(Level level, Cause cause, Optional player, List positions, + Optional placed) { + return allowed(level, cause, player, positions, positions, placed); + } + + public static boolean allowed(Level level, Cause cause, Optional player, List positions, + List changed, Optional placed) { + Optional world = worldOf(level); + if (world.isEmpty()) { + return true; + } + BlockChange change = new BlockChange(cause, positions, changed, player, placed); + return world.get().ask(listener -> listener.blockChanging(change), false); + } + + /** Whether the tool lets {@code player} use their hand as {@code use} describes. */ + public static boolean usingAllowed(ServerPlayer player, ToolUse use) { + Optional world = worldOf(player.level()); + if (world.isEmpty()) { + return true; + } + ToolPlayer toolPlayer = ModdedToolWorldService.players().of(player); + return world.get().ask(listener -> listener.used(toolPlayer, use), false); + } + + public static Optional toolPlayerOf(Entity entity) { + return actorPlayer(entity); + } + + static Optional worldOf(Level level) { + if (!ToolWorldRegistry.INSTANCE.hasWorlds() || !(level instanceof ServerLevel serverLevel)) { + return Optional.empty(); + } + return ToolWorldRegistry.INSTANCE.forLevel(serverLevel); + } + + private static Optional actorPlayer(Entity actor) { + if (actor instanceof ServerPlayer player) { + return Optional.of(ModdedToolWorldService.players().of(player)); + } + return Optional.empty(); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldHooks.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldHooks.java new file mode 100644 index 000000000..8facbaaed --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldHooks.java @@ -0,0 +1,239 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import art.arcane.iris.modded.structure.PrivateFields; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.BlockChange.Cause; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolUse; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.CompoundContainer; +import net.minecraft.world.Container; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.piston.PistonStructureResolver; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** What the mixins ask of a tool world for each kind of thing a player or the world does; all of it answers "allowed" outside tool worlds. */ +public final class ToolWorldHooks { + private static final String COMMAND_PREFIX = "/"; + private static final double LEFT_CLICK_REACH_BLOCKS = 5.0D; + + private ToolWorldHooks() { + } + + // What players do with their hands. + + public static boolean rightClickBlockAllowed(ServerPlayer player, InteractionHand hand, ItemStack stack, BlockHitResult hit) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return true; + } + return ToolWorldGuard.usingAllowed(player, new ToolUse(handOf(hand), ToolUse.Action.RIGHT_CLICK_BLOCK, + ToolItems.read(stack), Optional.of(ToolBlocks.positionOf(hit.getBlockPos())), ToolBlocks.faceOf(hit.getDirection()))); + } + + public static boolean rightClickAirAllowed(ServerPlayer player, InteractionHand hand, ItemStack stack) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return true; + } + return ToolWorldGuard.usingAllowed(player, new ToolUse(handOf(hand), ToolUse.Action.RIGHT_CLICK_AIR, + ToolItems.read(stack), Optional.empty(), Optional.empty())); + } + + /** Asks the tool about a left click on a block; a refusal puts the block back on the player's screen. */ + public static boolean leftClickBlockAllowed(ServerPlayer player, BlockPos at, Direction face, int sequence) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return true; + } + ToolUse use = new ToolUse(ToolUse.Hand.MAIN, ToolUse.Action.LEFT_CLICK_BLOCK, + ToolItems.read(player.getMainHandItem()), Optional.of(ToolBlocks.positionOf(at)), ToolBlocks.faceOf(face)); + if (ToolWorldGuard.usingAllowed(player, use)) { + return true; + } + player.connection.send(new ClientboundBlockUpdatePacket(at, player.level().getBlockState(at))); + player.connection.ackBlockChangesUpTo(sequence); + return false; + } + + /** Tells the tool about a swing at nothing; a swing at a block is the left click on the block. */ + public static void leftClickAir(ServerPlayer player, InteractionHand hand) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return; + } + HitResult target = player.pick(LEFT_CLICK_REACH_BLOCKS, 1.0F, false); + if (target.getType() == HitResult.Type.BLOCK) { + return; + } + ToolWorldGuard.usingAllowed(player, new ToolUse(handOf(hand), ToolUse.Action.LEFT_CLICK_AIR, + ToolItems.read(player.getItemInHand(hand)), Optional.empty(), Optional.empty())); + } + + private static ToolUse.Hand handOf(InteractionHand hand) { + return hand == InteractionHand.OFF_HAND ? ToolUse.Hand.OFF : ToolUse.Hand.MAIN; + } + + // Block changes a player starts. + + public static boolean placeAllowed(Level level, Entity actor, BlockPos at, BlockState placed) { + if (!ToolWorldGuard.isToolWorld(level)) { + return true; + } + Optional state = placed == null ? Optional.empty() : Optional.of(ToolBlocks.apiStateOf(placed)); + return ToolWorldGuard.allowed(level, Cause.PLACE, ToolWorldGuard.toolPlayerOf(actor), List.of(ToolBlocks.positionOf(at)), state); + } + + public static boolean breakAllowed(Level level, ServerPlayer actor, BlockPos at) { + return ToolWorldGuard.allowed(level, Cause.BREAK, ToolWorldGuard.toolPlayerOf(actor), List.of(ToolBlocks.positionOf(at)), Optional.empty()); + } + + public static boolean bucketEmptyAllowed(Level level, LivingEntity actor, BlockPos at) { + return ToolWorldGuard.allowed(level, Cause.BUCKET, ToolWorldGuard.toolPlayerOf(actor), List.of(ToolBlocks.positionOf(at)), Optional.empty()); + } + + // Pistons. + + /** Asks about each block a piston moves and the block each of them enters and leaves, and about the piston itself. */ + public static boolean pistonMoveAllowed(Level level, BlockPos piston, Direction direction, boolean extending) { + if (!ToolWorldGuard.isToolWorld(level)) { + return true; + } + PistonStructureResolver resolver = new PistonStructureResolver(level, piston, direction, extending); + if (!resolver.resolve()) { + return true; + } + List moved = new ArrayList<>(resolver.getToPush()); + moved.addAll(resolver.getToDestroy()); + List checked = new ArrayList<>(); + List changed = new ArrayList<>(); + changed.add(ToolBlocks.positionOf(piston)); + changed.add(ToolBlocks.positionOf(piston.relative(direction))); + for (BlockPos block : moved) { + checked.add(ToolBlocks.positionOf(block)); + checked.add(ToolBlocks.positionOf(block.relative(direction))); + checked.add(ToolBlocks.positionOf(block.relative(direction.getOpposite()))); + changed.add(ToolBlocks.positionOf(block)); + changed.add(ToolBlocks.positionOf(block.relative(direction))); + } + if (checked.isEmpty()) { + return true; + } + return ToolWorldGuard.allowed(level, Cause.PISTON, Optional.empty(), + checked.stream().distinct().toList(), changed.stream().distinct().toList(), Optional.empty()); + } + + // Containers and machines. + + public static boolean containerClickAllowed(ServerPlayer player, AbstractContainerMenu menu) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return true; + } + List blocks = containerBlocks(menu); + if (blocks.isEmpty()) { + return true; + } + return ToolWorldGuard.allowed(player.level(), Cause.CONTAINER, ToolWorldGuard.toolPlayerOf(player), blocks, Optional.empty()); + } + + /** Tells the tool that the inventory of a container block was closed, which may have changed what is in it. */ + public static void containerClosed(Entity closer, AbstractContainerMenu menu) { + Optional world = ToolWorldGuard.worldOf(closer.level()); + if (world.isEmpty() || !(closer instanceof ServerPlayer player)) { + return; + } + Optional toolPlayer = ToolWorldGuard.toolPlayerOf(player); + for (BlockPosition block : containerBlocks(menu)) { + world.get().tell(listener -> listener.containerChanged(toolPlayer, block)); + } + } + + /** The blocks the container inventory of {@code menu} is made of: none for a player's or a menu, two for a double chest. */ + private static List containerBlocks(AbstractContainerMenu menu) { + List blocks = new ArrayList<>(2); + for (Slot slot : menu.slots) { + addBlocksOf(blocks, slot.container); + } + return blocks; + } + + private static void addBlocksOf(List blocks, Container container) { + if (container instanceof CompoundContainer compound) { + addBlocksOf(blocks, PrivateFields.read(compound, "container1", Container.class)); + addBlocksOf(blocks, PrivateFields.read(compound, "container2", Container.class)); + return; + } + if (container instanceof BlockEntity blockEntity) { + BlockPosition at = ToolBlocks.positionOf(blockEntity.getBlockPos()); + if (!blocks.contains(at)) { + blocks.add(at); + } + } + } + + public static boolean machineAllowed(Level level, BlockPos at) { + if (!ToolWorldGuard.isToolWorld(level)) { + return true; + } + return ToolWorldGuard.allowed(level, Cause.MACHINE, Optional.empty(), List.of(ToolBlocks.positionOf(at)), Optional.empty()); + } + + // Commands. + + /** Asks the tool world a player stands in about their command; a command from anywhere else is every tool world's to hear. */ + public static boolean commandAllowed(CommandSourceStack source, String typed) { + if (!ToolWorldRegistry.INSTANCE.hasWorlds()) { + return true; + } + String line = typed.startsWith(COMMAND_PREFIX) ? typed.substring(COMMAND_PREFIX.length()) : typed; + ServerPlayer player = source.getPlayer(); + if (player != null) { + return playerCommandAllowed(player, line); + } + return ToolWorldRegistry.INSTANCE.all().stream().allMatch(world -> world.ask(listener -> listener.command(Optional.empty(), line), true)); + } + + private static boolean playerCommandAllowed(ServerPlayer player, String line) { + if (!(player.level() instanceof ServerLevel level)) { + return true; + } + Optional world = ToolWorldRegistry.INSTANCE.forLevel(level); + if (world.isEmpty()) { + return true; + } + ToolPlayer toolPlayer = ModdedToolWorldService.toolPlayerOf(player); + return world.get().ask(listener -> listener.command(Optional.of(toolPlayer), line), true); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldRegistry.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldRegistry.java new file mode 100644 index 000000000..0e67ed898 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldRegistry.java @@ -0,0 +1,72 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import net.minecraft.server.level.ServerLevel; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** The tool worlds that exist, from before their level is made until it is gone. */ +final class ToolWorldRegistry { + static final ToolWorldRegistry INSTANCE = new ToolWorldRegistry(); + + private final Map byDimensionId = new ConcurrentHashMap<>(); + + private ToolWorldRegistry() { + } + + /** Whether any tool world exists; the mixins ask this first so a server with none pays one read. */ + boolean hasWorlds() { + return !byDimensionId.isEmpty(); + } + + /** Registers {@code world}; false when its pack has a tool world of that name already. */ + synchronized boolean register(ModdedToolWorld world) { + if (forName(world.packName(), world.name()).isPresent()) { + return false; + } + byDimensionId.put(world.dimensionId(), world); + return true; + } + + void unregister(ModdedToolWorld world) { + byDimensionId.remove(world.dimensionId(), world); + } + + Optional forLevel(ServerLevel level) { + return Optional.ofNullable(byDimensionId.get(level.dimension().identifier().toString())); + } + + Optional forName(String packName, String name) { + return byDimensionId.values().stream() + .filter(world -> world.packName().equals(packName) && world.name().equals(name)) + .findFirst(); + } + + List all() { + return List.copyOf(byDimensionId.values()); + } + + void clear() { + byDimensionId.clear(); + } +} diff --git a/adapters/modded-common/src/main/resources/irisworldgen.entity.mixins.json b/adapters/modded-common/src/main/resources/irisworldgen.entity.mixins.json index e7b5a28e2..be27aaf09 100644 --- a/adapters/modded-common/src/main/resources/irisworldgen.entity.mixins.json +++ b/adapters/modded-common/src/main/resources/irisworldgen.entity.mixins.json @@ -4,9 +4,27 @@ "package": "art.arcane.iris.modded.mixin", "compatibilityLevel": "JAVA_21", "mixins": [ + "AbstractContainerMenuToolMixin", + "BlockItemToolMixin", + "BrewingStandToolMixin", + "BucketItemToolMixin", + "CommandsToolMixin", + "CrafterToolMixin", + "DispenserToolMixin", "EntityPersistenceMixin", + "EntityToolMixin", + "FurnaceToolMixin", + "LevelChunkToolMixin", + "LevelToolMixin", "LivingEntityLootMixin", "MobAwarenessMixin", + "NaturalSpawnerToolMixin", + "PistonBaseBlockToolMixin", + "SaplingBlockToolMixin", + "ServerExplosionToolMixin", + "ServerGamePacketListenerToolMixin", + "ServerLevelToolMixin", + "ServerPlayerGameModeToolMixin", "StructureTemplatePaletteConcurrencyMixin" ], "injectors": { diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/structure/PlatformStructuresVanillaTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/structure/PlatformStructuresVanillaTest.java new file mode 100644 index 000000000..cfd4b14eb --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/structure/PlatformStructuresVanillaTest.java @@ -0,0 +1,171 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.structure; + +import com.mojang.datafixers.util.Pair; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.JigsawStructureInfo; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplateBlock; +import com.volmit.tooling.TemplatePool; +import net.minecraft.SharedConstants; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.registries.VanillaRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.IntTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement; +import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; +import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** The records the tools read from vanilla data: the values the Bukkit host reads from the same data. */ +public class PlatformStructuresVanillaTest { + private static final String VILLAGE = "minecraft:village_plains"; + private static final String VILLAGE_START_POOL = "minecraft:village/plains/town_centers"; + private static final int VILLAGE_DEPTH = 6; + private static final int VILLAGE_DISTANCE = 80; + + private static HolderLookup.Provider vanilla; + + @BeforeClass + public static void bootstrapMinecraftRegistries() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + vanilla = VanillaRegistries.createLookup(); + } + + private static ListTag intsOf(int... values) { + ListTag list = new ListTag(); + for (int value : values) { + list.add(IntTag.valueOf(value)); + } + return list; + } + + private static CompoundTag blockOf(int state, int x, CompoundTag nbt) { + CompoundTag block = new CompoundTag(); + block.put("pos", intsOf(x, 0, 0)); + block.putInt("state", state); + if (nbt != null) { + block.put("nbt", nbt); + } + return block; + } + + /** A template of a stone block and a jigsaw block whose final state is oak planks, in the form a template file stores. */ + private static CompoundTag templateTag() { + CompoundTag finalState = new CompoundTag(); + finalState.putString("final_state", "minecraft:oak_planks"); + finalState.putString("id", "minecraft:jigsaw"); + finalState.putString("name", "minecraft:empty"); + finalState.putString("target", "minecraft:empty"); + finalState.putString("pool", "minecraft:empty"); + finalState.putString("joint", "rollable"); + ListTag palette = new ListTag(); + palette.add(NbtUtils.writeBlockState(Blocks.STONE.defaultBlockState())); + palette.add(NbtUtils.writeBlockState(Blocks.JIGSAW.defaultBlockState())); + ListTag blocks = new ListTag(); + blocks.add(blockOf(0, 0, null)); + blocks.add(blockOf(1, 1, finalState)); + CompoundTag tag = new CompoundTag(); + tag.put("size", intsOf(2, 1, 1)); + tag.put("palette", palette); + tag.put("blocks", blocks); + tag.put("entities", new ListTag()); + return tag; + } + + private static T registered(ResourceKey> registry, String key) { + return vanilla.lookupOrThrow(registry) + .getOrThrow(ResourceKey.create(registry, Identifier.parse(key))).value(); + } + + @Test + public void aVanillaJigsawStructureReadsAsItsStartPoolDepthAndDistance() { + JigsawStructure village = (JigsawStructure) registered(Registries.STRUCTURE, VILLAGE); + Identifier startPool = village.getStartPool().unwrapKey().orElseThrow().identifier(); + + JigsawStructureInfo info = ModdedPlatformStructures.jigsawInfoOf(ResourceId.parse(VILLAGE), village, startPool, "26.2"); + + assertEquals(ResourceId.parse(VILLAGE_START_POOL), info.startPool()); + assertEquals(VILLAGE_DEPTH, info.maxDepth()); + assertEquals(VILLAGE_DISTANCE, info.maxDistance()); + assertEquals("26.2", info.gameVersion()); + } + + @Test + public void theShuffleSeedIsTheHashBukkitGivesTheSameKey() { + long bukkitHash = 31 * "minecraft".hashCode() + "village_plains".hashCode(); + + assertEquals(bukkitHash, ModdedPlatformStructures.shuffleSeedOf(ResourceId.parse(VILLAGE))); + } + + @Test + public void aVanillaPoolReadsAsWeightedElementsWithTheirTemplates() { + StructureTemplatePool pool = registered(Registries.TEMPLATE_POOL, VILLAGE_START_POOL); + + assertTrue("pool " + pool + " has " + pool.getTemplates().size(), !pool.getTemplates().isEmpty()); + for (Pair pair : pool.getTemplates()) { + TemplatePool.Member member = PoolReading.memberOf(pair, null); + TemplatePool.Element element = (TemplatePool.Element) member; + assertEquals(Math.max(1, pair.getSecond()), element.weight()); + assertEquals("minecraft", element.template().orElseThrow().namespace()); + assertTrue("template of " + element, element.template().orElseThrow().path().startsWith("village/plains/")); + } + } + + @Test + public void aTemplateReadsAsItsSizeBlocksAndJigsawFinalState() throws Exception { + net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate template = + new net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate(); + template.load(BuiltInRegistries.BLOCK, templateTag()); + + StructureTemplate read = TemplateReading.read(template).orElseThrow(); + + assertEquals(new BlockPosition(2, 1, 1), read.size()); + assertEquals(1, read.paletteCount()); + assertEquals(0, read.entityCount()); + assertEquals(2, read.blocks().size()); + TemplateBlock stone = read.blocks().get(0); + assertEquals(new BlockPosition(0, 0, 0), stone.position()); + assertEquals(BlockState.parse("minecraft:stone"), stone.state()); + assertEquals(Optional.empty(), stone.jigsawFinalState()); + TemplateBlock jigsaw = read.blocks().get(1); + assertEquals(new BlockPosition(1, 0, 0), jigsaw.position()); + assertEquals(BlockState.parse("minecraft:jigsaw[orientation=north_up]"), jigsaw.state()); + assertEquals(Optional.of("minecraft:oak_planks"), jigsaw.jigsawFinalState()); + assertEquals(Optional.empty(), jigsaw.blockEntity()); + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolItemsTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolItemsTest.java new file mode 100644 index 000000000..fa4613c2f --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolItemsTest.java @@ -0,0 +1,50 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; +import net.minecraft.SharedConstants; +import net.minecraft.server.Bootstrap; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertThrows; + +/** + * Making and reading a stack needs the item components a running server binds, which a bootstrapped registry does not have; + * that round trip is checked in the game. + */ +public class ToolItemsTest { + @BeforeClass + public static void bootstrapMinecraftRegistries() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + @Test + public void anItemThePlatformLacksIsRefused() { + ToolItem missing = new ToolItem(ResourceId.parse("iris:no_such_item"), ToolText.EMPTY, List.of(), false, ""); + + assertThrows(IllegalArgumentException.class, () -> ToolItems.create(missing)); + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolTextsTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolTextsTest.java new file mode 100644 index 000000000..d98d28cb3 --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolTextsTest.java @@ -0,0 +1,67 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded.toolworld; + +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Style; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class ToolTextsTest { + private static final ToolText STYLED = ToolText.builder() + .gray("Size: ") + .append(new ToolText.Span("16", TextColor.WHITE, true, false, true)) + .append("plain") + .build(); + + @Test + public void chatKeepsTheColourAndStylesOfEachSpanAndNothingElse() { + List parts = ToolTexts.component(STYLED).getSiblings(); + + assertEquals(3, parts.size()); + assertEquals(Style.EMPTY.withColor(ChatFormatting.GRAY), parts.get(0).getStyle()); + assertEquals(Style.EMPTY.withColor(ChatFormatting.WHITE).withBold(true).withStrikethrough(true), parts.get(1).getStyle()); + assertEquals(Style.EMPTY, parts.get(2).getStyle()); + assertEquals("Size: 16plain", ToolTexts.component(STYLED).getString()); + } + + @Test + public void itemTextIsNeverItalicUnlessTheSpanAsksForIt() { + ToolText text = ToolText.builder() + .gold("Wand") + .append(new ToolText.Span("slanted", null, false, true, false)) + .build(); + + List parts = ToolTexts.itemComponent(text).getSiblings(); + + assertEquals(Style.EMPTY.withColor(ChatFormatting.GOLD).withItalic(false), parts.get(0).getStyle()); + assertEquals(Style.EMPTY.withItalic(true), parts.get(1).getStyle()); + } + + @Test + public void emptyTextIsAnEmptyComponent() { + assertEquals("", ToolTexts.component(ToolText.EMPTY).getString()); + } +} diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index 25d6f01e9..3bc93a897 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -48,7 +48,7 @@ types that carry them and lists what the Iris adapter still owes. | Sparse geometry | `GeneratedObject` | | Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | | Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `reading` with `Argument.Reader`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`, `platformStructures`), plain-text `Sender` (with `player()`), `PlatformStructures` (`templates`, `template` answering `StructureTemplate`, `structures`, `structureSets`, `jigsaw` answering `JigsawStructureInfo`, `pool` answering `TemplatePool` with `Member`, `Element`, `ConnectorSource`, `Connectors` and `JigsawConnector`, `supportsCapture`, `openCaptureArea` answering a closable `CaptureArea` whose `capture` answers `CapturedStructure`; `TemplateBlock`; readers throw `StructureAccessException`), `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`, `worlds`, `services`), host `CommandRegistration` in `FeatureCatalog.commands()` | -| Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `loaded`, `repaint`, `close`), `ToolPlayer` (`targetBlock`, `teleport`, `creative`, `message`, `actionBar`, `sound`, `sidebar`, `particles`, `give` answering whether the item fitted, `held`, `openMenu`), `ToolWorldDenied` (what `open` completes with when the host refuses for a reason the user can fix; a tool reports the message and logs no stack trace), `ToolText` with `TextColor` (styled text, spans in a colour with bold, italic and strikethrough: item names and lore, menu titles, sidebar, chat and action bar; the host shows each span in its colour and style, an empty sidebar title keeps the platform's, and an item read back has plain text), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `teleported` for every arrival other than walking, at the time of the teleport, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause` and `BlockChange.changed`, `containerChanged` for a closed container inventory or a furnace or brewing stand that started, `command`, `chunkLoaded`, `closeRefusal`, `closing`, `closed`), `com.volmit.geometry.ChunkPos`; a tool world takes the pack's studio slot, so the host asks `closeRefusal` before it closes the world for another studio, the studio close command or a server stop, and waits for `closing` when another studio replaces it; every Y is the world's own; implemented by each platform adapter (Bukkit; modded adapters answer with a failed `open`) | +| Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `loaded`, `repaint`, `close`), `ToolPlayer` (`targetBlock`, `teleport`, `creative`, `message`, `actionBar`, `sound`, `sidebar`, `particles`, `give` answering whether the item fitted, `held`, `openMenu`), `ToolWorldDenied` (what `open` completes with when the host refuses for a reason the user can fix; a tool reports the message and logs no stack trace), `ToolText` with `TextColor` (styled text, spans in a colour with bold, italic and strikethrough: item names and lore, menu titles, sidebar, chat and action bar; the host shows each span in its colour and style, an empty sidebar title keeps the platform's, and an item read back has plain text), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `teleported` for every arrival other than walking, at the time of the teleport, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause` and `BlockChange.changed`, `containerChanged` for a closed container inventory or a furnace or brewing stand that started, `command`, `chunkLoaded`, `closeRefusal`, `closing`, `closed`), `com.volmit.geometry.ChunkPos`; a tool world takes the pack's studio slot, so the host asks `closeRefusal` before it closes the world for another studio, the studio close command or a server stop, and waits for `closing` when another studio replaces it; every Y is the world's own; implemented by each platform adapter (Bukkit, and the modded adapters on the server thread) | | Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | | Typed generation and persistent storage | `mantle` package |