From f8d17472f2a8282f10c381ce92faf3791838c01a Mon Sep 17 00:00:00 2001 From: TheBusyBiscuit Date: Tue, 24 Mar 2020 02:00:21 +0100 Subject: [PATCH] [CI skip] Very small improvements to cargo networks --- CHANGELOG.md | 3 +- .../api/events/AndroidMineEvent.java | 19 +- .../api/events/AutoDisenchantEvent.java | 5 + .../api/events/MultiBlockInteractEvent.java | 6 + .../api/events/PlayerLanguageChangeEvent.java | 16 + .../api/events/ResearchUnlockEvent.java | 2 + .../slimefun4/api/network/Network.java | 11 + .../slimefun4/core/MultiBlock.java | 8 +- .../core/commands/SlimefunCommand.java | 6 +- .../core/networks/energy/EnergyNet.java | 42 +- .../setup/SlimefunItemSetup.java | 1 - .../Slimefun/Lists/Categories.java | 12 +- .../Slimefun/Objects/SeasonalCategory.java | 17 +- .../Slimefun/Setup/SlimefunManager.java | 4 - .../Slimefun/SlimefunPlugin.java | 22 +- .../Slimefun/api/GuideHandler.java | 8 + .../Slimefun/api/item_transport/CargoNet.java | 484 ++++-------------- .../item_transport/ChestTerminalNetwork.java | 342 +++++++++++++ .../api/item_transport/ItemRequest.java | 56 +- .../item_transport/ItemStackAndInteger.java | 38 +- 20 files changed, 616 insertions(+), 486 deletions(-) create mode 100644 src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ChestTerminalNetwork.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 4aec08aa1..7e2d31448 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,7 +63,8 @@ * Teleporters are now significantly faster * Item permissions have been moved to a seperate permissions.yml file * Salt now only requires 2 blocks of Sand -* Firework from researcheing no longer damages entities +* Fireworks from researching no longer damages entities +* Very slight performance improvements for Cargo networks #### Fixes * Fixed some languages showing numbers larger than 100% diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/AndroidMineEvent.java b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/AndroidMineEvent.java index 76aa4b7b9..2ab8419eb 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/AndroidMineEvent.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/AndroidMineEvent.java @@ -6,10 +6,11 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import io.github.thebusybiscuit.slimefun4.implementation.items.androids.AndroidInstance; +import io.github.thebusybiscuit.slimefun4.implementation.items.androids.MinerAndroid; /** - * This event is fired before a miner android mines a block. - * If this event is cancelled, the block will not be mined. + * This {@link Event} is fired before a {@link MinerAndroid} mines a {@link Block}. + * If this {@link Event} is cancelled, the {@link Block} will not be mined. * * @author poma123 * @@ -24,9 +25,9 @@ public class AndroidMineEvent extends Event implements Cancellable { /** * @param block - * - mined block + * The mined {@link Block} * @param android - * - the block of the android + * The {@link AndroidInstance} that triggered this {@link Event} */ public AndroidMineEvent(Block block, AndroidInstance android) { this.block = block; @@ -42,19 +43,19 @@ public class AndroidMineEvent extends Event implements Cancellable { } /** - * This method returns the mined block + * This method returns the mined {@link Block} * - * @return the mined block + * @return the mined {@link Block} */ public Block getBlock() { return block; } /** - * This method returns the block of the - * android who wants to mine a block. + * This method returns the {@link AndroidInstance} who + * triggered this {@link Event} * - * @return the block of the android + * @return the involved {@link AndroidInstance} */ public AndroidInstance getAndroid() { return android; diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/AutoDisenchantEvent.java b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/AutoDisenchantEvent.java index 8729add18..015289443 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/AutoDisenchantEvent.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/AutoDisenchantEvent.java @@ -35,6 +35,11 @@ public class AutoDisenchantEvent extends Event implements Cancellable { return handlers; } + /** + * This returns the {@link ItemStack} that is being disenchanted. + * + * @return The {@link ItemStack} that is being disenchanted + */ public ItemStack getItem() { return this.item; } diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/MultiBlockInteractEvent.java b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/MultiBlockInteractEvent.java index 2ab1be367..fc15957aa 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/MultiBlockInteractEvent.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/MultiBlockInteractEvent.java @@ -8,6 +8,12 @@ import org.bukkit.event.HandlerList; import io.github.thebusybiscuit.slimefun4.core.MultiBlock; +/** + * This {@link Event} is called when a {@link Player} interacts with a {@link MultiBlock}. + * + * @author TheBusyBiscuit + * + */ public class MultiBlockInteractEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/PlayerLanguageChangeEvent.java b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/PlayerLanguageChangeEvent.java index 3a25d4f72..08a628508 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/PlayerLanguageChangeEvent.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/PlayerLanguageChangeEvent.java @@ -38,14 +38,30 @@ public class PlayerLanguageChangeEvent extends Event { return handlers; } + /** + * Returns the {@link Player} who triggered this {@link Event}, + * the {@link Player} who switched his {@link Language} to be precise. + * + * @return The {@link Player} who switched his {@link Language} + */ public Player getPlayer() { return player; } + /** + * This returns the {@link Language} that this {@link Player} was using before. + * + * @return The previous {@link Language} of our {@link Player} + */ public Language getPreviousLanguage() { return from; } + /** + * This returns the {@link Language} that this {@link Player} wants to switch to. + * + * @return The new {@link Language} + */ public Language getNewLanguage() { return to; } diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/ResearchUnlockEvent.java b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/ResearchUnlockEvent.java index 29df3b747..2fcbfcc94 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/ResearchUnlockEvent.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/api/events/ResearchUnlockEvent.java @@ -11,6 +11,8 @@ import me.mrCookieSlime.Slimefun.Objects.Research; * This {@link Event} is called whenever a {@link Player} unlocks a {@link Research}. * * @author TheBusyBiscuit + * + * @see Research * */ public class ResearchUnlockEvent extends Event implements Cancellable { diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/api/network/Network.java b/src/main/java/io/github/thebusybiscuit/slimefun4/api/network/Network.java index c0261bc74..13546e56e 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/api/network/Network.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/api/network/Network.java @@ -46,6 +46,17 @@ public abstract class Network { */ public abstract NetworkComponent classifyLocation(Location l); + /** + * This method is called whenever a {@link Location} in this {@link Network} changes + * its classification. + * + * @param l + * The {@link Location} that is changing its classification + * @param from + * The {@link NetworkComponent} this {@link Location} was previously classified as + * @param to + * The {@link NetworkComponent} this {@link Location} is changing to + */ public abstract void onClassificationChange(Location l, NetworkComponent from, NetworkComponent to); protected Location regulator; diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/core/MultiBlock.java b/src/main/java/io/github/thebusybiscuit/slimefun4/core/MultiBlock.java index f257bb02b..b4aaa790b 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/core/MultiBlock.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/core/MultiBlock.java @@ -105,8 +105,14 @@ public class MultiBlock { return true; } + /** + * This returns whether this {@link MultiBlock} is a symmetric structure or whether + * the left and right side differ. + * + * @return Whether this {@link MultiBlock} is a symmetric structure + */ public boolean isSymmetric() { - return this.isSymmetric; + return isSymmetric; } @Override diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/core/commands/SlimefunCommand.java b/src/main/java/io/github/thebusybiscuit/slimefun4/core/commands/SlimefunCommand.java index 0f57ead7d..3edb69b1d 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/core/commands/SlimefunCommand.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/core/commands/SlimefunCommand.java @@ -30,12 +30,14 @@ public class SlimefunCommand implements CommandExecutor, Listener { private final Map commandUsage = new HashMap<>(); public SlimefunCommand(SlimefunPlugin plugin) { + this.plugin = plugin; + } + + public void register() { plugin.getServer().getPluginManager().registerEvents(this, plugin); plugin.getCommand("slimefun").setExecutor(this); plugin.getCommand("slimefun").setTabCompleter(new SlimefunTabCompleter(this)); - - this.plugin = plugin; Commands.addCommands(this, commands); } diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/core/networks/energy/EnergyNet.java b/src/main/java/io/github/thebusybiscuit/slimefun4/core/networks/energy/EnergyNet.java index 3b327eccb..33ae0c35d 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/core/networks/energy/EnergyNet.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/core/networks/energy/EnergyNet.java @@ -40,9 +40,18 @@ public class EnergyNet extends Network { } public static EnergyNetComponentType getComponent(String id) { - if (SlimefunPlugin.getRegistry().getEnergyGenerators().contains(id)) return EnergyNetComponentType.GENERATOR; - if (SlimefunPlugin.getRegistry().getEnergyCapacitors().contains(id)) return EnergyNetComponentType.CAPACITOR; - if (SlimefunPlugin.getRegistry().getEnergyConsumers().contains(id)) return EnergyNetComponentType.CONSUMER; + if (SlimefunPlugin.getRegistry().getEnergyGenerators().contains(id)) { + return EnergyNetComponentType.GENERATOR; + } + + if (SlimefunPlugin.getRegistry().getEnergyCapacitors().contains(id)) { + return EnergyNetComponentType.CAPACITOR; + } + + if (SlimefunPlugin.getRegistry().getEnergyConsumers().contains(id)) { + return EnergyNetComponentType.CONSUMER; + } + return EnergyNetComponentType.NONE; } @@ -83,9 +92,9 @@ public class EnergyNet extends Network { return energyNetwork; } - private Set input = new HashSet<>(); - private Set storage = new HashSet<>(); - private Set output = new HashSet<>(); + private final Set generators = new HashSet<>(); + private final Set storage = new HashSet<>(); + private final Set consumers = new HashSet<>(); protected EnergyNet(Location l) { super(l); @@ -98,7 +107,10 @@ public class EnergyNet extends Network { @Override public NetworkComponent classifyLocation(Location l) { - if (regulator.equals(l)) return NetworkComponent.REGULATOR; + if (regulator.equals(l)) { + return NetworkComponent.REGULATOR; + } + switch (getComponent(l)) { case CAPACITOR: return NetworkComponent.CONNECTOR; @@ -113,8 +125,8 @@ public class EnergyNet extends Network { @Override public void onClassificationChange(Location l, NetworkComponent from, NetworkComponent to) { if (from == NetworkComponent.TERMINUS) { - input.remove(l); - output.remove(l); + generators.remove(l); + consumers.remove(l); } switch (getComponent(l)) { @@ -122,10 +134,10 @@ public class EnergyNet extends Network { storage.add(l); break; case CONSUMER: - output.add(l); + consumers.add(l); break; case GENERATOR: - input.add(l); + generators.add(l); break; default: break; @@ -149,7 +161,7 @@ public class EnergyNet extends Network { int available = (int) supply; - for (Location destination : output) { + for (Location destination : consumers) { int capacity = ChargableBlock.getMaxCharge(destination); int charge = ChargableBlock.getCharge(destination); @@ -186,7 +198,7 @@ public class EnergyNet extends Network { else ChargableBlock.setUnsafeCharge(battery, 0, true); } - for (Location source : input) { + for (Location source : generators) { if (ChargableBlock.isChargable(source)) { if (available > 0) { int capacity = ChargableBlock.getMaxCharge(source); @@ -212,7 +224,7 @@ public class EnergyNet extends Network { double supply = 0; Set exploded = new HashSet<>(); - for (Location source : input) { + for (Location source : generators) { long timestamp = System.currentTimeMillis(); SlimefunItem item = BlockStorage.check(source); Config config = BlockStorage.getLocationInfo(source); @@ -235,7 +247,7 @@ public class EnergyNet extends Network { SlimefunPlugin.getTicker().addBlockTimings(source, System.currentTimeMillis() - timestamp); } - input.removeAll(exploded); + generators.removeAll(exploded); return supply; } diff --git a/src/main/java/io/github/thebusybiscuit/slimefun4/implementation/setup/SlimefunItemSetup.java b/src/main/java/io/github/thebusybiscuit/slimefun4/implementation/setup/SlimefunItemSetup.java index 94717d73d..0ca4f551e 100644 --- a/src/main/java/io/github/thebusybiscuit/slimefun4/implementation/setup/SlimefunItemSetup.java +++ b/src/main/java/io/github/thebusybiscuit/slimefun4/implementation/setup/SlimefunItemSetup.java @@ -165,7 +165,6 @@ import io.github.thebusybiscuit.slimefun4.implementation.items.weapons.Explosive import io.github.thebusybiscuit.slimefun4.implementation.items.weapons.IcyBow; import io.github.thebusybiscuit.slimefun4.implementation.items.weapons.SeismicAxe; import io.github.thebusybiscuit.slimefun4.implementation.items.weapons.SwordOfBeheading; -import io.github.thebusybiscuit.slimefun4.utils.SlimefunUtils; import me.mrCookieSlime.CSCoreLibPlugin.CSCoreLib; import me.mrCookieSlime.Slimefun.SlimefunPlugin; import me.mrCookieSlime.Slimefun.Lists.Categories; diff --git a/src/main/java/me/mrCookieSlime/Slimefun/Lists/Categories.java b/src/main/java/me/mrCookieSlime/Slimefun/Lists/Categories.java index 09bea6df1..0996ba7f6 100644 --- a/src/main/java/me/mrCookieSlime/Slimefun/Lists/Categories.java +++ b/src/main/java/me/mrCookieSlime/Slimefun/Lists/Categories.java @@ -1,5 +1,7 @@ package me.mrCookieSlime.Slimefun.Lists; +import java.time.Month; + import org.bukkit.Material; import org.bukkit.NamespacedKey; @@ -48,10 +50,10 @@ public final class Categories { public static final LockedCategory TALISMANS_2 = new LockedCategory(new NamespacedKey(SlimefunPlugin.instance, "ender_talismans"), new CustomItem(SlimefunItems.ENDER_TALISMAN, "&7Talismans - &aTier II"), 3, TALISMANS_1); // Seasonal Categories - public static final SeasonalCategory CHRISTMAS = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "christmas"), 12, 1, new CustomItem(Material.NETHER_STAR, ChatUtils.christmas("Christmas") + " &7(December only)")); - public static final SeasonalCategory VALENTINES_DAY = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "valentines_day"), 2, 2, new CustomItem(Material.POPPY, "&dValentine's Day" + " &7(14th February)")); - public static final SeasonalCategory EASTER = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "easter"), 4, 2, new CustomItem(Material.EGG, "&6Easter" + " &7(April)")); - public static final SeasonalCategory BIRTHDAY = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "birthday"), 10, 1, new CustomItem(Material.FIREWORK_ROCKET, "&a&lTheBusyBiscuit's Birthday &7(26th October)")); - public static final SeasonalCategory HALLOWEEN = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "halloween"), 10, 1, new CustomItem(Material.JACK_O_LANTERN, "&6&lHalloween &7(31st October)")); + public static final SeasonalCategory CHRISTMAS = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "christmas"), Month.DECEMBER, 1, new CustomItem(Material.NETHER_STAR, ChatUtils.christmas("Christmas") + " &7(December only)")); + public static final SeasonalCategory VALENTINES_DAY = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "valentines_day"), Month.FEBRUARY, 2, new CustomItem(Material.POPPY, "&dValentine's Day" + " &7(14th February)")); + public static final SeasonalCategory EASTER = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "easter"), Month.APRIL, 2, new CustomItem(Material.EGG, "&6Easter" + " &7(April)")); + public static final SeasonalCategory BIRTHDAY = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "birthday"), Month.OCTOBER, 1, new CustomItem(Material.FIREWORK_ROCKET, "&a&lTheBusyBiscuit's Birthday &7(26th October)")); + public static final SeasonalCategory HALLOWEEN = new SeasonalCategory(new NamespacedKey(SlimefunPlugin.instance, "halloween"), Month.OCTOBER, 1, new CustomItem(Material.JACK_O_LANTERN, "&6&lHalloween &7(31st October)")); } diff --git a/src/main/java/me/mrCookieSlime/Slimefun/Objects/SeasonalCategory.java b/src/main/java/me/mrCookieSlime/Slimefun/Objects/SeasonalCategory.java index 5fbad025f..a103905e9 100644 --- a/src/main/java/me/mrCookieSlime/Slimefun/Objects/SeasonalCategory.java +++ b/src/main/java/me/mrCookieSlime/Slimefun/Objects/SeasonalCategory.java @@ -1,5 +1,6 @@ package me.mrCookieSlime.Slimefun.Objects; +import java.time.Month; import java.util.Calendar; import org.bukkit.NamespacedKey; @@ -18,7 +19,7 @@ import org.bukkit.inventory.ItemStack; */ public class SeasonalCategory extends Category { - private final int month; + private final Month month; /** * The constructor for a SeasonCategory. @@ -32,14 +33,10 @@ public class SeasonalCategory extends Category { * @param item * The display item for this category */ - public SeasonalCategory(NamespacedKey key, int month, int tier, ItemStack item) { + public SeasonalCategory(NamespacedKey key, Month month, int tier, ItemStack item) { super(key, item, tier); - if (month < 1 || month > 12) { - throw new IllegalArgumentException("There is no month no. " + month); - } - - this.month = month - 1; + this.month = month; } /** @@ -47,8 +44,8 @@ public class SeasonalCategory extends Category { * * @return the id of the month this {@link SeasonalCategory} is assigned to (from 1 = January ; to 12 = December) */ - public int getMonth() { - return this.month; + public Month getMonth() { + return month; } /** @@ -59,6 +56,6 @@ public class SeasonalCategory extends Category { */ public boolean isUnlocked() { Calendar calendar = Calendar.getInstance(); - return month == calendar.get(Calendar.MONTH); + return month.ordinal() == calendar.get(Calendar.MONTH); } } diff --git a/src/main/java/me/mrCookieSlime/Slimefun/Setup/SlimefunManager.java b/src/main/java/me/mrCookieSlime/Slimefun/Setup/SlimefunManager.java index c4f46523f..84478ea9b 100644 --- a/src/main/java/me/mrCookieSlime/Slimefun/Setup/SlimefunManager.java +++ b/src/main/java/me/mrCookieSlime/Slimefun/Setup/SlimefunManager.java @@ -3,7 +3,6 @@ package me.mrCookieSlime.Slimefun.Setup; import java.util.ArrayList; import java.util.List; -import org.bukkit.ChatColor; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; @@ -20,9 +19,6 @@ import me.mrCookieSlime.Slimefun.api.SlimefunItemStack; public final class SlimefunManager { - private static final String EMERALDENCHANTS_LORE = ChatColor.YELLOW.toString() + ChatColor.YELLOW.toString() + ChatColor.GRAY.toString(); - private static final String SOULBOUND_LORE = ChatColor.GRAY + "Soulbound"; - private SlimefunManager() {} public static void registerArmorSet(ItemStack baseComponent, ItemStack[] items, String idSyntax, PotionEffect[][] effects, boolean magical, SlimefunAddon addon) { diff --git a/src/main/java/me/mrCookieSlime/Slimefun/SlimefunPlugin.java b/src/main/java/me/mrCookieSlime/Slimefun/SlimefunPlugin.java index b73a85c9a..95c79bbac 100644 --- a/src/main/java/me/mrCookieSlime/Slimefun/SlimefunPlugin.java +++ b/src/main/java/me/mrCookieSlime/Slimefun/SlimefunPlugin.java @@ -96,9 +96,11 @@ import me.mrCookieSlime.Slimefun.api.inventory.UniversalBlockMenu; public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon { public static SlimefunPlugin instance; + private MinecraftVersion minecraftVersion = MinecraftVersion.UNKNOWN; private final SlimefunRegistry registry = new SlimefunRegistry(); - private MinecraftVersion minecraftVersion = MinecraftVersion.UNKNOWN; + private final TickerTask ticker = new TickerTask(); + private final SlimefunCommand command = new SlimefunCommand(this); // Services - Systems that fulfill certain tasks, treat them as a black box private final CustomItemDataService itemDataService = new CustomItemDataService(this, "slimefun_item"); @@ -118,9 +120,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon { private NetworkManager networkManager; private ProtectionManager protections; - private TickerTask ticker; - private SlimefunCommand command; - + // Important config files for Slimefun private Config researches; private Config items; private Config whitelist; @@ -159,16 +159,14 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon { items = new Config(this, "Items.yml"); whitelist = new Config(this, "whitelist.yml"); - // Setup various config files + // Setup various other config files textureService.load(); permissionsService.load(); local = new LocalizationService(this, config.getString("options.language")); - // Setting up Network classes - networkManager = new NetworkManager(config.getInt("options.max-network-size")); - - // Setting up other stuff + // Setting up Networks gpsNetwork = new GPSNetwork(); + networkManager = new NetworkManager(config.getInt("options.max-network-size")); // Setting up bStats metricsService.start(); @@ -306,15 +304,13 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon { }, 0); // Setting up the command /sf and all subcommands - command = new SlimefunCommand(this); + command.register(); // Armor Update Task if (config.getBoolean("options.enable-armor-effects")) { getServer().getScheduler().runTaskTimerAsynchronously(this, new ArmorTask(), 0L, config.getInt("options.armor-update-interval") * 20L); } - ticker = new TickerTask(); - autoSavingService.start(this, config.getInt("options.auto-save-delay-in-minutes")); // Starting all ASYNC Tasks @@ -385,7 +381,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon { return true; } - getLogger().log(Level.WARNING, "We could not determine the version of Minecraft you were using ({0})", currentVersion);; + getLogger().log(Level.WARNING, "We could not determine the version of Minecraft you were using ({0})", currentVersion); return false; } diff --git a/src/main/java/me/mrCookieSlime/Slimefun/api/GuideHandler.java b/src/main/java/me/mrCookieSlime/Slimefun/api/GuideHandler.java index 211ee1570..2ba1369ff 100644 --- a/src/main/java/me/mrCookieSlime/Slimefun/api/GuideHandler.java +++ b/src/main/java/me/mrCookieSlime/Slimefun/api/GuideHandler.java @@ -7,6 +7,14 @@ import org.bukkit.entity.Player; import me.mrCookieSlime.CSCoreLibPlugin.PlayerRunnable; import me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.ChestMenu; +/** + * Guide Handlers are used to add "fake" categories to the Guide. + * + * @deprecated Some day in the future we will simply allow to override the "opening" method of a Category instead. + * + * @author TheBusyBiscuit + * + */ @Deprecated public interface GuideHandler { diff --git a/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/CargoNet.java b/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/CargoNet.java index c056b043a..31be39047 100644 --- a/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/CargoNet.java +++ b/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/CargoNet.java @@ -1,64 +1,38 @@ package me.mrCookieSlime.Slimefun.api.item_transport; import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.logging.Level; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; -import org.bukkit.block.data.Directional; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import io.github.thebusybiscuit.cscorelib2.chat.ChatColors; -import io.github.thebusybiscuit.cscorelib2.item.CustomItem; -import io.github.thebusybiscuit.cscorelib2.math.DoubleHandler; -import io.github.thebusybiscuit.slimefun4.api.network.Network; import io.github.thebusybiscuit.slimefun4.api.network.NetworkComponent; -import io.github.thebusybiscuit.slimefun4.utils.ChestMenuUtils; -import io.github.thebusybiscuit.slimefun4.utils.SlimefunUtils; import io.github.thebusybiscuit.slimefun4.utils.holograms.SimpleHologram; import me.mrCookieSlime.CSCoreLibPlugin.Configuration.Config; import me.mrCookieSlime.Slimefun.SlimefunPlugin; import me.mrCookieSlime.Slimefun.api.BlockStorage; import me.mrCookieSlime.Slimefun.api.Slimefun; -import me.mrCookieSlime.Slimefun.api.inventory.BlockMenu; import me.mrCookieSlime.Slimefun.api.inventory.DirtyChestMenu; -import me.mrCookieSlime.Slimefun.api.inventory.UniversalBlockMenu; -public class CargoNet extends Network { +public class CargoNet extends ChestTerminalNetwork { private static final int RANGE = 5; - private static final int[] slots = { 19, 20, 21, 28, 29, 30, 37, 38, 39 }; - // Chest Terminal Stuff - private static final int[] TERMINAL_SLOTS = { 0, 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22, 23, 24, 27, 28, 29, 30, 31, 32, 33, 36, 37, 38, 39, 40, 41, 42 }; - private static final int TERMINAL_OUT_SLOT = 17; - - private final ItemStack terminalPlaceholderItem = new CustomItem(new ItemStack(Material.BARRIER), "&4No Item cached"); - - private Set inputNodes = new HashSet<>(); - private Set outputNodes = new HashSet<>(); - - // Chest Terminal Stuff - private final Set terminals = new HashSet<>(); - private final Set imports = new HashSet<>(); - private final Set exports = new HashSet<>(); + private final Set inputNodes = new HashSet<>(); + private final Set outputNodes = new HashSet<>(); private final Map roundRobin = new HashMap<>(); - private final Set itemRequests = new HashSet<>(); public static CargoNet getNetworkFromLocation(Location l) { return SlimefunPlugin.getNetworkManager().getNetworkFromLocation(l, CargoNet.class); @@ -79,10 +53,12 @@ public class CargoNet extends Network { super(l); } + @Override public int getRange() { return RANGE; } + @Override public NetworkComponent classifyLocation(Location l) { String id = BlockStorage.checkID(l); if (id == null) return null; @@ -104,6 +80,7 @@ public class CargoNet extends Network { } } + @Override public void onClassificationChange(Location l, NetworkComponent from, NetworkComponent to) { if (from == NetworkComponent.TERMINUS) { inputNodes.remove(l); @@ -112,6 +89,7 @@ public class CargoNet extends Network { imports.remove(l); exports.remove(l); } + if (to == NetworkComponent.TERMINUS) { switch (BlockStorage.checkID(l)) { case "CARGO_NODE_INPUT": @@ -149,259 +127,142 @@ public class CargoNet extends Network { } else { SimpleHologram.update(b, "&7Status: &a&lONLINE"); - Map> output = new HashMap<>(); - - List list = new LinkedList<>(); - int lastFrequency = -1; - - for (Location outputNode : outputNodes) { - int frequency = getFrequency(outputNode); - - if (frequency != lastFrequency && lastFrequency != -1) { - output.merge(lastFrequency, list, (prev, next) -> { - prev.addAll(next); - return prev; - }); - - list = new LinkedList<>(); - } - - list.add(outputNode); - lastFrequency = frequency; - } - - if (!list.isEmpty()) { - output.merge(lastFrequency, list, (prev, next) -> { - prev.addAll(next); - return prev; - }); - } + Map> output = mapOutputNodes(); // Chest Terminal Stuff - Set providers = new HashSet<>(); Set destinations = new HashSet<>(); List output16 = output.get(16); if (output16 != null) destinations.addAll(output16); - for (Location inputNode : inputNodes) { - int frequency = getFrequency(inputNode); - - if (frequency == 16) { - providers.add(inputNode); - } - } - - Slimefun.runSync(() -> run(b, providers, destinations, output)); + Slimefun.runSync(() -> run(b, destinations, output)); } } - private void run(Block b, Set providers, Set destinations, Map> output) { + private Map> mapOutputNodes() { + Map> output = new HashMap<>(); + + List list = new LinkedList<>(); + int lastFrequency = -1; + + for (Location outputNode : outputNodes) { + int frequency = getFrequency(outputNode); + + if (frequency != lastFrequency && lastFrequency != -1) { + output.merge(lastFrequency, list, (prev, next) -> { + prev.addAll(next); + return prev; + }); + + list = new LinkedList<>(); + } + + list.add(outputNode); + lastFrequency = frequency; + } + + if (!list.isEmpty()) { + output.merge(lastFrequency, list, (prev, next) -> { + prev.addAll(next); + return prev; + }); + } + + return output; + } + + private void run(Block b, Set destinations, Map> output) { if (BlockStorage.getLocationInfo(b.getLocation(), "visualizer") == null) { display(); } - // Chest Terminal Code - if (SlimefunPlugin.getThirdPartySupportService().isChestTerminalInstalled()) { - for (Location bus : imports) { - BlockMenu menu = BlockStorage.getInventory(bus); + Set inputs = new HashSet<>(); + Set providers = new HashSet<>(); - if (menu.getItemInSlot(17) == null) { - Block target = getAttachedBlock(bus.getBlock()); - ItemStackAndInteger stack = CargoUtils.withdraw(bus.getBlock(), target, -1); + for (Location node : inputNodes) { + int frequency = getFrequency(node); - if (stack != null) { - menu.replaceExistingItem(17, stack.getItem()); - } - } - - if (menu.getItemInSlot(17) != null) { - itemRequests.add(new ItemRequest(bus, 17, menu.getItemInSlot(17), ItemTransportFlow.INSERT)); - } + if (frequency == 16) { + providers.add(node); } - - for (Location bus : exports) { - BlockMenu menu = BlockStorage.getInventory(bus); - - if (menu.getItemInSlot(17) != null) { - Block target = getAttachedBlock(bus.getBlock()); - - menu.replaceExistingItem(17, CargoUtils.insert(bus.getBlock(), target, menu.getItemInSlot(17), -1)); - } - - if (menu.getItemInSlot(17) == null) { - List items = new ArrayList<>(); - for (int slot : slots) { - ItemStack template = menu.getItemInSlot(slot); - if (template != null) items.add(new CustomItem(template, 1)); - } - - if (!items.isEmpty()) { - int index = Integer.parseInt(BlockStorage.getLocationInfo(bus, "index")); - - index++; - if (index > (items.size() - 1)) index = 0; - - BlockStorage.addBlockInfo(bus, "index", String.valueOf(index)); - itemRequests.add(new ItemRequest(bus, 17, items.get(index), ItemTransportFlow.WITHDRAW)); - } - } - } - - for (Location terminal : terminals) { - BlockMenu menu = BlockStorage.getInventory(terminal); - ItemStack sendingItem = menu.getItemInSlot(TERMINAL_OUT_SLOT); - - if (sendingItem != null) { - itemRequests.add(new ItemRequest(terminal, TERMINAL_OUT_SLOT, sendingItem, ItemTransportFlow.INSERT)); - } - } - - Iterator iterator = itemRequests.iterator(); - while (iterator.hasNext()) { - ItemRequest request = iterator.next(); - - if (terminals.contains(request.getTerminal()) || imports.contains(request.getTerminal()) || exports.contains(request.getTerminal())) { - BlockMenu menu = BlockStorage.getInventory(request.getTerminal()); - - switch (request.getDirection()) { - case INSERT: - ItemStack requestedItem = request.getItem(); - - for (Location l : destinations) { - Block target = getAttachedBlock(l.getBlock()); - requestedItem = CargoUtils.insert(l.getBlock(), target, requestedItem, -1); - - if (requestedItem == null) { - menu.replaceExistingItem(request.getSlot(), null); - break; - } - } - - if (requestedItem != null) { - menu.replaceExistingItem(request.getSlot(), requestedItem); - } - - iterator.remove(); - break; - case WITHDRAW: - int slot = request.getSlot(); - ItemStack prevStack = menu.getItemInSlot(slot); - - if (!(prevStack == null || (prevStack.getAmount() + request.getItem().getAmount() <= prevStack.getMaxStackSize() && SlimefunUtils.isItemSimilar(prevStack, new CustomItem(request.getItem(), 1), true)))) { - iterator.remove(); - break; - } - - ItemStack stack = null; - ItemStack requested = request.getItem(); - - for (Location l : providers) { - Block target = getAttachedBlock(l.getBlock()); - ItemStack is = CargoUtils.withdraw(l.getBlock(), target, requested); - - if (is != null) { - if (stack == null) { - stack = is; - } - else { - stack = new CustomItem(stack, stack.getAmount() + is.getAmount()); - } - - if (is.getAmount() == requested.getAmount()) { - break; - } - else { - requested = new CustomItem(requested, requested.getAmount() - is.getAmount()); - } - } - } - - if (stack != null) { - ItemStack prev = menu.getItemInSlot(slot); - - if (prev == null) menu.replaceExistingItem(slot, stack); - else menu.replaceExistingItem(slot, new CustomItem(stack, stack.getAmount() + prev.getAmount())); - } - - iterator.remove(); - break; - default: - break; - } - } + else if (frequency >= 0 && frequency < 16) { + inputs.add(node); } } - // All operations happen here: Everything gets iterated from the Input Nodes. (Apart from ChestTerminal - // Buses) - for (Location input : inputNodes) { - int frequency = getFrequency(input); + // Chest Terminal Code + if (SlimefunPlugin.getThirdPartySupportService().isChestTerminalInstalled()) { + handleItemRequests(providers, destinations); + } - if (frequency < 0 || frequency > 15) { - continue; - } + // All operations happen here: Everything gets iterated from the Input Nodes. + // (Apart from ChestTerminal Buses) + for (Location input : inputs) { + Optional inputTarget = getAttachedBlock(input.getBlock()); - Block inputTarget = getAttachedBlock(input.getBlock()); - ItemStack stack = null; - int previousSlot = -1; + if (inputTarget.isPresent()) { + int previousSlot = -1; - Config cfg = BlockStorage.getLocationInfo(input); - boolean roundrobin = "true".equals(cfg.getString("round-robin")); + Config cfg = BlockStorage.getLocationInfo(input); + boolean roundrobin = "true".equals(cfg.getString("round-robin")); - if (inputTarget != null) { - ItemStackAndInteger slot = CargoUtils.withdraw(input.getBlock(), inputTarget, Integer.parseInt(cfg.getString("index"))); + ItemStackAndInteger slot = CargoUtils.withdraw(input.getBlock(), inputTarget.get(), Integer.parseInt(cfg.getString("index"))); + ItemStack stack = null; if (slot != null) { stack = slot.getItem(); previousSlot = slot.getInt(); } - } - if (stack != null) { - List outputs = output.get(frequency); + if (stack != null) { + List outputs = output.get(getFrequency(input)); - if (outputs != null) { - List outputlist = new ArrayList<>(outputs); + if (outputs != null) { + List outputlist = new ArrayList<>(outputs); - if (roundrobin) { - int cIndex = roundRobin.getOrDefault(input, 0); + if (roundrobin) { + int index = roundRobin.getOrDefault(input, 0); - if (cIndex < outputlist.size()) { - for (int i = 0; i < cIndex; i++) { - Location temp = outputlist.get(0); - outputlist.remove(temp); - outputlist.add(temp); + if (index < outputlist.size()) { + for (int i = 0; i < index; i++) { + Location temp = outputlist.get(0); + outputlist.remove(temp); + outputlist.add(temp); + } + + index++; } - cIndex++; + else { + index = 1; + } + + roundRobin.put(input, index); } - else cIndex = 1; - roundRobin.put(input, cIndex); - } + for (Location out : outputlist) { + Optional target = getAttachedBlock(out.getBlock()); - for (Location out : outputlist) { - Block target = getAttachedBlock(out.getBlock()); - - if (target != null) { - stack = CargoUtils.insert(out.getBlock(), target, stack, -1); - if (stack == null) break; + if (target.isPresent()) { + stack = CargoUtils.insert(out.getBlock(), target.get(), stack, -1); + if (stack == null) break; + } } } - } - } - if (stack != null && previousSlot > -1) { - DirtyChestMenu menu = CargoUtils.getChestMenu(inputTarget); + if (stack != null && previousSlot > -1) { + DirtyChestMenu menu = CargoUtils.getChestMenu(inputTarget.get()); - if (menu != null) { - menu.replaceExistingItem(previousSlot, stack); - } - else { - BlockState state = inputTarget.getState(); - if (state instanceof InventoryHolder) { - Inventory inv = ((InventoryHolder) state).getInventory(); - inv.setItem(previousSlot, stack); + if (menu != null) { + menu.replaceExistingItem(previousSlot, stack); + } + else { + BlockState state = inputTarget.get().getState(); + + if (state instanceof InventoryHolder) { + Inventory inv = ((InventoryHolder) state).getInventory(); + inv.setItem(previousSlot, stack); + } + } } } } @@ -409,151 +270,18 @@ public class CargoNet extends Network { // Chest Terminal Code if (SlimefunPlugin.getThirdPartySupportService().isChestTerminalInstalled()) { - List items = new ArrayList<>(); - - for (Location l : providers) { - Block target = getAttachedBlock(l.getBlock()); - UniversalBlockMenu menu = BlockStorage.getUniversalInventory(target); - - if (menu != null) { - for (int slot : menu.getPreset().getSlotsAccessedByItemTransport((DirtyChestMenu) menu, ItemTransportFlow.WITHDRAW, null)) { - ItemStack is = menu.getItemInSlot(slot); - filter(is, items, l); - } - } - else if (BlockStorage.hasInventory(target)) { - BlockMenu blockMenu = BlockStorage.getInventory(target); - Config cfg = BlockStorage.getLocationInfo(target.getLocation()); - - if (cfg.getString("id").startsWith("BARREL_") && cfg.getString("storedItems") != null) { - int stored = Integer.parseInt(cfg.getString("storedItems")); - - for (int slot : blockMenu.getPreset().getSlotsAccessedByItemTransport((DirtyChestMenu) blockMenu, ItemTransportFlow.WITHDRAW, null)) { - ItemStack is = blockMenu.getItemInSlot(slot); - - if (is != null && CargoUtils.matchesFilter(l.getBlock(), is, -1)) { - boolean add = true; - - for (ItemStackAndInteger item : items) { - if (SlimefunUtils.isItemSimilar(is, item.getItem(), true)) { - add = false; - item.add(is.getAmount() + stored); - } - } - - if (add) { - items.add(new ItemStackAndInteger(new CustomItem(is, 1), is.getAmount() + stored)); - } - } - } - } - else { - handleWithdraw(blockMenu, items, l); - } - } - else { - BlockState state = target.getState(); - - if (state instanceof InventoryHolder) { - Inventory inv = ((InventoryHolder) state).getInventory(); - - for (ItemStack is : inv.getContents()) { - filter(is, items, l); - } - } - } - } - - Collections.sort(items, Comparator.comparingInt(item -> -item.getInt())); - - for (Location l : terminals) { - BlockMenu menu = BlockStorage.getInventory(l); - int page = Integer.parseInt(BlockStorage.getLocationInfo(l, "page")); - - if (!items.isEmpty() && items.size() < (page - 1) * TERMINAL_SLOTS.length + 1) { - page = 1; - BlockStorage.addBlockInfo(l, "page", String.valueOf(1)); - } - - for (int i = 0; i < TERMINAL_SLOTS.length; i++) { - int slot = TERMINAL_SLOTS[i]; - - if (items.size() > i + (TERMINAL_SLOTS.length * (page - 1))) { - ItemStackAndInteger item = items.get(i + (TERMINAL_SLOTS.length * (page - 1))); - - ItemStack stack = item.getItem().clone(); - ItemMeta im = stack.getItemMeta(); - List lore = new ArrayList<>(); - lore.add(""); - lore.add(ChatColors.color("&7Stored Items: &r" + DoubleHandler.getFancyDouble(item.getInt()))); - - if (stack.getMaxStackSize() > 1) lore.add(ChatColors.color("&7 stack.getMaxStackSize() ? stack.getMaxStackSize() : item.getInt()) + ">")); - else lore.add(ChatColors.color("&7")); - - lore.add(""); - if (im.hasLore()) { - lore.addAll(im.getLore()); - } - - im.setLore(lore); - stack.setItemMeta(im); - menu.replaceExistingItem(slot, stack); - menu.addMenuClickHandler(slot, (p, sl, is, action) -> { - int amount = item.getInt() > item.getItem().getMaxStackSize() ? item.getItem().getMaxStackSize() : item.getInt(); - itemRequests.add(new ItemRequest(l, 44, new CustomItem(item.getItem(), action.isRightClicked() ? amount : 1), ItemTransportFlow.WITHDRAW)); - return false; - }); - - } - else { - menu.replaceExistingItem(slot, terminalPlaceholderItem); - menu.addMenuClickHandler(slot, ChestMenuUtils.getEmptyClickHandler()); - } - } - } + updateTerminals(providers); } } - private static Block getAttachedBlock(Block block) { - if (block.getBlockData() instanceof Directional) { - return block.getRelative(((Directional) block.getBlockData()).getFacing().getOppositeFace()); - } - - return null; - } - private static int getFrequency(Location l) { - int freq = 0; try { String str = BlockStorage.getLocationInfo(l).getString("frequency"); - if (str != null) freq = Integer.parseInt(str); + return Integer.parseInt(str); } catch (Exception x) { Slimefun.getLogger().log(Level.SEVERE, "An Error occured while parsing a Cargo Node Frequency", x); - } - return freq; - } - - private void handleWithdraw(DirtyChestMenu menu, List items, Location l) { - for (int slot : menu.getPreset().getSlotsAccessedByItemTransport(menu, ItemTransportFlow.WITHDRAW, null)) { - filter(menu.getItemInSlot(slot), items, l); - } - } - - private void filter(ItemStack is, List items, Location l) { - if (is != null && CargoUtils.matchesFilter(l.getBlock(), is, -1)) { - boolean add = true; - - for (ItemStackAndInteger item : items) { - if (SlimefunUtils.isItemSimilar(is, item.getItem(), true)) { - add = false; - item.add(is.getAmount()); - } - } - - if (add) { - items.add(new ItemStackAndInteger(new CustomItem(is, 1), is.getAmount())); - } + return 0; } } } diff --git a/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ChestTerminalNetwork.java b/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ChestTerminalNetwork.java new file mode 100644 index 000000000..fc088ce9b --- /dev/null +++ b/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ChestTerminalNetwork.java @@ -0,0 +1,342 @@ +package me.mrCookieSlime.Slimefun.api.item_transport; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.block.data.Directional; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import io.github.thebusybiscuit.cscorelib2.chat.ChatColors; +import io.github.thebusybiscuit.cscorelib2.item.CustomItem; +import io.github.thebusybiscuit.cscorelib2.math.DoubleHandler; +import io.github.thebusybiscuit.slimefun4.api.network.Network; +import io.github.thebusybiscuit.slimefun4.utils.ChestMenuUtils; +import io.github.thebusybiscuit.slimefun4.utils.SlimefunUtils; +import me.mrCookieSlime.CSCoreLibPlugin.Configuration.Config; +import me.mrCookieSlime.Slimefun.api.BlockStorage; +import me.mrCookieSlime.Slimefun.api.inventory.BlockMenu; +import me.mrCookieSlime.Slimefun.api.inventory.DirtyChestMenu; +import me.mrCookieSlime.Slimefun.api.inventory.UniversalBlockMenu; + +/** + * An abstract super class of {@link CargoNet} that handles interactions with ChestTerminal. + * + * @author TheBusyBiscuit + * + */ +abstract class ChestTerminalNetwork extends Network { + + private static final int[] slots = { 19, 20, 21, 28, 29, 30, 37, 38, 39 }; + private static final int[] TERMINAL_SLOTS = { 0, 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22, 23, 24, 27, 28, 29, 30, 31, 32, 33, 36, 37, 38, 39, 40, 41, 42 }; + private static final int TERMINAL_OUT_SLOT = 17; + + private final ItemStack terminalPlaceholderItem = new CustomItem(Material.BARRIER, "&4No Item cached"); + + protected final Set terminals = new HashSet<>(); + protected final Set imports = new HashSet<>(); + protected final Set exports = new HashSet<>(); + + private final Set itemRequests = new HashSet<>(); + + protected ChestTerminalNetwork(Location regulator) { + super(regulator); + } + + protected static Optional getAttachedBlock(Block block) { + if (block.getType() == Material.PLAYER_WALL_HEAD) { + BlockFace face = ((Directional) block.getBlockData()).getFacing().getOppositeFace(); + return Optional.of(block.getRelative(face)); + } + + return Optional.empty(); + } + + protected void handleItemRequests(Set providers, Set destinations) { + for (Location bus : imports) { + BlockMenu menu = BlockStorage.getInventory(bus); + + if (menu.getItemInSlot(17) == null) { + Optional target = getAttachedBlock(bus.getBlock()); + + if (target.isPresent()) { + ItemStackAndInteger stack = CargoUtils.withdraw(bus.getBlock(), target.get(), -1); + + if (stack != null) { + menu.replaceExistingItem(17, stack.getItem()); + } + } + } + + if (menu.getItemInSlot(17) != null) { + itemRequests.add(new ItemRequest(bus, 17, menu.getItemInSlot(17), ItemTransportFlow.INSERT)); + } + } + + for (Location bus : exports) { + BlockMenu menu = BlockStorage.getInventory(bus); + + if (menu.getItemInSlot(17) != null) { + Optional target = getAttachedBlock(bus.getBlock()); + + if (target.isPresent()) { + menu.replaceExistingItem(17, CargoUtils.insert(bus.getBlock(), target.get(), menu.getItemInSlot(17), -1)); + } + } + + if (menu.getItemInSlot(17) == null) { + List items = new ArrayList<>(); + for (int slot : slots) { + ItemStack template = menu.getItemInSlot(slot); + if (template != null) items.add(new CustomItem(template, 1)); + } + + if (!items.isEmpty()) { + int index = Integer.parseInt(BlockStorage.getLocationInfo(bus, "index")); + + index++; + if (index > (items.size() - 1)) index = 0; + + BlockStorage.addBlockInfo(bus, "index", String.valueOf(index)); + itemRequests.add(new ItemRequest(bus, 17, items.get(index), ItemTransportFlow.WITHDRAW)); + } + } + } + + for (Location terminal : terminals) { + BlockMenu menu = BlockStorage.getInventory(terminal); + ItemStack sendingItem = menu.getItemInSlot(TERMINAL_OUT_SLOT); + + if (sendingItem != null) { + itemRequests.add(new ItemRequest(terminal, TERMINAL_OUT_SLOT, sendingItem, ItemTransportFlow.INSERT)); + } + } + + Iterator iterator = itemRequests.iterator(); + while (iterator.hasNext()) { + ItemRequest request = iterator.next(); + + if (terminals.contains(request.getTerminal()) || imports.contains(request.getTerminal()) || exports.contains(request.getTerminal())) { + BlockMenu menu = BlockStorage.getInventory(request.getTerminal()); + + switch (request.getDirection()) { + case INSERT: + ItemStack requestedItem = request.getItem(); + + for (Location l : destinations) { + Optional target = getAttachedBlock(l.getBlock()); + + if (target.isPresent()) { + requestedItem = CargoUtils.insert(l.getBlock(), target.get(), requestedItem, -1); + + if (requestedItem == null) { + menu.replaceExistingItem(request.getSlot(), null); + break; + } + } + } + + if (requestedItem != null) { + menu.replaceExistingItem(request.getSlot(), requestedItem); + } + + iterator.remove(); + break; + case WITHDRAW: + int slot = request.getSlot(); + ItemStack prevStack = menu.getItemInSlot(slot); + + if (!(prevStack == null || (prevStack.getAmount() + request.getItem().getAmount() <= prevStack.getMaxStackSize() && SlimefunUtils.isItemSimilar(prevStack, new CustomItem(request.getItem(), 1), true)))) { + iterator.remove(); + break; + } + + ItemStack stack = null; + ItemStack requested = request.getItem(); + + for (Location l : providers) { + Optional target = getAttachedBlock(l.getBlock()); + + if (target.isPresent()) { + ItemStack is = CargoUtils.withdraw(l.getBlock(), target.get(), requested); + + if (is != null) { + if (stack == null) { + stack = is; + } + else { + stack = new CustomItem(stack, stack.getAmount() + is.getAmount()); + } + + if (is.getAmount() == requested.getAmount()) { + break; + } + else { + requested = new CustomItem(requested, requested.getAmount() - is.getAmount()); + } + } + } + } + + if (stack != null) { + ItemStack prev = menu.getItemInSlot(slot); + + if (prev == null) menu.replaceExistingItem(slot, stack); + else menu.replaceExistingItem(slot, new CustomItem(stack, stack.getAmount() + prev.getAmount())); + } + + iterator.remove(); + break; + default: + break; + } + } + } + } + + protected void updateTerminals(Set providers) { + List items = new ArrayList<>(); + + for (Location l : providers) { + Optional block = getAttachedBlock(l.getBlock()); + + if (block.isPresent()) { + Block target = block.get(); + UniversalBlockMenu menu = BlockStorage.getUniversalInventory(target); + + if (menu != null) { + for (int slot : menu.getPreset().getSlotsAccessedByItemTransport((DirtyChestMenu) menu, ItemTransportFlow.WITHDRAW, null)) { + ItemStack is = menu.getItemInSlot(slot); + filter(is, items, l); + } + } + else if (BlockStorage.hasInventory(target)) { + BlockMenu blockMenu = BlockStorage.getInventory(target); + Config cfg = BlockStorage.getLocationInfo(target.getLocation()); + + if (cfg.getString("id").startsWith("BARREL_") && cfg.getString("storedItems") != null) { + int stored = Integer.parseInt(cfg.getString("storedItems")); + + for (int slot : blockMenu.getPreset().getSlotsAccessedByItemTransport((DirtyChestMenu) blockMenu, ItemTransportFlow.WITHDRAW, null)) { + ItemStack is = blockMenu.getItemInSlot(slot); + + if (is != null && CargoUtils.matchesFilter(l.getBlock(), is, -1)) { + boolean add = true; + + for (ItemStackAndInteger item : items) { + if (SlimefunUtils.isItemSimilar(is, item.getItem(), true)) { + add = false; + item.add(is.getAmount() + stored); + } + } + + if (add) { + items.add(new ItemStackAndInteger(new CustomItem(is, 1), is.getAmount() + stored)); + } + } + } + } + else { + handleWithdraw(blockMenu, items, l); + } + } + else { + BlockState state = target.getState(); + + if (state instanceof InventoryHolder) { + Inventory inv = ((InventoryHolder) state).getInventory(); + + for (ItemStack is : inv.getContents()) { + filter(is, items, l); + } + } + } + } + } + + Collections.sort(items, Comparator.comparingInt(item -> -item.getInt())); + + for (Location l : terminals) { + BlockMenu menu = BlockStorage.getInventory(l); + int page = Integer.parseInt(BlockStorage.getLocationInfo(l, "page")); + + if (!items.isEmpty() && items.size() < (page - 1) * TERMINAL_SLOTS.length + 1) { + page = 1; + BlockStorage.addBlockInfo(l, "page", String.valueOf(1)); + } + + for (int i = 0; i < TERMINAL_SLOTS.length; i++) { + int slot = TERMINAL_SLOTS[i]; + + if (items.size() > i + (TERMINAL_SLOTS.length * (page - 1))) { + ItemStackAndInteger item = items.get(i + (TERMINAL_SLOTS.length * (page - 1))); + + ItemStack stack = item.getItem().clone(); + ItemMeta im = stack.getItemMeta(); + List lore = new ArrayList<>(); + lore.add(""); + lore.add(ChatColors.color("&7Stored Items: &r" + DoubleHandler.getFancyDouble(item.getInt()))); + + if (stack.getMaxStackSize() > 1) lore.add(ChatColors.color("&7 stack.getMaxStackSize() ? stack.getMaxStackSize() : item.getInt()) + ">")); + else lore.add(ChatColors.color("&7")); + + lore.add(""); + if (im.hasLore()) { + lore.addAll(im.getLore()); + } + + im.setLore(lore); + stack.setItemMeta(im); + menu.replaceExistingItem(slot, stack); + menu.addMenuClickHandler(slot, (p, sl, is, action) -> { + int amount = item.getInt() > item.getItem().getMaxStackSize() ? item.getItem().getMaxStackSize() : item.getInt(); + itemRequests.add(new ItemRequest(l, 44, new CustomItem(item.getItem(), action.isRightClicked() ? amount : 1), ItemTransportFlow.WITHDRAW)); + return false; + }); + + } + else { + menu.replaceExistingItem(slot, terminalPlaceholderItem); + menu.addMenuClickHandler(slot, ChestMenuUtils.getEmptyClickHandler()); + } + } + } + } + + private void handleWithdraw(DirtyChestMenu menu, List items, Location l) { + for (int slot : menu.getPreset().getSlotsAccessedByItemTransport(menu, ItemTransportFlow.WITHDRAW, null)) { + filter(menu.getItemInSlot(slot), items, l); + } + } + + private void filter(ItemStack is, List items, Location l) { + if (is != null && CargoUtils.matchesFilter(l.getBlock(), is, -1)) { + boolean add = true; + + for (ItemStackAndInteger item : items) { + if (SlimefunUtils.isItemSimilar(is, item.getItem(), true)) { + add = false; + item.add(is.getAmount()); + } + } + + if (add) { + items.add(new ItemStackAndInteger(new CustomItem(is, 1), is.getAmount())); + } + } + } + +} diff --git a/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ItemRequest.java b/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ItemRequest.java index 4af22d91c..b9017bbcf 100644 --- a/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ItemRequest.java +++ b/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ItemRequest.java @@ -4,33 +4,33 @@ import org.bukkit.Location; import org.bukkit.inventory.ItemStack; class ItemRequest { - - private final ItemStack item; - private final ItemTransportFlow flow; - private final Location terminal; - private final int slot; - - public ItemRequest(Location terminal, int slot, ItemStack item, ItemTransportFlow flow) { - this.terminal = terminal; - this.item = item; - this.slot = slot; - this.flow = flow; - } - - public Location getTerminal() { - return this.terminal; - } - - public ItemStack getItem() { - return this.item; - } - - public ItemTransportFlow getDirection() { - return this.flow; - } - - public int getSlot() { - return this.slot; - } + + private final ItemStack item; + private final ItemTransportFlow flow; + private final Location terminal; + private final int slot; + + ItemRequest(Location terminal, int slot, ItemStack item, ItemTransportFlow flow) { + this.terminal = terminal; + this.item = item; + this.slot = slot; + this.flow = flow; + } + + public Location getTerminal() { + return terminal; + } + + public ItemStack getItem() { + return item; + } + + public ItemTransportFlow getDirection() { + return flow; + } + + public int getSlot() { + return slot; + } } diff --git a/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ItemStackAndInteger.java b/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ItemStackAndInteger.java index 75cbde684..d9a3ccf04 100644 --- a/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ItemStackAndInteger.java +++ b/src/main/java/me/mrCookieSlime/Slimefun/api/item_transport/ItemStackAndInteger.java @@ -3,25 +3,25 @@ package me.mrCookieSlime.Slimefun.api.item_transport; import org.bukkit.inventory.ItemStack; class ItemStackAndInteger { - - private final ItemStack item; - private int number; - - public ItemStackAndInteger(ItemStack item, int amount) { - this.number = amount; - this.item = item; - } - - public int getInt() { - return number; - } - - public ItemStack getItem() { - return item; - } - public void add(int amount) { - number += amount; - } + private final ItemStack item; + private int number; + + ItemStackAndInteger(ItemStack item, int amount) { + this.number = amount; + this.item = item; + } + + public int getInt() { + return number; + } + + public ItemStack getItem() { + return item; + } + + public void add(int amount) { + number += amount; + } }