diff --git a/README.md b/README.md deleted file mode 100644 index 25e1b0f..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# Chungamod -Funny utility mod for Minecraft 1.12.2 anarchy servers diff --git a/build.gradle b/build.gradle index 047751a..8bf2d71 100644 --- a/build.gradle +++ b/build.gradle @@ -14,7 +14,7 @@ apply plugin: 'net.minecraftforge.gradle' apply plugin: 'eclipse' apply plugin: 'maven-publish' -version = '0.1.1' +version = '0.2' group = 'magnileve.chungamod' // http://maven.apache.org/guides/mini/guide-naming-conventions.html archivesBaseName = 'chungamod' @@ -56,6 +56,10 @@ minecraft { } } +repositories { + maven { url 'https://jitpack.io' } +} + configurations { jarLibs } @@ -83,7 +87,8 @@ dependencies { // For more info... // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html // http://www.gradle.org/docs/current/userguide/dependency_management.html - jarLibs files('libs\\discord-rpc.jar') + + jarLibs 'com.github.Vatuu:discord-rpc:1.6.2' implementation configurations.jarLibs } diff --git a/libs/discord-rpc.jar b/libs/discord-rpc.jar deleted file mode 100644 index ef5c4bb..0000000 Binary files a/libs/discord-rpc.jar and /dev/null differ diff --git a/src/main/java/magnileve/chungamod/Chung.java b/src/main/java/magnileve/chungamod/Chung.java new file mode 100644 index 0000000..8e5067f --- /dev/null +++ b/src/main/java/magnileve/chungamod/Chung.java @@ -0,0 +1,92 @@ +package magnileve.chungamod; + +import java.util.LinkedList; + +import magnileve.chungamod.time.Activity; +import net.minecraft.client.Minecraft; +import net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; +import net.minecraft.util.text.TextComponentString; + +public class Chung { + +public static final String MODID = "chungamod"; +public static final String NAME = "Chungamod"; +public static final String VERSION = "0.2"; +public static final String ACCEPTED_MINECRAFT_VERSIONS = "[1.12]"; +private static Minecraft mc; +public static LinkedList runningActivities; + +public static void init(Minecraft mcIn) { + mc = mcIn; + runningActivities = new LinkedList(); +} + +/** + * Sends a client-side message in chat. + * @param message what shows up in chat + */ +public static void sendMessage(String message) { + mc.player.sendMessage(new TextComponentString("[Chungamod] " + message)); +} + +/** + * Inverse of String method split(regex). + * @param strings array of split strings to be converted back into one string + * @param regex what to put between each split string + */ +public static String inverseSplit(String[] strings, String regex) { + if (strings.length == 0) return ""; + StringBuilder str = new StringBuilder(strings[0]); + for (short i = 1; i < strings.length; i++) str.append(regex).append(strings[i]); + return str.toString(); +} + +/** + * Copied and pasted from the Mincerfat code becaues it has protected visibility there. + * @param pitch pitch of rotation + * @param yaw yaw of rotation + * @return vector with rotation of the input pitch and yaw + */ +public static final Vec3d getVectorForRotation(float pitch, float yaw) { + float f = MathHelper.cos(-yaw * 0.017453292F - (float)Math.PI); + float f1 = MathHelper.sin(-yaw * 0.017453292F - (float)Math.PI); + float f2 = -MathHelper.cos(-pitch * 0.017453292F); + float f3 = MathHelper.sin(-pitch * 0.017453292F); + return new Vec3d((double)(f1 * f2), (double)f3, (double)(f * f2)); +} + +/** + * Gets packet for right-clicking on a block. Blocks between the player and the input BlockPos do affect the side the block is used on, but not the BlockPos to be used. Range is 4.5 blocks. + * @param blockPos block to be used + * @param yOffset offsets the y coordinate of the 3d vector to be raytraced to in order to determine which side of the block is hit first + * @return a packet to use the input BlockPos ready to be sent to the server + */ +public static CPacketPlayerTryUseItemOnBlock useBlock(BlockPos blockPos, double yOffset) { + double dx = blockPos.getX() - mc.player.posX + 0.5; + double dy = blockPos.getY() - mc.player.posY + 0.5 + yOffset - mc.player.eyeHeight; + double dz = blockPos.getZ() - mc.player.posZ + 0.5; + + double r = Math.sqrt(dx * dx + dy * dy + dz * dz); + double yaw = -Math.atan2(dx, dz) / Math.PI * 180; + if(yaw < 0) yaw = 360 + yaw; + double pitch = -Math.asin(dy / r) / Math.PI * 180; + + Vec3d vec3d = mc.player.getPositionEyes(1.0F); + Vec3d vec3d1 = Chung.getVectorForRotation((float) pitch, (float) yaw); + Vec3d vec3d2 = vec3d.addVector(vec3d1.x * 4.5D, vec3d1.y * 4.5D, vec3d1.z * 4.5D); + RayTraceResult rayTrace = mc.world.rayTraceBlocks(vec3d, vec3d2, false, false, true); + + BlockPos pos1 = rayTrace.getBlockPos(); + Vec3d vec1 = rayTrace.hitVec; + float f = (float)(vec1.x - (double)pos1.getX()); + float f1 = (float)(vec1.y - (double)pos1.getY()); + float f2 = (float)(vec1.z - (double)pos1.getZ()); + return new CPacketPlayerTryUseItemOnBlock(blockPos, rayTrace.sideHit, EnumHand.MAIN_HAND, f, f1, f2); +} + +} \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/Chungamod.java b/src/main/java/magnileve/chungamod/ChungamodInitialization.java similarity index 60% rename from src/main/java/magnileve/chungamod/Chungamod.java rename to src/main/java/magnileve/chungamod/ChungamodInitialization.java index d3c4237..88e3bd8 100644 --- a/src/main/java/magnileve/chungamod/Chungamod.java +++ b/src/main/java/magnileve/chungamod/ChungamodInitialization.java @@ -7,39 +7,43 @@ import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.Logger; +import magnileve.chungamod.settings.CustomChatSuffix; import magnileve.chungamod.settings.Settings; +import magnileve.chungamod.time.LeaveServerListener; import magnileve.chungamod.time.TickTimer; -@Mod(modid = Ref.MODID, name = Ref.NAME, version = Ref.VERSION, acceptedMinecraftVersions = Ref.ACCEPTED_MINECRAFT_VERSIONS) -public class Chungamod { +@Mod(modid = Chung.MODID, name = Chung.NAME, version = Chung.VERSION, acceptedMinecraftVersions = Chung.ACCEPTED_MINECRAFT_VERSIONS) +public class ChungamodInitialization { private static Minecraft mc; private static Logger log; @Instance - public static Chungamod instance; + public static ChungamodInitialization instance; @EventHandler public void preInit(FMLPreInitializationEvent event) { mc = Minecraft.getMinecraft(); log = (Logger) event.getModLog(); - log.info(Ref.MODID + ":Pre-Initialization"); - Settings.load(log); - Ref.init(mc); + log.info(Chung.MODID + ": Pre-Initialization"); + Settings.init(log); + Chung.init(mc); TickTimer.init(log); - Commands.init(mc, log); } @EventHandler public void init(FMLInitializationEvent event) { - log.info(Ref.MODID + ":Initialization"); + log.info(Chung.MODID + ": Initialization"); + Commands.init(mc, log); + LeaveServerListener.init(mc, log); } @EventHandler public void postInit(FMLPostInitializationEvent event) { - log.info(Ref.MODID + ":Post-Initialization"); + log.info(Chung.MODID + ": Post-Initialization"); Commands.init2(); + CustomChatSuffix.init(mc, log); } } \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/Commands.java b/src/main/java/magnileve/chungamod/Commands.java index 4976e52..16d0a4e 100644 --- a/src/main/java/magnileve/chungamod/Commands.java +++ b/src/main/java/magnileve/chungamod/Commands.java @@ -6,55 +6,61 @@ import net.minecraftforge.fml.relauncher.SideOnly; import java.util.Collection; +import java.util.LinkedList; import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.Logger; -import magnileve.chungamod.itemstorage.AutoSort; +import magnileve.chungamod.auto.BaritoneTravel; +import magnileve.chungamod.auto.RotationAntiAFK; +import magnileve.chungamod.auto.itemstorage.AutoSort; import magnileve.chungamod.settings.DiscordRPCManager; -import magnileve.chungamod.settings.LogSetting; import magnileve.chungamod.settings.Settings; import magnileve.chungamod.time.ClientTps; +import magnileve.chungamod.time.TickListener; +import magnileve.chungamod.time.TickTimer; import magnileve.chungamod.time.Activity; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.client.Minecraft; import net.minecraft.tileentity.TileEntitySign; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.client.event.ClientChatEvent; -@Mod.EventBusSubscriber(modid=Ref.MODID) +@Mod.EventBusSubscriber(modid=Chung.MODID) public class Commands { private static Minecraft mc; private static Logger log; -private static final String HELP_MESSAGE = "Chungamod \\version by Magnileve\nCommands:\n\\prefixhelp - sends this message\n\\prefixset - get list of settings\n\\prefixset - set a setting\n\\prefixset - set a setting of a feature\n\\prefixcancel - cancel current activities\n\\prefixautosort - automatically sort shulker boxes\n\\prefixdiscordrpc - send list of Discord RPC setting values"; +private static final String HELP_MESSAGE = "Chungamod \\version by Magnileve\nCommands:\n\\prefixhelp - sends this message\n\\prefixset - get list of settings\n\\prefixset - set a setting\n\\prefixset - set a setting of a feature\n\\prefixcancel - cancel current activities\\n\\\\prefixgoto - Baritone goto command supporting multiple destinations\n\\prefixautosort - automatically sort shulker boxes\n\\prefixdiscordrpc - send list of Discord RPC setting values\n\\prefixgoto - run Baritone to go to multiple destinations in order\n\\prefixrotationantiafk - AntiAFK made for elytrafly using rotation packets"; private static final String HELP_DEBUG_MESSAGE = "\nDebug commands:\n\\prefixblockdata - get block state of selected block\n\\prefixclienttps - measure and periodically send client TPS\n\\prefixplayerdirection - send pitch and yaw of camera and player\n\\prefixentitylist - send list of all entities in your current chunk\n\\prefixplayerpos - send current player position"; -protected static void init(Minecraft minecraft, Logger logger) { - mc = minecraft; - log = logger; +public static void init(Minecraft mcIn, Logger logIn) { + mc = mcIn; + log = logIn; } public static void init2() { Settings.addListener(new DiscordRPCManager()); - Settings.addListener(new LogSetting(log)); } @SubscribeEvent @SideOnly(value = Side.CLIENT) -public static void onServerChatEvent(ClientChatEvent event) { - if(event.getMessage().startsWith((String) Settings.get("prefix"))) { +public static void onClientChatEvent(ClientChatEvent event) { + String message = event.getMessage(); + if(message.startsWith((String) Settings.get("prefix"))) { event.setCanceled(true); - log.info("Chungamod command called: " + event.getMessage()); + mc.ingameGUI.getChatGUI().addToSentMessages(message); + log.info("Chungamod command called: " + message); String[] command = event.getMessage().split(" "); - if (command[0].length() == ((String) Settings.get("prefix")).length()) mc.player.sendMessage(new TextComponentString(HELP_MESSAGE.concat((boolean) Settings.get("debug") ? HELP_DEBUG_MESSAGE : "").replaceAll("\\\\prefix", (String) Settings.get("prefix")).replaceFirst("\\\\version", Ref.VERSION))); + if (command[0].length() == ((String) Settings.get("prefix")).length()) mc.player.sendMessage(new TextComponentString(HELP_MESSAGE.concat((boolean) Settings.get("debug") ? HELP_DEBUG_MESSAGE : "").replaceAll("\\\\prefix", (String) Settings.get("prefix")).replaceFirst("\\\\version", Chung.VERSION))); else switch (command[0].substring(((String) Settings.get("prefix")).length()).toLowerCase()) { case "help": - mc.player.sendMessage(new TextComponentString(HELP_MESSAGE.concat((boolean) Settings.get("debug") ? HELP_DEBUG_MESSAGE : "").replaceAll("\\n\\\\prefix", "\n" + (String) Settings.get("prefix")).replaceFirst("\\\\version", Ref.VERSION))); + mc.player.sendMessage(new TextComponentString(HELP_MESSAGE.concat((boolean) Settings.get("debug") ? HELP_DEBUG_MESSAGE : "").replaceAll("\\n\\\\prefix", "\n" + (String) Settings.get("prefix")).replaceFirst("\\\\version", Chung.VERSION))); break; case "set": if(command.length > 1) { @@ -75,18 +81,18 @@ else switch (command[0].substring(((String) Settings.get("prefix")).length()).to switch((Settings.Type) featureSettings[i]) { case STRING: if(command.length > 3) { - String newString = Ref.inverseSplit(command, " ").substring(command[0].length() + command[1].length() + 2); + String newString = message.substring(command[0].length() + command[1].length() + command[2].length() + 3); Settings.set(command[1], command[2], newString); - Ref.sendMessage("Set " + command[1] + "." + command[2] + " to " + newString); - } else Ref.sendMessage(Settings.get(command[1], command[2]).toString()); + Chung.sendMessage("Set " + command[1] + "." + command[2] + " to " + newString); + } else Chung.sendMessage(Settings.get(command[1], command[2]).toString()); break; case BOOLEAN: if(command.length > 3) { - if(command[3].toLowerCase().equals("true") || command[3].toLowerCase().equals("false")) { + if(command[3].equalsIgnoreCase("true") || command[3].equalsIgnoreCase("false")) { Settings.set(command[1], command[2], Boolean.valueOf(command[3])); - Ref.sendMessage("Set " + command[1] + "." + command[2] + " to " + command[3]); - } Ref.sendMessage("Valid setting values: true, false"); - } else Ref.sendMessage(Settings.get(command[1], command[2]).toString()); + Chung.sendMessage("Set " + command[1] + "." + command[2] + " to " + command[3]); + } else Chung.sendMessage("Valid setting values: true, false"); + } else Chung.sendMessage(Settings.get(command[1], command[2]).toString()); break; case BLOCKPOS: try { @@ -96,18 +102,18 @@ else switch (command[0].substring(((String) Settings.get("prefix")).length()).to } else { newPos = mc.getRenderViewEntity().rayTrace(4.5D, 1.0F).getBlockPos(); if(Block.getIdFromBlock(mc.world.getBlockState(newPos).getBlock()) == 0) { - Ref.sendMessage(Settings.get(command[1], command[2]).toString()); + Chung.sendMessage(Settings.get(command[1], command[2]).toString()); break; } } Settings.set(command[1], command[2], newPos); - Ref.sendMessage("Set " + command[1] + "." + command[2] + " to " + newPos); + Chung.sendMessage("Set " + command[1] + "." + command[2] + " to " + newPos); } catch (IndexOutOfBoundsException e) { - Ref.sendMessage("Look at a block while setting this value or supply coordinates: " + command[0] + " " + command[1] + " " + command[2] + " "); + Chung.sendMessage("Look at a block while setting this value or supply coordinates: " + command[0] + " " + command[1] + " " + command[2] + " "); } catch (NumberFormatException e) { - Ref.sendMessage("Look at a block while setting this value or supply coordinates: " + command[0] + " " + command[1] + " " + command[2] + " "); + Chung.sendMessage("Look at a block while setting this value or supply coordinates: " + command[0] + " " + command[1] + " " + command[2] + " "); } catch (NullPointerException e) { - Ref.sendMessage("NullPointerException while setting BlockPos"); + Chung.sendMessage("NullPointerException while setting BlockPos"); log.warn("NullPointerException while setting BlockPos"); log.catching(Level.WARN, e); } @@ -121,35 +127,35 @@ else switch (command[0].substring(((String) Settings.get("prefix")).length()).to case BYTE_POSITIVE: if(Byte.valueOf(command[3]) > 0) featureSettings[i] = Settings.Type.BYTE; else { - Ref.sendMessage("Number value must be above 0"); + Chung.sendMessage("Number value must be above 0"); break; } case BYTE: Byte newByte = Byte.valueOf(command[3]); if(newByte < 0) newByte = 0; Settings.set(command[1], command[2], newByte); - Ref.sendMessage("Set " + command[1] + "." + command[2] + " to " + newByte); + Chung.sendMessage("Set " + command[1] + "." + command[2] + " to " + newByte); break; case SHORT: Short newShort = Short.valueOf(command[3]); if(newShort < 0) newShort = 0; Settings.set(command[1], command[2], newShort); - Ref.sendMessage("Set " + command[1] + "." + command[2] + " to " + newShort); + Chung.sendMessage("Set " + command[1] + "." + command[2] + " to " + newShort); break; default: break; } } catch(NumberFormatException e) { - Ref.sendMessage("Enter a number value"); + Chung.sendMessage("Enter a number value"); } - } else Ref.sendMessage(Settings.get(command[1], command[2]).toString()); + } else Chung.sendMessage(Settings.get(command[1], command[2]).toString()); break; case STRING_ONE_WORD: if(command.length == 4) { Settings.set(command[1], command[2], command[3]); - Ref.sendMessage("Set " + command[1] + "." + command[2] + " to " + command[3]); - } else if(command.length == 3) Ref.sendMessage(Settings.get(command[1], command[2]).toString()); - else Ref.sendMessage("Value can not contain spaces"); + Chung.sendMessage("Set " + command[1] + "." + command[2] + " to " + command[3]); + } else if(command.length == 3) Chung.sendMessage(Settings.get(command[1], command[2]).toString()); + else Chung.sendMessage("Value can not contain spaces"); break; case OBJECT_ARRAY: log.error("Enum representing object array in setting values"); @@ -161,25 +167,25 @@ else switch (command[0].substring(((String) Settings.get("prefix")).length()).to i++; } if(i != 0) { - Ref.sendMessage("Settings for " + command[1] + ": " + ((String) featureSettings[0]).replaceAll(" ", ", ")); + Chung.sendMessage("Settings for " + command[1] + ": " + ((String) featureSettings[0]).replaceAll(" ", ", ")); } - } else Ref.sendMessage("Settings for " + command[1] + ": " + ((String) featureSettings[0]).replaceAll(" ", ", ")); + } else Chung.sendMessage("Settings for " + command[1] + ": " + ((String) featureSettings[0]).replaceAll(" ", ", ")); } else { switch(settingValueEnum) { case STRING: if(command.length > 2) { - String newString = Ref.inverseSplit(command, " ").substring(command[0].length() + command[1].length() + 2); + String newString = message.substring(command[0].length() + command[1].length() + 2); Settings.set(command[1], newString); - Ref.sendMessage("Set " + command[1] + " to " + newString); - } else Ref.sendMessage(Settings.get(command[1]).toString()); + Chung.sendMessage("Set " + command[1] + " to " + newString); + } else Chung.sendMessage(Settings.get(command[1]).toString()); break; case BOOLEAN: if(command.length > 2) { - if(command[2].toLowerCase().equals("true") || command[2].toLowerCase().equals("false")) { + if(command[2].equalsIgnoreCase("true") || command[2].equalsIgnoreCase("false")) { Settings.set(command[1], Boolean.valueOf(command[2])); - Ref.sendMessage("Set " + command[1] + " to " + command[2]); - } Ref.sendMessage("Valid setting values: true, false"); - } else Ref.sendMessage(Settings.get(command[1]).toString()); + Chung.sendMessage("Set " + command[1] + " to " + command[2]); + } else Chung.sendMessage("Valid setting values: true, false"); + } else Chung.sendMessage(Settings.get(command[1]).toString()); break; case BLOCKPOS: try { @@ -189,18 +195,18 @@ else switch (command[0].substring(((String) Settings.get("prefix")).length()).to } else { newPos = mc.getRenderViewEntity().rayTrace(4.5D, 1.0F).getBlockPos(); if(Block.getIdFromBlock(mc.world.getBlockState(newPos).getBlock()) == 0) { - Ref.sendMessage(Settings.get(command[1]).toString()); + Chung.sendMessage(Settings.get(command[1]).toString()); break; } } Settings.set(command[1], newPos); - Ref.sendMessage("Set " + command[1] + " to " + newPos); + Chung.sendMessage("Set " + command[1] + " to " + newPos); } catch (IndexOutOfBoundsException e) { - Ref.sendMessage("Look at a block while setting this value or supply coordinates: " + command[0] + " " + command[1] + " "); + Chung.sendMessage("Look at a block while setting this value or supply coordinates: " + command[0] + " " + command[1] + " "); } catch (NumberFormatException e) { - Ref.sendMessage("Look at a block while setting this value or supply coordinates: " + command[0] + " " + command[1] + " "); + Chung.sendMessage("Look at a block while setting this value or supply coordinates: " + command[0] + " " + command[1] + " "); } catch (NullPointerException e) { - Ref.sendMessage("NullPointerException while setting BlockPos"); + Chung.sendMessage("NullPointerException while setting BlockPos"); log.warn("NullPointerException while setting BlockPos"); log.catching(Level.WARN, e); } @@ -214,35 +220,35 @@ else switch (command[0].substring(((String) Settings.get("prefix")).length()).to case BYTE_POSITIVE: if(Byte.valueOf(command[2]) > 0) settingValueEnum = Settings.Type.BYTE; else { - Ref.sendMessage("Number value must be above 0"); + Chung.sendMessage("Number value must be above 0"); break; } case BYTE: Byte newByte = Byte.valueOf(command[2]); if(newByte < 0) newByte = 0; Settings.set(command[1], newByte); - Ref.sendMessage("Set " + command[1] + " to " + newByte); + Chung.sendMessage("Set " + command[1] + " to " + newByte); break; case SHORT: Short newShort = Short.valueOf(command[2]); if(newShort < 0) newShort = 0; Settings.set(command[1], newShort); - Ref.sendMessage("Set " + command[1] + " to " + newShort); + Chung.sendMessage("Set " + command[1] + " to " + newShort); break; default: break; } } catch(NumberFormatException e) { - Ref.sendMessage("Enter a number value"); + Chung.sendMessage("Enter a number value"); } - } else Ref.sendMessage(Settings.get(command[1]).toString()); + } else Chung.sendMessage(Settings.get(command[1]).toString()); break; case STRING_ONE_WORD: if(command.length == 3) { Settings.set(command[1], command[2]); - Ref.sendMessage("Set " + command[1] + " to " + command[2]); - } else if(command.length == 2) Ref.sendMessage(Settings.get(command[1]).toString()); - else Ref.sendMessage("Value can not contain spaces"); + Chung.sendMessage("Set " + command[1] + " to " + command[2]); + } else if(command.length == 2) Chung.sendMessage(Settings.get(command[1]).toString()); + else Chung.sendMessage("Value can not contain spaces"); break; case OBJECT_ARRAY: log.error("Enum representing object array in setting values"); @@ -250,57 +256,77 @@ else switch (command[0].substring(((String) Settings.get("prefix")).length()).to } } } - } else Ref.sendMessage("Settings: " + Settings.SETTINGS_LIST); + } else Chung.sendMessage("Settings: " + Settings.SETTINGS_LIST); break; case "cancel": - Ref.sendMessage("Cancelling running activities"); - for(Activity activity:Ref.runningActivities) activity.stop(); - Ref.runningActivities.clear(); + Chung.sendMessage("Cancelling running activities"); + for(Activity activity:Chung.runningActivities) { + activity.stop(); + if(activity instanceof TickListener) TickTimer.removeListener((TickListener) activity); + } + Chung.runningActivities.clear(); break; case "autosort": if(Settings.get("autosort", "pos1") != null && Settings.get("autosort", "pos2") != null && Settings.get("autosort", "source") != null) { - Ref.sendMessage("Running AutoSort"); - Ref.runningActivities.add(new AutoSort(mc, (BlockPos) Settings.get("autosort", "pos1"), (BlockPos) Settings.get("autosort", "pos2"), (BlockPos) Settings.get("autosort", "source"), (Short) Settings.get("autosort", "source_empty_timeout"), (BlockPos) Settings.get("autosort", "overflow"), log)); + Chung.sendMessage("Running AutoSort"); + Chung.runningActivities.add(new AutoSort(mc, (BlockPos) Settings.get("autosort", "pos1"), (BlockPos) Settings.get("autosort", "pos2"), (BlockPos) Settings.get("autosort", "source"), (Short) Settings.get("autosort", "source_empty_timeout"), (BlockPos) Settings.get("autosort", "overflow"), log)); } - else Ref.sendMessage("Make sure to set AutoSort settings pos1, pos2, and source before running (use " + (String) Settings.get("prefix") + "set autosort "); + else Chung.sendMessage("Make sure to set AutoSort settings pos1, pos2, and source before running (use " + (String) Settings.get("prefix") + "set autosort "); break; case "discordrpc": - Ref.sendMessage(DiscordRPCManager.getDiscordRPCManager().getSettingValues()); + Chung.sendMessage(DiscordRPCManager.getDiscordRPCManager().getSettingValues()); + break; + case "goto": + try { + if(command.length < 4) throw new IllegalArgumentException("No coordinates entered in Baritone command"); + LinkedList destinations = new LinkedList<>(); + for(byte i = 0; i < Math.floor((command.length - 1) / 3); i++) { + int[] coords = new int[3]; + for(byte h = 0; h < 3; h++) coords[h] = command[i * 3 + h + 1].charAt(0) == '~' ? (command[i * 3 + h + 1].length() == 1 ? 0 : Integer.valueOf(command[i * 3 + h + 1].substring(1))) + (h == 0 ? MathHelper.floor(mc.player.posX) : ((h == 1 ? MathHelper.floor(mc.player.posY) : MathHelper.floor(mc.player.posZ)))) : Integer.valueOf(command[i * 3 + h + 1]); + destinations.add(new BlockPos(coords[0], coords[1], coords[2])); + } + Chung.runningActivities.add(new BaritoneTravel(mc, destinations)); + } catch(IllegalArgumentException e) { + Chung.sendMessage("Proper use of command: " + Settings.get("prefix") + "goto ... "); + } + break; + case "rotationantiafk": + Chung.runningActivities.add(new RotationAntiAFK(mc)); + Chung.sendMessage("Started Rotation AntiAFK"); break; - default: if((boolean) Settings.get("debug")) { switch (command[0].substring(((String) Settings.get("prefix")).length()).toLowerCase()) { case "clienttps": - Ref.runningActivities.add(new ClientTps()); + Chung.runningActivities.add(new ClientTps()); break; case "blockdata": BlockPos blockPos = mc.getRenderViewEntity().rayTrace(4.5D, 1.0F).getBlockPos(); for(IProperty property:mc.world.getBlockState(blockPos).getBlock().getBlockState().getProperties()) { - Ref.sendMessage(property.toString()); - Ref.sendMessage(property.getName()); - Ref.sendMessage(property.getClass().toString()); - Ref.sendMessage("property value: " + mc.world.getBlockState(blockPos).getValue(property)); + Chung.sendMessage(property.toString()); + Chung.sendMessage(property.getName()); + Chung.sendMessage(property.getClass().toString()); + Chung.sendMessage("property value: " + mc.world.getBlockState(blockPos).getValue(property)); } if(Block.getIdFromBlock(mc.world.getBlockState(blockPos).getBlock()) == 68) { TileEntitySign tileEntity = (TileEntitySign) mc.world.getChunkFromBlockCoords(blockPos).getTileEntity(blockPos, Chunk.EnumCreateEntityType.CHECK); - for(ITextComponent text:tileEntity.signText) Ref.sendMessage("Sign text: " + text); + for(ITextComponent text:tileEntity.signText) Chung.sendMessage("Sign text: " + text); } break; case "playerdirection": - Ref.sendMessage("Camera pitch: " + mc.player.cameraPitch + "\nCamera yaw: " + mc.player.cameraYaw + "\nRotation pitch: " + mc.player.rotationPitch + "\nRotation yaw: " + mc.player.rotationYaw); + Chung.sendMessage("Camera pitch: " + mc.player.cameraPitch + "\nCamera yaw: " + mc.player.cameraYaw + "\nRotation pitch: " + mc.player.rotationPitch + "\nRotation yaw: " + mc.player.rotationYaw); break; case "entitylist": for(Collection collection:mc.world.getChunkFromBlockCoords(mc.player.getPosition()).getEntityLists()) { - Ref.sendMessage("\nCollection " + collection.getClass()); + Chung.sendMessage("\nCollection " + collection.getClass()); for(Object o:collection) { - Ref.sendMessage(o.getClass().toString()); - Ref.sendMessage(o.toString()); + Chung.sendMessage(o.getClass().toString()); + Chung.sendMessage(o.toString()); } } break; case "playerpos": - Ref.sendMessage(new BlockPos(mc.player.posX, mc.player.posY, mc.player.posZ).toString()); + Chung.sendMessage(new BlockPos(mc.player.posX, mc.player.posY, mc.player.posZ).toString()); break; default: diff --git a/src/main/java/magnileve/chungamod/LeaveServerListener.java b/src/main/java/magnileve/chungamod/LeaveServerListener.java deleted file mode 100644 index 28b5b71..0000000 --- a/src/main/java/magnileve/chungamod/LeaveServerListener.java +++ /dev/null @@ -1,18 +0,0 @@ -package magnileve.chungamod; - -import magnileve.chungamod.time.Activity; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -@Mod.EventBusSubscriber(modid=Ref.MODID) -public class LeaveServerListener { - @SubscribeEvent - @SideOnly(value = Side.CLIENT) - public static void onClientDisconnectEvent(ClientDisconnectionFromServerEvent event) { - for(Activity activity:Ref.runningActivities) activity.stop(); - Ref.runningActivities.clear(); - } -} diff --git a/src/main/java/magnileve/chungamod/Ref.java b/src/main/java/magnileve/chungamod/Ref.java deleted file mode 100644 index 361942a..0000000 --- a/src/main/java/magnileve/chungamod/Ref.java +++ /dev/null @@ -1,46 +0,0 @@ -package magnileve.chungamod; - -import java.util.LinkedList; - -import magnileve.chungamod.time.Activity; -import net.minecraft.client.Minecraft; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.text.TextComponentString; - -public class Ref { - public static final String MODID = "chungamod"; - public static final String NAME = "Chungamod"; - public static final String VERSION = "0.1.1"; - public static final String ACCEPTED_MINECRAFT_VERSIONS = "[1.12]"; - private static Minecraft mc; - public static LinkedList runningActivities; - - public static void init(Minecraft minecraft) { - mc = minecraft; - runningActivities = new LinkedList(); - } - - //send message to player - public static void sendMessage(String message) { - mc.player.sendMessage(new TextComponentString("[Chungamod] " + message)); - } - - //inverse of string.split(regex) - public static String inverseSplit(String[] strings, String regex) { - if (strings.length == 0) return ""; - String str = strings[0]; - for (short i = 1; i < strings.length; i++) str = str + regex + strings[i]; - return str; - } - - //copied and pasted from the Mincerfat code becaues it has protected visibility there - public static final Vec3d getVectorForRotation(float pitch, float yaw) { - float f = MathHelper.cos(-yaw * 0.017453292F - (float)Math.PI); - float f1 = MathHelper.sin(-yaw * 0.017453292F - (float)Math.PI); - float f2 = -MathHelper.cos(-pitch * 0.017453292F); - float f3 = MathHelper.sin(-pitch * 0.017453292F); - return new Vec3d((double)(f1 * f2), (double)f3, (double)(f * f2)); - } -} \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/auto/BaritoneTravel.java b/src/main/java/magnileve/chungamod/auto/BaritoneTravel.java new file mode 100644 index 0000000..a49b458 --- /dev/null +++ b/src/main/java/magnileve/chungamod/auto/BaritoneTravel.java @@ -0,0 +1,70 @@ +package magnileve.chungamod.auto; + +import java.util.Queue; + +import magnileve.chungamod.Chung; +import magnileve.chungamod.time.Activity; +import magnileve.chungamod.time.TickListener; +import magnileve.chungamod.time.TickTimer; +import net.minecraft.client.Minecraft; +import net.minecraft.util.math.BlockPos; + +public class BaritoneTravel implements TickListener, Activity { + +private Minecraft mc; +private Queue destinations; +private BlockPos destination; +private BlockPos playerPos; +private int nextTick; +private boolean restartingBaritone; + +/** + * Runs Baritone to travel to a queue of destinations and restarts Baritone if it stops. + * @param mc instance of Mincerfat + * @param destinations queue of destinations + */ +public BaritoneTravel(Minecraft mc, Queue destinations) { + this.mc = mc; + destination = destinations.remove(); + this.destinations = destinations; + playerPos = mc.player.getPosition(); + TickTimer.addListener(this); + nextTick = nextTick(1); + restartingBaritone = false; +} + +@Override +public boolean onTick(int tick) { +if(tick == nextTick) { + if(playerPos.equals(mc.player.getPosition())) { + if(restartingBaritone) { + restartingBaritone = false; + mc.player.sendChatMessage("#goto ~" + (destination.getX() - (int) Math.floor(mc.player.posX)) + " ~" + (destination.getY() - (int) Math.floor(mc.player.posY)) + " ~" + (destination.getZ() - (int) Math.floor(mc.player.posZ))); + nextTick = nextTick(400); + } else { + if(playerPos.getDistance(destination.getX(), destination.getY(), destination.getZ()) < 10) { + if(destinations.isEmpty()) { + Chung.sendMessage("Final destination reached"); + Chung.runningActivities.remove(this); + if(!playerPos.equals(destination)) stop(); + return true; + } else destination = destinations.remove(); + } + restartingBaritone = true; + mc.player.sendChatMessage("#cancel"); + nextTick = nextTick(40); + } + } else { + nextTick = nextTick(400); + } + playerPos = mc.player.getPosition(); +} +return false; +} + +@Override +public void stop() { + mc.player.sendChatMessage("#cancel"); +} + +} \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/auto/RotationAntiAFK.java b/src/main/java/magnileve/chungamod/auto/RotationAntiAFK.java new file mode 100644 index 0000000..1bd84db --- /dev/null +++ b/src/main/java/magnileve/chungamod/auto/RotationAntiAFK.java @@ -0,0 +1,58 @@ +package magnileve.chungamod.auto; + +import magnileve.chungamod.time.Activity; +import magnileve.chungamod.time.TickListener; +import magnileve.chungamod.time.TickTimer; +import net.minecraft.client.Minecraft; +import net.minecraft.network.play.client.CPacketPlayer; + +public class RotationAntiAFK implements TickListener, Activity { + +private Minecraft mc; +private int nextTick; +private float playerYaw; +private byte changeNumber; + +/** + * Sends rotation packets every 25 seconds to avoid afk detection. + * @param mc instance of Mincerfat + */ +public RotationAntiAFK(Minecraft mc) { + this.mc = mc; + playerYaw = mc.player.rotationYaw; + changeNumber = 0; + TickTimer.addListener(this); + nextTick = nextTick(1); +} + +@Override +public boolean onTick(int tick) { +if(nextTick == tick) { + switch(changeNumber) { + case 0: + playerYaw = mc.player.rotationYaw; + mc.player.connection.sendPacket(new CPacketPlayer.Rotation((float) playerYaw + 1, (float) mc.player.rotationPitch, mc.player.onGround)); + break; + case 1: + mc.player.connection.sendPacket(new CPacketPlayer.Rotation((float) playerYaw - 1, (float) mc.player.rotationPitch, mc.player.onGround)); + break; + case 2: + mc.player.connection.sendPacket(new CPacketPlayer.Rotation((float) playerYaw, (float) mc.player.rotationPitch, mc.player.onGround)); + break; + } + if(changeNumber == 2) { + changeNumber = 0; + nextTick = nextTick(960); + } else { + changeNumber++; + nextTick = nextTick(20); + } +} +return false; +} + +@Override +public void stop() { + if(changeNumber != 0) mc.player.connection.sendPacket(new CPacketPlayer.Rotation((float) playerYaw, (float) mc.player.rotationPitch, mc.player.onGround)); +} +} \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/itemstorage/AutoSort.java b/src/main/java/magnileve/chungamod/auto/itemstorage/AutoSort.java similarity index 83% rename from src/main/java/magnileve/chungamod/itemstorage/AutoSort.java rename to src/main/java/magnileve/chungamod/auto/itemstorage/AutoSort.java index b0f9e56..89ee3f6 100644 --- a/src/main/java/magnileve/chungamod/itemstorage/AutoSort.java +++ b/src/main/java/magnileve/chungamod/auto/itemstorage/AutoSort.java @@ -1,11 +1,11 @@ -package magnileve.chungamod.itemstorage; +package magnileve.chungamod.auto.itemstorage; import java.util.LinkedList; import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.Logger; -import magnileve.chungamod.Ref; +import magnileve.chungamod.Chung; import magnileve.chungamod.settings.Settings; import magnileve.chungamod.time.Activity; import magnileve.chungamod.time.TickListener; @@ -55,10 +55,29 @@ public class AutoSort implements TickListener, Activity { private EnumFacing destinationOffset; private boolean goToOverflow; +/** + * Automatically sorts shulker boxes into chests with the shulker boxes' names labeled on signs. + * @param mcIn instance of Mincerfat + * @param pos1 looks for signs with shulker box names connected to a stack of chests between this and pos2 + * @param pos2 looks for signs with shulker box names connected to a stack of chests between this and pos1 + * @param sourceIn takes shulker boxes out of the chest at this location + * @param sourceEmptyTimeout how many seconds to wait when the source is empty before stopping + * @param overflowIn where to put shulker boxes which either don't have a designated chest or have full storage + * @param logIn instance of logger + */ public AutoSort(Minecraft mcIn, BlockPos pos1, BlockPos pos2, BlockPos sourceIn, short sourceEmptyTimeout, BlockPos overflowIn, Logger logIn) { this(mcIn, getStorageUnits(mcIn, pos1, pos2, logIn), sourceIn, sourceEmptyTimeout, overflowIn, logIn); } +/** + * Automatically sorts shulker boxes into chests with the shulker boxes' names labeled on signs. + * @param mcIn instance of Mincerfat + * @param sortLocationsIn stacks of chests to put shulker boxes with matching names into + * @param sourceIn takes shulker boxes out of the chest at this location + * @param sourceEmptyTimeout how many seconds to wait when the source is empty before stopping + * @param overflowIn where to put shulker boxes which either don't have a designated chest or have full storage + * @param logIn instance of logger + */ public AutoSort(Minecraft mcIn, LinkedList sortLocationsIn, BlockPos sourceIn, short sourceEmptyTimeout, BlockPos overflowIn, Logger logIn) { mc = mcIn; connection = mc.player.connection; @@ -71,8 +90,8 @@ public AutoSort(Minecraft mcIn, LinkedList sortLocationsIn, BlockPo goToOverflow = false; if(sortLocations == null || source.getDistance((int) mc.player.posX, (int) mc.player.posY, (int) mc.player.posZ) > 250 || (overflow == null ? false : overflow.getDistance((int) mc.player.posX, (int) mc.player.posY, (int) mc.player.posZ) > 250)) { - Ref.sendMessage("AutoSort error: Chests too far away"); - Ref.runningActivities.remove(this); + Chung.sendMessage("AutoSort error: Chests too far away"); + Chung.runningActivities.remove(this); sourceFacing = null; overflowFacing = null; sourceDoubleChest = false; @@ -115,8 +134,7 @@ public AutoSort(Minecraft mcIn, LinkedList sortLocationsIn, BlockPo slot = 9; status = Status.SEARCHING_STORAGE; TickTimer.addListener(this); - nextTick(1); - log.debug("finished initialization"); + nextTick = nextTick(1); } private static LinkedList getStorageUnits(Minecraft mc, BlockPos pos1, BlockPos pos2, Logger log) { @@ -170,7 +188,7 @@ private static LinkedList getStorageUnits(Minecraft mc, BlockPos po } @Override -public void onTick(int tick) { +public boolean onTick(int tick) { if(tick == nextTick) { try { switch(status) { @@ -194,13 +212,11 @@ public void onTick(int tick) { } } double dz = destination.getZ() - mc.player.posZ + 0.5; - log.debug("Start chest coords: " + (dx + mc.player.posX) + ", " + (dy + mc.player.posY) + ", " + (dz + mc.player.posZ)); double yawToPlayer = -Math.atan2(dx, dz) + Math.PI; double edgeOfBlockRadius = Math.min(Math.abs(1 / Math.cos(yawToPlayer)), Math.abs(1 / Math.sin(yawToPlayer))) / 2; dx += -Math.sin(yawToPlayer) * edgeOfBlockRadius; dz += Math.cos(yawToPlayer) * edgeOfBlockRadius; - log.debug("Shifted chest coords: " + (dx + mc.player.posX) + ", " + (dy + mc.player.posY) + ", " + (dz + mc.player.posZ)); double r = Math.sqrt(dx * dx + dy * dy + dz * dz); double yaw = -Math.atan2(dx, dz) / Math.PI * 180; @@ -209,7 +225,7 @@ public void onTick(int tick) { mc.player.connection.sendPacket(new CPacketPlayer.Rotation((float) yaw, (float) pitch, mc.player.onGround)); Vec3d vec3d = mc.player.getPositionEyes(1.0F); - Vec3d vec3d1 = Ref.getVectorForRotation((float) pitch, (float) yaw); + Vec3d vec3d1 = Chung.getVectorForRotation((float) pitch, (float) yaw); Vec3d vec3d2 = vec3d.addVector(vec3d1.x * 4.5D, vec3d1.y * 4.5D, vec3d1.z * 4.5D); RayTraceResult rayTrace = mc.world.rayTraceBlocks(vec3d, vec3d2, false, false, true); @@ -225,29 +241,29 @@ public void onTick(int tick) { else status = Status.WAITING_ON_OVERFLOW; prevDistance = 0D; - nextTick((Byte) Settings.get("tickdelay")); + nextTick = nextTick((Byte) Settings.get("tick_delay")); } else { if(distance == prevDistance) { if(stuckCheck + distance * 5 > 127) stuckCheck = 127; else stuckCheck += distance * 5; } prevDistance = distance; - nextTick((int) (distance * 5)); + nextTick = nextTick((int) (distance * 5)); } break; case WAITING_ON_SOURCE: if(mc.player.openContainer.windowId == 0) { stuckCheck++; - nextTick(1); + nextTick = nextTick(1); break; } else { stuckCheck = 0; slot = -1; moveSlot = 0; status = Status.TAKING_SHULKERS; - log.debug("[AutoSort] Taking shulkers"); + log.info("[AutoSort] Taking shulkers"); if((short) Settings.get("autosort", "chest_open_tick_delay") > 0) { - nextTick((short) Settings.get("autosort", "chest_open_tick_delay")); + nextTick = nextTick((short) Settings.get("autosort", "chest_open_tick_delay")); break; } } @@ -256,13 +272,14 @@ public void onTick(int tick) { if(moveSlot == 0) { status = Status.SOURCE_EMPTY_TIMEOUT; if(sourceEmptyTimeout != 0) { - nextTick(sourceEmptyTimeout * 40); + nextTick = nextTick(sourceEmptyTimeout * 40); break; } } else { mc.player.closeScreen(); slot = 9; status = Status.SEARCHING_STORAGE; + log.info("[AutoSort] Going to storage"); } } else { for(slot++; slot < (sourceDoubleChest ? 54 : 27); slot++) { @@ -278,7 +295,7 @@ public void onTick(int tick) { } } } - nextTick((Byte) Settings.get("tickdelay")); + nextTick = nextTick((Byte) Settings.get("tick_delay")); break; case SEARCHING_STORAGE: if(mc.player.openContainer.windowId == 0) { @@ -307,25 +324,25 @@ public void onTick(int tick) { } else { if(goToOverflow && overflow != null) { status = Status.GOING_TO_OVERFLOW; - log.debug("[AutoSort] Going to overflow"); + log.info("[AutoSort] Going to overflow"); destination = overflow; destinationOffset = overflowFacing; goToOverflow = false; } else { status = Status.GOING_TO_SOURCE; - log.debug("[AutoSort] Going to source"); + log.info("[AutoSort] Going to source"); destination = source; destinationOffset = sourceFacing; } } mc.player.sendChatMessage("#goto ~" + (destination.offset(destinationOffset).getX() - (int) Math.floor(mc.player.posX)) + " ~" + (destination.getY() - (int) Math.floor(mc.player.posY)) + " ~" + (destination.offset(destinationOffset).getZ() - (int) Math.floor(mc.player.posZ))); } else stuckCheck++; - nextTick(1); + nextTick = nextTick(1); break; case WAITING_ON_STORAGE: if(mc.player.openContainer.windowId == 0) { stuckCheck++; - nextTick(1); + nextTick = nextTick(1); break; } else { stuckCheck = 0; @@ -337,21 +354,21 @@ public void onTick(int tick) { } else { sortLocations.remove(unit); if(sortLocations.size() == 0) { - Ref.sendMessage("[AutoSort] Storage full"); + Chung.sendMessage("[AutoSort] Storage full"); stop(); - Ref.runningActivities.remove(this); - break; + Chung.runningActivities.remove(this); + return true; } status = Status.SEARCHING_STORAGE; } - nextTick(1); + nextTick = nextTick(1); break; } else { moveSlot = (byte) (slot + (unit.isDoubleChest() ? 44 : 17)); status = Status.PUTTING_SHULKERS; log.debug("Putting shulkers: " + unit.getName()); if((short) Settings.get("autosort", "chest_open_tick_delay") > 0) { - nextTick((short) Settings.get("autosort", "chest_open_tick_delay")); + nextTick = nextTick((short) Settings.get("autosort", "chest_open_tick_delay")); break; } } @@ -371,12 +388,12 @@ public void onTick(int tick) { mc.player.closeScreen(); status = Status.SEARCHING_STORAGE; } else if(mc.player.openContainer.getSlot(unit.isDoubleChest() ? 53 : 26).getHasStack()) status = Status.WAITING_ON_STORAGE; - nextTick((Byte) Settings.get("tickdelay")); + nextTick = nextTick((Byte) Settings.get("tick_delay")); break; case WAITING_ON_OVERFLOW: if(mc.player.openContainer.windowId == 0) { stuckCheck++; - nextTick(1); + nextTick = nextTick(1); break; } else { stuckCheck = 0; @@ -384,7 +401,7 @@ public void onTick(int tick) { status = Status.DUMPING_SHULKERS; log.debug("[AutoSort] Dumping shulkers"); if((short) Settings.get("autosort", "chest_open_tick_delay") > 0) { - nextTick((short) Settings.get("autosort", "chest_open_tick_delay")); + nextTick = nextTick((short) Settings.get("autosort", "chest_open_tick_delay")); break; } } @@ -404,12 +421,12 @@ public void onTick(int tick) { slot = 9; status = Status.SEARCHING_STORAGE; } else if(mc.player.openContainer.getSlot(overflowDoubleChest ? 53 : 26).getHasStack() && mc.player.openContainer.getSlot(0).getHasStack()) { - Ref.sendMessage("[AutoSort] Overflow chest full"); + Chung.sendMessage("[AutoSort] Overflow chest full"); stop(); - Ref.runningActivities.remove(this); - break; + Chung.runningActivities.remove(this); + return true; } - nextTick((Byte) Settings.get("tickdelay")); + nextTick = nextTick((Byte) Settings.get("tick_delay")); break; case SOURCE_EMPTY_TIMEOUT: Slot thisSlot = mc.player.openContainer.getSlot(0); @@ -423,45 +440,42 @@ public void onTick(int tick) { } } mc.player.closeScreen(); - Ref.sendMessage("[AutoSort] Finished sorting"); + Chung.sendMessage("[AutoSort] Finished sorting"); stop(); - Ref.runningActivities.remove(this); - break; + Chung.runningActivities.remove(this); + return true; } } catch(Exception e) { - Ref.sendMessage("Exception in AutoSort: " + e.getClass().getName() + (e.getMessage() == null ? "" : ": " + e.getMessage())); log.catching(Level.ERROR, e); + Chung.sendMessage("Exception in AutoSort: " + e.getClass().getName() + (e.getMessage() == null ? "" : ": " + e.getMessage())); stop(); - Ref.runningActivities.remove(this); + Chung.runningActivities.remove(this); + return true; } if(stuckCheck == 127) { - log.warn("Autosort stuck\nStatus: {}\nStorage chests: {}\nDestination: {}\nPlayer window ID: {}\nDistance to destination: {}\nSlot: {}\nMoveSlot: {}", status, sortLocations, destination, mc.player.openContainer.windowId, prevDistance, slot, moveSlot); - Ref.sendMessage("Autosort stuck in status: " + status); + Chung.sendMessage("AutoSort stuck in status: " + status); + log.warn("AutoSort stuck\nStatus: {}\nStorage chests: {}\nDestination: {}\nPlayer window ID: {}\nDistance to destination: {}\nSlot: {}\nMoveSlot: {}", status, sortLocations, destination, mc.player.openContainer.windowId, prevDistance, slot, moveSlot); stop(); - Ref.runningActivities.remove(this); - Ref.runningActivities.add(new AutoSort(mc, sortLocations, source, sourceEmptyTimeout, overflow, log)); + Chung.runningActivities.remove(this); + Chung.runningActivities.add(new AutoSort(mc, sortLocations, source, sourceEmptyTimeout, overflow, log)); + return true; } } +return false; } @Override public void stop() { log.info("[AutoSort] Stopping AutoSort"); if(status.equals(Status.GOING_TO_SOURCE) || status.equals(Status.GOING_TO_STORAGE) || status.equals(Status.GOING_TO_OVERFLOW)) mc.player.sendChatMessage("#cancel"); - TickTimer.removeListener(this); } -private enum Status { - GOING_TO_SOURCE, WAITING_ON_SOURCE, TAKING_SHULKERS, SEARCHING_STORAGE, GOING_TO_STORAGE, WAITING_ON_STORAGE, PUTTING_SHULKERS, GOING_TO_OVERFLOW, WAITING_ON_OVERFLOW, DUMPING_SHULKERS, SOURCE_EMPTY_TIMEOUT -} - -private void nextTick(int tick) { - nextTick = TickTimer.current() + tick; - TickTimer.add(tick); +public static boolean isChest(int blockID) { + return (blockID == 54 || blockID == 146); } -private static boolean isChest(int blockID) { - return (blockID == 54 || blockID == 146); +private enum Status { + GOING_TO_SOURCE, WAITING_ON_SOURCE, TAKING_SHULKERS, SEARCHING_STORAGE, GOING_TO_STORAGE, WAITING_ON_STORAGE, PUTTING_SHULKERS, GOING_TO_OVERFLOW, WAITING_ON_OVERFLOW, DUMPING_SHULKERS, SOURCE_EMPTY_TIMEOUT } } \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/itemstorage/StorageUnit.java b/src/main/java/magnileve/chungamod/auto/itemstorage/StorageUnit.java similarity index 95% rename from src/main/java/magnileve/chungamod/itemstorage/StorageUnit.java rename to src/main/java/magnileve/chungamod/auto/itemstorage/StorageUnit.java index f997b66..429ad65 100644 --- a/src/main/java/magnileve/chungamod/itemstorage/StorageUnit.java +++ b/src/main/java/magnileve/chungamod/auto/itemstorage/StorageUnit.java @@ -1,4 +1,4 @@ -package magnileve.chungamod.itemstorage; +package magnileve.chungamod.auto.itemstorage; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; diff --git a/src/main/java/magnileve/chungamod/settings/CustomChatSuffix.java b/src/main/java/magnileve/chungamod/settings/CustomChatSuffix.java new file mode 100644 index 0000000..b813753 --- /dev/null +++ b/src/main/java/magnileve/chungamod/settings/CustomChatSuffix.java @@ -0,0 +1,130 @@ +package magnileve.chungamod.settings; + +import java.util.LinkedList; + +import org.apache.logging.log4j.Logger; + +import magnileve.chungamod.Chung; +import magnileve.chungamod.time.TickTimer; +import net.minecraft.client.Minecraft; +import net.minecraftforge.client.event.ClientChatEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.EventPriority; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@Mod.EventBusSubscriber(modid=Chung.MODID) +public class CustomChatSuffix implements SettingListener { + +private static Minecraft mc; +private static Logger log; +private static LinkedList ignoredPrefixes; +private static String suffix; +private static String chungamodPrefix; +private static boolean off; +private static boolean addingSuffix; + +public static void init(Minecraft mcIn, Logger logIn) { + Settings.addListener(new CustomChatSuffix()); + mc = mcIn; + log = logIn; + addingSuffix = false; +} + +public CustomChatSuffix() { + suffix = (boolean) Settings.get("custom_chat_suffix", "add_space") ? " ".concat((String) Settings.get("custom_chat_suffix", "suffix")) : (String) Settings.get("custom_chat_suffix", "suffix"); + chungamodPrefix = (String) Settings.get("prefix"); + off = !(boolean) Settings.get("custom_chat_suffix", "on"); + String[] array = ((String) Settings.get("custom_chat_suffix", "ignored_prefixes")).substring(1).split("\""); + ignoredPrefixes = new LinkedList<>(); + boolean even = true; + for(String str:array) { + if(even) { + even = false; + ignoredPrefixes.add(str); + } else { + even = true; + if(!str.equals(" ")) break; + } + } + if(even && array.length != 0) { + Settings.set("custom_chat_suffix", null); + array = ((String) Settings.get("custom_chat_suffix", "ignored_prefixes")).substring(1).split("\""); + ignoredPrefixes.clear(); + for(byte i = 0; i < array.length; i += 2) ignoredPrefixes.add(array[i]); + } +} + +@SubscribeEvent(priority = EventPriority.HIGHEST) +@SideOnly(value = Side.CLIENT) +public static void onClientChatEvent(ClientChatEvent event) { + if(off) return; + String message = event.getMessage(); + if(message.startsWith(chungamodPrefix)) return; + for(String prefix:ignoredPrefixes) if(message.startsWith(prefix)) return; + addingSuffix = true; + mc.ingameGUI.getChatGUI().addToSentMessages(message); + event.setMessage(message.concat(suffix)); +} + +@SubscribeEvent(priority = EventPriority.LOWEST) +@SideOnly(value = Side.CLIENT) +public static void onClientChatEvent2(ClientChatEvent event) { + if(addingSuffix) { + addingSuffix = false; + event.setCanceled(true); + if(net.minecraftforge.client.ClientCommandHandler.instance.executeCommand(mc.player, event.getMessage()) != 0) return; + mc.player.sendChatMessage(event.getMessage()); + } +} + +@Override +public void onNewValue(String setting, Object value) { + switch(setting) { + case "prefix": + chungamodPrefix = (String) value; + break; + case "on": + off = !(boolean) value; + break; + case "suffix": + suffix = (boolean) Settings.get("custom_chat_suffix", "add_space") ? " ".concat((String) value) : (String) value; + break; + case "ignored_prefixes": + String[] array = ((String) value).substring(1).split("\""); + LinkedList list = new LinkedList<>(); + boolean even = true; + if(((String) value).charAt(0) == '\"' && ((String) value).charAt(((String) value).length() - 1) == '\"') for(String str:array) { + if(even) { + even = false; + list.add(str); + } else { + even = true; + if(!str.equals(" ")) break; + } + } + if(even) { + log.info("Syntax error in ignored prefixes"); + StringBuilder str = new StringBuilder(); + for(String prefix:ignoredPrefixes) if(!prefix.isEmpty()) str.append("\" \"").append(prefix); + TickTimer.addListener(tick -> { + Settings.set("custom_chat_suffix", "ignored_prefixes", str.length() == 0 ? "" : str.append("\"").substring(2)); + Chung.sendMessage("Syntax error: separate prefixes with spaces, and put each prefix in quotes"); + return true; + }); + TickTimer.add(1); + } else ignoredPrefixes = list; + break; + case "add_space": + suffix = (boolean) value ? " ".concat((String) Settings.get("custom_chat_suffix", "suffix")) : (String) Settings.get("custom_chat_suffix", "suffix"); + break; + } +} + +@Override +public boolean hasSetting(String setting) { + return setting.equals("prefix") || setting.startsWith("custom_chat_suffix"); +} + +} \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/settings/DiscordRPCManager.java b/src/main/java/magnileve/chungamod/settings/DiscordRPCManager.java index a54d10d..ca34de2 100644 --- a/src/main/java/magnileve/chungamod/settings/DiscordRPCManager.java +++ b/src/main/java/magnileve/chungamod/settings/DiscordRPCManager.java @@ -1,6 +1,6 @@ package magnileve.chungamod.settings; -import magnileve.chungamod.Ref; +import magnileve.chungamod.Chung; import net.arikia.dev.drpc.DiscordEventHandlers; import net.arikia.dev.drpc.DiscordRPC; import net.arikia.dev.drpc.DiscordRichPresence; @@ -8,7 +8,7 @@ public class DiscordRPCManager implements SettingListener { private final String[] SETTING_LIST = {"visible", "upper_line", "lower_line", "minecraft_name", "minecraft_version"}; -private final String[] STATUS_LIST = {"Playing \\Mincerfat \\version", "The funniest client", "Version " + Ref.VERSION, "v" + Ref.VERSION + " | \\Mincerfat \\version", "9b9t.org", "9b9t.com", "2b2t.org", "2b2t.com", "Hypixel.net", "All hail Big Chungus", "Big Chungus on top", "ok", "ok chains on top", "Building highways", "Digging nether tunnels", "NHS on top", "Chungamod on top", "Chungia on top", "NHS > HWU", "9b9t > 2b2t"}; +private final String[] STATUS_LIST = {"Playing \\Mincerfat \\version", "The funniest client", "Version " + Chung.VERSION, "v" + Chung.VERSION + " | \\Mincerfat \\version", "9b9t.org", "9b9t.com", "2b2t.org", "2b2t.com", "Hypixel.net", "All hail Big Chungus", "Big Chungus on top", "ok", "ok chains on top", "Building highways", "Digging nether tunnels", "NHS on top", "Chungamod on top", "Chungia on top", "9b9t on top", "9b9t > 2b2t"}; private final String[] MINCERFAT_NAME_LIST = {"Minecraft", "Mincerfat", "Minceraft", "block game"}; private final String[] MINCERFAT_VERSION_LIST = {"1.12", "1.12.2"}; private final long START_TIME; @@ -22,7 +22,7 @@ public class DiscordRPCManager implements SettingListener { public DiscordRPCManager() { START_TIME = System.currentTimeMillis() / 1000; - java.lang.Runtime.getRuntime().addShutdownHook(new Thread() { + Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if((boolean) Settings.get("discordrpc", "visible")) DiscordRPC.discordShutdown(); @@ -45,25 +45,25 @@ public void onNewValue(String setting, Object value) { switch(setting) { case "upper_line": if((byte) value > STATUS_LIST.length) { - Ref.sendMessage("Value must not be greater than " + STATUS_LIST.length); + Chung.sendMessage("Value must not be greater than " + STATUS_LIST.length); Settings.set("discordrpc", setting, details); } else details = (byte) value; break; case "lower_line": if((byte) value > STATUS_LIST.length) { - Ref.sendMessage("Value must not be greater than " + STATUS_LIST.length); + Chung.sendMessage("Value must not be greater than " + STATUS_LIST.length); Settings.set("discordrpc", setting, state); } else state = (byte) value; break; case "minecraft_name": if((byte) value > STATUS_LIST.length) { - Ref.sendMessage("Value must not be greater than " + MINCERFAT_NAME_LIST.length); + Chung.sendMessage("Value must not be greater than " + MINCERFAT_NAME_LIST.length); Settings.set("discordrpc", setting, mincerfatName); } else mincerfatName = (byte) value; break; case "minecraft_version": if((byte) value > STATUS_LIST.length) { - Ref.sendMessage("Value must not be greater than " + MINCERFAT_VERSION_LIST.length); + Chung.sendMessage("Value must not be greater than " + MINCERFAT_VERSION_LIST.length); Settings.set("discordrpc", setting, mincerfatVersion); } else mincerfatVersion = (byte) value; break; @@ -109,7 +109,6 @@ public String getSettingValues() { return str.toString(); } -//setup DiscordRPC private void discordRPCupdate() { DiscordRPC.discordUpdatePresence(new DiscordRichPresence.Builder(format(STATUS_LIST[state - 1])).setBigImage("chungamod-logo", "All hail Big Chungus").setDetails(format(STATUS_LIST[details - 1])).setStartTimestamps(START_TIME).build()); } diff --git a/src/main/java/magnileve/chungamod/settings/LogSetting.java b/src/main/java/magnileve/chungamod/settings/LogSetting.java deleted file mode 100644 index 8716e9e..0000000 --- a/src/main/java/magnileve/chungamod/settings/LogSetting.java +++ /dev/null @@ -1,39 +0,0 @@ -package magnileve.chungamod.settings; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.Logger; - -public class LogSetting implements SettingListener { - -private Logger log; -private Level defaultLevel; -private boolean currentSetting; - -public LogSetting(Logger log) { - this.log = log; - currentSetting = (boolean) Settings.get("debug"); - if(currentSetting) { - defaultLevel = log.getLevel(); - log.setLevel(Level.DEBUG); - log.debug("Log level set to debug"); - } -} - -@Override -public void onNewValue(String setting, Object value) { - if(setting.equals("debug") && !((Boolean) value).equals(currentSetting)) { - currentSetting = (Boolean) value; - if((Boolean) value) { - defaultLevel = log.getLevel(); - log.setLevel(Level.DEBUG); - log.debug("Log level set to debug"); - } else log.setLevel(defaultLevel); - } -} - -@Override -public boolean hasSetting(String setting) { - return setting.equals("debug"); -} - -} \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/settings/SettingListener.java b/src/main/java/magnileve/chungamod/settings/SettingListener.java index d61d4f6..f0b3211 100644 --- a/src/main/java/magnileve/chungamod/settings/SettingListener.java +++ b/src/main/java/magnileve/chungamod/settings/SettingListener.java @@ -1,6 +1,19 @@ package magnileve.chungamod.settings; public interface SettingListener { - public void onNewValue(String setting, Object value); - public boolean hasSetting(String setting); + +/** + * Called when the value of a setting is changed. + * @param setting name of setting + * @param value new value of setting + */ +public void onNewValue(String setting, Object value); + +/** + * Checks if a listener is listening for a change in the value of a certain setting. + * @param setting name of setting + * @return true if the listener is listening for a change in the value of this setting + */ +public boolean hasSetting(String setting); + } \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/settings/Settings.java b/src/main/java/magnileve/chungamod/settings/Settings.java index a918957..4e10278 100644 --- a/src/main/java/magnileve/chungamod/settings/Settings.java +++ b/src/main/java/magnileve/chungamod/settings/Settings.java @@ -11,7 +11,7 @@ import java.util.LinkedList; import java.util.Map.Entry; -import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.Logger; import net.minecraft.util.math.BlockPos; @@ -30,9 +30,11 @@ private static final HashMap settingValues() { Object[] discordRPCSettings = {"visible upper_line lower_line minecraft_name minecraft_version", Type.BOOLEAN, Type.BYTE_POSITIVE, Type.BYTE_POSITIVE, Type.BYTE_POSITIVE, Type.BYTE_POSITIVE}; settingValues.put("discordrpc", discordRPCSettings); settingValues.put("debug", Type.BOOLEAN); - settingValues.put("tickdelay", Type.BYTE_POSITIVE); + settingValues.put("tick_delay", Type.BYTE_POSITIVE); Object[] autoSortSettings = {"pos1 pos2 source chest_open_tick_delay source_empty_timeout overflow", Type.BLOCKPOS, Type.BLOCKPOS, Type.BLOCKPOS, Type.SHORT, Type.SHORT, Type.BLOCKPOS}; settingValues.put("autosort", autoSortSettings); + Object[] chatSuffixSettings = {"on suffix ignored_prefixes add_space", Type.BOOLEAN, Type.STRING, Type.STRING, Type.BOOLEAN}; + settingValues.put("custom_chat_suffix", chatSuffixSettings); return settingValues; } @@ -42,9 +44,11 @@ private static final HashMap defaultSettings() { Object[] discordRPCSettings = {"visible upper_line lower_line minecraft_name minecraft_version", true, new Byte((byte) 1), new Byte((byte) 2), new Byte((byte) 1), new Byte((byte) 1)}; defaultSettings.put("discordrpc", discordRPCSettings); defaultSettings.put("debug", false); - defaultSettings.put("tickdelay", new Byte((byte) 2)); + defaultSettings.put("tick_delay", new Byte((byte) 2)); Object[] autoSortSettings = {"pos1 pos2 source chest_open_tick_delay source_empty_timeout overflow", null, null, null, new Short((short) 2), new Short((short) 2), null}; defaultSettings.put("autosort", autoSortSettings); + Object[] chatSuffixSettings = {"on suffix ignored_prefixes add_space", true, "`Chungamod", "\"/\"", true}; + defaultSettings.put("custom_chat_suffix", chatSuffixSettings); return defaultSettings; } @@ -55,8 +59,24 @@ private static final String settingList() { return str.toString(); } +public static void init(Logger logIn) { + log = logIn; + settings = load(); + listeners = new LinkedList(); +} + +/** + * Gets the value of a setting that is not a feature setting. + * @param setting name of setting + * @return value of setting + */ public static Object get(String setting) { Object returnSetting = settings.get(setting); + if(returnSetting == null && getValue(setting) instanceof Type && (Type) getValue(setting) != Type.BLOCKPOS) { + log.error("Setting null for " + setting); + settings.put(setting, DEFAULT_SETTINGS.get(setting)); + returnSetting = settings.get(setting); + } if(returnSetting instanceof Integer[]) { Integer[] integersValue = (Integer[]) returnSetting; BlockPos blockPosValue = new BlockPos(integersValue[0], integersValue[1], integersValue[2]); @@ -65,6 +85,12 @@ public static Object get(String setting) { return returnSetting; } +/** + * Gets the value of a setting that is a feature setting. + * @param feature name of feature + * @param setting name of setting + * @return value of setting + */ public static Object get(String feature, String setting) { Object returnSetting; try { @@ -90,6 +116,11 @@ public static Object get(String feature, String setting) { return returnSetting; } +/** + * Sets the value of a setting that is not a feature setting. + * @param setting name of setting + * @param value new value of setting + */ public static void set(String setting, Object value) { if(value instanceof BlockPos) { BlockPos blockPosValue = (BlockPos) value; @@ -101,6 +132,12 @@ public static void set(String setting, Object value) { for(SettingListener listener:listeners) if(listener.hasSetting(setting)) listener.onNewValue(setting, value); } +/** + * Sets the value of a setting that is a feature setting. + * @param feature name of feature + * @param setting name of setting + * @param value new value of setting + */ public static void set(String feature, String setting, Object value) { if(value instanceof BlockPos) { BlockPos blockPosValue = (BlockPos) value; @@ -128,29 +165,33 @@ public static void set(String feature, String setting, Object value) { for(SettingListener listener:listeners) if(listener.hasSetting(feature + " " + setting)) listener.onNewValue(setting, value); } +/** + * Gets the type of value for a setting. + * @param setting name of setting + * @return type of value the setting holds + */ public static Object getValue(String setting) { return SETTING_VALUES.get(setting); } -public static Class getValue(String feature, String setting) { - Object[] featureSettings = (Object[]) SETTING_VALUES.get(feature); - String[] settingNames = ((String) (featureSettings[0])).split(" "); - byte i = 0; - while(!settingNames[i].equalsIgnoreCase(setting)) i++; - return (Class) featureSettings[i + 1]; -} - +/** + * Adds listener for changing setting values + * @param listener listener to be added + */ public static void addListener(SettingListener listener) { listeners.add(listener); } +/** + * Removes listener for changing setting values + * @param listener listener to be removed + */ public static void removeListener(SettingListener listener) { listeners.remove(listener); } @SuppressWarnings("unchecked") -public static void load(Logger logger) { - log = logger; +private static HashMap load() { HashMap loadedSettings; Object getSettingsResult = null; HashMap getSettings; @@ -194,8 +235,7 @@ public static void load(Logger logger) { loadedSettings = DEFAULT_SETTINGS; save(loadedSettings); } - settings = loadedSettings; - listeners = new LinkedList(); + return loadedSettings; } private static void save(HashMap settings) { diff --git a/src/main/java/magnileve/chungamod/time/Activity.java b/src/main/java/magnileve/chungamod/time/Activity.java index a6e68f8..3347e47 100644 --- a/src/main/java/magnileve/chungamod/time/Activity.java +++ b/src/main/java/magnileve/chungamod/time/Activity.java @@ -1,5 +1,10 @@ package magnileve.chungamod.time; public interface Activity { - public void stop(); + +/** + * Called when the activity is turning off. + */ +public void stop(); + } diff --git a/src/main/java/magnileve/chungamod/time/ClientTps.java b/src/main/java/magnileve/chungamod/time/ClientTps.java index 2e0a597..7985a43 100644 --- a/src/main/java/magnileve/chungamod/time/ClientTps.java +++ b/src/main/java/magnileve/chungamod/time/ClientTps.java @@ -1,31 +1,34 @@ package magnileve.chungamod.time; -import magnileve.chungamod.Ref; +import magnileve.chungamod.Chung; public class ClientTps implements TickListener, Activity { + +private byte tickCount; +private long time; + +/** + * Measures and sends client tps in chat every 256 ticks. + */ +public ClientTps() { + tickCount = 0; + time = System.currentTimeMillis(); + TickTimer.addListener(this); + TickTimer.add(1); +} +@Override +public void stop() { - private byte tickCount; - private long time; - - public ClientTps() { - tickCount = 0; - time = System.currentTimeMillis(); - TickTimer.addListener(this); - TickTimer.add(1); - } - @Override - public void stop() { - TickTimer.removeListener(this); - Ref.runningActivities.remove(this); - } +} - @Override - public void onTick(int tick) { - tickCount++; - if(tickCount == 0) { - Ref.sendMessage("Current Client TPS: " + (1 / (((double) (System.currentTimeMillis() - time)) / 256000))); - time = System.currentTimeMillis(); - } - TickTimer.add(1); +@Override +public boolean onTick(int tick) { + tickCount++; + if(tickCount == 0) { + Chung.sendMessage("Current Client TPS: " + (1 / (((double) (System.currentTimeMillis() - time)) / 256000))); + time = System.currentTimeMillis(); } + TickTimer.add(1); + return false; +} } diff --git a/src/main/java/magnileve/chungamod/time/LeaveServerListener.java b/src/main/java/magnileve/chungamod/time/LeaveServerListener.java new file mode 100644 index 0000000..7024c5d --- /dev/null +++ b/src/main/java/magnileve/chungamod/time/LeaveServerListener.java @@ -0,0 +1,36 @@ +package magnileve.chungamod.time; + +import org.apache.logging.log4j.Logger; + +import magnileve.chungamod.Chung; +import net.minecraft.client.Minecraft; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@Mod.EventBusSubscriber(modid=Chung.MODID) +public class LeaveServerListener { + +private static Minecraft mc; +private static Logger log; + +public static void init(Minecraft mcIn, Logger logIn) { + mc = mcIn; + log = logIn; +} + +@SubscribeEvent +@SideOnly(value = Side.CLIENT) +public static void onClientDisconnectEvent(ClientDisconnectionFromServerEvent event) { + log.info("Stopping running activities"); + for(Activity activity:Chung.runningActivities) { + log.info("Class: {} Restartable: {} TickListener: {}", activity.getClass().getName(), activity instanceof RestartableActivity, activity instanceof TickListener); + if(activity instanceof RestartableActivity) new RelogActivityListener(((RestartableActivity) activity), ((RestartableActivity) activity).getNearbyPosition(), mc, log); + if(activity instanceof TickListener) TickTimer.removeListener((TickListener) activity); + } + Chung.runningActivities.clear(); +} + +} \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/time/RelogActivityListener.java b/src/main/java/magnileve/chungamod/time/RelogActivityListener.java new file mode 100644 index 0000000..645cec7 --- /dev/null +++ b/src/main/java/magnileve/chungamod/time/RelogActivityListener.java @@ -0,0 +1,48 @@ +package magnileve.chungamod.time; + +import org.apache.logging.log4j.Logger; + +import net.minecraft.client.Minecraft; +import net.minecraft.util.math.BlockPos; + +public class RelogActivityListener implements TickListener { + +private Minecraft mc; +private Logger log; +private RestartableActivity activity; +private BlockPos nearbyPos; +private int nextTick; + +/** + * Waits until the player has logged in at a similar position to the activity's location, then restarts the activity. + * @param activity the activity to be restarted + * @param nearbyPos a BlockPos having to do with the activity + * @param mc instance of Mincerfat + * @param log instance of logger + */ +public RelogActivityListener(RestartableActivity activity, BlockPos nearbyPos, Minecraft mc, Logger log) { + this.mc = mc; + this.log = log; + this.activity = activity; + this.nearbyPos = nearbyPos; + TickTimer.addListener(this); + nextTick = nextTick(200); +} + +@Override +public boolean onTick(int tick) { +if(tick == nextTick) { + BlockPos playerPos = null; + try { + playerPos = mc.player.getPosition(); + } catch(NullPointerException e) {} + if(playerPos != null && playerPos.getDistance(nearbyPos.getX(), nearbyPos.getY(), nearbyPos.getZ()) < 250) { + log.info("Restarting activity " + activity.getClass().getName()); + activity.restart(); + return false; + } else nextTick = nextTick(200); +} +return true; +} + +} \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/time/RestartableActivity.java b/src/main/java/magnileve/chungamod/time/RestartableActivity.java new file mode 100644 index 0000000..12ab770 --- /dev/null +++ b/src/main/java/magnileve/chungamod/time/RestartableActivity.java @@ -0,0 +1,18 @@ +package magnileve.chungamod.time; + +import net.minecraft.util.math.BlockPos; + +public interface RestartableActivity extends Activity { + +/** + * Called when the client has reconnected to the world where the activity was running. + */ +public void restart(); + +/** + * Gets a BlockPos having to do with the activity in order to determine if the player has logged on at the same place where the activity was running. + * @return the BlockPos having to do with the activity + */ +public BlockPos getNearbyPosition(); + +} \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/time/TickListener.java b/src/main/java/magnileve/chungamod/time/TickListener.java index 0edf6eb..939ac61 100644 --- a/src/main/java/magnileve/chungamod/time/TickListener.java +++ b/src/main/java/magnileve/chungamod/time/TickListener.java @@ -1,5 +1,23 @@ package magnileve.chungamod.time; +@FunctionalInterface public interface TickListener { - public void onTick(int tick); + +/** + * Called on scheduled client ticks. + * @param tick the number of client ticks since client startup + * @return false unless the tick listener should be removed + */ +public boolean onTick(int tick); + +/** + * Schedules a client tick for method onTick to be called during. + * @param tick the number of ticks in the future for the tick being scheduled + * @return the number of client ticks since client startup when onTick will be called + */ +default int nextTick(int tick) { + TickTimer.add(tick); + return TickTimer.current() + tick; +} + } \ No newline at end of file diff --git a/src/main/java/magnileve/chungamod/time/TickTimer.java b/src/main/java/magnileve/chungamod/time/TickTimer.java index d3314be..7b74c31 100644 --- a/src/main/java/magnileve/chungamod/time/TickTimer.java +++ b/src/main/java/magnileve/chungamod/time/TickTimer.java @@ -2,27 +2,29 @@ import java.util.LinkedList; -import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.Logger; -import magnileve.chungamod.Ref; +import magnileve.chungamod.Chung; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -@Mod.EventBusSubscriber(modid=Ref.MODID) +@Mod.EventBusSubscriber(modid=Chung.MODID) public class TickTimer { private static int tick; private static LinkedList listenTicks; private static LinkedList listeners; +private static LinkedList listenerQueue; private static Logger log; public static void init(Logger logIn) { tick = 0; listenTicks = new LinkedList(); listeners = new LinkedList(); + listenerQueue = new LinkedList(); log = logIn; } @@ -32,10 +34,18 @@ public static void onTick(ClientTickEvent event) { tick++; if(!listenTicks.isEmpty() && listenTicks.getFirst() == tick) { listenTicks.remove(); - for(TickListener listener:listeners) listener.onTick(tick); + if(!listenerQueue.isEmpty()) { + for(TickListener listener:listenerQueue) listeners.add(listener); + listenerQueue.clear(); + } + for(TickListener listener:listeners) if(listener.onTick(tick)) removeListener(listener); } } +/** + * Schedules a client tick for method onTick to be called on all tick listeners during. + * @param futureTicks the number of ticks in the future for the tick being scheduled + */ public static void add(int futureTicks) { if(futureTicks > 0) { int i = 0; @@ -59,14 +69,26 @@ public static void add(int futureTicks) { } } +/** + * Adds listener for scheduled client ticks. + * @param listener listener to be added + */ public static void addListener(TickListener listener) { - listeners.add(listener); + listenerQueue.add(listener); } +/** + * Removes listener for scheduled client ticks. + * @param listener listener to be removed + */ public static void removeListener(TickListener listener) { listeners.remove(listener); } +/** + * Gets the number of client ticks since client startup. + * @return the number of client ticks since client startup + */ public static int current() { return tick; } diff --git a/src/main/java/mcmod.info b/src/main/java/mcmod.info index 04a7238..b118340 100644 --- a/src/main/java/mcmod.info +++ b/src/main/java/mcmod.info @@ -3,9 +3,9 @@ "modid": "chungamod", "name": "Chungamod", "description": "The funniest Mincerfat client", - "version": "Testing", + "version": "0.2", "mcversion": "1.12.2", - "url": "", + "url": "https://github.com/Magnileve/Chungamod", "updateUrl": "", "authorList": ["Magnileve"], "credits": "Big Chungus, the almighty Wabbit", diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info deleted file mode 100644 index 04a7238..0000000 --- a/src/main/resources/mcmod.info +++ /dev/null @@ -1,16 +0,0 @@ -[ -{ - "modid": "chungamod", - "name": "Chungamod", - "description": "The funniest Mincerfat client", - "version": "Testing", - "mcversion": "1.12.2", - "url": "", - "updateUrl": "", - "authorList": ["Magnileve"], - "credits": "Big Chungus, the almighty Wabbit", - "logoFile": "", - "screenshots": [], - "dependencies": [] -} -] \ No newline at end of file diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta deleted file mode 100644 index 4018267..0000000 --- a/src/main/resources/pack.mcmeta +++ /dev/null @@ -1,7 +0,0 @@ -{ - "pack": { - "description": "examplemod resources", - "pack_format": 3, - "_comment": "A pack_format of 3 should be used starting with Minecraft 1.11. All resources, including language files, should be lowercase (eg: en_us.lang). A pack_format of 2 will load your mod resources with LegacyV2Adapter, which requires language files to have uppercase letters (eg: en_US.lang)." - } -}