mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 16:54:04 +00:00
Give tools a platform-neutral world api and let modules ask each other's services
PackWorld, ValidationContext and ToolPack answer services(type) with the pack's providers. com.volmit.tooling.world lets a tool open a painter-backed world and drive its players, menus, items and block changes; ToolPack.worlds() and Sender.player() reach it. The Bukkit adapter implements it over the studio world creation with a painter slot keyed by world, one protection listener, VolmLib menus, persistent-data items and BoardSVC sidebars. Other platforms answer that tool worlds are not supported yet.
This commit is contained in:
1 parent
a81a3abb9f
commit
3691611c6c
76 files changed
+4533
-23
No files matched your search
@@ -46,6 +46,8 @@ import art.arcane.iris.core.lifecycle.WorldLifecycleService;
|
||||
import art.arcane.iris.core.runtime.BukkitEnginePlatformHooks;
|
||||
import art.arcane.iris.core.runtime.WorldDeletionQueue;
|
||||
import art.arcane.iris.core.runtime.WorldRuntimeControlService;
|
||||
import art.arcane.iris.core.toolworld.BukkitToolWorldService;
|
||||
import art.arcane.iris.core.tooling.ToolWorldsHost;
|
||||
import art.arcane.iris.api.terrain.IrisTerrainService;
|
||||
import art.arcane.iris.core.link.IrisPapiInstaller;
|
||||
import art.arcane.iris.core.link.IrisPapiListener;
|
||||
@@ -629,6 +631,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
new EntityRiseSVC(),
|
||||
new WandSVC(),
|
||||
new BoardSVC(),
|
||||
new BukkitToolWorldService(),
|
||||
new IrisIntegrationService(),
|
||||
new MultiverseSVC(),
|
||||
new IrisProtocolService(),
|
||||
@@ -640,6 +643,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
services.put(serviceType, i);
|
||||
IrisServices.register(serviceType, i);
|
||||
}
|
||||
IrisServices.register(ToolWorldsHost.class, services.get(BukkitToolWorldService.class));
|
||||
IrisServices.register(BlockEditAccess.class, services.get(EditSVC.class));
|
||||
IrisServices.register(PreservationRegistry.class, services.get(PreservationSVC.class));
|
||||
compat = IrisCompat.configured(getDataFile("compat.json"));
|
||||
|
||||
+13
-2
@@ -19,6 +19,7 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.project.IrisProject;
|
||||
import art.arcane.iris.core.toolworld.BukkitToolWorldService;
|
||||
import art.arcane.iris.core.tooling.IrisServedPack;
|
||||
import art.arcane.iris.core.tooling.SenderWorld;
|
||||
import art.arcane.iris.core.tooling.ServedPack;
|
||||
@@ -30,6 +31,7 @@ import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
@@ -39,13 +41,13 @@ import java.util.Optional;
|
||||
* A Bukkit sender of a tooling command. It reads the world the sender stands in and the open studio when it is built, which
|
||||
* the adapter does on the thread that received the command, and delivers messages on the sender's own thread.
|
||||
*/
|
||||
final class BukkitToolingSender implements ToolingSender {
|
||||
public final class BukkitToolingSender implements ToolingSender {
|
||||
private final CommandSender sender;
|
||||
private final VolmitSender messages;
|
||||
private final Optional<SenderWorld> world;
|
||||
private final Optional<ServedPack> openStudioPack;
|
||||
|
||||
BukkitToolingSender(CommandSender sender) {
|
||||
public BukkitToolingSender(CommandSender sender) {
|
||||
this.sender = sender;
|
||||
this.messages = new VolmitSender(sender);
|
||||
this.world = standingWorld(sender);
|
||||
@@ -77,6 +79,15 @@ final class BukkitToolingSender implements ToolingSender {
|
||||
return type.isInstance(sender) ? Optional.of(type.cast(sender)) : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ToolPlayer> player() {
|
||||
BukkitToolWorldService toolWorlds = IrisServices.getOrNull(BukkitToolWorldService.class);
|
||||
if (!(sender instanceof Player player) || toolWorlds == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(toolWorlds.playerOf(player));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOperator() {
|
||||
return sender.hasPermission(CommandSVC.ROOT_PERMISSION);
|
||||
|
||||
+99
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.modules.BlockEntities;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockFace;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** Blocks, positions and block entities between the tool world api and Bukkit. */
|
||||
final class BukkitToolBlocks {
|
||||
private BukkitToolBlocks() {
|
||||
}
|
||||
|
||||
static BlockPosition positionOf(Block block) {
|
||||
return new BlockPosition(block.getX(), block.getY(), block.getZ());
|
||||
}
|
||||
|
||||
static BlockPosition positionOf(Location location) {
|
||||
return new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ());
|
||||
}
|
||||
|
||||
static Block blockAt(World world, BlockPosition at) {
|
||||
return world.getBlockAt(at.x(), at.y(), at.z());
|
||||
}
|
||||
|
||||
/** The complete state of {@code data}, with every property. */
|
||||
static BlockState stateOf(BlockData data) {
|
||||
return BlockState.parse(data.getAsString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The platform's data for {@code state}.
|
||||
*
|
||||
* @throws IllegalArgumentException when the platform has no such block or property
|
||||
*/
|
||||
static BlockData dataOf(BlockState state) {
|
||||
return Bukkit.createBlockData(state.key());
|
||||
}
|
||||
|
||||
/** The block entity of {@code block}; empty for a block without one. */
|
||||
static Optional<BlockEntityData> blockEntityOf(Block block) {
|
||||
return Optional.ofNullable(TileData.getTileState(block, false)).map(BlockEntities::of);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@code data} into the block entity of {@code block}, which must already be the block it was made for.
|
||||
*
|
||||
* @throws IllegalArgumentException when the block cannot take it, or the data is not in the format Iris stores
|
||||
*/
|
||||
static void applyBlockEntity(Block block, BlockEntityData data) {
|
||||
TileData tile = BlockEntities.tileOf(data);
|
||||
if (!TileData.setTileState(block, tile)) {
|
||||
throw new IllegalArgumentException("The block " + block.getType() + " at " + block.getX() + ", " + block.getY()
|
||||
+ ", " + block.getZ() + " cannot take block entity data of " + tile.getMaterialKey());
|
||||
}
|
||||
}
|
||||
|
||||
/** The api face for a Bukkit face; empty for the diagonals and for {@code SELF}. */
|
||||
static Optional<BlockFace> faceOf(org.bukkit.block.BlockFace face) {
|
||||
if (face == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return switch (face) {
|
||||
case UP -> Optional.of(BlockFace.UP);
|
||||
case DOWN -> Optional.of(BlockFace.DOWN);
|
||||
case NORTH -> Optional.of(BlockFace.NORTH);
|
||||
case SOUTH -> Optional.of(BlockFace.SOUTH);
|
||||
case EAST -> Optional.of(BlockFace.EAST);
|
||||
case WEST -> Optional.of(BlockFace.WEST);
|
||||
default -> Optional.empty();
|
||||
};
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.world.ToolItem;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* {@link ToolItem}s as Bukkit item stacks. The payload is a string in the item's persistent data; its presence is what
|
||||
* makes a stack a tool item, so an empty payload is stored as an empty string.
|
||||
*/
|
||||
final class BukkitToolItems {
|
||||
static final NamespacedKey PAYLOAD_KEY = new NamespacedKey("iris", "tool_payload");
|
||||
|
||||
private BukkitToolItems() {
|
||||
}
|
||||
|
||||
/** A new stack of {@code item}. */
|
||||
static ItemStack create(ToolItem item) {
|
||||
Material material = Material.matchMaterial(item.item().toString());
|
||||
if (material == null || !material.isItem()) {
|
||||
throw new IllegalArgumentException("The platform has no item " + item.item());
|
||||
}
|
||||
ItemStack stack = new ItemStack(material);
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta == null) {
|
||||
throw new IllegalStateException("The item " + item.item() + " cannot carry a name or a payload");
|
||||
}
|
||||
if (!item.name().isEmpty()) {
|
||||
meta.displayName(plain(item.name()));
|
||||
}
|
||||
if (!item.lore().isEmpty()) {
|
||||
meta.lore(item.lore().stream().map(BukkitToolItems::plain).toList());
|
||||
}
|
||||
if (item.glowing()) {
|
||||
meta.setEnchantmentGlintOverride(true);
|
||||
}
|
||||
meta.getPersistentDataContainer().set(PAYLOAD_KEY, PersistentDataType.STRING, item.payload());
|
||||
if (!stack.setItemMeta(meta)) {
|
||||
throw new IllegalStateException("The metadata of tool item " + item.item() + " was rejected");
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
/** The tool item {@code stack} is; empty for nothing, air or a stack without the tool payload. */
|
||||
static Optional<ToolItem> read(ItemStack stack) {
|
||||
if (stack == null || stack.getType() == Material.AIR || !stack.hasItemMeta()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
PersistentDataContainer data = meta.getPersistentDataContainer();
|
||||
String payload = data.get(PAYLOAD_KEY, PersistentDataType.STRING);
|
||||
if (payload == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new ToolItem(
|
||||
ResourceId.parse(stack.getType().getKey().toString()),
|
||||
meta.hasDisplayName() ? plainText(meta.displayName()) : "",
|
||||
meta.hasLore() ? lore(meta) : List.of(),
|
||||
Boolean.TRUE.equals(meta.getEnchantmentGlintOverride()),
|
||||
payload));
|
||||
}
|
||||
|
||||
private static List<String> lore(ItemMeta meta) {
|
||||
List<Component> lines = meta.lore();
|
||||
return lines == null ? List.of() : lines.stream().map(BukkitToolItems::plainText).toList();
|
||||
}
|
||||
|
||||
private static Component plain(String text) {
|
||||
return Component.text(text).decoration(TextDecoration.ITALIC, false);
|
||||
}
|
||||
|
||||
private static String plainText(Component component) {
|
||||
return component == null ? "" : PlainTextComponentSerializer.plainText().serialize(component);
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import art.arcane.volmlib.util.data.MaterialBlock;
|
||||
import art.arcane.volmlib.util.inventorygui.UIElement;
|
||||
import art.arcane.volmlib.util.inventorygui.UIPaneDecorator;
|
||||
import art.arcane.volmlib.util.inventorygui.UIWindow;
|
||||
import art.arcane.volmlib.util.inventorygui.WindowResolution;
|
||||
import com.volmit.tooling.world.MenuButton;
|
||||
import com.volmit.tooling.world.MenuClick;
|
||||
import com.volmit.tooling.world.ToolItem;
|
||||
import com.volmit.tooling.world.ToolMenu;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** The chest menus tools open for players, as VolmLib inventory windows. */
|
||||
final class BukkitToolMenus {
|
||||
private static final int MAX_TITLE_LENGTH = 32;
|
||||
private static final int SLOTS_PER_ROW = ToolMenu.SLOTS_PER_ROW;
|
||||
private static final int CENTER_SLOT_OFFSET = SLOTS_PER_ROW / 2;
|
||||
|
||||
private final Map<UUID, UIWindow> windows = new ConcurrentHashMap<>();
|
||||
|
||||
/** Opens {@code menu} for {@code viewer}, closing the one they had. Runs on the viewer's thread. */
|
||||
void open(BukkitToolPlayer viewer, ToolMenu menu) {
|
||||
Player player = viewer.bukkit();
|
||||
close(player);
|
||||
UUID playerId = player.getUniqueId();
|
||||
UIWindow window = new UIWindow(BukkitPlatform.volmitPlugin(), player);
|
||||
window.setResolution(WindowResolution.W9_H6);
|
||||
window.setViewportHeight(menu.rows());
|
||||
window.setDecorator(new UIPaneDecorator(Material.BLACK_STAINED_GLASS_PANE));
|
||||
window.setTitle(shortened(menu.title()));
|
||||
window.onClosed(closed -> {
|
||||
windows.remove(playerId, window);
|
||||
runGuarded(menu.onClose(), "menu close handler of " + player.getName());
|
||||
});
|
||||
for (MenuButton button : menu.buttons()) {
|
||||
window.setElement(positionOf(button.slot()), button.slot() / SLOTS_PER_ROW, element(viewer, button));
|
||||
}
|
||||
windows.put(playerId, window);
|
||||
window.open();
|
||||
}
|
||||
|
||||
/** Closes the player's menu; does nothing when none is open. Runs on the player's thread. */
|
||||
void close(Player player) {
|
||||
UIWindow window = windows.remove(player.getUniqueId());
|
||||
if (window != null) {
|
||||
window.close();
|
||||
}
|
||||
}
|
||||
|
||||
void forget(UUID playerId) {
|
||||
windows.remove(playerId);
|
||||
}
|
||||
|
||||
private static UIElement element(BukkitToolPlayer viewer, MenuButton button) {
|
||||
ToolItem icon = button.icon();
|
||||
Material material = Material.matchMaterial(icon.item().toString());
|
||||
if (material == null || !material.isItem()) {
|
||||
throw new IllegalArgumentException("The platform has no item " + icon.item());
|
||||
}
|
||||
UIElement element = new UIElement("slot-" + button.slot())
|
||||
.setMaterial(new MaterialBlock(material))
|
||||
.setName(icon.name())
|
||||
.setEnchanted(icon.glowing());
|
||||
icon.lore().forEach(element::addLore);
|
||||
element.onLeftClick(clicked -> click(viewer, button, false, false));
|
||||
element.onRightClick(clicked -> click(viewer, button, true, false));
|
||||
element.onShiftLeftClick(clicked -> click(viewer, button, false, true));
|
||||
element.onShiftRightClick(clicked -> click(viewer, button, true, true));
|
||||
return element;
|
||||
}
|
||||
|
||||
private static void click(BukkitToolPlayer viewer, MenuButton button, boolean right, boolean shift) {
|
||||
runGuarded(() -> button.action().accept(new MenuClick(viewer, right, shift)), "menu button of " + viewer.name());
|
||||
}
|
||||
|
||||
/** The window counts positions from its middle column, left of it negative; a slot counts from the left. */
|
||||
static int positionOf(int slot) {
|
||||
return slot % SLOTS_PER_ROW - CENTER_SLOT_OFFSET;
|
||||
}
|
||||
|
||||
static String shortened(String title) {
|
||||
return title.length() > MAX_TITLE_LENGTH ? title.substring(0, MAX_TITLE_LENGTH) : title;
|
||||
}
|
||||
|
||||
private static void runGuarded(Runnable task, String what) {
|
||||
try {
|
||||
task.run();
|
||||
} catch (RuntimeException failure) {
|
||||
IrisLogging.reportError("A tool failed in the " + what + ".", failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.service.BoardSVC;
|
||||
import art.arcane.iris.core.service.BukkitToolingSender;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
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.ToolWorld;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/** A Bukkit player as a tool sees them. Readers must run on the player's thread; changes hop there by themselves. */
|
||||
final class BukkitToolPlayer implements ToolPlayer {
|
||||
private final Player player;
|
||||
private final OpenToolWorlds worlds;
|
||||
private final ToolPlayers players;
|
||||
private final BukkitToolMenus menus;
|
||||
|
||||
BukkitToolPlayer(Player player, OpenToolWorlds worlds, ToolPlayers players, BukkitToolMenus menus) {
|
||||
this.player = player;
|
||||
this.worlds = worlds;
|
||||
this.players = players;
|
||||
this.menus = menus;
|
||||
}
|
||||
|
||||
Player bukkit() {
|
||||
return player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID id() {
|
||||
return player.getUniqueId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return player.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Sender sender() {
|
||||
return new BukkitToolingSender(player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ToolWorld> world() {
|
||||
return worlds.forWorld(player.getWorld()).map(world -> world);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockPosition position() {
|
||||
return BukkitToolBlocks.positionOf(player.getLocation());
|
||||
}
|
||||
|
||||
@Override
|
||||
public float yaw() {
|
||||
return player.getLocation().getYaw();
|
||||
}
|
||||
|
||||
@Override
|
||||
public float pitch() {
|
||||
return player.getLocation().getPitch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sneaking() {
|
||||
return player.isSneaking();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(Runnable task) {
|
||||
J.runEntity(player, task);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch) {
|
||||
if (!(world instanceof BukkitToolWorld target)) {
|
||||
return CompletableFuture.failedFuture(new IllegalArgumentException("Not a tool world of this platform: " + world));
|
||||
}
|
||||
CompletableFuture<Boolean> arrived = new CompletableFuture<>();
|
||||
boolean scheduled = J.runEntity(player, () -> BukkitPlatform
|
||||
.teleportAsync(player, new Location(target.bukkit(), x, y, z, yaw, pitch))
|
||||
.whenComplete((success, failure) -> {
|
||||
if (failure != null) {
|
||||
arrived.completeExceptionally(failure);
|
||||
} else {
|
||||
arrived.complete(Boolean.TRUE.equals(success));
|
||||
}
|
||||
}));
|
||||
if (!scheduled) {
|
||||
arrived.complete(false);
|
||||
}
|
||||
return arrived;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void creative(boolean on) {
|
||||
J.runEntity(player, () -> {
|
||||
if (on) {
|
||||
players.rememberModeBeforeCreative(player);
|
||||
player.setGameMode(GameMode.CREATIVE);
|
||||
return;
|
||||
}
|
||||
players.restoreGameMode(player);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void actionBar(String text) {
|
||||
J.runEntity(player, () -> player.sendActionBar(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sound(ResourceId sound, float volume, float pitch) {
|
||||
J.runEntity(player, () -> player.playSound(player.getLocation(), sound.toString(), volume, pitch));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sidebar(String title, List<String> lines) {
|
||||
BoardSVC board = IrisServices.getOrNull(BoardSVC.class);
|
||||
if (board == null) {
|
||||
return;
|
||||
}
|
||||
J.runEntity(player, () -> board.applyToolSidebar(player,
|
||||
new BoardSVC.ToolSidebar(player.getWorld().getUID(), title, lines)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hideSidebar() {
|
||||
BoardSVC board = IrisServices.getOrNull(BoardSVC.class);
|
||||
if (board != null) {
|
||||
board.clearToolSidebar(player);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void particles(List<Particle> dust) {
|
||||
List<Particle> specks = List.copyOf(dust);
|
||||
J.runEntity(player, () -> specks.forEach(this::showDust));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void give(ToolItem item) {
|
||||
ItemStack stack = BukkitToolItems.create(item);
|
||||
J.runEntity(player, () -> player.getInventory().addItem(stack)
|
||||
.values()
|
||||
.forEach(leftover -> player.getWorld().dropItem(player.getLocation(), leftover)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ToolItem> held() {
|
||||
return BukkitToolItems.read(player.getInventory().getItemInMainHand());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openMenu(ToolMenu menu) {
|
||||
J.runEntity(player, () -> menus.open(this, menu));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closeMenu() {
|
||||
J.runEntity(player, () -> menus.close(player));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<Boolean> returnToOrigin() {
|
||||
CompletableFuture<Boolean> returned = new CompletableFuture<>();
|
||||
boolean scheduled = J.runEntity(player, () -> {
|
||||
menus.close(player);
|
||||
players.restoreGameMode(player);
|
||||
Location destination = players.takeOrigin(player)
|
||||
.filter(this::isOutsideToolWorlds)
|
||||
.orElseGet(() -> Bukkit.getWorlds().getFirst().getSpawnLocation());
|
||||
BukkitPlatform.teleportAsync(player, destination).whenComplete((success, failure) -> {
|
||||
if (failure != null) {
|
||||
returned.completeExceptionally(failure);
|
||||
} else {
|
||||
returned.complete(Boolean.TRUE.equals(success));
|
||||
}
|
||||
});
|
||||
});
|
||||
if (!scheduled) {
|
||||
returned.complete(false);
|
||||
}
|
||||
return returned;
|
||||
}
|
||||
|
||||
private boolean isOutsideToolWorlds(Location location) {
|
||||
return location.getWorld() != null && worlds.forWorld(location.getWorld()).isEmpty();
|
||||
}
|
||||
|
||||
private void showDust(Particle speck) {
|
||||
org.bukkit.Particle.DustOptions options = new org.bukkit.Particle.DustOptions(Color.fromRGB(speck.rgb()), speck.size());
|
||||
player.spawnParticle(org.bukkit.Particle.DUST, speck.x(), speck.y(), speck.z(), 1, 0.0D, 0.0D, 0.0D, 0.0D, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "tool player " + player.getName();
|
||||
}
|
||||
}
|
||||
+355
@@ -0,0 +1,355 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.core.runtime.InPlaceChunkRegenerator;
|
||||
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity;
|
||||
import art.arcane.iris.engine.data.chunk.TerrainChunk;
|
||||
import art.arcane.iris.engine.platform.studio.TerrainChunkCanvas;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
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 org.bukkit.Chunk;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* One tool world on Bukkit: a studio world whose chunks come from the tool's painter. It exists, registered, from before
|
||||
* Bukkit creates the world until the world is unloaded; {@link #bind} gives it the Bukkit world once that exists.
|
||||
*/
|
||||
final class BukkitToolWorld implements ToolWorld {
|
||||
private static final int CHUNK_SHIFT = 4;
|
||||
|
||||
private final String packName;
|
||||
private final String name;
|
||||
private final String storageName;
|
||||
private final ToolWorldListener listener;
|
||||
private final StudioPainterSlots.Slot slot;
|
||||
private final PendingBlockEntities pending;
|
||||
private final ToolWorldPresence presence = new ToolWorldPresence();
|
||||
private final OpenToolWorlds registry;
|
||||
private final ToolPlayers players;
|
||||
private final AtomicBoolean closing = new AtomicBoolean();
|
||||
private final AtomicBoolean gone = new AtomicBoolean();
|
||||
private final CompletableFuture<Void> closed = new CompletableFuture<>();
|
||||
private volatile World world;
|
||||
|
||||
BukkitToolWorld(
|
||||
String packName,
|
||||
String name,
|
||||
String storageName,
|
||||
ToolWorldListener listener,
|
||||
StudioPainterSlots.Slot slot,
|
||||
PendingBlockEntities pending,
|
||||
OpenToolWorlds registry,
|
||||
ToolPlayers players
|
||||
) {
|
||||
this.packName = packName;
|
||||
this.name = name;
|
||||
this.storageName = storageName;
|
||||
this.listener = listener;
|
||||
this.slot = slot;
|
||||
this.pending = pending;
|
||||
this.registry = registry;
|
||||
this.players = players;
|
||||
}
|
||||
|
||||
String packName() {
|
||||
return packName;
|
||||
}
|
||||
|
||||
/** The logical name of the world's storage, which the generator finds its painter by. */
|
||||
String storageName() {
|
||||
return storageName;
|
||||
}
|
||||
|
||||
/** Gives the world its Bukkit world, once Bukkit has created it. */
|
||||
void bind(World created) {
|
||||
world = Objects.requireNonNull(created, "created");
|
||||
registry.bound(this);
|
||||
}
|
||||
|
||||
boolean isBound() {
|
||||
return world != null;
|
||||
}
|
||||
|
||||
UUID worldId() {
|
||||
return bukkit().getUID();
|
||||
}
|
||||
|
||||
World bukkit() {
|
||||
World bound = world;
|
||||
if (bound == null) {
|
||||
throw new IllegalStateException("The tool world " + name + " is not created yet");
|
||||
}
|
||||
return bound;
|
||||
}
|
||||
|
||||
ToolWorldPresence presence() {
|
||||
return presence;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int minY() {
|
||||
return bukkit().getMinHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int maxY() {
|
||||
return bukkit().getMaxHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ToolPlayer> players() {
|
||||
return bukkit().getPlayers().stream().<ToolPlayer>map(players::of).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean owns(BlockPosition at) {
|
||||
return J.isOwnedByCurrentRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(BlockPosition at, Runnable task) {
|
||||
World target = bukkit();
|
||||
Runnable guarded = () -> runGuarded(task, "task at " + at);
|
||||
if (!J.runRegion(target, at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, guarded)) {
|
||||
IrisLogging.warn("Tool world %s could not schedule a task at %s.", name, at);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> CompletableFuture<T> call(BlockPosition at, Supplier<T> task) {
|
||||
CompletableFuture<T> result = new CompletableFuture<>();
|
||||
boolean scheduled = J.runRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, () -> {
|
||||
try {
|
||||
result.complete(task.get());
|
||||
} catch (Throwable failure) {
|
||||
result.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
result.completeExceptionally(new IllegalStateException("Tool world " + name + " could not schedule a task at " + at));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState block(BlockPosition at) {
|
||||
return BukkitToolBlocks.stateOf(ownedBlock(at).getBlockData());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<BlockEntityData> blockEntity(BlockPosition at) {
|
||||
return BukkitToolBlocks.blockEntityOf(ownedBlock(at));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBlock(BlockPosition at, BlockState state, Optional<BlockEntityData> data) {
|
||||
Block block = ownedBlock(at);
|
||||
block.setBlockData(BukkitToolBlocks.dataOf(state), false);
|
||||
data.ifPresent(entity -> BukkitToolBlocks.applyBlockEntity(block, entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> repaint(Collection<ChunkPos> chunks) {
|
||||
if (isClosed()) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException("Tool world " + name + " is closed"));
|
||||
}
|
||||
List<CompletableFuture<Void>> repaints = chunks.stream().distinct().map(this::repaintChunk).toList();
|
||||
return CompletableFuture.allOf(repaints.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> close() {
|
||||
if (!closing.compareAndSet(false, true)) {
|
||||
return closed;
|
||||
}
|
||||
sendPlayersBack()
|
||||
.thenCompose(ignored -> StudioOpenCoordinator.get().closeToolWorld(bukkit()))
|
||||
.whenComplete((result, failure) -> finishClose(result, failure));
|
||||
return closed;
|
||||
}
|
||||
|
||||
/** The tool's listener asked, with {@code fallback} as the answer when it throws. Runs on the caller's thread. */
|
||||
boolean ask(Function<ToolWorldListener, Boolean> question, boolean fallback) {
|
||||
try {
|
||||
return question.apply(listener);
|
||||
} catch (Throwable failure) {
|
||||
IrisLogging.reportError("The listener of tool world " + name + " failed.", failure);
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/** Tells the listener something. Runs on the caller's thread. */
|
||||
void tell(Consumer<ToolWorldListener> news) {
|
||||
ask(listener -> {
|
||||
news.accept(listener);
|
||||
return true;
|
||||
}, true);
|
||||
}
|
||||
|
||||
/** A chunk of the world loaded: writes the block entities its paint asked for, then tells the tool. */
|
||||
void chunkLoaded(Chunk chunk) {
|
||||
for (PaintedBlockEntity entity : pending.take(chunk.getX(), chunk.getZ())) {
|
||||
applyPainted(chunk, entity);
|
||||
}
|
||||
tell(toolListener -> toolListener.chunkLoaded(chunk.getX(), chunk.getZ()));
|
||||
}
|
||||
|
||||
/** Bukkit unloaded the world, whoever asked: it is gone for the tool and for the host. */
|
||||
void unloaded() {
|
||||
if (!gone.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
StudioPainterSlots.remove(storageName);
|
||||
registry.unregister(this);
|
||||
tell(ToolWorldListener::closed);
|
||||
}
|
||||
|
||||
/** Called by the opener when creating the world failed: nothing of it is left to unload. */
|
||||
void abandon() {
|
||||
StudioPainterSlots.remove(storageName);
|
||||
registry.unregister(this);
|
||||
}
|
||||
|
||||
private void finishClose(StudioOpenCoordinator.StudioCloseResult result, Throwable failure) {
|
||||
unloaded();
|
||||
Throwable cause = failure != null ? unwrap(failure) : result == null ? null : result.failureCause();
|
||||
if (cause == null) {
|
||||
closed.complete(null);
|
||||
return;
|
||||
}
|
||||
closed.completeExceptionally(cause);
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendPlayersBack() {
|
||||
List<CompletableFuture<Boolean>> departures = bukkit().getPlayers().stream()
|
||||
.map(player -> players.of(player).returnToOrigin())
|
||||
.toList();
|
||||
return CompletableFuture.allOf(departures.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
private record Repainted(TerrainChunk terrain, TerrainChunkCanvas canvas) {
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> repaintChunk(ChunkPos position) {
|
||||
World target = bukkit();
|
||||
AtomicReference<Repainted> repainted = new AtomicReference<>();
|
||||
CompletableFuture<Void> painting = J.afut(() -> repainted.set(paintAgain(target, position)));
|
||||
CompletableFuture<Chunk> loading = target.getChunkAtAsync(position.x(), position.z());
|
||||
return painting.thenCombine(loading, (ignored, chunk) -> chunk)
|
||||
.thenCompose(chunk -> J.runRegionFuture(target, position.x(), position.z(),
|
||||
() -> writeRepainted(target, chunk, repainted.get())));
|
||||
}
|
||||
|
||||
private Repainted paintAgain(World target, ChunkPos position) {
|
||||
TerrainChunk terrain = TerrainChunk.create(target);
|
||||
TerrainChunkCanvas canvas = TerrainChunkCanvas.onPlatform(terrain);
|
||||
slot.painter().paint(position.x(), position.z(), canvas);
|
||||
return new Repainted(terrain, canvas);
|
||||
}
|
||||
|
||||
private void writeRepainted(World target, Chunk chunk, Repainted repainted) {
|
||||
if (!INMS.get().applyChunkBlocks(chunk, repainted.terrain())) {
|
||||
InPlaceChunkRegenerator.applyBlockDiffs(chunk, repainted.terrain().getChunkData(),
|
||||
target.getMinHeight(), target.getMaxHeight());
|
||||
}
|
||||
repainted.canvas().blockEntities().forEach(entity -> applyPainted(chunk, entity));
|
||||
target.refreshChunk(chunk.getX(), chunk.getZ());
|
||||
}
|
||||
|
||||
private void applyPainted(Chunk chunk, PaintedBlockEntity entity) {
|
||||
Block block = chunk.getBlock(entity.x(), entity.y(), entity.z());
|
||||
try {
|
||||
BukkitToolBlocks.applyBlockEntity(block, entity.data());
|
||||
} catch (RuntimeException failure) {
|
||||
IrisLogging.reportError("Tool world " + name + " could not write a block entity at "
|
||||
+ block.getX() + ", " + block.getY() + ", " + block.getZ() + ".", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private Block ownedBlock(BlockPosition at) {
|
||||
requireOpen();
|
||||
if (!owns(at)) {
|
||||
throw new IllegalStateException("The calling thread does not own " + at + " in tool world " + name);
|
||||
}
|
||||
return BukkitToolBlocks.blockAt(bukkit(), at);
|
||||
}
|
||||
|
||||
private void requireOpen() {
|
||||
if (isClosed()) {
|
||||
throw new IllegalStateException("Tool world " + name + " is closed");
|
||||
}
|
||||
bukkit();
|
||||
}
|
||||
|
||||
private boolean isClosed() {
|
||||
return closing.get() || gone.get();
|
||||
}
|
||||
|
||||
private void runGuarded(Runnable task, String what) {
|
||||
try {
|
||||
task.run();
|
||||
} catch (Throwable failure) {
|
||||
IrisLogging.reportError("A task of tool world " + name + " failed: " + what + ".", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static Throwable unwrap(Throwable failure) {
|
||||
Throwable cursor = failure;
|
||||
while (cursor instanceof CompletionException && cursor.getCause() != null) {
|
||||
cursor = cursor.getCause();
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "tool world " + name;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.tooling.ToolWorldsHost;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.util.common.plugin.IrisService;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import com.volmit.tooling.world.ToolWorlds;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
/**
|
||||
* Tool worlds on Bukkit: the platform side of {@code com.volmit.tooling.world}. It keeps the open tool worlds and the
|
||||
* tool players, listens for the events that concern them ({@link ToolWorldEvents}), and hands each pack its
|
||||
* {@link ToolWorlds} through {@link ToolWorldsHost}, which core reaches it by.
|
||||
*/
|
||||
public final class BukkitToolWorldService implements IrisService, ToolWorldsHost {
|
||||
private final OpenToolWorlds worlds = new OpenToolWorlds();
|
||||
private final ToolPlayers players = new ToolPlayers(worlds);
|
||||
private final ToolWorldEvents events = new ToolWorldEvents(worlds, players);
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
Bukkit.getPluginManager().registerEvents(events, BukkitPlatform.plugin());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
HandlerList.unregisterAll(events);
|
||||
worlds.all().forEach(BukkitToolWorld::unloaded);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ToolWorlds worldsOf(String packName) {
|
||||
return new BukkitToolWorlds(packName, worlds, players);
|
||||
}
|
||||
|
||||
/** The tool player for {@code player}, the same object for as long as the player is online. */
|
||||
public ToolPlayer playerOf(Player player) {
|
||||
return players.of(player);
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots;
|
||||
import com.volmit.tooling.world.ToolWorld;
|
||||
import com.volmit.tooling.world.ToolWorldSpec;
|
||||
import com.volmit.tooling.world.ToolWorlds;
|
||||
import org.bukkit.World;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
|
||||
/**
|
||||
* The tool worlds of one pack on Bukkit. A tool world is created through the studio's own world creation, with the
|
||||
* tool's painter installed first so that even the first chunk is the tool's.
|
||||
*/
|
||||
final class BukkitToolWorlds implements ToolWorlds {
|
||||
private static final String STORAGE_NAME_PREFIX = "iris-";
|
||||
private static final long TOOL_WORLD_SEED = 1337L;
|
||||
|
||||
private final String packName;
|
||||
private final OpenToolWorlds registry;
|
||||
private final ToolPlayers players;
|
||||
|
||||
BukkitToolWorlds(String packName, OpenToolWorlds registry, ToolPlayers players) {
|
||||
this.packName = packName;
|
||||
this.registry = registry;
|
||||
this.players = players;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ToolWorld> open(ToolWorldSpec spec) {
|
||||
PendingBlockEntities pending = new PendingBlockEntities();
|
||||
StudioPainterSlots.Slot slot = new StudioPainterSlots.Slot(spec.painter(), pending::add);
|
||||
String storageName = STORAGE_NAME_PREFIX + UUID.randomUUID();
|
||||
BukkitToolWorld toolWorld = new BukkitToolWorld(packName, spec.name(), storageName, spec.listener(), slot, pending,
|
||||
registry, players);
|
||||
if (!registry.register(toolWorld)) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException(
|
||||
"A tool world called " + spec.name() + " is open already in pack " + packName));
|
||||
}
|
||||
StudioPainterSlots.install(storageName, slot);
|
||||
CompletableFuture<ToolWorld> opened = new CompletableFuture<>();
|
||||
StudioOpenCoordinator.get().open(openRequest(storageName, toolWorld)).whenComplete((result, failure) -> {
|
||||
if (failure != null) {
|
||||
toolWorld.abandon();
|
||||
opened.completeExceptionally(unwrap(failure));
|
||||
return;
|
||||
}
|
||||
opened.complete(toolWorld);
|
||||
});
|
||||
return opened;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ToolWorld> find(String name) {
|
||||
return registry.forName(packName, name).filter(BukkitToolWorld::isBound).map(world -> world);
|
||||
}
|
||||
|
||||
private StudioOpenCoordinator.StudioOpenRequest openRequest(String storageName, BukkitToolWorld toolWorld) {
|
||||
return new StudioOpenCoordinator.StudioOpenRequest(
|
||||
packName,
|
||||
null,
|
||||
null,
|
||||
TOOL_WORLD_SEED,
|
||||
storageName,
|
||||
null,
|
||||
StudioOpenCoordinator.StudioOpenKind.TOOL,
|
||||
false,
|
||||
null,
|
||||
world -> prepare(toolWorld, world),
|
||||
System.nanoTime());
|
||||
}
|
||||
|
||||
private static void prepare(BukkitToolWorld toolWorld, World created) {
|
||||
toolWorld.bind(created);
|
||||
ToolWorldRules.apply(created);
|
||||
}
|
||||
|
||||
private static Throwable unwrap(Throwable failure) {
|
||||
Throwable cursor = failure;
|
||||
while (cursor instanceof CompletionException && cursor.getCause() != null) {
|
||||
cursor = cursor.getCause();
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.IrisWorldStorage;
|
||||
import org.bukkit.World;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* The tool worlds that are open or opening: found by the Bukkit world they live in, and by the tool's name for them
|
||||
* within a pack. A world is registered before Bukkit has created it, since chunks load while it is created; until it
|
||||
* is bound to its Bukkit world it is found by the logical name of its storage, which the creator fixes beforehand.
|
||||
*/
|
||||
final class OpenToolWorlds {
|
||||
private final Map<String, BukkitToolWorld> byStorageName = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, BukkitToolWorld> byWorldId = new ConcurrentHashMap<>();
|
||||
private final Map<String, BukkitToolWorld> byPackAndName = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Registers {@code world} under its storage name and the name its tool gave it.
|
||||
*
|
||||
* @return whether the tool's name was free; when it is not, nothing is registered
|
||||
*/
|
||||
boolean register(BukkitToolWorld world) {
|
||||
if (byPackAndName.putIfAbsent(packAndName(world.packName(), world.name()), world) != null) {
|
||||
return false;
|
||||
}
|
||||
byStorageName.put(world.storageName(), world);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Records the Bukkit world of {@code world}, which is bound already. */
|
||||
void bound(BukkitToolWorld world) {
|
||||
byWorldId.put(world.worldId(), world);
|
||||
}
|
||||
|
||||
void unregister(BukkitToolWorld world) {
|
||||
byStorageName.remove(world.storageName(), world);
|
||||
byPackAndName.remove(packAndName(world.packName(), world.name()), world);
|
||||
if (world.isBound()) {
|
||||
byWorldId.remove(world.worldId(), world);
|
||||
}
|
||||
}
|
||||
|
||||
/** The tool world that {@code world} is; empty for every other world. */
|
||||
Optional<BukkitToolWorld> forWorld(World world) {
|
||||
if (world == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
BukkitToolWorld bound = byWorldId.get(world.getUID());
|
||||
return bound != null ? Optional.of(bound) : forOpeningWorld(world);
|
||||
}
|
||||
|
||||
Optional<BukkitToolWorld> forName(String packName, String name) {
|
||||
return Optional.ofNullable(byPackAndName.get(packAndName(packName, name)));
|
||||
}
|
||||
|
||||
List<BukkitToolWorld> all() {
|
||||
return new ArrayList<>(byStorageName.values());
|
||||
}
|
||||
|
||||
private Optional<BukkitToolWorld> forOpeningWorld(World world) {
|
||||
boolean anyOpening = byStorageName.values().stream().anyMatch(candidate -> !candidate.isBound());
|
||||
if (!anyOpening) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(byStorageName.get(IrisWorldStorage.logicalName(world)));
|
||||
}
|
||||
|
||||
private static String packAndName(String packName, String name) {
|
||||
return packName + "/" + name;
|
||||
}
|
||||
}
|
||||
+51
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedChunk;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* The block entities a painter asked for in chunks that are generated but not loaded yet. A chunk is painted on a
|
||||
* generation thread and its block entities can only be written once it is live, so they wait here for its load.
|
||||
*/
|
||||
final class PendingBlockEntities {
|
||||
private static final int INT_BITS = 32;
|
||||
|
||||
private final Map<Long, List<PaintedBlockEntity>> byChunk = new ConcurrentHashMap<>();
|
||||
|
||||
/** Keeps what a paint of a chunk asked for; a later paint of the same chunk replaces it. */
|
||||
void add(PaintedChunk painted) {
|
||||
byChunk.put(chunkKey(painted.chunkX(), painted.chunkZ()), painted.blockEntities());
|
||||
}
|
||||
|
||||
/** Hands over what waits for the chunk, once; empty when nothing does. */
|
||||
List<PaintedBlockEntity> take(int chunkX, int chunkZ) {
|
||||
List<PaintedBlockEntity> waiting = byChunk.remove(chunkKey(chunkX, chunkZ));
|
||||
return waiting == null ? List.of() : waiting;
|
||||
}
|
||||
|
||||
private static long chunkKey(int chunkX, int chunkZ) {
|
||||
return ((long) chunkX << INT_BITS) | (chunkZ & 0xFFFFFFFFL);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* The tool players: one {@link BukkitToolPlayer} for each online player, and what the host remembers about them while
|
||||
* they are in tool worlds, which is where they came from and the game mode they had before a tool made them creative.
|
||||
*/
|
||||
final class ToolPlayers {
|
||||
private final OpenToolWorlds worlds;
|
||||
private final BukkitToolMenus menus = new BukkitToolMenus();
|
||||
private final Map<UUID, BukkitToolPlayer> players = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Location> origins = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, GameMode> modesBeforeCreative = new ConcurrentHashMap<>();
|
||||
|
||||
ToolPlayers(OpenToolWorlds worlds) {
|
||||
this.worlds = worlds;
|
||||
}
|
||||
|
||||
BukkitToolPlayer of(Player player) {
|
||||
return players.computeIfAbsent(player.getUniqueId(), id -> new BukkitToolPlayer(player, worlds, this, menus));
|
||||
}
|
||||
|
||||
/** Forgets everything about a player who left the server. */
|
||||
void forget(Player player) {
|
||||
UUID id = player.getUniqueId();
|
||||
players.remove(id);
|
||||
origins.remove(id);
|
||||
modesBeforeCreative.remove(id);
|
||||
menus.forget(id);
|
||||
}
|
||||
|
||||
/** Remembers where a player was before their first step into a tool world; later steps keep the first. */
|
||||
void rememberOrigin(Player player, Location origin) {
|
||||
origins.putIfAbsent(player.getUniqueId(), origin.clone());
|
||||
}
|
||||
|
||||
/** Hands over where the player came from, once. */
|
||||
Optional<Location> takeOrigin(Player player) {
|
||||
return Optional.ofNullable(origins.remove(player.getUniqueId()));
|
||||
}
|
||||
|
||||
/** Remembers the game mode of a player a tool makes creative; the first mode is kept while they stay creative. */
|
||||
void rememberModeBeforeCreative(Player player) {
|
||||
modesBeforeCreative.putIfAbsent(player.getUniqueId(), player.getGameMode());
|
||||
}
|
||||
|
||||
/** Gives a player the game mode they had before a tool made them creative; does nothing when none did. */
|
||||
void restoreGameMode(Player player) {
|
||||
GameMode previous = modesBeforeCreative.remove(player.getUniqueId());
|
||||
if (previous != null) {
|
||||
player.setGameMode(previous);
|
||||
}
|
||||
}
|
||||
|
||||
BukkitToolMenus menus() {
|
||||
return menus;
|
||||
}
|
||||
}
|
||||
+519
@@ -0,0 +1,519 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.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 org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.block.DoubleChest;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockBurnEvent;
|
||||
import org.bukkit.event.block.BlockCookEvent;
|
||||
import org.bukkit.event.block.BlockDispenseEvent;
|
||||
import org.bukkit.event.block.BlockExplodeEvent;
|
||||
import org.bukkit.event.block.BlockFadeEvent;
|
||||
import org.bukkit.event.block.BlockFormEvent;
|
||||
import org.bukkit.event.block.BlockFromToEvent;
|
||||
import org.bukkit.event.block.BlockGrowEvent;
|
||||
import org.bukkit.event.block.BlockMultiPlaceEvent;
|
||||
import org.bukkit.event.block.BlockPistonExtendEvent;
|
||||
import org.bukkit.event.block.BlockPistonRetractEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.bukkit.event.block.BlockRedstoneEvent;
|
||||
import org.bukkit.event.block.BlockSpreadEvent;
|
||||
import org.bukkit.event.block.CrafterCraftEvent;
|
||||
import org.bukkit.event.entity.CreatureSpawnEvent;
|
||||
import org.bukkit.event.entity.EntityChangeBlockEvent;
|
||||
import org.bukkit.event.entity.EntityExplodeEvent;
|
||||
import org.bukkit.event.inventory.BrewEvent;
|
||||
import org.bukkit.event.inventory.BrewingStandFuelEvent;
|
||||
import org.bukkit.event.inventory.FurnaceBurnEvent;
|
||||
import org.bukkit.event.inventory.FurnaceSmeltEvent;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
import org.bukkit.event.inventory.InventoryMoveItemEvent;
|
||||
import org.bukkit.event.inventory.InventoryPickupItemEvent;
|
||||
import org.bukkit.event.player.PlayerBucketEmptyEvent;
|
||||
import org.bukkit.event.player.PlayerBucketFillEvent;
|
||||
import org.bukkit.event.player.PlayerChangedWorldEvent;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerMoveEvent;
|
||||
import org.bukkit.event.player.PlayerPortalEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerRespawnEvent;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent;
|
||||
import org.bukkit.event.player.PlayerToggleSneakEvent;
|
||||
import org.bukkit.event.server.ServerCommandEvent;
|
||||
import org.bukkit.event.world.ChunkLoadEvent;
|
||||
import org.bukkit.event.world.StructureGrowEvent;
|
||||
import org.bukkit.event.world.WorldUnloadEvent;
|
||||
import org.bukkit.inventory.BlockInventoryHolder;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The one listener that maps Bukkit's events onto {@link com.volmit.tooling.world.ToolWorldListener}, for tool worlds
|
||||
* only. Every handler first asks whether the event happens in a tool world and does nothing when it does not. The
|
||||
* priorities and {@code ignoreCancelled} flags are those of the jigsaw studio's own handlers: decisions at HIGHEST so
|
||||
* that other plugins have had their say, observations at MONITOR.
|
||||
*/
|
||||
public final class ToolWorldEvents implements Listener {
|
||||
private static final String COMMAND_PREFIX = "/";
|
||||
|
||||
private final OpenToolWorlds worlds;
|
||||
private final ToolPlayers players;
|
||||
|
||||
ToolWorldEvents(OpenToolWorlds worlds, ToolPlayers players) {
|
||||
this.worlds = worlds;
|
||||
this.players = players;
|
||||
}
|
||||
|
||||
// Block changes: the tool decides, `false` cancels.
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockPlace(BlockPlaceEvent event) {
|
||||
Block placed = event.getBlockPlaced();
|
||||
allowOrCancel(event, Cause.PLACE, placed.getWorld(), List.of(positionOf(placed)), Optional.of(event.getPlayer()),
|
||||
Optional.of(BukkitToolBlocks.stateOf(placed.getBlockData())));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockMultiPlace(BlockMultiPlaceEvent event) {
|
||||
List<BlockPosition> replaced = event.getReplacedBlockStates().stream()
|
||||
.map(state -> positionOf(state.getBlock())).toList();
|
||||
allowOrCancel(event, Cause.PLACE, event.getBlock().getWorld(), replaced, Optional.of(event.getPlayer()), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockBreak(BlockBreakEvent event) {
|
||||
allowOrCancel(event, Cause.BREAK, event.getBlock(), Optional.of(event.getPlayer()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBucketEmpty(PlayerBucketEmptyEvent event) {
|
||||
allowOrCancel(event, Cause.BUCKET, event.getBlockClicked().getRelative(event.getBlockFace()), Optional.of(event.getPlayer()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBucketFill(PlayerBucketFillEvent event) {
|
||||
allowOrCancel(event, Cause.BUCKET, event.getBlockClicked(), Optional.of(event.getPlayer()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockForm(BlockFormEvent event) {
|
||||
allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockFade(BlockFadeEvent event) {
|
||||
allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockSpread(BlockSpreadEvent event) {
|
||||
allowOrCancel(event, Cause.PHYSICS, event.getBlock().getWorld(),
|
||||
List.of(positionOf(event.getBlock()), positionOf(event.getSource())), Optional.empty(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockFromTo(BlockFromToEvent event) {
|
||||
allowOrCancel(event, Cause.FLUID, event.getBlock().getWorld(),
|
||||
List.of(positionOf(event.getBlock()), positionOf(event.getToBlock())), Optional.empty(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockGrow(BlockGrowEvent event) {
|
||||
allowOrCancel(event, Cause.GROWTH, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onStructureGrow(StructureGrowEvent event) {
|
||||
World world = event.getLocation().getWorld();
|
||||
List<BlockPosition> grown = event.getBlocks().stream().map(state -> positionOf(state.getBlock())).toList();
|
||||
if (!grown.isEmpty()) {
|
||||
allowOrCancel(event, Cause.GROWTH, world, grown, Optional.ofNullable(event.getPlayer()), Optional.empty());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockBurn(BlockBurnEvent event) {
|
||||
allowOrCancel(event, Cause.FIRE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onBlockRedstone(BlockRedstoneEvent event) {
|
||||
Block block = event.getBlock();
|
||||
if (!isAllowed(Cause.REDSTONE, block.getWorld(), List.of(positionOf(block)), Optional.empty(), Optional.empty())) {
|
||||
event.setNewCurrent(event.getOldCurrent());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPistonExtend(BlockPistonExtendEvent event) {
|
||||
allowOrCancel(event, Cause.PISTON, event.getBlock().getWorld(),
|
||||
pistonPositions(event.getBlock(), event.getBlocks(), event.getDirection()), Optional.empty(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPistonRetract(BlockPistonRetractEvent event) {
|
||||
allowOrCancel(event, Cause.PISTON, event.getBlock().getWorld(),
|
||||
pistonPositions(event.getBlock(), event.getBlocks(), event.getDirection()), Optional.empty(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockExplode(BlockExplodeEvent event) {
|
||||
keepAllowedBlocks(event.getBlock().getWorld(), event.blockList());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onEntityExplode(EntityExplodeEvent event) {
|
||||
keepAllowedBlocks(event.getEntity().getWorld(), event.blockList());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
|
||||
Optional<Player> actor = event.getEntity() instanceof Player player ? Optional.of(player) : Optional.empty();
|
||||
allowOrCancel(event, Cause.ENTITY, event.getBlock(), actor);
|
||||
}
|
||||
|
||||
// Containers and machines.
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryDrag(InventoryDragEvent event) {
|
||||
allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryMove(InventoryMoveItemEvent event) {
|
||||
allowContainerOrCancel(event, event.getSource(), null);
|
||||
if (!event.isCancelled()) {
|
||||
allowContainerOrCancel(event, event.getDestination(), null);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryPickup(InventoryPickupItemEvent event) {
|
||||
allowContainerOrCancel(event, event.getInventory(), null);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockCook(BlockCookEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onFurnaceBurn(FurnaceBurnEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onFurnaceSmelt(FurnaceSmeltEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBrew(BrewEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBrewingStandFuel(BrewingStandFuelEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockDispense(BlockDispenseEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onCrafterCraft(CrafterCraftEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
// What players do.
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
|
||||
public void onInteract(PlayerInteractEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Optional<BukkitToolWorld> toolWorld = worlds.forWorld(player.getWorld());
|
||||
if (toolWorld.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
ToolUse use = new ToolUse(
|
||||
event.getHand() == org.bukkit.inventory.EquipmentSlot.OFF_HAND ? ToolUse.Hand.OFF : ToolUse.Hand.MAIN,
|
||||
ToolUse.Action.valueOf(event.getAction().name()),
|
||||
BukkitToolItems.read(event.getItem()),
|
||||
Optional.ofNullable(event.getClickedBlock()).map(ToolWorldEvents::positionOf),
|
||||
BukkitToolBlocks.faceOf(event.getBlockFace()));
|
||||
ToolPlayer toolPlayer = players.of(player);
|
||||
if (!toolWorld.get().ask(listener -> listener.used(toolPlayer, use), false)) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onToggleSneak(PlayerToggleSneakEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
worlds.forWorld(player.getWorld()).ifPresent(world ->
|
||||
world.tell(listener -> listener.sneakToggled(players.of(player), event.isSneaking())));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Optional<BukkitToolWorld> toolWorld = worlds.forWorld(player.getWorld());
|
||||
if (toolWorld.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String line = lineOf(event.getMessage());
|
||||
ToolPlayer toolPlayer = players.of(player);
|
||||
if (!toolWorld.get().ask(listener -> listener.command(Optional.of(toolPlayer), line), true)) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onServerCommand(ServerCommandEvent event) {
|
||||
String line = lineOf(event.getCommand());
|
||||
for (BukkitToolWorld toolWorld : worlds.all()) {
|
||||
if (!toolWorld.ask(listener -> listener.command(Optional.empty(), line), true)) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Arriving, leaving and moving.
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
worlds.forWorld(event.getPlayer().getWorld()).ifPresent(world -> enter(world, event.getPlayer()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
worlds.forWorld(player.getWorld()).ifPresent(world -> leave(world, player));
|
||||
players.forget(player);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onChangedWorld(PlayerChangedWorldEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
worlds.forWorld(event.getFrom()).ifPresent(world -> leave(world, player));
|
||||
worlds.forWorld(player.getWorld()).ifPresent(world -> enter(world, player));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onTeleport(PlayerTeleportEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Optional<BukkitToolWorld> from = worlds.forWorld(event.getFrom().getWorld());
|
||||
Optional<BukkitToolWorld> to = event.getTo() == null ? Optional.empty() : worlds.forWorld(event.getTo().getWorld());
|
||||
if (from.isPresent() && from.equals(to)) {
|
||||
return;
|
||||
}
|
||||
if (from.isEmpty() && to.isPresent()) {
|
||||
players.rememberOrigin(player, event.getFrom());
|
||||
}
|
||||
if (from.isPresent() && to.isEmpty()) {
|
||||
players.restoreGameMode(player);
|
||||
players.takeOrigin(player);
|
||||
}
|
||||
from.ifPresent(world -> leave(world, player));
|
||||
to.ifPresent(world -> enter(world, player));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onRespawn(PlayerRespawnEvent event) {
|
||||
worlds.forWorld(event.getRespawnLocation().getWorld()).ifPresent(world -> enter(world, event.getPlayer()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onMove(PlayerMoveEvent event) {
|
||||
Location to = event.getTo();
|
||||
if (to == null || sameBlock(event.getFrom(), to)) {
|
||||
return;
|
||||
}
|
||||
worlds.forWorld(to.getWorld()).ifPresent(world ->
|
||||
world.tell(listener -> listener.moved(players.of(event.getPlayer()), BukkitToolBlocks.positionOf(to))));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onChunkLoad(ChunkLoadEvent event) {
|
||||
worlds.forWorld(event.getWorld()).ifPresent(world -> world.chunkLoaded(event.getChunk()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onWorldUnload(WorldUnloadEvent event) {
|
||||
worlds.forWorld(event.getWorld()).ifPresent(BukkitToolWorld::unloaded);
|
||||
}
|
||||
|
||||
// The host's own rules.
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onNaturalSpawn(CreatureSpawnEvent event) {
|
||||
if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NATURAL
|
||||
&& worlds.forWorld(event.getLocation().getWorld()).isPresent()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPortal(PlayerPortalEvent event) {
|
||||
if (worlds.forWorld(event.getFrom().getWorld()).isPresent()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void enter(BukkitToolWorld world, Player player) {
|
||||
if (world.presence().enter(player.getUniqueId())) {
|
||||
world.tell(listener -> listener.entered(players.of(player)));
|
||||
}
|
||||
}
|
||||
|
||||
private void leave(BukkitToolWorld world, Player player) {
|
||||
if (world.presence().leave(player.getUniqueId())) {
|
||||
world.tell(listener -> listener.left(players.of(player)));
|
||||
}
|
||||
}
|
||||
|
||||
private void allowOrCancel(Cancellable event, Cause cause, Block block, Optional<Player> player) {
|
||||
allowOrCancel(event, cause, block.getWorld(), List.of(positionOf(block)), player, Optional.empty());
|
||||
}
|
||||
|
||||
private void allowOrCancel(
|
||||
Cancellable event,
|
||||
Cause cause,
|
||||
World world,
|
||||
List<BlockPosition> positions,
|
||||
Optional<Player> player,
|
||||
Optional<BlockState> placed
|
||||
) {
|
||||
if (!isAllowed(cause, world, positions, player, placed)) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void allowContainerOrCancel(Cancellable event, Inventory inventory, Player player) {
|
||||
List<Block> blocks = containerBlocks(inventory);
|
||||
if (blocks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<BlockPosition> positions = blocks.stream().map(ToolWorldEvents::positionOf).toList();
|
||||
allowOrCancel(event, Cause.CONTAINER, blocks.getFirst().getWorld(), positions, Optional.ofNullable(player), Optional.empty());
|
||||
}
|
||||
|
||||
/** Whether the tool lets the change happen; changes outside tool worlds are none of the host's business. */
|
||||
private boolean isAllowed(
|
||||
Cause cause,
|
||||
World world,
|
||||
List<BlockPosition> positions,
|
||||
Optional<Player> player,
|
||||
Optional<BlockState> placed
|
||||
) {
|
||||
Optional<BukkitToolWorld> toolWorld = worlds.forWorld(world);
|
||||
if (toolWorld.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
BlockChange change = new BlockChange(cause, positions, player.map(players::of).map(ToolPlayer.class::cast), placed);
|
||||
return toolWorld.get().ask(listener -> listener.blockChanging(change), false);
|
||||
}
|
||||
|
||||
private void keepAllowedBlocks(World world, List<Block> exploded) {
|
||||
if (worlds.forWorld(world).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
exploded.removeIf(block -> !isAllowed(Cause.EXPLOSION, world, List.of(positionOf(block)), Optional.empty(), Optional.empty()));
|
||||
}
|
||||
|
||||
/** The piston, each block it moves, and the block each of them leaves and enters, as a protected area is checked. */
|
||||
static List<BlockPosition> pistonPositions(Block piston, List<Block> moved, BlockFace direction) {
|
||||
List<BlockPosition> positions = new ArrayList<>();
|
||||
positions.add(positionOf(piston));
|
||||
for (Block block : moved) {
|
||||
positions.add(positionOf(block));
|
||||
positions.add(positionOf(block.getRelative(direction)));
|
||||
positions.add(positionOf(block.getRelative(direction.getOppositeFace())));
|
||||
}
|
||||
return positions.stream().distinct().toList();
|
||||
}
|
||||
|
||||
/** The blocks a container inventory is made of: none for a player's or a menu, two for a double chest. */
|
||||
static List<Block> containerBlocks(Inventory inventory) {
|
||||
if (inventory == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<Block> blocks = new ArrayList<>(2);
|
||||
InventoryHolder holder = inventory.getHolder();
|
||||
if (holder instanceof BlockInventoryHolder blockHolder) {
|
||||
blocks.add(blockHolder.getBlock());
|
||||
} else if (holder instanceof DoubleChest doubleChest) {
|
||||
addBlockOf(blocks, doubleChest.getLeftSide());
|
||||
addBlockOf(blocks, doubleChest.getRightSide());
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private static void addBlockOf(List<Block> blocks, InventoryHolder holder) {
|
||||
if (holder instanceof BlockInventoryHolder blockHolder && !blocks.contains(blockHolder.getBlock())) {
|
||||
blocks.add(blockHolder.getBlock());
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether two locations are in one block of one world. */
|
||||
static boolean sameBlock(Location from, Location to) {
|
||||
return from.getWorld() == to.getWorld()
|
||||
&& from.getBlockX() == to.getBlockX()
|
||||
&& from.getBlockY() == to.getBlockY()
|
||||
&& from.getBlockZ() == to.getBlockZ();
|
||||
}
|
||||
|
||||
/** What a command line is for the tool: without the slash a player types before it. */
|
||||
static String lineOf(String typed) {
|
||||
return typed.startsWith(COMMAND_PREFIX) ? typed.substring(COMMAND_PREFIX.length()) : typed;
|
||||
}
|
||||
|
||||
private static BlockPosition positionOf(Block block) {
|
||||
return BukkitToolBlocks.positionOf(block);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Who stands in one tool world, so that the platform's several ways of arriving and leaving (join, teleport, world
|
||||
* change, respawn, quit) tell the tool once for each stay: {@code entered} on the first of them, {@code left} on the
|
||||
* first of them after.
|
||||
*/
|
||||
final class ToolWorldPresence {
|
||||
private final Set<UUID> present = ConcurrentHashMap.newKeySet();
|
||||
|
||||
/** Whether the player was not here before, which is when the tool hears {@code entered}. */
|
||||
boolean enter(UUID player) {
|
||||
return present.add(player);
|
||||
}
|
||||
|
||||
/** Whether the player was here, which is when the tool hears {@code left}. */
|
||||
boolean leave(UUID player) {
|
||||
return present.remove(player);
|
||||
}
|
||||
|
||||
boolean isPresent(UUID player) {
|
||||
return present.contains(player);
|
||||
}
|
||||
}
|
||||
+43
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.runtime.WorldRuntimeControlService;
|
||||
import org.bukkit.GameRules;
|
||||
import org.bukkit.World;
|
||||
|
||||
/**
|
||||
* What every tool world is made to be, whatever the server's studio settings say: no natural mobs, no weather, no
|
||||
* daylight cycle, no portals, on top of the rules the object and jigsaw studios already use.
|
||||
*/
|
||||
final class ToolWorldRules {
|
||||
private ToolWorldRules() {
|
||||
}
|
||||
|
||||
/** Applies the rules; runs on the thread that may change the world's rules (the main or global thread). */
|
||||
static void apply(World world) {
|
||||
WorldRuntimeControlService.get().applyObjectStudioWorldRules(world);
|
||||
world.setGameRule(GameRules.SPAWN_MOBS, false);
|
||||
world.setGameRule(GameRules.ADVANCE_WEATHER, false);
|
||||
world.setGameRule(GameRules.ADVANCE_TIME, false);
|
||||
world.setGameRule(GameRules.ALLOW_ENTERING_NETHER_USING_PORTALS, false);
|
||||
world.setStorm(false);
|
||||
world.setThundering(false);
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.world.ToolItem;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class BukkitToolItemsTest {
|
||||
private ItemStack stackWith(PersistentDataContainer data, ItemMeta meta) {
|
||||
ItemStack stack = mock(ItemStack.class);
|
||||
when(stack.getType()).thenReturn(Material.STICK);
|
||||
when(stack.hasItemMeta()).thenReturn(true);
|
||||
when(stack.getItemMeta()).thenReturn(meta);
|
||||
when(meta.getPersistentDataContainer()).thenReturn(data);
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aStackWithThePayloadReadsBackAsTheToolItemItWasMadeFrom() {
|
||||
PersistentDataContainer data = mock(PersistentDataContainer.class);
|
||||
ItemMeta meta = mock(ItemMeta.class);
|
||||
when(data.get(BukkitToolItems.PAYLOAD_KEY, PersistentDataType.STRING)).thenReturn("select:bay-1");
|
||||
when(meta.hasDisplayName()).thenReturn(true);
|
||||
when(meta.displayName()).thenReturn(Component.text("Select bay"));
|
||||
when(meta.hasLore()).thenReturn(true);
|
||||
when(meta.lore()).thenReturn(List.of(Component.text("Right-click to use")));
|
||||
when(meta.getEnchantmentGlintOverride()).thenReturn(true);
|
||||
|
||||
Optional<ToolItem> item = BukkitToolItems.read(stackWith(data, meta));
|
||||
|
||||
assertEquals(Optional.of(new ToolItem(ResourceId.parse("minecraft:stick"), "Select bay",
|
||||
List.of("Right-click to use"), true, "select:bay-1")), item);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void anEmptyPayloadStillMakesAToolItemAndAMissingOneDoesNot() {
|
||||
PersistentDataContainer empty = mock(PersistentDataContainer.class);
|
||||
when(empty.get(BukkitToolItems.PAYLOAD_KEY, PersistentDataType.STRING)).thenReturn("");
|
||||
PersistentDataContainer missing = mock(PersistentDataContainer.class);
|
||||
|
||||
ToolItem tagged = BukkitToolItems.read(stackWith(empty, mock(ItemMeta.class))).orElseThrow();
|
||||
|
||||
assertEquals("", tagged.payload());
|
||||
assertEquals("", tagged.name());
|
||||
assertEquals(List.of(), tagged.lore());
|
||||
assertTrue(BukkitToolItems.read(stackWith(missing, mock(ItemMeta.class))).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nothingAirOrAStackWithoutMetadataIsNotAToolItem() {
|
||||
ItemStack air = mock(ItemStack.class);
|
||||
when(air.getType()).thenReturn(Material.AIR);
|
||||
ItemStack plain = mock(ItemStack.class);
|
||||
when(plain.getType()).thenReturn(Material.STICK);
|
||||
when(plain.hasItemMeta()).thenReturn(false);
|
||||
|
||||
assertTrue(BukkitToolItems.read(null).isEmpty());
|
||||
assertTrue(BukkitToolItems.read(air).isEmpty());
|
||||
assertTrue(BukkitToolItems.read(plain).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void thePayloadLivesUnderTheIrisToolPayloadKey() {
|
||||
assertEquals("iris:tool_payload", BukkitToolItems.PAYLOAD_KEY.toString());
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedChunk;
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import org.bukkit.World;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The small pieces of state the Bukkit host keeps for its tool worlds. */
|
||||
public class ToolWorldBookkeepingTest {
|
||||
private static final BlockEntityData DATA = new BlockEntityData(ResourceId.parse("iris:tile"), 1, new byte[] {1});
|
||||
|
||||
@Test
|
||||
public void aPlayerEntersAndLeavesOncePerStay() {
|
||||
ToolWorldPresence presence = new ToolWorldPresence();
|
||||
UUID player = UUID.randomUUID();
|
||||
|
||||
assertFalse(presence.leave(player));
|
||||
assertTrue(presence.enter(player));
|
||||
assertFalse(presence.enter(player));
|
||||
assertTrue(presence.isPresent(player));
|
||||
assertTrue(presence.leave(player));
|
||||
assertFalse(presence.leave(player));
|
||||
assertTrue("a second stay is told again", presence.enter(player));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void blockEntitiesWaitForTheirChunkAndAreHandedOverOnce() {
|
||||
PendingBlockEntities pending = new PendingBlockEntities();
|
||||
PaintedBlockEntity chest = new PaintedBlockEntity(1, 64, 2, DATA);
|
||||
pending.add(new PaintedChunk(-3, 7, List.of(chest)));
|
||||
|
||||
assertEquals(List.of(), pending.take(3, 7));
|
||||
assertEquals(List.of(), pending.take(-3, -7));
|
||||
assertEquals(List.of(chest), pending.take(-3, 7));
|
||||
assertEquals(List.of(), pending.take(-3, 7));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aLaterPaintOfAChunkReplacesWhatWaitedForIt() {
|
||||
PendingBlockEntities pending = new PendingBlockEntities();
|
||||
PaintedBlockEntity first = new PaintedBlockEntity(1, 64, 2, DATA);
|
||||
PaintedBlockEntity second = new PaintedBlockEntity(3, 64, 4, DATA);
|
||||
pending.add(new PaintedChunk(0, 0, List.of(first)));
|
||||
pending.add(new PaintedChunk(0, 0, List.of(second)));
|
||||
|
||||
assertEquals(List.of(second), pending.take(0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aToolNameIsTakenWithinAPackAndFreeAgainOnceTheWorldIsUnregistered() {
|
||||
OpenToolWorlds worlds = new OpenToolWorlds();
|
||||
BukkitToolWorld first = toolWorld(worlds, "pack-a", "scratch", "iris-1");
|
||||
BukkitToolWorld sameNameOtherPack = toolWorld(worlds, "pack-b", "scratch", "iris-2");
|
||||
BukkitToolWorld sameNameSamePack = toolWorld(worlds, "pack-a", "scratch", "iris-3");
|
||||
|
||||
assertTrue(worlds.register(first));
|
||||
assertTrue(worlds.register(sameNameOtherPack));
|
||||
assertFalse(worlds.register(sameNameSamePack));
|
||||
assertEquals(first, worlds.forName("pack-a", "scratch").orElseThrow());
|
||||
|
||||
worlds.unregister(first);
|
||||
|
||||
assertTrue(worlds.forName("pack-a", "scratch").isEmpty());
|
||||
assertTrue(worlds.register(sameNameSamePack));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aBoundWorldIsFoundByItsBukkitWorldAndNotByAnotherWorld() {
|
||||
OpenToolWorlds worlds = new OpenToolWorlds();
|
||||
BukkitToolWorld toolWorld = toolWorld(worlds, "pack", "scratch", "iris-1");
|
||||
World bukkit = world(UUID.randomUUID());
|
||||
World other = world(UUID.randomUUID());
|
||||
assertTrue(worlds.register(toolWorld));
|
||||
|
||||
toolWorld.bind(bukkit);
|
||||
|
||||
assertEquals(toolWorld, worlds.forWorld(bukkit).orElseThrow());
|
||||
assertTrue(worlds.forWorld(other).isEmpty());
|
||||
assertTrue(worlds.forWorld(null).isEmpty());
|
||||
|
||||
worlds.unregister(toolWorld);
|
||||
|
||||
assertTrue(worlds.forWorld(bukkit).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aMenuSlotCountsFromTheMiddleColumnOfTheWindow() {
|
||||
assertEquals(-4, BukkitToolMenus.positionOf(0));
|
||||
assertEquals(0, BukkitToolMenus.positionOf(4));
|
||||
assertEquals(4, BukkitToolMenus.positionOf(8));
|
||||
assertEquals(-4, BukkitToolMenus.positionOf(9));
|
||||
assertEquals(4, BukkitToolMenus.positionOf(53));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aMenuTitleIsShortenedToWhatTheWindowCanShow() {
|
||||
assertEquals("short", BukkitToolMenus.shortened("short"));
|
||||
assertEquals(32, BukkitToolMenus.shortened("x".repeat(50)).length());
|
||||
}
|
||||
|
||||
private static BukkitToolWorld toolWorld(OpenToolWorlds worlds, String pack, String name, String storageName) {
|
||||
return new BukkitToolWorld(pack, name, storageName, new com.volmit.tooling.world.ToolWorldListener() { }, null,
|
||||
new PendingBlockEntities(), worlds, new ToolPlayers(worlds));
|
||||
}
|
||||
|
||||
private static World world(UUID id) {
|
||||
World world = mock(World.class);
|
||||
when(world.getUID()).thenReturn(id);
|
||||
return world;
|
||||
}
|
||||
}
|
||||
+433
@@ -0,0 +1,433 @@
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
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 com.volmit.tooling.world.ToolWorldListener;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockExplodeEvent;
|
||||
import org.bukkit.event.block.BlockFromToEvent;
|
||||
import org.bukkit.event.block.BlockPistonExtendEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.bukkit.event.block.BlockRedstoneEvent;
|
||||
import org.bukkit.event.block.CrafterCraftEvent;
|
||||
import org.bukkit.event.entity.CreatureSpawnEvent;
|
||||
import org.bukkit.event.player.PlayerBucketEmptyEvent;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent;
|
||||
import org.bukkit.event.server.ServerCommandEvent;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The events of a tool world reach its listener as the api says, and the events of other worlds reach nobody. */
|
||||
public class ToolWorldEventsTest {
|
||||
private static final UUID TOOL_WORLD_ID = UUID.fromString("00000000-0000-0000-0000-0000000000a1");
|
||||
private static final UUID OTHER_WORLD_ID = UUID.fromString("00000000-0000-0000-0000-0000000000b2");
|
||||
private static final UUID PLAYER_ID = UUID.fromString("00000000-0000-0000-0000-0000000000c3");
|
||||
|
||||
private final List<BlockChange> changes = new ArrayList<>();
|
||||
private final List<String> heard = new ArrayList<>();
|
||||
private boolean allowChanges;
|
||||
private boolean allowUses = true;
|
||||
private boolean allowCommands = true;
|
||||
private World toolBukkitWorld;
|
||||
private World otherBukkitWorld;
|
||||
private Player bukkitPlayer;
|
||||
private ToolWorldEvents events;
|
||||
|
||||
@Before
|
||||
public void aToolWorldAndAnotherWorld() {
|
||||
ToolWorldListener listener = new ToolWorldListener() {
|
||||
@Override
|
||||
public void entered(ToolPlayer player) {
|
||||
heard.add("entered " + player.name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void left(ToolPlayer player) {
|
||||
heard.add("left " + player.name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean used(ToolPlayer player, ToolUse use) {
|
||||
heard.add("used " + use.action() + " " + use.hand());
|
||||
return allowUses;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean blockChanging(BlockChange change) {
|
||||
changes.add(change);
|
||||
return allowChanges;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean command(Optional<ToolPlayer> sender, String line) {
|
||||
heard.add("command " + sender.map(ToolPlayer::name).orElse("console") + " " + line);
|
||||
return allowCommands;
|
||||
}
|
||||
};
|
||||
OpenToolWorlds worlds = new OpenToolWorlds();
|
||||
ToolPlayers players = new ToolPlayers(worlds);
|
||||
BukkitToolWorld toolWorld = new BukkitToolWorld("pack", "scratch", "iris-test", listener, null,
|
||||
new PendingBlockEntities(), worlds, players);
|
||||
toolBukkitWorld = world(TOOL_WORLD_ID);
|
||||
otherBukkitWorld = world(OTHER_WORLD_ID);
|
||||
assertTrue(worlds.register(toolWorld));
|
||||
toolWorld.bind(toolBukkitWorld);
|
||||
bukkitPlayer = mock(Player.class);
|
||||
when(bukkitPlayer.getUniqueId()).thenReturn(PLAYER_ID);
|
||||
when(bukkitPlayer.getName()).thenReturn("Tester");
|
||||
when(bukkitPlayer.getWorld()).thenReturn(toolBukkitWorld);
|
||||
events = new ToolWorldEvents(worlds, players);
|
||||
}
|
||||
|
||||
private static World world(UUID id) {
|
||||
World world = mock(World.class);
|
||||
when(world.getUID()).thenReturn(id);
|
||||
return world;
|
||||
}
|
||||
|
||||
private static Block block(World world, int x, int y, int z) {
|
||||
Block block = mock(Block.class);
|
||||
when(block.getWorld()).thenReturn(world);
|
||||
when(block.getX()).thenReturn(x);
|
||||
when(block.getY()).thenReturn(y);
|
||||
when(block.getZ()).thenReturn(z);
|
||||
BlockData data = mock(BlockData.class);
|
||||
when(data.getAsString()).thenReturn("minecraft:stone");
|
||||
when(block.getBlockData()).thenReturn(data);
|
||||
return block;
|
||||
}
|
||||
|
||||
private BlockChange onlyChange() {
|
||||
assertEquals(1, changes.size());
|
||||
return changes.getFirst();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aPlacedBlockIsAPlaceChangeWithThePlacedStateAndThePlayer() {
|
||||
Block placed = block(toolBukkitWorld, 3, 70, -4);
|
||||
BlockPlaceEvent event = mock(BlockPlaceEvent.class);
|
||||
when(event.getBlockPlaced()).thenReturn(placed);
|
||||
when(event.getPlayer()).thenReturn(bukkitPlayer);
|
||||
|
||||
events.onBlockPlace(event);
|
||||
|
||||
BlockChange change = onlyChange();
|
||||
assertEquals(Cause.PLACE, change.cause());
|
||||
assertEquals(List.of(new BlockPosition(3, 70, -4)), change.positions());
|
||||
assertEquals("minecraft:stone", change.placed().orElseThrow().key());
|
||||
assertEquals("Tester", change.player().orElseThrow().name());
|
||||
verify(event).setCancelled(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aListenerThatAllowsTheChangeLeavesTheEventAlone() {
|
||||
allowChanges = true;
|
||||
Block broken = block(toolBukkitWorld, 1, 2, 3);
|
||||
BlockBreakEvent event = mock(BlockBreakEvent.class);
|
||||
when(event.getBlock()).thenReturn(broken);
|
||||
when(event.getPlayer()).thenReturn(bukkitPlayer);
|
||||
|
||||
events.onBlockBreak(event);
|
||||
|
||||
assertEquals(Cause.BREAK, onlyChange().cause());
|
||||
verify(event, never()).setCancelled(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aBucketEmptiesIntoTheBlockNextToTheOneClicked() {
|
||||
Block clicked = block(toolBukkitWorld, 0, 64, 0);
|
||||
Block target = block(toolBukkitWorld, 0, 65, 0);
|
||||
when(clicked.getRelative(BlockFace.UP)).thenReturn(target);
|
||||
PlayerBucketEmptyEvent event = mock(PlayerBucketEmptyEvent.class);
|
||||
when(event.getBlockClicked()).thenReturn(clicked);
|
||||
when(event.getBlockFace()).thenReturn(BlockFace.UP);
|
||||
when(event.getPlayer()).thenReturn(bukkitPlayer);
|
||||
|
||||
events.onBucketEmpty(event);
|
||||
|
||||
BlockChange change = onlyChange();
|
||||
assertEquals(Cause.BUCKET, change.cause());
|
||||
assertEquals(List.of(new BlockPosition(0, 65, 0)), change.positions());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void flowingFluidNamesTheSourceAndTheTargetBlock() {
|
||||
Block source = block(toolBukkitWorld, 0, 64, 0);
|
||||
Block target = block(toolBukkitWorld, 1, 64, 0);
|
||||
BlockFromToEvent event = mock(BlockFromToEvent.class);
|
||||
when(event.getBlock()).thenReturn(source);
|
||||
when(event.getToBlock()).thenReturn(target);
|
||||
|
||||
events.onBlockFromTo(event);
|
||||
|
||||
BlockChange change = onlyChange();
|
||||
assertEquals(Cause.FLUID, change.cause());
|
||||
assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0)), change.positions());
|
||||
assertTrue(change.player().isEmpty());
|
||||
verify(event).setCancelled(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aPistonNamesItselfAndEveryBlockItMovesAndTheirNeighboursInTheDirectionOfTheMove() {
|
||||
Block piston = block(toolBukkitWorld, 0, 64, 0);
|
||||
Block moved = block(toolBukkitWorld, 1, 64, 0);
|
||||
Block ahead = block(toolBukkitWorld, 2, 64, 0);
|
||||
when(moved.getRelative(BlockFace.EAST)).thenReturn(ahead);
|
||||
when(moved.getRelative(BlockFace.WEST)).thenReturn(piston);
|
||||
|
||||
List<BlockPosition> positions = ToolWorldEvents.pistonPositions(piston, List.of(moved), BlockFace.EAST);
|
||||
|
||||
assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0), new BlockPosition(2, 64, 0)), positions);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aPistonExtendingInAToolWorldIsAPistonChange() {
|
||||
Block piston = block(toolBukkitWorld, 0, 64, 0);
|
||||
BlockPistonExtendEvent event = mock(BlockPistonExtendEvent.class);
|
||||
when(event.getBlock()).thenReturn(piston);
|
||||
when(event.getBlocks()).thenReturn(List.of());
|
||||
when(event.getDirection()).thenReturn(BlockFace.EAST);
|
||||
|
||||
events.onPistonExtend(event);
|
||||
|
||||
assertEquals(Cause.PISTON, onlyChange().cause());
|
||||
verify(event).setCancelled(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void anExplosionAsksForEachBlockAndKeepsOnlyTheOnesTheToolAllows() {
|
||||
allowChanges = false;
|
||||
Block first = block(toolBukkitWorld, 0, 64, 0);
|
||||
Block second = block(toolBukkitWorld, 5, 64, 5);
|
||||
List<Block> blockList = new ArrayList<>(List.of(first, second));
|
||||
Block source = block(toolBukkitWorld, 0, 70, 0);
|
||||
BlockExplodeEvent event = mock(BlockExplodeEvent.class);
|
||||
when(event.getBlock()).thenReturn(source);
|
||||
when(event.blockList()).thenReturn(blockList);
|
||||
|
||||
events.onBlockExplode(event);
|
||||
|
||||
assertEquals(2, changes.size());
|
||||
assertEquals(Cause.EXPLOSION, changes.getFirst().cause());
|
||||
assertTrue("nothing was allowed to blow up", blockList.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void refusedRedstoneKeepsTheOldCurrent() {
|
||||
Block wire = block(toolBukkitWorld, 0, 64, 0);
|
||||
BlockRedstoneEvent event = mock(BlockRedstoneEvent.class);
|
||||
when(event.getBlock()).thenReturn(wire);
|
||||
when(event.getOldCurrent()).thenReturn(7);
|
||||
|
||||
events.onBlockRedstone(event);
|
||||
|
||||
assertEquals(Cause.REDSTONE, onlyChange().cause());
|
||||
verify(event).setNewCurrent(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aCrafterIsAMachine() {
|
||||
Block crafter = block(toolBukkitWorld, 0, 64, 0);
|
||||
CrafterCraftEvent event = mock(CrafterCraftEvent.class);
|
||||
when(event.getBlock()).thenReturn(crafter);
|
||||
|
||||
events.onCrafterCraft(event);
|
||||
|
||||
assertEquals(Cause.MACHINE, onlyChange().cause());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nothingThatHappensInAnotherWorldReachesTheToolOrIsCancelled() {
|
||||
Block brokenElsewhere = block(otherBukkitWorld, 1, 2, 3);
|
||||
Block wireElsewhere = block(otherBukkitWorld, 1, 2, 3);
|
||||
BlockBreakEvent breaking = mock(BlockBreakEvent.class);
|
||||
when(breaking.getBlock()).thenReturn(brokenElsewhere);
|
||||
when(breaking.getPlayer()).thenReturn(bukkitPlayer);
|
||||
BlockRedstoneEvent redstone = mock(BlockRedstoneEvent.class);
|
||||
when(redstone.getBlock()).thenReturn(wireElsewhere);
|
||||
|
||||
events.onBlockBreak(breaking);
|
||||
events.onBlockRedstone(redstone);
|
||||
|
||||
assertTrue(changes.isEmpty());
|
||||
verify(breaking, never()).setCancelled(true);
|
||||
verify(redstone, never()).setNewCurrent(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usingTheHandIsAUseWithTheHandAndActionAndAFalseCancelsIt() {
|
||||
allowUses = false;
|
||||
PlayerInteractEvent event = mock(PlayerInteractEvent.class);
|
||||
when(event.getPlayer()).thenReturn(bukkitPlayer);
|
||||
when(event.getHand()).thenReturn(EquipmentSlot.OFF_HAND);
|
||||
when(event.getAction()).thenReturn(Action.RIGHT_CLICK_AIR);
|
||||
when(event.getBlockFace()).thenReturn(BlockFace.SELF);
|
||||
|
||||
events.onInteract(event);
|
||||
|
||||
assertEquals(List.of("used RIGHT_CLICK_AIR OFF"), heard);
|
||||
verify(event).setCancelled(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aCommandReachesTheToolWithoutItsSlashAndTheConsoleHasNoPlayer() {
|
||||
allowCommands = false;
|
||||
PlayerCommandPreprocessEvent typed = mock(PlayerCommandPreprocessEvent.class);
|
||||
when(typed.getPlayer()).thenReturn(bukkitPlayer);
|
||||
when(typed.getMessage()).thenReturn("/gamemode survival");
|
||||
ServerCommandEvent console = mock(ServerCommandEvent.class);
|
||||
when(console.getCommand()).thenReturn("stop");
|
||||
|
||||
events.onPlayerCommand(typed);
|
||||
events.onServerCommand(console);
|
||||
|
||||
assertEquals(List.of("command Tester gamemode survival", "command console stop"), heard);
|
||||
verify(typed).setCancelled(true);
|
||||
verify(console).setCancelled(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void naturalSpawnsInAToolWorldAreCancelledButOtherSpawnsAreNot() {
|
||||
CreatureSpawnEvent natural = mock(CreatureSpawnEvent.class);
|
||||
when(natural.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.NATURAL);
|
||||
when(natural.getLocation()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
|
||||
CreatureSpawnEvent egg = mock(CreatureSpawnEvent.class);
|
||||
when(egg.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.SPAWNER_EGG);
|
||||
when(egg.getLocation()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
|
||||
CreatureSpawnEvent elsewhere = mock(CreatureSpawnEvent.class);
|
||||
when(elsewhere.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.NATURAL);
|
||||
when(elsewhere.getLocation()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0));
|
||||
|
||||
events.onNaturalSpawn(natural);
|
||||
events.onNaturalSpawn(egg);
|
||||
events.onNaturalSpawn(elsewhere);
|
||||
|
||||
verify(natural).setCancelled(true);
|
||||
verify(egg, never()).setCancelled(true);
|
||||
verify(elsewhere, never()).setCancelled(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void enteringIsToldOnceHoweverManyEventsAnnounceTheArrival() {
|
||||
PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class);
|
||||
when(teleport.getPlayer()).thenReturn(bukkitPlayer);
|
||||
when(teleport.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0));
|
||||
when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
|
||||
|
||||
events.onTeleport(teleport);
|
||||
events.onTeleport(teleport);
|
||||
|
||||
assertEquals(List.of("entered Tester"), heard);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void leavingByQuittingIsToldOnceAfterTheStay() {
|
||||
PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class);
|
||||
when(teleport.getPlayer()).thenReturn(bukkitPlayer);
|
||||
when(teleport.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0));
|
||||
when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0));
|
||||
PlayerQuitEvent quit = mock(PlayerQuitEvent.class);
|
||||
when(quit.getPlayer()).thenReturn(bukkitPlayer);
|
||||
|
||||
events.onTeleport(teleport);
|
||||
events.onQuit(quit);
|
||||
events.onQuit(quit);
|
||||
|
||||
assertEquals(List.of("entered Tester", "left Tester"), heard);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void movingInsideOneBlockIsNotAMove() {
|
||||
Location from = new Location(toolBukkitWorld, 1.1, 64.0, 2.2);
|
||||
|
||||
assertTrue(ToolWorldEvents.sameBlock(from, new Location(toolBukkitWorld, 1.9, 64.5, 2.9)));
|
||||
assertFalse(ToolWorldEvents.sameBlock(from, new Location(toolBukkitWorld, 2.1, 64.0, 2.2)));
|
||||
assertFalse(ToolWorldEvents.sameBlock(from, new Location(otherBukkitWorld, 1.1, 64.0, 2.2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aCommandLineHasNoLeadingSlash() {
|
||||
assertEquals("tp a b", ToolWorldEvents.lineOf("/tp a b"));
|
||||
assertEquals("tp a b", ToolWorldEvents.lineOf("tp a b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void everyHandlerKeepsThePriorityAndCancelFlagOfTheJigsawStudioHandlerItReplaces() {
|
||||
Map<String, EventHandler> byMethod = new HashMap<>();
|
||||
for (Method method : ToolWorldEvents.class.getDeclaredMethods()) {
|
||||
EventHandler handler = method.getAnnotation(EventHandler.class);
|
||||
if (handler != null) {
|
||||
byMethod.put(method.getName(), handler);
|
||||
}
|
||||
}
|
||||
Set<String> checked = new HashSet<>();
|
||||
|
||||
for (String decision : List.of("onBlockPlace", "onBlockMultiPlace", "onBlockBreak", "onBucketEmpty", "onBucketFill",
|
||||
"onBlockForm", "onBlockFade", "onBlockSpread", "onBlockFromTo", "onBlockGrow", "onStructureGrow", "onBlockBurn",
|
||||
"onPistonExtend", "onPistonRetract", "onBlockExplode", "onEntityExplode", "onEntityChangeBlock",
|
||||
"onInventoryClick", "onInventoryDrag", "onInventoryMove", "onInventoryPickup", "onBlockCook", "onFurnaceBurn",
|
||||
"onFurnaceSmelt", "onBrew", "onBrewingStandFuel", "onBlockDispense", "onCrafterCraft", "onPlayerCommand",
|
||||
"onServerCommand", "onNaturalSpawn", "onPortal")) {
|
||||
assertPriority(byMethod, checked, decision, EventPriority.HIGHEST, true);
|
||||
}
|
||||
assertPriority(byMethod, checked, "onBlockRedstone", EventPriority.HIGHEST, false);
|
||||
assertPriority(byMethod, checked, "onInteract", EventPriority.LOWEST, true);
|
||||
assertPriority(byMethod, checked, "onToggleSneak", EventPriority.NORMAL, false);
|
||||
for (String arrival : List.of("onJoin", "onQuit", "onChangedWorld", "onChunkLoad")) {
|
||||
assertPriority(byMethod, checked, arrival, EventPriority.NORMAL, false);
|
||||
}
|
||||
assertPriority(byMethod, checked, "onTeleport", EventPriority.MONITOR, true);
|
||||
assertPriority(byMethod, checked, "onMove", EventPriority.MONITOR, true);
|
||||
assertPriority(byMethod, checked, "onRespawn", EventPriority.MONITOR, false);
|
||||
assertPriority(byMethod, checked, "onWorldUnload", EventPriority.MONITOR, true);
|
||||
assertEquals("every handler of the class was checked", byMethod.keySet(), checked);
|
||||
}
|
||||
|
||||
private static void assertPriority(
|
||||
Map<String, EventHandler> byMethod,
|
||||
Set<String> checked,
|
||||
String method,
|
||||
EventPriority priority,
|
||||
boolean ignoreCancelled
|
||||
) {
|
||||
checked.add(method);
|
||||
EventHandler handler = byMethod.get(method);
|
||||
assertTrue(method + " is a handler", handler != null);
|
||||
assertEquals(method + " priority", priority, handler.priority());
|
||||
assertEquals(method + " ignoreCancelled", ignoreCancelled, handler.ignoreCancelled());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user