Added the ability to convert from stackmob and wildstacker.

This commit is contained in:
Brianna 2019-06-09 20:47:29 -04:00
parent 43737db620
commit 6f40d5c20c
23 changed files with 1165 additions and 103 deletions

View File

@ -93,5 +93,10 @@
<artifactId>WildStacker</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>uk.antiperson</groupId>
<artifactId>stackmob</artifactId>
<version>4</version>
</dependency>
</dependencies>
</project>

View File

@ -5,6 +5,8 @@ import com.songoda.ultimatestacker.entity.EntityStack;
import com.songoda.ultimatestacker.entity.EntityStackManager;
import com.songoda.ultimatestacker.hologram.Hologram;
import com.songoda.ultimatestacker.hologram.HologramHolographicDisplays;
import com.songoda.ultimatestacker.hook.StackerHook;
import com.songoda.ultimatestacker.hook.hooks.JobsHook;
import com.songoda.ultimatestacker.listeners.*;
import com.songoda.ultimatestacker.spawner.SpawnerStack;
import com.songoda.ultimatestacker.spawner.SpawnerStackManager;
@ -28,9 +30,12 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class UltimateStacker extends JavaPlugin {
@ -50,6 +55,8 @@ public class UltimateStacker extends JavaPlugin {
private StackingTask stackingTask;
private Hologram hologram;
private List<StackerHook> stackerHooks = new ArrayList<>();
private ServerVersion serverVersion = ServerVersion.fromPackageName(Bukkit.getServer().getClass().getPackage().getName());
private Storage storage;
@ -183,6 +190,11 @@ public class UltimateStacker extends JavaPlugin {
hologram = new HologramHolographicDisplays(this);
}
// Register Hooks
if (pluginManager.isPluginEnabled("Jobs")) {
stackerHooks.add(new JobsHook());
}
Bukkit.getScheduler().runTaskTimerAsynchronously(this, this::saveToFile, 6000, 6000);
// Starting Metrics
@ -191,6 +203,12 @@ public class UltimateStacker extends JavaPlugin {
console.sendMessage(Methods.formatText("&a============================="));
}
public void addExp(Player player, EntityStack stack) {
for (StackerHook stackerHook : stackerHooks) {
stackerHook.applyExperience(player, stack);
}
}
private void checkStorage() {
if (getConfig().getBoolean("Database.Activate Mysql Support")) {
this.storage = new StorageMysql(this);
@ -217,10 +235,6 @@ public class UltimateStacker extends JavaPlugin {
this.settingsManager.reloadConfig();
}
private void convert() {
WildS
}
public boolean spawnersEnabled() {
return !this.getServer().getPluginManager().isPluginEnabled("EpicSpawners") && Setting.SPAWNERS_ENABLED.getBoolean();
}

View File

@ -28,6 +28,7 @@ public class CommandManager implements CommandExecutor {
addCommand(new CommandRemoveAll(commandUltimateStacker));
addCommand(new CommandReload(commandUltimateStacker));
addCommand(new CommandGive(commandUltimateStacker));
addCommand(new CommandConvert(commandUltimateStacker));
}
private AbstractCommand addCommand(AbstractCommand abstractCommand) {

View File

@ -0,0 +1,43 @@
package com.songoda.ultimatestacker.command.commands;
import com.songoda.ultimatestacker.UltimateStacker;
import com.songoda.ultimatestacker.command.AbstractCommand;
import com.songoda.ultimatestacker.gui.GUIConvert;
import com.songoda.ultimatestacker.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandConvert extends AbstractCommand {
public CommandConvert(AbstractCommand parent) {
super("convert", parent, true);
}
@Override
protected ReturnType runCommand(UltimateStacker instance, CommandSender sender, String... args) {
if (Bukkit.getPluginManager().isPluginEnabled("WildStacker")
|| Bukkit.getPluginManager().isPluginEnabled("StackMob")) {
new GUIConvert(instance, (Player) sender);
} else {
sender.sendMessage(Methods.formatText("&cYou need to have the plugin &4WildStacker &cor &4StackMob &cenabled " +
"in order to convert data."));
}
return ReturnType.SUCCESS;
}
@Override
public String getPermissionNode() {
return "ultimatestacker.admin";
}
@Override
public String getSyntax() {
return "/us convert";
}
@Override
public String getDescription() {
return "Allows you to convert data from other stacking plugins.";
}
}

View File

@ -24,7 +24,7 @@ public class CommandSettings extends AbstractCommand {
@Override
public String getSyntax() {
return "/us Settings";
return "/us settings";
}
@Override

View File

@ -0,0 +1,16 @@
package com.songoda.ultimatestacker.convert;
public interface Convert {
String getName();
boolean canEntities();
boolean canSpawners();
void convertEntities();
void convertSpawners();
void disablePlugin();
}

View File

@ -0,0 +1,58 @@
package com.songoda.ultimatestacker.convert;
import com.songoda.ultimatestacker.UltimateStacker;
import com.songoda.ultimatestacker.entity.EntityStackManager;
import org.bukkit.Bukkit;
import uk.antiperson.stackmob.StackMob;
import java.util.Map;
import java.util.UUID;
public class StackMobConvert implements Convert {
private final UltimateStacker plugin;
private final StackMob stackMob;
public StackMobConvert(UltimateStacker plugin) {
this.plugin = plugin;
stackMob = (StackMob) Bukkit.getPluginManager().getPlugin("StackMob");
}
@Override
public String getName() {
return "StackMob";
}
@Override
public boolean canEntities() {
return true;
}
@Override
public boolean canSpawners() {
return false;
}
@Override
public void convertEntities() {
EntityStackManager entityStackManager = plugin.getEntityStackManager();
for (Map.Entry<UUID, Integer> entry : stackMob.getStorageManager().getAmountCache().entrySet()) {
if (!entityStackManager.isStacked(entry.getKey())) {
entityStackManager.addStack(entry.getKey(), entry.getValue());
continue;
}
entityStackManager.getStack(entry.getKey()).setAmount(entry.getValue());
}
}
@Override
public void convertSpawners() {
}
@Override
public void disablePlugin() {
Bukkit.getPluginManager().disablePlugin(stackMob);
}
}

View File

@ -0,0 +1,62 @@
package com.songoda.ultimatestacker.convert;
import com.bgsoftware.wildstacker.WildStackerPlugin;
import com.bgsoftware.wildstacker.api.WildStackerAPI;
import com.bgsoftware.wildstacker.api.objects.StackedEntity;
import com.bgsoftware.wildstacker.api.objects.StackedSpawner;
import com.songoda.ultimatestacker.UltimateStacker;
import com.songoda.ultimatestacker.entity.EntityStackManager;
import com.songoda.ultimatestacker.spawner.SpawnerStack;
import org.bukkit.Bukkit;
public class WildStackerConvert implements Convert {
private final UltimateStacker plugin;
public WildStackerConvert(UltimateStacker plugin) {
this.plugin = plugin;
}
@Override
public String getName() {
return "WildStacker";
}
@Override
public boolean canEntities() {
return true;
}
@Override
public boolean canSpawners() {
return true;
}
@Override
public void convertEntities() {
EntityStackManager entityStackManager = plugin.getEntityStackManager();
for (StackedEntity entity : WildStackerAPI.getWildStacker().getSystemManager().getStackedEntities()) {
if (!entityStackManager.isStacked(entity.getLivingEntity())) {
entityStackManager.addStack(entity.getLivingEntity(), entity.getStackAmount());
continue;
}
entityStackManager.getStack(entity.getLivingEntity()).setAmount(entity.getStackAmount());
}
}
@Override
public void convertSpawners() {
for (StackedSpawner spawner : WildStackerAPI.getWildStacker().getSystemManager().getStackedSpawners()) {
SpawnerStack stack = plugin.getSpawnerStackManager().getSpawner(spawner.getLocation());
stack.setAmount(spawner.getStackAmount());
if (plugin.getHologram() != null)
plugin.getHologram().add(stack);
}
}
@Override
public void disablePlugin() {
Bukkit.getPluginManager().disablePlugin(WildStackerPlugin.getPlugin());
}
}

View File

@ -5,9 +5,17 @@ import com.songoda.ultimatestacker.utils.Methods;
import com.songoda.ultimatestacker.utils.ServerVersion;
import com.songoda.ultimatestacker.utils.settings.Setting;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.inventory.ItemStack;
import java.util.List;
import java.util.UUID;
public class EntityStack {
@ -88,6 +96,72 @@ public class EntityStack {
return null;
}
private void handleWholeStackDeath(LivingEntity killed, List<ItemStack> items, int droppedExp) {
Location killedLocation = killed.getLocation();
for (int i = 1; i < getAmount(); i++) {
if (i == 1) {
items.removeIf(it -> it.isSimilar(killed.getEquipment().getItemInHand()));
for (ItemStack item : killed.getEquipment().getArmorContents()) {
items.removeIf(it -> it.isSimilar(item));
}
}
for (ItemStack item : items) {
killedLocation.getWorld().dropItemNaturally(killedLocation, item);
}
killedLocation.getWorld().spawn(killedLocation, ExperienceOrb.class).setExperience(droppedExp);
}
UltimateStacker.getInstance().addExp(killed.getKiller(), this);
}
private void handleSingleStackDeath(LivingEntity killed) {
UltimateStacker instance = UltimateStacker.getInstance();
EntityStackManager stackManager = instance.getEntityStackManager();
LivingEntity newEntity = Methods.newEntity(killed);
newEntity.getEquipment().clear();
if (killed.getType() == EntityType.PIG_ZOMBIE)
newEntity.getEquipment().setItemInHand(new ItemStack(instance.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.GOLDEN_SWORD : Material.valueOf("GOLD_SWORD")));
if (Bukkit.getPluginManager().isPluginEnabled("EpicSpawners"))
if (killed.hasMetadata("ES"))
newEntity.setMetadata("ES", killed.getMetadata("ES").get(0));
EntityStack entityStack = stackManager.updateStack(killed, newEntity);
entityStack.addAmount(-1);
if (entityStack.getAmount() <= 1) {
stackManager.removeStack(newEntity);
newEntity.setCustomNameVisible(false);
newEntity.setCustomName(null);
}
}
public void onDeath(LivingEntity killed, List<ItemStack> items, int droppedExp) {
killed.setCustomName(null);
killed.setCustomNameVisible(true);
killed.setCustomName(Methods.formatText("&7"));
if (Setting.KILL_WHOLE_STACK_ON_DEATH.getBoolean() && getAmount() != 1) {
handleWholeStackDeath(killed, items, droppedExp);
} else if (getAmount() != 1) {
List<String> reasons = Setting.INSTANT_KILL.getStringList();
EntityDamageEvent lastDamageCause = killed.getLastDamageCause();
if (lastDamageCause != null) {
EntityDamageEvent.DamageCause cause = lastDamageCause.getCause();
for (String s : reasons) {
if (!cause.name().equalsIgnoreCase(s)) continue;
handleWholeStackDeath(killed, items, droppedExp);
return;
}
}
handleSingleStackDeath(killed);
}
}
@Override
public String toString() {
return "EntityStack:{"

View File

@ -18,15 +18,27 @@ public class EntityStackManager {
}
public EntityStack addStack(Entity entity, int amount) {
return stacks.put(entity.getUniqueId(), new EntityStack(entity, amount));
return addStack(entity.getUniqueId(), amount);
}
public EntityStack addStack(UUID uuid, int amount) {
return stacks.put(uuid, new EntityStack(uuid, amount));
}
public EntityStack getStack(Entity entity) {
return stacks.get(entity.getUniqueId());
return getStack(entity.getUniqueId());
}
public EntityStack getStack(UUID uuid) {
return stacks.get(uuid);
}
public boolean isStacked(Entity entity) {
return stacks.containsKey(entity.getUniqueId());
return isStacked(entity.getUniqueId());
}
public boolean isStacked(UUID uuid) {
return stacks.containsKey(uuid);
}
public EntityStack removeStack(UUID entity) {

View File

@ -0,0 +1,50 @@
package com.songoda.ultimatestacker.gui;
import com.songoda.ultimatestacker.UltimateStacker;
import com.songoda.ultimatestacker.convert.StackMobConvert;
import com.songoda.ultimatestacker.convert.WildStackerConvert;
import com.songoda.ultimatestacker.utils.gui.AbstractGUI;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
public class GUIConvert extends AbstractGUI {
private final UltimateStacker plugin;
public GUIConvert(UltimateStacker plugin, Player player) {
super(player);
this.plugin = plugin;
init("Convert", 9);
}
@Override
public void constructGUI() {
int current = 0;
if (Bukkit.getPluginManager().isPluginEnabled("WildStacker")) {
createButton(current, Material.STONE, "&6WildStacker");
registerClickable(current, ((player1, inventory1, cursor, slot, type) ->
new GUIConvertWhat(plugin, player, new WildStackerConvert(plugin))));
current ++;
}
if (Bukkit.getPluginManager().isPluginEnabled("StackMob")) {
createButton(current, Material.STONE, "&6StackMob");
registerClickable(current, ((player1, inventory1, cursor, slot, type) ->
new GUIConvertWhat(plugin, player, new StackMobConvert(plugin))));
}
}
@Override
protected void registerClickables() {
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -0,0 +1,75 @@
package com.songoda.ultimatestacker.gui;
import com.songoda.ultimatestacker.UltimateStacker;
import com.songoda.ultimatestacker.convert.Convert;
import com.songoda.ultimatestacker.utils.Methods;
import com.songoda.ultimatestacker.utils.gui.AbstractGUI;
import org.bukkit.Material;
import org.bukkit.entity.Player;
public class GUIConvertWhat extends AbstractGUI {
private final UltimateStacker plugin;
private Convert convertFrom = null;
private boolean entities = true;
private boolean spawners = true;
public GUIConvertWhat(UltimateStacker plugin, Player player, Convert convertFrom) {
super(player);
this.plugin = plugin;
this.convertFrom = convertFrom;
init("What Do You Want To Convert?", 9);
}
@Override
public void constructGUI() {
inventory.clear();
if (convertFrom.canEntities())
createButton(0, Material.STONE, "&7Stacked Entities", entities ? "&aYes" : "&cNo");
if (convertFrom.canSpawners())
createButton(1, Material.STONE, "&7Stacked Spawners", spawners ? "&aYes" : "&cNo");
createButton(8, Material.STONE, "&aRun");
}
@Override
protected void registerClickables() {
if (convertFrom.canSpawners()) {
registerClickable(0, ((player1, inventory1, cursor, slot, type) -> {
entities = !entities;
constructGUI();
}));
}
if (convertFrom.canSpawners()) {
registerClickable(1, ((player1, inventory1, cursor, slot, type) -> {
spawners = !spawners;
constructGUI();
}));
}
registerClickable(8, ((player1, inventory1, cursor, slot, type) -> {
if (entities)
convertFrom.convertEntities();
if (spawners)
convertFrom.convertSpawners();
convertFrom.disablePlugin();
player.closeInventory();
player.sendMessage(Methods.formatText("&7Data converted successfully. Remove &6" + convertFrom.getName() + " &7and restart your server to continue."));
}));
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -0,0 +1,16 @@
package com.songoda.ultimatestacker.hook;
import com.songoda.ultimatestacker.entity.EntityStack;
import org.bukkit.entity.Player;
public interface StackerHook {
/**
* Applies experience to a player for a killed stack.
*
* @param player The player
* @param entityStack The stack that was killed
*/
void applyExperience(Player player, EntityStack entityStack);
}

View File

@ -0,0 +1,30 @@
package com.songoda.ultimatestacker.hook.hooks;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.actions.EntityActionInfo;
import com.gamingmesh.jobs.container.ActionType;
import com.gamingmesh.jobs.container.JobsPlayer;
import com.songoda.ultimatestacker.entity.EntityStack;
import com.songoda.ultimatestacker.hook.StackerHook;
import org.bukkit.GameMode;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public class JobsHook implements StackerHook {
@Override
public void applyExperience(Player player, EntityStack entityStack) {
if (player.getGameMode().equals(GameMode.CREATIVE))
return;
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
if (jPlayer == null)
return;
for (int i = 1; i < entityStack.getAmount(); i++) {
Entity entity = entityStack.getEntity();
EntityActionInfo eInfo = new EntityActionInfo(entity, ActionType.KILL);
Jobs.action(jPlayer, eInfo, entity);
}
}
}

View File

@ -18,6 +18,8 @@ public class DeathListeners implements Listener {
@EventHandler
public void onEntityDeath(EntityDeathEvent event) {
Methods.onDeath(event.getEntity(), new ArrayList<>(event.getDrops()), event.getDroppedExp());
if (instance.getEntityStackManager().isStacked(event.getEntity()))
instance.getEntityStackManager().getStack(event.getEntity())
.onDeath(event.getEntity(), new ArrayList<>(event.getDrops()), event.getDroppedExp());
}
}

View File

@ -1,19 +1,13 @@
package com.songoda.ultimatestacker.utils;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.actions.EntityActionInfo;
import com.gamingmesh.jobs.container.ActionType;
import com.gamingmesh.jobs.container.JobsPlayer;
import com.songoda.ultimatestacker.UltimateStacker;
import com.songoda.ultimatestacker.entity.Check;
import com.songoda.ultimatestacker.entity.EntityStack;
import com.songoda.ultimatestacker.entity.EntityStackManager;
import com.songoda.ultimatestacker.utils.settings.Setting;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.*;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BlockStateMeta;
import org.bukkit.inventory.meta.ItemMeta;
@ -28,94 +22,6 @@ import java.util.stream.Collectors;
public class Methods {
private static void handleWholeStackDeath(LivingEntity killed, EntityStack stack, List<ItemStack> items, int droppedExp) {
Location killedLocation = killed.getLocation();
for (int i = 1; i < stack.getAmount(); i++) {
if (i == 1) {
items.removeIf(it -> it.isSimilar(killed.getEquipment().getItemInHand()));
for (ItemStack item : killed.getEquipment().getArmorContents()) {
items.removeIf(it -> it.isSimilar(item));
}
}
for (ItemStack item : items) {
killedLocation.getWorld().dropItemNaturally(killedLocation, item);
}
killedLocation.getWorld().spawn(killedLocation, ExperienceOrb.class).setExperience(droppedExp);
}
if (Bukkit.getPluginManager().isPluginEnabled("Jobs"))
runJobs(killed, stack.getAmount());
}
private static void handleSingleStackDeath(LivingEntity killed) {
UltimateStacker instance = UltimateStacker.getInstance();
EntityStackManager stackManager = instance.getEntityStackManager();
LivingEntity newEntity = newEntity(killed);
newEntity.getEquipment().clear();
if (killed.getType() == EntityType.PIG_ZOMBIE)
newEntity.getEquipment().setItemInHand(new ItemStack(instance.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.GOLDEN_SWORD : Material.valueOf("GOLD_SWORD")));
if (Bukkit.getPluginManager().isPluginEnabled("EpicSpawners"))
if (killed.hasMetadata("ES"))
newEntity.setMetadata("ES", killed.getMetadata("ES").get(0));
EntityStack entityStack = stackManager.updateStack(killed, newEntity);
entityStack.addAmount(-1);
if (entityStack.getAmount() <= 1) {
stackManager.removeStack(newEntity);
newEntity.setCustomNameVisible(false);
newEntity.setCustomName(null);
}
}
private static void runJobs(LivingEntity killed, int amount) {
if (killed.getKiller() == null) return;
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(killed.getKiller());
if (jPlayer == null)
return;
EntityActionInfo eInfo = new EntityActionInfo(killed, ActionType.KILL);
for (int i = 1; i < amount; i++)
Jobs.action(jPlayer, eInfo, killed);
}
public static void onDeath(LivingEntity killed, List<ItemStack> items, int droppedExp) {
UltimateStacker instance = UltimateStacker.getInstance();
EntityStackManager stackManager = instance.getEntityStackManager();
if (!stackManager.isStacked(killed)) return;
killed.setCustomName(null);
killed.setCustomNameVisible(true);
killed.setCustomName(formatText("&7"));
EntityStack stack = stackManager.getStack(killed);
if (Setting.KILL_WHOLE_STACK_ON_DEATH.getBoolean() && stack.getAmount() != 1) {
handleWholeStackDeath(killed, stack, items, droppedExp);
} else if(stack.getAmount() != 1) {
List<String> reasons = Setting.INSTANT_KILL.getStringList();
EntityDamageEvent lastDamageCause = killed.getLastDamageCause();
if(lastDamageCause != null) {
EntityDamageEvent.DamageCause cause = lastDamageCause.getCause();
for(String s : reasons) {
if(!cause.name().equalsIgnoreCase(s)) continue;
handleWholeStackDeath(killed, stack, items, droppedExp);
return;
}
}
handleSingleStackDeath(killed);
}
}
public static LivingEntity newEntity(LivingEntity toClone) {
LivingEntity newEntity = (LivingEntity) toClone.getWorld().spawnEntity(toClone.getLocation(), toClone.getType());
newEntity.setVelocity(toClone.getVelocity());
@ -601,6 +507,17 @@ public class Methods {
return glass;
}
public static String formatTitle(String text) {
if (text == null || text.equals(""))
return "";
if (!UltimateStacker.getInstance().isServerVersionAtLeast(ServerVersion.V1_9)) {
if (text.length() > 31)
text = text.substring(0, 29) + "...";
}
text = formatText(text);
return text;
}
/**
* Serializes the location of the block specified.
*

View File

@ -0,0 +1,289 @@
package com.songoda.ultimatestacker.utils.gui;
import com.songoda.ultimatestacker.UltimateStacker;
import com.songoda.ultimatestacker.utils.version.NMSUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class AbstractAnvilGUI {
private static Class<?> BlockPositionClass;
private static Class<?> PacketPlayOutOpenWindowClass;
private static Class<?> IChatBaseComponentClass;
private static Class<?> ICraftingClass;
private static Class<?> ContainerAnvilClass;
private static Class<?> ChatMessageClass;
private static Class<?> EntityHumanClass;
private static Class<?> ContainerClass;
private static Class<?> ContainerAccessClass;
private static Class<?> WorldClass;
private static Class<?> PlayerInventoryClass;
private static Class<?> ContainersClass;
private static Class<?> CraftPlayerClass;
private Player player;
private Map<AnvilSlot, ItemStack> items = new HashMap<>();
private OnClose onClose = null;
private Inventory inv;
private Listener listener;
static {
BlockPositionClass = NMSUtil.getNMSClass("BlockPosition");
PacketPlayOutOpenWindowClass = NMSUtil.getNMSClass("PacketPlayOutOpenWindow");
IChatBaseComponentClass = NMSUtil.getNMSClass("IChatBaseComponent");
ICraftingClass = NMSUtil.getNMSClass("ICrafting");
ContainerAnvilClass = NMSUtil.getNMSClass("ContainerAnvil");
EntityHumanClass = NMSUtil.getNMSClass("EntityHuman");
ChatMessageClass = NMSUtil.getNMSClass("ChatMessage");
ContainerClass = NMSUtil.getNMSClass("Container");
WorldClass = NMSUtil.getNMSClass("World");
PlayerInventoryClass = NMSUtil.getNMSClass("PlayerInventory");
CraftPlayerClass = NMSUtil.getCraftClass("entity.CraftPlayer");
if (NMSUtil.getVersionNumber() > 13) {
ContainerAccessClass = NMSUtil.getNMSClass("ContainerAccess");
ContainersClass = NMSUtil.getNMSClass("Containers");
}
}
public AbstractAnvilGUI(Player player, AnvilClickEventHandler handler) {
UltimateStacker instance = UltimateStacker.getInstance();
this.player = player;
this.listener = new Listener() {
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent event) {
if (event.getWhoClicked() instanceof Player && event.getInventory().equals(AbstractAnvilGUI.this.inv)) {
event.setCancelled(true);
ItemStack item = event.getCurrentItem();
int slot = event.getRawSlot();
if (item == null || item.getType().equals(Material.AIR) || slot != 2)
return;
String name = "";
ItemMeta meta = item.getItemMeta();
if (meta != null && meta.hasDisplayName())
name = meta.getDisplayName();
AnvilClickEvent clickEvent = new AnvilClickEvent(AnvilSlot.bySlot(slot), name);
handler.onAnvilClick(clickEvent);
if (clickEvent.getWillClose())
event.getWhoClicked().closeInventory();
if (clickEvent.getWillDestroy())
AbstractAnvilGUI.this.destroy();
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClose(InventoryCloseEvent event) {
if (event.getPlayer() instanceof Player && AbstractAnvilGUI.this.inv.equals(event.getInventory())) {
Inventory inv = event.getInventory();
player.setLevel(player.getLevel() - 1);
inv.clear();
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> {
if (AbstractAnvilGUI.this.onClose != null)
AbstractAnvilGUI.this.onClose.onClose(player, inv);
AbstractAnvilGUI.this.destroy();
}, 1L);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerQuit(PlayerQuitEvent event) {
if (event.getPlayer().equals(AbstractAnvilGUI.this.player)) {
player.setLevel(player.getLevel() - 1);
AbstractAnvilGUI.this.destroy();
}
}
};
Bukkit.getPluginManager().registerEvents(this.listener, instance);
}
public Player getPlayer() {
return this.player;
}
public void setSlot(AnvilSlot slot, ItemStack item) {
this.items.put(slot, item);
}
public void open() {
this.player.setLevel(this.player.getLevel() + 1);
try {
Object craftPlayer = CraftPlayerClass.cast(this.player);
Method getHandleMethod = CraftPlayerClass.getMethod("getHandle");
Object entityPlayer = getHandleMethod.invoke(craftPlayer);
Object playerInventory = NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "inventory", false));
Object world = NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "world", false));
Object blockPosition = BlockPositionClass.getConstructor(int.class, int.class, int.class).newInstance(0, 0, 0);
Object container;
if (NMSUtil.getVersionNumber() > 13) {
container = ContainerAnvilClass
.getConstructor(int.class, PlayerInventoryClass, ContainerAccessClass)
.newInstance(7, playerInventory, ContainerAccessClass.getMethod("at", WorldClass, BlockPositionClass).invoke(null, world, blockPosition));
} else {
container = ContainerAnvilClass
.getConstructor(PlayerInventoryClass, WorldClass, BlockPositionClass, EntityHumanClass)
.newInstance(playerInventory, world, blockPosition, entityPlayer);
}
NMSUtil.getField(ContainerClass, "checkReachable", true).set(container, false);
Method getBukkitViewMethod = container.getClass().getMethod("getBukkitView");
Object bukkitView = getBukkitViewMethod.invoke(container);
Method getTopInventoryMethod = bukkitView.getClass().getMethod("getTopInventory");
this.inv = (Inventory) getTopInventoryMethod.invoke(bukkitView);
for (AnvilSlot slot : this.items.keySet()) {
this.inv.setItem(slot.getSlot(), this.items.get(slot));
}
Method nextContainerCounterMethod = entityPlayer.getClass().getMethod("nextContainerCounter");
int c = (int) nextContainerCounterMethod.invoke(entityPlayer);
Constructor<?> chatMessageConstructor = ChatMessageClass.getConstructor(String.class, Object[].class);
Object inventoryTitle = chatMessageConstructor.newInstance("Repairing", new Object[]{});
Object packet;
if (NMSUtil.getVersionNumber() > 13) {
packet = PacketPlayOutOpenWindowClass
.getConstructor(int.class, ContainersClass, IChatBaseComponentClass)
.newInstance(c, ContainersClass.getField("ANVIL").get(null), inventoryTitle);
} else {
packet = PacketPlayOutOpenWindowClass
.getConstructor(int.class, String.class, IChatBaseComponentClass, int.class)
.newInstance(c, "minecraft:anvil", inventoryTitle, 0);
}
NMSUtil.sendPacket(this.player, packet);
Field activeContainerField = NMSUtil.getField(EntityHumanClass, "activeContainer", true);
if (activeContainerField != null) {
activeContainerField.set(entityPlayer, container);
NMSUtil.getField(ContainerClass, "windowId", true).set(activeContainerField.get(entityPlayer), c);
Method addSlotListenerMethod = activeContainerField.get(entityPlayer).getClass().getMethod("addSlotListener", ICraftingClass);
addSlotListenerMethod.invoke(activeContainerField.get(entityPlayer), entityPlayer);
if (NMSUtil.getVersionNumber() > 13) {
ContainerClass.getMethod("setTitle", IChatBaseComponentClass).invoke(container, inventoryTitle);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void destroy() {
this.player = null;
this.items = null;
HandlerList.unregisterAll(this.listener);
this.listener = null;
}
private OnClose getOnClose() {
return this.onClose;
}
public void setOnClose(OnClose onClose) {
this.onClose = onClose;
}
public enum AnvilSlot {
INPUT_LEFT(0),
INPUT_RIGHT(1),
OUTPUT(2);
private int slot;
AnvilSlot(int slot) {
this.slot = slot;
}
public static AnvilSlot bySlot(int slot) {
for (AnvilSlot anvilSlot : values()) {
if (anvilSlot.getSlot() == slot) {
return anvilSlot;
}
}
return null;
}
public int getSlot() {
return this.slot;
}
}
@FunctionalInterface
public interface AnvilClickEventHandler {
void onAnvilClick(AnvilClickEvent event);
}
public class AnvilClickEvent {
private AnvilSlot slot;
private String name;
private boolean close = true;
private boolean destroy = true;
public AnvilClickEvent(AnvilSlot slot, String name) {
this.slot = slot;
this.name = name;
}
public AnvilSlot getSlot() {
return this.slot;
}
public String getName() {
return this.name;
}
public boolean getWillClose() {
return this.close;
}
public void setWillClose(boolean close) {
this.close = close;
}
public boolean getWillDestroy() {
return this.destroy;
}
public void setWillDestroy(boolean destroy) {
this.destroy = destroy;
}
}
}

View File

@ -0,0 +1,226 @@
package com.songoda.ultimatestacker.utils.gui;
import com.songoda.ultimatestacker.UltimateStacker;
import com.songoda.ultimatestacker.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class AbstractGUI implements Listener {
private static boolean listenersInitialized = false;
protected Player player;
protected Inventory inventory = null;
protected String setTitle = null;
protected boolean cancelBottom = false;
private Map<Range, Clickable> clickables = new HashMap<>();
private List<OnClose> onCloses = new ArrayList<>();
private Map<Range, Boolean> draggableRanges = new HashMap<>();
public AbstractGUI(Player player) {
this.player = player;
}
public static void initializeListeners(JavaPlugin plugin) {
if (listenersInitialized) return;
Bukkit.getPluginManager().registerEvents(new Listener() {
@EventHandler
public void onClickGUI(InventoryClickEvent event) {
Inventory inventory = event.getClickedInventory();
if (inventory == null) return;
AbstractGUI gui = getGUIFromInventory(inventory);
Player player = (Player) event.getWhoClicked();
boolean bottom = false;
InventoryType type = event.getClickedInventory().getType();
if (type != InventoryType.CHEST && type != InventoryType.PLAYER) return;
if (gui == null && event.getWhoClicked().getOpenInventory().getTopInventory() != null) {
Inventory top = event.getWhoClicked().getOpenInventory().getTopInventory();
gui = getGUIFromInventory(top);
if (gui != null && gui.cancelBottom) event.setCancelled(true);
bottom = true;
}
if (gui == null) return;
if (!bottom) event.setCancelled(true);
if (!gui.draggableRanges.isEmpty() && !bottom) {
for (Map.Entry<Range, Boolean> entry : gui.draggableRanges.entrySet()) {
Range range = entry.getKey();
if (range.getMax() == range.getMin() && event.getSlot() == range.getMin()
|| event.getSlot() >= range.getMin() && event.getSlot() <= range.getMax()) {
event.setCancelled(!entry.getValue());
if (!entry.getValue()) break;
}
}
}
Map<Range, Clickable> entries = new HashMap<>(gui.clickables);
for (Map.Entry<Range, Clickable> entry : entries.entrySet()) {
Range range = entry.getKey();
if (range.isBottom() && !bottom || !range.isBottom() && bottom || range.getClickType() != null && range.getClickType() != event.getClick())
continue;
if (event.getSlot() >= range.getMin() && event.getSlot() <= range.getMax()) {
entry.getValue().Clickable(player, inventory, event.getCursor(), event.getSlot(), event.getClick());
player.playSound(player.getLocation(), entry.getKey().getOnClickSound(), 1F, 1F);
}
}
}
@EventHandler
public void onCloseGUI(InventoryCloseEvent event) {
Inventory inventory = event.getInventory();
AbstractGUI gui = getGUIFromInventory(inventory);
if (gui == null || gui.inventory == null) return;
for (OnClose onClose : gui.onCloses) {
onClose.onClose((Player) event.getPlayer(), inventory);
}
}
private AbstractGUI getGUIFromInventory(Inventory inventory) {
if (inventory.getHolder() == null) return null;
InventoryHolder holder = inventory.getHolder();
if (!(holder instanceof GUIHolder)) return null;
return ((AbstractGUI.GUIHolder) holder).getGUI();
}
}, plugin);
listenersInitialized = true;
}
public void init(String title, int slots) {
if (inventory == null
|| inventory.getSize() != slots
|| ChatColor.translateAlternateColorCodes('&', title) != player.getOpenInventory().getTitle()) {
this.inventory = Bukkit.getServer().createInventory(new GUIHolder(), slots, Methods.formatTitle(title));
this.setTitle = Methods.formatText(title);
if (this.clickables.size() == 0)
registerClickables();
if (this.onCloses.size() == 0)
registerOnCloses();
}
constructGUI();
initializeListeners(UltimateStacker.getInstance());
player.openInventory(inventory);
}
public abstract void constructGUI();
protected void addDraggable(Range range, boolean option) {
this.draggableRanges.put(range, option);
}
protected void removeDraggable() {
this.draggableRanges.clear();
}
protected abstract void registerClickables();
protected abstract void registerOnCloses();
protected ItemStack createButton(int slot, Inventory inventory, ItemStack item, String name, String... lore) {
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
if (lore != null && lore.length != 0) {
List<String> newLore = new ArrayList<>();
for (String line : lore) newLore.add(ChatColor.translateAlternateColorCodes('&', line));
meta.setLore(newLore);
}
item.setItemMeta(meta);
inventory.setItem(slot, item);
return item;
}
protected ItemStack createButton(int slot, ItemStack item, String name, String... lore) {
return createButton(slot, inventory, item, name, lore);
}
protected ItemStack createButton(int slot, Inventory inventory, Material material, String name, String... lore) {
return createButton(slot, inventory, new ItemStack(material), name, lore);
}
protected ItemStack createButton(int slot, Material material, String name, String... lore) {
return createButton(slot, inventory, new ItemStack(material), name, lore);
}
protected ItemStack createButton(int slot, Material material, String name, ArrayList<String> lore) {
return createButton(slot, material, name, lore.toArray(new String[0]));
}
protected void registerClickable(int min, int max, ClickType clickType, boolean bottom, Clickable clickable) {
clickables.put(new Range(min, max, clickType, bottom), clickable);
}
protected void registerClickable(int min, int max, ClickType clickType, Clickable clickable) {
registerClickable(min, max, clickType, false, clickable);
}
protected void registerClickable(int slot, ClickType clickType, Clickable clickable) {
registerClickable(slot, slot, clickType, false, clickable);
}
protected void registerClickable(int min, int max, Clickable clickable) {
registerClickable(min, max, null, false, clickable);
}
protected void registerClickable(int slot, boolean bottom, Clickable clickable) {
registerClickable(slot, slot, null, bottom, clickable);
}
protected void registerClickable(int slot, Clickable clickable) {
registerClickable(slot, slot, null, false, clickable);
}
protected void resetClickables() {
clickables.clear();
}
protected void registerOnClose(OnClose onClose) {
onCloses.add(onClose);
}
public Inventory getInventory() {
return inventory;
}
public class GUIHolder implements InventoryHolder {
@Override
public Inventory getInventory() {
return inventory;
}
public AbstractGUI getGUI() {
return AbstractGUI.this;
}
}
public String getSetTitle() {
return setTitle;
}
}

View File

@ -0,0 +1,11 @@
package com.songoda.ultimatestacker.utils.gui;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public interface Clickable {
void Clickable(Player player, Inventory inventory, ItemStack cursor, int slot, ClickType type);
}

View File

@ -0,0 +1,10 @@
package com.songoda.ultimatestacker.utils.gui;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public interface OnClose {
void onClose(Player player, Inventory inventory);
}

View File

@ -0,0 +1,51 @@
package com.songoda.ultimatestacker.utils.gui;
import com.songoda.ultimatestacker.UltimateStacker;
import com.songoda.ultimatestacker.utils.ServerVersion;
import org.bukkit.Sound;
import org.bukkit.event.inventory.ClickType;
public class Range {
private int min;
private int max;
private ClickType clickType;
private boolean bottom;
private Sound onClickSound;
public Range(int min, int max, ClickType clickType, boolean bottom) {
this.min = min;
this.max = max;
this.clickType = clickType;
this.bottom = bottom;
if (UltimateStacker.getInstance().isServerVersionAtLeast(ServerVersion.V1_9)) onClickSound = Sound.UI_BUTTON_CLICK;
}
public Range(int min, int max, Sound onClickSound, ClickType clickType, boolean bottom) {
this.min = min;
this.max = max;
this.onClickSound = onClickSound;
this.clickType = clickType;
this.bottom = bottom;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
public ClickType getClickType() {
return clickType;
}
public boolean isBottom() {
return bottom;
}
public Sound getOnClickSound() {
return onClickSound;
}
}

View File

@ -0,0 +1,100 @@
package com.songoda.ultimatestacker.utils.version;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
public class NMSUtil {
public static String getVersion() {
String name = Bukkit.getServer().getClass().getPackage().getName();
return name.substring(name.lastIndexOf('.') + 1) + ".";
}
public static int getVersionNumber() {
String name = getVersion().substring(3);
return Integer.valueOf(name.substring(0, name.length() - 4));
}
public static int getVersionReleaseNumber() {
String NMSVersion = getVersion();
return Integer.valueOf(NMSVersion.substring(NMSVersion.length() - 2).replace(".", ""));
}
public static Class<?> getNMSClass(String className) {
try {
String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = Class.forName(fullName);
return clazz;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Class<?> getCraftClass(String className) {
try {
String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz = Class.forName(fullName);
return clazz;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Field getField(Class<?> clazz, String name, boolean declared) {
try {
Field field;
if (declared) {
field = clazz.getDeclaredField(name);
} else {
field = clazz.getField(name);
}
field.setAccessible(true);
return field;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Object getFieldObject(Object object, Field field) {
try {
return field.get(object);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void setField(Object object, String fieldName, Object fieldValue, boolean declared) {
try {
Field field;
if (declared) {
field = object.getClass().getDeclaredField(fieldName);
} else {
field = object.getClass().getField(fieldName);
}
field.setAccessible(true);
field.set(object, fieldValue);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendPacket(Player player, Object packet) {
try {
Object handle = player.getClass().getMethod("getHandle").invoke(player);
Object playerConnection = handle.getClass().getField("playerConnection").get(handle);
playerConnection.getClass().getMethod("sendPacket", getNMSClass("Packet")).invoke(playerConnection, packet);
} catch (Exception e) {
e.printStackTrace();
}
}
}