diff --git a/api/build.gradle.kts b/api/build.gradle.kts index 8fdb04e..64a17b0 100644 --- a/api/build.gradle.kts +++ b/api/build.gradle.kts @@ -1,18 +1,10 @@ -version = "0.1.0" - -plugins { - id("java-library") -} +import net.labymod.labygradle.common.extension.LabyModAnnotationProcessorExtension.ReferenceType dependencies { + labyProcessor() labyApi("api") } -labyModProcessor { - referenceType = net.labymod.gradle.core.processor.ReferenceType.INTERFACE -} - -java { - sourceCompatibility = JavaVersion.VERSION_21 - targetCompatibility = JavaVersion.VERSION_21 +labyModAnnotationProcessor { + referenceType = ReferenceType.INTERFACE } \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 98a7e00..3a10f57 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,14 +1,16 @@ plugins { - id("java-library") - id("net.labymod.gradle") - id("net.labymod.gradle.addon") + id("net.labymod.labygradle") + id("net.labymod.labygradle.addon") } +val versions = providers.gradleProperty("net.labymod.minecraft-versions").get().split(";") + group = "ml.volder" version = System.getenv().getOrDefault("VERSION", "1.0.0") labyMod { - defaultPackageName = "ml.volder" //change this to your main package name (used by all modules) + defaultPackageName = "ml.volder" + addonInfo { namespace = "sa-transporter" displayName = "Transporter Addon" @@ -19,78 +21,21 @@ labyMod { } minecraft { - registerVersions( - "1.8.9", - "1.12.2", - "1.16.5", - "1.17.1", - "1.18.2", - "1.19.2", - "1.19.3", - "1.19.4", - "1.20.1", - "1.20.2", - "1.20.4", - "1.20.5", - "1.20.6", - "1.21" - ) { version, provider -> - configureRun(provider, version) - } - - subprojects.forEach { - if (it.name != "game-runner") { - filter(it.name) + registerVersion(versions.toTypedArray()) { + runs { + getByName("client") { + // When the property is set to true, you can log in with a Minecraft account + // devLogin = true + } } } } - - addonDev { - productionRelease() - } } subprojects { - plugins.apply("java-library") - plugins.apply("net.labymod.gradle") - plugins.apply("net.labymod.gradle.addon") - - repositories { - maven("https://libraries.minecraft.net/") - maven("https://repo.spongepowered.org/repository/maven-public/") - } -} - -fun configureRun(provider: net.labymod.gradle.core.minecraft.provider.VersionProvider, gameVersion: String) { - provider.runConfiguration { - mainClass = "net.minecraft.launchwrapper.Launch" - jvmArgs("-Dnet.labymod.running-version=${gameVersion}") - jvmArgs("-Dmixin.debug=true") - jvmArgs("-Dnet.labymod.debugging.all=true") - jvmArgs("-Dmixin.env.disableRefMap=true") - - args("--tweakClass", "net.labymod.core.loader.vanilla.launchwrapper.LabyModLaunchWrapperTweaker") - args("--labymod-dev-environment", "true") - args("--addon-dev-environment", "true") - } - - provider.javaVersion = when (gameVersion) { - else -> { - JavaVersion.VERSION_21 - } - } - - provider.mixin { - val mixinMinVersion = when (gameVersion) { - "1.8.9", "1.12.2", "1.16.5" -> { - "0.6.6" - } + plugins.apply("net.labymod.labygradle") + plugins.apply("net.labymod.labygradle.addon") - else -> { - "0.8.2" - } - } - - minVersion = mixinMinVersion - } -} + group = rootProject.group + version = rootProject.version +} \ No newline at end of file diff --git a/core/build.gradle.kts b/core/build.gradle.kts index f96ae4a..d7d5df1 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -1,18 +1,12 @@ -version = "0.1.0" - -plugins { - id("java-library") -} +import net.labymod.labygradle.common.extension.LabyModAnnotationProcessorExtension.ReferenceType dependencies { + labyProcessor() api(project(":api")) -} -labyModProcessor { - referenceType = net.labymod.gradle.core.processor.ReferenceType.DEFAULT + implementation("io.netty:netty-buffer:4.1.113.Final") } -java { - sourceCompatibility = JavaVersion.VERSION_21 - targetCompatibility = JavaVersion.VERSION_21 +labyModAnnotationProcessor { + referenceType = ReferenceType.DEFAULT } \ No newline at end of file diff --git a/core/src/main/java/ml/volder/transporter/TransporterAddon.java b/core/src/main/java/ml/volder/transporter/TransporterAddon.java index a8d2230..6e9877b 100644 --- a/core/src/main/java/ml/volder/transporter/TransporterAddon.java +++ b/core/src/main/java/ml/volder/transporter/TransporterAddon.java @@ -2,9 +2,11 @@ import ml.volder.transporter.classes.exceptions.LoadingFailedException; import ml.volder.transporter.classes.items.ItemManager; +import ml.volder.transporter.dev.command.DevCommand; import ml.volder.transporter.gui.TransporterModulesMenu; import ml.volder.transporter.listeners.KeyboardListener; import ml.volder.transporter.listeners.MainMenuOpenListener; +import ml.volder.transporter.messaging.PluginMessageHandler; import ml.volder.transporter.modules.ModuleManager; import ml.volder.transporter.updater.UpdateManager; import ml.volder.unikapi.AddonMain; @@ -14,6 +16,7 @@ import ml.volder.unikapi.datasystem.DataManager; import ml.volder.unikapi.event.EventManager; import ml.volder.unikapi.keysystem.Key; +import ml.volder.unikapi.loader.Laby4Loader; import ml.volder.unikapi.logger.Logger; import ml.volder.unikapi.utils.LoadTimer; import net.labymod.api.Laby; @@ -86,6 +89,9 @@ public void onEnable() { transporterItemManager = new ItemManager(); transporterItemManager.loadItems(); + //Payload Handler + PluginMessageHandler.getInstance().init(); + //Modules ModuleManager.getInstance().registerModules(); ModuleManager.getInstance().initModules(); @@ -94,6 +100,9 @@ public void onEnable() { //Events EventManager.registerEvents(new KeyboardListener()); EventManager.registerEvents(new MainMenuOpenListener()); + + //Developer tools + //Laby4Loader.registerCommands(new DevCommand()); }catch (Exception e) { UnikAPI.getCommonDataFolder().delete(); UnikAPI.LOGGER.printStackTrace(Logger.LOG_LEVEL.SEVERE, e); diff --git a/core/src/main/java/ml/volder/transporter/classes/items/Item.java b/core/src/main/java/ml/volder/transporter/classes/items/Item.java index d33937a..22c6cea 100644 --- a/core/src/main/java/ml/volder/transporter/classes/items/Item.java +++ b/core/src/main/java/ml/volder/transporter/classes/items/Item.java @@ -3,7 +3,12 @@ import ml.volder.transporter.TransporterAddon; import ml.volder.transporter.classes.api.TransporterPriceApi; import ml.volder.transporter.events.ItemAmountUpdatedEvent; +import ml.volder.transporter.messaging.PluginMessageHandler; +import ml.volder.transporter.messaging.channels.GetChannel; +import ml.volder.transporter.messaging.channels.PutChannel; import ml.volder.unikapi.api.player.PlayerAPI; +import ml.volder.unikapi.datasystem.Data; +import ml.volder.unikapi.datasystem.DataManager; import ml.volder.unikapi.event.EventManager; import ml.volder.unikapi.event.EventType; import ml.volder.unikapi.types.Material; @@ -15,6 +20,8 @@ public class Item { + private DataManager dataManagerSettings; + private Material material; private Integer sellValue; @@ -27,6 +34,7 @@ public class Item { public Item(String type, String legacy_type){ this.material = Material.create("minecraft", type, legacy_type); loadData(); + this.dataManagerSettings = DataManager.getOrCreateDataManager("%common%/settings.json"); } public void setSellValue(Integer sellValue) { @@ -86,6 +94,32 @@ public Material getMaterial() { return material; } + /** + * Send get payload to server + * + * @param amount amount to get from transporter + */ + public void get(Integer amount) { + if(dataManagerSettings.getBoolean("useTransporterPackets")) { + PluginMessageHandler.getChannel(GetChannel.class).sendPayload(this.getModernType(), amount); + } else { + PlayerAPI.getAPI().sendCommand("transporter get " + this.getModernType() + " " + amount); + } + } + + /** + * Send put payload to server + * + * @param amount amount to put in transporter + */ + public void put(Integer amount) { + if(dataManagerSettings.getBoolean("useTransporterPackets")) { + PluginMessageHandler.getChannel(PutChannel.class).sendPayload(this.getModernType(), amount); + } else { + PlayerAPI.getAPI().sendCommand("transporter put " + this.getModernType() + " " + amount); + } + } + private void loadData() { this.sellValue = TransporterAddon.getInstance().getTransporterItemManager().getDataManagerGlobal().getSettings().getData().has("sellValue." + this.getModernType()) ? TransporterAddon.getInstance().getTransporterItemManager().getDataManagerGlobal().getSettings().getData().get("sellValue." + this.getModernType()).getAsInt() diff --git a/core/src/main/java/ml/volder/transporter/classes/items/ItemManager.java b/core/src/main/java/ml/volder/transporter/classes/items/ItemManager.java index 0b50da4..919f903 100644 --- a/core/src/main/java/ml/volder/transporter/classes/items/ItemManager.java +++ b/core/src/main/java/ml/volder/transporter/classes/items/ItemManager.java @@ -22,6 +22,8 @@ public class ItemManager { private List itemList = new ArrayList<>(); + private boolean hasTransporterData = false; + public void loadItems() { LoadTimer.start("loadItems"); loadItemsFromCSV(); @@ -157,6 +159,7 @@ private void initDataManager() { return; this.dataManager = DataManager.getOrCreateDataManager(new File(UnikAPI.getPlayerDataFolder(), "itemData.json")); dataManagerUUID = PlayerAPI.getAPI().getUUID(); + hasTransporterData = dataManager.getBoolean("hasTransporterData"); } public DataManager getDataManager() { @@ -176,4 +179,19 @@ public DataManager getDataManagerGlobal() { initDataManagerGlobal(); return globalDataManager; } + + public boolean hasTransporterData() { + if(dataManager == null || PlayerAPI.getAPI().getUUID() == null || !dataManagerUUID.equals(PlayerAPI.getAPI().getUUID())) + getDataManager(); + return hasTransporterData; + } + + public void transporterInfoSet() { + if(hasTransporterData) + return; + hasTransporterData = true; + getDataManager().getSettings().getData().addProperty("hasTransporterData", hasTransporterData); + getDataManager().save(); + } + } diff --git a/core/src/main/java/ml/volder/transporter/dev/command/DevCommand.java b/core/src/main/java/ml/volder/transporter/dev/command/DevCommand.java new file mode 100644 index 0000000..ee1d5e5 --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/dev/command/DevCommand.java @@ -0,0 +1,51 @@ +package ml.volder.transporter.dev.command; + +import ml.volder.transporter.messaging.PluginMessageHandler; +import ml.volder.transporter.messaging.channels.*; +import net.labymod.api.Laby; +import net.labymod.api.client.chat.command.Command; +import net.labymod.api.client.component.Component; +import net.labymod.api.client.component.format.NamedTextColor; + +import java.util.UUID; +import java.util.function.Consumer; + +public class DevCommand extends Command { + + + public DevCommand() { + super("dev", "developer"); + } + + @Override + public boolean execute(String prefix, String[] arguments) { + if(arguments.length >= 1) { + if(arguments[0].equalsIgnoreCase("get")) { + if(arguments.length == 3) { + String item = arguments[1]; + Integer amount = Integer.parseInt(arguments[2]); + PluginMessageHandler.getChannel(GetChannel.class).sendPayload(item, amount); + } + } else if(arguments[0].equalsIgnoreCase("put")) { + if(arguments.length == 3) { + String item = arguments[1]; + Integer amount = Integer.parseInt(arguments[2]); + PluginMessageHandler.getChannel(PutChannel.class).sendPayload(item, amount); + + } + } else if(arguments[0].equalsIgnoreCase("send")) { + if(arguments.length == 4) { + String item = arguments[2]; + Integer amount = Integer.parseInt(arguments[3]); + UUID player = UUID.fromString(arguments[1]); + PluginMessageHandler.getChannel(SendChannel.class).sendPayload(item, amount, player); + } + } else if(arguments[0].equalsIgnoreCase("infoall")) { + PluginMessageHandler.getChannel(InfoAllChannel.class).sendPayload("sand", "stone", "dirt"); + } else if(arguments[0].equalsIgnoreCase("balance")) { + PluginMessageHandler.getChannel(BalanceChannel.class).sendPayload(); + } + } + return true; + } +} diff --git a/core/src/main/java/ml/volder/transporter/events/TransporterChannelRegisteredEvent.java b/core/src/main/java/ml/volder/transporter/events/TransporterChannelRegisteredEvent.java new file mode 100644 index 0000000..7996a81 --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/events/TransporterChannelRegisteredEvent.java @@ -0,0 +1,29 @@ +package ml.volder.transporter.events; + +import ml.volder.unikapi.event.Event; +import ml.volder.unikapi.event.EventType; +import ml.volder.unikapi.event.Handler; + +import java.util.ArrayList; +import java.util.List; + +public class TransporterChannelRegisteredEvent extends Event { + private static List handlerList = new ArrayList<>(); + + public TransporterChannelRegisteredEvent(EventType eventType, String eventName) { + super(eventType, eventName); + } + + public TransporterChannelRegisteredEvent(EventType eventType) { + this(eventType, "transporter_channel_registered_event"); + } + + @Override + public List getHandlerList() { + return handlerList; + } + + public static List getHandlers(){ + return handlerList; + } +} diff --git a/core/src/main/java/ml/volder/transporter/gui/elements/ScrollableGrid.java b/core/src/main/java/ml/volder/transporter/gui/elements/ScrollableGrid.java new file mode 100644 index 0000000..9fa1bec --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/gui/elements/ScrollableGrid.java @@ -0,0 +1,137 @@ +package ml.volder.transporter.gui.elements; + +import ml.volder.unikapi.guisystem.elements.Scrollbar; +import ml.volder.unikapi.keysystem.MouseButton; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class ScrollableGrid { + + private double width; + private double height; + private int x; + private int y; + + private final int entryWidth; + private final int entryHeight; + private final int spacingHorizontal; + private final int spacingVertical; + private List entries; + + private final Scrollbar scrollbar; + + public ScrollableGrid(double width, double height, int x, int y, int entryWidth, int entryHeight, int spacingHorizontal, int spacingVertical) { + this.width = width; + this.height = height; + this.x = x; + this.y = y; + this.entryWidth = entryWidth; + this.entryHeight = entryHeight; + this.spacingHorizontal = spacingHorizontal; + this.spacingVertical = spacingVertical; + this.entries = new ArrayList<>(); + this.scrollbar = new Scrollbar(entryHeight + spacingVertical); + this.scrollbar.setSpeed(39); + } + + public void render(int mouseX, int mouseY) { + int entryAmountHorizontal = (int)Math.floor(width / (entryWidth + spacingHorizontal)); + double entriesWidth = entryAmountHorizontal * (entryWidth + spacingHorizontal); //Total width of all entries including spacing between them + double startX = (width - entriesWidth) / 2 + x; //Start x position of the first entry so that all entries are centered + + int rows = (int) Math.ceil((double) entries.size() / entryAmountHorizontal); //Amount of rows that the entries will take up + + int scrollY = (int)this.scrollbar.getScrollY(); + int outOfViewEntryRows = Math.abs(scrollY) / (entryHeight + spacingVertical); //Amount of rows that are out of view above the visible area + int inViewEntryRows = (int) (height / (entryHeight + spacingVertical)); //Amount of rows that are visible + int outOfViewAmount = entryAmountHorizontal * outOfViewEntryRows; //Amount of entries that are out of view above the visible area + int visibleEntriesAmount = entryAmountHorizontal * (inViewEntryRows + 2); //Amount of entries that are visible + + int firstIndex = Math.max(Math.min(outOfViewAmount, entries.size() - visibleEntriesAmount), 0); + int lastIndex = Math.max(Math.min(outOfViewAmount + visibleEntriesAmount, entries.size()),0); + + Collection visibleEntries = entries.subList(firstIndex, lastIndex); + + int offset = scrollY + Math.max(Math.min(outOfViewEntryRows, rows - inViewEntryRows - 2), 0) * (entryHeight + spacingVertical); //Offset for the y position of the entries + + int currentX = (int) startX; + int currentY = y; + + for(Entry entry : visibleEntries) { + if(currentX + entryWidth >= startX + entriesWidth) { + currentX = (int) startX; + currentY += entryHeight + spacingVertical; + } + entry.render(currentX, currentY + offset, mouseX, mouseY); + currentX += entryWidth + spacingHorizontal; + } + + this.scrollbar.setPosition(startX + entriesWidth + 3, y, startX + entriesWidth + 6, y + height); + this.scrollbar.update(rows); + + if(rows < inViewEntryRows){ + this.scrollbar.update(0); + } + + this.scrollbar.draw(); + + hoverEntries = visibleEntries; + } + + private Collection hoverEntries = new ArrayList<>(); + + public void renderHoverText() { + for(Entry entry : hoverEntries) { + entry.renderHoverText(); + } + } + + public void initGui() { + this.scrollbar.init(); + } + + public void mouseClicked(int mouseX, int mouseY, MouseButton mouseButton) { + if(mouseY > y && mouseY < y + height && mouseX > x && mouseX < x + width) + entries.forEach(transporterMenuEntry -> transporterMenuEntry.mouseClicked(mouseX, mouseY, mouseButton)); + this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.CLICKED); + } + + public void mouseClickMove(int mouseX, int mouseY, MouseButton clickedMouseButton, long timeSinceLastClick) { + this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.DRAGGING); + } + + public void mouseReleased(int mouseX, int mouseY, MouseButton mouseButton) { + this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.RELEASED); + } + + public void handleMouseInput() { + this.scrollbar.mouseInput(); + } + + public void updateEntries(List entries) { + this.entries = entries; + } + + public void resetScroll() { + this.scrollbar.reset(); + } + + public void updateGridSize(double width, double height, int x, int y) { + this.width = width; + this.height = height; + this.x = x; + this.y = y; + } + + public static abstract class Entry { + public abstract void render(int x, int y, int mouseX, int mouseY); + + public abstract void renderHoverText(); + + public void mouseClicked(int mouseX, int mouseY, MouseButton mouseButton) { + + } + } +} diff --git a/core/src/main/java/ml/volder/transporter/gui/pricegui/PriceMenu.java b/core/src/main/java/ml/volder/transporter/gui/pricegui/PriceMenu.java index 503bcc8..a08be50 100644 --- a/core/src/main/java/ml/volder/transporter/gui/pricegui/PriceMenu.java +++ b/core/src/main/java/ml/volder/transporter/gui/pricegui/PriceMenu.java @@ -2,6 +2,7 @@ import ml.volder.transporter.TransporterAddon; import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.gui.elements.ScrollableGrid; import ml.volder.unikapi.api.draw.DrawAPI; import ml.volder.unikapi.guisystem.elements.Scrollbar; import ml.volder.unikapi.keysystem.Key; @@ -21,9 +22,8 @@ public class PriceMenu extends WrappedGuiScreen { private boolean isInBackground = false; private int entryWidth = 120; private int entryHeight = 37; - private Scrollbar scrollbar = new Scrollbar(entryHeight); - private List itemEntries = new ArrayList<>(); + private ScrollableGrid scrollableGrid = new ScrollableGrid(0, 0, 0, 0, entryWidth, entryHeight, 2, 2); public PriceMenu(ScreenWrapper lastScreen) { this.lastScreen = lastScreen; @@ -41,11 +41,12 @@ public void initGui() { for(Item item : TransporterAddon.getInstance().getTransporterItemManager().getItemList()) { itemEntries.add(new PriceMenuEntry(this, item, entryWidth, entryHeight)); } - this.scrollbar.setSpeed(39); - this.scrollbar.init(); + this.addButton(new WrappedGuiButton(1, 5, 10, 22, 20, "<")); + this.addButton(new WrappedGuiButton(2, 5, getHeight() - 31, 120, 20, "Opdatere alle priser")); - this.addButton(new WrappedGuiButton(1, 5, 10, 22, 21, "<")); - this.addButton(new WrappedGuiButton(2, 5, getHeight() - 31, 120, 21, "Opdatere alle priser")); + scrollableGrid.initGui(); + scrollableGrid.updateGridSize(getWidth(), getHeight() - 90, 0, 45); + scrollableGrid.updateEntries(itemEntries); } @Override @@ -53,40 +54,7 @@ public void drawScreen(int mouseX, int mouseY, float partialTicks) { DrawAPI drawAPI = DrawAPI.getAPI(); drawAPI.drawAutoDimmedBackground(0); - double emptySpaceWidth = getWidth(); - int entryAmountHorizontal = (int)Math.floor(emptySpaceWidth / (entryWidth + 2)); - double entriesWidth = entryAmountHorizontal * (entryWidth + 2); - double startX = (emptySpaceWidth - entriesWidth) / 2; - double currentX = startX; - - double startY = 45; - int rows = (int)Math.ceil((double)itemEntries.size() / (double)entryAmountHorizontal); - - //Only draw the entries that are visible - int scrollY = (int)this.scrollbar.getScrollY(); - int outOfViewEntryRows = Math.abs(scrollY) / (entryHeight + 2); - int inViewEntryRows = (getHeight() - 90) / (entryHeight + 2) + 1; - int outOfViewAmount = entryAmountHorizontal * outOfViewEntryRows; - int visibleEntriesAmount = entryAmountHorizontal * inViewEntryRows; - - int firstIndex = Math.max(Math.min(outOfViewAmount, itemEntries.size() - visibleEntriesAmount), 0); - int lastIndex = Math.max(Math.min(outOfViewAmount + visibleEntriesAmount, itemEntries.size()),0); - - List visibleEntries = itemEntries.subList(firstIndex, lastIndex); - - if(lastIndex == itemEntries.size()) { - startY -= (getHeight() - 90); - startY -= Math.abs(scrollY) - (lastIndex / entryAmountHorizontal) * (entryHeight + 2); - } - - for(PriceMenuEntry entry : visibleEntries) { - if(currentX + entryWidth >= startX + entriesWidth) { - currentX = startX; - startY += entryHeight + 2; - } - entry.draw((int)currentX, (int)(startY), mouseX, mouseY); - currentX += entryWidth + 2; - } + scrollableGrid.render(mouseX, mouseY); drawAPI.drawOverlayBackground(0, 41); drawAPI.drawGradientShadowTop(41.0, 0.0, this.getWidth()); @@ -94,13 +62,7 @@ public void drawScreen(int mouseX, int mouseY, float partialTicks) { drawAPI.drawGradientShadowBottom(this.getHeight() - 40, 0.0, this.getWidth()); drawAPI.drawCenteredString(ModColor.cl("a")+ModColor.cl("l")+"Værdi indstillinger", (double)(this.getWidth() / 2), 10.0D, 2.0D); - this.scrollbar.setPosition(startX + entriesWidth + 3, 43, startX + entriesWidth + 6, getHeight() - 42); - this.scrollbar.update(rows + 5); - this.scrollbar.draw(); - - for(PriceMenuEntry entry : visibleEntries) { - entry.drawHoverText(); - } + scrollableGrid.renderHoverText(); } @Override @@ -117,22 +79,22 @@ else if(button.getId() == 2) { public void mouseClicked(int mouseX, int mouseY, MouseButton mouseButton) { if(mouseY > 41 && mouseY < getHeight() - 40) itemEntries.forEach(priceMenuEntry -> priceMenuEntry.mouseClicked(mouseX, mouseY, mouseButton)); - this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.CLICKED); + this.scrollableGrid.mouseClicked(mouseX, mouseY, mouseButton); } @Override public void mouseClickMove(int mouseX, int mouseY, MouseButton clickedMouseButton, long timeSinceLastClick) { - this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.DRAGGING); + this.scrollableGrid.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); } @Override public void mouseReleased(int mouseX, int mouseY, MouseButton mouseButton) { - this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.RELEASED); + this.scrollableGrid.mouseReleased(mouseX, mouseY, mouseButton); } @Override public void handleMouseInput() { - this.scrollbar.mouseInput(); + this.scrollableGrid.handleMouseInput(); } @Override diff --git a/core/src/main/java/ml/volder/transporter/gui/pricegui/PriceMenuEntry.java b/core/src/main/java/ml/volder/transporter/gui/pricegui/PriceMenuEntry.java index 4d067dc..2599eca 100644 --- a/core/src/main/java/ml/volder/transporter/gui/pricegui/PriceMenuEntry.java +++ b/core/src/main/java/ml/volder/transporter/gui/pricegui/PriceMenuEntry.java @@ -1,6 +1,7 @@ package ml.volder.transporter.gui.pricegui; import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.gui.elements.ScrollableGrid; import ml.volder.transporter.utils.FormatingUtils; import ml.volder.unikapi.api.draw.DrawAPI; import ml.volder.unikapi.api.player.PlayerAPI; @@ -14,7 +15,7 @@ import java.util.Collections; -public class PriceMenuEntry { +public class PriceMenuEntry extends ScrollableGrid.Entry { private int width = 120; private int height = 37; @@ -36,7 +37,7 @@ public PriceMenuEntry(PriceMenu priceMenu, Item item, int width, int height) { this.height = height; } - public void draw(int x, int y, int mouseX, int mouseY) { + public void render(int x, int y, int mouseX, int mouseY) { hoverText = null; hoverTextX = -1000; hoverTextY = -1000; @@ -82,7 +83,7 @@ public void draw(int x, int y, int mouseX, int mouseY) { private int hoverTextX = -1000; private int hoverTextY = -1000; - public void drawHoverText() { + public void renderHoverText() { if(hoverText == null || hoverTextX == -1000 || hoverTextY == -1000) return; DrawAPI.getAPI().drawHoverText(Collections.singletonList(hoverText), hoverTextX, hoverTextY); diff --git a/core/src/main/java/ml/volder/transporter/messaging/PluginMessageHandler.java b/core/src/main/java/ml/volder/transporter/messaging/PluginMessageHandler.java new file mode 100644 index 0000000..9bd1432 --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/messaging/PluginMessageHandler.java @@ -0,0 +1,139 @@ +package ml.volder.transporter.messaging; + +import ml.volder.transporter.events.TransporterChannelRegisteredEvent; +import ml.volder.transporter.messaging.channels.*; +import ml.volder.unikapi.UnikAPI; +import ml.volder.unikapi.event.EventManager; +import ml.volder.unikapi.event.EventType; +import ml.volder.unikapi.logger.Logger; +import net.labymod.api.Laby; +import net.labymod.api.client.resources.ResourceLocation; +import net.labymod.api.event.Subscribe; +import net.labymod.api.event.client.network.server.NetworkPayloadEvent; + +import javax.inject.Singleton; +import java.util.*; + +@Singleton +public class PluginMessageHandler { + + private static final ResourceLocation CHANNEL = ResourceLocation.create("sa", "transporter"); + private static PluginMessageHandler instance; + + //Channels + private final Map channels = new HashMap<>(); + private final Map, Channel> channelsByClass = new HashMap<>(); + + private void registerChannel(Channel channel) { + channels.put(channel.getChannelId(), channel); + channelsByClass.put(channel.getClass(), channel); + } + + private final Deque senderDeque = new LinkedList<>(); + private boolean isRegistered = false; + + public static PluginMessageHandler getInstance() { + if (instance == null) { + instance = new PluginMessageHandler(); + } + return instance; + } + + public void init() { + Laby.references().eventBus().registerListener(this); + Laby.references().payloadRegistry().registerPayloadChannel(CHANNEL); + + + registerChannel(GetChannel.init()); + registerChannel(PutChannel.init()); + registerChannel(SendChannel.init()); + registerChannel(BalanceChannel.init()); + registerChannel(InfoAllChannel.init()); + } + + + public void infoAllPayload() { + TAByteBuf buf = TAByteBuf.create(); + buf.writeVarInt(4); // Channel: 4 = InfoAll + String[] excludeItems = new String[]{"sand", "stone"}; + buf.writeByte(excludeItems.length); + for (String item : excludeItems) { + buf.writeUTF(item); + } + byte[] payload = new byte[buf.readableBytes()]; + buf.readBytes(payload); + Laby.references().serverController().sendPayload(CHANNEL, payload); + } + + private T internalGetChannel(Class klass) { + Channel module = channelsByClass.getOrDefault(klass, null); + if(module.getClass().isAssignableFrom(klass)) + return (T) module; + throw new IllegalArgumentException("Channel not found"); + } + + public static T getChannel(Class klass) { + if(instance == null) + throw new IllegalStateException("PluginMessageHandler not initialized"); + return instance.internalGetChannel(klass); + } + + private Channel internalGetChannel(int channelId) { + Channel channel = channels.getOrDefault(channelId, null); + if(channel == null) + throw new IllegalArgumentException("Channel not found"); + return channel; + } + + public static Channel getChannel(int channelId) { + if(instance == null) + throw new IllegalStateException("PluginMessageHandler not initialized"); + return instance.internalGetChannel(channelId); + } + + @Subscribe + public void onPayload(NetworkPayloadEvent event) { + if (event.getPayload().length > 0 && event.identifier() != null) { + UnikAPI.LOGGER.debug("Received payload - side:" + event.side() + " - " + Arrays.toString(event.getPayload()) + " - " + event.identifier()); + } + + if(event.identifier().toString().equals("minecraft:register")) { + if(event.side() == NetworkPayloadEvent.Side.SEND) { + isRegistered = false; + } + if(event.side() == NetworkPayloadEvent.Side.RECEIVE) { + TAByteBuf buf = TAByteBuf.create(); + buf.writeBytes(event.getPayload()); + String[] registeredChannels = buf.readNullSeparatedUTF(); + UnikAPI.LOGGER.debug("Registered channel: " + Arrays.toString(registeredChannels), Logger.DEBUG_LEVEL.LOWEST); + + for(String registeredChannel : registeredChannels) { + if (registeredChannel.equals(CHANNEL.toString())) { + isRegistered = true; + EventManager.callEvent(new TransporterChannelRegisteredEvent(EventType.POST)); + } + } + } + } + + if(event.side() == NetworkPayloadEvent.Side.RECEIVE && event.identifier().equals(CHANNEL) && !senderDeque.isEmpty()) { + senderDeque.pollLast().handleIncomingPayload(event.getPayload()); + } + } + + private void internalSendPayload(byte[] payload, Channel sender) { + if(!isRegistered) { + UnikAPI.LOGGER.debug("Ignored payload: Payload channel 'sa:transporter' not registered", Logger.DEBUG_LEVEL.LOWEST); + sender.payloadNotDispatched(payload); + return; + } + senderDeque.push(sender); + Laby.references().serverController().sendPayload(CHANNEL, payload); + } + + public static void sendPayload(byte[] payload, Channel sender) { + if(instance == null) + return; + getInstance().internalSendPayload(payload, sender); + } +} diff --git a/core/src/main/java/ml/volder/transporter/messaging/TAByteBuf.java b/core/src/main/java/ml/volder/transporter/messaging/TAByteBuf.java new file mode 100644 index 0000000..7359d10 --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/messaging/TAByteBuf.java @@ -0,0 +1,177 @@ +package ml.volder.transporter.messaging; + +import io.netty.buffer.AbstractByteBuf; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.UnpooledHeapByteBuf; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +public class TAByteBuf extends UnpooledHeapByteBuf { + + private static final int MAX_LENGTH = 32767; + private static final int SEGMENT_BITS = 0x7F; + private static final int CONTINUE_BIT = 0x80; + + protected TAByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) { + super(alloc, initialCapacity, maxCapacity); + } + + public static TAByteBuf create() { + return create(256, Integer.MAX_VALUE); + } + + public static TAByteBuf create(int initialCapacity) { + return create(initialCapacity, Integer.MAX_VALUE); + } + + public static TAByteBuf create(int initialCapacity, int maxCapacity) { + validate(initialCapacity, maxCapacity); + return new TAByteBuf(ByteBufAllocator.DEFAULT, initialCapacity, maxCapacity); + } + + private static void validate(int initialCapacity, int maxCapacity) { + if (maxCapacity == 0) { + throw new IllegalArgumentException("maxCapacity: " + maxCapacity + " (expected greater than 0)"); + } + if (initialCapacity < 0) { + throw new IllegalArgumentException("initialCapacity: " + initialCapacity + " (expectd: 0+)"); + } + if (initialCapacity > maxCapacity) { + throw new IllegalArgumentException(String.format( + "initialCapacity: %d (expected: not greater than maxCapacity(%d)", + initialCapacity, maxCapacity)); + } + } + + public int readVarInt() { + int value = 0; + int position = 0; + byte currentByte; + + while (true) { + currentByte = this.readByte(); + value |= (currentByte & SEGMENT_BITS) << position; + + if ((currentByte & CONTINUE_BIT) == 0) break; + + position += 7; + + if (position >= 32) throw new RuntimeException("VarInt is too big"); + } + + return value; + } + + public long readVarLong() { + long value = 0; + int position = 0; + byte currentByte; + + while (true) { + currentByte = readByte(); + value |= (long) (currentByte & SEGMENT_BITS) << position; + + if ((currentByte & CONTINUE_BIT) == 0) break; + + position += 7; + + if (position >= 64) throw new RuntimeException("VarLong is too big"); + } + + return value; + } + + public void writeVarInt(int value) { + while (true) { + if ((value & ~SEGMENT_BITS) == 0) { + this.writeByte(value); + return; + } + + this.writeByte((value & SEGMENT_BITS) | CONTINUE_BIT); + + value >>>= 7; + } + } + + public void writeVarLong(long value) { + while (true) { + if ((value & ~((long) SEGMENT_BITS)) == 0) { + writeByte((int) value); + return; + } + + writeByte((int) ((value & SEGMENT_BITS) | CONTINUE_BIT)); + + value >>>= 7; + } + } + + + public String readUTF() { + int stringByteLength = readVarInt(); + if (stringByteLength > MAX_LENGTH) { + throw new IllegalArgumentException("The received encoded string buffer length is longer than maximum allowed (" + stringByteLength + " > " + MAX_LENGTH + ")"); + } + + if (stringByteLength < 0) { + throw new IllegalArgumentException("The received encoded string buffer length is less than zero! Weird string!"); + } + + int remaining = this.readableBytes(); + if (stringByteLength > remaining) { + throw new IllegalArgumentException("Not enough bytes in buffer, expected " + stringByteLength + ", but got " + remaining); + } + + String decodedString = this.toString(this.readerIndex(), stringByteLength, StandardCharsets.UTF_8); + this.skipBytes(stringByteLength); + + if (decodedString.length() > MAX_LENGTH) { + throw new IllegalArgumentException("The received string length is longer than maximum allowed (" + decodedString.length() + " > " + MAX_LENGTH + ")"); + } + + return decodedString; + } + + public String[] readNullSeparatedUTF() { + List strings = new ArrayList<>(); + int startIndex = this.readerIndex(); + int length = 0; + + while (this.isReadable()) { + byte b = this.readByte(); + + if (b == 0x00) { + String decodedString = this.toString(startIndex, length, StandardCharsets.UTF_8); + strings.add(decodedString); + startIndex = this.readerIndex(); + length = 0; + } else { + length++; + } + } + + return strings.toArray(new String[0]); + } + + public void writeUTF(String val) { + byte[] encodedByteArray = val.getBytes(StandardCharsets.UTF_8); + if (encodedByteArray.length > MAX_LENGTH) { + throw new IllegalArgumentException("String too big (was " + encodedByteArray.length + " bytes encoded, max " + MAX_LENGTH + ")"); + } + + writeVarInt(encodedByteArray.length); + this.writeBytes(encodedByteArray); + } + + public byte[] toByteArray() { + this.resetReaderIndex(); + byte[] bytes = new byte[this.readableBytes()]; + this.readBytes(bytes); + return bytes; + } + +} diff --git a/core/src/main/java/ml/volder/transporter/messaging/channels/Channel.java b/core/src/main/java/ml/volder/transporter/messaging/channels/Channel.java new file mode 100644 index 0000000..f2fceee --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/messaging/channels/Channel.java @@ -0,0 +1,41 @@ +package ml.volder.transporter.messaging.channels; + +import ml.volder.transporter.messaging.PluginMessageHandler; +import ml.volder.transporter.messaging.TAByteBuf; + +public abstract class Channel { + private final int channelId; + private final String channelName; + + protected Channel(int channelId, String channelName) { + this.channelId = channelId; + this.channelName = channelName; + } + + public abstract void handleIncomingPayload(byte[] payload); + public void payloadNotDispatched(byte[] payload) { + // Do nothing + } + + public void sendPayload(byte[] payload, Channel channel) { + TAByteBuf buf = TAByteBuf.create(); + buf.writeVarInt(channel.channelId); + buf.writeBytes(payload); + PluginMessageHandler.sendPayload(buf.toByteArray(), channel); + } + + public void sendPayload(byte[] payload, int channelId) { + sendPayload(payload, PluginMessageHandler.getChannel(channelId)); + } + public void sendPayload(byte[] payload) { + sendPayload(payload, this); + } + + public int getChannelId() { + return channelId; + } + + public String getChannelName() { + return channelName; + } +} diff --git a/core/src/main/java/ml/volder/transporter/messaging/channels/GetChannel.java b/core/src/main/java/ml/volder/transporter/messaging/channels/GetChannel.java new file mode 100644 index 0000000..4ee24e3 --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/messaging/channels/GetChannel.java @@ -0,0 +1,59 @@ +package ml.volder.transporter.messaging.channels; + +import ml.volder.transporter.TransporterAddon; +import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.messaging.TAByteBuf; +import ml.volder.unikapi.UnikAPI; +import ml.volder.unikapi.logger.Logger; + +import javax.inject.Singleton; +import java.util.Deque; +import java.util.LinkedList; + +@Singleton +public class GetChannel extends Channel { + + private static GetChannel instance; + + public static GetChannel init() { + if (instance != null) { + throw new IllegalStateException("GetChannel already initialized"); + } + instance = new GetChannel(); + return instance; + } + + private GetChannel() { + super(0, "get"); + } + + + private final Deque itemDeque = new LinkedList<>(); + + public void sendPayload(String item, Integer amount) { + TAByteBuf buf = TAByteBuf.create(); + buf.writeUTF(item); + buf.writeVarInt(amount); + sendPayload(buf.toByteArray()); + itemDeque.push(item); + } + + @Override + public void handleIncomingPayload(byte[] payload) { + TAByteBuf buf = TAByteBuf.create(); + buf.writeBytes(payload); + int amount = buf.readVarInt(); + if(!itemDeque.isEmpty()) { + Item item = TransporterAddon.getInstance().getTransporterItemManager().getItemByType(itemDeque.pollLast()); + if(item == null) + return; + item.setAmountInTransporter(item.getAmountInTransporter() + amount); + UnikAPI.LOGGER.debug("Took " + amount + " " + item.getDisplayName() + " from transporter", Logger.DEBUG_LEVEL.LOWEST); + } + } + + @Override + public void payloadNotDispatched(byte[] payload) { + itemDeque.clear(); + } +} diff --git a/core/src/main/java/ml/volder/transporter/messaging/channels/InfoAllChannel.java b/core/src/main/java/ml/volder/transporter/messaging/channels/InfoAllChannel.java new file mode 100644 index 0000000..31b4bac --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/messaging/channels/InfoAllChannel.java @@ -0,0 +1,55 @@ +package ml.volder.transporter.messaging.channels; + +import ml.volder.transporter.messaging.TAByteBuf; +import ml.volder.unikapi.UnikAPI; + +import javax.inject.Singleton; +import java.util.ArrayList; +import java.util.List; + +@Singleton +public class InfoAllChannel extends Channel { + + private static InfoAllChannel instance; + + public static InfoAllChannel init() { + if (instance != null) { + throw new IllegalStateException("InfoAllChannel already initialized"); + } + instance = new InfoAllChannel(); + return instance; + } + + private InfoAllChannel() { + super(4, "infoall"); + } + + public void sendPayload(String... excludeItems) { + TAByteBuf buf = TAByteBuf.create(); + buf.writeByte(excludeItems.length); + UnikAPI.LOGGER.debug("ignore items (sendPayload):"); + for (String item : excludeItems) { + buf.writeUTF(item); + UnikAPI.LOGGER.debug(item); + } + + handle((TAByteBuf) buf.resetReaderIndex()); + sendPayload(buf.toByteArray()); + } + + private void handle(TAByteBuf buf) { + List ignore = new ArrayList<>(); + int ignoreLength = buf.readByte(); + for (int i = 0; i < ignoreLength; i++) { + ignore.add(buf.readUTF()); + } + + UnikAPI.LOGGER.debug("ignore items (handle):"); + ignore.forEach(UnikAPI.LOGGER::debug); + } + + @Override + public void handleIncomingPayload(byte[] payload) { + //TODO + } +} diff --git a/core/src/main/java/ml/volder/transporter/messaging/channels/PutChannel.java b/core/src/main/java/ml/volder/transporter/messaging/channels/PutChannel.java new file mode 100644 index 0000000..2b571e2 --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/messaging/channels/PutChannel.java @@ -0,0 +1,59 @@ +package ml.volder.transporter.messaging.channels; + +import ml.volder.transporter.TransporterAddon; +import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.messaging.TAByteBuf; +import ml.volder.unikapi.UnikAPI; +import ml.volder.unikapi.logger.Logger; + +import javax.inject.Singleton; +import java.util.Deque; +import java.util.LinkedList; + +@Singleton +public class PutChannel extends Channel { + + private static PutChannel instance; + + public static PutChannel init() { + if (instance != null) { + throw new IllegalStateException("PutChannel already initialized"); + } + instance = new PutChannel(); + return instance; + } + + private PutChannel() { + super(1, "put"); + } + + + private final Deque itemDeque = new LinkedList<>(); + + public void sendPayload(String item, Integer amount) { + TAByteBuf buf = TAByteBuf.create(); + buf.writeUTF(item); + buf.writeVarInt(amount); + sendPayload(buf.toByteArray()); + itemDeque.push(item); + } + + @Override + public void handleIncomingPayload(byte[] payload) { + TAByteBuf buf = TAByteBuf.create(); + buf.writeBytes(payload); + int amount = buf.readVarInt(); + if(!itemDeque.isEmpty()) { + Item item = TransporterAddon.getInstance().getTransporterItemManager().getItemByType(itemDeque.pollLast()); + if(item == null) + return; + item.setAmountInTransporter(item.getAmountInTransporter() - amount); + UnikAPI.LOGGER.debug("Put " + amount + " " + item.getDisplayName() + " in transporter", Logger.DEBUG_LEVEL.LOWEST); + } + } + + @Override + public void payloadNotDispatched(byte[] payload) { + itemDeque.clear(); + } +} diff --git a/core/src/main/java/ml/volder/transporter/messaging/channels/SendChannel.java b/core/src/main/java/ml/volder/transporter/messaging/channels/SendChannel.java new file mode 100644 index 0000000..d9f21cd --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/messaging/channels/SendChannel.java @@ -0,0 +1,62 @@ +package ml.volder.transporter.messaging.channels; + +import ml.volder.transporter.TransporterAddon; +import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.messaging.TAByteBuf; +import ml.volder.unikapi.UnikAPI; +import ml.volder.unikapi.logger.Logger; + +import javax.inject.Singleton; +import java.util.Deque; +import java.util.LinkedList; +import java.util.UUID; + +@Singleton +public class SendChannel extends Channel { + + private static SendChannel instance; + + public static SendChannel init() { + if (instance != null) { + throw new IllegalStateException("SendChannel already initialized"); + } + instance = new SendChannel(); + return instance; + } + + private SendChannel() { + super(2, "send"); + } + + + private final Deque itemDeque = new LinkedList<>(); + + public void sendPayload(String item, Integer amount, UUID player) { + TAByteBuf buf = TAByteBuf.create(); + buf.writeVarLong(player.getMostSignificantBits()); + buf.writeVarLong(player.getLeastSignificantBits()); + buf.writeUTF(item); + buf.writeVarInt(amount); + sendPayload(buf.toByteArray()); + itemDeque.push(item); + } + + @Override + public void handleIncomingPayload(byte[] payload) { + TAByteBuf buf = TAByteBuf.create(); + buf.writeBytes(payload); + int amount = buf.readVarInt(); + if(!itemDeque.isEmpty()) { + Item item = TransporterAddon.getInstance().getTransporterItemManager().getItemByType(itemDeque.pollLast()); + if(item == null) + return; + item.setAmountInTransporter(item.getAmountInTransporter() - amount); + UnikAPI.LOGGER.debug("Send " + amount + " of " + item.getDisplayName(), Logger.DEBUG_LEVEL.LOWEST); + } + } + + @Override + public void payloadNotDispatched(byte[] payload) { + itemDeque.clear(); + } +} diff --git a/core/src/main/java/ml/volder/transporter/modules/AutoTransporter.java b/core/src/main/java/ml/volder/transporter/modules/AutoTransporter.java index 9eed1c7..8dbec89 100644 --- a/core/src/main/java/ml/volder/transporter/modules/AutoTransporter.java +++ b/core/src/main/java/ml/volder/transporter/modules/AutoTransporter.java @@ -13,7 +13,9 @@ import ml.volder.unikapi.event.EventManager; import ml.volder.unikapi.event.Listener; import ml.volder.unikapi.event.events.clientkeypressevent.ClientKeyPressEvent; +import ml.volder.unikapi.event.events.clientmessageevent.ClientMessageEvent; import ml.volder.unikapi.event.events.clienttickevent.ClientTickEvent; +import ml.volder.unikapi.event.events.serverswitchevent.ServerSwitchEvent; import ml.volder.unikapi.guisystem.ModTextures; import ml.volder.unikapi.keysystem.Key; import ml.volder.unikapi.keysystem.impl.Laby4KeyMapper; @@ -27,16 +29,15 @@ public class AutoTransporter extends SimpleModule implements Listener { - private boolean onlyActiveInLobby = true; - private boolean hasTransporterData; + //private boolean onlyActiveInLobby = true; private boolean isEnabled; private TransporterAddon addon; - private int delay = 50; - private Key toggleKey = Key.P; // Default key = P + //private int delay = 50; + private Key toggleKey = Key.O; // Default key = P - private boolean useTransporterPutMine = true; + //private boolean useTransporterPutMine = true; - private int timer = 0; + //private int timer = 0; public AutoTransporter(ModuleManager.ModuleInfo moduleInfo) { super(moduleInfo); @@ -56,7 +57,7 @@ public SimpleModule enable() { @Override public void fillSettings(SettingRegistryAccessor subSettings) { - subSettings.add(TransporterSettingElementFactory.Builder.begin() + /*subSettings.add(TransporterSettingElementFactory.Builder.begin() .addWidget(TransporterWidgetFactory.createWidget( SwitchWidget.class, new TransporterAction((b) -> this.onlyActiveInLobby = b), @@ -66,9 +67,9 @@ public void fillSettings(SettingRegistryAccessor subSettings) { .id("onlyActiveInLobby") .icon(Icon.sprite16(ModTextures.SETTINGS_ICONS_1, 4, 1)) .build() - ); + );*/ - subSettings.add(TransporterSettingElementFactory.Builder.begin() + /*subSettings.add(TransporterSettingElementFactory.Builder.begin() .addWidget(TransporterWidgetFactory.createWidget( SliderWidget.class, new TransporterAction(v -> delay = v != null ? v.intValue() : delay), @@ -78,7 +79,7 @@ public void fillSettings(SettingRegistryAccessor subSettings) { .id("autoTransporterDelay") .icon(Icon.sprite16(ModTextures.SETTINGS_ICONS, 1, 1)) .build() - ); + );*/ subSettings.add(TransporterSettingElementFactory.Builder.begin() .addWidget(TransporterWidgetFactory.createWidget( @@ -86,13 +87,14 @@ public void fillSettings(SettingRegistryAccessor subSettings) { new TransporterAction(key -> toggleKey = Laby4KeyMapper.convert(key)), getDataManager(), "autoTransporterKeybind", - net.labymod.api.client.gui.screen.key.Key.P)) + net.labymod.api.client.gui.screen.key.Key.O)) .id("autoTransporterKeybind") .icon(Icon.sprite16(ModTextures.SETTINGS_ICONS, 1, 5)) .build() ); - subSettings.add(TransporterSettingElementFactory.Builder.begin() + /*subSettings.add(TransporterSettingElementFactory.Builder.begin() + .addWidget(TransporterWidgetFactory.createWidget( SwitchWidget.class, new TransporterAction((b) -> this.useTransporterPutMine = b), @@ -102,16 +104,16 @@ public void fillSettings(SettingRegistryAccessor subSettings) { .id("useTransporterPutMine") .icon(Icon.sprite16(ModTextures.SETTINGS_ICONS, 5, 1)) .build() - ); + );*/ } @Override public void loadConfig() { super.loadConfig(); - hasTransporterData = hasConfigEntry("hasTransporterData") ? getConfigEntry("hasTransporterData", Boolean.class) : false; + //hasTransporterData = hasConfigEntry("hasTransporterData") ? getConfigEntry("hasTransporterData", Boolean.class) : false; } - @EventHandler + /*@EventHandler public void onTick(ClientTickEvent tickEvent) { if(!TransporterAddon.isEnabled() || !this.isEnabled || !this.isFeatureActive) return; @@ -126,8 +128,9 @@ public void onTick(ClientTickEvent tickEvent) { executeAutoTransporterPutMineMethod(); else executeAutoTransporterPutItemMethod(); - } + }*/ + @Deprecated(forRemoval = true) private void executeAutoTransporterPutItemMethod() { Map itemAmountMap = new HashMap<>(); @@ -145,10 +148,11 @@ private void executeAutoTransporterPutItemMethod() { if(maxAmount > 0 && itemWithMost.length() > 0){ PlayerAPI.getAPI().sendCommand("transporter put " + itemWithMost); - timer = 0; + //timer = 0; } } + @Deprecated(forRemoval = true) private void executeAutoTransporterPutMineMethod() { int itemAmount = 0; @@ -157,14 +161,14 @@ private void executeAutoTransporterPutMineMethod() { if (itemAmount < 1) return; PlayerAPI.getAPI().sendCommand("transporter put all"); - timer = 0; + //timer = 0; } @EventHandler public void onKeyInput(ClientKeyPressEvent event) { if(!TransporterAddon.isEnabled() || !this.isFeatureActive) return; - if(onlyActiveInLobby && !TransporterAddon.getInstance().getServerList().contains(ModuleManager.getInstance().getModule(ServerModule.class).getCurrentServer())) + if(!TransporterAddon.getInstance().getServerList().contains(ModuleManager.getInstance().getModule(ServerModule.class).getCurrentServer())) return; if(toggleKey == null) return; @@ -172,29 +176,29 @@ public void onKeyInput(ClientKeyPressEvent event) { this.toggle(); } - public void setDelay(int delay){ - this.delay = delay; + @EventHandler + public void onMessage(ClientMessageEvent event) { + if(event.getCleanMessage().equals("Slår auto-transporter til! (all)") || event.getCleanMessage().equals("Slår auto-transporter til! (mine)")) { + isEnabled = true; + } else if (event.getCleanMessage().equals("Slår auto-transporter fra!")) { + isEnabled = false; + } + } + + @EventHandler + public void onServerSwitch(ServerSwitchEvent event) { + isEnabled = false; } public void toggle(){ isEnabled = !isEnabled; + PlayerAPI.getAPI().sendCommand("autotransporter"); } public boolean isFeatureActive() { return isFeatureActive; } - public boolean hasTransporterData() { - return hasTransporterData; - } - - public void transporterInfoSet() { - if(hasTransporterData) - return; - hasTransporterData = true; - getDataManager().getSettings().getData().addProperty("hasTransporterData", hasTransporterData); - getDataManager().save(); - } public boolean isEnabled() { return isEnabled; diff --git a/core/src/main/java/ml/volder/transporter/modules/BalanceModule.java b/core/src/main/java/ml/volder/transporter/modules/BalanceModule.java index 14bf86f..f053db3 100644 --- a/core/src/main/java/ml/volder/transporter/modules/BalanceModule.java +++ b/core/src/main/java/ml/volder/transporter/modules/BalanceModule.java @@ -1,12 +1,17 @@ package ml.volder.transporter.modules; import ml.volder.transporter.TransporterAddon; +import ml.volder.transporter.events.TransporterChannelRegisteredEvent; +import ml.volder.transporter.messaging.PluginMessageHandler; +import ml.volder.transporter.messaging.channels.BalanceChannel; import ml.volder.transporter.settings.accesors.SettingRegistryAccessor; import ml.volder.transporter.settings.action.TransporterAction; import ml.volder.transporter.settings.classes.TransporterSettingElementFactory; import ml.volder.transporter.settings.classes.TransporterWidgetFactory; import ml.volder.unikapi.UnikAPI; import ml.volder.unikapi.api.player.PlayerAPI; +import ml.volder.unikapi.datasystem.Data; +import ml.volder.unikapi.datasystem.DataManager; import ml.volder.unikapi.event.EventHandler; import ml.volder.unikapi.event.EventManager; import ml.volder.unikapi.event.Listener; @@ -30,11 +35,13 @@ import java.util.regex.Pattern; public class BalanceModule extends SimpleModule implements Listener { + private DataManager dataManagerSettings; private TransporterAddon addon; public BalanceModule(ModuleManager.ModuleInfo moduleInfo) { super(moduleInfo); this.addon = TransporterAddon.getInstance(); + this.dataManagerSettings = DataManager.getOrCreateDataManager("%common%/settings.json"); } @Override @@ -213,30 +220,11 @@ private boolean matchBalCommandMessage(String clean) { return false; } - @EventHandler - public void onServerSwitch(ServerSwitchEvent event) { + public void onTransporterChannelRegister(TransporterChannelRegisteredEvent event) { if (!isFeatureActive() || !updateOnJoin || !TransporterAddon.isEnabled()) return; - if(event.getSwitchType() == ServerSwitchEvent.SWITCH_TYPE.LEAVE) - return; - new Timer("updateBalance").schedule(new TimerTask() { - @Override - public void run() { - if(ModuleManager.getInstance().getModule(ServerModule.class).getCurrentServer() == null) - return; - if(TransporterAddon.getInstance().getServerList().contains(ModuleManager.getInstance().getModule(ServerModule.class).getCurrentServer())) { - cancelNextBalanceCommand = true; - PlayerAPI.getAPI().sendCommand("bal"); - } - } - }, 1000L); - new Timer("updateCancelVar").schedule(new TimerTask() { - @Override - public void run() { - cancelNextBalanceCommand = false; - } - }, 1500L); + PluginMessageHandler.getChannel(BalanceChannel.class).sendPayload(); } private int timer = 0; @@ -246,15 +234,20 @@ public void onTick(ClientTickEvent event) { return; timer+=1; if(timer/20 >= updateIntervalSeconds) { - if(TransporterAddon.getInstance().getServerList().contains(ModuleManager.getInstance().getModule(ServerModule.class).getCurrentServer())){ - cancelNextBalanceCommand = true; - PlayerAPI.getAPI().sendCommand("bal"); + if(dataManagerSettings.getBoolean("useTransporterPackets")) { + PluginMessageHandler.getChannel(BalanceChannel.class).sendPayload(); + } else { + if(TransporterAddon.getInstance().getServerList().contains(ModuleManager.getInstance().getModule(ServerModule.class).getCurrentServer())){ + cancelNextBalanceCommand = true; + PlayerAPI.getAPI().sendCommand("bal"); + } } timer = 0; + } } - private void updateBalance(BigDecimal newBalance) { + public void updateBalance(BigDecimal newBalance) { this.balance = newBalance; getDataManager().getSettings().getData().addProperty("currentBalance", balance); getDataManager().save(); diff --git a/core/src/main/java/ml/volder/transporter/modules/McmmoModule.java b/core/src/main/java/ml/volder/transporter/modules/McmmoModule.java index e2eba32..44a1ccf 100644 --- a/core/src/main/java/ml/volder/transporter/modules/McmmoModule.java +++ b/core/src/main/java/ml/volder/transporter/modules/McmmoModule.java @@ -3,12 +3,18 @@ import ml.volder.transporter.TransporterAddon; import ml.volder.transporter.modules.mcmmomodule.McmmoManager; import ml.volder.transporter.settings.accesors.SettingRegistryAccessor; +import ml.volder.unikapi.UnikAPI; import ml.volder.unikapi.api.minecraft.MinecraftAPI; import ml.volder.unikapi.event.EventHandler; import ml.volder.unikapi.event.EventManager; import ml.volder.unikapi.event.Listener; import ml.volder.unikapi.event.events.clientmessageevent.ClientMessageEvent; import ml.volder.unikapi.event.events.sendmessageevent.SendMessageEvent; +import ml.volder.unikapi.logger.Logger; +import net.labymod.api.Laby; +import net.labymod.api.event.Phase; +import net.labymod.api.event.Subscribe; +import net.labymod.api.event.client.chat.ActionBarReceiveEvent; import java.util.Map; import java.util.Timer; @@ -32,6 +38,7 @@ public SimpleModule init() { public SimpleModule enable() { mcmmoManager.registerModules(); EventManager.registerEvents(this); + Laby.labyAPI().eventBus().registerListener(this); return this; } @@ -44,7 +51,17 @@ public void fillSettings(SettingRegistryAccessor subSettings) { public void onChatMessage(ClientMessageEvent event) { if(!TransporterAddon.isEnabled() || !this.isFeatureActive) return; - mcmmoManager.onMessageReceive(event); + mcmmoManager.onMessageReceive(event.getCleanMessage()); + } + + @Subscribe + public void onActionBarMessage(ActionBarReceiveEvent event) { + if(!TransporterAddon.isEnabled() || !this.isFeatureActive || event.getMessage() == null || event.phase() != Phase.PRE) + return; + String message = event.getMessage().toString().replace("literal{", ""); + message = message.substring(0, message.length() - 1); + UnikAPI.LOGGER.debug("Action bar: " + message, Logger.DEBUG_LEVEL.LOWEST); + mcmmoManager.onMessageReceive(message); } @EventHandler diff --git a/core/src/main/java/ml/volder/transporter/modules/MessagesModule.java b/core/src/main/java/ml/volder/transporter/modules/MessagesModule.java index db4cad8..c80a829 100644 --- a/core/src/main/java/ml/volder/transporter/modules/MessagesModule.java +++ b/core/src/main/java/ml/volder/transporter/modules/MessagesModule.java @@ -50,6 +50,7 @@ public SimpleModule init() { messageHandlers.add(new TransporterPutMessageHandler(this)); messageHandlers.add(new TransporterInfoHandler(this)); messageHandlers.add(new TransporterSendMessageHandler(this)); + messageHandlers.add(new TransporterMiscellaneousMessageHandler(this)); return this; } @@ -188,6 +189,24 @@ public void fillSettings(SettingRegistryAccessor subSettings) { Icon.sprite16(ModTextures.COMMON_ICONS, 3, 1) )); + subSettings.add(createMessageSetting( + "putAllMessage", + "&bGemte &3%antal% &bitems i din transporter!", + Icon.sprite8(ModTextures.WIDGET_EDITOR_ICONS, 4, 1) + )); + + subSettings.add(createMessageSetting( + "autoTransporterOn", + "&aAuto-transporter er nu aktiv!", + Icon.sprite16(ModTextures.COMMON_ICONS, 1, 0) + )); + + subSettings.add(createMessageSetting( + "autoTransporterOff", + "&cAuto-transporter er nu inaktiv!", + Icon.sprite16(ModTextures.COMMON_ICONS, 4, 6) + )); + subSettings.add(createMessageSetting( "sendOffline", "&cDenne spiller er ikke online!", diff --git a/core/src/main/java/ml/volder/transporter/modules/TransporterMenuModule.java b/core/src/main/java/ml/volder/transporter/modules/TransporterMenuModule.java index e920810..ad27097 100644 --- a/core/src/main/java/ml/volder/transporter/modules/TransporterMenuModule.java +++ b/core/src/main/java/ml/volder/transporter/modules/TransporterMenuModule.java @@ -22,13 +22,12 @@ import net.labymod.api.client.gui.screen.widget.widgets.input.SliderWidget; import net.labymod.api.client.gui.screen.widget.widgets.input.SwitchWidget; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; +import java.util.stream.Collectors; public class TransporterMenuModule extends SimpleModule implements Listener { - private List activeItems = new ArrayList<>(); + private Map activeItems = new HashMap<>(); private boolean onlyActiveInLobby = true; private int withdrawAmount = 64; @@ -92,30 +91,46 @@ public void fillSettings(SettingRegistryAccessor subSettings) { public void loadConfig() { super.loadConfig(); if(getDataManager() != null){ - for(Item item : TransporterAddon.getInstance().getTransporterItemManager().getItemList()){ - if(getDataManager().getSettings().getData().has(item.getModernType())){ - if(getDataManager().getSettings().getData().get(item.getModernType()).getAsBoolean()){ - activeItems.add(item); - } + + //Config adapter - Convert old config to new config + if(!getDataManager().getSettings().getData().has("configVersion") || getDataManager().getSettings().getData().get("configVersion").getAsInt() < 1){ + int slot = 0; + + for(Item item : TransporterAddon.getInstance().getTransporterItemManager().getItemList()){ + if(getDataManager().getSettings().getData().has(item.getModernType())){ + if(getDataManager().getSettings().getData().get(item.getModernType()).getAsBoolean()){ + getDataManager().getSettings().getData().addProperty(item.getModernType(), slot); + slot++; + } else if (!(getDataManager().getSettings().getData().get(item.getModernType()).getAsInt() >= 0)) { + getDataManager().getSettings().getData().remove(item.getModernType()); + } + } + } + getDataManager().getSettings().getData().addProperty("configVersion", 1); + getDataManager().save(); } - } - if(activeItems.size() == 0) { - List defaultItems = Arrays.asList("stone","cobblestone","diamond_ore","diamond_block","gold_block","iron_block","iron_ore","gold_ore","red_sand","sand","oak_log","spruce_log","dirt","grass_block","birch_log","glass","white_wool","chest","crafting_table","emerald_block","beacon","redstone","trapped_chest","sticky_piston","piston","hopper","comparator","diamond","emerald","iron_ingot","gold_ingot","lapis_lazuli","quartz","coal","bone","bone_meal","item_frame","cooked_beef","glowstone","obsidian","glowstone_dust","slime_ball","spruce_planks","spruce_sapling","oak_sapling","leather","sugar_cane","torch","blue_stained_glass","white_stained_glass","cocoa_beans","grass","oak_planks","jukebox","repeater"); - for(String item : defaultItems){ - Item i = TransporterAddon.getInstance().getTransporterItemManager().getItemByType(item); - if(i != null){ - addActiveItem(i); - } + + for(Item item : TransporterAddon.getInstance().getTransporterItemManager().getItemList()){ + if(getDataManager().getSettings().getData().has(item.getModernType())){ + if(getDataManager().getSettings().getData().get(item.getModernType()).getAsInt() >= 0){ + activeItems.put(item, getDataManager().getSettings().getData().get(item.getModernType()).getAsInt()); + } + } + } + if(activeItems.isEmpty()) { + List defaultItems = Arrays.asList("stone","cobblestone","diamond_ore","diamond_block","gold_block","iron_block","iron_ore","gold_ore","red_sand","sand","oak_log","spruce_log","dirt","grass_block","birch_log","glass","white_wool","chest","crafting_table","emerald_block","beacon","redstone","trapped_chest","sticky_piston","piston","hopper","comparator","diamond","emerald","iron_ingot","gold_ingot","lapis_lazuli","quartz","coal","bone","bone_meal","item_frame","cooked_beef","glowstone","obsidian","glowstone_dust","slime_ball","spruce_planks","spruce_sapling","oak_sapling","leather","sugar_cane","torch","blue_stained_glass","white_stained_glass","cocoa_beans","grass","oak_planks","jukebox","repeater"); + for(String item : defaultItems) { + Item i = TransporterAddon.getInstance().getTransporterItemManager().getItemByType(item); + if(i != null){ + addActiveItem(i); + } + } } - } - } - } - public void fillSettings(Settings subSettings) { - //onlyActiveInLobby: Kun aktiv i lobbyer! - //transporterMenuKeybind: Åben menu - //withdrawAmount: Antal items der skal trækkes ud + adjustSlots(); + saveActiveItems(); } + } @EventHandler @@ -136,28 +151,92 @@ private void open() { PlayerAPI.getAPI().openGuiScreen(new TransporterMenu()); } - public void addActiveItem(Item item) { - activeItems.add(item); + public void swap(int slot, int slot2) { + Item item = activeItems.entrySet().stream().filter(e -> e.getValue() == slot).map(Map.Entry::getKey).findFirst().orElse(null); + Item item2 = activeItems.entrySet().stream().filter(e -> e.getValue() == slot2).map(Map.Entry::getKey).findFirst().orElse(null); + if(item != null && item2 != null){ + activeItems.put(item, slot2); + activeItems.put(item2, slot); + saveActiveItems(); + } + } + + /** + * Adds an item to the active items list without saving it to the config, + * and ensures that the item is not already in the list aswell as each slot only being used once. + */ + private void internalAddActiveItem(Item item) { + //write + if(activeItems.containsKey(item)) + return; + int slot = 0; + while(activeItems.containsValue(slot)) { + slot++; + } + activeItems.put(item, slot); + adjustSlots(); + } + + private void adjustSlots() { + List> sortedEntries = new ArrayList<>(activeItems.entrySet()); + sortedEntries.sort(Map.Entry.comparingByValue()); //Sortere liste efter slot + + Map slotMap = new HashMap<>(); + + int slot = 0; + for (Map.Entry entry : sortedEntries) { + while (slotMap.containsValue(slot)) { + slot++; // Move to the next slot + } + slotMap.put(entry.getKey(), slot); + slot++; + } + + activeItems = slotMap; + } + + private void saveActiveItems() { if(getDataManager() != null){ - getDataManager().getSettings().getData().addProperty(item.getModernType(), true); - getDataManager().save(); + for (Map.Entry entry : activeItems.entrySet()) { + getDataManager().getSettings().getData().addProperty(entry.getKey().getModernType(), entry.getValue()); + } + getDataManager().save(); } } + public void addActiveItem(Item item) { + internalAddActiveItem(item); + saveActiveItems(); + } + public void removeActiveItem(Item item) { activeItems.remove(item); + adjustSlots(); if(getDataManager() != null){ - getDataManager().getSettings().getData().addProperty(item.getModernType(), false); - getDataManager().save(); + getDataManager().getSettings().getData().remove(item.getModernType()); + saveActiveItems(); } } public boolean isActiveItem(Item item) { - return activeItems.contains(item); + return activeItems.containsKey(item); + } + + // Get the slot of an item + public int getSlot(Item item) { + return activeItems.getOrDefault(item, -1); + } + + // Has slot + public boolean hasSlot(int slot) { + return activeItems.containsValue(slot); } + /** + * @return List of active items sorted by slot + */ public List getActiveItems() { - return activeItems; + return activeItems.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getValue)).map(Map.Entry::getKey).collect(Collectors.toList()); } public int getWithdrawAmount() { diff --git a/core/src/main/java/ml/volder/transporter/modules/guimodules/ModuleRegistry.java b/core/src/main/java/ml/volder/transporter/modules/guimodules/ModuleRegistry.java index 05efc52..b9fcd3d 100644 --- a/core/src/main/java/ml/volder/transporter/modules/guimodules/ModuleRegistry.java +++ b/core/src/main/java/ml/volder/transporter/modules/guimodules/ModuleRegistry.java @@ -32,7 +32,7 @@ private boolean isActiveOnCurrentServer() { public ModuleRegistry(GuiModulesModule guiModulesModule) { this.guiModulesModule = guiModulesModule; - NO_DATA_TRANSLATION = I18n.translate("transporter.guiModules.nodata"); + NO_DATA_TRANSLATION = I18n.translate("sa-transporter.guiModules.nodata"); ModuleSystem.shouldRenderPredicate = () -> guiModulesModule.isFeatureActive() && TransporterAddon.isEnabled() && isActiveOnCurrentServer(); } @@ -52,7 +52,7 @@ public void registerModules() { itemAmountCategory, item.getMaterial(), s -> { - if(!ModuleManager.getInstance().getModule(AutoTransporter.class).hasTransporterData()) + if(!TransporterAddon.getInstance().getTransporterItemManager().hasTransporterData()) return NO_DATA_TRANSLATION; return ModuleManager.getInstance().getModule(MessagesModule.class).isFeatureActive() ? (item.getAmountInTransporter() == null ? "0" : FormatingUtils.formatNumber(item.getAmountInTransporter())) : "Besked featuren er deaktiveret!"; } @@ -67,14 +67,14 @@ public void registerModules() { itemValueCategory, item.getMaterial(), s -> { - if(!ModuleManager.getInstance().getModule(AutoTransporter.class).hasTransporterData()) + if(!TransporterAddon.getInstance().getTransporterItemManager().hasTransporterData()) return NO_DATA_TRANSLATION; return ModuleManager.getInstance().getModule(MessagesModule.class).isFeatureActive() ? (item.getAmountInTransporter() == null ? "0 EMs" : FormatingUtils.formatNumber((long)((item.getAmountInTransporter().doubleValue() / 6400) * item.getSellValue().doubleValue())) + " EMs" ) - : I18n.translate("transporter.guiModules.messageFeatureInactive"); + : I18n.translate("sa-transporter.guiModules.messageFeatureInactive"); } ); } @@ -86,7 +86,7 @@ public void registerModules() { otherCategory, Material.DIODE, s -> { - if(!ModuleManager.getInstance().getModule(AutoTransporter.class).hasTransporterData()) + if(!TransporterAddon.getInstance().getTransporterItemManager().hasTransporterData()) return NO_DATA_TRANSLATION; return ModuleManager.getInstance().getModule(AutoTransporter.class).isFeatureActive() && ModuleManager.getInstance().getModule(AutoTransporter.class).isEnabled() ? ModColor.GREEN + "Til" : ModColor.RED + "Fra"; } @@ -99,7 +99,7 @@ public void registerModules() { otherCategory, Material.REDSTONE_LAMP, s -> { - if(!ModuleManager.getInstance().getModule(AutoTransporter.class).hasTransporterData()) + if(!TransporterAddon.getInstance().getTransporterItemManager().hasTransporterData()) return NO_DATA_TRANSLATION; return ModuleManager.getInstance().getModule(AutoGetModule.class).isFeatureActive() && ModuleManager.getInstance().getModule(AutoGetModule.class).isEnabled() ? ModColor.GREEN + "Til" : ModColor.RED + "Fra"; } @@ -113,8 +113,8 @@ public void registerModules() { Material.EMERALD, s -> { if(!ModuleManager.getInstance().getModule(MessagesModule.class).isFeatureActive()) - return I18n.translate("transporter.guiModules.messageFeatureInactive"); - if(!ModuleManager.getInstance().getModule(AutoTransporter.class).hasTransporterData()) + return I18n.translate("sa-transporter.guiModules.messageFeatureInactive"); + if(!TransporterAddon.getInstance().getTransporterItemManager().hasTransporterData()) return NO_DATA_TRANSLATION; double value = 0; for(Item item : TransporterAddon.getInstance().getTransporterItemManager().getItemList()) { @@ -134,7 +134,7 @@ public void registerModules() { Material.EMERALD, s -> ModuleManager.getInstance().getModule(BalanceModule.class).isFeatureActive() ? FormatingUtils.formatNumber(ModuleManager.getInstance().getModule(BalanceModule.class).getBalance().longValue()) + " EMs" - : I18n.translate("transporter.guiModules.balanceFeatureInactive") + : I18n.translate("sa-transporter.guiModules.balanceFeatureInactive") ); ModuleSystem.registerModule( @@ -145,7 +145,7 @@ public void registerModules() { Material.OAK_SIGN, s -> ModuleManager.getInstance().getModule(SignToolsModule.class).isFeatureActive() ? ModuleManager.getInstance().getModule(SignToolsModule.class).isOpenSignEditor() ? ModColor.GREEN + "Ja" : ModColor.RED + "Nej" - : I18n.translate("transporter.guiModules.signtoolsFeatureInactive") + : I18n.translate("sa-transporter.guiModules.signtoolsFeatureInactive") ); } diff --git a/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/McmmoManager.java b/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/McmmoManager.java index 6ccb10e..7b599f4 100644 --- a/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/McmmoManager.java +++ b/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/McmmoManager.java @@ -22,8 +22,8 @@ public McmmoManager(DataManager dataManager) { } public void init() { - mcmmoSkills.add(new AbilitySkill("Excavation", "**GIGA DRILL BREAKER ACTIVATED**", dataManager).setIcon(Material.DIAMOND_SHOVEL)); - mcmmoSkills.add(new AbilitySkill("Woodcutting", "**TREE FELLER ACTIVATED**",dataManager).setIcon(Material.DIAMOND_AXE)); + mcmmoSkills.add(new AbilitySkill("Excavation", "§a**GIGA DRILL BREAKER ACTIVATED**", dataManager).setIcon(Material.DIAMOND_SHOVEL)); + mcmmoSkills.add(new AbilitySkill("Woodcutting", "§a**TREE FELLER ACTIVATED**",dataManager).setIcon(Material.DIAMOND_AXE)); mcmmoSkills.add(new SimpleSkill("Repair", dataManager).setIcon(Material.ANVIL)); mcmmoSkills.add(new SimpleSkill("Acrobatics", dataManager).setIcon(Material.LEATHER_BOOTS)); mcmmoSkills.add(new SimpleSkill("Alchemy", dataManager).setIcon(Material.BREWING_STAND)); @@ -31,7 +31,7 @@ public void init() { mcmmoSkills.add(new SimpleSkill("Axes", dataManager).setIcon(Material.DIAMOND_AXE)); mcmmoSkills.add(new SimpleSkill("Fishing", dataManager).setIcon(Material.FISHING_ROD)); mcmmoSkills.add(new SimpleSkill("Herbalism", dataManager).setIcon(Material.SPIDER_EYE)); - mcmmoSkills.add(new AbilitySkill("Mining", "**SUPER BREAKER ACTIVATED**",dataManager).setIcon(Material.DIAMOND_PICKAXE)); + mcmmoSkills.add(new AbilitySkill("Mining", "§a**SUPER BREAKER ACTIVATED**",dataManager).setIcon(Material.DIAMOND_PICKAXE)); mcmmoSkills.add(new SimpleSkill("Swords", dataManager).setIcon(Material.DIAMOND_SWORD)); mcmmoSkills.add(new SimpleSkill("Taming", dataManager).setIcon(Material.SADDLE)); mcmmoSkills.add(new SimpleSkill("Unarmed", dataManager).setIcon(Material.STICK)); @@ -45,9 +45,9 @@ public McmmoSkill getSkillById(String id) { return null; } - public void onMessageReceive(ClientMessageEvent event) { - final Pattern pattern = Pattern.compile("([a-zA-Z]+) skill increased by 1\\. Total \\(([^)]*)\\)"); - final Matcher matcher = pattern.matcher(event.getCleanMessage()); + public void onMessageReceive(String clean) { + final Pattern pattern = Pattern.compile("§l([a-zA-Z]+) increased to §r§a§l([^)]*)§r§f"); + final Matcher matcher = pattern.matcher(clean); if (matcher.find()) { String numString = matcher.group(2).replace(",", ""); int num = Integer.parseInt(numString); @@ -57,7 +57,7 @@ public void onMessageReceive(ClientMessageEvent event) { } for (McmmoSkill mcmmoSkill : mcmmoSkills) - mcmmoSkill.onChatMessageReceive(event); + mcmmoSkill.onChatMessageReceive(clean); } public void registerModules() { diff --git a/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/McmmoSkill.java b/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/McmmoSkill.java index 1436a4b..aac7462 100644 --- a/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/McmmoSkill.java +++ b/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/McmmoSkill.java @@ -7,7 +7,7 @@ public interface McmmoSkill { int getLevel(); String getId(); - default void onChatMessageReceive(ClientMessageEvent event) {} + default void onChatMessageReceive(String clean) {} default void registerModules(Object category) {} default void registerModules(Object category, Object powerupCategory) { diff --git a/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/skills/AbilitySkill.java b/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/skills/AbilitySkill.java index d2978c7..4ab3563 100644 --- a/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/skills/AbilitySkill.java +++ b/core/src/main/java/ml/volder/transporter/modules/mcmmomodule/skills/AbilitySkill.java @@ -30,8 +30,8 @@ private void activatePowerUp() { } @Override - public void onChatMessageReceive(ClientMessageEvent event) { - if(event.getCleanMessage().equals(activatedMessage)) { + public void onChatMessageReceive(String clean) { + if(clean.equals(activatedMessage)) { powerUpDuration = (Math.floor((double) level / 50)) + 2; activatePowerUp(); } diff --git a/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterInfoHandler.java b/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterInfoHandler.java index 136eb46..7f44ae1 100644 --- a/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterInfoHandler.java +++ b/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterInfoHandler.java @@ -30,7 +30,7 @@ public boolean messageReceived(String msg, String clean) { for(Item item : TransporterAddon.getInstance().getTransporterItemManager().getItemList()){ if(Parser.parseFormattedItemName(matcher.group("item")).equals(item.getModernType())){ item.setAmountInTransporter(Parser.parseInt(matcher.group("amount"))); - ModuleManager.getInstance().getModule(AutoTransporter.class).transporterInfoSet(); + TransporterAddon.getInstance().getTransporterItemManager().transporterInfoSet(); return false; } } diff --git a/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterMiscellaneousMessageHandler.java b/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterMiscellaneousMessageHandler.java new file mode 100644 index 0000000..d8ac741 --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterMiscellaneousMessageHandler.java @@ -0,0 +1,63 @@ +package ml.volder.transporter.modules.messagemodule; + +import ml.volder.transporter.modules.MessagesModule; +import ml.volder.unikapi.api.player.PlayerAPI; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class TransporterMiscellaneousMessageHandler implements IMessageHandler { + + MessagesModule module; + + public TransporterMiscellaneousMessageHandler(MessagesModule module) { + this.module = module; + } + + @Override + public boolean messageReceived(String msg, String clean) { + boolean result = autoTransporterOn(clean); + boolean result2 = autoTransporterOff(clean); + + return result || result2; + } + + private boolean autoTransporterOn(String clean){ + final Pattern pattern = Pattern.compile(module.getRegexByMessageId("autotransporter_on")); + final Matcher matcher = pattern.matcher(clean); + if (matcher.find()) { + MessageModes mode = module.getMessageMode(); + if(mode == MessageModes.NO_MESSAGES){ + return true; + }else if(mode == MessageModes.CHAT_MESSAGES){ + PlayerAPI.getAPI().displayChatMessage(module.getMessage(module.getRawMessage("autoTransporterOn"), null, null, null)); + return true; + }else if(mode == MessageModes.ACTIONBAR_MESSAGES){ + PlayerAPI.getAPI().displayActionBarMessage(module.getMessage(module.getRawMessage("autoTransporterOn"), null, null, null)); + return true; + } + } + return false; + } + + private boolean autoTransporterOff(String clean){ + final Pattern pattern = Pattern.compile(module.getRegexByMessageId("autotransporter_off")); + final Matcher matcher = pattern.matcher(clean); + if (matcher.find()) { + MessageModes mode = module.getMessageMode(); + if(mode == MessageModes.NO_MESSAGES){ + return true; + }else if(mode == MessageModes.CHAT_MESSAGES){ + PlayerAPI.getAPI().displayChatMessage(module.getMessage(module.getRawMessage("autoTransporterOff"), null, null, null)); + return true; + }else if(mode == MessageModes.ACTIONBAR_MESSAGES){ + PlayerAPI.getAPI().displayActionBarMessage(module.getMessage(module.getRawMessage("autoTransporterOff"), null, null, null)); + return true; + } + } + return false; + } + + + +} diff --git a/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterPutMessageHandler.java b/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterPutMessageHandler.java index 10c5fbc..83d2378 100644 --- a/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterPutMessageHandler.java +++ b/core/src/main/java/ml/volder/transporter/modules/messagemodule/TransporterPutMessageHandler.java @@ -6,6 +6,7 @@ import ml.volder.transporter.modules.MessagesModule; import ml.volder.transporter.modules.MessagesModule.LatestTitle; import ml.volder.transporter.modules.ModuleManager; +import ml.volder.transporter.utils.FormatingUtils; import ml.volder.transporter.utils.Parser; import ml.volder.unikapi.api.player.PlayerAPI; @@ -25,10 +26,13 @@ public TransporterPutMessageHandler(MessagesModule module) { public boolean messageReceived(String msg, String clean) { boolean result = matchPutManglerMessage(clean); boolean result2 = matchPutSuccessMessage(clean); - boolean result3 = matchPutMineTitle(clean); - boolean result4 = matchPutMineMessage(clean); + boolean result3 = matchPutMineMessage(clean); + boolean result4 = matchPutAllTitle(clean); - return result || result2 || result3 || result4; + if(!result3) + totalAdded = 0; + + return result || result2 || result3 || result4; } private boolean matchPutManglerMessage(String clean){ @@ -76,29 +80,47 @@ private boolean matchPutSuccessMessage(String clean){ return false; } + int totalAdded = 0; + private boolean matchPutMineMessage(String clean){ //TODO lav besked i actionbar - if(ModuleManager.getInstance().getModule(MessagesModule.class).LAST_TITLE != LatestTitle.TRANSPORTER_PUT_MINE) - return false; final Pattern pattern = Pattern.compile(module.getRegexByMessageId("put_mine_entry")); final Matcher matcher = pattern.matcher(clean); if (matcher.find()) { for(Item item : TransporterAddon.getInstance().getTransporterItemManager().getItemList()){ if(Parser.parseFormattedItemName(matcher.group("item")).equals(item.getModernType())){ - item.setAmountInTransporter((item.getAmountInTransporter() + Parser.parseInt(matcher.group("amount")))); - return ModuleManager.getInstance().getModule(AutoTransporter.class).isEnabled(); + item.setAmountInTransporter((Parser.parseInt(matcher.group("total")))); + totalAdded += Parser.parseInt(matcher.group("amount")); + + MessageModes mode = module.getMessageMode(); + if(mode == MessageModes.NO_MESSAGES){ + return true; + }else if(mode == MessageModes.CHAT_MESSAGES){ + return false; + } + + PlayerAPI.getAPI().displayActionBarMessage(module.getMessage(module.getRawMessage("putAllMessage"), null, FormatingUtils.formatNumber(totalAdded), null)); + return true; } } } return false; } - private boolean matchPutMineTitle(String clean){ - final Pattern pattern = Pattern.compile(module.getRegexByMessageId("put_mine_title")); + private boolean matchPutAllTitle(String clean) { + final Pattern pattern = Pattern.compile(module.getRegexByMessageId("put_all")); final Matcher matcher = pattern.matcher(clean); - boolean result = matcher.find(); - if(result) - ModuleManager.getInstance().getModule(MessagesModule.class).LAST_TITLE = LatestTitle.TRANSPORTER_PUT_MINE; - return result && ModuleManager.getInstance().getModule(AutoTransporter.class).isEnabled(); + if (matcher.find()) { + MessageModes mode = module.getMessageMode(); + if(mode == MessageModes.NO_MESSAGES) { + return true; + }else if(mode == MessageModes.ACTIONBAR_MESSAGES){ + return true; + }else if(mode == MessageModes.CHAT_MESSAGES){ + return false; + } + } + return false; } + } diff --git a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenu.java b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenu.java index f582fac..ff51d89 100644 --- a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenu.java +++ b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenu.java @@ -1,6 +1,7 @@ package ml.volder.transporter.modules.transportermenumodule; import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.gui.elements.ScrollableGrid; import ml.volder.transporter.modules.ModuleManager; import ml.volder.transporter.modules.TransporterMenuModule; import ml.volder.unikapi.api.draw.DrawAPI; @@ -20,15 +21,17 @@ public class TransporterMenu extends WrappedGuiScreen { private int entryWidth = 120; private int entryHeight = 37; - private Scrollbar scrollbar = new Scrollbar(entryHeight); + private List itemEntries = new ArrayList<>(); + private ScrollableGrid scrollableGrid = new ScrollableGrid(0, 0, 0, 0, entryWidth, entryHeight, 2, 2); - private List itemEntries = new ArrayList<>(); private WrappedGuiButton buttonMenuOptions; - private void createButton() { + + private void createButtons() { this.buttonMenuOptions = new WrappedGuiButton(11, 0, 0, 23, 20, ""); + this.addButton(new WrappedGuiButton(12, this.getWidth() - 28 - 80, this.getHeight() - 25, 75, 20, "Ændre layout")); } private void renderButtonMenuOptions(int mouseX, int mouseY) { @@ -38,7 +41,7 @@ private void renderButtonMenuOptions(int mouseX, int mouseY) { this.buttonMenuOptions.drawButton(mouseX, mouseY); DrawAPI drawAPI = DrawAPI.getAPI(); drawAPI.bindTexture(ModTextures.BUTTON_ADVANCED); - drawAPI.drawTexture((double)(this.buttonMenuOptions.getX() + 4), (double)(this.buttonMenuOptions.getY() + 3), 0.0, 0.0, 256.0, 256.0, 14.0, 14.0, 2.0F); + drawAPI.drawTexture(this.buttonMenuOptions.getX() + 4, this.buttonMenuOptions.getY() + 3, 0.0, 0.0, 256.0, 256.0, 14.0, 14.0, 2.0F); } @Override @@ -52,9 +55,11 @@ public void initGui() { for(Item item : ModuleManager.getInstance().getModule(TransporterMenuModule.class).getActiveItems()) { itemEntries.add(new TransporterMenuEntry(item, entryWidth, entryHeight)); } - this.scrollbar.setSpeed(39); - this.scrollbar.init(); - createButton(); + createButtons(); + + scrollableGrid.initGui(); + scrollableGrid.updateGridSize(getWidth(), getHeight() - 90, 0, 45); + scrollableGrid.updateEntries(itemEntries); } @Override @@ -62,40 +67,7 @@ public void drawScreen(int mouseX, int mouseY, float partialTicks) { DrawAPI drawAPI = DrawAPI.getAPI(); drawAPI.drawAutoDimmedBackground(0); - double emptySpaceWidth = getWidth(); - int entryAmountHorizontal = (int)Math.floor(emptySpaceWidth / (entryWidth + 2)); - double entriesWidth = entryAmountHorizontal * (entryWidth + 2); - double startX = (emptySpaceWidth - entriesWidth) / 2; - double currentX = startX; - - double startY = 45; - int rows = (int)Math.ceil((double)itemEntries.size() / (double)entryAmountHorizontal); - - //Only draw the entries that are visible - int scrollY = (int)this.scrollbar.getScrollY(); - int outOfViewEntryRows = Math.abs(scrollY) / (entryHeight + 2); - int inViewEntryRows = (getHeight() - 90) / (entryHeight + 2) + 1; - int outOfViewAmount = entryAmountHorizontal * outOfViewEntryRows; - int visibleEntriesAmount = entryAmountHorizontal * inViewEntryRows; - - int firstIndex = Math.max(Math.min(outOfViewAmount, itemEntries.size() - visibleEntriesAmount), 0); - int lastIndex = Math.max(Math.min(outOfViewAmount + visibleEntriesAmount, itemEntries.size()),0); - - List visibleEntries = itemEntries.subList(firstIndex, lastIndex); - - if(lastIndex == itemEntries.size() && lastIndex > visibleEntriesAmount) { - startY -= (getHeight() - 90); - startY -= Math.abs(scrollY) - (lastIndex / entryAmountHorizontal) * (entryHeight + 2); - } - - for(TransporterMenuEntry entry : visibleEntries) { - if(currentX + entryWidth >= startX + entriesWidth) { - currentX = startX; - startY += entryHeight + 2; - } - entry.draw((int)currentX, (int)(startY), mouseX, mouseY); - currentX += entryWidth + 2; - } + scrollableGrid.render(mouseX, mouseY); drawAPI.drawOverlayBackground(0, 41); drawAPI.drawGradientShadowTop(41.0, 0.0, this.getWidth()); @@ -103,32 +75,21 @@ public void drawScreen(int mouseX, int mouseY, float partialTicks) { drawAPI.drawGradientShadowBottom(this.getHeight() - 40, 0.0, this.getWidth()); drawAPI.drawCenteredString(ModColor.cl("a")+ModColor.cl("l")+"Transporter Menu", (double)(this.getWidth() / 2), 20.0D, 2.0D); - this.scrollbar.setPosition(startX + entriesWidth + 3, 43, startX + entriesWidth + 6, getHeight() - 42); - this.scrollbar.update(rows + 5); - - if(rows < inViewEntryRows){ - this.scrollbar.update(0); - } - - this.scrollbar.draw(); - renderButtonMenuOptions(mouseX, mouseY); - for(TransporterMenuEntry entry : visibleEntries) { - entry.drawHoverText(); - } + scrollableGrid.renderHoverText(); } @Override public void actionPerformed(WrappedGuiButton button) { - + if(button.getId() == 12) { + PlayerAPI.getAPI().openGuiScreen(new TransporterMenuLayout()); + } } @Override public void mouseClicked(int mouseX, int mouseY, MouseButton mouseButton) { - if(mouseY > 41 && mouseY < getHeight() - 40) - itemEntries.forEach(transporterMenuEntry -> transporterMenuEntry.mouseClicked(mouseX, mouseY, mouseButton)); - this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.CLICKED); + this.scrollableGrid.mouseClicked(mouseX, mouseY, mouseButton); if(buttonMenuOptions.isEnabled() && buttonMenuOptions.isMouseOver()) { PlayerAPI.getAPI().openGuiScreen(new TransporterMenuSettingsGui()); @@ -137,17 +98,17 @@ public void mouseClicked(int mouseX, int mouseY, MouseButton mouseButton) { @Override public void mouseClickMove(int mouseX, int mouseY, MouseButton clickedMouseButton, long timeSinceLastClick) { - this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.DRAGGING); + this.scrollableGrid.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); } @Override public void mouseReleased(int mouseX, int mouseY, MouseButton mouseButton) { - this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.RELEASED); + this.scrollableGrid.mouseReleased(mouseX, mouseY, mouseButton); } @Override public void handleMouseInput() { - this.scrollbar.mouseInput(); + this.scrollableGrid.handleMouseInput(); } @Override diff --git a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuEntry.java b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuEntry.java index e5d2e21..c73907b 100644 --- a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuEntry.java +++ b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuEntry.java @@ -1,6 +1,7 @@ package ml.volder.transporter.modules.transportermenumodule; import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.gui.elements.ScrollableGrid; import ml.volder.transporter.modules.MessagesModule; import ml.volder.transporter.modules.ModuleManager; import ml.volder.transporter.modules.TransporterMenuModule; @@ -15,7 +16,7 @@ import java.util.Collections; -public class TransporterMenuEntry { +public class TransporterMenuEntry extends ScrollableGrid.Entry{ private int width = 120; private int height = 37; @@ -32,7 +33,7 @@ public TransporterMenuEntry(Item item, int width, int height) { this.height = height; } - public void draw(int x, int y, int mouseX, int mouseY) { + public void render(int x, int y, int mouseX, int mouseY) { hoverText = null; hoverTextX = -1000; hoverTextY = -1000; @@ -72,7 +73,7 @@ public void draw(int x, int y, int mouseX, int mouseY) { private int hoverTextX = -1000; private int hoverTextY = -1000; - public void drawHoverText() { + public void renderHoverText() { if(hoverText == null || hoverTextX == -1000 || hoverTextY == -1000) return; DrawAPI.getAPI().drawHoverText(Collections.singletonList(hoverText), hoverTextX, hoverTextY); @@ -101,14 +102,13 @@ public void mouseClicked(int mouseX, int mouseY, MouseButton mouseButton) { return; if(hoverGetButton) { if(InputAPI.getAPI().isShiftKeyDown()) { - PlayerAPI.getAPI().sendCommand("transporter get " + item.getModernType()); + item.get(-1); } else { - PlayerAPI.getAPI().sendCommand("transporter get " + item.getModernType() + " " + ModuleManager.getInstance().getModule(TransporterMenuModule.class).getWithdrawAmount()); - + item.get(ModuleManager.getInstance().getModule(TransporterMenuModule.class).getWithdrawAmount()); } PlayerAPI.getAPI().openGuiScreen(null); }else if (hoverPutButton) { - PlayerAPI.getAPI().sendCommand("transporter put " + item.getModernType()); + item.put(-1); PlayerAPI.getAPI().openGuiScreen(null); } } diff --git a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuLayout.java b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuLayout.java new file mode 100644 index 0000000..78a8a47 --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuLayout.java @@ -0,0 +1,106 @@ +package ml.volder.transporter.modules.transportermenumodule; + +import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.gui.elements.ScrollableGrid; +import ml.volder.transporter.modules.ModuleManager; +import ml.volder.transporter.modules.TransporterMenuModule; +import ml.volder.unikapi.api.draw.DrawAPI; +import ml.volder.unikapi.api.player.PlayerAPI; +import ml.volder.unikapi.guisystem.ModTextures; +import ml.volder.unikapi.keysystem.Key; +import ml.volder.unikapi.keysystem.MouseButton; +import ml.volder.unikapi.types.ModColor; +import ml.volder.unikapi.wrappers.guibutton.WrappedGuiButton; +import ml.volder.unikapi.wrappers.guiscreen.WrappedGuiScreen; + +import java.util.ArrayList; +import java.util.List; + +public class TransporterMenuLayout extends WrappedGuiScreen { + + private int entryWidth = 120; + private int entryHeight = 37; + private List itemEntries = new ArrayList<>(); + private ScrollableGrid scrollableGrid = new ScrollableGrid(0, 0, 0, 0, entryWidth, entryHeight, 2, 2); + private boolean flagChanged = false; + + @Override + public void updateScreen() { + + } + + @Override + public void initGui() { + itemEntries.clear(); + for(Item item : ModuleManager.getInstance().getModule(TransporterMenuModule.class).getActiveItems()) { + itemEntries.add(new TransporterMenuLayoutEntry(item, entryWidth, entryHeight, this)); + } + + scrollableGrid.initGui(); + scrollableGrid.updateGridSize(getWidth(), getHeight() - 90, 0, 45); + scrollableGrid.updateEntries(itemEntries); + + addButton(new WrappedGuiButton(1, 20, 20, 22, 20, "<")); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + if(flagChanged) { + initGui(); + flagChanged = false; + } + DrawAPI drawAPI = DrawAPI.getAPI(); + drawAPI.drawAutoDimmedBackground(0); + + scrollableGrid.render(mouseX, mouseY); + + drawAPI.drawOverlayBackground(0, 41); + drawAPI.drawGradientShadowTop(41.0, 0.0, this.getWidth()); + drawAPI.drawOverlayBackground(this.getHeight() - 40, this.getHeight()); + drawAPI.drawGradientShadowBottom(this.getHeight() - 40, 0.0, this.getWidth()); + drawAPI.drawCenteredString(ModColor.cl("a")+ModColor.cl("l")+"Transporter Menu", (double)(this.getWidth() / 2), 20.0D, 2.0D); + + scrollableGrid.renderHoverText(); + } + + @Override + public void actionPerformed(WrappedGuiButton button) { + if(button.getId() == 1) { + PlayerAPI.getAPI().openGuiScreen(new TransporterMenu()); + } + } + + @Override + public void mouseClicked(int mouseX, int mouseY, MouseButton mouseButton) { + this.scrollableGrid.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + public void mouseClickMove(int mouseX, int mouseY, MouseButton clickedMouseButton, long timeSinceLastClick) { + this.scrollableGrid.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); + } + + @Override + public void mouseReleased(int mouseX, int mouseY, MouseButton mouseButton) { + this.scrollableGrid.mouseReleased(mouseX, mouseY, mouseButton); + } + + @Override + public void handleMouseInput() { + this.scrollableGrid.handleMouseInput(); + } + + @Override + public void keyTyped(char typedChar, Key key) { + + } + + @Override + public void onGuiClosed() { + + } + + public void flagChanged() { + flagChanged = true; + } +} diff --git a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuLayoutEntry.java b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuLayoutEntry.java new file mode 100644 index 0000000..d746a72 --- /dev/null +++ b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuLayoutEntry.java @@ -0,0 +1,128 @@ +package ml.volder.transporter.modules.transportermenumodule; + +import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.gui.elements.ScrollableGrid; +import ml.volder.transporter.modules.ModuleManager; +import ml.volder.transporter.modules.TransporterMenuModule; +import ml.volder.unikapi.api.draw.DrawAPI; +import ml.volder.unikapi.keysystem.MouseButton; +import ml.volder.unikapi.types.ModColor; +import ml.volder.unikapi.types.ResourceLocation; + +import java.util.Collections; + +public class TransporterMenuLayoutEntry extends ScrollableGrid.Entry { + private int width; + private int height; + + private int outlineWidth = 1; + + private Item item; + + private boolean hoverLeftButton = false; + private boolean hoverTrashButton = false; + private boolean hoverRightButton = false; + private boolean isUpdating = false; + + private TransporterMenuLayout backgroundScreen; + + public TransporterMenuLayoutEntry(Item item, int width, int height, TransporterMenuLayout backgroundScreen) { + this.item = item; + this.width = width; + this.height = height; + this.backgroundScreen = backgroundScreen; + } + + public void render(int x, int y, int mouseX, int mouseY) { + hoverText = null; + hoverTextX = -1000; + hoverTextY = -1000; + if(item == null) + return; + boolean isMouseOver = mouseX > x && mouseX < x + width && mouseY > y && mouseY < y + height; + DrawAPI drawAPI = DrawAPI.getAPI(); + + int color = !item.getAutoUpdateSellValue() + ? ModColor.toRGB(100, 50, 50, isMouseOver ? 90 : 70) + : ModColor.toRGB(50, 100, 50, isMouseOver ? 90 : 70); + + if(isUpdating) + color = ModColor.toRGB(150, 90, 50, isMouseOver ? 90 : 70); + + drawAPI.drawRect(x, y, x + width, y + height, color); + drawAPI.drawRect(x, y, x + width, y + outlineWidth, ModColor.toRGB(128,128, 128, 255)); + drawAPI.drawRect(x, y + height - outlineWidth, x + width, y + height, ModColor.toRGB(128,128, 128, 255)); + drawAPI.drawRect(x, y, x + outlineWidth, y + height, ModColor.toRGB(128,128, 128, 255)); + drawAPI.drawRect(x + width - outlineWidth, y, x + width, y + height, ModColor.toRGB(128,128, 128, 255)); + + drawAPI.drawItem(item.getMaterial(), item.getItemDamage(), x + 2, y + 3, "", 2); + drawAPI.drawString(item.getDisplayName().length() >= 15 ? item.getDisplayName().substring(0, 14) : item.getDisplayName(), x + 32 + 4, y + 5, 0xFFFFFF); + this.hoverLeftButton = this.drawButton(new ResourceLocation("transporter/textures/buttons/left-arrow.png"), x + 36 ,y + 22, 12, mouseX, mouseY); + this.hoverTrashButton = this.drawButton(new ResourceLocation("transporter/textures/buttons/trash.png"), x + 52 ,y + 22, 12, mouseX, mouseY); + this.hoverRightButton = this.drawButton(new ResourceLocation("transporter/textures/buttons/right-arrow.png"), x + 52 + 16 ,y + 22, 12, mouseX, mouseY); + + + + if(hoverLeftButton || hoverTrashButton || hoverRightButton) { + hoverText = hoverTrashButton ? "Klik her for at fjerne " + item.getDisplayName() + " fra transporter menuen." : hoverText; + hoverText = hoverLeftButton ? "Klik her for at flytte " + item.getDisplayName() + " til venstre." : hoverText; + hoverText = hoverRightButton ? "Klik her for at flytte " + item.getDisplayName() + " til højre." : hoverText; + hoverTextX = mouseX; + hoverTextY = mouseY; + } + } + + private String hoverText = null; + private int hoverTextX = -1000; + private int hoverTextY = -1000; + + public void renderHoverText() { + if(hoverText == null || hoverTextX == -1000 || hoverTextY == -1000) + return; + DrawAPI.getAPI().drawHoverText(Collections.singletonList(hoverText), hoverTextX, hoverTextY); + } + + private boolean drawButton(ResourceLocation resourceLocation, int x, int y, int buttonSize, int mouseX, int mouseY) { + DrawAPI drawAPI = DrawAPI.getAPI(); + boolean hover = mouseX > x && mouseX < x + buttonSize && mouseY > y && mouseY < y + buttonSize; + int colorA = hover ? ModColor.toRGB(10, 10, 10, 255) : ModColor.toRGB(220, 220, 220, 255); + int colorB = hover ? ModColor.toRGB(150, 150, 150, 255) : ModColor.toRGB(0, 0, 0, 255); + int colorC = hover ? ModColor.toRGB(150, 150, 150, 255) : ModColor.toRGB(180, 180, 180, 255); + drawAPI.drawRectangle(x, y, x + buttonSize, y + buttonSize, colorA); + drawAPI.drawRectangle(x + 1, y + 1, x+ buttonSize + 1, y + buttonSize + 1, colorB); + drawAPI.drawRectangle(x + 1, y + 1, x + buttonSize, y + buttonSize, colorC); + if(resourceLocation != null) { + drawAPI.bindTexture(resourceLocation); + drawAPI.drawTexture(x + (hover ? 1 : 0), y + (hover ? 1 : 0), 256.0D, 256.0D, buttonSize, buttonSize, 0.8F); + } + return hover; + } + + public void mouseClicked(int mouseX, int mouseY, MouseButton mouseButton) { + if(!mouseButton.isLeft()) + return; + if(hoverLeftButton) { + TransporterMenuModule module = ModuleManager.getInstance().getModule(TransporterMenuModule.class); + //Move left + int slot = module.getSlot(item); + int newSlot = slot - 1; + if(newSlot < 0) + return; + ModuleManager.getInstance().getModule(TransporterMenuModule.class).swap(slot, newSlot); + backgroundScreen.flagChanged(); + }else if(hoverTrashButton) { + //Remove item + ModuleManager.getInstance().getModule(TransporterMenuModule.class).removeActiveItem(item); + backgroundScreen.flagChanged(); + }else if (hoverRightButton) { + TransporterMenuModule module = ModuleManager.getInstance().getModule(TransporterMenuModule.class); + //Move right + int slot = module.getSlot(item); + int newSlot = slot + 1; + if(!module.hasSlot(newSlot)) + return; + ModuleManager.getInstance().getModule(TransporterMenuModule.class).swap(slot, newSlot); + backgroundScreen.flagChanged(); + } + } +} diff --git a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuSettingsGui.java b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuSettingsGui.java index 75810d6..67481df 100644 --- a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuSettingsGui.java +++ b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterMenuSettingsGui.java @@ -2,8 +2,10 @@ import ml.volder.transporter.TransporterAddon; import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.gui.elements.ScrollableGrid; import ml.volder.unikapi.api.draw.DrawAPI; import ml.volder.unikapi.api.player.PlayerAPI; +import ml.volder.unikapi.guisystem.elements.ModTextField; import ml.volder.unikapi.guisystem.elements.Scrollbar; import ml.volder.unikapi.keysystem.Key; import ml.volder.unikapi.keysystem.MouseButton; @@ -18,10 +20,12 @@ public class TransporterMenuSettingsGui extends WrappedGuiScreen { private int entryWidth = 120; private int entryHeight = 37; - private Scrollbar scrollbar = new Scrollbar(entryHeight); - private List itemEntries = new ArrayList<>(); + private List itemEntries = new ArrayList<>(); + private ScrollableGrid scrollableGrid = new ScrollableGrid(0, 0, 0, 0, entryWidth, entryHeight, 2, 2); private WrappedGuiButton buttonBack; + private ModTextField searchField; + private String searchText = ""; @Override public void updateScreen() { @@ -34,66 +38,47 @@ public void initGui() { for(Item item : TransporterAddon.getInstance().getTransporterItemManager().getItemList()) { itemEntries.add(new TransporterSettingsMenuEntry(item, entryWidth, entryHeight)); } - this.scrollbar.setSpeed(39); - this.scrollbar.init(); this.buttonBack = new WrappedGuiButton(1, 20, 20, 22, 20, "<"); this.addButton(buttonBack); + + this.searchField = new ModTextField(1000, getWidth()/2 - 100, this.getHeight() - 20 - 10, 200, 20); + searchField.setPlaceHolder("Søg efter item..."); + + scrollableGrid.initGui(); + scrollableGrid.updateGridSize(getWidth(), getHeight() - 90, 0, 45); + scrollableGrid.updateEntries(itemEntries); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { - DrawAPI drawAPI = DrawAPI.getAPI(); - drawAPI.drawAutoDimmedBackground(0); - - double emptySpaceWidth = getWidth(); - int entryAmountHorizontal = (int)Math.floor(emptySpaceWidth / (entryWidth + 2)); - double entriesWidth = entryAmountHorizontal * (entryWidth + 2); - double startX = (emptySpaceWidth - entriesWidth) / 2; - double currentX = startX; - - double startY = 45; - int rows = (int)Math.ceil((double)itemEntries.size() / (double)entryAmountHorizontal); - - //Only draw the entries that are visible - int scrollY = (int)this.scrollbar.getScrollY(); - int outOfViewEntryRows = Math.abs(scrollY) / (entryHeight + 2); - int inViewEntryRows = (getHeight() - 90) / (entryHeight + 2) + 1; - int outOfViewAmount = entryAmountHorizontal * outOfViewEntryRows; - int visibleEntriesAmount = entryAmountHorizontal * inViewEntryRows; - - int firstIndex = Math.max(Math.min(outOfViewAmount, itemEntries.size() - visibleEntriesAmount), 0); - int lastIndex = Math.max(Math.min(outOfViewAmount + visibleEntriesAmount, itemEntries.size()),0); - - List visibleEntries = itemEntries.subList(firstIndex, lastIndex); - if(lastIndex == itemEntries.size()) { - startY -= (getHeight() - 90); - startY -= Math.abs(scrollY) - (lastIndex / entryAmountHorizontal) * (entryHeight + 2); - } - - for(TransporterSettingsMenuEntry entry : visibleEntries) { - if(currentX + entryWidth >= startX + entriesWidth) { - currentX = startX; - startY += entryHeight + 2; + if(searchField != null && !searchField.getText().toLowerCase().equals(searchText)) { + searchText = searchField.getText().toLowerCase(); + itemEntries.clear(); + for(Item item : TransporterAddon.getInstance().getTransporterItemManager().getItemList()) { + if(item.getDisplayName().toLowerCase().contains(searchText) || item.getModernType().toLowerCase().contains(searchText)) + itemEntries.add(new TransporterSettingsMenuEntry(item, entryWidth, entryHeight)); } - entry.draw((int)currentX, (int)(startY), mouseX, mouseY); - currentX += entryWidth + 2; + this.scrollableGrid.resetScroll(); + this.scrollableGrid.updateEntries(itemEntries); } + DrawAPI drawAPI = DrawAPI.getAPI(); + drawAPI.drawAutoDimmedBackground(0); + + scrollableGrid.render(mouseX, mouseY); + drawAPI.drawOverlayBackground(0, 41); drawAPI.drawGradientShadowTop(41.0, 0.0, this.getWidth()); drawAPI.drawOverlayBackground(this.getHeight() - 40, this.getHeight()); drawAPI.drawGradientShadowBottom(this.getHeight() - 40, 0.0, this.getWidth()); drawAPI.drawCenteredString( - ModColor.cl("a")+ModColor.cl("l")+"Transporter Menu Settings", (double)(this.getWidth() / 2), 20.0D, 2.0D); + ModColor.cl("a")+ModColor.cl("l")+"Transporter Menu Settings", this.getWidth() / 2, 20.0D, 2.0D); - this.scrollbar.setPosition(startX + entriesWidth + 3, 43, startX + entriesWidth + 6, getHeight() - 42); - this.scrollbar.update(rows + 5); - this.scrollbar.draw(); + if(searchField != null) + searchField.drawTextBox(); - for(TransporterSettingsMenuEntry entry : visibleEntries) { - entry.drawHoverText(); - } + scrollableGrid.renderHoverText(); } @Override @@ -105,29 +90,30 @@ public void actionPerformed(WrappedGuiButton button) { @Override public void mouseClicked(int mouseX, int mouseY, MouseButton mouseButton) { - if(mouseY > 41 && mouseY < getHeight() - 40) - itemEntries.forEach(transporterMenuEntry -> transporterMenuEntry.mouseClicked(mouseX, mouseY, mouseButton)); - this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.CLICKED); + if(searchField != null) + this.searchField.mouseClicked(mouseX, mouseY, mouseButton); + scrollableGrid.mouseClicked(mouseX, mouseY, mouseButton); } @Override public void mouseClickMove(int mouseX, int mouseY, MouseButton clickedMouseButton, long timeSinceLastClick) { - this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.DRAGGING); + scrollableGrid.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); } @Override public void mouseReleased(int mouseX, int mouseY, MouseButton mouseButton) { - this.scrollbar.mouseAction(mouseX, mouseY, Scrollbar.EnumMouseAction.RELEASED); + scrollableGrid.mouseReleased(mouseX, mouseY, mouseButton); } @Override public void handleMouseInput() { - this.scrollbar.mouseInput(); + scrollableGrid.handleMouseInput(); } @Override public void keyTyped(char typedChar, Key key) { - + if(searchField != null) + searchField.textboxKeyTyped(typedChar, key); } @Override diff --git a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterSettingsMenuEntry.java b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterSettingsMenuEntry.java index 40d263a..43d4ed4 100644 --- a/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterSettingsMenuEntry.java +++ b/core/src/main/java/ml/volder/transporter/modules/transportermenumodule/TransporterSettingsMenuEntry.java @@ -1,6 +1,7 @@ package ml.volder.transporter.modules.transportermenumodule; import ml.volder.transporter.classes.items.Item; +import ml.volder.transporter.gui.elements.ScrollableGrid; import ml.volder.transporter.modules.ModuleManager; import ml.volder.transporter.modules.TransporterMenuModule; import ml.volder.unikapi.api.draw.DrawAPI; @@ -9,7 +10,7 @@ import java.util.Collections; -public class TransporterSettingsMenuEntry { +public class TransporterSettingsMenuEntry extends ScrollableGrid.Entry { private int width = 120; private int height = 37; @@ -27,7 +28,7 @@ public TransporterSettingsMenuEntry(Item item, int width, int height) { this.isActive = ModuleManager.getInstance().getModule(TransporterMenuModule.class).isActiveItem(item); } - public void draw(int x, int y, int mouseX, int mouseY) { + public void render(int x, int y, int mouseX, int mouseY) { hoverText = null; hoverTextX = -1000; hoverTextY = -1000; @@ -61,7 +62,7 @@ public void draw(int x, int y, int mouseX, int mouseY) { private int hoverTextX = -1000; private int hoverTextY = -1000; - public void drawHoverText() { + public void renderHoverText() { if(hoverText == null || hoverTextX == -1000 || hoverTextY == -1000) return; DrawAPI.getAPI().drawHoverText(Collections.singletonList(hoverText), hoverTextX, hoverTextY); diff --git a/core/src/main/java/ml/volder/transporter/settings/AdvancedConfig.java b/core/src/main/java/ml/volder/transporter/settings/AdvancedConfig.java index 8d94629..a91f0f2 100644 --- a/core/src/main/java/ml/volder/transporter/settings/AdvancedConfig.java +++ b/core/src/main/java/ml/volder/transporter/settings/AdvancedConfig.java @@ -68,4 +68,8 @@ public void openBalanceMessagesEditor(Setting setting) { ); Laby.labyAPI().minecraft().sounds().playButtonPress(); } + + @SpriteSlot(y = 7, x = 7) + @SwitchWidget.SwitchSetting(configEntryName = "useTransporterPackets") + private ConfigProperty useTransporterPackets = new ConfigProperty<>(false); } diff --git a/core/src/main/java/ml/volder/unikapi/api/draw/impl/Laby4DrawAPI.java b/core/src/main/java/ml/volder/unikapi/api/draw/impl/Laby4DrawAPI.java index 29a235e..4668e1a 100644 --- a/core/src/main/java/ml/volder/unikapi/api/draw/impl/Laby4DrawAPI.java +++ b/core/src/main/java/ml/volder/unikapi/api/draw/impl/Laby4DrawAPI.java @@ -3,6 +3,7 @@ import ml.volder.unikapi.SupportedClient; import ml.volder.unikapi.api.draw.DrawAPI; import ml.volder.unikapi.api.minecraft.MinecraftAPI; +import ml.volder.unikapi.guisystem.ModTextures; import ml.volder.unikapi.loader.Laby4Loader; import ml.volder.unikapi.types.Material; import ml.volder.unikapi.types.ResourceLocation; @@ -10,8 +11,9 @@ import net.labymod.api.client.component.Component; import net.labymod.api.client.entity.player.badge.PositionType; import net.labymod.api.client.entity.player.badge.renderer.BadgeRenderer; +import net.labymod.api.client.gfx.GFXBridge; import net.labymod.api.client.gfx.pipeline.util.MatrixTracker; -import net.labymod.api.client.gfx.texture.GFXGetTextureParameter; +import net.labymod.api.client.gfx.texture.TextureTarget; import net.labymod.api.client.gui.HorizontalAlignment; import net.labymod.api.client.gui.icon.Icon; import net.labymod.api.client.gui.screen.theme.Theme; @@ -21,6 +23,7 @@ import net.labymod.api.client.render.font.text.TextRenderer; import net.labymod.api.client.render.font.text.TextRenderer.StringStart; import net.labymod.api.client.render.matrix.Stack; +import net.labymod.api.client.resources.texture.Texture; import net.labymod.api.client.world.item.ItemStack; import net.labymod.api.util.bounds.Point; import net.labymod.api.util.bounds.Rectangle; @@ -31,6 +34,7 @@ import java.util.function.Predicate; @SupportedClient(clientBrand = "labymod4", minecraftVersion = "*") +@Deprecated(forRemoval = true) public class Laby4DrawAPI implements DrawAPI { private String namespace = Laby4Loader.namespace(); @@ -38,6 +42,8 @@ public class Laby4DrawAPI implements DrawAPI { private static Stack PREVIOUS_RENDER_STACK; private static Laby4DrawAPI instance; + private final GFXBridge gfx = Laby.references().gfxRenderPipeline().gfx(); + public static Laby4DrawAPI getAPI() { if(instance == null) instance = new Laby4DrawAPI(); @@ -78,12 +84,12 @@ public int getScaledHeight() { @Override public int getTextureWidth() { - return GFXGetTextureParameter.TEXTURE_WIDTH.getHandle(); + return gfx.getTexLevelParameterI(TextureTarget.TEXTURE_2D, 0, 4096); } @Override public int getTextureHeight() { - return GFXGetTextureParameter.TEXTURE_HEIGHT.getHandle(); + return gfx.getTexLevelParameterI(TextureTarget.TEXTURE_2D, 0, 4097); } @Override @@ -151,6 +157,8 @@ public void drawTexturedModalRect(double left, double top, double right, double public void drawTexture(double x, double y, double texturePosX, double texturePosY, double imageWidth, double imageHeight, double maxWidth, double maxHeight, float alpha) { + if(boundTexture == null) + return; if (alpha <= 1.0F) { Laby.gfx().enableBlend(); @@ -185,13 +193,17 @@ public void drawTexture(double x, double y, double texturePosX, double texturePo @Override public void bindTexture(ResourceLocation resourceLocation) { - this.boundTexture = Laby.references().resourceLocationFactory().create(namespace, resourceLocation.getResourcePath()); - Laby.references().glStateBridge().bindTexture(boundTexture); + bindTexture(Laby.references().resourceLocationFactory().create(namespace, resourceLocation.getResourcePath())); } public void bindTexture(net.labymod.api.client.resources.ResourceLocation resourceLocation) { this.boundTexture = resourceLocation; - Laby.references().glStateBridge().bindTexture(boundTexture); + if(resourceLocation == null) + return; + Texture texture = Laby.references().textureRepository().getTexture(resourceLocation); + if(texture == null) + return; + gfx.bindTexture2D(texture.getTextureId()); } //endregion @@ -275,7 +287,7 @@ public void drawGradientRect(int left, int top, int right, int bottom, Color sta public void drawBackground(int tint, double scrolling, int brightness) { Rectangle bounds = Rectangle.absolute(0, 0, getScaledWidth(), getScaledHeight()); Laby.references().resourceRenderer() - .texture(Laby.labyAPI().minecraft().textures().backgroundTexture()) + .texture(ModTextures.BACKGROUND.toLaby()) .pos(bounds) .sprite(bounds.getX() * 8.0F, bounds.getY() * 8.0F, bounds.getWidth() * 8.0F, bounds.getHeight() * 8.0F) .color(brightness / 255.0F, brightness / 255.0F, brightness / 255.0F, 1.0F) @@ -286,7 +298,7 @@ public void drawOverlayBackground(int startY, int endY) { float brightness = 64; Rectangle bounds = Rectangle.absolute(0, startY, getScaledWidth(), endY); Laby.references().resourceRenderer() - .texture(Laby.labyAPI().minecraft().textures().backgroundTexture()) + .texture(ModTextures.BACKGROUND.toLaby()) .pos(bounds) .sprite(bounds.getX() * 8.0F, bounds.getY() * 8.0F, bounds.getWidth() * 8.0F, bounds.getHeight() * 8.0F) .color(brightness / 255.0F, brightness / 255.0F, brightness / 255.0F, 1.0F) @@ -297,7 +309,7 @@ public void drawDimmedOverlayBackground(int left, int top, int right, int bottom float brightness = 64; Rectangle bounds = Rectangle.absolute(left, top, right, bottom); Laby.references().resourceRenderer() - .texture(Laby.labyAPI().minecraft().textures().backgroundTexture()) + .texture(ModTextures.BACKGROUND.toLaby()) .pos(bounds) .sprite(bounds.getX() * 8.0F, bounds.getY() * 8.0F, bounds.getWidth() * 8.0F, bounds.getHeight() * 8.0F) .color(brightness / 255.0F, brightness / 255.0F, brightness / 255.0F, 1.0F) @@ -323,12 +335,22 @@ public void renderItemIntoGUI(Material material, int itemDamage, double x, doubl //TODO fiks så blocks ikke er mørke og så chest ikke ser mærklig ud. if(itemStack == null) return; + Laby.references().blaze3DGlStatePipeline().enableDepthTest(); + //Laby.references().glStateBridge().enableDepth(); + Laby.references().blaze3DGlStatePipeline().enableDepthTest(); + Laby.labyAPI().minecraft().itemStackRenderer().renderItemStack( stack, itemStack, (int) (x / scale), (int) (y / scale) ); + + Laby.references().blaze3DGlStatePipeline().disableDepthTest(); + //Laby.references().glStateBridge().disableDepth(); + Laby.references().blaze3DGlStatePipeline().disableDepthTest(); + + //Laby.references().glStateBridge().disableCull(); stack.scale((float) (1.0F / scale), (float) (1.0F / scale), 0); diff --git a/core/src/main/java/ml/volder/unikapi/datasystem/DataManager.java b/core/src/main/java/ml/volder/unikapi/datasystem/DataManager.java index 5723e58..ccb4c99 100644 --- a/core/src/main/java/ml/volder/unikapi/datasystem/DataManager.java +++ b/core/src/main/java/ml/volder/unikapi/datasystem/DataManager.java @@ -2,6 +2,7 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; import ml.volder.unikapi.UnikAPI; import ml.volder.unikapi.logger.Logger; import ml.volder.unikapi.utils.IOUtils; @@ -95,6 +96,22 @@ public File getFile() { return this.file; } + /** + * Get boolean from key if T is class Data + * + * @param key the boolean to get from file + * + * @return boolean at key (false if not present or T is not class Data) + */ + public boolean getBoolean(String key) { + if(!(this.getSettings() instanceof Data)) + return false; + JsonObject jsonObject = ((Data)this.getSettings()).getData(); + if(!jsonObject.has(key)) + return false; + return jsonObject.get(key).getAsBoolean(); + } + private static Map> dataManagerMap = new HashMap<>(); public static DataManager getOrCreateDataManager(File file) { if(dataManagerMap.containsKey(file)) diff --git a/core/src/main/java/ml/volder/unikapi/guisystem/ModTextures.java b/core/src/main/java/ml/volder/unikapi/guisystem/ModTextures.java index 650e117..e35a060 100644 --- a/core/src/main/java/ml/volder/unikapi/guisystem/ModTextures.java +++ b/core/src/main/java/ml/volder/unikapi/guisystem/ModTextures.java @@ -35,6 +35,7 @@ public class ModTextures { public static final ResourceLocation BUTTON_HOVER_DEFAULT = new ResourceLocation(RESOURCE_DOMAIN, TEXTURE_FOLDER + "buttons/hover_default.png"); public static final ResourceLocation BUTTON_PASTE = new ResourceLocation(RESOURCE_DOMAIN, TEXTURE_FOLDER + "buttons/paste.png"); public static final ResourceLocation BUTTON_COPY = new ResourceLocation(RESOURCE_DOMAIN, TEXTURE_FOLDER + "buttons/copy.png"); + public static final ResourceLocation BACKGROUND = new ResourceLocation(RESOURCE_DOMAIN, TEXTURE_FOLDER + "gui/options_background.png"); public static net.labymod.api.client.resources.ResourceLocation SETTINGS_ICONS = Laby.labyAPI().themeService().currentTheme().resource("labymod", "textures/settings/main/laby.png"); public static net.labymod.api.client.resources.ResourceLocation SETTINGS_ICONS_1 = Laby.labyAPI().themeService().currentTheme().resource("labymod", "textures/settings/main/laby_1.png"); diff --git a/core/src/main/java/ml/volder/unikapi/types/ResourceLocation.java b/core/src/main/java/ml/volder/unikapi/types/ResourceLocation.java index d40e970..74c672d 100644 --- a/core/src/main/java/ml/volder/unikapi/types/ResourceLocation.java +++ b/core/src/main/java/ml/volder/unikapi/types/ResourceLocation.java @@ -85,6 +85,8 @@ private boolean isEmpty(final CharSequence cs) { } public net.labymod.api.client.resources.ResourceLocation toLaby() { + if(resourceDomain == null || resourcePath == null) + return null; return Laby.references().resourceLocationFactory().create(resourceDomain, resourcePath); } } diff --git a/core/src/main/java/ml/volder/unikapi/wrappers/guibutton/impl/Laby4GuiButton.java b/core/src/main/java/ml/volder/unikapi/wrappers/guibutton/impl/Laby4GuiButton.java index d75485b..c28ff4f 100644 --- a/core/src/main/java/ml/volder/unikapi/wrappers/guibutton/impl/Laby4GuiButton.java +++ b/core/src/main/java/ml/volder/unikapi/wrappers/guibutton/impl/Laby4GuiButton.java @@ -3,6 +3,7 @@ import ml.volder.unikapi.SupportedClient; import ml.volder.unikapi.api.draw.DrawAPI; import ml.volder.unikapi.api.draw.impl.Laby4DrawAPI; +import ml.volder.unikapi.guisystem.ModTextures; import ml.volder.unikapi.wrappers.guibutton.IGuiButtonImpl; import ml.volder.unikapi.wrappers.guibutton.WrappedGuiButton; import net.labymod.api.Laby; @@ -19,7 +20,7 @@ public WrappedGuiButton getWrapper() { private WrappedGuiButton guiButton; - protected static final ResourceLocation buttonTextures = Laby.labyAPI().minecraft().textures().widgetsTexture(); + protected static final ResourceLocation buttonTextures = ModTextures.WIDGETS.toLaby(); /** Button width in pixels */ public int width; /** Button height in pixels */ diff --git a/core/src/main/java/ml/volder/unikapi/wrappers/guiscreen/impl/Laby4GuiScreenImpl.java b/core/src/main/java/ml/volder/unikapi/wrappers/guiscreen/impl/Laby4GuiScreenImpl.java index b5e47f5..66f2cd9 100644 --- a/core/src/main/java/ml/volder/unikapi/wrappers/guiscreen/impl/Laby4GuiScreenImpl.java +++ b/core/src/main/java/ml/volder/unikapi/wrappers/guiscreen/impl/Laby4GuiScreenImpl.java @@ -13,6 +13,7 @@ import net.labymod.api.client.gui.mouse.MutableMouse; import net.labymod.api.client.gui.screen.LabyScreen; import net.labymod.api.client.gui.screen.Parent; +import net.labymod.api.client.gui.screen.ScreenContext; import net.labymod.api.client.gui.screen.ScreenInstance; import net.labymod.api.client.gui.screen.key.InputType; import net.labymod.api.client.gui.screen.key.Key; @@ -89,8 +90,17 @@ public void resize(int width, int height) { this.height = height; } + @Override + public void render(ScreenContext context) { + internalRender(context.stack(), context.mouse(), context.getTickDelta()); + } + @Override public void render(Stack stack, MutableMouse mouse, float partialTicks) { + //internalRender(stack, mouse, partialTicks); + } + + private void internalRender(Stack stack, MutableMouse mouse, float partialTicks) { Stack currentStack = Laby4DrawAPI.CURRENT_RENDER_STACK; Laby4DrawAPI.CURRENT_RENDER_STACK = stack; screen.drawScreen(mouse.getX(), mouse.getY(), partialTicks); @@ -102,17 +112,17 @@ public void render(Stack stack, MutableMouse mouse, float partialTicks) { } @Override - public boolean renderBackground(Stack stack, int mouseX, int mouseY, float tickDelta) { + public boolean renderBackground(ScreenContext context) { return true; } @Override - public void renderOverlay(Stack stack, MutableMouse mouse, float partialTicks) { + public void renderOverlay(ScreenContext context) { } @Override - public void renderHoverComponent(Stack stack, MutableMouse mouse, float partialTicks) { + public void renderHoverComponent(ScreenContext context) { } diff --git a/core/src/main/resources/assets/sa-transporter/i18n/en_us.json b/core/src/main/resources/assets/sa-transporter/i18n/en_us.json index befb03d..e4f9826 100644 --- a/core/src/main/resources/assets/sa-transporter/i18n/en_us.json +++ b/core/src/main/resources/assets/sa-transporter/i18n/en_us.json @@ -56,7 +56,8 @@ "updateMessages.name": "Opdatere beskeder automatisk", "openMessagesEditor.name": "Åben beskeder editor", "updateBalanceMessages.name": "Opdatere balance beskeder automatisk", - "openBalanceMessagesEditor.name": "Åben balance beskeder editor" + "openBalanceMessagesEditor.name": "Åben balance beskeder editor", + "useTransporterPackets.name": "Brug Transporter Packets" }, "autoGetModule": { "name": "§fTransporter Addon §7- §fAuto Get", @@ -92,6 +93,9 @@ "putFailed.name": "Besked - Put Failed", "sendSuccess.name": "Besked - Send Success", "modtagSuccess.name": "Besked - Modtag", + "putAllMessage.name": "Besked - Put All", + "autoTransporterOn.name": "Besked - Auto Transporter On", + "autoTransporterOff.name": "Besked - Auto Transporter Off", "sendOffline.name": "Besked - Send Offline", "sendSelf.name": "Besked - Send Dig Selv", "commandDelay.name": "Besked - Vent" diff --git a/core/src/main/resources/assets/sa-transporter/transporter/textures/buttons/left-arrow.png b/core/src/main/resources/assets/sa-transporter/transporter/textures/buttons/left-arrow.png new file mode 100644 index 0000000..efd2449 Binary files /dev/null and b/core/src/main/resources/assets/sa-transporter/transporter/textures/buttons/left-arrow.png differ diff --git a/core/src/main/resources/assets/sa-transporter/transporter/textures/buttons/right-arrow.png b/core/src/main/resources/assets/sa-transporter/transporter/textures/buttons/right-arrow.png new file mode 100644 index 0000000..4ec1bdd Binary files /dev/null and b/core/src/main/resources/assets/sa-transporter/transporter/textures/buttons/right-arrow.png differ diff --git a/core/src/main/resources/assets/sa-transporter/transporter/textures/buttons/trash.png b/core/src/main/resources/assets/sa-transporter/transporter/textures/buttons/trash.png new file mode 100644 index 0000000..d25f72d Binary files /dev/null and b/core/src/main/resources/assets/sa-transporter/transporter/textures/buttons/trash.png differ diff --git a/core/src/main/resources/assets/sa-transporter/transporter/textures/gui/options_background.png b/core/src/main/resources/assets/sa-transporter/transporter/textures/gui/options_background.png new file mode 100644 index 0000000..cae5528 Binary files /dev/null and b/core/src/main/resources/assets/sa-transporter/transporter/textures/gui/options_background.png differ diff --git a/core/src/main/resources/transporter/transporter-messages.csv b/core/src/main/resources/transporter/transporter-messages.csv index 743a730..7071731 100644 --- a/core/src/main/resources/transporter/transporter-messages.csv +++ b/core/src/main/resources/transporter/transporter-messages.csv @@ -12,5 +12,7 @@ get_success,^Du har taget (?[0-9.]+) (?%item_regex%) \((?[0 failed_too_fast,^Du skriver kommandoer for hurtigt!$ info_entry,^ (?%item_regex%): (?[0-9.]+)$ info_title,^Du har følgende i din transporter:$ -put_mine_entry,^ (?%item_regex%): (?[0-9.]+)$ -put_mine_title,^Du har nu puttet følgende i din transporter:$ +put_mine_entry,^ (?[0-9A-Za-z:_ ]+): (?[0-9.]+) \((?[0-9.]+) i alt\)$ +autotransporter_on,^Slår auto-transporter til! \([mineall]+\)$ +autotransporter_off,^Slår auto-transporter fra!$ +put_all,Du har nu puttet følgende i din transporter: \ No newline at end of file diff --git a/game-runner/gradle.properties b/game-runner/gradle.properties new file mode 100644 index 0000000..982be3f --- /dev/null +++ b/game-runner/gradle.properties @@ -0,0 +1 @@ +lg_versioned_module=true \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 609a9ce..8f550f5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,2 @@ -org.gradle.jvmargs=-Xmx4096m \ No newline at end of file +org.gradle.jvmargs=-Xmx4096m +net.labymod.minecraft-versions=1.8.9;1.12.2;1.16.5;1.17.1;1.18.2;1.19.2;1.19.3;1.19.4;1.20.1;1.20.2;1.20.4;1.20.5;1.20.6;1.21;1.21.1 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a8382d7..b1e749b 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts index 3cb97af..58e7394 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,25 +1,23 @@ rootProject.name = "TransporterAddon" pluginManagement { - val labyGradlePluginVersion = "0.4.6" - plugins { - id("net.labymod.gradle") version (labyGradlePluginVersion) - } - + val labyGradlePluginVersion = "0.5.7" buildscript { repositories { maven("https://dist.labymod.net/api/v1/maven/release/") - maven("https://repo.spongepowered.org/repository/maven-public") + maven("https://maven.neoforged.net/releases/") + maven("https://maven.fabricmc.net/") + gradlePluginPortal() mavenCentral() } dependencies { - classpath("net.labymod.gradle", "addon", labyGradlePluginVersion) + classpath("net.labymod.gradle", "common", labyGradlePluginVersion) } } } -plugins.apply("net.labymod.gradle") +plugins.apply("net.labymod.labygradle.settings") include(":api") -include(":core") +include(":core") \ No newline at end of file