From 24905c16017decae4ee60ce4128b6d26de66baf5 Mon Sep 17 00:00:00 2001 From: Jordan Byrne Date: Thu, 22 Feb 2018 13:55:56 +1000 Subject: % Minor project cleanup. --- src/Java/gtPlusPlus/core/util/BaseHandler.java | 11 - src/Java/gtPlusPlus/core/util/ClassUtils.java | 76 --- src/Java/gtPlusPlus/core/util/Log.java | 24 - src/Java/gtPlusPlus/core/util/LoggingUtils.java | 49 -- src/Java/gtPlusPlus/core/util/PollutionUtils.java | 54 -- src/Java/gtPlusPlus/core/util/Quality.java | 61 -- src/Java/gtPlusPlus/core/util/StringUtils.java | 97 --- src/Java/gtPlusPlus/core/util/SystemUtils.java | 77 --- src/Java/gtPlusPlus/core/util/Utils.java | 7 +- .../gtPlusPlus/core/util/UtilsChatFormatting.java | 129 ---- src/Java/gtPlusPlus/core/util/UtilsRarity.java | 18 - src/Java/gtPlusPlus/core/util/UtilsText.java | 2 +- .../gtPlusPlus/core/util/array/ArrayUtils.java | 34 - src/Java/gtPlusPlus/core/util/data/ArrayUtils.java | 34 + src/Java/gtPlusPlus/core/util/data/EnumUtils.java | 41 ++ .../gtPlusPlus/core/util/data/LocaleUtils.java | 91 +++ .../gtPlusPlus/core/util/data/LoggingUtils.java | 49 ++ .../gtPlusPlus/core/util/data/StringUtils.java | 97 +++ .../gtPlusPlus/core/util/data/UUIDGenerator.java | 451 +++++++++++++ src/Java/gtPlusPlus/core/util/data/UUIDUtils.java | 25 + .../core/util/enchanting/EnchantingUtils.java | 102 --- .../gtPlusPlus/core/util/entity/EntityUtils.java | 113 ---- src/Java/gtPlusPlus/core/util/fluid/FluidGT6.java | 30 - .../gtPlusPlus/core/util/fluid/FluidUtils.java | 551 ---------------- src/Java/gtPlusPlus/core/util/geo/GeoUtils.java | 107 --- .../util/gregtech/material/MaterialBuilder.java | 254 -------- .../gregtech/recipehandlers/GregtechRecipe.java | 74 --- .../gtPlusPlus/core/util/input/KeyboardUtils.java | 23 - .../core/util/inventory/InventoryUtils.java | 60 -- src/Java/gtPlusPlus/core/util/item/ItemUtils.java | 722 --------------------- .../gtPlusPlus/core/util/locale/LocaleUtils.java | 91 --- .../core/util/materials/MaterialUtils.java | 253 -------- .../core/util/minecraft/EnchantingUtils.java | 102 +++ .../core/util/minecraft/EntityUtils.java | 113 ++++ .../gtPlusPlus/core/util/minecraft/FluidUtils.java | 550 ++++++++++++++++ .../core/util/minecraft/InventoryUtils.java | 60 ++ .../gtPlusPlus/core/util/minecraft/ItemUtils.java | 717 ++++++++++++++++++++ .../core/util/minecraft/MaterialUtils.java | 205 ++++++ .../core/util/minecraft/ModularArmourUtils.java | 159 +++++ .../gtPlusPlus/core/util/minecraft/NBTUtils.java | 453 +++++++++++++ .../core/util/minecraft/PlayerUtils.java | 175 +++++ .../core/util/minecraft/RecipeUtils.java | 479 ++++++++++++++ .../core/util/minecraft/ShapelessUtils.java | 55 ++ .../core/util/minecraft/UtilsMining.java | 214 ++++++ .../util/minecraft/gregtech/PollutionUtils.java | 54 ++ .../gregtech/material/MaterialBuilder.java | 254 ++++++++ .../gregtech/recipehandlers/GregtechRecipe.java | 74 +++ .../minecraft/particles/BlockBreakParticles.java | 17 + .../particles/EntityParticleFXMysterious.java | 17 + .../core/util/nbt/ModularArmourUtils.java | 159 ----- src/Java/gtPlusPlus/core/util/nbt/NBTUtils.java | 454 ------------- .../core/util/networking/NetworkUtils.java | 153 ----- .../core/util/particles/BlockBreakParticles.java | 17 - .../util/particles/EntityParticleFXMysterious.java | 17 - .../gtPlusPlus/core/util/player/PlayerUtils.java | 175 ----- .../gtPlusPlus/core/util/player/UtilsMining.java | 214 ------ .../gtPlusPlus/core/util/recipe/RecipeUtils.java | 481 -------------- .../core/util/recipe/shapeless/ShapelessUtils.java | 55 -- .../core/util/reflect/AddGregtechRecipe.java | 4 +- .../core/util/reflect/ReflectionUtils.java | 74 ++- src/Java/gtPlusPlus/core/util/sys/GeoUtils.java | 106 +++ .../gtPlusPlus/core/util/sys/KeyboardUtils.java | 23 + src/Java/gtPlusPlus/core/util/sys/Log.java | 24 + .../gtPlusPlus/core/util/sys/NetworkUtils.java | 153 +++++ src/Java/gtPlusPlus/core/util/sys/SystemUtils.java | 77 +++ .../gtPlusPlus/core/util/uuid/UUIDGenerator.java | 451 ------------- src/Java/gtPlusPlus/core/util/uuid/UUIDUtils.java | 25 - src/Java/gtPlusPlus/core/util/wrapper/var.java | 67 -- 68 files changed, 4947 insertions(+), 5287 deletions(-) delete mode 100644 src/Java/gtPlusPlus/core/util/BaseHandler.java delete mode 100644 src/Java/gtPlusPlus/core/util/ClassUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/Log.java delete mode 100644 src/Java/gtPlusPlus/core/util/LoggingUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/PollutionUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/Quality.java delete mode 100644 src/Java/gtPlusPlus/core/util/StringUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/SystemUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/UtilsChatFormatting.java delete mode 100644 src/Java/gtPlusPlus/core/util/UtilsRarity.java delete mode 100644 src/Java/gtPlusPlus/core/util/array/ArrayUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/data/ArrayUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/data/EnumUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/data/LocaleUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/data/LoggingUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/data/StringUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/data/UUIDGenerator.java create mode 100644 src/Java/gtPlusPlus/core/util/data/UUIDUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/enchanting/EnchantingUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/entity/EntityUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/fluid/FluidGT6.java delete mode 100644 src/Java/gtPlusPlus/core/util/fluid/FluidUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/geo/GeoUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/gregtech/material/MaterialBuilder.java delete mode 100644 src/Java/gtPlusPlus/core/util/gregtech/recipehandlers/GregtechRecipe.java delete mode 100644 src/Java/gtPlusPlus/core/util/input/KeyboardUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/inventory/InventoryUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/item/ItemUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/locale/LocaleUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/materials/MaterialUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/EnchantingUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/EntityUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/FluidUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/InventoryUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/ItemUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/MaterialUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/ModularArmourUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/NBTUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/PlayerUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/RecipeUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/ShapelessUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/UtilsMining.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/gregtech/PollutionUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/gregtech/material/MaterialBuilder.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/gregtech/recipehandlers/GregtechRecipe.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/particles/BlockBreakParticles.java create mode 100644 src/Java/gtPlusPlus/core/util/minecraft/particles/EntityParticleFXMysterious.java delete mode 100644 src/Java/gtPlusPlus/core/util/nbt/ModularArmourUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/nbt/NBTUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/networking/NetworkUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/particles/BlockBreakParticles.java delete mode 100644 src/Java/gtPlusPlus/core/util/particles/EntityParticleFXMysterious.java delete mode 100644 src/Java/gtPlusPlus/core/util/player/PlayerUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/player/UtilsMining.java delete mode 100644 src/Java/gtPlusPlus/core/util/recipe/RecipeUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/recipe/shapeless/ShapelessUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/sys/GeoUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/sys/KeyboardUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/sys/Log.java create mode 100644 src/Java/gtPlusPlus/core/util/sys/NetworkUtils.java create mode 100644 src/Java/gtPlusPlus/core/util/sys/SystemUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/uuid/UUIDGenerator.java delete mode 100644 src/Java/gtPlusPlus/core/util/uuid/UUIDUtils.java delete mode 100644 src/Java/gtPlusPlus/core/util/wrapper/var.java (limited to 'src/Java/gtPlusPlus/core/util') diff --git a/src/Java/gtPlusPlus/core/util/BaseHandler.java b/src/Java/gtPlusPlus/core/util/BaseHandler.java deleted file mode 100644 index 9457dc363f..0000000000 --- a/src/Java/gtPlusPlus/core/util/BaseHandler.java +++ /dev/null @@ -1,11 +0,0 @@ -package gtPlusPlus.core.util; - -public abstract class BaseHandler { - - public abstract void preInit(); - - public abstract void init(); - - public abstract void postInit(); - -} diff --git a/src/Java/gtPlusPlus/core/util/ClassUtils.java b/src/Java/gtPlusPlus/core/util/ClassUtils.java deleted file mode 100644 index 8f55fca299..0000000000 --- a/src/Java/gtPlusPlus/core/util/ClassUtils.java +++ /dev/null @@ -1,76 +0,0 @@ -package gtPlusPlus.core.util; - -import java.lang.reflect.*; - -public class ClassUtils { - - /* - * @ if (isPresent("com.optionaldependency.DependencyClass")) { // This - * block will never execute when the dependency is not present // There is - * therefore no more risk of code throwing NoClassDefFoundException. - * executeCodeLinkingToDependency(); } - */ - public static boolean isPresent(final String className) { - try { - Class.forName(className); - return true; - } catch (final Throwable ex) { - // Class or one of its dependencies is not present... - return false; - } - } - - @SuppressWarnings("rawtypes") - public static Method getMethodViaReflection(final Class lookupClass, final String methodName, - final boolean invoke) throws Exception { - final Class lookup = lookupClass.getClass(); - final Method m = lookup.getDeclaredMethod(methodName); - m.setAccessible(true);// Abracadabra - if (invoke) { - m.invoke(lookup);// now its OK - } - return m; - } - - public static Class getNonPublicClass(final String className) { - Class c = null; - try { - c = Class.forName(className); - } catch (final ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // full package name --------^^^^^^^^^^ - // or simpler without Class.forName: - // Class c = package1.A.class; - - if (null != c) { - // In our case we need to use - Constructor constructor = null; - try { - constructor = c.getDeclaredConstructor(); - } catch (NoSuchMethodException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // note: getConstructor() can return only public constructors - // so we needed to search for any Declared constructor - - // now we need to make this constructor accessible - if (null != constructor) { - constructor.setAccessible(true);// ABRACADABRA! - - try { - final Object o = constructor.newInstance(); - return (Class) o; - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - return null; - } - -} diff --git a/src/Java/gtPlusPlus/core/util/Log.java b/src/Java/gtPlusPlus/core/util/Log.java deleted file mode 100644 index fe06fcb271..0000000000 --- a/src/Java/gtPlusPlus/core/util/Log.java +++ /dev/null @@ -1,24 +0,0 @@ -package gtPlusPlus.core.util; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public final class Log { - public static final Logger LOGGER = LogManager.getLogger("MiscUtils"); - - public static void warn(final String msg) { - LOGGER.warn(msg); - } - - public static void error(final String msg) { - LOGGER.error(msg); - } - - public static void info(final String msg) { - LOGGER.info(msg); - } - - public static void debug(final String msg) { - LOGGER.debug(msg); - } -} diff --git a/src/Java/gtPlusPlus/core/util/LoggingUtils.java b/src/Java/gtPlusPlus/core/util/LoggingUtils.java deleted file mode 100644 index 6aae8e52ec..0000000000 --- a/src/Java/gtPlusPlus/core/util/LoggingUtils.java +++ /dev/null @@ -1,49 +0,0 @@ -package gtPlusPlus.core.util; - -import java.io.*; -import java.util.Date; - -public class LoggingUtils { - - public static void profileLog(final Object o) { - try { - String content; - final File file = new File("GregtechTimingsTC.txt"); - // if file doesnt exists, then create it - if (!file.exists()) { - file.createNewFile(); - final FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); - final BufferedWriter bw = new BufferedWriter(fw); - bw.write("============================================================"); - bw.write(System.lineSeparator()); - bw.close(); - } - if (o instanceof String) { - content = (String) o; - } else { - content = o.toString(); - } - final FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); - final BufferedWriter bw = new BufferedWriter(fw); - bw.write(content); - bw.write(System.lineSeparator()); - bw.close(); - System.out.println("Data Logged."); - - } catch (final IOException e) { - System.out.println("Data logging failed."); - } - } - - public static boolean logCurrentSystemTime(final String message) { - final Date date = new Date(System.currentTimeMillis()); - try { - profileLog(message + " | " + date.toString()); - return true; - } catch (final Throwable r) { - return false; - } - - } - -} diff --git a/src/Java/gtPlusPlus/core/util/PollutionUtils.java b/src/Java/gtPlusPlus/core/util/PollutionUtils.java deleted file mode 100644 index d68a25a844..0000000000 --- a/src/Java/gtPlusPlus/core/util/PollutionUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -package gtPlusPlus.core.util; - -import java.lang.reflect.*; - -import gregtech.GT_Mod; -import gregtech.api.interfaces.tileentity.IGregTechTileEntity; -import gregtech.common.GT_Proxy; -import gtPlusPlus.core.util.reflect.ReflectionUtils; - -public class PollutionUtils { - - public static boolean mPollution() { - try { - GT_Proxy GT_Pollution = GT_Mod.gregtechproxy; - if (GT_Pollution != null) { - Field mPollution = ReflectionUtils.getField(GT_Pollution.getClass(), "mPollution"); - if (mPollution != null) { - return mPollution.getBoolean(GT_Pollution); - } - } - } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {} - return false; - } - - public static boolean addPollution(IGregTechTileEntity te, int pollutionValue) { - try { - Class GT_Pollution = Class.forName("gregtech.common.GT_Pollution"); - if (GT_Pollution != null) { - Method addPollution = GT_Pollution.getMethod("addPollution", IGregTechTileEntity.class, int.class); - if (addPollution != null) { - addPollution.invoke(null, te, pollutionValue); - return true; - } - } - } catch (ClassNotFoundException | SecurityException | NoSuchMethodException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) {} - return false; - } - - public static int getPollution(IGregTechTileEntity te) { - try { - Class GT_Pollution = Class.forName("gregtech.common.GT_Pollution"); - if (GT_Pollution != null) { - Method addPollution = GT_Pollution.getMethod("getPollution", IGregTechTileEntity.class); - if (addPollution != null) { - return (int) addPollution.invoke(null, te); - } - } - } catch (ClassNotFoundException | SecurityException | NoSuchMethodException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) {} - return 0; - } - -} diff --git a/src/Java/gtPlusPlus/core/util/Quality.java b/src/Java/gtPlusPlus/core/util/Quality.java deleted file mode 100644 index 3e13409a10..0000000000 --- a/src/Java/gtPlusPlus/core/util/Quality.java +++ /dev/null @@ -1,61 +0,0 @@ -package gtPlusPlus.core.util; - -import gtPlusPlus.core.util.math.MathUtils; -import net.minecraft.util.EnumChatFormatting; - -public enum Quality { - - // Magic Blue - // Rare Yellow - // Set Green - // Unique Gold/Purple - // Trade-off Brown - - POOR("Poor", EnumChatFormatting.GRAY), COMMON("Common", EnumChatFormatting.WHITE), UNCOMMON("Uncommon", - EnumChatFormatting.DARK_GREEN), MAGIC("Magic", EnumChatFormatting.BLUE), RARE("Rare", - EnumChatFormatting.YELLOW), UNIQUE("Unique", EnumChatFormatting.GOLD), ARTIFACT("Artifact", - EnumChatFormatting.AQUA), SET("Set Piece", EnumChatFormatting.GREEN), TRADEOFF("Trade-off", - EnumChatFormatting.DARK_RED), EPIC("Epic", EnumChatFormatting.LIGHT_PURPLE); - - private String LOOT; - private EnumChatFormatting COLOUR; - - private Quality(final String lootTier, final EnumChatFormatting tooltipColour) { - this.LOOT = lootTier; - this.COLOUR = tooltipColour; - } - - public String getQuality() { - return this.LOOT; - } - - protected EnumChatFormatting getColour() { - return this.COLOUR; - } - - public String formatted() { - return this.COLOUR + this.LOOT; - } - - public static Quality getRandomQuality() { - final int lootChance = MathUtils.randInt(0, 100); - if (lootChance <= 10) { - return Quality.POOR; - } else if (lootChance <= 45) { - return Quality.COMMON; - } else if (lootChance <= 65) { - return Quality.UNCOMMON; - } else if (lootChance <= 82) { - return Quality.MAGIC; - } else if (lootChance <= 92) { - return Quality.EPIC; - } else if (lootChance <= 97) { - return Quality.RARE; - } else if (lootChance <= 99) { - return Quality.ARTIFACT; - } else { - return null; - } - } - -} diff --git a/src/Java/gtPlusPlus/core/util/StringUtils.java b/src/Java/gtPlusPlus/core/util/StringUtils.java deleted file mode 100644 index a4679d36a1..0000000000 --- a/src/Java/gtPlusPlus/core/util/StringUtils.java +++ /dev/null @@ -1,97 +0,0 @@ -package gtPlusPlus.core.util; - -public class StringUtils { - - public static String superscript(String str) { - str = str.replaceAll("0", "\u2070"); - str = str.replaceAll("1", "\u00B9"); - str = str.replaceAll("2", "\u00B2"); - str = str.replaceAll("3", "\u00B3"); - str = str.replaceAll("4", "\u2074"); - str = str.replaceAll("5", "\u2075"); - str = str.replaceAll("6", "\u2076"); - str = str.replaceAll("7", "\u2077"); - str = str.replaceAll("8", "\u2078"); - str = str.replaceAll("9", "\u2079"); - return str; - } - - public static String subscript(String str) { - str = str.replaceAll("0", "\u2080"); - str = str.replaceAll("1", "\u2081"); - str = str.replaceAll("2", "\u2082"); - str = str.replaceAll("3", "\u2083"); - str = str.replaceAll("4", "\u2084"); - str = str.replaceAll("5", "\u2085"); - str = str.replaceAll("6", "\u2086"); - str = str.replaceAll("7", "\u2087"); - str = str.replaceAll("8", "\u2088"); - str = str.replaceAll("9", "\u2089"); - return str; - } - - public static boolean containsSuperOrSubScript(final String s){ - if (s.contains(StringUtils.superscript("0"))) { - return true; - } - else if (s.contains(StringUtils.superscript("1"))) { - return true; - } - else if (s.contains(StringUtils.superscript("2"))) { - return true; - } - else if (s.contains(StringUtils.superscript("3"))) { - return true; - } - else if (s.contains(StringUtils.superscript("4"))) { - return true; - } - else if (s.contains(StringUtils.superscript("5"))) { - return true; - } - else if (s.contains(StringUtils.superscript("6"))) { - return true; - } - else if (s.contains(StringUtils.superscript("7"))) { - return true; - } - else if (s.contains(StringUtils.superscript("8"))) { - return true; - } - else if (s.contains(StringUtils.superscript("9"))) { - return true; - } - if (s.contains(StringUtils.subscript("0"))) { - return true; - } - else if (s.contains(StringUtils.subscript("1"))) { - return true; - } - else if (s.contains(StringUtils.subscript("2"))) { - return true; - } - else if (s.contains(StringUtils.subscript("3"))) { - return true; - } - else if (s.contains(StringUtils.subscript("4"))) { - return true; - } - else if (s.contains(StringUtils.subscript("5"))) { - return true; - } - else if (s.contains(StringUtils.subscript("6"))) { - return true; - } - else if (s.contains(StringUtils.subscript("7"))) { - return true; - } - else if (s.contains(StringUtils.subscript("8"))) { - return true; - } - else if (s.contains(StringUtils.subscript("9"))) { - return true; - } - return false; - } - -} diff --git a/src/Java/gtPlusPlus/core/util/SystemUtils.java b/src/Java/gtPlusPlus/core/util/SystemUtils.java deleted file mode 100644 index 45fc25caf6..0000000000 --- a/src/Java/gtPlusPlus/core/util/SystemUtils.java +++ /dev/null @@ -1,77 +0,0 @@ -package gtPlusPlus.core.util; - -public class SystemUtils { - - private static OS SystemType; - - public static OS getOS(){ - if (SystemType != null){ - return SystemType; - } - else { - SystemType = getOperatingSystem(); - return SystemType; - } - } - - public static boolean isWindows() { - return (getOSString().indexOf("win") >= 0); - } - - public static boolean isMac() { - return (getOSString().indexOf("mac") >= 0); - } - - public static boolean isUnix() { - return (getOSString().indexOf("nix") >= 0 || getOSString().indexOf("nux") >= 0 || getOSString().indexOf("aix") > 0 ); - } - - public static boolean isSolaris() { - return (getOSString().indexOf("sunos") >= 0); - } - - public static String getOSString(){ - try { - return System.getProperty("os.name").toLowerCase(); - } - catch (Throwable t){ - return "other"; - } - } - - public static OS getOperatingSystem(){ - if (isMac()){ - return OS.MAC; - } - else if (isWindows()){ - return OS.WINDOWS; - } - else if (isUnix()){ - return OS.UNIX; - } - else if (isSolaris()){ - return OS.SOLARIS; - } - else { - return OS.OTHER; - } - } - - public static enum OS { - MAC(1), - WINDOWS(2), - UNIX(3), - SOLARIS(4), - OTHER(0); - - private int mID; - private OS (final int ID){ - this.mID = ID; - } - - public int getID() { - return this.mID; - } - } - -} diff --git a/src/Java/gtPlusPlus/core/util/Utils.java b/src/Java/gtPlusPlus/core/util/Utils.java index e15f8ba202..bca7f53b0c 100644 --- a/src/Java/gtPlusPlus/core/util/Utils.java +++ b/src/Java/gtPlusPlus/core/util/Utils.java @@ -38,11 +38,12 @@ import gtPlusPlus.api.objects.data.Pair; import gtPlusPlus.core.item.ModItems; import gtPlusPlus.core.lib.CORE; import gtPlusPlus.core.material.Material; -import gtPlusPlus.core.util.fluid.FluidUtils; -import gtPlusPlus.core.util.item.ItemUtils; import gtPlusPlus.core.util.math.MathUtils; -import gtPlusPlus.core.util.nbt.NBTUtils; +import gtPlusPlus.core.util.minecraft.FluidUtils; +import gtPlusPlus.core.util.minecraft.ItemUtils; +import gtPlusPlus.core.util.minecraft.NBTUtils; import gtPlusPlus.core.util.reflect.ReflectionUtils; +import gtPlusPlus.core.util.sys.SystemUtils; import ic2.core.Ic2Items; import ic2.core.init.InternalName; import ic2.core.item.resources.ItemCell; diff --git a/src/Java/gtPlusPlus/core/util/UtilsChatFormatting.java b/src/Java/gtPlusPlus/core/util/UtilsChatFormatting.java deleted file mode 100644 index a7945311d6..0000000000 --- a/src/Java/gtPlusPlus/core/util/UtilsChatFormatting.java +++ /dev/null @@ -1,129 +0,0 @@ -package gtPlusPlus.core.util; - -import java.util.*; -import java.util.regex.Pattern; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -public enum UtilsChatFormatting { - BLACK('0'), DARK_BLUE('1'), DARK_GREEN('2'), DARK_AQUA('3'), DARK_RED('4'), DARK_PURPLE('5'), GOLD('6'), GRAY( - '7'), DARK_GRAY('8'), BLUE('9'), GREEN('a'), AQUA('b'), RED('c'), LIGHT_PURPLE('d'), YELLOW('e'), WHITE( - 'f'), OBFUSCATED('k', true), BOLD('l', - true), STRIKETHROUGH('m', true), UNDERLINE('n', true), ITALIC('o', true), RESET('r'); - /** - * Maps a formatting code (e.g., 'f') to its corresponding enum value (e.g., - * WHITE). - */ - private static final Map formattingCodeMapping = new HashMap<>(); - /** - * Maps a name (e.g., 'underline') to its corresponding enum value (e.g., - * UNDERLINE). - */ - private static final Map nameMapping = new HashMap<>(); - /** - * Matches formatting codes that indicate that the client should treat the - * following text as bold, recolored, obfuscated, etc. - */ - private static final Pattern formattingCodePattern = Pattern - .compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]"); - /** The formatting code that produces this format. */ - private final char formattingCode; - private final boolean fancyStyling; - /** - * The control string (section sign + formatting code) that can be inserted - * into client-side text to display subsequent text in this format. - */ - private final String controlString; - - private UtilsChatFormatting(final char p_i1336_3_) { - this(p_i1336_3_, false); - } - - private UtilsChatFormatting(final char p_i1337_3_, final boolean p_i1337_4_) { - this.formattingCode = p_i1337_3_; - this.fancyStyling = p_i1337_4_; - this.controlString = "\u00a7" + p_i1337_3_; - } - - /** - * Gets the formatting code that produces this format. - */ - public char getFormattingCode() { - return this.formattingCode; - } - - /** - * False if this is just changing the color or resetting; true otherwise. - */ - public boolean isFancyStyling() { - return this.fancyStyling; - } - - /** - * Checks if typo is a color. - */ - public boolean isColor() { - return !this.fancyStyling && (this != RESET); - } - - /** - * Gets the friendly name of this value. - */ - public String getFriendlyName() { - return this.name().toLowerCase(); - } - - @Override - public String toString() { - return this.controlString; - } - - /** - * Returns a copy of the given string, with formatting codes stripped away. - */ - @SideOnly(Side.CLIENT) - public static String getTextWithoutFormattingCodes(final String p_110646_0_) { - return p_110646_0_ == null ? null : formattingCodePattern.matcher(p_110646_0_).replaceAll(""); - } - - /** - * Gets a value by its friendly name; null if the given name does not map to - * a defined value. - */ - public static UtilsChatFormatting getValueByName(final String p_96300_0_) { - return p_96300_0_ == null ? null : (UtilsChatFormatting) nameMapping.get(p_96300_0_.toLowerCase()); - } - - /** - * Gets all the valid values. Args: @param par0: Whether or not to include - * color values. @param par1: Whether or not to include fancy-styling values - * (anything that isn't a color value or the "reset" value). - */ - public static Collection getValidValues(final boolean p_96296_0_, final boolean p_96296_1_) { - final ArrayList arraylist = new ArrayList<>(); - final UtilsChatFormatting[] aenumchatformatting = values(); - final int i = aenumchatformatting.length; - - for (int j = 0; j < i; ++j) { - final UtilsChatFormatting enumchatformatting = aenumchatformatting[j]; - - if ((!enumchatformatting.isColor() || p_96296_0_) && (!enumchatformatting.isFancyStyling() || p_96296_1_)) { - arraylist.add(enumchatformatting.getFriendlyName()); - } - } - - return arraylist; - } - - static { - final UtilsChatFormatting[] var0 = values(); - final int var1 = var0.length; - - for (int var2 = 0; var2 < var1; ++var2) { - final UtilsChatFormatting var3 = var0[var2]; - formattingCodeMapping.put(Character.valueOf(var3.getFormattingCode()), var3); - nameMapping.put(var3.getFriendlyName(), var3); - } - } -} \ No newline at end of file diff --git a/src/Java/gtPlusPlus/core/util/UtilsRarity.java b/src/Java/gtPlusPlus/core/util/UtilsRarity.java deleted file mode 100644 index 54f4ba8c07..0000000000 --- a/src/Java/gtPlusPlus/core/util/UtilsRarity.java +++ /dev/null @@ -1,18 +0,0 @@ -package gtPlusPlus.core.util; - -import net.minecraft.util.EnumChatFormatting; - -public enum UtilsRarity { - T1_poor(EnumChatFormatting.GRAY, "Poor"), T2_normal(EnumChatFormatting.WHITE, "Common"), T3_uncommon( - EnumChatFormatting.GREEN, - "Uncommon"), T4_magic(EnumChatFormatting.BLUE, "Magic"), T5_rare(EnumChatFormatting.LIGHT_PURPLE, - "Rare"), T6_epic(EnumChatFormatting.YELLOW, "Epic"), T8_unique(EnumChatFormatting.GOLD, "Unique"); - - public final EnumChatFormatting rarityColor; - public final String rarityName; - - private UtilsRarity(final EnumChatFormatting rarity, final String name) { - this.rarityColor = rarity; - this.rarityName = name; - } -} \ No newline at end of file diff --git a/src/Java/gtPlusPlus/core/util/UtilsText.java b/src/Java/gtPlusPlus/core/util/UtilsText.java index 0db7dd35a2..9896f2be0c 100644 --- a/src/Java/gtPlusPlus/core/util/UtilsText.java +++ b/src/Java/gtPlusPlus/core/util/UtilsText.java @@ -12,7 +12,7 @@ public enum UtilsText { } public String colour() { - return "�" + this.colourValue; + return "§" + this.colourValue; } } diff --git a/src/Java/gtPlusPlus/core/util/array/ArrayUtils.java b/src/Java/gtPlusPlus/core/util/array/ArrayUtils.java deleted file mode 100644 index fbab888cbf..0000000000 --- a/src/Java/gtPlusPlus/core/util/array/ArrayUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -package gtPlusPlus.core.util.array; - -import net.minecraft.item.ItemStack; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class ArrayUtils { - - public static void expandArray(final Object[] someArray, final Object newValueToAdd) { - Object[] series = someArray; - series = addElement(series, newValueToAdd); - } - - private static Object[] addElement(Object[] series, final Object newValueToAdd) { - series = Arrays.copyOf(series, series.length + 1); - series[series.length - 1] = newValueToAdd; - return series; - } - - /*public static Object getMostCommonElement(List list) { - Optional r = list.stream().map(V::getTextureSet).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey); - return r.get(); - }*/ - - public static ItemStack[] removeNulls(final ItemStack[] v) { - List list = new ArrayList(Arrays.asList(v)); - list.removeAll(Collections.singleton((ItemStack)null)); - return list.toArray(new ItemStack[list.size()]); - } -} - diff --git a/src/Java/gtPlusPlus/core/util/data/ArrayUtils.java b/src/Java/gtPlusPlus/core/util/data/ArrayUtils.java new file mode 100644 index 0000000000..63ffe63314 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/data/ArrayUtils.java @@ -0,0 +1,34 @@ +package gtPlusPlus.core.util.data; + +import net.minecraft.item.ItemStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class ArrayUtils { + + public static void expandArray(final Object[] someArray, final Object newValueToAdd) { + Object[] series = someArray; + series = addElement(series, newValueToAdd); + } + + private static Object[] addElement(Object[] series, final Object newValueToAdd) { + series = Arrays.copyOf(series, series.length + 1); + series[series.length - 1] = newValueToAdd; + return series; + } + + /*public static Object getMostCommonElement(List list) { + Optional r = list.stream().map(V::getTextureSet).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey); + return r.get(); + }*/ + + public static ItemStack[] removeNulls(final ItemStack[] v) { + List list = new ArrayList(Arrays.asList(v)); + list.removeAll(Collections.singleton((ItemStack)null)); + return list.toArray(new ItemStack[list.size()]); + } +} + diff --git a/src/Java/gtPlusPlus/core/util/data/EnumUtils.java b/src/Java/gtPlusPlus/core/util/data/EnumUtils.java new file mode 100644 index 0000000000..22ca73be0b --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/data/EnumUtils.java @@ -0,0 +1,41 @@ +package gtPlusPlus.core.util.data; + +import com.google.common.base.Enums; +import com.google.common.base.Optional; + +public class EnumUtils { + + /** + * Returns the value of an Enum if it exists. + * If value is not found, case-insensitive search will occur. + * If value still not found, an IllegalArgumentException is thrown. + **/ + public static > T getValue(Class enumeration, String name) { + Optional j = Enums.getIfPresent(enumeration, name); + T VALUE = j.get(); + if (j.get() == null) { + VALUE = valueOfIgnoreCase(enumeration, name); + } + return VALUE; + } + + /** + * Finds the value of the given enumeration by name, case-insensitive. + * Throws an IllegalArgumentException if no match is found. + **/ + private static > T valueOfIgnoreCase(Class enumeration, String name) { + + for (T enumValue : enumeration.getEnumConstants()) { + if (enumValue.name().equalsIgnoreCase(name)) { + return enumValue; + } + } + + throw new IllegalArgumentException(String.format( + "There is no value with name '%s' in Enum %s", + name, enumeration.getName() + )); + } + + +} diff --git a/src/Java/gtPlusPlus/core/util/data/LocaleUtils.java b/src/Java/gtPlusPlus/core/util/data/LocaleUtils.java new file mode 100644 index 0000000000..957f7923f8 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/data/LocaleUtils.java @@ -0,0 +1,91 @@ +package gtPlusPlus.core.util.data; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.ModContainer; +import cpw.mods.fml.common.registry.GameData; +import gtPlusPlus.core.util.Utils; +import gtPlusPlus.core.util.minecraft.ItemUtils; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class LocaleUtils { + + public static boolean GenerateFakeLocaleFile() { + for (ModContainer modcontainer : Loader.instance().getModList()){ + if (modcontainer.getModId().toLowerCase().equals("miscutils")) { + String S = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"; + writeToFile(S); + dumpItemsAndBlocksForModContainer(modcontainer); + } + } + return true; + } + + public static boolean dumpItemsAndBlocksForModContainer(ModContainer mod) { + writeToFile("Dumping Items from "+mod.getModId()+"."); + for (Object C : GameData.getItemRegistry()) { + + try { + + if (C != null) { + if (C instanceof Item) { + Item R = (Item) C; + ItemStack IS = ItemUtils.getSimpleStack(R); + String modid = ItemUtils.getModId(IS); + if (modid.equals("miscutils") || modid.equals("ToxicEverglades")) { + String S = "["+modid+"] "+IS.getUnlocalizedName()+".name="; + writeToFile(S); + } + } + } + + } + catch (Throwable T) {} + + } + writeToFile("Dumping Blocks from "+mod.getModId()+"."); + for (Object B : GameData.getBlockRegistry()) { + + try { + + if (B != null) { + if (B instanceof Block) { + Block R = (Block) B; + ItemStack IS = ItemUtils.getSimpleStack(R); + String modid = ItemUtils.getModId(IS); + if (modid.equals("miscutils") || modid.equals("ToxicEverglades")) { + String S = "["+modid+"] "+IS.getUnlocalizedName()+".name="; + writeToFile(S); + } + } + } + + } + catch (Throwable T) {} + + } + + + return true; + } + + public static void writeToFile(String S) { + try { + File F = new File(Utils.getMcDir(), "config/GTplusplus/en_US.lang"); + BufferedWriter writer; + writer = new BufferedWriter(new FileWriter(F, true)); + writer.write(S); + writer.newLine(); + writer.close(); + } + catch (IOException e) {} + } + + +} diff --git a/src/Java/gtPlusPlus/core/util/data/LoggingUtils.java b/src/Java/gtPlusPlus/core/util/data/LoggingUtils.java new file mode 100644 index 0000000000..8415ab32fe --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/data/LoggingUtils.java @@ -0,0 +1,49 @@ +package gtPlusPlus.core.util.data; + +import java.io.*; +import java.util.Date; + +public class LoggingUtils { + + public static void profileLog(final Object o) { + try { + String content; + final File file = new File("GregtechTimingsTC.txt"); + // if file doesnt exists, then create it + if (!file.exists()) { + file.createNewFile(); + final FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); + final BufferedWriter bw = new BufferedWriter(fw); + bw.write("============================================================"); + bw.write(System.lineSeparator()); + bw.close(); + } + if (o instanceof String) { + content = (String) o; + } else { + content = o.toString(); + } + final FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); + final BufferedWriter bw = new BufferedWriter(fw); + bw.write(content); + bw.write(System.lineSeparator()); + bw.close(); + System.out.println("Data Logged."); + + } catch (final IOException e) { + System.out.println("Data logging failed."); + } + } + + public static boolean logCurrentSystemTime(final String message) { + final Date date = new Date(System.currentTimeMillis()); + try { + profileLog(message + " | " + date.toString()); + return true; + } catch (final Throwable r) { + return false; + } + + } + +} diff --git a/src/Java/gtPlusPlus/core/util/data/StringUtils.java b/src/Java/gtPlusPlus/core/util/data/StringUtils.java new file mode 100644 index 0000000000..77b1fc8413 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/data/StringUtils.java @@ -0,0 +1,97 @@ +package gtPlusPlus.core.util.data; + +public class StringUtils { + + public static String superscript(String str) { + str = str.replaceAll("0", "\u2070"); + str = str.replaceAll("1", "\u00B9"); + str = str.replaceAll("2", "\u00B2"); + str = str.replaceAll("3", "\u00B3"); + str = str.replaceAll("4", "\u2074"); + str = str.replaceAll("5", "\u2075"); + str = str.replaceAll("6", "\u2076"); + str = str.replaceAll("7", "\u2077"); + str = str.replaceAll("8", "\u2078"); + str = str.replaceAll("9", "\u2079"); + return str; + } + + public static String subscript(String str) { + str = str.replaceAll("0", "\u2080"); + str = str.replaceAll("1", "\u2081"); + str = str.replaceAll("2", "\u2082"); + str = str.replaceAll("3", "\u2083"); + str = str.replaceAll("4", "\u2084"); + str = str.replaceAll("5", "\u2085"); + str = str.replaceAll("6", "\u2086"); + str = str.replaceAll("7", "\u2087"); + str = str.replaceAll("8", "\u2088"); + str = str.replaceAll("9", "\u2089"); + return str; + } + + public static boolean containsSuperOrSubScript(final String s){ + if (s.contains(StringUtils.superscript("0"))) { + return true; + } + else if (s.contains(StringUtils.superscript("1"))) { + return true; + } + else if (s.contains(StringUtils.superscript("2"))) { + return true; + } + else if (s.contains(StringUtils.superscript("3"))) { + return true; + } + else if (s.contains(StringUtils.superscript("4"))) { + return true; + } + else if (s.contains(StringUtils.superscript("5"))) { + return true; + } + else if (s.contains(StringUtils.superscript("6"))) { + return true; + } + else if (s.contains(StringUtils.superscript("7"))) { + return true; + } + else if (s.contains(StringUtils.superscript("8"))) { + return true; + } + else if (s.contains(StringUtils.superscript("9"))) { + return true; + } + if (s.contains(StringUtils.subscript("0"))) { + return true; + } + else if (s.contains(StringUtils.subscript("1"))) { + return true; + } + else if (s.contains(StringUtils.subscript("2"))) { + return true; + } + else if (s.contains(StringUtils.subscript("3"))) { + return true; + } + else if (s.contains(StringUtils.subscript("4"))) { + return true; + } + else if (s.contains(StringUtils.subscript("5"))) { + return true; + } + else if (s.contains(StringUtils.subscript("6"))) { + return true; + } + else if (s.contains(StringUtils.subscript("7"))) { + return true; + } + else if (s.contains(StringUtils.subscript("8"))) { + return true; + } + else if (s.contains(StringUtils.subscript("9"))) { + return true; + } + return false; + } + +} diff --git a/src/Java/gtPlusPlus/core/util/data/UUIDGenerator.java b/src/Java/gtPlusPlus/core/util/data/UUIDGenerator.java new file mode 100644 index 0000000000..513468a9f6 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/data/UUIDGenerator.java @@ -0,0 +1,451 @@ +package gtPlusPlus.core.util.data; + +import java.io.IOException; +import java.net.InetAddress; +import java.util.Random; +import java.util.UUID; + +import gtPlusPlus.api.objects.random.CSPRNG_DO_NOT_USE; + +/** + * + * Implement modified version of Apache's OpenJPA UUID generator. + * This UUID generator is paired with a Blum-Blum-Shub random number generator + * which in itself is seeded by custom SecureRandom. + * + * The UUID generator class has been converted from a static factory to an instanced factory. + * + */ + +//========================================= APACHE BLOCK ========================================= + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/** + * UUID value generator. Type 1 generator is based on the time-based generator + * in the Apache Commons Id project: http://jakarta.apache.org/commons/sandbox + * /id/uuid.html The type 4 generator uses the standard Java UUID generator. + * + * The type 1 code has been vastly simplified and modified to replace the + * ethernet address of the host machine with the IP, since we do not want to + * require native libs and Java cannot access the MAC address directly. + * + * In spirit, implements the IETF UUID draft specification, found here:
+ * http://www1.ics.uci.edu/~ejw/authoring/uuid-guid/draft-leach-uuids-guids-01 + * .txt + * + * @author Abe White, Kevin Sutter + * @since 0.3.3 + */ +public class UUIDGenerator { + + // supported UUID types + public static final int TYPE1 = 1; + public static final int TYPE4 = 4; + // indexes within the uuid array for certain boundaries + private static final byte IDX_TIME_HI = 6; + private static final byte IDX_TYPE = 6; // multiplexed + private static final byte IDX_TIME_MID = 4; + private static final byte IDX_TIME_LO = 0; + private static final byte IDX_TIME_SEQ = 8; + private static final byte IDX_VARIATION = 8; // multiplexed + // indexes and lengths within the timestamp for certain boundaries + private static final byte TS_TIME_LO_IDX = 4; + private static final byte TS_TIME_LO_LEN = 4; + private static final byte TS_TIME_MID_IDX = 2; + private static final byte TS_TIME_MID_LEN = 2; + private static final byte TS_TIME_HI_IDX = 0; + private static final byte TS_TIME_HI_LEN = 2; + // offset to move from 1/1/1970, which is 0-time for Java, to gregorian + // 0-time 10/15/1582, and multiplier to go from 100nsec to msec units + private static final long GREG_OFFSET = 0xB1D069B5400L; + private static final long MILLI_MULT = 10000L; + // type of UUID -- time based + private final static byte TYPE_TIME_BASED = 0x10; + // random number generator used to reduce conflicts with other JVMs, and + // hasher for strings. + private Random RANDOM; + // 4-byte IP address + 2 random bytes to compensate for the fact that + // the MAC address is usually 6 bytes + private byte[] IP; + // counter is initialized to 0 and is incremented for each uuid request + // within the same timestamp window. + private int _counter; + // current timestamp (used to detect multiple uuid requests within same + // timestamp) + private long _currentMillis; + // last used millis time, and a semi-random sequence that gets reset + // when it overflows + private long _lastMillis = 0L; + private static final int MAX_14BIT = 0x3FFF; + private short _seq = 0; + private boolean type1Initialized = false; /* + * Initializer for type 1 UUIDs. Creates random generator and genenerates + * the node portion of the UUID using the IP address. + */ + private synchronized void initializeForType1() { + if (type1Initialized == true) { + return; + } + // note that secure random is very slow the first time + // it is used; consider switching to a standard random + RANDOM = CSPRNG_DO_NOT_USE.generate(); + _seq = (short) RANDOM.nextInt(MAX_14BIT); + + byte[] ip = null; + try { + ip = InetAddress.getLocalHost().getAddress(); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + IP = new byte[6]; + RANDOM.nextBytes(IP); + //OPENJPA-2055: account for the fact that 'getAddress' + //may return an IPv6 address which is 16 bytes wide. + for( int i = 0 ; i < ip.length; ++i ) { + IP[2+(i%4)] ^= ip[i]; + } + type1Initialized = true; + } + /** + * Return a unique UUID value. + */ + public byte[] next(int type) { + if (type == TYPE4) { + return createType4(); + } + return createType1(); + } + /* + * Creates a type 1 UUID + */ + public byte[] createType1() { + if (type1Initialized == false) { + initializeForType1(); + } + // set ip addr + byte[] uuid = new byte[16]; + System.arraycopy(IP, 0, uuid, 10, IP.length); + // Set time info. Have to do this processing within a synchronized + // block because of the statics... + long now = 0; + synchronized (UUIDGenerator.class) { + // Get the time to use for this uuid. This method has the side + // effect of modifying the clock sequence, as well. + now = getTime(); + // Insert the resulting clock sequence into the uuid + uuid[IDX_TIME_SEQ] = (byte) ((_seq & 0x3F00) >>> 8); + uuid[IDX_VARIATION] |= 0x80; + uuid[IDX_TIME_SEQ+1] = (byte) (_seq & 0xFF); + } + // have to break up time because bytes are spread through uuid + byte[] timeBytes = Bytes.toBytes(now); + // Copy time low + System.arraycopy(timeBytes, TS_TIME_LO_IDX, uuid, IDX_TIME_LO, + TS_TIME_LO_LEN); + // Copy time mid + System.arraycopy(timeBytes, TS_TIME_MID_IDX, uuid, IDX_TIME_MID, + TS_TIME_MID_LEN); + // Copy time hi + System.arraycopy(timeBytes, TS_TIME_HI_IDX, uuid, IDX_TIME_HI, + TS_TIME_HI_LEN); + //Set version (time-based) + uuid[IDX_TYPE] |= TYPE_TIME_BASED; // 0001 0000 + return uuid; + } + /* + * Creates a type 4 UUID + */ + private byte[] createType4() { + UUID type4 = UUID.randomUUID(); + byte[] uuid = new byte[16]; + longToBytes(type4.getMostSignificantBits(), uuid, 0); + longToBytes(type4.getLeastSignificantBits(), uuid, 8); + return uuid; + } + /* + * Converts a long to byte values, setting them in a byte array + * at a given starting position. + */ + private void longToBytes(long longVal, byte[] buf, int sPos) { + sPos += 7; + for(int i = 0; i < 8; i++) + buf[sPos-i] = (byte)(longVal >>> (i * 8)); + } + + /** + * Return the next unique uuid value as a 16-character string. + */ + public String nextString(int type) { + byte[] bytes = next(type); + try { + return new String(bytes, "ISO-8859-1"); + } catch (Exception e) { + return new String(bytes); + } + } + /** + * Return the next unique uuid value as a 32-character hex string. + */ + public String nextHex(int type) { + return Base16Encoder.encode(next(type)); + } + /** + * Get the timestamp to be used for this uuid. Must be called from + * a synchronized block. + * + * @return long timestamp + */ + // package-visibility for testing + private long getTime() { + if (RANDOM == null) + initializeForType1(); + long newTime = getUUIDTime(); + if (newTime <= _lastMillis) { + incrementSequence(); + newTime = getUUIDTime(); + } + _lastMillis = newTime; + return newTime; + } + /** + * Gets the appropriately modified timestamep for the UUID. Must be called + * from a synchronized block. + * + * @return long timestamp in 100ns intervals since the Gregorian change + * offset + */ + private long getUUIDTime() { + if (_currentMillis != System.currentTimeMillis()) { + _currentMillis = System.currentTimeMillis(); + _counter = 0; // reset counter + } + // check to see if we have created too many uuid's for this timestamp + if (_counter + 1 >= MILLI_MULT) { + // Original algorithm threw exception. Seemed like overkill. + // Let's just increment the timestamp instead and start over... + _currentMillis++; + _counter = 0; + } + // calculate time as current millis plus offset times 100 ns ticks + long currentTime = (_currentMillis + GREG_OFFSET) * MILLI_MULT; + // return the uuid time plus the artificial tick counter incremented + return currentTime + _counter++; + } + /** + * Increments the clock sequence for this uuid. Must be called from a + * synchronized block. + */ + private void incrementSequence() { + // increment, but if it's greater than its 14-bits, reset it + if (++_seq > MAX_14BIT) { + _seq = (short) RANDOM.nextInt(MAX_14BIT); // semi-random + } + } + + //Add Dependant classes internally + + /** + * This class came from the Apache Commons Id sandbox project in support + * of the UUIDGenerator implementation. + * + *

Static methods for managing byte arrays (all methods follow Big + * Endian order where most significant bits are in front).

+ */ + public static final class Bytes { + /** + *

Hide constructor in utility class.

+ */ + private Bytes() { + } + /** + * Appends two bytes array into one. + * + * @param a A byte[]. + * @param b A byte[]. + * @return A byte[]. + */ + public static byte[] append(byte[] a, byte[] b) { + byte[] z = new byte[a.length + b.length]; + System.arraycopy(a, 0, z, 0, a.length); + System.arraycopy(b, 0, z, a.length, b.length); + return z; + } + /** + * Returns a 8-byte array built from a long. + * + * @param n The number to convert. + * @return A byte[]. + */ + public static byte[] toBytes(long n) { + return toBytes(n, new byte[8]); + } + /** + * Build a 8-byte array from a long. No check is performed on the + * array length. + * + * @param n The number to convert. + * @param b The array to fill. + * @return A byte[]. + */ + public static byte[] toBytes(long n, byte[] b) { + b[7] = (byte) (n); + n >>>= 8; + b[6] = (byte) (n); + n >>>= 8; + b[5] = (byte) (n); + n >>>= 8; + b[4] = (byte) (n); + n >>>= 8; + b[3] = (byte) (n); + n >>>= 8; + b[2] = (byte) (n); + n >>>= 8; + b[1] = (byte) (n); + n >>>= 8; + b[0] = (byte) (n); + + return b; + } + /** + * Build a long from first 8 bytes of the array. + * + * @param b The byte[] to convert. + * @return A long. + */ + public static long toLong(byte[] b) { + return ((((long) b[7]) & 0xFF) + + ((((long) b[6]) & 0xFF) << 8) + + ((((long) b[5]) & 0xFF) << 16) + + ((((long) b[4]) & 0xFF) << 24) + + ((((long) b[3]) & 0xFF) << 32) + + ((((long) b[2]) & 0xFF) << 40) + + ((((long) b[1]) & 0xFF) << 48) + + ((((long) b[0]) & 0xFF) << 56)); + } + /** + * Compares two byte arrays for equality. + * + * @param a A byte[]. + * @param b A byte[]. + * @return True if the arrays have identical contents. + */ + public static boolean areEqual(byte[] a, byte[] b) { + int aLength = a.length; + if (aLength != b.length) { + return false; + } + for (int i = 0; i < aLength; i++) { + if (a[i] != b[i]) { + return false; + } + } + return true; + } + /** + *

Compares two byte arrays as specified by Comparable. + * + * @param lhs - left hand value in the comparison operation. + * @param rhs - right hand value in the comparison operation. + * @return a negative integer, zero, or a positive integer as + * lhs is less than, equal to, or greater than + * rhs. + */ + public static int compareTo(byte[] lhs, byte[] rhs) { + if (lhs == rhs) { + return 0; + } + if (lhs == null) { + return -1; + } + if (rhs == null) { + return +1; + } + if (lhs.length != rhs.length) { + return ((lhs.length < rhs.length) ? -1 : +1); + } + for (int i = 0; i < lhs.length; i++) { + if (lhs[i] < rhs[i]) { + return -1; + } else if (lhs[i] > rhs[i]) { + return 1; + } + } + return 0; + } + /** + * Build a short from first 2 bytes of the array. + * + * @param b The byte[] to convert. + * @return A short. + */ + public static short toShort(byte[] b) { + return (short) ((b[1] & 0xFF) + ((b[0] & 0xFF) << 8)); + } + } + /** + * Base 16 encoder. + * + * @author Marc Prud'hommeaux + */ + public static final class Base16Encoder { + + private final static char[] HEX = new char[]{ + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + /** + * Convert bytes to a base16 string. + */ + public static String encode(byte[] byteArray) { + StringBuilder hexBuffer = new StringBuilder(byteArray.length * 2); + for (int i = 0; i < byteArray.length; i++) + for (int j = 1; j >= 0; j--) + hexBuffer.append(HEX[(byteArray[i] >> (j * 4)) & 0xF]); + return hexBuffer.toString(); + } + /** + * Convert a base16 string into a byte array. + */ + public static byte[] decode(String s) { + int len = s.length(); + byte[] r = new byte[len / 2]; + for (int i = 0; i < r.length; i++) { + int digit1 = s.charAt(i * 2), digit2 = s.charAt(i * 2 + 1); + if (digit1 >= '0' && digit1 <= '9') + digit1 -= '0'; + else if (digit1 >= 'A' && digit1 <= 'F') + digit1 -= 'A' - 10; + if (digit2 >= '0' && digit2 <= '9') + digit2 -= '0'; + else if (digit2 >= 'A' && digit2 <= 'F') + digit2 -= 'A' - 10; + + r[i] = (byte) ((digit1 << 4) + digit2); + } + return r; + } + } + + + +} + +//========================================= APACHE BLOCK ========================================= + diff --git a/src/Java/gtPlusPlus/core/util/data/UUIDUtils.java b/src/Java/gtPlusPlus/core/util/data/UUIDUtils.java new file mode 100644 index 0000000000..d6b32314b1 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/data/UUIDUtils.java @@ -0,0 +1,25 @@ +package gtPlusPlus.core.util.data; + +import java.nio.ByteBuffer; +import java.util.UUID; + +public class UUIDUtils { + + //UUID Methods below created by https://gist.github.com/jeffjohnson9046 + //https://gist.github.com/jeffjohnson9046/c663dd22bbe6bb0b3f5e + + public static byte[] getBytesFromUUID(UUID uuid) { + ByteBuffer bb = ByteBuffer.wrap(new byte[16]); + bb.putLong(uuid.getMostSignificantBits()); + bb.putLong(uuid.getLeastSignificantBits()); + return bb.array(); + } + + public static UUID getUUIDFromBytes(byte[] bytes) { + ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); + Long high = byteBuffer.getLong(); + Long low = byteBuffer.getLong(); + return new UUID(high, low); + } + +} diff --git a/src/Java/gtPlusPlus/core/util/enchanting/EnchantingUtils.java b/src/Java/gtPlusPlus/core/util/enchanting/EnchantingUtils.java deleted file mode 100644 index 288ca2e2cc..0000000000 --- a/src/Java/gtPlusPlus/core/util/enchanting/EnchantingUtils.java +++ /dev/null @@ -1,102 +0,0 @@ -package gtPlusPlus.core.util.enchanting; - -import gtPlusPlus.api.objects.Logger; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - -public class EnchantingUtils { - - - public static final int XP_PER_BOTTLE = 8; - public static final int RATIO = 20; - public static final int LIQUID_PER_XP_BOTTLE = 160; - public static final double RATIO_MOB_ESSENCE_TO_LIQUID_XP = 13.32; - - public static int liquidToXpRatio(final int liquid) { - return liquid / RATIO; - } - - public static int xpToLiquidRatio(final int xp) { - return xp * RATIO; - } - - public static FluidStack getEssenceFromLiquidXp(final int xpAmount){ - if (xpAmount <= 0){ - return null; - } - return getMobEssence((int) (xpAmount*RATIO_MOB_ESSENCE_TO_LIQUID_XP)); - } - - public static FluidStack getLiquidXpFromEssence(final int essenceAmount){ - if (essenceAmount <= 0){ - return null; - } - return getLiquidXP((int) (essenceAmount/RATIO_MOB_ESSENCE_TO_LIQUID_XP)); - } - - public static int getLiquidForLevel(final int level) { - final int xp = getExperienceForLevel(level); - return xpToLiquidRatio(xp); - } - - public static int getLevelForLiquid(final int liquid) { - final int xp = liquidToXpRatio(liquid); - return getLevelForExperience(xp); - } - - public static int getExperienceForLevel(final int level) { - if (level == 0) { - return 0; - } - if ((level > 0) && (level < 16)) { - return level * 17; - } - if ((level > 15) && (level < 31)) { - return (int) (((1.5 * Math.pow(level, 2.0)) - (29.5 * level)) + 360.0); - } - return (int) (((3.5 * Math.pow(level, 2.0)) - (151.5 * level)) + 2220.0); - } - - public static int getXpToNextLevel(final int level) { - final int levelXP = getLevelForExperience(level); - final int nextXP = getExperienceForLevel(level + 1); - return nextXP - levelXP; - } - - public static int getLevelForExperience(final int experience) { - int i; - for (i = 0; getExperienceForLevel(i) <= experience; ++i) { - } - return i - 1; - } - - - - - - - - //Xp Fluids - public static FluidStack getMobEssence(final int amount){ - Logger.WARNING("Trying to get a fluid stack of Mob Essence."); - try { - return FluidRegistry.getFluidStack("mobessence", amount).copy(); - } - catch (final Throwable e){ - return null; - } - - } - - public static FluidStack getLiquidXP(final int amount){ - Logger.WARNING("Trying to get a fluid stack of Liquid XP."); - try { - return FluidRegistry.getFluidStack("xpjuice", amount).copy(); - } - catch (final Throwable e){ - return null; - } - - } - -} diff --git a/src/Java/gtPlusPlus/core/util/entity/EntityUtils.java b/src/Java/gtPlusPlus/core/util/entity/EntityUtils.java deleted file mode 100644 index 27412d647f..0000000000 --- a/src/Java/gtPlusPlus/core/util/entity/EntityUtils.java +++ /dev/null @@ -1,113 +0,0 @@ -package gtPlusPlus.core.util.entity; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import cpw.mods.fml.common.registry.EntityRegistry; -import gregtech.api.util.GT_Utility; -import gtPlusPlus.api.objects.minecraft.BlockPos; -import gtPlusPlus.core.util.reflect.ReflectionUtils; -import ic2.core.IC2Potion; -import ic2.core.item.armor.ItemArmorHazmat; -import net.minecraft.block.Block; -import net.minecraft.entity.*; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.DamageSource; -import net.minecraft.util.MathHelper; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -public class EntityUtils { - - public static void setEntityOnFire(final Entity entity, final int length){ - entity.setFire(length); - } - - public static int getFacingDirection(final Entity entity){ - final int d = MathHelper.floor_double((entity.rotationYaw * 4.0F) / 360 + 0.50) & 3; - return d; - } - - @Deprecated - public static Block findBlockUnderEntityNonBoundingBox(final Entity parEntity){ - final int blockX = MathHelper.floor_double(parEntity.posX); - final int blockY = MathHelper.floor_double(parEntity.posY-0.2D - parEntity.yOffset); - final int blockZ = MathHelper.floor_double(parEntity.posZ); - return parEntity.worldObj.getBlock(blockX, blockY, blockZ); - } - - public static Block findBlockUnderEntity(final Entity parEntity){ - final int blockX = MathHelper.floor_double(parEntity.posX); - final int blockY = MathHelper.floor_double(parEntity.boundingBox.minY)-1; - final int blockZ = MathHelper.floor_double(parEntity.posZ); - return parEntity.worldObj.getBlock(blockX, blockY, blockZ); - } - - public static BlockPos findBlockPosUnderEntity(final Entity parEntity){ - final int blockX = MathHelper.floor_double(parEntity.posX); - final int blockY = MathHelper.floor_double(parEntity.boundingBox.minY)-1; - final int blockZ = MathHelper.floor_double(parEntity.posZ); - return new BlockPos(blockX, blockY, blockZ); - } - - //TODO - public static void registerEntityToBiomeSpawns(final Class classy, final EnumCreatureType EntityType, final BiomeGenBase baseBiomeGen){ - EntityRegistry.addSpawn(classy, 6, 1, 5, EntityType, baseBiomeGen); //change the values to vary the spawn rarity, biome, etc. - } - - public static boolean applyRadiationDamageToEntity(final int stackSize, final int radiationLevel, final World world, final Entity entityHolding){ - if (!world.isRemote){ - if ((radiationLevel > 0) && (entityHolding instanceof EntityLivingBase)) { - final EntityLivingBase entityLiving = (EntityLivingBase) entityHolding; - if (!((EntityPlayer) entityHolding).capabilities.isCreativeMode){ - if (!ItemArmorHazmat.hasCompleteHazmat(entityLiving) && !GT_Utility.isWearingFullRadioHazmat(entityLiving)) { - int duration; - if (entityLiving.getActivePotionEffect(IC2Potion.radiation) != null){ - //Utils.LOG_INFO("t"); - duration = (radiationLevel*5)+entityLiving.getActivePotionEffect(IC2Potion.radiation).getDuration(); - } - else { - //Utils.LOG_INFO("f"); - duration = radiationLevel*30; - } - //IC2Potion.radiation.applyTo(entityLiving, duration, damage * 15); - GT_Utility.applyRadioactivity(entityLiving, radiationLevel, stackSize); - } - } - } - return true; - } - return false; - } - - - /** - * Static Version of the method used in {@code doFireDamage(entity, int)} to save memory. - */ - private static volatile Method dealFireDamage; - - /** - * Reflective Call to do Fire Damage to an entity (Does not set entity on fire though) - */ - public static boolean doFireDamage(Entity entity, int amount){ - if (dealFireDamage == null){ - try { - dealFireDamage = Entity.class.getDeclaredMethod("dealFireDamage", int.class); - dealFireDamage.setAccessible(true); - } - catch (NoSuchMethodException | SecurityException e) {} - } - else { - try { - dealFireDamage.invoke(entity, amount); - } - catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {} - } - return false; - } - - public static void doDamage(Entity entity, DamageSource dmg, int i) { - entity.attackEntityFrom(dmg, i); - } - -} diff --git a/src/Java/gtPlusPlus/core/util/fluid/FluidGT6.java b/src/Java/gtPlusPlus/core/util/fluid/FluidGT6.java deleted file mode 100644 index b09c9dd795..0000000000 --- a/src/Java/gtPlusPlus/core/util/fluid/FluidGT6.java +++ /dev/null @@ -1,30 +0,0 @@ -package gtPlusPlus.core.util.fluid; - -import gregtech.api.GregTech_API; -import gtPlusPlus.core.lib.CORE; -import net.minecraftforge.fluids.Fluid; - -public class FluidGT6 extends Fluid implements Runnable -{ - private final short[] mRGBa; - public final String mTextureName; - - public FluidGT6(final String aName, final String aTextureName, final short[] aRGBa) { - super(aName); - this.mRGBa = aRGBa; - this.mTextureName = aTextureName; - if (GregTech_API.sGTBlockIconload != null) { - GregTech_API.sGTBlockIconload.add(this); - } - } - - @Override - public int getColor() { - return (Math.max(0, Math.min(255, this.mRGBa[0])) << 16) | (Math.max(0, Math.min(255, this.mRGBa[1])) << 8) | Math.max(0, Math.min(255, this.mRGBa[2])); - } - - @Override - public void run() { - this.setIcons(GregTech_API.sBlockIcons.registerIcon(CORE.MODID+ ":" + "fluids/fluid." + this.mTextureName)); - } -} diff --git a/src/Java/gtPlusPlus/core/util/fluid/FluidUtils.java b/src/Java/gtPlusPlus/core/util/fluid/FluidUtils.java deleted file mode 100644 index 8a99edac5f..0000000000 --- a/src/Java/gtPlusPlus/core/util/fluid/FluidUtils.java +++ /dev/null @@ -1,551 +0,0 @@ -package gtPlusPlus.core.util.fluid; - -import gregtech.api.enums.Dyes; -import gregtech.api.enums.GT_Values; -import gregtech.api.enums.ItemList; -import gregtech.api.util.GT_LanguageManager; -import gtPlusPlus.api.objects.Logger; -import gtPlusPlus.core.fluids.GenericFluid; -import gtPlusPlus.core.item.base.BaseItemComponent; -import gtPlusPlus.core.item.base.cell.BaseItemCell; -import gtPlusPlus.core.item.base.cell.BaseItemPlasmaCell; -import gtPlusPlus.core.material.Material; -import gtPlusPlus.core.material.MaterialStack; -import gtPlusPlus.core.util.Utils; -import gtPlusPlus.core.util.enchanting.EnchantingUtils; -import gtPlusPlus.core.util.item.ItemUtils; -import gtPlusPlus.xmod.gregtech.api.enums.GregtechOrePrefixes.GT_Materials; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidContainerRegistry; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidContainerItem; - -public class FluidUtils { - - public static FluidStack getWater(final int amount){ - return FluidUtils.getFluidStack("water", amount); - } - - public static FluidStack getlava(final int amount){ - return FluidUtils.getFluidStack("lava", amount); - } - - public static FluidStack getMilk(final int amount){ - return FluidUtils.getFluidStack("milk", amount); - } - - public static FluidStack getFluidStack(final String fluidName, final int amount){ - Logger.WARNING("Trying to get a fluid stack of "+fluidName); - try { - return FluidRegistry.getFluidStack(fluidName, amount).copy(); - } - catch (final Throwable e){ - return null; - } - - } - - public static FluidStack getFluidStack(final FluidStack vmoltenFluid, final int fluidAmount) { - Logger.WARNING("Trying to get a fluid stack of "+vmoltenFluid.getFluid().getName()); - try { - return FluidRegistry.getFluidStack(vmoltenFluid.getFluid().getName(), fluidAmount).copy(); - } - catch (final Throwable e){ - return null; - } - } - - public static FluidStack getFluidStack(final Fluid vFluid, final int fluidAmount) { - Logger.WARNING("Trying to get a fluid stack of "+vFluid.getName()); - try { - return FluidRegistry.getFluidStack(vFluid.getName(), fluidAmount).copy(); - } - catch (final Throwable e){ - return null; - } - } - - public static FluidStack[] getFluidStackArray(final String fluidName, final int amount){ - Logger.WARNING("Trying to get a fluid stack of "+fluidName); - try { - final FluidStack[] singleFluid = {FluidRegistry.getFluidStack(fluidName, amount)}; - return singleFluid; - } - catch (final Throwable e){ - return null; - } - - } - - public static FluidStack[] getFluidStackArray(final FluidStack fluidName, final int amount){ - Logger.WARNING("Trying to get a fluid stack of "+fluidName); - try { - final FluidStack[] singleFluid = {FluidRegistry.getFluidStack(fluidName.getLocalizedName(), amount)}; - return singleFluid; - } - catch (final Throwable e){ - return null; - } - - } - - - /** - * @param String displayName - * @param String fluidName - * @param int meltingPointC Temp - * @param short[] rgba - * @param byte state - * States: 0 (Solid), 1 (Fluid), 2(Gas), 3(Plasma) 4(Fuel I think? Don't use.) - * - * @return short[] - */ - public static Fluid generateFluid(final String displayName, final String fluidName, final int tempK, final short[] rgba ,final int aState){ - Fluid generatedFluid = null; - switch (aState) { - case 0: { - generatedFluid = new GenericFluid(displayName, fluidName, 0, 100, tempK, 10000, false, rgba); - break; - } - default: - case 1: - case 4: { - generatedFluid = new GenericFluid(displayName, fluidName, 0, 100, tempK, 1000, false, rgba); - break; - } - case 2: { - generatedFluid = new GenericFluid(displayName, fluidName, 0, -100, tempK, 200, true, rgba); - break; - } - case 3: { - generatedFluid = new GenericFluid(displayName, fluidName, 15, -10000, tempK, 10, true, rgba); - break; - } - } - return generatedFluid; - } - /** - * - * @param String fluidName - * @param int meltingPointC Temp - * @param short[] rgba - * @param byte state - * States: 0 (Solid), 1 (Fluid), 2(Gas), 3(Plasma) 4(Fuel I think? Don't use.) - * - * @return short[] - */ - public static Fluid generateFluid(final Material material ,final int aState){ - final int tempK = material.getMeltingPointC(); - Fluid generatedFluid = null; - switch (aState) { - case 0: { - generatedFluid = new GenericFluid(material, 0, 100, tempK, 10000, false); - break; - } - default: - case 1: - case 4: { - generatedFluid = new GenericFluid(material, 0, 100, tempK, 1000, false); - break; - } - case 2: { - generatedFluid = new GenericFluid(material, 0, -100, tempK, 200, true); - break; - } - case 3: { - generatedFluid = new GenericFluid(material, 15, -10000, tempK, 10, true); - break; - } - } - return generatedFluid; - } - - - public static Fluid addAutogeneratedMoltenFluid(final String materialNameFormatted, final short[] rgba, final int MeltingPoint) { - return addFluid("molten." + materialNameFormatted.toLowerCase(), "molten.autogenerated", "Molten " + materialNameFormatted, null, rgba, 1, (MeltingPoint <= 0L) ? 1000L : MeltingPoint, null, null, 0); - } - - public static Fluid addAutogeneratedMoltenFluid(final GT_Materials aMaterial) { - return addFluid("molten." + aMaterial.name().toLowerCase(), "molten.autogenerated", "Molten " + aMaterial.name(), aMaterial, aMaterial.mMoltenRGBa, 1, (aMaterial.mMeltingPoint <= 0L) ? 1000L : aMaterial.mMeltingPoint, null, null, 0); - } - - public static Fluid addFluid(final String aName, final String aLocalized, final GT_Materials aMaterial, final int aState, final long aTemperatureK) { - return addFluid(aName, aLocalized, aMaterial, aState, aTemperatureK, null, null, 0); - } - - public static Fluid addFluid(final String aName, final String aLocalized, final GT_Materials aMaterial, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { - return addFluid(aName, aName.toLowerCase(), aLocalized, aMaterial, null, aState, aTemperatureK, aFullContainer, aEmptyContainer, aFluidAmount); - } - - public static Fluid addFluid(String aName, final String aTexture, final String aLocalized, final GT_Materials aMaterial, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { - aName = Utils.sanitizeString(aName.toLowerCase()); - Fluid rFluid = new FluidGT6(aName, aTexture, (aRGBa != null) ? aRGBa : Dyes._NULL.getRGBA()); - GT_LanguageManager.addStringLocalization(rFluid.getUnlocalizedName(), (aLocalized == null) ? aName : aLocalized); - if (FluidRegistry.registerFluid(rFluid)) { - switch (aState) { - case 0: { - rFluid.setGaseous(false); - rFluid.setViscosity(10000); - break; - } - case 1: - case 4: { - rFluid.setGaseous(false); - rFluid.setViscosity(1000); - break; - } - case 2: { - rFluid.setGaseous(true); - rFluid.setDensity(-100); - rFluid.setViscosity(200); - break; - } - case 3: { - rFluid.setGaseous(true); - rFluid.setDensity(-10000); - rFluid.setViscosity(10); - rFluid.setLuminosity(15); - break; - } - } - } - else { - rFluid = FluidRegistry.getFluid(aName); - } - if ((rFluid.getTemperature() == new Fluid("test").getTemperature()) || (rFluid.getTemperature() <= 0)) { - rFluid.setTemperature((int) (aTemperatureK)); - } - if (aMaterial != null) { - switch (aState) { - case 1: { - aMaterial.mFluid = (rFluid); - break; - } - case 2: { - aMaterial.mGas = (rFluid); - break; - } - case 3: { - aMaterial.mPlasma = (rFluid); - break; - } - } - } - if ((aFullContainer != null) && (aEmptyContainer != null) && !FluidContainerRegistry.registerFluidContainer(new FluidStack(rFluid, aFluidAmount), aFullContainer, aEmptyContainer)) { - GT_Values.RA.addFluidCannerRecipe(aFullContainer, container(aFullContainer, false), null, new FluidStack(rFluid, aFluidAmount)); - } - return rFluid; - } - - public static Fluid addGTFluid(final String aName, final String aLocalized, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { - return addGTFluid("molten."+aName, "molten.autogenerated", aLocalized, aRGBa, aState, aTemperatureK, aFullContainer, aEmptyContainer, aFluidAmount); - } - - public static Fluid addGTFluidNonMolten(final String aName, final String aLocalized, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { - return addGTFluid("fluid."+aName, "fluid.autogenerated", aLocalized, aRGBa, aState, aTemperatureK, aFullContainer, aEmptyContainer, aFluidAmount); - } - - public static Fluid addGTFluidNoPrefix(final String aName, final String aLocalized, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { - return addGTFluid(aName, "fluid.autogenerated", aLocalized, aRGBa, aState, aTemperatureK, aFullContainer, aEmptyContainer, aFluidAmount); - } - - public static Fluid addGTPlasma(final Material aMaterial) { - if (aMaterial.getLocalizedName().toLowerCase().contains("clay") || (aMaterial.getComposites().size()>1) || aMaterial.getLocalizedName().toLowerCase().contains("wrought")){ - return null; - } - Logger.INFO("Generating a "+aMaterial.getLocalizedName()+" Plasma Cell"); - if (aMaterial.vComponentCount != 1){ - Logger.INFO("Compound made from: "); - for (final MaterialStack x : aMaterial.getComposites()){ - Logger.INFO(x.getStackMaterial().getLocalizedName()); - } - Logger.INFO("Material is a composite, not generating plasma."); - return null; - } - - ItemStack temp = null; - //Generate a Cell if we need to - if (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cellPlasma"+aMaterial.getUnlocalizedName(), 1) == null){ - final Item temp2 = new BaseItemPlasmaCell(aMaterial); - temp = aMaterial.getPlasmaCell(1); - } - else { - temp = ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cellPlasma"+aMaterial.getUnlocalizedName(), 1); - } - if (temp != null){ - return addGTFluid( - "plasma." + Utils.sanitizeString(aMaterial.getLocalizedName().toLowerCase()), - "plasma.autogenerated", - aMaterial.getLocalizedName() + " Plasma", - aMaterial.getRGBA(), - 3, - 10000, - temp, - ItemList.Cell_Empty.get(1L, new Object[0]), - 1000); - } - return null; - } - - public static Fluid addGTFluid(String aName, final String aTexture, final String aLocalized, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { - aName = Utils.sanitizeString(aName.toLowerCase()); - Fluid rFluid = new FluidGT6(aName, aTexture, (aRGBa != null) ? aRGBa : Dyes._NULL.getRGBA()); - GT_LanguageManager.addStringLocalization(rFluid.getUnlocalizedName(), (aLocalized == null) ? aName : aLocalized); - if (FluidRegistry.registerFluid(rFluid)) { - switch (aState) { - case 0: { - rFluid.setGaseous(false); - rFluid.setViscosity(10000); - break; - } - case 1: - case 4: { - rFluid.setGaseous(false); - rFluid.setViscosity(1000); - break; - } - case 2: { - rFluid.setGaseous(true); - rFluid.setDensity(-100); - rFluid.setViscosity(200); - break; - } - case 3: { - rFluid.setGaseous(true); - rFluid.setDensity(-10000); - rFluid.setViscosity(10); - rFluid.setLuminosity(15); - break; - } - } - } - else { - rFluid = FluidRegistry.getFluid(aName); - } - if ((rFluid.getTemperature() == new Fluid("test").getTemperature()) || (rFluid.getTemperature() <= 0)) { - rFluid.setTemperature((int) (aTemperatureK)); - } - if ((aFullContainer != null) && (aEmptyContainer != null) && !FluidContainerRegistry.registerFluidContainer(new FluidStack(rFluid, aFluidAmount), aFullContainer, aEmptyContainer)) { - GT_Values.RA.addFluidCannerRecipe(aFullContainer, container(aFullContainer, false), null, new FluidStack(rFluid, aFluidAmount)); - } - else { - //Utils.LOG_INFO("Failed creating recipes to fill/empty cells of "+aName+"."); - } - return rFluid; - } - - public static boolean valid(final Object aStack) { - return (aStack != null) && (aStack instanceof ItemStack) && (((ItemStack)aStack).getItem() != null) && (((ItemStack)aStack).stackSize >= 0); - } - - public static boolean invalid(final Object aStack) { - return (aStack == null) || !(aStack instanceof ItemStack) || (((ItemStack)aStack).getItem() == null) || (((ItemStack)aStack).stackSize < 0); - } - - public static boolean equal(final ItemStack aStack1, final ItemStack aStack2) { - return equal(aStack1, aStack2, false); - } - - public static boolean equal(final ItemStack aStack1, final ItemStack aStack2, final boolean aIgnoreNBT) { - return (aStack1 != null) && (aStack2 != null) && equal_(aStack1, aStack2, aIgnoreNBT); - } - - public static boolean equal_(final ItemStack aStack1, final ItemStack aStack2, final boolean aIgnoreNBT) { - return (aStack1.getItem() == aStack2.getItem()) && (aIgnoreNBT || ((aStack1.getTagCompound() == null == (aStack2.getTagCompound() == null)) && ((aStack1.getTagCompound() == null) || aStack1.getTagCompound().equals(aStack2.getTagCompound())))) && ((meta(aStack1) == meta(aStack2)) || (meta(aStack1) == 32767) || (meta(aStack2) == 32767)); - } - - public static ItemStack copy(final Object... aStacks) { - for (final Object tStack : aStacks) { - if (valid(tStack)) { - return ((ItemStack)tStack).copy(); - } - } - return null; - } - - public static ItemStack copyMeta(final long aMetaData, final Object... aStacks) { - final ItemStack rStack = copy(aStacks); - if (invalid(rStack)) { - return null; - } - return meta(rStack, aMetaData); - } - - public static short meta(final ItemStack aStack) { - return (short)Items.feather.getDamage(aStack); - } - - public static ItemStack meta(final ItemStack aStack, final long aMeta) { - Items.feather.setDamage(aStack, (short)aMeta); - return aStack; - } - - public static ItemStack amount(final long aAmount, final Object... aStacks) { - final ItemStack rStack = copy(aStacks); - if (invalid(rStack)) { - return null; - } - rStack.stackSize = (int)aAmount; - return rStack; - } - - public static ItemStack container(final ItemStack aStack, final boolean aCheckIFluidContainerItems) { - if (invalid(aStack)) { - return null; - } - if (aStack.getItem().hasContainerItem(aStack)) { - return aStack.getItem().getContainerItem(aStack); - } - if (equal(aStack, ItemList.Cell_Empty.get(1), true)) { - return null; - } - if (aCheckIFluidContainerItems && (aStack.getItem() instanceof IFluidContainerItem) && (((IFluidContainerItem)aStack.getItem()).getCapacity(aStack) > 0)) { - final ItemStack tStack = amount(1L, aStack); - ((IFluidContainerItem)aStack.getItem()).drain(tStack, Integer.MAX_VALUE, true); - if (!equal(aStack, tStack)) { - return tStack; - } - return null; - } - if (equal(aStack, ItemList.IC2_ForgeHammer.get(1)) || equal(aStack, ItemList.IC2_WireCutter.get(1))) { - return copyMeta(meta(aStack) + 1, aStack); - } - return null; - } - - public static ItemStack container(final ItemStack aStack, final boolean aCheckIFluidContainerItems, final int aStacksize) { - return amount(aStacksize, container(aStack, aCheckIFluidContainerItems)); - } - - public final static Fluid generateFluid(final String unlocalizedName, final String localizedName, final int MeltingPoint, final short[] RGBA){ - if ((FluidUtils.getFluidStack("molten"+"."+unlocalizedName.toLowerCase(), 1) == null) && (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("dust"+Utils.sanitizeString(localizedName), 1) != null)){ - Logger.WARNING("Generating our own fluid."); - - //Generate a Cell if we need to - if (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1) == null){ - @SuppressWarnings("unused") - final - Item temp = new BaseItemComponent(unlocalizedName, localizedName, RGBA); - } - - final Fluid gtFluid = FluidUtils.addGTFluid( - unlocalizedName, - "Molten "+localizedName, - RGBA, - 4, - MeltingPoint, - ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1), - ItemList.Cell_Empty.get(1L, new Object[0]), - 1000); - - //Disable this, not sure why it exists //TODO - /*GT_Values.RA.addFluidExtractionRecipe( - ItemUtils.getItemStackOfAmountFromOreDictNoBroken("dust"+Utils.sanitizeString(localizedName), 1), //Input - null, //Input 2 - FluidUtils.getFluidStack(gtFluid, 144), //Fluid Output - 0, //Chance - 1*20, //Duration - 16 //Eu Tick - );*/ - - - return gtFluid; - } - Logger.INFO("FLUID GENERATION FAILED FOR "+localizedName); - return null; - } - - public final static Fluid generateFluidNonMolten(final String unlocalizedName, final String localizedName, final int MeltingPoint, final short[] RGBA, final ItemStack dustStack, final ItemStack dustStack2){ - return generateFluidNonMolten(unlocalizedName, localizedName, MeltingPoint, RGBA, dustStack, dustStack2, 144); - } - - public final static Fluid generateFluidNonMolten(final String unlocalizedName, final String localizedName, final int MeltingPoint, final short[] RGBA, ItemStack dustStack, final ItemStack dustStack2, final int amountPerItem){ - if (dustStack == null){ - dustStack = ItemUtils.getItemStackOfAmountFromOreDictNoBroken("dust"+Utils.sanitizeString(localizedName), 1); - } - if ((FluidUtils.getFluidStack(unlocalizedName.toLowerCase(), 1) == null)/* && ((dustStack != null) || (dustStack2 != null))*/){ - Logger.WARNING("Generating our own fluid."); - - //Generate a Cell if we need to - if (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1) == null){ - @SuppressWarnings("unused") - final - Item temp = new BaseItemComponent(unlocalizedName, localizedName, RGBA); - } - - final Fluid gtFluid = FluidUtils.addGTFluidNonMolten( - unlocalizedName, - localizedName, - RGBA, - 4, - MeltingPoint, - ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1), - ItemList.Cell_Empty.get(1L, new Object[0]), - 1000); - - if (dustStack != null){ - GT_Values.RA.addFluidExtractionRecipe( - dustStack, //Input - null, //Input 2 - FluidUtils.getFluidStack(gtFluid, amountPerItem), //Fluid Output - 0, //Chance - 1*20, //Duration - 16 //Eu Tick - ); - } - if (dustStack2 != null){ - GT_Values.RA.addFluidExtractionRecipe( - dustStack2, //Input - null, //Input 2 - FluidUtils.getFluidStack(gtFluid, amountPerItem), //Fluid Output - 0, //Chance - 1*20, //Duration - 16 //Eu Tick - ); - } - - return gtFluid; - } - Logger.INFO("FLUID GENERATION FAILED FOR "+localizedName); - return null; - } - - public final static Fluid generateFluidNoPrefix(final String unlocalizedName, final String localizedName, final int MeltingPoint, final short[] RGBA){ - Fluid gtFluid; - if (FluidUtils.getFluidStack(unlocalizedName.toLowerCase(), 1) == null){ - Logger.WARNING("Generating our own fluid."); - gtFluid = FluidUtils.addGTFluidNoPrefix( - unlocalizedName, - localizedName, - RGBA, - 4, - MeltingPoint, - ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1), - ItemList.Cell_Empty.get(1L, new Object[0]), - 1000); - } - else { - gtFluid = FluidUtils.getFluidStack(unlocalizedName.toLowerCase(), 1).getFluid(); - } - //Generate a Cell if we need to - if (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1) == null){ - new BaseItemCell(unlocalizedName, localizedName, RGBA, gtFluid); - } - return gtFluid; - } - - - public static FluidStack getMobEssence(final int amount){ - return EnchantingUtils.getMobEssence(amount); - } - - public static FluidStack getLiquidXP(final int amount){ - return EnchantingUtils.getLiquidXP(amount); - } - - -} diff --git a/src/Java/gtPlusPlus/core/util/geo/GeoUtils.java b/src/Java/gtPlusPlus/core/util/geo/GeoUtils.java deleted file mode 100644 index 84528e0cd5..0000000000 --- a/src/Java/gtPlusPlus/core/util/geo/GeoUtils.java +++ /dev/null @@ -1,107 +0,0 @@ -package gtPlusPlus.core.util.geo; - -import java.io.*; -import java.net.*; - -import org.apache.http.client.utils.URIBuilder; - -import gtPlusPlus.api.objects.Logger; -import gtPlusPlus.core.util.networking.NetworkUtils; - -public class GeoUtils { - - public static String determineUsersCountry(){ - try { - if (NetworkUtils.checkNetworkIsAvailableWithValidInterface()){ - return getUsersCountry(); - } - else { - return "Offline."; - } - } catch (Throwable T){ - Logger.INFO("Failed to initialise GeoUtils."); - return "Failed."; - } - } - - private static String getUsersIPAddress() { - try { - String webPage = "http://checkip.amazonaws.com/"; - URL url = new URL(webPage); - URLConnection urlConnection = url.openConnection(); - InputStream is = urlConnection.getInputStream(); - InputStreamReader isr = new InputStreamReader(is); - int numCharsRead; - char[] charArray = new char[1024]; - StringBuffer sb = new StringBuffer(); - while ((numCharsRead = isr.read(charArray)) > 0) { - sb.append(charArray, 0, numCharsRead); - } - isr.close(); - String result = sb.toString(); - return result; - } catch (IOException e) {} - return "Error getting users IP."; - } - - private static String getUsersCountry() { - - //Get the IP - String ipAddress = getUsersIPAddress(); - - //Build a URL - URIBuilder builder = new URIBuilder() - .setScheme("http") - .setHost("ipinfo.io") - .setPath("/"+ipAddress+"/country/"); - - URI uri; - try { - //Convert the URI Builder to a URI, then to a URL - uri = builder.build(); - URL url = uri.toURL(); - - //Main Check method - try { - URLConnection urlConnection = url.openConnection(); - InputStream is = urlConnection.getInputStream(); - InputStreamReader isr = new InputStreamReader(is); - int numCharsRead; - char[] charArray = new char[1024]; - StringBuffer sb = new StringBuffer(); - while ((numCharsRead = isr.read(charArray)) > 0) { - sb.append(charArray, 0, numCharsRead); - } - String temp = sb.toString(); - String result = temp.replaceAll("(\\r|\\n)", ""); - isr.close(); - return result; - //Catch block for bad connection - } catch (IOException e) { - Logger.INFO("Method 1 - Failed."); - } - - //Secondary method - try (java.util.Scanner s = new java.util.Scanner(url.openStream(), "UTF-8").useDelimiter("\\A")) { - String r = s.next(); - return r.replaceAll("(\\r|\\n)", ""); - //Catch block for bad connection - } catch (java.io.IOException e) { - Logger.INFO("Method 2 - Failed."); - } - - } - //Catch block for all the Bad URI/URL building - catch (URISyntaxException | MalformedURLException e1) { - if (e1 instanceof URISyntaxException){ - Logger.INFO("Bad URI Syntax for builder."); - } - else { - Logger.INFO("Malformed URL."); - } - Logger.INFO("Country Check - Failed."); - } - return "Error getting users Country. "+ipAddress; - } - -} diff --git a/src/Java/gtPlusPlus/core/util/gregtech/material/MaterialBuilder.java b/src/Java/gtPlusPlus/core/util/gregtech/material/MaterialBuilder.java deleted file mode 100644 index 64c2751cde..0000000000 --- a/src/Java/gtPlusPlus/core/util/gregtech/material/MaterialBuilder.java +++ /dev/null @@ -1,254 +0,0 @@ -package gtPlusPlus.core.util.gregtech.material; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import gregtech.api.enums.Dyes; -import gregtech.api.enums.Materials; -import gregtech.api.enums.TC_Aspects; -import gregtech.api.enums.TextureSet; -import gregtech.api.objects.MaterialStack; - -public class MaterialBuilder { - /*public static final int DIESEL = 0, GAS = 1, THERMAL = 2, SEMIFLUID = 3, PLASMA = 4, MAGIC = 5; - - private int metaItemSubID; - private TextureSet iconSet; - private float toolSpeed = 1.0f; - private int durability = 0; - private int toolQuality = 0; - private int types = 0; - private int r = 255, g = 255, b = 255, a = 0; - private String name; - private String defaultLocalName; - private int fuelType = 0; - private int fuelPower = 0; - private int meltingPoint = 0; - private int blastFurnaceTemp = 0; - private boolean blastFurnaceRequired = false; - private boolean transparent = false; - private int oreValue = 1; - private int densityMultiplier = 1; - private int densityDivider = 1; - private Dyes color = Dyes._NULL; - private int extraData = 0; - private List materialList = new ArrayList(); - private List aspects = new ArrayList(); - private boolean canBeCracked = false; - private int liquidTemperature = 300; - private int gasTemperature = 300; - - public MaterialBuilder(int metaItemSubID, TextureSet iconSet, String defaultLocalName) { - this.metaItemSubID = metaItemSubID; - this.iconSet = iconSet; - this.name = defaultLocalName.replace(" ", "").replace("-", ""); - this.defaultLocalName = defaultLocalName; - } - - public Materials constructMaterial() { - return new Materials( - metaItemSubID, iconSet, toolSpeed, durability, toolQuality, types, r, g, b, a, name, defaultLocalName, fuelType, fuelPower, meltingPoint, blastFurnaceTemp, - blastFurnaceRequired, transparent, oreValue, densityMultiplier, densityDivider, color, extraData, materialList, aspects); - - } - - public MaterialBuilder setName(String name){ - this.name = name; - return this; - } - - public MaterialBuilder setTypes(int types){ - this.types = types; - return this; - } - - public MaterialBuilder addDustItems(){ - types = types | 1; - return this; - } - - public MaterialBuilder addMetalItems(){ - types = types | 2; - return this; - } - - public MaterialBuilder addGemItems(){ - types = types | 4; - return this; - } - - public MaterialBuilder addOreItems(){ - types = types | 8; - return this; - } - - public MaterialBuilder addCell(){ - types = types | 16; - return this; - } - - public MaterialBuilder addPlasma(){ - types = types | 32; - return this; - } - - public MaterialBuilder addToolHeadItems(){ - types = types | 64; - return this; - } - - public MaterialBuilder addGearItems(){ - types = types | 128; - return this; - } - - public MaterialBuilder addFluid(){ - return this; - } - - public MaterialBuilder addGas(){ - return this; - } - - - public MaterialBuilder setRGBA(int r, int g, int b, int a){ - this.r = r; - this.g = g; - this.b = b; - this.a = a; - return this; - } - - public MaterialBuilder setRGB(int r, int g, int b){ - this.r = r; - this.g = g; - this.b = b; - return this; - } - - public MaterialBuilder setTransparent(boolean transparent){ - this.transparent = transparent; - return this; - } - - public MaterialBuilder setColor(Dyes color){ - this.color = color; - return this; - } - - - public MaterialBuilder setToolSpeed(float toolSpeed) { - this.toolSpeed = toolSpeed; - return this; - } - - public MaterialBuilder setDurability(int durability) { - this.durability = durability; - return this; - } - - public MaterialBuilder setToolQuality(int toolQuality) { - this.toolQuality = toolQuality; - return this; - } - - - public MaterialBuilder setFuelType(int fuelType) { - this.fuelType = fuelType; - return this; - } - - public MaterialBuilder setFuelPower(int fuelPower) { - this.fuelPower = fuelPower; - return this; - } - - public MaterialBuilder setMeltingPoint(int meltingPoint) { - this.meltingPoint = meltingPoint; - return this; - } - - public MaterialBuilder setBlastFurnaceTemp(int blastFurnaceTemp) { - this.blastFurnaceTemp = blastFurnaceTemp; - return this; - } - - public MaterialBuilder setBlastFurnaceRequired(boolean blastFurnaceRequired) { - this.blastFurnaceRequired = blastFurnaceRequired; - return this; - } - - public MaterialBuilder setOreValue(int oreValue) { - this.oreValue = oreValue; - return this; - } - - public MaterialBuilder setDensityMultiplier(int densityMultiplier) { - this.densityMultiplier = densityMultiplier; - return this; - } - - public MaterialBuilder setDensityDivider(int densityDivider) { - this.densityDivider = densityDivider; - return this; - } - - public MaterialBuilder setExtraData(int extraData) { - this.extraData = extraData; - return this; - } - - public MaterialBuilder addElectrolyzerRecipe(){ - extraData = extraData | 1; - return this; - } - - public MaterialBuilder addCentrifugeRecipe(){ - extraData = extraData | 2; - return this; - } - - public MaterialBuilder setMaterialList(List materialList) { - this.materialList = materialList; - return this; - } - - public MaterialBuilder setMaterialList(MaterialStack ... materials) { - this.materialList = Arrays.asList(materials); - return this; - } - - public MaterialBuilder setAspects(List aspects) { - this.aspects = aspects; - return this; - } - - public int getLiquidTemperature() { - return liquidTemperature; - } - - public MaterialBuilder setLiquidTemperature(int liquidTemperature) { - this.liquidTemperature = liquidTemperature; - return this; - } - - public int getGasTemperature() { - return gasTemperature; - } - - public MaterialBuilder setGasTemperature(int gasTemperature) { - this.gasTemperature = gasTemperature; - return this; - } - - public boolean canBeCracked() { - return canBeCracked; - } - - public MaterialBuilder setCanBeCracked(boolean canBeCracked) { - this.canBeCracked = canBeCracked; - return this; - } -*/ -} \ No newline at end of file diff --git a/src/Java/gtPlusPlus/core/util/gregtech/recipehandlers/GregtechRecipe.java b/src/Java/gtPlusPlus/core/util/gregtech/recipehandlers/GregtechRecipe.java deleted file mode 100644 index 9bc5ee804d..0000000000 --- a/src/Java/gtPlusPlus/core/util/gregtech/recipehandlers/GregtechRecipe.java +++ /dev/null @@ -1,74 +0,0 @@ -package gtPlusPlus.core.util.gregtech.recipehandlers; - -import java.lang.reflect.Method; - -import gregtech.api.util.GT_ModHandler; -import gtPlusPlus.api.objects.Logger; -import gtPlusPlus.core.lib.CORE; -import net.minecraft.item.ItemStack; - -public final class GregtechRecipe { - - public LibraryProxy ourProxy; - public GregtechRecipe(){ - Logger.INFO("Initializing a recipe handler for different versions of Gregtech 5."); - try { - if (!CORE.MAIN_GREGTECH_5U_EXPERIMENTAL_FORK){ - this.ourProxy = new LibProxy1(); - Logger.INFO("Selecting GT 5.7/5.8 Recipe Set"); - } - if (CORE.MAIN_GREGTECH_5U_EXPERIMENTAL_FORK){ - this.ourProxy = new LibProxy2(); - Logger.INFO("Selecting GT 5.9 Recipe Set"); - } - } catch (final NoSuchMethodException e) { - this.ourProxy = null; - } - } - - public boolean addSmeltingAndAlloySmeltingRecipe(final ItemStack aInput, final ItemStack aOutput) { - Logger.WARNING("Adding a GT Furnace/Alloy Smelter Recipe"+"| Input:"+aInput.getDisplayName()+" | Output:"+aOutput.getDisplayName()+" |"); - return this.ourProxy.addSmeltingAndAlloySmeltingRecipe(aInput, aOutput); - } - -} - -abstract class LibraryProxy { // can also be interface unless you want to have common code here - abstract public boolean addSmeltingAndAlloySmeltingRecipe(ItemStack aInput, ItemStack aOutput); -} - -class LibProxy1 extends LibraryProxy { - final Method m1; - - public LibProxy1() throws NoSuchMethodException { - this.m1 = GT_ModHandler.class.getDeclaredMethod("addSmeltingAndAlloySmeltingRecipe", ItemStack.class, ItemStack.class); - } - - @Override - public boolean addSmeltingAndAlloySmeltingRecipe(final ItemStack aInput, final ItemStack aOutput) { - try { - Logger.INFO("Trying with Gt 5.7/5.8 Method."); - return (boolean) this.m1.invoke(null, aInput, aOutput); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } -} - -class LibProxy2 extends LibraryProxy { - final Method m2; - - public LibProxy2() throws NoSuchMethodException { - this.m2 = GT_ModHandler.class.getDeclaredMethod("addSmeltingAndAlloySmeltingRecipe", ItemStack.class, ItemStack.class, boolean.class); - } - - @Override - public boolean addSmeltingAndAlloySmeltingRecipe(final ItemStack aInput, final ItemStack aOutput) { - try { - Logger.INFO("Trying with Gt 5.9 Method."); - return (boolean) this.m2.invoke(null, aInput, aOutput, true); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } -} \ No newline at end of file diff --git a/src/Java/gtPlusPlus/core/util/input/KeyboardUtils.java b/src/Java/gtPlusPlus/core/util/input/KeyboardUtils.java deleted file mode 100644 index 3b5dc3b5d8..0000000000 --- a/src/Java/gtPlusPlus/core/util/input/KeyboardUtils.java +++ /dev/null @@ -1,23 +0,0 @@ -package gtPlusPlus.core.util.input; - -import org.lwjgl.input.Keyboard; - -import net.minecraft.client.Minecraft; - -public class KeyboardUtils { - - public static boolean isCtrlKeyDown(){ - // prioritize CONTROL, but allow OPTION as well on Mac (note: GuiScreen's isCtrlKeyDown only checks for the OPTION key on Mac) - boolean isCtrlKeyDown = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); - if (!isCtrlKeyDown && Minecraft.isRunningOnMac) - isCtrlKeyDown = Keyboard.isKeyDown(Keyboard.KEY_LMETA) || Keyboard.isKeyDown(Keyboard.KEY_RMETA); - - return isCtrlKeyDown; - } - - public static boolean isShiftKeyDown(){ - return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - - } - -} diff --git a/src/Java/gtPlusPlus/core/util/inventory/InventoryUtils.java b/src/Java/gtPlusPlus/core/util/inventory/InventoryUtils.java deleted file mode 100644 index 779f9b14c1..0000000000 --- a/src/Java/gtPlusPlus/core/util/inventory/InventoryUtils.java +++ /dev/null @@ -1,60 +0,0 @@ -package gtPlusPlus.core.util.inventory; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - -public class InventoryUtils { - - private final static Random mRandom = new Random(); - - public static void dropInventoryItems(World world, int x, int y, int z, Block block){ - Object tileentity = world.getTileEntity(x, y, z); - - if (tileentity != null) - { - for (int i1 = 0; i1 < ((IInventory) tileentity).getSizeInventory(); ++i1) - { - ItemStack itemstack = ((IInventory) tileentity).getStackInSlot(i1); - - if (itemstack != null) - { - float f = mRandom.nextFloat() * 0.8F + 0.1F; - float f1 = mRandom.nextFloat() * 0.8F + 0.1F; - EntityItem entityitem; - - for (float f2 = mRandom.nextFloat() * 0.8F + 0.1F; itemstack.stackSize > 0; world.spawnEntityInWorld(entityitem)) - { - int j1 = mRandom.nextInt(21) + 10; - - if (j1 > itemstack.stackSize) - { - j1 = itemstack.stackSize; - } - - itemstack.stackSize -= j1; - entityitem = new EntityItem(world, x + f, y + f1, z + f2, new ItemStack(itemstack.getItem(), j1, itemstack.getItemDamage())); - float f3 = 0.05F; - entityitem.motionX = (float)mRandom.nextGaussian() * f3; - entityitem.motionY = (float)mRandom.nextGaussian() * f3 + 0.2F; - entityitem.motionZ = (float)mRandom.nextGaussian() * f3; - - if (itemstack.hasTagCompound()) - { - entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy()); - } - } - } - } - - world.func_147453_f(x, y, z, block); - } - - } - -} diff --git a/src/Java/gtPlusPlus/core/util/item/ItemUtils.java b/src/Java/gtPlusPlus/core/util/item/ItemUtils.java deleted file mode 100644 index d5caad9dee..0000000000 --- a/src/Java/gtPlusPlus/core/util/item/ItemUtils.java +++ /dev/null @@ -1,722 +0,0 @@ -package gtPlusPlus.core.util.item; - -import java.util.ArrayList; -import java.util.List; - -import cpw.mods.fml.common.registry.GameRegistry; -import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; -import gregtech.api.enums.Materials; -import gregtech.api.enums.OrePrefixes; -import gregtech.api.util.GT_ModHandler; -import gregtech.api.util.GT_OreDictUnificator; -import gtPlusPlus.api.objects.Logger; -import gtPlusPlus.api.objects.data.Pair; -import gtPlusPlus.core.item.ModItems; -import gtPlusPlus.core.item.base.BasicSpawnEgg; -import gtPlusPlus.core.item.base.dusts.BaseItemDust; -import gtPlusPlus.core.item.base.dusts.BaseItemDustUnique; -import gtPlusPlus.core.item.base.dusts.decimal.BaseItemCentidust; -import gtPlusPlus.core.item.base.dusts.decimal.BaseItemDecidust; -import gtPlusPlus.core.item.base.plates.BaseItemPlate_OLD; -import gtPlusPlus.core.item.tool.staballoy.MultiPickaxeBase; -import gtPlusPlus.core.item.tool.staballoy.MultiSpadeBase; -import gtPlusPlus.core.lib.CORE; -import gtPlusPlus.core.lib.LoadedMods; -import gtPlusPlus.core.material.Material; -import gtPlusPlus.core.util.Utils; -import gtPlusPlus.core.util.materials.MaterialUtils; -import gtPlusPlus.core.util.reflect.ReflectionUtils; -import gtPlusPlus.core.util.wrapper.var; -import gtPlusPlus.xmod.gregtech.loaders.RecipeGen_DustGeneration; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.Item.ToolMaterial; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.oredict.OreDictionary; - -public class ItemUtils { - - public static ItemStack getSimpleStack(final Item x){ - return getSimpleStack(x, 1); - } - public static ItemStack getSimpleStack(final Block x){ - return getSimpleStack(Item.getItemFromBlock(x), 1); - } - public static ItemStack getSimpleStack(final Block x, final int i){ - return getSimpleStack(Item.getItemFromBlock(x), i); - } - public static ItemStack getSimpleStack(final Item x, final int i){ - try { - final ItemStack r = new ItemStack(x, i); - return r.copy(); - } catch(final Throwable e){ - return null; - } - } - public static ItemStack getSimpleStack(final ItemStack x, final int i){ - try { - final ItemStack r = x.copy(); - r.stackSize = i; - return r; - } catch(final Throwable e){ - return null; - } - } - - public static final int WILDCARD_VALUE = Short.MAX_VALUE; - public static ItemStack getWildcardStack(final Item x){ - final ItemStack y = new ItemStack(x, 1, WILDCARD_VALUE); - return y; - } - - - public static ItemStack getIC2Cell(final String S){ - final ItemStack moreTemp = ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+S, 1); - - if (moreTemp == null){ - final int cellID = 0; - final ItemStack temp =GT_ModHandler.getModItem("IC2", "itemCellEmpty", 1L, cellID); - return temp != null ? temp : null; - } - - return moreTemp; - } - - public static ItemStack getIC2Cell(final int meta){ - final ItemStack temp = GT_ModHandler.getModItem("IC2", "itemCellEmpty", 1L, meta); - return temp != null ? temp : null; - } - - public static ItemStack getEmptyCell(){ - return getEmptyCell(1); - } - - public static ItemStack getEmptyCell(int i){ - final ItemStack temp = GT_ModHandler.getModItem("IC2", "itemCellEmpty", i, 0); - return temp != null ? temp : null; - } - - public static void getItemForOreDict(final String FQRN, final String oreDictName, final String itemName, final int meta){ - try { - Item em = null; - final Item em1 = getItem(FQRN); - //Utils.LOG_WARNING("Found: "+em1.getUnlocalizedName()+":"+meta); - if (em1 != null){ - em = em1; - } - if (em != null){ - - final ItemStack metaStack = new ItemStack(em,1,meta); - GT_OreDictUnificator.registerOre(oreDictName, metaStack); - - /*ItemStack itemStackWithMeta = new ItemStack(em,1,meta); - GT_OreDictUnificator.registerOre(oreDictName, new ItemStack(itemStackWithMeta.getItem()));*/ - } - } catch (final NullPointerException e) { - Logger.ERROR(itemName+" not found. [NULL]"); - } - } - - public static void addItemToOreDictionary(final ItemStack stack, final String oreDictName){ - try { - GT_OreDictUnificator.registerOre(oreDictName, stack); - } catch (final NullPointerException e) { - Logger.ERROR(stack.getDisplayName()+" not registered. [NULL]"); - } - } - - public static ItemStack getItemStackWithMeta(final boolean MOD, final String FQRN, final String itemName, final int meta, final int itemstackSize){ - if (MOD){ - try { - Item em = null; - final Item em1 = getItem(FQRN); - //Utils.LOG_WARNING("Found: "+em1.getUnlocalizedName()+":"+meta); - if (em1 != null){ - if (null == em){ - em = em1; - } - if (em != null){ - final ItemStack metaStack = new ItemStack(em,itemstackSize,meta); - return metaStack; - } - } - return null; - } catch (final NullPointerException e) { - Logger.ERROR(itemName+" not found. [NULL]"); - return null; - } - } - return null; - } - - public static ItemStack simpleMetaStack(final String FQRN, final int meta, final int itemstackSize){ - try { - Item em = null; - final Item em1 = getItem(FQRN); - //Utils.LOG_WARNING("Found: "+em1.getUnlocalizedName()+":"+meta); - if (em1 != null){ - if (null == em){ - em = em1; - } - if (em != null){ - final ItemStack metaStack = new ItemStack(em,itemstackSize,meta); - return metaStack; - } - } - return null; - } catch (final NullPointerException e) { - Logger.ERROR(FQRN+" not found. [NULL]"); - return null; - } - } - - @SuppressWarnings("unused") - public static ItemStack simpleMetaStack(final Item item, final int meta, final int size){ - try { - if (item == null){ - return null; - } - Item em = item; - final Item em1 = item; - Logger.WARNING("Found: "+em1.getUnlocalizedName()+":"+meta); - if (em1 != null){ - if (null == em){ - em = em1; - } - if (em != null){ - final ItemStack metaStack = new ItemStack(em,size,meta); - return metaStack; - } - } - return null; - } catch (final NullPointerException e) { - //Utils.LOG_ERROR(item.getUnlocalizedName()+" not found. [NULL]"); - return null; - } - } - - public static ItemStack simpleMetaStack(final Block block, final int meta, final int size) { - return simpleMetaStack(Item.getItemFromBlock(block), meta, size); - } - - public static ItemStack getCorrectStacktype(final String fqrn, final int stackSize){ - final String oreDict = "ore:"; - ItemStack temp; - if (fqrn.toLowerCase().contains(oreDict.toLowerCase())){ - final String sanitizedName = fqrn.replace(oreDict, ""); - temp = ItemUtils.getItemStack(sanitizedName, stackSize); - return temp; - } - final String[] fqrnSplit = fqrn.split(":"); - String temp1; - String temp2; - temp1 = fqrnSplit[1]; - if (fqrnSplit.length < 3){temp2 = "0";} - else {temp2 = fqrnSplit[2];} - temp = ItemUtils.getItemStackWithMeta(LoadedMods.MiscUtils, fqrn, temp1, Integer.parseInt(temp2), stackSize); - return temp; - } - - public static ItemStack getCorrectStacktype(final Object item_Input, final int stackSize) { - if (item_Input instanceof String){ - return getItemStackOfAmountFromOreDictNoBroken((String) item_Input, stackSize); - } - else if (item_Input instanceof ItemStack){ - return (ItemStack) item_Input; - } - if (item_Input instanceof var){ - return ((var) item_Input).getStack(stackSize); - } - return null; - } - - public static Item getItem(final String fqrn) // fqrn = fully qualified resource name - { - final String[] fqrnSplit = fqrn.split(":"); - return GameRegistry.findItem(fqrnSplit[0], fqrnSplit[1]); - } - - public static ItemStack getItemStack(final String fqrn, final int Size) // fqrn = fully qualified resource name - { - final String[] fqrnSplit = fqrn.split(":"); - return GameRegistry.findItemStack(fqrnSplit[0], fqrnSplit[1], Size); - } - - public static void generateSpawnEgg(final String entityModID, final String parSpawnName, final int colourEgg, final int colourOverlay){ - final Item itemSpawnEgg = new BasicSpawnEgg(entityModID, parSpawnName, colourEgg, colourOverlay).setUnlocalizedName("spawn_egg_"+parSpawnName.toLowerCase()).setTextureName(CORE.MODID+":spawn_egg"); - GameRegistry.registerItem(itemSpawnEgg, "spawnEgg"+parSpawnName); - } - - - public static ItemStack[] validItemsForOreDict(final String oredictName){ - final List validNames = MaterialUtils.oreDictValuesForEntry(oredictName); - final ItemStack[] inputs = new ItemStack[validNames.size()]; - for (int i=0; i oreDictList = OreDictionary.getOres(mTemp); - if (!oreDictList.isEmpty()){ - final ItemStack returnValue = oreDictList.get(0).copy(); - returnValue.stackSize = amount; - return returnValue; - } - return getSimpleStack(ModItems.AAA_Broken, amount); - } - - public static ItemStack getItemStackOfAmountFromOreDictNoBroken(final String oredictName, final int amount){ - if (CORE.DEBUG){ - Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(1)); - Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(2)); - Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(3)); - Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(4)); - Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(5)); - } - try{ - - //Adds a check to grab dusts using GT methodology if possible. - ItemStack returnValue = null; - if (oredictName.toLowerCase().contains("dust")){ - final String MaterialName = oredictName.toLowerCase().replace("dust", ""); - final Materials m = Materials.get(MaterialName); - returnValue = getGregtechDust(m, amount); - if (returnValue != null){ - return returnValue; - } - } - - if (returnValue == null){ - returnValue = getItemStackOfAmountFromOreDict(oredictName, amount); - if (returnValue != null){ - if ((returnValue.getItem().getClass() != ModItems.AAA_Broken.getClass()) || (returnValue.getItem() != ModItems.AAA_Broken)){ - return returnValue.copy(); - } - } - } - Logger.WARNING(oredictName+" was not valid."); - return null; - } - catch (final Throwable t){ - return null; - } - } - - public static ItemStack getGregtechDust(final Materials material, final int amount){ - final ItemStack returnValue = GT_OreDictUnificator.get(OrePrefixes.dust, material, 1L); - if (returnValue != null){ - if ((returnValue.getItem().getClass() != ModItems.AAA_Broken.getClass()) || (returnValue.getItem() != ModItems.AAA_Broken)){ - return returnValue.copy(); - } - } - Logger.WARNING(material+" was not valid."); - return null; - } - - public static Item[] generateDusts(final String unlocalizedName, final String materialName, final int materialTier, final Material matInfo, final int Colour){ - final int radioactive = getRadioactivityLevel(materialName); - final Item[] output = { - new BaseItemDust("itemDust"+unlocalizedName, materialName, matInfo, Colour, "Dust", materialTier, radioactive), - new BaseItemDust("itemDustSmall"+unlocalizedName, materialName, matInfo, Colour, "Small", materialTier, radioactive), - new BaseItemDust("itemDustTiny"+unlocalizedName, materialName, matInfo, Colour, "Tiny", materialTier, radioactive)}; - return output; - } - - //NullFormula - public static Item[] generateSpecialUseDusts(final String unlocalizedName, final String materialName, final int Colour){ - return generateSpecialUseDusts(unlocalizedName, materialName, "NullFormula", Colour); - } - - public static Item[] generateSpecialUseDusts(final String unlocalizedName, final String materialName, String mChemForm, final int Colour){ - final Item[] output = { - new BaseItemDustUnique("itemDust"+unlocalizedName, materialName, mChemForm, Colour, "Dust"), - new BaseItemDustUnique("itemDustSmall"+unlocalizedName, materialName, mChemForm, Colour, "Small"), - new BaseItemDustUnique("itemDustTiny"+unlocalizedName, materialName, mChemForm, Colour, "Tiny")}; - return output; - } - - public static Item generateSpecialUsePlate(final String internalName, final String displayName, final short[] rgb, final int radioactivity){ - return generateSpecialUsePlate(internalName, displayName, Utils.rgbtoHexValue(rgb[0], rgb[1], rgb[2]), radioactivity); - } - - public static Item generateSpecialUsePlate(final String internalName, final String displayName, final String mFormula, final short[] rgb, final int radioactivity){ - return generateSpecialUsePlate(internalName, displayName, mFormula, Utils.rgbtoHexValue(rgb[0], rgb[1], rgb[2]), radioactivity); - } - - public static Item generateSpecialUsePlate(final String internalName, final String displayName, final int rgb, final int radioactivity){ - return new BaseItemPlate_OLD(internalName, displayName, rgb, radioactivity); - } - - public static Item generateSpecialUsePlate(final String internalName, final String displayName, final String mFormula, final int rgb, final int radioactivity){ - return new BaseItemPlate_OLD(internalName, displayName, mFormula, rgb, radioactivity); - } - - public static Item[] generateSpecialUseDusts(final Material material, final boolean onlyLargeDust){ - final String materialName = material.getLocalizedName(); - final String unlocalizedName = Utils.sanitizeString(materialName); - final int Colour = material.getRgbAsHex(); - Item[] output = null; - if (onlyLargeDust == false){ - output = new Item[]{ - new BaseItemDustUnique("itemDust"+unlocalizedName, materialName, Colour, "Dust"), - new BaseItemDustUnique("itemDustSmall"+unlocalizedName, materialName, Colour, "Small"), - new BaseItemDustUnique("itemDustTiny"+unlocalizedName, materialName, Colour, "Tiny")}; - } else{ - output = new Item[]{ - new BaseItemDustUnique("itemDust"+unlocalizedName, materialName, Colour, "Dust") - }; - } - - RecipeGen_DustGeneration.generateRecipes(material); - - return output; - } - - public static MultiPickaxeBase generateMultiPick(final boolean GT_Durability, final Materials material){ - final ToolMaterial customMaterial = Utils.generateToolMaterialFromGT(material); - final int enchantLevel = material.mEnchantmentToolsLevel; - final Object enchant = new Pair(material.mEnchantmentTools, enchantLevel); - return generateMultiPick(GT_Durability, customMaterial, material.mDefaultLocalName, material.mDurability, material.mRGBa, enchant); - } - - public static MultiPickaxeBase generateMultiPick(final Material material){ - final ToolMaterial customMaterial = Utils.generateToolMaterial(material); - return generateMultiPick(true, customMaterial, material.getLocalizedName(), (int) material.vDurability, material.getRGBA(), null); - } - - public static MultiPickaxeBase generateMultiPick(final boolean GT_Durability, final ToolMaterial customMaterial, final String name, final int durability, final short[] rgba, final Object enchantment){ - Logger.WARNING("Generating a Multi-Pick out of "+name); - final short[] rgb = rgba; - int dur = customMaterial.getMaxUses(); - Logger.WARNING("Determined durability for "+name+" is "+dur); - if (GT_Durability){ - dur = durability*100; - Logger.WARNING("Using gregtech durability value, "+name+" is now "+dur+"."); - } - else if (dur <= 0){ - dur = durability; - Logger.WARNING("Determined durability too low, "+name+" is now "+dur+" based on the GT material durability."); - } - if (dur <= 0){ - Logger.WARNING("Still too low, "+name+" will now go unused."); - return null; - } - - Object enchant; - if (enchantment != null){ - if (enchantment instanceof Pair){ - enchant = enchantment; - } - } - else { - enchant = null; - } - - final MultiPickaxeBase MP_Redstone = new MultiPickaxeBase( - name+" Multipick", - (customMaterial), - dur, - Utils.rgbtoHexValue(rgb[0],rgb[1],rgb[2]), - enchantment); - - if (MP_Redstone.isValid){ - return MP_Redstone; - } - Logger.WARNING("Pickaxe was not valid."); - return null; - } - - - - - - - public static MultiSpadeBase generateMultiShovel(final boolean GT_Durability, final Materials material){ - final ToolMaterial customMaterial = Utils.generateToolMaterialFromGT(material); - return generateMultiShovel(GT_Durability, customMaterial, material.mDefaultLocalName, material.mDurability, material.mRGBa); - } - - public static MultiSpadeBase generateMultiShovel(final Material material){ - final ToolMaterial customMaterial = Utils.generateToolMaterial(material); - return generateMultiShovel(true, customMaterial, material.getLocalizedName(), (int) material.vDurability, material.getRGBA()); - } - - public static MultiSpadeBase generateMultiShovel(final boolean GT_Durability, final ToolMaterial customMaterial, final String name, final int durability, final short[] rgba){ - Logger.WARNING("Generating a Multi-Spade out of "+name); - final short[] rgb = rgba; - int dur = customMaterial.getMaxUses(); - Logger.WARNING("Determined durability for "+name+" is "+dur); - if (GT_Durability){ - dur = durability*100; - Logger.WARNING("Using gregtech durability value, "+name+" is now "+dur+"."); - } - else if (dur <= 0){ - dur = durability; - Logger.WARNING("Determined durability too low, "+name+" is now "+dur+" based on the GT material durability."); - } - if (dur <= 0){ - Logger.WARNING("Still too low, "+name+" will now go unused."); - return null; - } - final MultiSpadeBase MP_Redstone = new MultiSpadeBase( - name+" Multispade", - (customMaterial), - dur, - Utils.rgbtoHexValue(rgb[0],rgb[1],rgb[2]) - ); - - if (MP_Redstone.isValid){ - return MP_Redstone; - } - return null; - } - - - - - - - - - - - - - public static BaseItemDecidust generateDecidust(final Materials material){ - if (GT_OreDictUnificator.get(OrePrefixes.dust, material, 1L) != null){ - final Material placeholder = MaterialUtils.generateMaterialFromGtENUM(material); - if (placeholder != null) { - generateDecidust(placeholder); - } - } - return null; - } - - public static BaseItemDecidust generateDecidust(final Material material){ - if ((material.getDust(1) != null) && MaterialUtils.hasValidRGBA(material.getRGBA())){ - final BaseItemDecidust Decidust = new BaseItemDecidust(material); - return Decidust; - } - return null; - } - - public static BaseItemCentidust generateCentidust(final Materials material){ - if (GT_OreDictUnificator.get(OrePrefixes.dust, material, 1L) != null){ - final Material placeholder = MaterialUtils.generateMaterialFromGtENUM(material); - if (placeholder != null) { - generateCentidust(placeholder); - } - } - return null; - } - - public static BaseItemCentidust generateCentidust(final Material material){ - if ((material.getDust(1) != null) && MaterialUtils.hasValidRGBA(material.getRGBA())){ - final BaseItemCentidust Centidust = new BaseItemCentidust(material); - return Centidust; - } - return null; - } - - public static boolean isRadioactive(final String materialName){ - int sRadiation = 0; - if (materialName.toLowerCase().contains("uranium")){ - sRadiation = 2; - } - else if (materialName.toLowerCase().contains("plutonium")){ - sRadiation = 4; - } - else if (materialName.toLowerCase().contains("thorium")){ - sRadiation = 1; - } - if (sRadiation >= 1){ - return true; - } - return false; - } - - public static int getRadioactivityLevel(final String materialName){ - int sRadiation = 0; - if (materialName.toLowerCase().contains("uranium")){ - sRadiation = 2; - } - else if (materialName.toLowerCase().contains("plutonium")){ - sRadiation = 4; - } - else if (materialName.toLowerCase().contains("thorium")){ - sRadiation = 1; - } - return sRadiation; - } - - public static String getArrayStackNames(final ItemStack[] aStack){ - String itemNames = "Item Array: "; - for (final ItemStack alph : aStack){ - - if (alph != null){ - final String temp = itemNames; - itemNames = temp + ", " + alph.getDisplayName() + " x" + alph.stackSize; - } - else { - final String temp = itemNames; - itemNames = temp + ", " + "null" + " x" + "0"; - } - } - return itemNames; - - } - - public static String[] getArrayStackNamesAsArray(final ItemStack[] aStack){ - final String[] itemNames = {}; - int arpos = 0; - for (final ItemStack alph : aStack){ - itemNames[arpos] = alph.getDisplayName(); - arpos++; - } - return itemNames; - - } - - public static String getFluidArrayStackNames(final FluidStack[] aStack){ - String itemNames = "Fluid Array: "; - for (final FluidStack alph : aStack){ - final String temp = itemNames; - itemNames = temp + ", " + alph.getFluid().getName() + " x" + alph.amount; - } - return itemNames; - - } - - public static ItemStack getGregtechCircuit(final int Meta){ - return ItemUtils.getItemStackWithMeta(LoadedMods.Gregtech, "gregtech:gt.integrated_circuit", "Gregtech Circuit", Meta, 0); - } - public static ItemStack[] getBlockDrops(final ArrayList blockDrops) { - if (blockDrops == null){ - return null; - } - if (blockDrops.isEmpty()){ - return null; - } - final ItemStack[] outputs = new ItemStack[blockDrops.size()]; - short forCounter = 0; - for (final ItemStack I : blockDrops){ - outputs[forCounter++] = I; - } - return outputs; - } - - private static String getModId(final Item item) { - try { - final GameRegistry.UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor(item); - final String modname = (id.modId == null ? id.name : id.modId); - return (id == null) || id.modId.equals("") ? "minecraft" : modname; - } catch (final Throwable t){ - try { - final UniqueIdentifier t2 = GameRegistry.findUniqueIdentifierFor(Block.getBlockFromItem(item)); - final String modname = (t2.modId == null ? t2.name : t2.modId); - return (t2 == null) || t2.modId.equals("") ? "minecraft" : modname; - } - catch (final Throwable t3){ - return "bad modid"; - } - } - } - - public static String getModId(final ItemStack key) { - return getModId(key.getItem()); - } - - //Take 2 - GT/GT++ Dusts - public static ItemStack getGregtechDust(final String oredictName, final int amount){ - final ArrayList oreDictList = OreDictionary.getOres(oredictName); - if (!oreDictList.isEmpty()){ - ItemStack returnvalue; - for (int xrc=0;xrc oreDictList = OreDictionary.getOres(oredictName); - if (!oreDictList.isEmpty()){ - ItemStack returnvalue; - for (int xrc=0;xrc oreDictList = OreDictionary.getOres(oredictname); - if (!oreDictList.isEmpty()){ - final ItemStack[] returnValues = new ItemStack[oreDictList.size()]; - for (int i=0;i0 ? returnValues : null; - } - else { - return null; - } - } - - -} diff --git a/src/Java/gtPlusPlus/core/util/locale/LocaleUtils.java b/src/Java/gtPlusPlus/core/util/locale/LocaleUtils.java deleted file mode 100644 index aea38d341e..0000000000 --- a/src/Java/gtPlusPlus/core/util/locale/LocaleUtils.java +++ /dev/null @@ -1,91 +0,0 @@ -package gtPlusPlus.core.util.locale; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -import cpw.mods.fml.common.Loader; -import cpw.mods.fml.common.ModContainer; -import cpw.mods.fml.common.registry.GameData; -import gtPlusPlus.core.util.Utils; -import gtPlusPlus.core.util.item.ItemUtils; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -public class LocaleUtils { - - public static boolean GenerateFakeLocaleFile() { - for (ModContainer modcontainer : Loader.instance().getModList()){ - if (modcontainer.getModId().toLowerCase().equals("miscutils")) { - String S = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"; - writeToFile(S); - dumpItemsAndBlocksForModContainer(modcontainer); - } - } - return true; - } - - public static boolean dumpItemsAndBlocksForModContainer(ModContainer mod) { - writeToFile("Dumping Items from "+mod.getModId()+"."); - for (Object C : GameData.getItemRegistry()) { - - try { - - if (C != null) { - if (C instanceof Item) { - Item R = (Item) C; - ItemStack IS = ItemUtils.getSimpleStack(R); - String modid = ItemUtils.getModId(IS); - if (modid.equals("miscutils") || modid.equals("ToxicEverglades")) { - String S = "["+modid+"] "+IS.getUnlocalizedName()+".name="; - writeToFile(S); - } - } - } - - } - catch (Throwable T) {} - - } - writeToFile("Dumping Blocks from "+mod.getModId()+"."); - for (Object B : GameData.getBlockRegistry()) { - - try { - - if (B != null) { - if (B instanceof Block) { - Block R = (Block) B; - ItemStack IS = ItemUtils.getSimpleStack(R); - String modid = ItemUtils.getModId(IS); - if (modid.equals("miscutils") || modid.equals("ToxicEverglades")) { - String S = "["+modid+"] "+IS.getUnlocalizedName()+".name="; - writeToFile(S); - } - } - } - - } - catch (Throwable T) {} - - } - - - return true; - } - - public static void writeToFile(String S) { - try { - File F = new File(Utils.getMcDir(), "config/GTplusplus/en_US.lang"); - BufferedWriter writer; - writer = new BufferedWriter(new FileWriter(F, true)); - writer.write(S); - writer.newLine(); - writer.close(); - } - catch (IOException e) {} - } - - -} diff --git a/src/Java/gtPlusPlus/core/util/materials/MaterialUtils.java b/src/Java/gtPlusPlus/core/util/materials/MaterialUtils.java deleted file mode 100644 index 5cd7532f0f..0000000000 --- a/src/Java/gtPlusPlus/core/util/materials/MaterialUtils.java +++ /dev/null @@ -1,253 +0,0 @@ -package gtPlusPlus.core.util.materials; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Function; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.reflect.FieldUtils; - -import gregtech.api.enums.*; -import gtPlusPlus.api.objects.Logger; -import gtPlusPlus.core.material.Material; -import gtPlusPlus.core.material.state.MaterialState; -import gtPlusPlus.core.util.StringUtils; -import gtPlusPlus.core.util.Utils; -import net.minecraft.item.ItemStack; -import net.minecraftforge.oredict.OreDictionary; - -public class MaterialUtils { - - public static short firstID = 791; - - @SuppressWarnings({ "rawtypes", "unused" }) - private static Class[][] commonTypes = -{{Materials.class, int.class, TextureSet.class, float.class, int.class, - int.class, int.class, int.class, int.class, int.class, int.class, - String.class, int.class, int.class, int.class, int.class, boolean.class, - boolean.class, int.class, int.class, int.class, Dyes.class, int.class, - List.class , List.class}}; - - public static List oreDictValuesForEntry(final String oredictName){ - List oredictItemNames; - if(OreDictionary.doesOreNameExist(oredictName)){ - final List oredictItems = OreDictionary.getOres(oredictName); - oredictItemNames = oredictItems; - return oredictItemNames; - } - return null; - } - - public static Material generateMaterialFromGtENUM(final Materials material){ - @SuppressWarnings("deprecation") - String name = material.name(); - final short[] rgba = material.mRGBa; - final int melting = material.mMeltingPoint; - final int boiling = material.mBlastFurnaceTemp; - final long protons = material.getProtons(); - final long neutrons = material.getNeutrons(); - final boolean blastFurnace = material.mBlastFurnaceRequired; - final TextureSet iconSet = material.mIconSet; - final int durability = material.mDurability; - boolean mGenerateCell = false; - MaterialState materialState; - String chemicalFormula = StringUtils.subscript(Utils.sanitizeString(material.mChemicalFormula)); - final Element element = material.mElement; - int radioactivity = 0; - if (material.isRadioactive()){ - radioactivity = 1; - } - - //Weird Blacklist of Bad Chemical Strings - if (material.mElement == Element.Pb || material.mElement == Element.Na || material.mElement == Element.Ar){ - chemicalFormula = StringUtils.subscript(Utils.sanitizeString(material.mElement.name())); - } - - //Determine default state - Logger.MATERIALS("[Debug] Setting State of GT generated material. "+material.mDefaultLocalName); - if (material.getMolten(1) != null || material.getSolid(1) != null){ - materialState = MaterialState.SOLID; - Logger.MATERIALS("[Debug] Molten or Solid was not null."); - if (material.getMolten(1) == null && material.getSolid(1) != null){ - Logger.MATERIALS("[Debug] Molten is Null, Solid is not. Enabling cell generation."); - mGenerateCell = true; - } - else if (material.getMolten(1) != null && material.getSolid(1) == null){ - Logger.MATERIALS("[Debug] Molten is not Null, Solid is null. Not enabling cell generation."); - //mGenerateCell = true; - } - Logger.MATERIALS("[Debug] State set as solid."); - } - else if (material.getFluid(1) != null){ - Logger.MATERIALS("[Debug] State set as liquid."); - materialState = MaterialState.LIQUID; - } - else if (material.getGas(1) != null){ - Logger.MATERIALS("[Debug] State set as gas."); - materialState = MaterialState.GAS; - }/* - else if (material.getPlasma(1) != null){ - Logger.MATERIALS("[Debug] State set as plasma."); - materialState = MaterialState.PLASMA; - }*/ - else { - Logger.MATERIALS("[Debug] State set as solid."); - materialState = MaterialState.SOLID; - } - - - if (name.toLowerCase().contains("infused")){ - final String tempname = name.substring(7, name.length()); - name = "Infused " + tempname; - } - if (hasValidRGBA(rgba) || (element == Element.H) || ((material == Materials.InfusedAir) || (material == Materials.InfusedFire) || (material == Materials.InfusedEarth) || (material == Materials.InfusedWater))){ - //ModItems.itemBaseDecidust = UtilsItems.generateDecidust(material); - //ModItems.itemBaseCentidust = UtilsItems.generateCentidust(material); - return new Material(name, materialState,iconSet, durability, rgba, melting, boiling, protons, neutrons, blastFurnace, chemicalFormula, radioactivity, mGenerateCell); - } - else { - Logger.DEBUG_MATERIALS("Failed to generate GT++ material instance for "+material.name() +" | Valid RGB? "+(hasValidRGBA(rgba))); - } - return null; - - } - - public static Material generateQuickMaterial(final String materialName, final MaterialState defaultState, final short[] colour, final int sRadioactivity) { - final Material temp = new Material( - materialName, - defaultState, - 0, //Durability - colour, - 1000, //melting - 3000, //boiling - 50, //Protons - 50, //Neutrons - false, - "", - sRadioactivity); - return temp; - } - - public static boolean hasValidRGBA(final short[] rgba){ - if (rgba == null || rgba.length < 3 || rgba.length > 4){ - return false; - } - return true; - } - - public static int getTierOfMaterial(final int M){ - if ((M >= 0) && (M <= 1000)){ - return 1; - } - else if((M >= 1001) && (M <= 2000)){ - return 2; - } - else if((M >= 2001) && (M <= 3000)){ - return 3; - } - else if((M >= 3001) && (M <= 4000)){ - return 4; - } - else if((M >= 4001) && (M <= 5000)){ - return 5; - } - else if((M >= 5001) && (M <= 6000)){ - return 6; - } - else if((M >= 6001) && (M <= 7000)){ - return 7; - } - else if((M >= 7001) && (M <= 8000)){ - return 8; - } - else if((M >= 8001) && (M <= 9000)){ - return 9; - } - else if((M >= 9001) && (M <= 9999)){ - return 10; - } - else { - return 0; - } - } - - - /* - * That's shown, many times, in the EnumHelper code, all the add functions just wrap the addEnum function. - You need the target enum class, and 2 arrays, 1 holding the types for the constructor arguments, - and the other holding the constructor argument values (the things being passed to the constructor) - - The 'decompiled' Boolean should be set to true if the class you're adding to has been decompiled/recompiled again. - (it adds a 2nd enum arguments that need to be accounted for, but isn't actually useful to you) - - * - *new Class[{int.class, TextureSet.class, float.class, int.class, - int.class, int.class, int.class, int.class, int.class, int.class, - String.class, int.class, int.class, int.class, int.class, boolean.class, - boolean.class, int.class, int.class, int.class, Dyes.class, int.class, - List.class , List.class}], - */ - - - - /*public static Materials GenerateGtMaterialForSingleUse(MaterialInfo s){ - - Materials yourName = EnumHelper.addEnum( - - Materials.class, s.name(), - - - - new Object[0] - - ); - try - { - - - - Class clz = item.getClass(); - Method methode = clz.getDeclaredMethod("addCell", int.class, InternalName.class, Block[].class); - methode.setAccessible(true); - ItemStack temp = (ItemStack) methode.invoke(item, cellID++, yourName, new Block[0]); - - - - - - - return Materials.Abyssal; - } - catch(Exception e){ - e.printStackTrace(); - } - return null; - }*/ - - - @SuppressWarnings("deprecation") - public static String getMaterialName(Materials mat){ - String mName; - try { - mName = (String) FieldUtils.getDeclaredField(Materials.class, "mName", true).get(mat); - } - catch (IllegalArgumentException | IllegalAccessException e) { - mName = mat.name(); - } - if (mName == null || mName.equals("") || mName == ""){ - mName = mat.name(); - } - return mName; - } - - public static TextureSet getMostCommonTextureSet(List list) { - Optional r = list.stream().map(Material::getTextureSet).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey); - TextureSet o = (r != null && r.isPresent() && r.get() != null) ? r.get() : null; - return o; - } - - - } - - diff --git a/src/Java/gtPlusPlus/core/util/minecraft/EnchantingUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/EnchantingUtils.java new file mode 100644 index 0000000000..2f273d5f7f --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/EnchantingUtils.java @@ -0,0 +1,102 @@ +package gtPlusPlus.core.util.minecraft; + +import gtPlusPlus.api.objects.Logger; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +public class EnchantingUtils { + + + public static final int XP_PER_BOTTLE = 8; + public static final int RATIO = 20; + public static final int LIQUID_PER_XP_BOTTLE = 160; + public static final double RATIO_MOB_ESSENCE_TO_LIQUID_XP = 13.32; + + public static int liquidToXpRatio(final int liquid) { + return liquid / RATIO; + } + + public static int xpToLiquidRatio(final int xp) { + return xp * RATIO; + } + + public static FluidStack getEssenceFromLiquidXp(final int xpAmount){ + if (xpAmount <= 0){ + return null; + } + return getMobEssence((int) (xpAmount*RATIO_MOB_ESSENCE_TO_LIQUID_XP)); + } + + public static FluidStack getLiquidXpFromEssence(final int essenceAmount){ + if (essenceAmount <= 0){ + return null; + } + return getLiquidXP((int) (essenceAmount/RATIO_MOB_ESSENCE_TO_LIQUID_XP)); + } + + public static int getLiquidForLevel(final int level) { + final int xp = getExperienceForLevel(level); + return xpToLiquidRatio(xp); + } + + public static int getLevelForLiquid(final int liquid) { + final int xp = liquidToXpRatio(liquid); + return getLevelForExperience(xp); + } + + public static int getExperienceForLevel(final int level) { + if (level == 0) { + return 0; + } + if ((level > 0) && (level < 16)) { + return level * 17; + } + if ((level > 15) && (level < 31)) { + return (int) (((1.5 * Math.pow(level, 2.0)) - (29.5 * level)) + 360.0); + } + return (int) (((3.5 * Math.pow(level, 2.0)) - (151.5 * level)) + 2220.0); + } + + public static int getXpToNextLevel(final int level) { + final int levelXP = getLevelForExperience(level); + final int nextXP = getExperienceForLevel(level + 1); + return nextXP - levelXP; + } + + public static int getLevelForExperience(final int experience) { + int i; + for (i = 0; getExperienceForLevel(i) <= experience; ++i) { + } + return i - 1; + } + + + + + + + + //Xp Fluids + public static FluidStack getMobEssence(final int amount){ + Logger.WARNING("Trying to get a fluid stack of Mob Essence."); + try { + return FluidRegistry.getFluidStack("mobessence", amount).copy(); + } + catch (final Throwable e){ + return null; + } + + } + + public static FluidStack getLiquidXP(final int amount){ + Logger.WARNING("Trying to get a fluid stack of Liquid XP."); + try { + return FluidRegistry.getFluidStack("xpjuice", amount).copy(); + } + catch (final Throwable e){ + return null; + } + + } + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/EntityUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/EntityUtils.java new file mode 100644 index 0000000000..b16089c0de --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/EntityUtils.java @@ -0,0 +1,113 @@ +package gtPlusPlus.core.util.minecraft; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import cpw.mods.fml.common.registry.EntityRegistry; +import gregtech.api.util.GT_Utility; +import gtPlusPlus.api.objects.minecraft.BlockPos; +import gtPlusPlus.core.util.reflect.ReflectionUtils; +import ic2.core.IC2Potion; +import ic2.core.item.armor.ItemArmorHazmat; +import net.minecraft.block.Block; +import net.minecraft.entity.*; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.DamageSource; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; + +public class EntityUtils { + + public static void setEntityOnFire(final Entity entity, final int length){ + entity.setFire(length); + } + + public static int getFacingDirection(final Entity entity){ + final int d = MathHelper.floor_double((entity.rotationYaw * 4.0F) / 360 + 0.50) & 3; + return d; + } + + @Deprecated + public static Block findBlockUnderEntityNonBoundingBox(final Entity parEntity){ + final int blockX = MathHelper.floor_double(parEntity.posX); + final int blockY = MathHelper.floor_double(parEntity.posY-0.2D - parEntity.yOffset); + final int blockZ = MathHelper.floor_double(parEntity.posZ); + return parEntity.worldObj.getBlock(blockX, blockY, blockZ); + } + + public static Block findBlockUnderEntity(final Entity parEntity){ + final int blockX = MathHelper.floor_double(parEntity.posX); + final int blockY = MathHelper.floor_double(parEntity.boundingBox.minY)-1; + final int blockZ = MathHelper.floor_double(parEntity.posZ); + return parEntity.worldObj.getBlock(blockX, blockY, blockZ); + } + + public static BlockPos findBlockPosUnderEntity(final Entity parEntity){ + final int blockX = MathHelper.floor_double(parEntity.posX); + final int blockY = MathHelper.floor_double(parEntity.boundingBox.minY)-1; + final int blockZ = MathHelper.floor_double(parEntity.posZ); + return new BlockPos(blockX, blockY, blockZ); + } + + //TODO + public static void registerEntityToBiomeSpawns(final Class classy, final EnumCreatureType EntityType, final BiomeGenBase baseBiomeGen){ + EntityRegistry.addSpawn(classy, 6, 1, 5, EntityType, baseBiomeGen); //change the values to vary the spawn rarity, biome, etc. + } + + public static boolean applyRadiationDamageToEntity(final int stackSize, final int radiationLevel, final World world, final Entity entityHolding){ + if (!world.isRemote){ + if ((radiationLevel > 0) && (entityHolding instanceof EntityLivingBase)) { + final EntityLivingBase entityLiving = (EntityLivingBase) entityHolding; + if (!((EntityPlayer) entityHolding).capabilities.isCreativeMode){ + if (!ItemArmorHazmat.hasCompleteHazmat(entityLiving) && !GT_Utility.isWearingFullRadioHazmat(entityLiving)) { + int duration; + if (entityLiving.getActivePotionEffect(IC2Potion.radiation) != null){ + //Utils.LOG_INFO("t"); + duration = (radiationLevel*5)+entityLiving.getActivePotionEffect(IC2Potion.radiation).getDuration(); + } + else { + //Utils.LOG_INFO("f"); + duration = radiationLevel*30; + } + //IC2Potion.radiation.applyTo(entityLiving, duration, damage * 15); + GT_Utility.applyRadioactivity(entityLiving, radiationLevel, stackSize); + } + } + } + return true; + } + return false; + } + + + /** + * Static Version of the method used in {@code doFireDamage(entity, int)} to save memory. + */ + private static volatile Method dealFireDamage; + + /** + * Reflective Call to do Fire Damage to an entity (Does not set entity on fire though) + */ + public static boolean doFireDamage(Entity entity, int amount){ + if (dealFireDamage == null){ + try { + dealFireDamage = Entity.class.getDeclaredMethod("dealFireDamage", int.class); + dealFireDamage.setAccessible(true); + } + catch (NoSuchMethodException | SecurityException e) {} + } + else { + try { + dealFireDamage.invoke(entity, amount); + } + catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {} + } + return false; + } + + public static void doDamage(Entity entity, DamageSource dmg, int i) { + entity.attackEntityFrom(dmg, i); + } + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/FluidUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/FluidUtils.java new file mode 100644 index 0000000000..3e46b01fc7 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/FluidUtils.java @@ -0,0 +1,550 @@ +package gtPlusPlus.core.util.minecraft; + +import gregtech.api.enums.Dyes; +import gregtech.api.enums.GT_Values; +import gregtech.api.enums.ItemList; +import gregtech.api.util.GT_LanguageManager; +import gtPlusPlus.api.objects.Logger; +import gtPlusPlus.api.objects.minecraft.FluidGT6; +import gtPlusPlus.core.fluids.GenericFluid; +import gtPlusPlus.core.item.base.BaseItemComponent; +import gtPlusPlus.core.item.base.cell.BaseItemCell; +import gtPlusPlus.core.item.base.cell.BaseItemPlasmaCell; +import gtPlusPlus.core.material.Material; +import gtPlusPlus.core.material.MaterialStack; +import gtPlusPlus.core.util.Utils; +import gtPlusPlus.xmod.gregtech.api.enums.GregtechOrePrefixes.GT_Materials; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidContainerItem; + +public class FluidUtils { + + public static FluidStack getWater(final int amount){ + return FluidUtils.getFluidStack("water", amount); + } + + public static FluidStack getlava(final int amount){ + return FluidUtils.getFluidStack("lava", amount); + } + + public static FluidStack getMilk(final int amount){ + return FluidUtils.getFluidStack("milk", amount); + } + + public static FluidStack getFluidStack(final String fluidName, final int amount){ + Logger.WARNING("Trying to get a fluid stack of "+fluidName); + try { + return FluidRegistry.getFluidStack(fluidName, amount).copy(); + } + catch (final Throwable e){ + return null; + } + + } + + public static FluidStack getFluidStack(final FluidStack vmoltenFluid, final int fluidAmount) { + Logger.WARNING("Trying to get a fluid stack of "+vmoltenFluid.getFluid().getName()); + try { + return FluidRegistry.getFluidStack(vmoltenFluid.getFluid().getName(), fluidAmount).copy(); + } + catch (final Throwable e){ + return null; + } + } + + public static FluidStack getFluidStack(final Fluid vFluid, final int fluidAmount) { + Logger.WARNING("Trying to get a fluid stack of "+vFluid.getName()); + try { + return FluidRegistry.getFluidStack(vFluid.getName(), fluidAmount).copy(); + } + catch (final Throwable e){ + return null; + } + } + + public static FluidStack[] getFluidStackArray(final String fluidName, final int amount){ + Logger.WARNING("Trying to get a fluid stack of "+fluidName); + try { + final FluidStack[] singleFluid = {FluidRegistry.getFluidStack(fluidName, amount)}; + return singleFluid; + } + catch (final Throwable e){ + return null; + } + + } + + public static FluidStack[] getFluidStackArray(final FluidStack fluidName, final int amount){ + Logger.WARNING("Trying to get a fluid stack of "+fluidName); + try { + final FluidStack[] singleFluid = {FluidRegistry.getFluidStack(fluidName.getLocalizedName(), amount)}; + return singleFluid; + } + catch (final Throwable e){ + return null; + } + + } + + + /** + * @param String displayName + * @param String fluidName + * @param int meltingPointC Temp + * @param short[] rgba + * @param byte state + * States: 0 (Solid), 1 (Fluid), 2(Gas), 3(Plasma) 4(Fuel I think? Don't use.) + * + * @return short[] + */ + public static Fluid generateFluid(final String displayName, final String fluidName, final int tempK, final short[] rgba ,final int aState){ + Fluid generatedFluid = null; + switch (aState) { + case 0: { + generatedFluid = new GenericFluid(displayName, fluidName, 0, 100, tempK, 10000, false, rgba); + break; + } + default: + case 1: + case 4: { + generatedFluid = new GenericFluid(displayName, fluidName, 0, 100, tempK, 1000, false, rgba); + break; + } + case 2: { + generatedFluid = new GenericFluid(displayName, fluidName, 0, -100, tempK, 200, true, rgba); + break; + } + case 3: { + generatedFluid = new GenericFluid(displayName, fluidName, 15, -10000, tempK, 10, true, rgba); + break; + } + } + return generatedFluid; + } + /** + * + * @param String fluidName + * @param int meltingPointC Temp + * @param short[] rgba + * @param byte state + * States: 0 (Solid), 1 (Fluid), 2(Gas), 3(Plasma) 4(Fuel I think? Don't use.) + * + * @return short[] + */ + public static Fluid generateFluid(final Material material ,final int aState){ + final int tempK = material.getMeltingPointC(); + Fluid generatedFluid = null; + switch (aState) { + case 0: { + generatedFluid = new GenericFluid(material, 0, 100, tempK, 10000, false); + break; + } + default: + case 1: + case 4: { + generatedFluid = new GenericFluid(material, 0, 100, tempK, 1000, false); + break; + } + case 2: { + generatedFluid = new GenericFluid(material, 0, -100, tempK, 200, true); + break; + } + case 3: { + generatedFluid = new GenericFluid(material, 15, -10000, tempK, 10, true); + break; + } + } + return generatedFluid; + } + + + public static Fluid addAutogeneratedMoltenFluid(final String materialNameFormatted, final short[] rgba, final int MeltingPoint) { + return addFluid("molten." + materialNameFormatted.toLowerCase(), "molten.autogenerated", "Molten " + materialNameFormatted, null, rgba, 1, (MeltingPoint <= 0L) ? 1000L : MeltingPoint, null, null, 0); + } + + public static Fluid addAutogeneratedMoltenFluid(final GT_Materials aMaterial) { + return addFluid("molten." + aMaterial.name().toLowerCase(), "molten.autogenerated", "Molten " + aMaterial.name(), aMaterial, aMaterial.mMoltenRGBa, 1, (aMaterial.mMeltingPoint <= 0L) ? 1000L : aMaterial.mMeltingPoint, null, null, 0); + } + + public static Fluid addFluid(final String aName, final String aLocalized, final GT_Materials aMaterial, final int aState, final long aTemperatureK) { + return addFluid(aName, aLocalized, aMaterial, aState, aTemperatureK, null, null, 0); + } + + public static Fluid addFluid(final String aName, final String aLocalized, final GT_Materials aMaterial, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { + return addFluid(aName, aName.toLowerCase(), aLocalized, aMaterial, null, aState, aTemperatureK, aFullContainer, aEmptyContainer, aFluidAmount); + } + + public static Fluid addFluid(String aName, final String aTexture, final String aLocalized, final GT_Materials aMaterial, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { + aName = Utils.sanitizeString(aName.toLowerCase()); + Fluid rFluid = new FluidGT6(aName, aTexture, (aRGBa != null) ? aRGBa : Dyes._NULL.getRGBA()); + GT_LanguageManager.addStringLocalization(rFluid.getUnlocalizedName(), (aLocalized == null) ? aName : aLocalized); + if (FluidRegistry.registerFluid(rFluid)) { + switch (aState) { + case 0: { + rFluid.setGaseous(false); + rFluid.setViscosity(10000); + break; + } + case 1: + case 4: { + rFluid.setGaseous(false); + rFluid.setViscosity(1000); + break; + } + case 2: { + rFluid.setGaseous(true); + rFluid.setDensity(-100); + rFluid.setViscosity(200); + break; + } + case 3: { + rFluid.setGaseous(true); + rFluid.setDensity(-10000); + rFluid.setViscosity(10); + rFluid.setLuminosity(15); + break; + } + } + } + else { + rFluid = FluidRegistry.getFluid(aName); + } + if ((rFluid.getTemperature() == new Fluid("test").getTemperature()) || (rFluid.getTemperature() <= 0)) { + rFluid.setTemperature((int) (aTemperatureK)); + } + if (aMaterial != null) { + switch (aState) { + case 1: { + aMaterial.mFluid = (rFluid); + break; + } + case 2: { + aMaterial.mGas = (rFluid); + break; + } + case 3: { + aMaterial.mPlasma = (rFluid); + break; + } + } + } + if ((aFullContainer != null) && (aEmptyContainer != null) && !FluidContainerRegistry.registerFluidContainer(new FluidStack(rFluid, aFluidAmount), aFullContainer, aEmptyContainer)) { + GT_Values.RA.addFluidCannerRecipe(aFullContainer, container(aFullContainer, false), null, new FluidStack(rFluid, aFluidAmount)); + } + return rFluid; + } + + public static Fluid addGTFluid(final String aName, final String aLocalized, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { + return addGTFluid("molten."+aName, "molten.autogenerated", aLocalized, aRGBa, aState, aTemperatureK, aFullContainer, aEmptyContainer, aFluidAmount); + } + + public static Fluid addGTFluidNonMolten(final String aName, final String aLocalized, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { + return addGTFluid("fluid."+aName, "fluid.autogenerated", aLocalized, aRGBa, aState, aTemperatureK, aFullContainer, aEmptyContainer, aFluidAmount); + } + + public static Fluid addGTFluidNoPrefix(final String aName, final String aLocalized, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { + return addGTFluid(aName, "fluid.autogenerated", aLocalized, aRGBa, aState, aTemperatureK, aFullContainer, aEmptyContainer, aFluidAmount); + } + + public static Fluid addGTPlasma(final Material aMaterial) { + if (aMaterial.getLocalizedName().toLowerCase().contains("clay") || (aMaterial.getComposites().size()>1) || aMaterial.getLocalizedName().toLowerCase().contains("wrought")){ + return null; + } + Logger.INFO("Generating a "+aMaterial.getLocalizedName()+" Plasma Cell"); + if (aMaterial.vComponentCount != 1){ + Logger.INFO("Compound made from: "); + for (final MaterialStack x : aMaterial.getComposites()){ + Logger.INFO(x.getStackMaterial().getLocalizedName()); + } + Logger.INFO("Material is a composite, not generating plasma."); + return null; + } + + ItemStack temp = null; + //Generate a Cell if we need to + if (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cellPlasma"+aMaterial.getUnlocalizedName(), 1) == null){ + final Item temp2 = new BaseItemPlasmaCell(aMaterial); + temp = aMaterial.getPlasmaCell(1); + } + else { + temp = ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cellPlasma"+aMaterial.getUnlocalizedName(), 1); + } + if (temp != null){ + return addGTFluid( + "plasma." + Utils.sanitizeString(aMaterial.getLocalizedName().toLowerCase()), + "plasma.autogenerated", + aMaterial.getLocalizedName() + " Plasma", + aMaterial.getRGBA(), + 3, + 10000, + temp, + ItemList.Cell_Empty.get(1L, new Object[0]), + 1000); + } + return null; + } + + public static Fluid addGTFluid(String aName, final String aTexture, final String aLocalized, final short[] aRGBa, final int aState, final long aTemperatureK, final ItemStack aFullContainer, final ItemStack aEmptyContainer, final int aFluidAmount) { + aName = Utils.sanitizeString(aName.toLowerCase()); + Fluid rFluid = new FluidGT6(aName, aTexture, (aRGBa != null) ? aRGBa : Dyes._NULL.getRGBA()); + GT_LanguageManager.addStringLocalization(rFluid.getUnlocalizedName(), (aLocalized == null) ? aName : aLocalized); + if (FluidRegistry.registerFluid(rFluid)) { + switch (aState) { + case 0: { + rFluid.setGaseous(false); + rFluid.setViscosity(10000); + break; + } + case 1: + case 4: { + rFluid.setGaseous(false); + rFluid.setViscosity(1000); + break; + } + case 2: { + rFluid.setGaseous(true); + rFluid.setDensity(-100); + rFluid.setViscosity(200); + break; + } + case 3: { + rFluid.setGaseous(true); + rFluid.setDensity(-10000); + rFluid.setViscosity(10); + rFluid.setLuminosity(15); + break; + } + } + } + else { + rFluid = FluidRegistry.getFluid(aName); + } + if ((rFluid.getTemperature() == new Fluid("test").getTemperature()) || (rFluid.getTemperature() <= 0)) { + rFluid.setTemperature((int) (aTemperatureK)); + } + if ((aFullContainer != null) && (aEmptyContainer != null) && !FluidContainerRegistry.registerFluidContainer(new FluidStack(rFluid, aFluidAmount), aFullContainer, aEmptyContainer)) { + GT_Values.RA.addFluidCannerRecipe(aFullContainer, container(aFullContainer, false), null, new FluidStack(rFluid, aFluidAmount)); + } + else { + //Utils.LOG_INFO("Failed creating recipes to fill/empty cells of "+aName+"."); + } + return rFluid; + } + + public static boolean valid(final Object aStack) { + return (aStack != null) && (aStack instanceof ItemStack) && (((ItemStack)aStack).getItem() != null) && (((ItemStack)aStack).stackSize >= 0); + } + + public static boolean invalid(final Object aStack) { + return (aStack == null) || !(aStack instanceof ItemStack) || (((ItemStack)aStack).getItem() == null) || (((ItemStack)aStack).stackSize < 0); + } + + public static boolean equal(final ItemStack aStack1, final ItemStack aStack2) { + return equal(aStack1, aStack2, false); + } + + public static boolean equal(final ItemStack aStack1, final ItemStack aStack2, final boolean aIgnoreNBT) { + return (aStack1 != null) && (aStack2 != null) && equal_(aStack1, aStack2, aIgnoreNBT); + } + + public static boolean equal_(final ItemStack aStack1, final ItemStack aStack2, final boolean aIgnoreNBT) { + return (aStack1.getItem() == aStack2.getItem()) && (aIgnoreNBT || ((aStack1.getTagCompound() == null == (aStack2.getTagCompound() == null)) && ((aStack1.getTagCompound() == null) || aStack1.getTagCompound().equals(aStack2.getTagCompound())))) && ((meta(aStack1) == meta(aStack2)) || (meta(aStack1) == 32767) || (meta(aStack2) == 32767)); + } + + public static ItemStack copy(final Object... aStacks) { + for (final Object tStack : aStacks) { + if (valid(tStack)) { + return ((ItemStack)tStack).copy(); + } + } + return null; + } + + public static ItemStack copyMeta(final long aMetaData, final Object... aStacks) { + final ItemStack rStack = copy(aStacks); + if (invalid(rStack)) { + return null; + } + return meta(rStack, aMetaData); + } + + public static short meta(final ItemStack aStack) { + return (short)Items.feather.getDamage(aStack); + } + + public static ItemStack meta(final ItemStack aStack, final long aMeta) { + Items.feather.setDamage(aStack, (short)aMeta); + return aStack; + } + + public static ItemStack amount(final long aAmount, final Object... aStacks) { + final ItemStack rStack = copy(aStacks); + if (invalid(rStack)) { + return null; + } + rStack.stackSize = (int)aAmount; + return rStack; + } + + public static ItemStack container(final ItemStack aStack, final boolean aCheckIFluidContainerItems) { + if (invalid(aStack)) { + return null; + } + if (aStack.getItem().hasContainerItem(aStack)) { + return aStack.getItem().getContainerItem(aStack); + } + if (equal(aStack, ItemList.Cell_Empty.get(1), true)) { + return null; + } + if (aCheckIFluidContainerItems && (aStack.getItem() instanceof IFluidContainerItem) && (((IFluidContainerItem)aStack.getItem()).getCapacity(aStack) > 0)) { + final ItemStack tStack = amount(1L, aStack); + ((IFluidContainerItem)aStack.getItem()).drain(tStack, Integer.MAX_VALUE, true); + if (!equal(aStack, tStack)) { + return tStack; + } + return null; + } + if (equal(aStack, ItemList.IC2_ForgeHammer.get(1)) || equal(aStack, ItemList.IC2_WireCutter.get(1))) { + return copyMeta(meta(aStack) + 1, aStack); + } + return null; + } + + public static ItemStack container(final ItemStack aStack, final boolean aCheckIFluidContainerItems, final int aStacksize) { + return amount(aStacksize, container(aStack, aCheckIFluidContainerItems)); + } + + public final static Fluid generateFluid(final String unlocalizedName, final String localizedName, final int MeltingPoint, final short[] RGBA){ + if ((FluidUtils.getFluidStack("molten"+"."+unlocalizedName.toLowerCase(), 1) == null) && (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("dust"+Utils.sanitizeString(localizedName), 1) != null)){ + Logger.WARNING("Generating our own fluid."); + + //Generate a Cell if we need to + if (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1) == null){ + @SuppressWarnings("unused") + final + Item temp = new BaseItemComponent(unlocalizedName, localizedName, RGBA); + } + + final Fluid gtFluid = FluidUtils.addGTFluid( + unlocalizedName, + "Molten "+localizedName, + RGBA, + 4, + MeltingPoint, + ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1), + ItemList.Cell_Empty.get(1L, new Object[0]), + 1000); + + //Disable this, not sure why it exists //TODO + /*GT_Values.RA.addFluidExtractionRecipe( + ItemUtils.getItemStackOfAmountFromOreDictNoBroken("dust"+Utils.sanitizeString(localizedName), 1), //Input + null, //Input 2 + FluidUtils.getFluidStack(gtFluid, 144), //Fluid Output + 0, //Chance + 1*20, //Duration + 16 //Eu Tick + );*/ + + + return gtFluid; + } + Logger.INFO("FLUID GENERATION FAILED FOR "+localizedName); + return null; + } + + public final static Fluid generateFluidNonMolten(final String unlocalizedName, final String localizedName, final int MeltingPoint, final short[] RGBA, final ItemStack dustStack, final ItemStack dustStack2){ + return generateFluidNonMolten(unlocalizedName, localizedName, MeltingPoint, RGBA, dustStack, dustStack2, 144); + } + + public final static Fluid generateFluidNonMolten(final String unlocalizedName, final String localizedName, final int MeltingPoint, final short[] RGBA, ItemStack dustStack, final ItemStack dustStack2, final int amountPerItem){ + if (dustStack == null){ + dustStack = ItemUtils.getItemStackOfAmountFromOreDictNoBroken("dust"+Utils.sanitizeString(localizedName), 1); + } + if ((FluidUtils.getFluidStack(unlocalizedName.toLowerCase(), 1) == null)/* && ((dustStack != null) || (dustStack2 != null))*/){ + Logger.WARNING("Generating our own fluid."); + + //Generate a Cell if we need to + if (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1) == null){ + @SuppressWarnings("unused") + final + Item temp = new BaseItemComponent(unlocalizedName, localizedName, RGBA); + } + + final Fluid gtFluid = FluidUtils.addGTFluidNonMolten( + unlocalizedName, + localizedName, + RGBA, + 4, + MeltingPoint, + ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1), + ItemList.Cell_Empty.get(1L, new Object[0]), + 1000); + + if (dustStack != null){ + GT_Values.RA.addFluidExtractionRecipe( + dustStack, //Input + null, //Input 2 + FluidUtils.getFluidStack(gtFluid, amountPerItem), //Fluid Output + 0, //Chance + 1*20, //Duration + 16 //Eu Tick + ); + } + if (dustStack2 != null){ + GT_Values.RA.addFluidExtractionRecipe( + dustStack2, //Input + null, //Input 2 + FluidUtils.getFluidStack(gtFluid, amountPerItem), //Fluid Output + 0, //Chance + 1*20, //Duration + 16 //Eu Tick + ); + } + + return gtFluid; + } + Logger.INFO("FLUID GENERATION FAILED FOR "+localizedName); + return null; + } + + public final static Fluid generateFluidNoPrefix(final String unlocalizedName, final String localizedName, final int MeltingPoint, final short[] RGBA){ + Fluid gtFluid; + if (FluidUtils.getFluidStack(unlocalizedName.toLowerCase(), 1) == null){ + Logger.WARNING("Generating our own fluid."); + gtFluid = FluidUtils.addGTFluidNoPrefix( + unlocalizedName, + localizedName, + RGBA, + 4, + MeltingPoint, + ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1), + ItemList.Cell_Empty.get(1L, new Object[0]), + 1000); + } + else { + gtFluid = FluidUtils.getFluidStack(unlocalizedName.toLowerCase(), 1).getFluid(); + } + //Generate a Cell if we need to + if (ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+unlocalizedName, 1) == null){ + new BaseItemCell(unlocalizedName, localizedName, RGBA, gtFluid); + } + return gtFluid; + } + + + public static FluidStack getMobEssence(final int amount){ + return EnchantingUtils.getMobEssence(amount); + } + + public static FluidStack getLiquidXP(final int amount){ + return EnchantingUtils.getLiquidXP(amount); + } + + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/InventoryUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/InventoryUtils.java new file mode 100644 index 0000000000..0d4394d773 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/InventoryUtils.java @@ -0,0 +1,60 @@ +package gtPlusPlus.core.util.minecraft; + +import java.util.Random; + +import net.minecraft.block.Block; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +public class InventoryUtils { + + private final static Random mRandom = new Random(); + + public static void dropInventoryItems(World world, int x, int y, int z, Block block){ + Object tileentity = world.getTileEntity(x, y, z); + + if (tileentity != null) + { + for (int i1 = 0; i1 < ((IInventory) tileentity).getSizeInventory(); ++i1) + { + ItemStack itemstack = ((IInventory) tileentity).getStackInSlot(i1); + + if (itemstack != null) + { + float f = mRandom.nextFloat() * 0.8F + 0.1F; + float f1 = mRandom.nextFloat() * 0.8F + 0.1F; + EntityItem entityitem; + + for (float f2 = mRandom.nextFloat() * 0.8F + 0.1F; itemstack.stackSize > 0; world.spawnEntityInWorld(entityitem)) + { + int j1 = mRandom.nextInt(21) + 10; + + if (j1 > itemstack.stackSize) + { + j1 = itemstack.stackSize; + } + + itemstack.stackSize -= j1; + entityitem = new EntityItem(world, x + f, y + f1, z + f2, new ItemStack(itemstack.getItem(), j1, itemstack.getItemDamage())); + float f3 = 0.05F; + entityitem.motionX = (float)mRandom.nextGaussian() * f3; + entityitem.motionY = (float)mRandom.nextGaussian() * f3 + 0.2F; + entityitem.motionZ = (float)mRandom.nextGaussian() * f3; + + if (itemstack.hasTagCompound()) + { + entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy()); + } + } + } + } + + world.func_147453_f(x, y, z, block); + } + + } + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/ItemUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/ItemUtils.java new file mode 100644 index 0000000000..06176751eb --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/ItemUtils.java @@ -0,0 +1,717 @@ +package gtPlusPlus.core.util.minecraft; + +import java.util.ArrayList; +import java.util.List; + +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; +import gregtech.api.enums.Materials; +import gregtech.api.enums.OrePrefixes; +import gregtech.api.util.GT_ModHandler; +import gregtech.api.util.GT_OreDictUnificator; +import gtPlusPlus.api.objects.Logger; +import gtPlusPlus.api.objects.data.Pair; +import gtPlusPlus.core.item.ModItems; +import gtPlusPlus.core.item.base.BasicSpawnEgg; +import gtPlusPlus.core.item.base.dusts.BaseItemDust; +import gtPlusPlus.core.item.base.dusts.BaseItemDustUnique; +import gtPlusPlus.core.item.base.dusts.decimal.BaseItemCentidust; +import gtPlusPlus.core.item.base.dusts.decimal.BaseItemDecidust; +import gtPlusPlus.core.item.base.plates.BaseItemPlate_OLD; +import gtPlusPlus.core.item.tool.staballoy.MultiPickaxeBase; +import gtPlusPlus.core.item.tool.staballoy.MultiSpadeBase; +import gtPlusPlus.core.lib.CORE; +import gtPlusPlus.core.lib.LoadedMods; +import gtPlusPlus.core.material.Material; +import gtPlusPlus.core.util.Utils; +import gtPlusPlus.core.util.reflect.ReflectionUtils; +import gtPlusPlus.xmod.gregtech.loaders.RecipeGen_DustGeneration; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.Item.ToolMaterial; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.oredict.OreDictionary; + +public class ItemUtils { + + public static ItemStack getSimpleStack(final Item x){ + return getSimpleStack(x, 1); + } + public static ItemStack getSimpleStack(final Block x){ + return getSimpleStack(Item.getItemFromBlock(x), 1); + } + public static ItemStack getSimpleStack(final Block x, final int i){ + return getSimpleStack(Item.getItemFromBlock(x), i); + } + public static ItemStack getSimpleStack(final Item x, final int i){ + try { + final ItemStack r = new ItemStack(x, i); + return r.copy(); + } catch(final Throwable e){ + return null; + } + } + public static ItemStack getSimpleStack(final ItemStack x, final int i){ + try { + final ItemStack r = x.copy(); + r.stackSize = i; + return r; + } catch(final Throwable e){ + return null; + } + } + + public static final int WILDCARD_VALUE = Short.MAX_VALUE; + public static ItemStack getWildcardStack(final Item x){ + final ItemStack y = new ItemStack(x, 1, WILDCARD_VALUE); + return y; + } + + + public static ItemStack getIC2Cell(final String S){ + final ItemStack moreTemp = ItemUtils.getItemStackOfAmountFromOreDictNoBroken("cell"+S, 1); + + if (moreTemp == null){ + final int cellID = 0; + final ItemStack temp =GT_ModHandler.getModItem("IC2", "itemCellEmpty", 1L, cellID); + return temp != null ? temp : null; + } + + return moreTemp; + } + + public static ItemStack getIC2Cell(final int meta){ + final ItemStack temp = GT_ModHandler.getModItem("IC2", "itemCellEmpty", 1L, meta); + return temp != null ? temp : null; + } + + public static ItemStack getEmptyCell(){ + return getEmptyCell(1); + } + + public static ItemStack getEmptyCell(int i){ + final ItemStack temp = GT_ModHandler.getModItem("IC2", "itemCellEmpty", i, 0); + return temp != null ? temp : null; + } + + public static void getItemForOreDict(final String FQRN, final String oreDictName, final String itemName, final int meta){ + try { + Item em = null; + final Item em1 = getItem(FQRN); + //Utils.LOG_WARNING("Found: "+em1.getUnlocalizedName()+":"+meta); + if (em1 != null){ + em = em1; + } + if (em != null){ + + final ItemStack metaStack = new ItemStack(em,1,meta); + GT_OreDictUnificator.registerOre(oreDictName, metaStack); + + /*ItemStack itemStackWithMeta = new ItemStack(em,1,meta); + GT_OreDictUnificator.registerOre(oreDictName, new ItemStack(itemStackWithMeta.getItem()));*/ + } + } catch (final NullPointerException e) { + Logger.ERROR(itemName+" not found. [NULL]"); + } + } + + public static void addItemToOreDictionary(final ItemStack stack, final String oreDictName){ + try { + GT_OreDictUnificator.registerOre(oreDictName, stack); + } catch (final NullPointerException e) { + Logger.ERROR(stack.getDisplayName()+" not registered. [NULL]"); + } + } + + public static ItemStack getItemStackWithMeta(final boolean MOD, final String FQRN, final String itemName, final int meta, final int itemstackSize){ + if (MOD){ + try { + Item em = null; + final Item em1 = getItem(FQRN); + //Utils.LOG_WARNING("Found: "+em1.getUnlocalizedName()+":"+meta); + if (em1 != null){ + if (null == em){ + em = em1; + } + if (em != null){ + final ItemStack metaStack = new ItemStack(em,itemstackSize,meta); + return metaStack; + } + } + return null; + } catch (final NullPointerException e) { + Logger.ERROR(itemName+" not found. [NULL]"); + return null; + } + } + return null; + } + + public static ItemStack simpleMetaStack(final String FQRN, final int meta, final int itemstackSize){ + try { + Item em = null; + final Item em1 = getItem(FQRN); + //Utils.LOG_WARNING("Found: "+em1.getUnlocalizedName()+":"+meta); + if (em1 != null){ + if (null == em){ + em = em1; + } + if (em != null){ + final ItemStack metaStack = new ItemStack(em,itemstackSize,meta); + return metaStack; + } + } + return null; + } catch (final NullPointerException e) { + Logger.ERROR(FQRN+" not found. [NULL]"); + return null; + } + } + + @SuppressWarnings("unused") + public static ItemStack simpleMetaStack(final Item item, final int meta, final int size){ + try { + if (item == null){ + return null; + } + Item em = item; + final Item em1 = item; + Logger.WARNING("Found: "+em1.getUnlocalizedName()+":"+meta); + if (em1 != null){ + if (null == em){ + em = em1; + } + if (em != null){ + final ItemStack metaStack = new ItemStack(em,size,meta); + return metaStack; + } + } + return null; + } catch (final NullPointerException e) { + //Utils.LOG_ERROR(item.getUnlocalizedName()+" not found. [NULL]"); + return null; + } + } + + public static ItemStack simpleMetaStack(final Block block, final int meta, final int size) { + return simpleMetaStack(Item.getItemFromBlock(block), meta, size); + } + + public static ItemStack getCorrectStacktype(final String fqrn, final int stackSize){ + final String oreDict = "ore:"; + ItemStack temp; + if (fqrn.toLowerCase().contains(oreDict.toLowerCase())){ + final String sanitizedName = fqrn.replace(oreDict, ""); + temp = ItemUtils.getItemStack(sanitizedName, stackSize); + return temp; + } + final String[] fqrnSplit = fqrn.split(":"); + String temp1; + String temp2; + temp1 = fqrnSplit[1]; + if (fqrnSplit.length < 3){temp2 = "0";} + else {temp2 = fqrnSplit[2];} + temp = ItemUtils.getItemStackWithMeta(LoadedMods.MiscUtils, fqrn, temp1, Integer.parseInt(temp2), stackSize); + return temp; + } + + public static ItemStack getCorrectStacktype(final Object item_Input, final int stackSize) { + if (item_Input instanceof String){ + return getItemStackOfAmountFromOreDictNoBroken((String) item_Input, stackSize); + } + else if (item_Input instanceof ItemStack){ + return (ItemStack) item_Input; + } + return null; + } + + public static Item getItem(final String fqrn) // fqrn = fully qualified resource name + { + final String[] fqrnSplit = fqrn.split(":"); + return GameRegistry.findItem(fqrnSplit[0], fqrnSplit[1]); + } + + public static ItemStack getItemStack(final String fqrn, final int Size) // fqrn = fully qualified resource name + { + final String[] fqrnSplit = fqrn.split(":"); + return GameRegistry.findItemStack(fqrnSplit[0], fqrnSplit[1], Size); + } + + public static void generateSpawnEgg(final String entityModID, final String parSpawnName, final int colourEgg, final int colourOverlay){ + final Item itemSpawnEgg = new BasicSpawnEgg(entityModID, parSpawnName, colourEgg, colourOverlay).setUnlocalizedName("spawn_egg_"+parSpawnName.toLowerCase()).setTextureName(CORE.MODID+":spawn_egg"); + GameRegistry.registerItem(itemSpawnEgg, "spawnEgg"+parSpawnName); + } + + + public static ItemStack[] validItemsForOreDict(final String oredictName){ + final List validNames = MaterialUtils.oreDictValuesForEntry(oredictName); + final ItemStack[] inputs = new ItemStack[validNames.size()]; + for (int i=0; i oreDictList = OreDictionary.getOres(mTemp); + if (!oreDictList.isEmpty()){ + final ItemStack returnValue = oreDictList.get(0).copy(); + returnValue.stackSize = amount; + return returnValue; + } + return getSimpleStack(ModItems.AAA_Broken, amount); + } + + public static ItemStack getItemStackOfAmountFromOreDictNoBroken(final String oredictName, final int amount){ + if (CORE.DEBUG){ + Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(1)); + Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(2)); + Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(3)); + Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(4)); + Logger.WARNING("Looking up: "+oredictName+" - from method: "+ReflectionUtils.getMethodName(5)); + } + try{ + + //Adds a check to grab dusts using GT methodology if possible. + ItemStack returnValue = null; + if (oredictName.toLowerCase().contains("dust")){ + final String MaterialName = oredictName.toLowerCase().replace("dust", ""); + final Materials m = Materials.get(MaterialName); + returnValue = getGregtechDust(m, amount); + if (returnValue != null){ + return returnValue; + } + } + + if (returnValue == null){ + returnValue = getItemStackOfAmountFromOreDict(oredictName, amount); + if (returnValue != null){ + if ((returnValue.getItem().getClass() != ModItems.AAA_Broken.getClass()) || (returnValue.getItem() != ModItems.AAA_Broken)){ + return returnValue.copy(); + } + } + } + Logger.WARNING(oredictName+" was not valid."); + return null; + } + catch (final Throwable t){ + return null; + } + } + + public static ItemStack getGregtechDust(final Materials material, final int amount){ + final ItemStack returnValue = GT_OreDictUnificator.get(OrePrefixes.dust, material, 1L); + if (returnValue != null){ + if ((returnValue.getItem().getClass() != ModItems.AAA_Broken.getClass()) || (returnValue.getItem() != ModItems.AAA_Broken)){ + return returnValue.copy(); + } + } + Logger.WARNING(material+" was not valid."); + return null; + } + + public static Item[] generateDusts(final String unlocalizedName, final String materialName, final int materialTier, final Material matInfo, final int Colour){ + final int radioactive = getRadioactivityLevel(materialName); + final Item[] output = { + new BaseItemDust("itemDust"+unlocalizedName, materialName, matInfo, Colour, "Dust", materialTier, radioactive), + new BaseItemDust("itemDustSmall"+unlocalizedName, materialName, matInfo, Colour, "Small", materialTier, radioactive), + new BaseItemDust("itemDustTiny"+unlocalizedName, materialName, matInfo, Colour, "Tiny", materialTier, radioactive)}; + return output; + } + + //NullFormula + public static Item[] generateSpecialUseDusts(final String unlocalizedName, final String materialName, final int Colour){ + return generateSpecialUseDusts(unlocalizedName, materialName, "NullFormula", Colour); + } + + public static Item[] generateSpecialUseDusts(final String unlocalizedName, final String materialName, String mChemForm, final int Colour){ + final Item[] output = { + new BaseItemDustUnique("itemDust"+unlocalizedName, materialName, mChemForm, Colour, "Dust"), + new BaseItemDustUnique("itemDustSmall"+unlocalizedName, materialName, mChemForm, Colour, "Small"), + new BaseItemDustUnique("itemDustTiny"+unlocalizedName, materialName, mChemForm, Colour, "Tiny")}; + return output; + } + + public static Item generateSpecialUsePlate(final String internalName, final String displayName, final short[] rgb, final int radioactivity){ + return generateSpecialUsePlate(internalName, displayName, Utils.rgbtoHexValue(rgb[0], rgb[1], rgb[2]), radioactivity); + } + + public static Item generateSpecialUsePlate(final String internalName, final String displayName, final String mFormula, final short[] rgb, final int radioactivity){ + return generateSpecialUsePlate(internalName, displayName, mFormula, Utils.rgbtoHexValue(rgb[0], rgb[1], rgb[2]), radioactivity); + } + + public static Item generateSpecialUsePlate(final String internalName, final String displayName, final int rgb, final int radioactivity){ + return new BaseItemPlate_OLD(internalName, displayName, rgb, radioactivity); + } + + public static Item generateSpecialUsePlate(final String internalName, final String displayName, final String mFormula, final int rgb, final int radioactivity){ + return new BaseItemPlate_OLD(internalName, displayName, mFormula, rgb, radioactivity); + } + + public static Item[] generateSpecialUseDusts(final Material material, final boolean onlyLargeDust){ + final String materialName = material.getLocalizedName(); + final String unlocalizedName = Utils.sanitizeString(materialName); + final int Colour = material.getRgbAsHex(); + Item[] output = null; + if (onlyLargeDust == false){ + output = new Item[]{ + new BaseItemDustUnique("itemDust"+unlocalizedName, materialName, Colour, "Dust"), + new BaseItemDustUnique("itemDustSmall"+unlocalizedName, materialName, Colour, "Small"), + new BaseItemDustUnique("itemDustTiny"+unlocalizedName, materialName, Colour, "Tiny")}; + } else{ + output = new Item[]{ + new BaseItemDustUnique("itemDust"+unlocalizedName, materialName, Colour, "Dust") + }; + } + + RecipeGen_DustGeneration.generateRecipes(material); + + return output; + } + + public static MultiPickaxeBase generateMultiPick(final boolean GT_Durability, final Materials material){ + final ToolMaterial customMaterial = Utils.generateToolMaterialFromGT(material); + final int enchantLevel = material.mEnchantmentToolsLevel; + final Object enchant = new Pair(material.mEnchantmentTools, enchantLevel); + return generateMultiPick(GT_Durability, customMaterial, material.mDefaultLocalName, material.mDurability, material.mRGBa, enchant); + } + + public static MultiPickaxeBase generateMultiPick(final Material material){ + final ToolMaterial customMaterial = Utils.generateToolMaterial(material); + return generateMultiPick(true, customMaterial, material.getLocalizedName(), (int) material.vDurability, material.getRGBA(), null); + } + + public static MultiPickaxeBase generateMultiPick(final boolean GT_Durability, final ToolMaterial customMaterial, final String name, final int durability, final short[] rgba, final Object enchantment){ + Logger.WARNING("Generating a Multi-Pick out of "+name); + final short[] rgb = rgba; + int dur = customMaterial.getMaxUses(); + Logger.WARNING("Determined durability for "+name+" is "+dur); + if (GT_Durability){ + dur = durability*100; + Logger.WARNING("Using gregtech durability value, "+name+" is now "+dur+"."); + } + else if (dur <= 0){ + dur = durability; + Logger.WARNING("Determined durability too low, "+name+" is now "+dur+" based on the GT material durability."); + } + if (dur <= 0){ + Logger.WARNING("Still too low, "+name+" will now go unused."); + return null; + } + + Object enchant; + if (enchantment != null){ + if (enchantment instanceof Pair){ + enchant = enchantment; + } + } + else { + enchant = null; + } + + final MultiPickaxeBase MP_Redstone = new MultiPickaxeBase( + name+" Multipick", + (customMaterial), + dur, + Utils.rgbtoHexValue(rgb[0],rgb[1],rgb[2]), + enchantment); + + if (MP_Redstone.isValid){ + return MP_Redstone; + } + Logger.WARNING("Pickaxe was not valid."); + return null; + } + + + + + + + public static MultiSpadeBase generateMultiShovel(final boolean GT_Durability, final Materials material){ + final ToolMaterial customMaterial = Utils.generateToolMaterialFromGT(material); + return generateMultiShovel(GT_Durability, customMaterial, material.mDefaultLocalName, material.mDurability, material.mRGBa); + } + + public static MultiSpadeBase generateMultiShovel(final Material material){ + final ToolMaterial customMaterial = Utils.generateToolMaterial(material); + return generateMultiShovel(true, customMaterial, material.getLocalizedName(), (int) material.vDurability, material.getRGBA()); + } + + public static MultiSpadeBase generateMultiShovel(final boolean GT_Durability, final ToolMaterial customMaterial, final String name, final int durability, final short[] rgba){ + Logger.WARNING("Generating a Multi-Spade out of "+name); + final short[] rgb = rgba; + int dur = customMaterial.getMaxUses(); + Logger.WARNING("Determined durability for "+name+" is "+dur); + if (GT_Durability){ + dur = durability*100; + Logger.WARNING("Using gregtech durability value, "+name+" is now "+dur+"."); + } + else if (dur <= 0){ + dur = durability; + Logger.WARNING("Determined durability too low, "+name+" is now "+dur+" based on the GT material durability."); + } + if (dur <= 0){ + Logger.WARNING("Still too low, "+name+" will now go unused."); + return null; + } + final MultiSpadeBase MP_Redstone = new MultiSpadeBase( + name+" Multispade", + (customMaterial), + dur, + Utils.rgbtoHexValue(rgb[0],rgb[1],rgb[2]) + ); + + if (MP_Redstone.isValid){ + return MP_Redstone; + } + return null; + } + + + + + + + + + + + + + public static BaseItemDecidust generateDecidust(final Materials material){ + if (GT_OreDictUnificator.get(OrePrefixes.dust, material, 1L) != null){ + final Material placeholder = MaterialUtils.generateMaterialFromGtENUM(material); + if (placeholder != null) { + generateDecidust(placeholder); + } + } + return null; + } + + public static BaseItemDecidust generateDecidust(final Material material){ + if ((material.getDust(1) != null) && MaterialUtils.hasValidRGBA(material.getRGBA())){ + final BaseItemDecidust Decidust = new BaseItemDecidust(material); + return Decidust; + } + return null; + } + + public static BaseItemCentidust generateCentidust(final Materials material){ + if (GT_OreDictUnificator.get(OrePrefixes.dust, material, 1L) != null){ + final Material placeholder = MaterialUtils.generateMaterialFromGtENUM(material); + if (placeholder != null) { + generateCentidust(placeholder); + } + } + return null; + } + + public static BaseItemCentidust generateCentidust(final Material material){ + if ((material.getDust(1) != null) && MaterialUtils.hasValidRGBA(material.getRGBA())){ + final BaseItemCentidust Centidust = new BaseItemCentidust(material); + return Centidust; + } + return null; + } + + public static boolean isRadioactive(final String materialName){ + int sRadiation = 0; + if (materialName.toLowerCase().contains("uranium")){ + sRadiation = 2; + } + else if (materialName.toLowerCase().contains("plutonium")){ + sRadiation = 4; + } + else if (materialName.toLowerCase().contains("thorium")){ + sRadiation = 1; + } + if (sRadiation >= 1){ + return true; + } + return false; + } + + public static int getRadioactivityLevel(final String materialName){ + int sRadiation = 0; + if (materialName.toLowerCase().contains("uranium")){ + sRadiation = 2; + } + else if (materialName.toLowerCase().contains("plutonium")){ + sRadiation = 4; + } + else if (materialName.toLowerCase().contains("thorium")){ + sRadiation = 1; + } + return sRadiation; + } + + public static String getArrayStackNames(final ItemStack[] aStack){ + String itemNames = "Item Array: "; + for (final ItemStack alph : aStack){ + + if (alph != null){ + final String temp = itemNames; + itemNames = temp + ", " + alph.getDisplayName() + " x" + alph.stackSize; + } + else { + final String temp = itemNames; + itemNames = temp + ", " + "null" + " x" + "0"; + } + } + return itemNames; + + } + + public static String[] getArrayStackNamesAsArray(final ItemStack[] aStack){ + final String[] itemNames = {}; + int arpos = 0; + for (final ItemStack alph : aStack){ + itemNames[arpos] = alph.getDisplayName(); + arpos++; + } + return itemNames; + + } + + public static String getFluidArrayStackNames(final FluidStack[] aStack){ + String itemNames = "Fluid Array: "; + for (final FluidStack alph : aStack){ + final String temp = itemNames; + itemNames = temp + ", " + alph.getFluid().getName() + " x" + alph.amount; + } + return itemNames; + + } + + public static ItemStack getGregtechCircuit(final int Meta){ + return ItemUtils.getItemStackWithMeta(LoadedMods.Gregtech, "gregtech:gt.integrated_circuit", "Gregtech Circuit", Meta, 0); + } + public static ItemStack[] getBlockDrops(final ArrayList blockDrops) { + if (blockDrops == null){ + return null; + } + if (blockDrops.isEmpty()){ + return null; + } + final ItemStack[] outputs = new ItemStack[blockDrops.size()]; + short forCounter = 0; + for (final ItemStack I : blockDrops){ + outputs[forCounter++] = I; + } + return outputs; + } + + private static String getModId(final Item item) { + try { + final GameRegistry.UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor(item); + final String modname = (id.modId == null ? id.name : id.modId); + return (id == null) || id.modId.equals("") ? "minecraft" : modname; + } catch (final Throwable t){ + try { + final UniqueIdentifier t2 = GameRegistry.findUniqueIdentifierFor(Block.getBlockFromItem(item)); + final String modname = (t2.modId == null ? t2.name : t2.modId); + return (t2 == null) || t2.modId.equals("") ? "minecraft" : modname; + } + catch (final Throwable t3){ + return "bad modid"; + } + } + } + + public static String getModId(final ItemStack key) { + return getModId(key.getItem()); + } + + //Take 2 - GT/GT++ Dusts + public static ItemStack getGregtechDust(final String oredictName, final int amount){ + final ArrayList oreDictList = OreDictionary.getOres(oredictName); + if (!oreDictList.isEmpty()){ + ItemStack returnvalue; + for (int xrc=0;xrc oreDictList = OreDictionary.getOres(oredictName); + if (!oreDictList.isEmpty()){ + ItemStack returnvalue; + for (int xrc=0;xrc oreDictList = OreDictionary.getOres(oredictname); + if (!oreDictList.isEmpty()){ + final ItemStack[] returnValues = new ItemStack[oreDictList.size()]; + for (int i=0;i0 ? returnValues : null; + } + else { + return null; + } + } + + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/MaterialUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/MaterialUtils.java new file mode 100644 index 0000000000..0af72661e9 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/MaterialUtils.java @@ -0,0 +1,205 @@ +package gtPlusPlus.core.util.minecraft; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.reflect.FieldUtils; + +import gregtech.api.enums.*; +import gtPlusPlus.api.objects.Logger; +import gtPlusPlus.core.material.Material; +import gtPlusPlus.core.material.state.MaterialState; +import gtPlusPlus.core.util.Utils; +import gtPlusPlus.core.util.data.EnumUtils; +import gtPlusPlus.core.util.data.StringUtils; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; + +public class MaterialUtils { + + public static short firstID = 791; + + @SuppressWarnings({ "rawtypes", "unused" }) + private static Class[][] commonTypes = +{{Materials.class, int.class, TextureSet.class, float.class, int.class, + int.class, int.class, int.class, int.class, int.class, int.class, + String.class, int.class, int.class, int.class, int.class, boolean.class, + boolean.class, int.class, int.class, int.class, Dyes.class, int.class, + List.class , List.class}}; + + public static List oreDictValuesForEntry(final String oredictName){ + List oredictItemNames; + if(OreDictionary.doesOreNameExist(oredictName)){ + final List oredictItems = OreDictionary.getOres(oredictName); + oredictItemNames = oredictItems; + return oredictItemNames; + } + return null; + } + + public static Material generateMaterialFromGtENUM(final Materials material){ + @SuppressWarnings("deprecation") + String name = material.name(); + final short[] rgba = material.mRGBa; + final int melting = material.mMeltingPoint; + final int boiling = material.mBlastFurnaceTemp; + final long protons = material.getProtons(); + final long neutrons = material.getNeutrons(); + final boolean blastFurnace = material.mBlastFurnaceRequired; + final TextureSet iconSet = material.mIconSet; + final int durability = material.mDurability; + boolean mGenerateCell = false; + MaterialState materialState; + String chemicalFormula = StringUtils.subscript(Utils.sanitizeString(material.mChemicalFormula)); + final Element element = material.mElement; + int radioactivity = 0; + if (material.isRadioactive()){ + radioactivity = 1; + } + + //Weird Blacklist of Bad Chemical Strings + if (material.mElement == Element.Pb || material.mElement == Element.Na || material.mElement == Element.Ar){ + chemicalFormula = StringUtils.subscript(Utils.sanitizeString(material.mElement.name())); + } + + //Determine default state + Logger.MATERIALS("[Debug] Setting State of GT generated material. "+material.mDefaultLocalName); + if (material.getMolten(1) != null || material.getSolid(1) != null){ + materialState = MaterialState.SOLID; + Logger.MATERIALS("[Debug] Molten or Solid was not null."); + if (material.getMolten(1) == null && material.getSolid(1) != null){ + Logger.MATERIALS("[Debug] Molten is Null, Solid is not. Enabling cell generation."); + mGenerateCell = true; + } + else if (material.getMolten(1) != null && material.getSolid(1) == null){ + Logger.MATERIALS("[Debug] Molten is not Null, Solid is null. Not enabling cell generation."); + //mGenerateCell = true; + } + Logger.MATERIALS("[Debug] State set as solid."); + } + else if (material.getFluid(1) != null){ + Logger.MATERIALS("[Debug] State set as liquid."); + materialState = MaterialState.LIQUID; + } + else if (material.getGas(1) != null){ + Logger.MATERIALS("[Debug] State set as gas."); + materialState = MaterialState.GAS; + }/* + else if (material.getPlasma(1) != null){ + Logger.MATERIALS("[Debug] State set as plasma."); + materialState = MaterialState.PLASMA; + }*/ + else { + Logger.MATERIALS("[Debug] State set as solid."); + materialState = MaterialState.SOLID; + } + + + if (name.toLowerCase().contains("infused")){ + final String tempname = name.substring(7, name.length()); + name = "Infused " + tempname; + } + if (hasValidRGBA(rgba) || (element == Element.H) || ((material == Materials.InfusedAir) || (material == Materials.InfusedFire) || (material == Materials.InfusedEarth) || (material == Materials.InfusedWater))){ + //ModItems.itemBaseDecidust = UtilsItems.generateDecidust(material); + //ModItems.itemBaseCentidust = UtilsItems.generateCentidust(material); + return new Material(name, materialState,iconSet, durability, rgba, melting, boiling, protons, neutrons, blastFurnace, chemicalFormula, radioactivity, mGenerateCell); + } + else { + Logger.DEBUG_MATERIALS("Failed to generate GT++ material instance for "+material.name() +" | Valid RGB? "+(hasValidRGBA(rgba))); + } + return null; + + } + + public static Material generateQuickMaterial(final String materialName, final MaterialState defaultState, final short[] colour, final int sRadioactivity) { + final Material temp = new Material( + materialName, + defaultState, + 0, //Durability + colour, + 1000, //melting + 3000, //boiling + 50, //Protons + 50, //Neutrons + false, + "", + sRadioactivity); + return temp; + } + + public static boolean hasValidRGBA(final short[] rgba){ + if (rgba == null || rgba.length < 3 || rgba.length > 4){ + return false; + } + return true; + } + + public static int getTierOfMaterial(final int M){ + if ((M >= 0) && (M <= 1000)){ + return 1; + } + else if((M >= 1001) && (M <= 2000)){ + return 2; + } + else if((M >= 2001) && (M <= 3000)){ + return 3; + } + else if((M >= 3001) && (M <= 4000)){ + return 4; + } + else if((M >= 4001) && (M <= 5000)){ + return 5; + } + else if((M >= 5001) && (M <= 6000)){ + return 6; + } + else if((M >= 6001) && (M <= 7000)){ + return 7; + } + else if((M >= 7001) && (M <= 8000)){ + return 8; + } + else if((M >= 8001) && (M <= 9000)){ + return 9; + } + else if((M >= 9001) && (M <= 9999)){ + return 10; + } + else { + return 0; + } + } + + static Class materialsEnum = Materials.class; + public static Materials getMaterialByName(String materialName) { + return EnumUtils.getValue(materialsEnum, materialName); + } + + @SuppressWarnings("deprecation") + public static String getMaterialName(Materials mat){ + String mName; + try { + mName = (String) FieldUtils.getDeclaredField(Materials.class, "mName", true).get(mat); + } + catch (IllegalArgumentException | IllegalAccessException e) { + mName = mat.name(); + } + if (mName == null || mName.equals("") || mName == ""){ + mName = mat.name(); + } + return mName; + } + + public static TextureSet getMostCommonTextureSet(List list) { + Optional r = list.stream().map(Material::getTextureSet).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey); + TextureSet o = (r != null && r.isPresent() && r.get() != null) ? r.get() : null; + return o; + } + + + } + + diff --git a/src/Java/gtPlusPlus/core/util/minecraft/ModularArmourUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/ModularArmourUtils.java new file mode 100644 index 0000000000..2ce6bafae0 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/ModularArmourUtils.java @@ -0,0 +1,159 @@ +package gtPlusPlus.core.util.minecraft; + +import baubles.api.BaubleType; +import gregtech.api.util.GT_Utility; +import gtPlusPlus.api.objects.Logger; +import gtPlusPlus.api.objects.data.Pair; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public class ModularArmourUtils { + + public static ItemStack addComponent(ItemStack tArmour, ItemStack[] tComponents) { + if (tArmour != null) { + ItemStack rArmour = NBTUtils.writeItemsToGtCraftingComponents(tArmour, tComponents, true); + if (rArmour != null) { + + } + } + return null; + } + + public static enum Modifiers { + BOOST_HP("skill.hpboost"), BOOST_DEF("skill.defenceboost"), BOOST_SPEED("skill.speedboost"), BOOST_MINING( + "skill.miningboost"), BOOST_DAMAGE("skill.damageboost"), BOOST_HOLY("skill.holyboost"); + private String MODIFIER_NAME; + + private Modifiers(final String mModifier) { + this.MODIFIER_NAME = mModifier; + } + + public String getModifier() { + return this.MODIFIER_NAME; + } + + public boolean isValidLevel(int i) { + if (i >= 0 && i <= 100) { + return true; + } + return false; + } + } + + public static enum BT { + TYPE_AMULET(BaubleType.AMULET, 0), TYPE_RING(BaubleType.RING, 1), TYPE_BELT(BaubleType.BELT, 2); + private final BaubleType mType; + private final int mID; + private final String mBaubleType; + + private BT(final BaubleType tType, int tID) { + this.mType = tType; + this.mID = tID; + this.mBaubleType = tType.name().toLowerCase(); + } + + public BaubleType getType() { + return this.mType; + } + + public BT getThis() { + return this; + } + + public BaubleType getBaubleByID(int tID) { + if (tID == 0) { + return BaubleType.AMULET; + } else if (tID == 1) { + return BaubleType.RING; + } else if (tID == 2) { + return BaubleType.BELT; + } else { + return BaubleType.RING; + } + } + + public int getID() { + return this.mID; + } + + public String getTypeAsString() { + return this.mBaubleType; + } + } + + public static void setModifierLevel(ItemStack aStack, Pair mPair) { + setModifierLevel(aStack, mPair.getKey(), mPair.getValue().intValue()); + } + + public static void setModifierLevel(ItemStack aStack, Modifiers aMod, Integer aInt) { + setModifierLevel(aStack, aMod, aInt.intValue()); + } + + public static void setModifierLevel(ItemStack aStack, Modifiers aMod, int aInt) { + + int mCurrentLevel = getModifierLevel(aStack, aMod); + int mNewTotalLevel = mCurrentLevel + aInt; + + NBTTagCompound tNBT = NBTUtils.getNBT(aStack); + if (aMod.isValidLevel(mNewTotalLevel)) { + tNBT.setInteger(aMod.getModifier(), mNewTotalLevel); + GT_Utility.ItemNBT.setNBT(aStack, tNBT); + } else { + if (getModifierLevel(aStack, aMod) > 100) { + setModifierLevel(aStack, aMod, 100); + } + } + } + + public static int getModifierLevel(ItemStack aStack, Pair newPair) { + return getModifierLevel(aStack, newPair.getKey()); + } + + public static int getModifierLevel(ItemStack aStack, Modifiers aMod) { + NBTTagCompound tNBT = NBTUtils.getNBT(aStack); + return tNBT.getInteger(aMod.getModifier()); + } + + public static void setBaubleType(ItemStack aStack, BT aMod) { + Logger.INFO("Changing bauble type."); + NBTTagCompound tNBT = NBTUtils.getNBT(aStack); + if (aMod != null) { + tNBT.setInteger("mBaubleType", aMod.getID()); + GT_Utility.ItemNBT.setNBT(aStack, tNBT); + } + } + + public static int getBaubleTypeID(ItemStack aStack) { + NBTTagCompound tNBT = NBTUtils.getNBT(aStack); + return tNBT.getInteger("mBaubleType"); + } + + public static BaubleType getBaubleType(ItemStack aStack) { + NBTTagCompound tNBT = NBTUtils.getNBT(aStack); + return getBaubleByID(tNBT.getInteger("mBaubleType")); + } + + public static BaubleType getBaubleByID(int tID) { + if (tID == 0) { + return BaubleType.AMULET; + } else if (tID == 1) { + return BaubleType.RING; + } else if (tID == 2) { + return BaubleType.BELT; + } else { + return BaubleType.RING; + } + } + + public static ItemStack setDefaultStats(ItemStack aStack) { + ItemStack tempStack = aStack; + setModifierLevel(tempStack, Modifiers.BOOST_DAMAGE, 0); + setModifierLevel(tempStack, Modifiers.BOOST_DEF, 0); + setModifierLevel(tempStack, Modifiers.BOOST_HOLY, 0); + setModifierLevel(tempStack, Modifiers.BOOST_HP, 0); + setModifierLevel(tempStack, Modifiers.BOOST_MINING, 0); + setModifierLevel(tempStack, Modifiers.BOOST_SPEED, 0); + return tempStack; + } + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/NBTUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/NBTUtils.java new file mode 100644 index 0000000000..b79fadf3a1 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/NBTUtils.java @@ -0,0 +1,453 @@ +package gtPlusPlus.core.util.minecraft; + +import static gtPlusPlus.core.item.ModItems.ZZZ_Empty; + +import java.util.Map; + +import gregtech.api.items.GT_MetaGenerated_Tool; +import gregtech.api.util.GT_ModHandler; +import gregtech.api.util.GT_Utility; +import gtPlusPlus.api.objects.Logger; +import gtPlusPlus.core.util.reflect.ReflectionUtils; +import net.minecraft.entity.Entity; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +public class NBTUtils { + + public static NBTTagCompound getNBT(ItemStack aStack) { + NBTTagCompound rNBT = aStack.getTagCompound(); + return ((rNBT == null) ? new NBTTagCompound() : rNBT); + } + + public static void setBookTitle(ItemStack aStack, String aTitle) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setString("title", aTitle); + GT_Utility.ItemNBT.setNBT(aStack, tNBT); + } + + public static String getBookTitle(ItemStack aStack) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getString("title"); + } + + public static ItemStack[] readItemsFromNBT(ItemStack itemstack) { + NBTTagCompound tNBT = getNBT(itemstack); + final NBTTagList list = tNBT.getTagList("Items", 10); + ItemStack inventory[] = new ItemStack[list.tagCount()]; + for (int i = 0; i < list.tagCount(); i++) { + final NBTTagCompound data = list.getCompoundTagAt(i); + final int slot = data.getInteger("Slot"); + if ((slot >= 0) && (slot < list.tagCount())) { + if (ItemStack.loadItemStackFromNBT(data) == ItemUtils.getSimpleStack(ZZZ_Empty)) { + inventory[slot] = null; + } else { + inventory[slot] = ItemStack.loadItemStackFromNBT(data); + } + + } + } + return inventory; + } + + public static ItemStack[] readItemsFromNBT(ItemStack itemstack, String customkey) { + NBTTagCompound tNBT = getNBT(itemstack); + final NBTTagList list = tNBT.getTagList(customkey, 10); + ItemStack inventory[] = new ItemStack[list.tagCount()]; + for (int i = 0; i < list.tagCount(); i++) { + final NBTTagCompound data = list.getCompoundTagAt(i); + final int slot = data.getInteger("Slot"); + if ((slot >= 0) && (slot < list.tagCount())) { + if (ItemStack.loadItemStackFromNBT(data) == ItemUtils.getSimpleStack(ZZZ_Empty)) { + inventory[slot] = null; + } else { + inventory[slot] = ItemStack.loadItemStackFromNBT(data); + } + + } + } + return inventory; + } + + public static ItemStack writeItemsToNBT(ItemStack itemstack, ItemStack[] stored) { + NBTTagCompound tNBT = getNBT(itemstack); + final NBTTagList list = new NBTTagList(); + for (int i = 0; i < stored.length; i++) { + final ItemStack stack = stored[i]; + if (stack != null) { + final NBTTagCompound data = new NBTTagCompound(); + stack.writeToNBT(data); + data.setInteger("Slot", i); + list.appendTag(data); + } else { + final NBTTagCompound data = new NBTTagCompound(); + ItemStack nullstack = ItemUtils.getSimpleStack(ZZZ_Empty); + nullstack.writeToNBT(data); + data.setInteger("Slot", i); + list.appendTag(data); + } + } + tNBT.setTag("Items", list); + itemstack.setTagCompound(tNBT); + return itemstack; + } + + public static ItemStack writeItemsToNBT(ItemStack itemstack, ItemStack[] stored, String customkey) { + NBTTagCompound tNBT = getNBT(itemstack); + final NBTTagList list = new NBTTagList(); + for (int i = 0; i < stored.length; i++) { + final ItemStack stack = stored[i]; + if (stack != null) { + final NBTTagCompound data = new NBTTagCompound(); + stack.writeToNBT(data); + data.setInteger("Slot", i); + list.appendTag(data); + } + } + tNBT.setTag(customkey, list); + itemstack.setTagCompound(tNBT); + return itemstack; + } + + public static ItemStack writeItemsToGtCraftingComponents(ItemStack rStack, ItemStack[] stored, boolean copyTags) { + + if (copyTags) { + for (int i = 0; i < stored.length; i++) { + if (stored[i] != null && stored[i].hasTagCompound()) { + rStack.setTagCompound((NBTTagCompound) stored[i].getTagCompound().copy()); + break; + } + } + } + + NBTTagCompound rNBT = rStack.getTagCompound(), tNBT = new NBTTagCompound(); + if (rNBT == null) + rNBT = new NBTTagCompound(); + for (int i = 0; i < 9; i++) { + ItemStack tStack = stored[i]; + if (tStack != null && GT_Utility.getContainerItem(tStack, true) == null + && !(tStack.getItem() instanceof GT_MetaGenerated_Tool)) { + tStack = GT_Utility.copyAmount(1, tStack); + if (GT_Utility.isStackValid(tStack)) { + GT_ModHandler.dischargeElectricItem(tStack, Integer.MAX_VALUE, Integer.MAX_VALUE, true, false, + true); + tNBT.setTag("Ingredient." + i, tStack.writeToNBT(new NBTTagCompound())); + } + } + } + rNBT.setTag("GT.CraftingComponents", tNBT); + rStack.setTagCompound(rNBT); + return rStack; + } + + public static void setBoolean(ItemStack aStack, String aTag, boolean aBoolean) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setBoolean(aTag, aBoolean); + GT_Utility.ItemNBT.setNBT(aStack, tNBT); + } + + public static boolean getBoolean(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getBoolean(aTag); + } + + public static void setInteger(ItemStack aStack, String aTag, int aInt) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setInteger(aTag, aInt); + GT_Utility.ItemNBT.setNBT(aStack, tNBT); + } + + public static int getInteger(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getInteger(aTag); + } + + public static void setLong(ItemStack aStack, String aTag, long aInt) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setLong(aTag, aInt); + GT_Utility.ItemNBT.setNBT(aStack, tNBT); + } + + public static long getLong(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getLong(aTag); + } + + public static void setFloat(ItemStack aStack, String aTag, float aInt) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setFloat(aTag, aInt); + GT_Utility.ItemNBT.setNBT(aStack, tNBT); + } + + public static float getFloat(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getFloat(aTag); + } + + public static void setString(ItemStack aStack, String aTag, String aString) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setString(aTag, aString); + GT_Utility.ItemNBT.setNBT(aStack, tNBT); + } + + public static String getString(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getString(aTag); + } + + public static boolean doesStringExist(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.hasKey(aTag); + } + + public static boolean tryIterateNBTData(ItemStack aStack) { + try { + NBTTagCompound aNBT = NBTUtils.getNBT(aStack); + if (aNBT != null) { + if (!aNBT.hasNoTags()) { + Map mInternalMap = ReflectionUtils.getField(aNBT, "tagMap"); + if (mInternalMap != null) { + for (Map.Entry e : mInternalMap.entrySet()) { + Logger.INFO("Key: " + e.getKey().toString() + " | Value: " + e.getValue()); + } + return true; + } else { + Logger.INFO("Data map reflected from NBTTagCompound was not valid."); + return false; + } + } + } + } catch (Throwable t) {} + return false; + } + + // Botania soulbind handling + public static boolean setBotanicaSoulboundOwner(ItemStack aStack, String aName) { + final String TAG_SOULBIND = "soulbind"; + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setString(TAG_SOULBIND, aName); + GT_Utility.ItemNBT.setNBT(aStack, tNBT); + if (NBTUtils.doesStringExist(aStack, TAG_SOULBIND)) { + return true; + } else { + return false; + } + } + + public static String getBotanicaSoulboundOwner(ItemStack aStack) { + final String TAG_SOULBIND = "soulbind"; + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getString(TAG_SOULBIND); + } + + public static boolean hasKey(ItemStack stack, String key) { + final NBTTagCompound itemData = getNBT(stack); + if (itemData.hasKey(key)) { + return true; + } + return false; + } + + public static boolean createIntegerTagCompound(ItemStack rStack, String tagName, String keyName, int keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setInteger(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createLongTagCompound(ItemStack rStack, String tagName, String keyName, long keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setLong(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createStringTagCompound(ItemStack rStack, String tagName, String keyName, String keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setString(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createFloatTagCompound(ItemStack rStack, String tagName, String keyName, float keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setFloat(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createDoubleTagCompound(ItemStack rStack, String tagName, String keyName, double keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setDouble(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createBooleanTagCompound(ItemStack rStack, String tagName, String keyName, boolean keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setBoolean(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createTagCompound(ItemStack rStack, String tagName, NBTTagCompound keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + NBTTagCompound tagNBT = keyValue; + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static int getIntegerTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getInteger(keyName); + } + } + return 0; + } + + public static long getLongTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getLong(keyName); + } + } + return 0L; + } + + public static String getStringTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getString(keyName); + } + } + return null; + } + + public static float getFloatTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getFloat(keyName); + } + } + return 0; + } + + public static double getDoubleTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getDouble(keyName); + } + } + return 0; + } + + public static boolean getBooleanTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getBoolean(keyName); + } + } + return false; + } + + public static NBTTagCompound getTagCompound(ItemStack aStack, String tagName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null && hasKey(aStack, tagName)) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT; + } + } + return null; + } + + public static boolean hasKeyInTagCompound(ItemStack stack, String tag, String key) { + NBTTagCompound aNBT = stack.getTagCompound(); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tag); + if (aNBT.hasKey(key)) { + return true; + } + } + return false; + } + + public static boolean tryCloneTagCompoundDataIntoSubTag(ItemStack aStack, NBTTagCompound aTagCompound) { + try { + NBTTagCompound aNBT = aTagCompound; + if (aNBT != null) { + if (!aNBT.hasNoTags()) { + Map mInternalMap = ReflectionUtils.getField(aNBT, "tagMap"); + if (mInternalMap != null) { + for (Map.Entry e : mInternalMap.entrySet()) { + Logger.INFO("Key: " + e.getKey().toString() + " | Value: " + e.getValue().toString()); + if (e.getValue().getClass() == String.class){ + createStringTagCompound(aStack, "mEntityTag", (String) e.getKey(), (String) e.getValue()); + } + else if (e.getValue().getClass() == Boolean.class || e.getValue().getClass() == boolean.class){ + createBooleanTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Boolean) e.getValue()); + } + else if (e.getValue().getClass() == Integer.class || e.getValue().getClass() == int.class){ + createIntegerTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Integer) e.getValue()); + } + else if (e.getValue().getClass() == Double.class || e.getValue().getClass() == double.class){ + createDoubleTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Double) e.getValue()); + } + else if (e.getValue().getClass() == Long.class || e.getValue().getClass() == long.class){ + createLongTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Long) e.getValue()); + } + else if (e.getValue().getClass() == Float.class || e.getValue().getClass() == float.class){ + createFloatTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Float) e.getValue()); + } + else { + + + } + + } + return true; + } + } + } + return false; + } catch (Throwable t) { + return false; + } + } + + public static NBTTagCompound getEntityCustomData(Entity aEntity){ + return ReflectionUtils.getField(aEntity, "customEntityData"); + } + + public static boolean setEntityCustomData(Entity aEntity, NBTTagCompound aTag){ + return ReflectionUtils.setField(aEntity, "customEntityData", aTag); + } + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/PlayerUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/PlayerUtils.java new file mode 100644 index 0000000000..dd0acba4cc --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/PlayerUtils.java @@ -0,0 +1,175 @@ +package gtPlusPlus.core.util.minecraft; + +import java.util.*; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import gtPlusPlus.core.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.World; + +public class PlayerUtils { + + public static void messagePlayer(final EntityPlayer P, final String S){ + gregtech.api.util.GT_Utility.sendChatToPlayer(P, S); + } + + public static EntityPlayer getPlayer(final String name){ + try{ + final List i = new ArrayList<>(); + final Iterator iterator = MinecraftServer.getServer().getConfigurationManager().playerEntityList.iterator(); + while (iterator.hasNext()) { + i.add((iterator.next())); + } + for (final EntityPlayer temp : i) { + if (temp.getDisplayName().toLowerCase().equals(name.toLowerCase())){ + return temp; + } + } + } + catch(final Throwable e){} + return null; + } + + public static EntityPlayer getPlayerOnServerFromUUID(final UUID parUUID){ + if (parUUID == null) + { + return null; + } + final List allPlayers = MinecraftServer.getServer().getConfigurationManager().playerEntityList; + for (final EntityPlayerMP player : allPlayers) + { + if (player.getUniqueID().equals(parUUID)) + { + return player; + } + } + return null; + } + + //Not Clientside + public static EntityPlayer getPlayerInWorld(final World world, final String Name){ + final List i = world.playerEntities; + final Minecraft mc = Minecraft.getMinecraft(); + try{ + for (final EntityPlayer temp : i) { + if (temp.getDisplayName().toLowerCase().equals(Name.toLowerCase())){ + return temp; + } + } + } + catch(final NullPointerException e){} + return null; + } + + public static boolean isPlayerOP(final EntityPlayer player){ + if (player.canCommandSenderUseCommand(2, "")){ + return true; + } + return false; + } + + //Not Clientside + public static ItemStack getItemStackInPlayersHand(final World world, final String Name){ + final EntityPlayer thePlayer = getPlayer(Name); + ItemStack heldItem = null; + try{heldItem = thePlayer.getHeldItem(); + }catch(final NullPointerException e){return null;} + if (heldItem != null){ + return heldItem; + } + return null; + } + + @SideOnly(Side.CLIENT) + public static ItemStack getItemStackInPlayersHand(){ + final Minecraft mc = Minecraft.getMinecraft(); + ItemStack heldItem = null; + try{heldItem = mc.thePlayer.getHeldItem(); + }catch(final NullPointerException e){return null;} + if (heldItem != null){ + return heldItem; + } + return null; + } + + @SideOnly(Side.SERVER) + public static ItemStack getItemStackInPlayersHand(final EntityPlayer player){ + ItemStack heldItem = null; + try{heldItem = player.getHeldItem(); + }catch(final NullPointerException e){ + e.printStackTrace(); + return null; + } + if (heldItem != null){ + return heldItem; + } + return null; + } + + @SideOnly(Side.CLIENT) + public static Item getItemInPlayersHandClient(){ + final Minecraft mc = Minecraft.getMinecraft(); + Item heldItem = null; + + try{heldItem = mc.thePlayer.getHeldItem().getItem(); + }catch(final NullPointerException e){return null;} + + if (heldItem != null){ + return heldItem; + } + + return null; + } + + public static Item getItemInPlayersHand(final EntityPlayer player){ + Item heldItem = null; + try{ + heldItem = player.getHeldItem().getItem(); + }catch(final NullPointerException e){return null;} + + if (heldItem != null){ + return heldItem; + } + return null; + } + + public final static EntityPlayer getPlayerEntityByName(final String aPlayerName){ + final EntityPlayer player = PlayerUtils.getPlayer(aPlayerName); + if (player != null){ + return player; + } + return null; + } + + public final static UUID getPlayersUUIDByName(final String aPlayerName){ + final EntityPlayer player = PlayerUtils.getPlayer(aPlayerName); + if (player != null){ + return player.getUniqueID(); + } + return null; + } + + @SideOnly(Side.CLIENT) + public static final boolean isPlayerAlkalus(){ + if (Utils.isServer()){ + return false; + } + return isPlayerAlkalus(Minecraft.getMinecraft().thePlayer); + } + + public static final boolean isPlayerAlkalus(EntityPlayer player){ + if (player != null){ + if (player.getDisplayName().toLowerCase().equals("draknyte1") || player.getDisplayName().toLowerCase().equals("alkalus")){ + return true; + } + } + return false; + } + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/RecipeUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/RecipeUtils.java new file mode 100644 index 0000000000..f10279dbd7 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/RecipeUtils.java @@ -0,0 +1,479 @@ +package gtPlusPlus.core.util.minecraft; + +import java.util.*; + +import cpw.mods.fml.common.registry.GameRegistry; +import gregtech.api.util.GT_ModHandler; +import gtPlusPlus.api.objects.Logger; +import gtPlusPlus.core.handler.COMPAT_HANDLER; +import gtPlusPlus.core.handler.Recipes.LateRegistrationHandler; +import gtPlusPlus.core.handler.Recipes.RegistrationHandler; +import gtPlusPlus.core.lib.CORE; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.minecraftforge.oredict.*; + +public class RecipeUtils { + + public static boolean recipeBuilder(final Object slot_1, final Object slot_2, final Object slot_3, final Object slot_4, final Object slot_5, final Object slot_6, final Object slot_7, final Object slot_8, final Object slot_9, final ItemStack resultItem){ + + final ArrayList validSlots = new ArrayList<>(); + if (resultItem == null){ + Logger.WARNING("Found a recipe with an invalid output, yet had a valid inputs. Skipping."); + return false; + } + + if ((slot_1 == null) && (slot_2 == null) && (slot_3 == null) && + (slot_4 == null) && (slot_5 == null) && (slot_6 == null) && + (slot_7 == null) && (slot_8 == null) && (slot_9 == null)){ + Logger.WARNING("Found a recipe with 0 inputs, yet had a valid output."); + Logger.WARNING("Error found while adding a recipe for: "+resultItem.getDisplayName()+" | Please report this issue on Github."); + RegistrationHandler.recipesFailed++; + return false; + } + + //Utils.LOG_WARNING("Trying to add a recipe for "+resultItem.toString()); + String a,b,c,d,e,f,g,h,i; + if (slot_1 == null){ a = " ";} else { a = "1";validSlots.add('1');validSlots.add(slot_1);} + Logger.WARNING(a); + if (slot_2 == null){ b = " ";} else { b = "2";validSlots.add('2');validSlots.add(slot_2);} + Logger.WARNING(b); + if (slot_3 == null){ c = " ";} else { c = "3";validSlots.add('3');validSlots.add(slot_3);} + Logger.WARNING(c); + if (slot_4 == null){ d = " ";} else { d = "4";validSlots.add('4');validSlots.add(slot_4);} + Logger.WARNING(d); + if (slot_5 == null){ e = " ";} else { e = "5";validSlots.add('5');validSlots.add(slot_5);} + Logger.WARNING(e); + if (slot_6 == null){ f = " ";} else { f = "6";validSlots.add('6');validSlots.add(slot_6);} + Logger.WARNING(f); + if (slot_7 == null){ g = " ";} else { g = "7";validSlots.add('7');validSlots.add(slot_7);} + Logger.WARNING(g); + if (slot_8 == null){ h = " ";} else { h = "8";validSlots.add('8');validSlots.add(slot_8);} + Logger.WARNING(h); + if (slot_9 == null){ i = " ";} else { i = "9";validSlots.add('9');validSlots.add(slot_9);} + Logger.WARNING(i); + + + Logger.ERROR("_______"); + final String lineOne = a+b+c; + Logger.ERROR("|"+a+"|"+b+"|"+c+"|"); + Logger.ERROR("_______"); + final String lineTwo = d+e+f; + Logger.ERROR("|"+d+"|"+e+"|"+f+"|"); + Logger.ERROR("_______"); + final String lineThree = g+h+i; + Logger.ERROR("|"+g+"|"+h+"|"+i+"|"); + Logger.ERROR("_______"); + + validSlots.add(0, lineOne); + validSlots.add(1, lineTwo); + validSlots.add(2, lineThree); + boolean advancedLog = false; + if (CORE.DEBUG){ + advancedLog = true; + } + if (advancedLog){ + int j = 0; + final int l = validSlots.size(); + Logger.WARNING("l:"+l); + while (j <= l) { + Logger.WARNING("j:"+j); + if (j <= 2){ + Logger.WARNING("ArrayList Values: "+validSlots.get(j)); + Logger.WARNING("Adding 1."); + j++; + } + else if (j == l){ + Logger.WARNING("Done iteration."); + break; + } + else { + Logger.WARNING("ArrayList Values: '"+validSlots.get(j)+"' "+validSlots.get(j+1)); + if (j < (l-2)){ + Logger.WARNING("Adding 2."); + j=j+2; + } + else { + Logger.WARNING("Done iteration."); + break; + } + } + if ((validSlots.get(j) instanceof String) || (validSlots.get(j) instanceof ItemStack)){ + //Utils.LOG_WARNING("Is Valid: "+validSlots.get(j)); + } + } + } + + try { + GameRegistry.addRecipe(new ShapedOreRecipe(resultItem.copy(), validSlots.toArray())); + //Utils.LOG_WARNING("Success! Added a recipe for "+resultItem.getDisplayName()); + if (!COMPAT_HANDLER.areInitItemsLoaded){ + RegistrationHandler.recipesSuccess++; + } + else { + LateRegistrationHandler.recipesSuccess++; + } + return true; + } + catch(RuntimeException k){ + //k.getMessage(); + //k.getClass(); + //k.printStackTrace(); + //k.getLocalizedMessage(); + Logger.INFO("@@@: Invalid Recipe detected for: "+resultItem.getUnlocalizedName()); + if (!COMPAT_HANDLER.areInitItemsLoaded){ + RegistrationHandler.recipesFailed++; + } + else { + LateRegistrationHandler.recipesFailed++; + } + return false; + } + } + + public static void shapelessBuilder(final ItemStack Output, final Object slot_1, final Object slot_2, final Object slot_3, final Object slot_4, final Object slot_5, final Object slot_6, final Object slot_7, final Object slot_8, final Object slot_9){ + //Item output_ITEM = Output.getItem(); + + final ArrayList validSlots = new ArrayList<>(); + + Logger.WARNING("Trying to add a recipe for "+Output.toString()); + String a,b,c,d,e,f,g,h,i; + if (slot_1 == null){ a = " ";} else { a = "1";validSlots.add('1');validSlots.add(slot_1);} + Logger.WARNING(a); + if (slot_2 == null){ b = " ";} else { b = "2";validSlots.add('2');validSlots.add(slot_2);} + Logger.WARNING(b); + if (slot_3 == null){ c = " ";} else { c = "3";validSlots.add('3');validSlots.add(slot_3);} + Logger.WARNING(c); + if (slot_4 == null){ d = " ";} else { d = "4";validSlots.add('4');validSlots.add(slot_4);} + Logger.WARNING(d); + if (slot_5 == null){ e = " ";} else { e = "5";validSlots.add('5');validSlots.add(slot_5);} + Logger.WARNING(e); + if (slot_6 == null){ f = " ";} else { f = "6";validSlots.add('6');validSlots.add(slot_6);} + Logger.WARNING(f); + if (slot_7 == null){ g = " ";} else { g = "7";validSlots.add('7');validSlots.add(slot_7);} + Logger.WARNING(g); + if (slot_8 == null){ h = " ";} else { h = "8";validSlots.add('8');validSlots.add(slot_8);} + Logger.WARNING(h); + if (slot_9 == null){ i = " ";} else { i = "9";validSlots.add('9');validSlots.add(slot_9);} + Logger.WARNING(i); + + + Logger.ERROR("_______"); + Logger.ERROR("|"+a+"|"+b+"|"+c+"|"); + Logger.ERROR("_______"); + Logger.ERROR("|"+d+"|"+e+"|"+f+"|"); + Logger.ERROR("_______"); + Logger.ERROR("|"+g+"|"+h+"|"+i+"|"); + Logger.ERROR("_______"); + + validSlots.add(0, a); + validSlots.add(1, b); + validSlots.add(2, c); + validSlots.add(3, d); + validSlots.add(4, e); + validSlots.add(5, f); + validSlots.add(6, g); + validSlots.add(7, h); + validSlots.add(8, i); + + try { + //GameRegistry.addRecipe(new ShapelessOreRecipe(Output, outputAmount), (Object[]) validSlots.toArray()); + GameRegistry.addRecipe(new ShapelessOreRecipe(Output, validSlots.toArray())); + //GameRegistry.addShapelessRecipe(new ItemStack(output_ITEM, 1), new Object[] {slot_1, slot_2}); + Logger.WARNING("Success! Added a recipe for "+Output.getDisplayName()); + RegistrationHandler.recipesSuccess++; + } + catch(final RuntimeException k){ + k.getMessage(); + k.getClass(); + k.printStackTrace(); + k.getLocalizedMessage(); + Logger.WARNING("@@@: Invalid Recipe detected for: "+Output.getUnlocalizedName()); + RegistrationHandler.recipesFailed++; + } + + + //GameRegistry.addShapelessRecipe(new ItemStack(output_ITEM, 1), new Object[] {slot_1, slot_2}); + } + + public static void recipeBuilder(final Object[] array, final ItemStack outPut) { + Logger.SPECIFIC_WARNING("object Array - recipeBuilder", "Attempting to build a recipe using an object array as an input, splitting it, then running the normal recipeBuilder() method.", 396); + Object a=null; + Object b=null; + Object c=null; + Object d=null; + Object e=null; + Object f=null; + Object g=null; + Object h=null; + Object i=null; + for(int z =0; z <= array.length; z++){ + array[z].toString(); + switch(z) + { + case 0: + a = array[z]; + break; + case 1: + b = array[z]; + break; + case 2: + c = array[z]; + break; + case 3: + d = array[z]; + break; + case 4: + e = array[z]; + break; + case 5: + f = array[z]; + break; + case 6: + g = array[z]; + break; + case 7: + h = array[z]; + break; + case 8: + i = array[z]; + break; + default: + break; + } + recipeBuilder(a, b, c, d, e, f, g, h, i, outPut); + } + } + + public static boolean removeCraftingRecipe(Object x){ + if (null == x){return false;} + if (x instanceof String){ + final Item R = ItemUtils.getItem((String) x); + if (R != null){ + x = R; + } + else { + return false; + } + } + if ((x instanceof Item) || (x instanceof ItemStack)){ + if (x instanceof Item){ + final ItemStack r = new ItemStack((Item) x); + Logger.WARNING("Removing Recipe for "+r.getUnlocalizedName()); + } + else { + Logger.WARNING("Removing Recipe for "+((ItemStack) x).getUnlocalizedName()); + } + if (x instanceof ItemStack){ + final Item r = ((ItemStack) x).getItem(); + if (null != r){ + x = r; + } + else { + Logger.WARNING("Recipe removal failed - Tell Alkalus."); + return false; + } + } + if (RecipeUtils.attemptRecipeRemoval((Item) x)){ + Logger.WARNING("Recipe removal successful"); + return true; + } + Logger.WARNING("Recipe removal failed - Tell Alkalus."); + return false; + } + return false; + } + + private static boolean attemptRecipeRemoval(final Item I){ + Logger.WARNING("Create list of recipes."); + final List recipes = CraftingManager.getInstance().getRecipeList(); + final Iterator items = recipes.iterator(); + Logger.WARNING("Begin list iteration."); + while (items.hasNext()) { + final ItemStack is = items.next().getRecipeOutput(); + if ((is != null) && (is.getItem() == I)){ + items.remove(); + Logger.WARNING("Remove a recipe with "+I.getUnlocalizedName()+" as output."); + continue; + } + } + Logger.WARNING("All recipes should be gone?"); + if (!items.hasNext()){ + Logger.WARNING("We iterated once, let's try again to double check."); + final Iterator items2 = recipes.iterator(); + while (items2.hasNext()) { + final ItemStack is = items2.next().getRecipeOutput(); + if ((is != null) && (is.getItem() == I)){ + items.remove(); + Logger.WARNING("REMOVING MISSED RECIPE - RECHECK CONSTRUCTORS"); + return true; + } + } + Logger.WARNING("Should be all gone now after double checking, so return true."); + return true; + } + Logger.WARNING("Return false, because something went wrong."); + return false; + } + + + + public static boolean addShapedGregtechRecipeForTypes( + final Object InputItem1, final Object InputItem2, final Object InputItem3, + final Object InputItem4, final Object InputItem5, final Object InputItem6, + final Object InputItem7, final Object InputItem8, final Object InputItem9, + final ItemStack OutputItem){ + + int using = 0, recipeSlotCurrent = 0; + boolean[] hasMultiStack = new boolean[9]; + boolean inUse[] = {false, false, false}; + ItemStack array[][] = new ItemStack[3][9]; + + Object[] inputs = { + InputItem1, InputItem2, InputItem3, + InputItem4, InputItem5, InputItem6, + InputItem7, InputItem8, InputItem9}; + + for (Object o : inputs){ + if (o.getClass().isArray()){ + if (inUse[using] == false){ + inUse[using] = true; + array[using] = (ItemStack[]) o; + hasMultiStack[recipeSlotCurrent] = true; + using++; + } + } + else { + hasMultiStack[recipeSlotCurrent] = false; + } + recipeSlotCurrent++; + } + + int using2 = 0; + for (boolean t : inUse){ + + if (t){ + if (array[using2] != null){ + //addShapedGregtechRecipe + } + } + using2++; + } + + + return false; + } + + + + public static boolean addShapedGregtechRecipe( + final Object InputItem1, final Object InputItem2, final Object InputItem3, + final Object InputItem4, final Object InputItem5, final Object InputItem6, + final Object InputItem7, final Object InputItem8, final Object InputItem9, + final ItemStack OutputItem){ + + Object[] o = { + InputItem1, InputItem2, InputItem3, + InputItem4, InputItem5, InputItem6, + InputItem7, InputItem8, InputItem9 + }; + + if (addShapedGregtechRecipe(o, OutputItem)){ + return true; + } + else if (recipeBuilder( + InputItem1, InputItem2, InputItem3, + InputItem4, InputItem5, InputItem6, + InputItem7, InputItem8, InputItem9, + OutputItem)){ + return true; + } + else { + if (OutputItem != null){ + Logger.WARNING("Adding recipe for "+OutputItem.getDisplayName()+" failed. Error 62."); + } + RegistrationHandler.recipesFailed++; + return false; + } + } + + public static boolean addShapedGregtechRecipe(final Object[] inputs, ItemStack output){ + + if (inputs.length != 9){ + Logger.WARNING("Input array for "+output.getDisplayName()+" does not equal 9. "+inputs.length+" is the actual size."); + + RegistrationHandler.recipesFailed++; + return false; + } + + for (int x=0;x<9;x++){ + if (inputs[x] == null){ + inputs[x] = " "; + Logger.WARNING("Input slot "+x+" changed from NULL to a blank space."); + } + else if (!(inputs[x] instanceof ItemStack) && !(inputs[x] instanceof String)){ + if (output != null){ + Logger.WARNING("Invalid Item inserted into inputArray. Item:"+output.getDisplayName()+" has a bad recipe. Please report to Alkalus."); + + RegistrationHandler.recipesFailed++; + return false; + } + else { + Logger.WARNING("Output is Null for a recipe. Report to Alkalus."); + output = ItemUtils.getItemStackOfAmountFromOreDict("sadibasdkjnad", 1); + } + } + } + + if (GT_ModHandler.addCraftingRecipe(output, + GT_ModHandler.RecipeBits.DISMANTLEABLE | GT_ModHandler.RecipeBits.NOT_REMOVABLE | + GT_ModHandler.RecipeBits.REVERSIBLE | GT_ModHandler.RecipeBits.BUFFERED, + new Object[]{"ABC", "DEF", "GHI", + 'A', inputs[0], + 'B', inputs[1], + 'C', inputs[2], + 'D', inputs[3], + 'E', inputs[4], + 'F', inputs[5], + 'G', inputs[6], + 'H', inputs[7], + 'I', inputs[8]})){ + Logger.WARNING("Success! Added a recipe for "+output.getDisplayName()); + RegistrationHandler.recipesSuccess++; + return true; + } + else { + if (output != null){ + Logger.WARNING("Adding recipe for "+output.getDisplayName()+" failed. Error 61."); + } + return false; + } + } + + public static boolean addShapelessGregtechRecipe(final Object[] inputItems, final ItemStack OutputItem){ + //Catch Invalid Recipes + if (inputItems.length > 9 || inputItems.length < 1){ + if (OutputItem != null){ + Logger.WARNING("Invalid input array for shapeless recipe, which should output "+OutputItem.getDisplayName()); + } + return false; + } + //let gregtech handle shapeless recipes. + if (GT_ModHandler.addShapelessCraftingRecipe(OutputItem, inputItems)){ + return true; + } + return false; + } + + public static ItemStack getItemStackFromOreDict(final String oredictName){ + final ArrayList oreDictList = OreDictionary.getOres(oredictName); + return oreDictList.get(0); + } + + public static boolean buildShapelessRecipe(final ItemStack output, final Object[] input){ + return ShapelessUtils.addShapelessRecipe(output, input); + } + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/ShapelessUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/ShapelessUtils.java new file mode 100644 index 0000000000..702fd87db6 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/ShapelessUtils.java @@ -0,0 +1,55 @@ +package gtPlusPlus.core.util.minecraft; + +import java.util.ArrayList; + +import gtPlusPlus.api.objects.Logger; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.ShapelessRecipes; + +public class ShapelessUtils { + + + public static boolean addShapelessRecipe(final ItemStack output, final Object ... params) + { + final ArrayList arraylist = new ArrayList<>(); + final Object[] aobject = params; + final int i = params.length; + + for (int j = 0; j < i; ++j) + { + final Object object1 = aobject[j]; + + if (object1 instanceof ItemStack) + { + arraylist.add(((ItemStack)object1).copy()); + } + else if (object1 instanceof Item) + { + arraylist.add(new ItemStack((Item)object1)); + } + else + { + if ((object1 == null)) + { + Logger.INFO(("Invalid shapeless input, ignoring!")); + } + else if (!(object1 instanceof Block) && (object1 != null)) + { + Logger.INFO(("Invalid shapeless recipe!")); + return false; + } + else { + arraylist.add(new ItemStack((Block)object1)); + } + } + } + CraftingManager.getInstance().getRecipeList().add(new ShapelessRecipes(output, arraylist)); + //CraftingManager.getInstance().addShapelessRecipe(output, arraylist); + return true; + } + + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/UtilsMining.java b/src/Java/gtPlusPlus/core/util/minecraft/UtilsMining.java new file mode 100644 index 0000000000..eb6044fcd7 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/UtilsMining.java @@ -0,0 +1,214 @@ +package gtPlusPlus.core.util.minecraft; + +import gtPlusPlus.api.objects.Logger; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +public class UtilsMining { + + private static boolean durabilityDamage = false; + private static ItemStack stack; + + public static Boolean canPickaxeBlock(final Block currentBlock, final World currentWorld){ + String correctTool = ""; + if (!currentWorld.isRemote){ + try { + correctTool = currentBlock.getHarvestTool(0); + //Utils.LOG_WARNING(correctTool); + if (correctTool.equals("pickaxe")){ + return true;} + } catch (final NullPointerException e){ + return false;} + } + return false; + } + + private static void removeBlockAndDropAsItem(final World world, final int X, final int Y, final int Z){ + try { + final Block block = world.getBlock(X, Y, Z); + if (canPickaxeBlock(block, world)){ + if((block != Blocks.bedrock) && (block.getBlockHardness(world, X, Y, Z) != -1) && (block.getBlockHardness(world, X, Y, Z) <= 100) && (block != Blocks.water) && (block != Blocks.lava)){ + block.dropBlockAsItem(world, X, Y, Z, world.getBlockMetadata(X, Y, Z), 0); + world.setBlockToAir(X, Y, Z); + + } + else { + Logger.WARNING("Incorrect Tool for mining this block."); + } + } + } catch (final NullPointerException e){ + + } + } + + /*public static void customMine(World world, String FACING, EntityPlayer aPlayer){ + + float DURABILITY_LOSS = 0; + if (!world.isRemote){ + int X = 0; + int Y = 0; + int Z = 0; + + if (FACING.equals("below") || FACING.equals("above")){ + + //Set Player Facing + X = (int) aPlayer.posX; + Utils.LOG_WARNING("Setting Variable X: "+X); + if (FACING.equals("above")){ + Z = (int) aPlayer.posY + 1; + Utils.LOG_WARNING("Setting Variable Y: "+Y); + } + else { + Z = (int) aPlayer.posY - 1; + Utils.LOG_WARNING("Setting Variable Y: "+Y);} + Z = (int) aPlayer.posZ; + Utils.LOG_WARNING("Setting Variable Z: "+Z); + + DURABILITY_LOSS = 0; + for(int i = -2; i < 3; i++) { + for(int j = -2; j < 3; j++) { + for(int k = -2; k < 3; k++) { +// float dur = calculateDurabilityLoss(world, X + i, Y + k, Z + j); +// DURABILITY_LOSS = (DURABILITY_LOSS + dur); +// Utils.LOG_WARNING("Added Loss: "+dur); + removeBlockAndDropAsItem(world, X + i, Y + k, Z + j); + } + } + } + } + + else if (FACING.equals("facingEast") || FACING.equals("facingWest")){ + + //Set Player Facing + Z = (int) aPlayer.posZ; + Y = (int) aPlayer.posY; + if (FACING.equals("facingEast")){ + X = (int) aPlayer.posX + 1;} + else { + X = (int) aPlayer.posX - 1;} + + + DURABILITY_LOSS = 0; + for(int i = -1; i < 2; i++) { + for(int j = -1; j < 2; j++) { + for(int k = -1; k < 2; k++) { + float dur = calculateDurabilityLoss(world, X+k, Y + i, Z + j); + DURABILITY_LOSS = (DURABILITY_LOSS + dur); + Utils.LOG_WARNING("Added Loss: "+dur); + removeBlockAndDropAsItem(world, X+k, Y + i, Z + j); + } + } + } + } + + else if (FACING.equals("facingNorth") || FACING.equals("facingSouth")){ + + //Set Player Facing + X = (int) aPlayer.posX; + Y = (int) aPlayer.posY; + + if (FACING.equals("facingNorth")){ + Z = (int) aPlayer.posZ + 1;} + else { + Z = (int) aPlayer.posZ - 1;} + + DURABILITY_LOSS = 0; + for(int i = -1; i < 2; i++) { + for(int j = -1; j < 2; j++) { + for(int k = -1; k < 2; k++) { + float dur = calculateDurabilityLoss(world, X + j, Y + i, Z+k); + DURABILITY_LOSS = (DURABILITY_LOSS + dur); + Utils.LOG_WARNING("Added Loss: "+dur); + removeBlockAndDropAsItem(world, X + j, Y + i, Z+k); + } + } + } + } + + //Set Durability damage to the item + if (durabilityDamage == true){ + Utils.LOG_WARNING("Total Loss: "+(int)DURABILITY_LOSS); + if (stack.getItemDamage() < (stack.getMaxDamage()-DURABILITY_LOSS)){ + stack.damageItem((int) DURABILITY_LOSS, aPlayer); + } + } + DURABILITY_LOSS = 0; + } + }*/ + + + public static boolean getBlockType(final Block block, final World world, final int[] xyz, final int miningLevel){ + final String LIQUID = "liquid"; + final String BLOCK = "block"; + final String ORE = "ore"; + final String AIR = "air"; + String blockClass = ""; + + if (world.isRemote){ + return false; + } + + if (block == Blocks.end_stone) { + return true; + } + if (block == Blocks.stone) { + return true; + } + if (block == Blocks.sandstone) { + return true; + } + if (block == Blocks.netherrack) { + return true; + } + if (block == Blocks.nether_brick) { + return true; + } + if (block == Blocks.nether_brick_stairs) { + return true; + } + if (block == Blocks.nether_brick_fence) { + return true; + } + if (block == Blocks.glowstone) { + return true; + } + + + + try { + blockClass = block.getClass().toString().toLowerCase(); + Logger.WARNING(blockClass); + if (blockClass.toLowerCase().contains(LIQUID)){ + Logger.WARNING(block.toString()+" is a Liquid."); + return false; + } + else if (blockClass.toLowerCase().contains(ORE)){ + Logger.WARNING(block.toString()+" is an Ore."); + return true; + } + else if (block.getHarvestLevel(world.getBlockMetadata(xyz[0], xyz[1], xyz[2])) >= miningLevel){ + Logger.WARNING(block.toString()+" is minable."); + return true; + } + else if (blockClass.toLowerCase().contains(AIR)){ + Logger.WARNING(block.toString()+" is Air."); + return false; + } + else if (blockClass.toLowerCase().contains(BLOCK)){ + Logger.WARNING(block.toString()+" is a block of some kind."); + return false; + } + else { + Logger.WARNING(block.toString()+" is mystery."); + return false; + } + } + catch(final NullPointerException e){ + return false; + } + } + + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/gregtech/PollutionUtils.java b/src/Java/gtPlusPlus/core/util/minecraft/gregtech/PollutionUtils.java new file mode 100644 index 0000000000..d7258cfd60 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/gregtech/PollutionUtils.java @@ -0,0 +1,54 @@ +package gtPlusPlus.core.util.minecraft.gregtech; + +import java.lang.reflect.*; + +import gregtech.GT_Mod; +import gregtech.api.interfaces.tileentity.IGregTechTileEntity; +import gregtech.common.GT_Proxy; +import gtPlusPlus.core.util.reflect.ReflectionUtils; + +public class PollutionUtils { + + public static boolean mPollution() { + try { + GT_Proxy GT_Pollution = GT_Mod.gregtechproxy; + if (GT_Pollution != null) { + Field mPollution = ReflectionUtils.getField(GT_Pollution.getClass(), "mPollution"); + if (mPollution != null) { + return mPollution.getBoolean(GT_Pollution); + } + } + } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {} + return false; + } + + public static boolean addPollution(IGregTechTileEntity te, int pollutionValue) { + try { + Class GT_Pollution = Class.forName("gregtech.common.GT_Pollution"); + if (GT_Pollution != null) { + Method addPollution = GT_Pollution.getMethod("addPollution", IGregTechTileEntity.class, int.class); + if (addPollution != null) { + addPollution.invoke(null, te, pollutionValue); + return true; + } + } + } catch (ClassNotFoundException | SecurityException | NoSuchMethodException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) {} + return false; + } + + public static int getPollution(IGregTechTileEntity te) { + try { + Class GT_Pollution = Class.forName("gregtech.common.GT_Pollution"); + if (GT_Pollution != null) { + Method addPollution = GT_Pollution.getMethod("getPollution", IGregTechTileEntity.class); + if (addPollution != null) { + return (int) addPollution.invoke(null, te); + } + } + } catch (ClassNotFoundException | SecurityException | NoSuchMethodException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) {} + return 0; + } + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/gregtech/material/MaterialBuilder.java b/src/Java/gtPlusPlus/core/util/minecraft/gregtech/material/MaterialBuilder.java new file mode 100644 index 0000000000..61a0f97129 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/gregtech/material/MaterialBuilder.java @@ -0,0 +1,254 @@ +package gtPlusPlus.core.util.minecraft.gregtech.material; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import gregtech.api.enums.Dyes; +import gregtech.api.enums.Materials; +import gregtech.api.enums.TC_Aspects; +import gregtech.api.enums.TextureSet; +import gregtech.api.objects.MaterialStack; + +public class MaterialBuilder { + /*public static final int DIESEL = 0, GAS = 1, THERMAL = 2, SEMIFLUID = 3, PLASMA = 4, MAGIC = 5; + + private int metaItemSubID; + private TextureSet iconSet; + private float toolSpeed = 1.0f; + private int durability = 0; + private int toolQuality = 0; + private int types = 0; + private int r = 255, g = 255, b = 255, a = 0; + private String name; + private String defaultLocalName; + private int fuelType = 0; + private int fuelPower = 0; + private int meltingPoint = 0; + private int blastFurnaceTemp = 0; + private boolean blastFurnaceRequired = false; + private boolean transparent = false; + private int oreValue = 1; + private int densityMultiplier = 1; + private int densityDivider = 1; + private Dyes color = Dyes._NULL; + private int extraData = 0; + private List materialList = new ArrayList(); + private List aspects = new ArrayList(); + private boolean canBeCracked = false; + private int liquidTemperature = 300; + private int gasTemperature = 300; + + public MaterialBuilder(int metaItemSubID, TextureSet iconSet, String defaultLocalName) { + this.metaItemSubID = metaItemSubID; + this.iconSet = iconSet; + this.name = defaultLocalName.replace(" ", "").replace("-", ""); + this.defaultLocalName = defaultLocalName; + } + + public Materials constructMaterial() { + return new Materials( + metaItemSubID, iconSet, toolSpeed, durability, toolQuality, types, r, g, b, a, name, defaultLocalName, fuelType, fuelPower, meltingPoint, blastFurnaceTemp, + blastFurnaceRequired, transparent, oreValue, densityMultiplier, densityDivider, color, extraData, materialList, aspects); + + } + + public MaterialBuilder setName(String name){ + this.name = name; + return this; + } + + public MaterialBuilder setTypes(int types){ + this.types = types; + return this; + } + + public MaterialBuilder addDustItems(){ + types = types | 1; + return this; + } + + public MaterialBuilder addMetalItems(){ + types = types | 2; + return this; + } + + public MaterialBuilder addGemItems(){ + types = types | 4; + return this; + } + + public MaterialBuilder addOreItems(){ + types = types | 8; + return this; + } + + public MaterialBuilder addCell(){ + types = types | 16; + return this; + } + + public MaterialBuilder addPlasma(){ + types = types | 32; + return this; + } + + public MaterialBuilder addToolHeadItems(){ + types = types | 64; + return this; + } + + public MaterialBuilder addGearItems(){ + types = types | 128; + return this; + } + + public MaterialBuilder addFluid(){ + return this; + } + + public MaterialBuilder addGas(){ + return this; + } + + + public MaterialBuilder setRGBA(int r, int g, int b, int a){ + this.r = r; + this.g = g; + this.b = b; + this.a = a; + return this; + } + + public MaterialBuilder setRGB(int r, int g, int b){ + this.r = r; + this.g = g; + this.b = b; + return this; + } + + public MaterialBuilder setTransparent(boolean transparent){ + this.transparent = transparent; + return this; + } + + public MaterialBuilder setColor(Dyes color){ + this.color = color; + return this; + } + + + public MaterialBuilder setToolSpeed(float toolSpeed) { + this.toolSpeed = toolSpeed; + return this; + } + + public MaterialBuilder setDurability(int durability) { + this.durability = durability; + return this; + } + + public MaterialBuilder setToolQuality(int toolQuality) { + this.toolQuality = toolQuality; + return this; + } + + + public MaterialBuilder setFuelType(int fuelType) { + this.fuelType = fuelType; + return this; + } + + public MaterialBuilder setFuelPower(int fuelPower) { + this.fuelPower = fuelPower; + return this; + } + + public MaterialBuilder setMeltingPoint(int meltingPoint) { + this.meltingPoint = meltingPoint; + return this; + } + + public MaterialBuilder setBlastFurnaceTemp(int blastFurnaceTemp) { + this.blastFurnaceTemp = blastFurnaceTemp; + return this; + } + + public MaterialBuilder setBlastFurnaceRequired(boolean blastFurnaceRequired) { + this.blastFurnaceRequired = blastFurnaceRequired; + return this; + } + + public MaterialBuilder setOreValue(int oreValue) { + this.oreValue = oreValue; + return this; + } + + public MaterialBuilder setDensityMultiplier(int densityMultiplier) { + this.densityMultiplier = densityMultiplier; + return this; + } + + public MaterialBuilder setDensityDivider(int densityDivider) { + this.densityDivider = densityDivider; + return this; + } + + public MaterialBuilder setExtraData(int extraData) { + this.extraData = extraData; + return this; + } + + public MaterialBuilder addElectrolyzerRecipe(){ + extraData = extraData | 1; + return this; + } + + public MaterialBuilder addCentrifugeRecipe(){ + extraData = extraData | 2; + return this; + } + + public MaterialBuilder setMaterialList(List materialList) { + this.materialList = materialList; + return this; + } + + public MaterialBuilder setMaterialList(MaterialStack ... materials) { + this.materialList = Arrays.asList(materials); + return this; + } + + public MaterialBuilder setAspects(List aspects) { + this.aspects = aspects; + return this; + } + + public int getLiquidTemperature() { + return liquidTemperature; + } + + public MaterialBuilder setLiquidTemperature(int liquidTemperature) { + this.liquidTemperature = liquidTemperature; + return this; + } + + public int getGasTemperature() { + return gasTemperature; + } + + public MaterialBuilder setGasTemperature(int gasTemperature) { + this.gasTemperature = gasTemperature; + return this; + } + + public boolean canBeCracked() { + return canBeCracked; + } + + public MaterialBuilder setCanBeCracked(boolean canBeCracked) { + this.canBeCracked = canBeCracked; + return this; + } +*/ +} \ No newline at end of file diff --git a/src/Java/gtPlusPlus/core/util/minecraft/gregtech/recipehandlers/GregtechRecipe.java b/src/Java/gtPlusPlus/core/util/minecraft/gregtech/recipehandlers/GregtechRecipe.java new file mode 100644 index 0000000000..854f813d2b --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/gregtech/recipehandlers/GregtechRecipe.java @@ -0,0 +1,74 @@ +package gtPlusPlus.core.util.minecraft.gregtech.recipehandlers; + +import java.lang.reflect.Method; + +import gregtech.api.util.GT_ModHandler; +import gtPlusPlus.api.objects.Logger; +import gtPlusPlus.core.lib.CORE; +import net.minecraft.item.ItemStack; + +public final class GregtechRecipe { + + public LibraryProxy ourProxy; + public GregtechRecipe(){ + Logger.INFO("Initializing a recipe handler for different versions of Gregtech 5."); + try { + if (!CORE.MAIN_GREGTECH_5U_EXPERIMENTAL_FORK){ + this.ourProxy = new LibProxy1(); + Logger.INFO("Selecting GT 5.7/5.8 Recipe Set"); + } + if (CORE.MAIN_GREGTECH_5U_EXPERIMENTAL_FORK){ + this.ourProxy = new LibProxy2(); + Logger.INFO("Selecting GT 5.9 Recipe Set"); + } + } catch (final NoSuchMethodException e) { + this.ourProxy = null; + } + } + + public boolean addSmeltingAndAlloySmeltingRecipe(final ItemStack aInput, final ItemStack aOutput) { + Logger.WARNING("Adding a GT Furnace/Alloy Smelter Recipe"+"| Input:"+aInput.getDisplayName()+" | Output:"+aOutput.getDisplayName()+" |"); + return this.ourProxy.addSmeltingAndAlloySmeltingRecipe(aInput, aOutput); + } + +} + +abstract class LibraryProxy { // can also be interface unless you want to have common code here + abstract public boolean addSmeltingAndAlloySmeltingRecipe(ItemStack aInput, ItemStack aOutput); +} + +class LibProxy1 extends LibraryProxy { + final Method m1; + + public LibProxy1() throws NoSuchMethodException { + this.m1 = GT_ModHandler.class.getDeclaredMethod("addSmeltingAndAlloySmeltingRecipe", ItemStack.class, ItemStack.class); + } + + @Override + public boolean addSmeltingAndAlloySmeltingRecipe(final ItemStack aInput, final ItemStack aOutput) { + try { + Logger.INFO("Trying with Gt 5.7/5.8 Method."); + return (boolean) this.m1.invoke(null, aInput, aOutput); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } +} + +class LibProxy2 extends LibraryProxy { + final Method m2; + + public LibProxy2() throws NoSuchMethodException { + this.m2 = GT_ModHandler.class.getDeclaredMethod("addSmeltingAndAlloySmeltingRecipe", ItemStack.class, ItemStack.class, boolean.class); + } + + @Override + public boolean addSmeltingAndAlloySmeltingRecipe(final ItemStack aInput, final ItemStack aOutput) { + try { + Logger.INFO("Trying with Gt 5.9 Method."); + return (boolean) this.m2.invoke(null, aInput, aOutput, true); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } +} \ No newline at end of file diff --git a/src/Java/gtPlusPlus/core/util/minecraft/particles/BlockBreakParticles.java b/src/Java/gtPlusPlus/core/util/minecraft/particles/BlockBreakParticles.java new file mode 100644 index 0000000000..c5a0949bb5 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/particles/BlockBreakParticles.java @@ -0,0 +1,17 @@ +package gtPlusPlus.core.util.minecraft.particles; + +import gtPlusPlus.xmod.forestry.HANDLER_FR; +import net.minecraft.block.Block; +import net.minecraft.world.World; + +public class BlockBreakParticles { + + public BlockBreakParticles(final World world, final int x, final int y, final int z, final Block block){ + try { + HANDLER_FR.createBlockBreakParticles(world, x, y, z, block); + } catch (final Throwable T){ + + } + } + +} diff --git a/src/Java/gtPlusPlus/core/util/minecraft/particles/EntityParticleFXMysterious.java b/src/Java/gtPlusPlus/core/util/minecraft/particles/EntityParticleFXMysterious.java new file mode 100644 index 0000000000..d996cf705a --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/minecraft/particles/EntityParticleFXMysterious.java @@ -0,0 +1,17 @@ +package gtPlusPlus.core.util.minecraft.particles; + +import net.minecraft.client.particle.EntityAuraFX; +import net.minecraft.world.World; + +public class EntityParticleFXMysterious extends EntityAuraFX +{ + public EntityParticleFXMysterious(final World parWorld, + final double parX, final double parY, final double parZ, + final double parMotionX, final double parMotionY, final double parMotionZ) + { + super(parWorld, parX, parY, parZ, parMotionX, parMotionY, parMotionZ); + this.setParticleTextureIndex(82); // same as happy villager + this.particleScale = 2.0F; + this.setRBGColorF(0x88, 0x00, 0x88); + } +} diff --git a/src/Java/gtPlusPlus/core/util/nbt/ModularArmourUtils.java b/src/Java/gtPlusPlus/core/util/nbt/ModularArmourUtils.java deleted file mode 100644 index c9ac557fee..0000000000 --- a/src/Java/gtPlusPlus/core/util/nbt/ModularArmourUtils.java +++ /dev/null @@ -1,159 +0,0 @@ -package gtPlusPlus.core.util.nbt; - -import baubles.api.BaubleType; -import gregtech.api.util.GT_Utility; -import gtPlusPlus.api.objects.Logger; -import gtPlusPlus.api.objects.data.Pair; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -public class ModularArmourUtils { - - public static ItemStack addComponent(ItemStack tArmour, ItemStack[] tComponents) { - if (tArmour != null) { - ItemStack rArmour = NBTUtils.writeItemsToGtCraftingComponents(tArmour, tComponents, true); - if (rArmour != null) { - - } - } - return null; - } - - public static enum Modifiers { - BOOST_HP("skill.hpboost"), BOOST_DEF("skill.defenceboost"), BOOST_SPEED("skill.speedboost"), BOOST_MINING( - "skill.miningboost"), BOOST_DAMAGE("skill.damageboost"), BOOST_HOLY("skill.holyboost"); - private String MODIFIER_NAME; - - private Modifiers(final String mModifier) { - this.MODIFIER_NAME = mModifier; - } - - public String getModifier() { - return this.MODIFIER_NAME; - } - - public boolean isValidLevel(int i) { - if (i >= 0 && i <= 100) { - return true; - } - return false; - } - } - - public static enum BT { - TYPE_AMULET(BaubleType.AMULET, 0), TYPE_RING(BaubleType.RING, 1), TYPE_BELT(BaubleType.BELT, 2); - private final BaubleType mType; - private final int mID; - private final String mBaubleType; - - private BT(final BaubleType tType, int tID) { - this.mType = tType; - this.mID = tID; - this.mBaubleType = tType.name().toLowerCase(); - } - - public BaubleType getType() { - return this.mType; - } - - public BT getThis() { - return this; - } - - public BaubleType getBaubleByID(int tID) { - if (tID == 0) { - return BaubleType.AMULET; - } else if (tID == 1) { - return BaubleType.RING; - } else if (tID == 2) { - return BaubleType.BELT; - } else { - return BaubleType.RING; - } - } - - public int getID() { - return this.mID; - } - - public String getTypeAsString() { - return this.mBaubleType; - } - } - - public static void setModifierLevel(ItemStack aStack, Pair mPair) { - setModifierLevel(aStack, mPair.getKey(), mPair.getValue().intValue()); - } - - public static void setModifierLevel(ItemStack aStack, Modifiers aMod, Integer aInt) { - setModifierLevel(aStack, aMod, aInt.intValue()); - } - - public static void setModifierLevel(ItemStack aStack, Modifiers aMod, int aInt) { - - int mCurrentLevel = getModifierLevel(aStack, aMod); - int mNewTotalLevel = mCurrentLevel + aInt; - - NBTTagCompound tNBT = NBTUtils.getNBT(aStack); - if (aMod.isValidLevel(mNewTotalLevel)) { - tNBT.setInteger(aMod.getModifier(), mNewTotalLevel); - GT_Utility.ItemNBT.setNBT(aStack, tNBT); - } else { - if (getModifierLevel(aStack, aMod) > 100) { - setModifierLevel(aStack, aMod, 100); - } - } - } - - public static int getModifierLevel(ItemStack aStack, Pair newPair) { - return getModifierLevel(aStack, newPair.getKey()); - } - - public static int getModifierLevel(ItemStack aStack, Modifiers aMod) { - NBTTagCompound tNBT = NBTUtils.getNBT(aStack); - return tNBT.getInteger(aMod.getModifier()); - } - - public static void setBaubleType(ItemStack aStack, BT aMod) { - Logger.INFO("Changing bauble type."); - NBTTagCompound tNBT = NBTUtils.getNBT(aStack); - if (aMod != null) { - tNBT.setInteger("mBaubleType", aMod.getID()); - GT_Utility.ItemNBT.setNBT(aStack, tNBT); - } - } - - public static int getBaubleTypeID(ItemStack aStack) { - NBTTagCompound tNBT = NBTUtils.getNBT(aStack); - return tNBT.getInteger("mBaubleType"); - } - - public static BaubleType getBaubleType(ItemStack aStack) { - NBTTagCompound tNBT = NBTUtils.getNBT(aStack); - return getBaubleByID(tNBT.getInteger("mBaubleType")); - } - - public static BaubleType getBaubleByID(int tID) { - if (tID == 0) { - return BaubleType.AMULET; - } else if (tID == 1) { - return BaubleType.RING; - } else if (tID == 2) { - return BaubleType.BELT; - } else { - return BaubleType.RING; - } - } - - public static ItemStack setDefaultStats(ItemStack aStack) { - ItemStack tempStack = aStack; - setModifierLevel(tempStack, Modifiers.BOOST_DAMAGE, 0); - setModifierLevel(tempStack, Modifiers.BOOST_DEF, 0); - setModifierLevel(tempStack, Modifiers.BOOST_HOLY, 0); - setModifierLevel(tempStack, Modifiers.BOOST_HP, 0); - setModifierLevel(tempStack, Modifiers.BOOST_MINING, 0); - setModifierLevel(tempStack, Modifiers.BOOST_SPEED, 0); - return tempStack; - } - -} diff --git a/src/Java/gtPlusPlus/core/util/nbt/NBTUtils.java b/src/Java/gtPlusPlus/core/util/nbt/NBTUtils.java deleted file mode 100644 index 58d47eb0fa..0000000000 --- a/src/Java/gtPlusPlus/core/util/nbt/NBTUtils.java +++ /dev/null @@ -1,454 +0,0 @@ -package gtPlusPlus.core.util.nbt; - -import static gtPlusPlus.core.item.ModItems.ZZZ_Empty; - -import java.util.Map; - -import gregtech.api.items.GT_MetaGenerated_Tool; -import gregtech.api.util.GT_ModHandler; -import gregtech.api.util.GT_Utility; -import gtPlusPlus.api.objects.Logger; -import gtPlusPlus.core.util.item.ItemUtils; -import gtPlusPlus.core.util.reflect.ReflectionUtils; -import net.minecraft.entity.Entity; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - -public class NBTUtils { - - public static NBTTagCompound getNBT(ItemStack aStack) { - NBTTagCompound rNBT = aStack.getTagCompound(); - return ((rNBT == null) ? new NBTTagCompound() : rNBT); - } - - public static void setBookTitle(ItemStack aStack, String aTitle) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setString("title", aTitle); - GT_Utility.ItemNBT.setNBT(aStack, tNBT); - } - - public static String getBookTitle(ItemStack aStack) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getString("title"); - } - - public static ItemStack[] readItemsFromNBT(ItemStack itemstack) { - NBTTagCompound tNBT = getNBT(itemstack); - final NBTTagList list = tNBT.getTagList("Items", 10); - ItemStack inventory[] = new ItemStack[list.tagCount()]; - for (int i = 0; i < list.tagCount(); i++) { - final NBTTagCompound data = list.getCompoundTagAt(i); - final int slot = data.getInteger("Slot"); - if ((slot >= 0) && (slot < list.tagCount())) { - if (ItemStack.loadItemStackFromNBT(data) == ItemUtils.getSimpleStack(ZZZ_Empty)) { - inventory[slot] = null; - } else { - inventory[slot] = ItemStack.loadItemStackFromNBT(data); - } - - } - } - return inventory; - } - - public static ItemStack[] readItemsFromNBT(ItemStack itemstack, String customkey) { - NBTTagCompound tNBT = getNBT(itemstack); - final NBTTagList list = tNBT.getTagList(customkey, 10); - ItemStack inventory[] = new ItemStack[list.tagCount()]; - for (int i = 0; i < list.tagCount(); i++) { - final NBTTagCompound data = list.getCompoundTagAt(i); - final int slot = data.getInteger("Slot"); - if ((slot >= 0) && (slot < list.tagCount())) { - if (ItemStack.loadItemStackFromNBT(data) == ItemUtils.getSimpleStack(ZZZ_Empty)) { - inventory[slot] = null; - } else { - inventory[slot] = ItemStack.loadItemStackFromNBT(data); - } - - } - } - return inventory; - } - - public static ItemStack writeItemsToNBT(ItemStack itemstack, ItemStack[] stored) { - NBTTagCompound tNBT = getNBT(itemstack); - final NBTTagList list = new NBTTagList(); - for (int i = 0; i < stored.length; i++) { - final ItemStack stack = stored[i]; - if (stack != null) { - final NBTTagCompound data = new NBTTagCompound(); - stack.writeToNBT(data); - data.setInteger("Slot", i); - list.appendTag(data); - } else { - final NBTTagCompound data = new NBTTagCompound(); - ItemStack nullstack = ItemUtils.getSimpleStack(ZZZ_Empty); - nullstack.writeToNBT(data); - data.setInteger("Slot", i); - list.appendTag(data); - } - } - tNBT.setTag("Items", list); - itemstack.setTagCompound(tNBT); - return itemstack; - } - - public static ItemStack writeItemsToNBT(ItemStack itemstack, ItemStack[] stored, String customkey) { - NBTTagCompound tNBT = getNBT(itemstack); - final NBTTagList list = new NBTTagList(); - for (int i = 0; i < stored.length; i++) { - final ItemStack stack = stored[i]; - if (stack != null) { - final NBTTagCompound data = new NBTTagCompound(); - stack.writeToNBT(data); - data.setInteger("Slot", i); - list.appendTag(data); - } - } - tNBT.setTag(customkey, list); - itemstack.setTagCompound(tNBT); - return itemstack; - } - - public static ItemStack writeItemsToGtCraftingComponents(ItemStack rStack, ItemStack[] stored, boolean copyTags) { - - if (copyTags) { - for (int i = 0; i < stored.length; i++) { - if (stored[i] != null && stored[i].hasTagCompound()) { - rStack.setTagCompound((NBTTagCompound) stored[i].getTagCompound().copy()); - break; - } - } - } - - NBTTagCompound rNBT = rStack.getTagCompound(), tNBT = new NBTTagCompound(); - if (rNBT == null) - rNBT = new NBTTagCompound(); - for (int i = 0; i < 9; i++) { - ItemStack tStack = stored[i]; - if (tStack != null && GT_Utility.getContainerItem(tStack, true) == null - && !(tStack.getItem() instanceof GT_MetaGenerated_Tool)) { - tStack = GT_Utility.copyAmount(1, tStack); - if (GT_Utility.isStackValid(tStack)) { - GT_ModHandler.dischargeElectricItem(tStack, Integer.MAX_VALUE, Integer.MAX_VALUE, true, false, - true); - tNBT.setTag("Ingredient." + i, tStack.writeToNBT(new NBTTagCompound())); - } - } - } - rNBT.setTag("GT.CraftingComponents", tNBT); - rStack.setTagCompound(rNBT); - return rStack; - } - - public static void setBoolean(ItemStack aStack, String aTag, boolean aBoolean) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setBoolean(aTag, aBoolean); - GT_Utility.ItemNBT.setNBT(aStack, tNBT); - } - - public static boolean getBoolean(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getBoolean(aTag); - } - - public static void setInteger(ItemStack aStack, String aTag, int aInt) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setInteger(aTag, aInt); - GT_Utility.ItemNBT.setNBT(aStack, tNBT); - } - - public static int getInteger(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getInteger(aTag); - } - - public static void setLong(ItemStack aStack, String aTag, long aInt) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setLong(aTag, aInt); - GT_Utility.ItemNBT.setNBT(aStack, tNBT); - } - - public static long getLong(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getLong(aTag); - } - - public static void setFloat(ItemStack aStack, String aTag, float aInt) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setFloat(aTag, aInt); - GT_Utility.ItemNBT.setNBT(aStack, tNBT); - } - - public static float getFloat(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getFloat(aTag); - } - - public static void setString(ItemStack aStack, String aTag, String aString) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setString(aTag, aString); - GT_Utility.ItemNBT.setNBT(aStack, tNBT); - } - - public static String getString(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getString(aTag); - } - - public static boolean doesStringExist(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.hasKey(aTag); - } - - public static boolean tryIterateNBTData(ItemStack aStack) { - try { - NBTTagCompound aNBT = NBTUtils.getNBT(aStack); - if (aNBT != null) { - if (!aNBT.hasNoTags()) { - Map mInternalMap = ReflectionUtils.getField(aNBT, "tagMap"); - if (mInternalMap != null) { - for (Map.Entry e : mInternalMap.entrySet()) { - Logger.INFO("Key: " + e.getKey().toString() + " | Value: " + e.getValue()); - } - return true; - } else { - Logger.INFO("Data map reflected from NBTTagCompound was not valid."); - return false; - } - } - } - } catch (Throwable t) {} - return false; - } - - // Botania soulbind handling - public static boolean setBotanicaSoulboundOwner(ItemStack aStack, String aName) { - final String TAG_SOULBIND = "soulbind"; - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setString(TAG_SOULBIND, aName); - GT_Utility.ItemNBT.setNBT(aStack, tNBT); - if (NBTUtils.doesStringExist(aStack, TAG_SOULBIND)) { - return true; - } else { - return false; - } - } - - public static String getBotanicaSoulboundOwner(ItemStack aStack) { - final String TAG_SOULBIND = "soulbind"; - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getString(TAG_SOULBIND); - } - - public static boolean hasKey(ItemStack stack, String key) { - final NBTTagCompound itemData = getNBT(stack); - if (itemData.hasKey(key)) { - return true; - } - return false; - } - - public static boolean createIntegerTagCompound(ItemStack rStack, String tagName, String keyName, int keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setInteger(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createLongTagCompound(ItemStack rStack, String tagName, String keyName, long keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setLong(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createStringTagCompound(ItemStack rStack, String tagName, String keyName, String keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setString(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createFloatTagCompound(ItemStack rStack, String tagName, String keyName, float keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setFloat(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createDoubleTagCompound(ItemStack rStack, String tagName, String keyName, double keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setDouble(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createBooleanTagCompound(ItemStack rStack, String tagName, String keyName, boolean keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setBoolean(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createTagCompound(ItemStack rStack, String tagName, NBTTagCompound keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - NBTTagCompound tagNBT = keyValue; - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static int getIntegerTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getInteger(keyName); - } - } - return 0; - } - - public static long getLongTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getLong(keyName); - } - } - return 0L; - } - - public static String getStringTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getString(keyName); - } - } - return null; - } - - public static float getFloatTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getFloat(keyName); - } - } - return 0; - } - - public static double getDoubleTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getDouble(keyName); - } - } - return 0; - } - - public static boolean getBooleanTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getBoolean(keyName); - } - } - return false; - } - - public static NBTTagCompound getTagCompound(ItemStack aStack, String tagName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null && hasKey(aStack, tagName)) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT; - } - } - return null; - } - - public static boolean hasKeyInTagCompound(ItemStack stack, String tag, String key) { - NBTTagCompound aNBT = stack.getTagCompound(); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tag); - if (aNBT.hasKey(key)) { - return true; - } - } - return false; - } - - public static boolean tryCloneTagCompoundDataIntoSubTag(ItemStack aStack, NBTTagCompound aTagCompound) { - try { - NBTTagCompound aNBT = aTagCompound; - if (aNBT != null) { - if (!aNBT.hasNoTags()) { - Map mInternalMap = ReflectionUtils.getField(aNBT, "tagMap"); - if (mInternalMap != null) { - for (Map.Entry e : mInternalMap.entrySet()) { - Logger.INFO("Key: " + e.getKey().toString() + " | Value: " + e.getValue().toString()); - if (e.getValue().getClass() == String.class){ - createStringTagCompound(aStack, "mEntityTag", (String) e.getKey(), (String) e.getValue()); - } - else if (e.getValue().getClass() == Boolean.class || e.getValue().getClass() == boolean.class){ - createBooleanTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Boolean) e.getValue()); - } - else if (e.getValue().getClass() == Integer.class || e.getValue().getClass() == int.class){ - createIntegerTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Integer) e.getValue()); - } - else if (e.getValue().getClass() == Double.class || e.getValue().getClass() == double.class){ - createDoubleTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Double) e.getValue()); - } - else if (e.getValue().getClass() == Long.class || e.getValue().getClass() == long.class){ - createLongTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Long) e.getValue()); - } - else if (e.getValue().getClass() == Float.class || e.getValue().getClass() == float.class){ - createFloatTagCompound(aStack, "mEntityTag", (String) e.getKey(), (Float) e.getValue()); - } - else { - - - } - - } - return true; - } - } - } - return false; - } catch (Throwable t) { - return false; - } - } - - public static NBTTagCompound getEntityCustomData(Entity aEntity){ - return ReflectionUtils.getField(aEntity, "customEntityData"); - } - - public static boolean setEntityCustomData(Entity aEntity, NBTTagCompound aTag){ - return ReflectionUtils.setField(aEntity, "customEntityData", aTag); - } - -} diff --git a/src/Java/gtPlusPlus/core/util/networking/NetworkUtils.java b/src/Java/gtPlusPlus/core/util/networking/NetworkUtils.java deleted file mode 100644 index ce2888ef29..0000000000 --- a/src/Java/gtPlusPlus/core/util/networking/NetworkUtils.java +++ /dev/null @@ -1,153 +0,0 @@ -package gtPlusPlus.core.util.networking; - -import java.io.*; -import java.net.*; -import java.util.Enumeration; - -import gtPlusPlus.api.objects.Logger; - -public class NetworkUtils { - - public static String getContentFromURL(final String args) { - if (checkNetworkIsAvailableWithValidInterface()){ - try { - URL url; - // get URL content - url = new URL(args); - final URLConnection conn = url.openConnection(); - // open the stream and put it into BufferedReader - final BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String inputLine; - String tempLine = null; - while ((inputLine = br.readLine()) != null) { - tempLine = inputLine; - } - br.close(); - return tempLine; - } - catch (final MalformedURLException e) { - Logger.INFO("Bad URL for Version Check."); - } - catch (final IOException e) { - Logger.INFO("IOException during Version Check."); - } - } - Logger.INFO("Network Not Available during Version Check."); - return "offline"; - } - - public static boolean checkNetworkIsAvailableWithValidInterface(){ - try { - if (hasValidNetworkInterface()){ - if (checkAddressWithTimeout("http://www.google.com", 10) || - checkAddressWithTimeout("http://www.baidu.com", 10) || - checkAddressWithTimeout("https://github.com/draknyte1/GTplusplus", 10) || - checkAddressWithTimeout("www.yahoo.com", 10)/* || - netIsAvailableGoogle() || - netIsAvailableBaidu() || - netIsAvailableGithub() || - netIsAvailableOther()*/){ - return true; - } - else { - Logger.INFO("No sites responded to network connectivity test."); - } - } - else { - Logger.INFO("Network Adapter was not valid."); - } - } - catch (SocketException e) {} - return false; - } - - private static boolean netIsAvailableGoogle() { - try { - final URL url = new URL("http://www.google.com"); - final URLConnection conn = url.openConnection(); - conn.connect(); - return true; - } catch (final MalformedURLException e) { - throw new RuntimeException(e); - } catch (final IOException e) { - return false; - } - } - - private static boolean netIsAvailableBaidu() { - try { - final URL url = new URL("http://www.baidu.com"); - final URLConnection conn = url.openConnection(); - conn.connect(); - return true; - } catch (final MalformedURLException e) { - throw new RuntimeException(e); - } catch (final IOException e) { - return false; - } - } - - private static boolean netIsAvailableGithub() { - try { - final URL url = new URL("https://github.com/draknyte1/GTplusplus"); - final URLConnection conn = url.openConnection(); - conn.connect(); - return true; - } catch (final MalformedURLException e) { - throw new RuntimeException(e); - } catch (final IOException e) { - return false; - } - } - - private static boolean netIsAvailableOther() { - try { - final int timeout = 200; - final InetAddress[] addresses = InetAddress.getAllByName("www.yahoo.com"); - for (final InetAddress address : addresses) { - if (address.isReachable(timeout)) { - return true; - } - return false; - } - } catch (final Exception e) { - return false; - } - return false; - } - - private static boolean checkAddressWithTimeout(String URL, int timeout) { - - try { - InetAddress.getByName(URL).isReachable(3000); //Replace with your name - return true; - } catch (Exception e) { - return false; - } - - /*try { - final InetAddress[] addresses = InetAddress.getAllByName(URL); - for (final InetAddress address : addresses) { - if (address.isReachable(timeout)) { - return true; - } - return false; - } - } catch (final Exception e) { - return false; - } - return false;*/ - } - - private static boolean hasValidNetworkInterface() throws SocketException{ - final Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - while (interfaces.hasMoreElements()) { - final NetworkInterface interf = interfaces.nextElement(); - if (interf.isUp() && !interf.isLoopback()) { - return true; - } - } - return false; - } - -} diff --git a/src/Java/gtPlusPlus/core/util/particles/BlockBreakParticles.java b/src/Java/gtPlusPlus/core/util/particles/BlockBreakParticles.java deleted file mode 100644 index a1a46b39f4..0000000000 --- a/src/Java/gtPlusPlus/core/util/particles/BlockBreakParticles.java +++ /dev/null @@ -1,17 +0,0 @@ -package gtPlusPlus.core.util.particles; - -import gtPlusPlus.xmod.forestry.HANDLER_FR; -import net.minecraft.block.Block; -import net.minecraft.world.World; - -public class BlockBreakParticles { - - public BlockBreakParticles(final World world, final int x, final int y, final int z, final Block block){ - try { - HANDLER_FR.createBlockBreakParticles(world, x, y, z, block); - } catch (final Throwable T){ - - } - } - -} diff --git a/src/Java/gtPlusPlus/core/util/particles/EntityParticleFXMysterious.java b/src/Java/gtPlusPlus/core/util/particles/EntityParticleFXMysterious.java deleted file mode 100644 index 97103b636b..0000000000 --- a/src/Java/gtPlusPlus/core/util/particles/EntityParticleFXMysterious.java +++ /dev/null @@ -1,17 +0,0 @@ -package gtPlusPlus.core.util.particles; - -import net.minecraft.client.particle.EntityAuraFX; -import net.minecraft.world.World; - -public class EntityParticleFXMysterious extends EntityAuraFX -{ - public EntityParticleFXMysterious(final World parWorld, - final double parX, final double parY, final double parZ, - final double parMotionX, final double parMotionY, final double parMotionZ) - { - super(parWorld, parX, parY, parZ, parMotionX, parMotionY, parMotionZ); - this.setParticleTextureIndex(82); // same as happy villager - this.particleScale = 2.0F; - this.setRBGColorF(0x88, 0x00, 0x88); - } -} diff --git a/src/Java/gtPlusPlus/core/util/player/PlayerUtils.java b/src/Java/gtPlusPlus/core/util/player/PlayerUtils.java deleted file mode 100644 index 32488f074d..0000000000 --- a/src/Java/gtPlusPlus/core/util/player/PlayerUtils.java +++ /dev/null @@ -1,175 +0,0 @@ -package gtPlusPlus.core.util.player; - -import java.util.*; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import gtPlusPlus.core.util.Utils; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.World; - -public class PlayerUtils { - - public static void messagePlayer(final EntityPlayer P, final String S){ - gregtech.api.util.GT_Utility.sendChatToPlayer(P, S); - } - - public static EntityPlayer getPlayer(final String name){ - try{ - final List i = new ArrayList<>(); - final Iterator iterator = MinecraftServer.getServer().getConfigurationManager().playerEntityList.iterator(); - while (iterator.hasNext()) { - i.add((iterator.next())); - } - for (final EntityPlayer temp : i) { - if (temp.getDisplayName().toLowerCase().equals(name.toLowerCase())){ - return temp; - } - } - } - catch(final Throwable e){} - return null; - } - - public static EntityPlayer getPlayerOnServerFromUUID(final UUID parUUID){ - if (parUUID == null) - { - return null; - } - final List allPlayers = MinecraftServer.getServer().getConfigurationManager().playerEntityList; - for (final EntityPlayerMP player : allPlayers) - { - if (player.getUniqueID().equals(parUUID)) - { - return player; - } - } - return null; - } - - //Not Clientside - public static EntityPlayer getPlayerInWorld(final World world, final String Name){ - final List i = world.playerEntities; - final Minecraft mc = Minecraft.getMinecraft(); - try{ - for (final EntityPlayer temp : i) { - if (temp.getDisplayName().toLowerCase().equals(Name.toLowerCase())){ - return temp; - } - } - } - catch(final NullPointerException e){} - return null; - } - - public static boolean isPlayerOP(final EntityPlayer player){ - if (player.canCommandSenderUseCommand(2, "")){ - return true; - } - return false; - } - - //Not Clientside - public static ItemStack getItemStackInPlayersHand(final World world, final String Name){ - final EntityPlayer thePlayer = getPlayer(Name); - ItemStack heldItem = null; - try{heldItem = thePlayer.getHeldItem(); - }catch(final NullPointerException e){return null;} - if (heldItem != null){ - return heldItem; - } - return null; - } - - @SideOnly(Side.CLIENT) - public static ItemStack getItemStackInPlayersHand(){ - final Minecraft mc = Minecraft.getMinecraft(); - ItemStack heldItem = null; - try{heldItem = mc.thePlayer.getHeldItem(); - }catch(final NullPointerException e){return null;} - if (heldItem != null){ - return heldItem; - } - return null; - } - - @SideOnly(Side.SERVER) - public static ItemStack getItemStackInPlayersHand(final EntityPlayer player){ - ItemStack heldItem = null; - try{heldItem = player.getHeldItem(); - }catch(final NullPointerException e){ - e.printStackTrace(); - return null; - } - if (heldItem != null){ - return heldItem; - } - return null; - } - - @SideOnly(Side.CLIENT) - public static Item getItemInPlayersHandClient(){ - final Minecraft mc = Minecraft.getMinecraft(); - Item heldItem = null; - - try{heldItem = mc.thePlayer.getHeldItem().getItem(); - }catch(final NullPointerException e){return null;} - - if (heldItem != null){ - return heldItem; - } - - return null; - } - - public static Item getItemInPlayersHand(final EntityPlayer player){ - Item heldItem = null; - try{ - heldItem = player.getHeldItem().getItem(); - }catch(final NullPointerException e){return null;} - - if (heldItem != null){ - return heldItem; - } - return null; - } - - public final static EntityPlayer getPlayerEntityByName(final String aPlayerName){ - final EntityPlayer player = PlayerUtils.getPlayer(aPlayerName); - if (player != null){ - return player; - } - return null; - } - - public final static UUID getPlayersUUIDByName(final String aPlayerName){ - final EntityPlayer player = PlayerUtils.getPlayer(aPlayerName); - if (player != null){ - return player.getUniqueID(); - } - return null; - } - - @SideOnly(Side.CLIENT) - public static final boolean isPlayerAlkalus(){ - if (Utils.isServer()){ - return false; - } - return isPlayerAlkalus(Minecraft.getMinecraft().thePlayer); - } - - public static final boolean isPlayerAlkalus(EntityPlayer player){ - if (player != null){ - if (player.getDisplayName().toLowerCase().equals("draknyte1") || player.getDisplayName().toLowerCase().equals("alkalus")){ - return true; - } - } - return false; - } - -} diff --git a/src/Java/gtPlusPlus/core/util/player/UtilsMining.java b/src/Java/gtPlusPlus/core/util/player/UtilsMining.java deleted file mode 100644 index 4f0402a18e..0000000000 --- a/src/Java/gtPlusPlus/core/util/player/UtilsMining.java +++ /dev/null @@ -1,214 +0,0 @@ -package gtPlusPlus.core.util.player; - -import gtPlusPlus.api.objects.Logger; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -public class UtilsMining { - - private static boolean durabilityDamage = false; - private static ItemStack stack; - - public static Boolean canPickaxeBlock(final Block currentBlock, final World currentWorld){ - String correctTool = ""; - if (!currentWorld.isRemote){ - try { - correctTool = currentBlock.getHarvestTool(0); - //Utils.LOG_WARNING(correctTool); - if (correctTool.equals("pickaxe")){ - return true;} - } catch (final NullPointerException e){ - return false;} - } - return false; - } - - private static void removeBlockAndDropAsItem(final World world, final int X, final int Y, final int Z){ - try { - final Block block = world.getBlock(X, Y, Z); - if (canPickaxeBlock(block, world)){ - if((block != Blocks.bedrock) && (block.getBlockHardness(world, X, Y, Z) != -1) && (block.getBlockHardness(world, X, Y, Z) <= 100) && (block != Blocks.water) && (block != Blocks.lava)){ - block.dropBlockAsItem(world, X, Y, Z, world.getBlockMetadata(X, Y, Z), 0); - world.setBlockToAir(X, Y, Z); - - } - else { - Logger.WARNING("Incorrect Tool for mining this block."); - } - } - } catch (final NullPointerException e){ - - } - } - - /*public static void customMine(World world, String FACING, EntityPlayer aPlayer){ - - float DURABILITY_LOSS = 0; - if (!world.isRemote){ - int X = 0; - int Y = 0; - int Z = 0; - - if (FACING.equals("below") || FACING.equals("above")){ - - //Set Player Facing - X = (int) aPlayer.posX; - Utils.LOG_WARNING("Setting Variable X: "+X); - if (FACING.equals("above")){ - Z = (int) aPlayer.posY + 1; - Utils.LOG_WARNING("Setting Variable Y: "+Y); - } - else { - Z = (int) aPlayer.posY - 1; - Utils.LOG_WARNING("Setting Variable Y: "+Y);} - Z = (int) aPlayer.posZ; - Utils.LOG_WARNING("Setting Variable Z: "+Z); - - DURABILITY_LOSS = 0; - for(int i = -2; i < 3; i++) { - for(int j = -2; j < 3; j++) { - for(int k = -2; k < 3; k++) { -// float dur = calculateDurabilityLoss(world, X + i, Y + k, Z + j); -// DURABILITY_LOSS = (DURABILITY_LOSS + dur); -// Utils.LOG_WARNING("Added Loss: "+dur); - removeBlockAndDropAsItem(world, X + i, Y + k, Z + j); - } - } - } - } - - else if (FACING.equals("facingEast") || FACING.equals("facingWest")){ - - //Set Player Facing - Z = (int) aPlayer.posZ; - Y = (int) aPlayer.posY; - if (FACING.equals("facingEast")){ - X = (int) aPlayer.posX + 1;} - else { - X = (int) aPlayer.posX - 1;} - - - DURABILITY_LOSS = 0; - for(int i = -1; i < 2; i++) { - for(int j = -1; j < 2; j++) { - for(int k = -1; k < 2; k++) { - float dur = calculateDurabilityLoss(world, X+k, Y + i, Z + j); - DURABILITY_LOSS = (DURABILITY_LOSS + dur); - Utils.LOG_WARNING("Added Loss: "+dur); - removeBlockAndDropAsItem(world, X+k, Y + i, Z + j); - } - } - } - } - - else if (FACING.equals("facingNorth") || FACING.equals("facingSouth")){ - - //Set Player Facing - X = (int) aPlayer.posX; - Y = (int) aPlayer.posY; - - if (FACING.equals("facingNorth")){ - Z = (int) aPlayer.posZ + 1;} - else { - Z = (int) aPlayer.posZ - 1;} - - DURABILITY_LOSS = 0; - for(int i = -1; i < 2; i++) { - for(int j = -1; j < 2; j++) { - for(int k = -1; k < 2; k++) { - float dur = calculateDurabilityLoss(world, X + j, Y + i, Z+k); - DURABILITY_LOSS = (DURABILITY_LOSS + dur); - Utils.LOG_WARNING("Added Loss: "+dur); - removeBlockAndDropAsItem(world, X + j, Y + i, Z+k); - } - } - } - } - - //Set Durability damage to the item - if (durabilityDamage == true){ - Utils.LOG_WARNING("Total Loss: "+(int)DURABILITY_LOSS); - if (stack.getItemDamage() < (stack.getMaxDamage()-DURABILITY_LOSS)){ - stack.damageItem((int) DURABILITY_LOSS, aPlayer); - } - } - DURABILITY_LOSS = 0; - } - }*/ - - - public static boolean getBlockType(final Block block, final World world, final int[] xyz, final int miningLevel){ - final String LIQUID = "liquid"; - final String BLOCK = "block"; - final String ORE = "ore"; - final String AIR = "air"; - String blockClass = ""; - - if (world.isRemote){ - return false; - } - - if (block == Blocks.end_stone) { - return true; - } - if (block == Blocks.stone) { - return true; - } - if (block == Blocks.sandstone) { - return true; - } - if (block == Blocks.netherrack) { - return true; - } - if (block == Blocks.nether_brick) { - return true; - } - if (block == Blocks.nether_brick_stairs) { - return true; - } - if (block == Blocks.nether_brick_fence) { - return true; - } - if (block == Blocks.glowstone) { - return true; - } - - - - try { - blockClass = block.getClass().toString().toLowerCase(); - Logger.WARNING(blockClass); - if (blockClass.toLowerCase().contains(LIQUID)){ - Logger.WARNING(block.toString()+" is a Liquid."); - return false; - } - else if (blockClass.toLowerCase().contains(ORE)){ - Logger.WARNING(block.toString()+" is an Ore."); - return true; - } - else if (block.getHarvestLevel(world.getBlockMetadata(xyz[0], xyz[1], xyz[2])) >= miningLevel){ - Logger.WARNING(block.toString()+" is minable."); - return true; - } - else if (blockClass.toLowerCase().contains(AIR)){ - Logger.WARNING(block.toString()+" is Air."); - return false; - } - else if (blockClass.toLowerCase().contains(BLOCK)){ - Logger.WARNING(block.toString()+" is a block of some kind."); - return false; - } - else { - Logger.WARNING(block.toString()+" is mystery."); - return false; - } - } - catch(final NullPointerException e){ - return false; - } - } - - -} diff --git a/src/Java/gtPlusPlus/core/util/recipe/RecipeUtils.java b/src/Java/gtPlusPlus/core/util/recipe/RecipeUtils.java deleted file mode 100644 index cdb8255231..0000000000 --- a/src/Java/gtPlusPlus/core/util/recipe/RecipeUtils.java +++ /dev/null @@ -1,481 +0,0 @@ -package gtPlusPlus.core.util.recipe; - -import java.util.*; - -import cpw.mods.fml.common.registry.GameRegistry; -import gregtech.api.util.GT_ModHandler; -import gtPlusPlus.api.objects.Logger; -import gtPlusPlus.core.handler.COMPAT_HANDLER; -import gtPlusPlus.core.handler.Recipes.LateRegistrationHandler; -import gtPlusPlus.core.handler.Recipes.RegistrationHandler; -import gtPlusPlus.core.lib.CORE; -import gtPlusPlus.core.util.item.ItemUtils; -import gtPlusPlus.core.util.recipe.shapeless.ShapelessUtils; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; -import net.minecraft.item.crafting.IRecipe; -import net.minecraftforge.oredict.*; - -public class RecipeUtils { - - public static boolean recipeBuilder(final Object slot_1, final Object slot_2, final Object slot_3, final Object slot_4, final Object slot_5, final Object slot_6, final Object slot_7, final Object slot_8, final Object slot_9, final ItemStack resultItem){ - - final ArrayList validSlots = new ArrayList<>(); - if (resultItem == null){ - Logger.WARNING("Found a recipe with an invalid output, yet had a valid inputs. Skipping."); - return false; - } - - if ((slot_1 == null) && (slot_2 == null) && (slot_3 == null) && - (slot_4 == null) && (slot_5 == null) && (slot_6 == null) && - (slot_7 == null) && (slot_8 == null) && (slot_9 == null)){ - Logger.WARNING("Found a recipe with 0 inputs, yet had a valid output."); - Logger.WARNING("Error found while adding a recipe for: "+resultItem.getDisplayName()+" | Please report this issue on Github."); - RegistrationHandler.recipesFailed++; - return false; - } - - //Utils.LOG_WARNING("Trying to add a recipe for "+resultItem.toString()); - String a,b,c,d,e,f,g,h,i; - if (slot_1 == null){ a = " ";} else { a = "1";validSlots.add('1');validSlots.add(slot_1);} - Logger.WARNING(a); - if (slot_2 == null){ b = " ";} else { b = "2";validSlots.add('2');validSlots.add(slot_2);} - Logger.WARNING(b); - if (slot_3 == null){ c = " ";} else { c = "3";validSlots.add('3');validSlots.add(slot_3);} - Logger.WARNING(c); - if (slot_4 == null){ d = " ";} else { d = "4";validSlots.add('4');validSlots.add(slot_4);} - Logger.WARNING(d); - if (slot_5 == null){ e = " ";} else { e = "5";validSlots.add('5');validSlots.add(slot_5);} - Logger.WARNING(e); - if (slot_6 == null){ f = " ";} else { f = "6";validSlots.add('6');validSlots.add(slot_6);} - Logger.WARNING(f); - if (slot_7 == null){ g = " ";} else { g = "7";validSlots.add('7');validSlots.add(slot_7);} - Logger.WARNING(g); - if (slot_8 == null){ h = " ";} else { h = "8";validSlots.add('8');validSlots.add(slot_8);} - Logger.WARNING(h); - if (slot_9 == null){ i = " ";} else { i = "9";validSlots.add('9');validSlots.add(slot_9);} - Logger.WARNING(i); - - - Logger.ERROR("_______"); - final String lineOne = a+b+c; - Logger.ERROR("|"+a+"|"+b+"|"+c+"|"); - Logger.ERROR("_______"); - final String lineTwo = d+e+f; - Logger.ERROR("|"+d+"|"+e+"|"+f+"|"); - Logger.ERROR("_______"); - final String lineThree = g+h+i; - Logger.ERROR("|"+g+"|"+h+"|"+i+"|"); - Logger.ERROR("_______"); - - validSlots.add(0, lineOne); - validSlots.add(1, lineTwo); - validSlots.add(2, lineThree); - boolean advancedLog = false; - if (CORE.DEBUG){ - advancedLog = true; - } - if (advancedLog){ - int j = 0; - final int l = validSlots.size(); - Logger.WARNING("l:"+l); - while (j <= l) { - Logger.WARNING("j:"+j); - if (j <= 2){ - Logger.WARNING("ArrayList Values: "+validSlots.get(j)); - Logger.WARNING("Adding 1."); - j++; - } - else if (j == l){ - Logger.WARNING("Done iteration."); - break; - } - else { - Logger.WARNING("ArrayList Values: '"+validSlots.get(j)+"' "+validSlots.get(j+1)); - if (j < (l-2)){ - Logger.WARNING("Adding 2."); - j=j+2; - } - else { - Logger.WARNING("Done iteration."); - break; - } - } - if ((validSlots.get(j) instanceof String) || (validSlots.get(j) instanceof ItemStack)){ - //Utils.LOG_WARNING("Is Valid: "+validSlots.get(j)); - } - } - } - - try { - GameRegistry.addRecipe(new ShapedOreRecipe(resultItem.copy(), validSlots.toArray())); - //Utils.LOG_WARNING("Success! Added a recipe for "+resultItem.getDisplayName()); - if (!COMPAT_HANDLER.areInitItemsLoaded){ - RegistrationHandler.recipesSuccess++; - } - else { - LateRegistrationHandler.recipesSuccess++; - } - return true; - } - catch(RuntimeException k){ - //k.getMessage(); - //k.getClass(); - //k.printStackTrace(); - //k.getLocalizedMessage(); - Logger.INFO("@@@: Invalid Recipe detected for: "+resultItem.getUnlocalizedName()); - if (!COMPAT_HANDLER.areInitItemsLoaded){ - RegistrationHandler.recipesFailed++; - } - else { - LateRegistrationHandler.recipesFailed++; - } - return false; - } - } - - public static void shapelessBuilder(final ItemStack Output, final Object slot_1, final Object slot_2, final Object slot_3, final Object slot_4, final Object slot_5, final Object slot_6, final Object slot_7, final Object slot_8, final Object slot_9){ - //Item output_ITEM = Output.getItem(); - - final ArrayList validSlots = new ArrayList<>(); - - Logger.WARNING("Trying to add a recipe for "+Output.toString()); - String a,b,c,d,e,f,g,h,i; - if (slot_1 == null){ a = " ";} else { a = "1";validSlots.add('1');validSlots.add(slot_1);} - Logger.WARNING(a); - if (slot_2 == null){ b = " ";} else { b = "2";validSlots.add('2');validSlots.add(slot_2);} - Logger.WARNING(b); - if (slot_3 == null){ c = " ";} else { c = "3";validSlots.add('3');validSlots.add(slot_3);} - Logger.WARNING(c); - if (slot_4 == null){ d = " ";} else { d = "4";validSlots.add('4');validSlots.add(slot_4);} - Logger.WARNING(d); - if (slot_5 == null){ e = " ";} else { e = "5";validSlots.add('5');validSlots.add(slot_5);} - Logger.WARNING(e); - if (slot_6 == null){ f = " ";} else { f = "6";validSlots.add('6');validSlots.add(slot_6);} - Logger.WARNING(f); - if (slot_7 == null){ g = " ";} else { g = "7";validSlots.add('7');validSlots.add(slot_7);} - Logger.WARNING(g); - if (slot_8 == null){ h = " ";} else { h = "8";validSlots.add('8');validSlots.add(slot_8);} - Logger.WARNING(h); - if (slot_9 == null){ i = " ";} else { i = "9";validSlots.add('9');validSlots.add(slot_9);} - Logger.WARNING(i); - - - Logger.ERROR("_______"); - Logger.ERROR("|"+a+"|"+b+"|"+c+"|"); - Logger.ERROR("_______"); - Logger.ERROR("|"+d+"|"+e+"|"+f+"|"); - Logger.ERROR("_______"); - Logger.ERROR("|"+g+"|"+h+"|"+i+"|"); - Logger.ERROR("_______"); - - validSlots.add(0, a); - validSlots.add(1, b); - validSlots.add(2, c); - validSlots.add(3, d); - validSlots.add(4, e); - validSlots.add(5, f); - validSlots.add(6, g); - validSlots.add(7, h); - validSlots.add(8, i); - - try { - //GameRegistry.addRecipe(new ShapelessOreRecipe(Output, outputAmount), (Object[]) validSlots.toArray()); - GameRegistry.addRecipe(new ShapelessOreRecipe(Output, validSlots.toArray())); - //GameRegistry.addShapelessRecipe(new ItemStack(output_ITEM, 1), new Object[] {slot_1, slot_2}); - Logger.WARNING("Success! Added a recipe for "+Output.getDisplayName()); - RegistrationHandler.recipesSuccess++; - } - catch(final RuntimeException k){ - k.getMessage(); - k.getClass(); - k.printStackTrace(); - k.getLocalizedMessage(); - Logger.WARNING("@@@: Invalid Recipe detected for: "+Output.getUnlocalizedName()); - RegistrationHandler.recipesFailed++; - } - - - //GameRegistry.addShapelessRecipe(new ItemStack(output_ITEM, 1), new Object[] {slot_1, slot_2}); - } - - public static void recipeBuilder(final Object[] array, final ItemStack outPut) { - Logger.SPECIFIC_WARNING("object Array - recipeBuilder", "Attempting to build a recipe using an object array as an input, splitting it, then running the normal recipeBuilder() method.", 396); - Object a=null; - Object b=null; - Object c=null; - Object d=null; - Object e=null; - Object f=null; - Object g=null; - Object h=null; - Object i=null; - for(int z =0; z <= array.length; z++){ - array[z].toString(); - switch(z) - { - case 0: - a = array[z]; - break; - case 1: - b = array[z]; - break; - case 2: - c = array[z]; - break; - case 3: - d = array[z]; - break; - case 4: - e = array[z]; - break; - case 5: - f = array[z]; - break; - case 6: - g = array[z]; - break; - case 7: - h = array[z]; - break; - case 8: - i = array[z]; - break; - default: - break; - } - recipeBuilder(a, b, c, d, e, f, g, h, i, outPut); - } - } - - public static boolean removeCraftingRecipe(Object x){ - if (null == x){return false;} - if (x instanceof String){ - final Item R = ItemUtils.getItem((String) x); - if (R != null){ - x = R; - } - else { - return false; - } - } - if ((x instanceof Item) || (x instanceof ItemStack)){ - if (x instanceof Item){ - final ItemStack r = new ItemStack((Item) x); - Logger.WARNING("Removing Recipe for "+r.getUnlocalizedName()); - } - else { - Logger.WARNING("Removing Recipe for "+((ItemStack) x).getUnlocalizedName()); - } - if (x instanceof ItemStack){ - final Item r = ((ItemStack) x).getItem(); - if (null != r){ - x = r; - } - else { - Logger.WARNING("Recipe removal failed - Tell Alkalus."); - return false; - } - } - if (RecipeUtils.attemptRecipeRemoval((Item) x)){ - Logger.WARNING("Recipe removal successful"); - return true; - } - Logger.WARNING("Recipe removal failed - Tell Alkalus."); - return false; - } - return false; - } - - private static boolean attemptRecipeRemoval(final Item I){ - Logger.WARNING("Create list of recipes."); - final List recipes = CraftingManager.getInstance().getRecipeList(); - final Iterator items = recipes.iterator(); - Logger.WARNING("Begin list iteration."); - while (items.hasNext()) { - final ItemStack is = items.next().getRecipeOutput(); - if ((is != null) && (is.getItem() == I)){ - items.remove(); - Logger.WARNING("Remove a recipe with "+I.getUnlocalizedName()+" as output."); - continue; - } - } - Logger.WARNING("All recipes should be gone?"); - if (!items.hasNext()){ - Logger.WARNING("We iterated once, let's try again to double check."); - final Iterator items2 = recipes.iterator(); - while (items2.hasNext()) { - final ItemStack is = items2.next().getRecipeOutput(); - if ((is != null) && (is.getItem() == I)){ - items.remove(); - Logger.WARNING("REMOVING MISSED RECIPE - RECHECK CONSTRUCTORS"); - return true; - } - } - Logger.WARNING("Should be all gone now after double checking, so return true."); - return true; - } - Logger.WARNING("Return false, because something went wrong."); - return false; - } - - - - public static boolean addShapedGregtechRecipeForTypes( - final Object InputItem1, final Object InputItem2, final Object InputItem3, - final Object InputItem4, final Object InputItem5, final Object InputItem6, - final Object InputItem7, final Object InputItem8, final Object InputItem9, - final ItemStack OutputItem){ - - int using = 0, recipeSlotCurrent = 0; - boolean[] hasMultiStack = new boolean[9]; - boolean inUse[] = {false, false, false}; - ItemStack array[][] = new ItemStack[3][9]; - - Object[] inputs = { - InputItem1, InputItem2, InputItem3, - InputItem4, InputItem5, InputItem6, - InputItem7, InputItem8, InputItem9}; - - for (Object o : inputs){ - if (o.getClass().isArray()){ - if (inUse[using] == false){ - inUse[using] = true; - array[using] = (ItemStack[]) o; - hasMultiStack[recipeSlotCurrent] = true; - using++; - } - } - else { - hasMultiStack[recipeSlotCurrent] = false; - } - recipeSlotCurrent++; - } - - int using2 = 0; - for (boolean t : inUse){ - - if (t){ - if (array[using2] != null){ - //addShapedGregtechRecipe - } - } - using2++; - } - - - return false; - } - - - - public static boolean addShapedGregtechRecipe( - final Object InputItem1, final Object InputItem2, final Object InputItem3, - final Object InputItem4, final Object InputItem5, final Object InputItem6, - final Object InputItem7, final Object InputItem8, final Object InputItem9, - final ItemStack OutputItem){ - - Object[] o = { - InputItem1, InputItem2, InputItem3, - InputItem4, InputItem5, InputItem6, - InputItem7, InputItem8, InputItem9 - }; - - if (addShapedGregtechRecipe(o, OutputItem)){ - return true; - } - else if (recipeBuilder( - InputItem1, InputItem2, InputItem3, - InputItem4, InputItem5, InputItem6, - InputItem7, InputItem8, InputItem9, - OutputItem)){ - return true; - } - else { - if (OutputItem != null){ - Logger.WARNING("Adding recipe for "+OutputItem.getDisplayName()+" failed. Error 62."); - } - RegistrationHandler.recipesFailed++; - return false; - } - } - - public static boolean addShapedGregtechRecipe(final Object[] inputs, ItemStack output){ - - if (inputs.length != 9){ - Logger.WARNING("Input array for "+output.getDisplayName()+" does not equal 9. "+inputs.length+" is the actual size."); - - RegistrationHandler.recipesFailed++; - return false; - } - - for (int x=0;x<9;x++){ - if (inputs[x] == null){ - inputs[x] = " "; - Logger.WARNING("Input slot "+x+" changed from NULL to a blank space."); - } - else if (!(inputs[x] instanceof ItemStack) && !(inputs[x] instanceof String)){ - if (output != null){ - Logger.WARNING("Invalid Item inserted into inputArray. Item:"+output.getDisplayName()+" has a bad recipe. Please report to Alkalus."); - - RegistrationHandler.recipesFailed++; - return false; - } - else { - Logger.WARNING("Output is Null for a recipe. Report to Alkalus."); - output = ItemUtils.getItemStackOfAmountFromOreDict("sadibasdkjnad", 1); - } - } - } - - if (GT_ModHandler.addCraftingRecipe(output, - GT_ModHandler.RecipeBits.DISMANTLEABLE | GT_ModHandler.RecipeBits.NOT_REMOVABLE | - GT_ModHandler.RecipeBits.REVERSIBLE | GT_ModHandler.RecipeBits.BUFFERED, - new Object[]{"ABC", "DEF", "GHI", - 'A', inputs[0], - 'B', inputs[1], - 'C', inputs[2], - 'D', inputs[3], - 'E', inputs[4], - 'F', inputs[5], - 'G', inputs[6], - 'H', inputs[7], - 'I', inputs[8]})){ - Logger.WARNING("Success! Added a recipe for "+output.getDisplayName()); - RegistrationHandler.recipesSuccess++; - return true; - } - else { - if (output != null){ - Logger.WARNING("Adding recipe for "+output.getDisplayName()+" failed. Error 61."); - } - return false; - } - } - - public static boolean addShapelessGregtechRecipe(final Object[] inputItems, final ItemStack OutputItem){ - //Catch Invalid Recipes - if (inputItems.length > 9 || inputItems.length < 1){ - if (OutputItem != null){ - Logger.WARNING("Invalid input array for shapeless recipe, which should output "+OutputItem.getDisplayName()); - } - return false; - } - //let gregtech handle shapeless recipes. - if (GT_ModHandler.addShapelessCraftingRecipe(OutputItem, inputItems)){ - return true; - } - return false; - } - - public static ItemStack getItemStackFromOreDict(final String oredictName){ - final ArrayList oreDictList = OreDictionary.getOres(oredictName); - return oreDictList.get(0); - } - - public static boolean buildShapelessRecipe(final ItemStack output, final Object[] input){ - return ShapelessUtils.addShapelessRecipe(output, input); - } - -} diff --git a/src/Java/gtPlusPlus/core/util/recipe/shapeless/ShapelessUtils.java b/src/Java/gtPlusPlus/core/util/recipe/shapeless/ShapelessUtils.java deleted file mode 100644 index 29ca257134..0000000000 --- a/src/Java/gtPlusPlus/core/util/recipe/shapeless/ShapelessUtils.java +++ /dev/null @@ -1,55 +0,0 @@ -package gtPlusPlus.core.util.recipe.shapeless; - -import java.util.ArrayList; - -import gtPlusPlus.api.objects.Logger; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; -import net.minecraft.item.crafting.ShapelessRecipes; - -public class ShapelessUtils { - - - public static boolean addShapelessRecipe(final ItemStack output, final Object ... params) - { - final ArrayList arraylist = new ArrayList<>(); - final Object[] aobject = params; - final int i = params.length; - - for (int j = 0; j < i; ++j) - { - final Object object1 = aobject[j]; - - if (object1 instanceof ItemStack) - { - arraylist.add(((ItemStack)object1).copy()); - } - else if (object1 instanceof Item) - { - arraylist.add(new ItemStack((Item)object1)); - } - else - { - if ((object1 == null)) - { - Logger.INFO(("Invalid shapeless input, ignoring!")); - } - else if (!(object1 instanceof Block) && (object1 != null)) - { - Logger.INFO(("Invalid shapeless recipe!")); - return false; - } - else { - arraylist.add(new ItemStack((Block)object1)); - } - } - } - CraftingManager.getInstance().getRecipeList().add(new ShapelessRecipes(output, arraylist)); - //CraftingManager.getInstance().addShapelessRecipe(output, arraylist); - return true; - } - - -} diff --git a/src/Java/gtPlusPlus/core/util/reflect/AddGregtechRecipe.java b/src/Java/gtPlusPlus/core/util/reflect/AddGregtechRecipe.java index 3542ea6143..aee1c4dfec 100644 --- a/src/Java/gtPlusPlus/core/util/reflect/AddGregtechRecipe.java +++ b/src/Java/gtPlusPlus/core/util/reflect/AddGregtechRecipe.java @@ -8,8 +8,8 @@ import gregtech.api.enums.GT_Values; import gregtech.api.interfaces.internal.IGT_RecipeAdder; import gtPlusPlus.core.lib.CORE; import gtPlusPlus.core.util.Utils; -import gtPlusPlus.core.util.fluid.FluidUtils; -import gtPlusPlus.core.util.item.ItemUtils; +import gtPlusPlus.core.util.minecraft.FluidUtils; +import gtPlusPlus.core.util.minecraft.ItemUtils; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; diff --git a/src/Java/gtPlusPlus/core/util/reflect/ReflectionUtils.java b/src/Java/gtPlusPlus/core/util/reflect/ReflectionUtils.java index a0968fd5c1..ac7b8492e2 100644 --- a/src/Java/gtPlusPlus/core/util/reflect/ReflectionUtils.java +++ b/src/Java/gtPlusPlus/core/util/reflect/ReflectionUtils.java @@ -14,7 +14,7 @@ import net.minecraft.client.Minecraft; public class ReflectionUtils { - public static Field getField(final Class clazz, final String fieldName) throws NoSuchFieldException { + public static Field getField(final Class clazz, final String fieldName) throws NoSuchFieldException { try { Field k = clazz.getDeclaredField(fieldName); makeAccessible(k); @@ -172,10 +172,10 @@ public class ReflectionUtils { public static boolean invoke(Object objectInstance, String methodName, Class[] parameters, Object[] values){ if (objectInstance == null || methodName == null || parameters == null || values == null){ - Logger.REFLECTION("Null value when trying to Dynamically invoke "+methodName+" on an object of type: "+objectInstance.getClass().getName()); + //Logger.REFLECTION("Null value when trying to Dynamically invoke "+methodName+" on an object of type: "+objectInstance.getClass().getName()); return false; } - Class mLocalClass = (objectInstance instanceof Class ? (Class) objectInstance : objectInstance.getClass()); + Class mLocalClass = (objectInstance instanceof Class ? (Class) objectInstance : objectInstance.getClass()); Logger.REFLECTION("Trying to invoke "+methodName+" on an instance of "+mLocalClass.getCanonicalName()+"."); try { Method mInvokingMethod = mLocalClass.getDeclaredMethod(methodName, parameters); @@ -201,6 +201,74 @@ public class ReflectionUtils { return false; } + /* + * @ if (isPresent("com.optionaldependency.DependencyClass")) { // This + * block will never execute when the dependency is not present // There is + * therefore no more risk of code throwing NoClassDefFoundException. + * executeCodeLinkingToDependency(); } + */ + public static boolean isPresent(final String className) { + try { + Class.forName(className); + return true; + } catch (final Throwable ex) { + // Class or one of its dependencies is not present... + return false; + } + } + + @SuppressWarnings("rawtypes") + public static Method getMethodViaReflection(final Class lookupClass, final String methodName, + final boolean invoke) throws Exception { + final Class lookup = lookupClass.getClass(); + final Method m = lookup.getDeclaredMethod(methodName); + m.setAccessible(true);// Abracadabra + if (invoke) { + m.invoke(lookup);// now its OK + } + return m; + } + + public static Class getNonPublicClass(final String className) { + Class c = null; + try { + c = Class.forName(className); + } catch (final ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // full package name --------^^^^^^^^^^ + // or simpler without Class.forName: + // Class c = package1.A.class; + + if (null != c) { + // In our case we need to use + Constructor constructor = null; + try { + constructor = c.getDeclaredConstructor(); + } catch (NoSuchMethodException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // note: getConstructor() can return only public constructors + // so we needed to search for any Declared constructor + + // now we need to make this constructor accessible + if (null != constructor) { + constructor.setAccessible(true);// ABRACADABRA! + + try { + final Object o = constructor.newInstance(); + return (Class) o; + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + return null; + } } diff --git a/src/Java/gtPlusPlus/core/util/sys/GeoUtils.java b/src/Java/gtPlusPlus/core/util/sys/GeoUtils.java new file mode 100644 index 0000000000..ae3e6242ed --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/sys/GeoUtils.java @@ -0,0 +1,106 @@ +package gtPlusPlus.core.util.sys; + +import java.io.*; +import java.net.*; + +import org.apache.http.client.utils.URIBuilder; + +import gtPlusPlus.api.objects.Logger; + +public class GeoUtils { + + public static String determineUsersCountry(){ + try { + if (NetworkUtils.checkNetworkIsAvailableWithValidInterface()){ + return getUsersCountry(); + } + else { + return "Offline."; + } + } catch (Throwable T){ + Logger.INFO("Failed to initialise GeoUtils."); + return "Failed."; + } + } + + private static String getUsersIPAddress() { + try { + String webPage = "http://checkip.amazonaws.com/"; + URL url = new URL(webPage); + URLConnection urlConnection = url.openConnection(); + InputStream is = urlConnection.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + int numCharsRead; + char[] charArray = new char[1024]; + StringBuffer sb = new StringBuffer(); + while ((numCharsRead = isr.read(charArray)) > 0) { + sb.append(charArray, 0, numCharsRead); + } + isr.close(); + String result = sb.toString(); + return result; + } catch (IOException e) {} + return "Error getting users IP."; + } + + private static String getUsersCountry() { + + //Get the IP + String ipAddress = getUsersIPAddress(); + + //Build a URL + URIBuilder builder = new URIBuilder() + .setScheme("http") + .setHost("ipinfo.io") + .setPath("/"+ipAddress+"/country/"); + + URI uri; + try { + //Convert the URI Builder to a URI, then to a URL + uri = builder.build(); + URL url = uri.toURL(); + + //Main Check method + try { + URLConnection urlConnection = url.openConnection(); + InputStream is = urlConnection.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + int numCharsRead; + char[] charArray = new char[1024]; + StringBuffer sb = new StringBuffer(); + while ((numCharsRead = isr.read(charArray)) > 0) { + sb.append(charArray, 0, numCharsRead); + } + String temp = sb.toString(); + String result = temp.replaceAll("(\\r|\\n)", ""); + isr.close(); + return result; + //Catch block for bad connection + } catch (IOException e) { + Logger.INFO("Method 1 - Failed."); + } + + //Secondary method + try (java.util.Scanner s = new java.util.Scanner(url.openStream(), "UTF-8").useDelimiter("\\A")) { + String r = s.next(); + return r.replaceAll("(\\r|\\n)", ""); + //Catch block for bad connection + } catch (java.io.IOException e) { + Logger.INFO("Method 2 - Failed."); + } + + } + //Catch block for all the Bad URI/URL building + catch (URISyntaxException | MalformedURLException e1) { + if (e1 instanceof URISyntaxException){ + Logger.INFO("Bad URI Syntax for builder."); + } + else { + Logger.INFO("Malformed URL."); + } + Logger.INFO("Country Check - Failed."); + } + return "Error getting users Country. "+ipAddress; + } + +} diff --git a/src/Java/gtPlusPlus/core/util/sys/KeyboardUtils.java b/src/Java/gtPlusPlus/core/util/sys/KeyboardUtils.java new file mode 100644 index 0000000000..ba834e345e --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/sys/KeyboardUtils.java @@ -0,0 +1,23 @@ +package gtPlusPlus.core.util.sys; + +import org.lwjgl.input.Keyboard; + +import net.minecraft.client.Minecraft; + +public class KeyboardUtils { + + public static boolean isCtrlKeyDown(){ + // prioritize CONTROL, but allow OPTION as well on Mac (note: GuiScreen's isCtrlKeyDown only checks for the OPTION key on Mac) + boolean isCtrlKeyDown = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); + if (!isCtrlKeyDown && Minecraft.isRunningOnMac) + isCtrlKeyDown = Keyboard.isKeyDown(Keyboard.KEY_LMETA) || Keyboard.isKeyDown(Keyboard.KEY_RMETA); + + return isCtrlKeyDown; + } + + public static boolean isShiftKeyDown(){ + return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + + } + +} diff --git a/src/Java/gtPlusPlus/core/util/sys/Log.java b/src/Java/gtPlusPlus/core/util/sys/Log.java new file mode 100644 index 0000000000..fcd4f34c1b --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/sys/Log.java @@ -0,0 +1,24 @@ +package gtPlusPlus.core.util.sys; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public final class Log { + public static final Logger LOGGER = LogManager.getLogger("MiscUtils"); + + public static void warn(final String msg) { + LOGGER.warn(msg); + } + + public static void error(final String msg) { + LOGGER.error(msg); + } + + public static void info(final String msg) { + LOGGER.info(msg); + } + + public static void debug(final String msg) { + LOGGER.debug(msg); + } +} diff --git a/src/Java/gtPlusPlus/core/util/sys/NetworkUtils.java b/src/Java/gtPlusPlus/core/util/sys/NetworkUtils.java new file mode 100644 index 0000000000..b6324f18f5 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/sys/NetworkUtils.java @@ -0,0 +1,153 @@ +package gtPlusPlus.core.util.sys; + +import java.io.*; +import java.net.*; +import java.util.Enumeration; + +import gtPlusPlus.api.objects.Logger; + +public class NetworkUtils { + + public static String getContentFromURL(final String args) { + if (checkNetworkIsAvailableWithValidInterface()){ + try { + URL url; + // get URL content + url = new URL(args); + final URLConnection conn = url.openConnection(); + // open the stream and put it into BufferedReader + final BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String inputLine; + String tempLine = null; + while ((inputLine = br.readLine()) != null) { + tempLine = inputLine; + } + br.close(); + return tempLine; + } + catch (final MalformedURLException e) { + Logger.INFO("Bad URL for Version Check."); + } + catch (final IOException e) { + Logger.INFO("IOException during Version Check."); + } + } + Logger.INFO("Network Not Available during Version Check."); + return "offline"; + } + + public static boolean checkNetworkIsAvailableWithValidInterface(){ + try { + if (hasValidNetworkInterface()){ + if (checkAddressWithTimeout("http://www.google.com", 10) || + checkAddressWithTimeout("http://www.baidu.com", 10) || + checkAddressWithTimeout("https://github.com/draknyte1/GTplusplus", 10) || + checkAddressWithTimeout("www.yahoo.com", 10)/* || + netIsAvailableGoogle() || + netIsAvailableBaidu() || + netIsAvailableGithub() || + netIsAvailableOther()*/){ + return true; + } + else { + Logger.INFO("No sites responded to network connectivity test."); + } + } + else { + Logger.INFO("Network Adapter was not valid."); + } + } + catch (SocketException e) {} + return false; + } + + private static boolean netIsAvailableGoogle() { + try { + final URL url = new URL("http://www.google.com"); + final URLConnection conn = url.openConnection(); + conn.connect(); + return true; + } catch (final MalformedURLException e) { + throw new RuntimeException(e); + } catch (final IOException e) { + return false; + } + } + + private static boolean netIsAvailableBaidu() { + try { + final URL url = new URL("http://www.baidu.com"); + final URLConnection conn = url.openConnection(); + conn.connect(); + return true; + } catch (final MalformedURLException e) { + throw new RuntimeException(e); + } catch (final IOException e) { + return false; + } + } + + private static boolean netIsAvailableGithub() { + try { + final URL url = new URL("https://github.com/draknyte1/GTplusplus"); + final URLConnection conn = url.openConnection(); + conn.connect(); + return true; + } catch (final MalformedURLException e) { + throw new RuntimeException(e); + } catch (final IOException e) { + return false; + } + } + + private static boolean netIsAvailableOther() { + try { + final int timeout = 200; + final InetAddress[] addresses = InetAddress.getAllByName("www.yahoo.com"); + for (final InetAddress address : addresses) { + if (address.isReachable(timeout)) { + return true; + } + return false; + } + } catch (final Exception e) { + return false; + } + return false; + } + + private static boolean checkAddressWithTimeout(String URL, int timeout) { + + try { + InetAddress.getByName(URL).isReachable(3000); //Replace with your name + return true; + } catch (Exception e) { + return false; + } + + /*try { + final InetAddress[] addresses = InetAddress.getAllByName(URL); + for (final InetAddress address : addresses) { + if (address.isReachable(timeout)) { + return true; + } + return false; + } + } catch (final Exception e) { + return false; + } + return false;*/ + } + + private static boolean hasValidNetworkInterface() throws SocketException{ + final Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces.hasMoreElements()) { + final NetworkInterface interf = interfaces.nextElement(); + if (interf.isUp() && !interf.isLoopback()) { + return true; + } + } + return false; + } + +} diff --git a/src/Java/gtPlusPlus/core/util/sys/SystemUtils.java b/src/Java/gtPlusPlus/core/util/sys/SystemUtils.java new file mode 100644 index 0000000000..efcfaf8d04 --- /dev/null +++ b/src/Java/gtPlusPlus/core/util/sys/SystemUtils.java @@ -0,0 +1,77 @@ +package gtPlusPlus.core.util.sys; + +public class SystemUtils { + + private static OS SystemType; + + public static OS getOS(){ + if (SystemType != null){ + return SystemType; + } + else { + SystemType = getOperatingSystem(); + return SystemType; + } + } + + public static boolean isWindows() { + return (getOSString().indexOf("win") >= 0); + } + + public static boolean isMac() { + return (getOSString().indexOf("mac") >= 0); + } + + public static boolean isUnix() { + return (getOSString().indexOf("nix") >= 0 || getOSString().indexOf("nux") >= 0 || getOSString().indexOf("aix") > 0 ); + } + + public static boolean isSolaris() { + return (getOSString().indexOf("sunos") >= 0); + } + + public static String getOSString(){ + try { + return System.getProperty("os.name").toLowerCase(); + } + catch (Throwable t){ + return "other"; + } + } + + public static OS getOperatingSystem(){ + if (isMac()){ + return OS.MAC; + } + else if (isWindows()){ + return OS.WINDOWS; + } + else if (isUnix()){ + return OS.UNIX; + } + else if (isSolaris()){ + return OS.SOLARIS; + } + else { + return OS.OTHER; + } + } + + public static enum OS { + MAC(1), + WINDOWS(2), + UNIX(3), + SOLARIS(4), + OTHER(0); + + private int mID; + private OS (final int ID){ + this.mID = ID; + } + + public int getID() { + return this.mID; + } + } + +} diff --git a/src/Java/gtPlusPlus/core/util/uuid/UUIDGenerator.java b/src/Java/gtPlusPlus/core/util/uuid/UUIDGenerator.java deleted file mode 100644 index bf0ac3d1f5..0000000000 --- a/src/Java/gtPlusPlus/core/util/uuid/UUIDGenerator.java +++ /dev/null @@ -1,451 +0,0 @@ -package gtPlusPlus.core.util.uuid; - -import java.io.IOException; -import java.net.InetAddress; -import java.util.Random; -import java.util.UUID; - -import gtPlusPlus.api.objects.random.CSPRNG_DO_NOT_USE; - -/** - * - * Implement modified version of Apache's OpenJPA UUID generator. - * This UUID generator is paired with a Blum-Blum-Shub random number generator - * which in itself is seeded by custom SecureRandom. - * - * The UUID generator class has been converted from a static factory to an instanced factory. - * - */ - -//========================================= APACHE BLOCK ========================================= - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * UUID value generator. Type 1 generator is based on the time-based generator - * in the Apache Commons Id project: http://jakarta.apache.org/commons/sandbox - * /id/uuid.html The type 4 generator uses the standard Java UUID generator. - * - * The type 1 code has been vastly simplified and modified to replace the - * ethernet address of the host machine with the IP, since we do not want to - * require native libs and Java cannot access the MAC address directly. - * - * In spirit, implements the IETF UUID draft specification, found here:
- * http://www1.ics.uci.edu/~ejw/authoring/uuid-guid/draft-leach-uuids-guids-01 - * .txt - * - * @author Abe White, Kevin Sutter - * @since 0.3.3 - */ -public class UUIDGenerator { - - // supported UUID types - public static final int TYPE1 = 1; - public static final int TYPE4 = 4; - // indexes within the uuid array for certain boundaries - private static final byte IDX_TIME_HI = 6; - private static final byte IDX_TYPE = 6; // multiplexed - private static final byte IDX_TIME_MID = 4; - private static final byte IDX_TIME_LO = 0; - private static final byte IDX_TIME_SEQ = 8; - private static final byte IDX_VARIATION = 8; // multiplexed - // indexes and lengths within the timestamp for certain boundaries - private static final byte TS_TIME_LO_IDX = 4; - private static final byte TS_TIME_LO_LEN = 4; - private static final byte TS_TIME_MID_IDX = 2; - private static final byte TS_TIME_MID_LEN = 2; - private static final byte TS_TIME_HI_IDX = 0; - private static final byte TS_TIME_HI_LEN = 2; - // offset to move from 1/1/1970, which is 0-time for Java, to gregorian - // 0-time 10/15/1582, and multiplier to go from 100nsec to msec units - private static final long GREG_OFFSET = 0xB1D069B5400L; - private static final long MILLI_MULT = 10000L; - // type of UUID -- time based - private final static byte TYPE_TIME_BASED = 0x10; - // random number generator used to reduce conflicts with other JVMs, and - // hasher for strings. - private Random RANDOM; - // 4-byte IP address + 2 random bytes to compensate for the fact that - // the MAC address is usually 6 bytes - private byte[] IP; - // counter is initialized to 0 and is incremented for each uuid request - // within the same timestamp window. - private int _counter; - // current timestamp (used to detect multiple uuid requests within same - // timestamp) - private long _currentMillis; - // last used millis time, and a semi-random sequence that gets reset - // when it overflows - private long _lastMillis = 0L; - private static final int MAX_14BIT = 0x3FFF; - private short _seq = 0; - private boolean type1Initialized = false; /* - * Initializer for type 1 UUIDs. Creates random generator and genenerates - * the node portion of the UUID using the IP address. - */ - private synchronized void initializeForType1() { - if (type1Initialized == true) { - return; - } - // note that secure random is very slow the first time - // it is used; consider switching to a standard random - RANDOM = CSPRNG_DO_NOT_USE.generate(); - _seq = (short) RANDOM.nextInt(MAX_14BIT); - - byte[] ip = null; - try { - ip = InetAddress.getLocalHost().getAddress(); - } catch (IOException ioe) { - throw new RuntimeException(ioe); - } - IP = new byte[6]; - RANDOM.nextBytes(IP); - //OPENJPA-2055: account for the fact that 'getAddress' - //may return an IPv6 address which is 16 bytes wide. - for( int i = 0 ; i < ip.length; ++i ) { - IP[2+(i%4)] ^= ip[i]; - } - type1Initialized = true; - } - /** - * Return a unique UUID value. - */ - public byte[] next(int type) { - if (type == TYPE4) { - return createType4(); - } - return createType1(); - } - /* - * Creates a type 1 UUID - */ - public byte[] createType1() { - if (type1Initialized == false) { - initializeForType1(); - } - // set ip addr - byte[] uuid = new byte[16]; - System.arraycopy(IP, 0, uuid, 10, IP.length); - // Set time info. Have to do this processing within a synchronized - // block because of the statics... - long now = 0; - synchronized (UUIDGenerator.class) { - // Get the time to use for this uuid. This method has the side - // effect of modifying the clock sequence, as well. - now = getTime(); - // Insert the resulting clock sequence into the uuid - uuid[IDX_TIME_SEQ] = (byte) ((_seq & 0x3F00) >>> 8); - uuid[IDX_VARIATION] |= 0x80; - uuid[IDX_TIME_SEQ+1] = (byte) (_seq & 0xFF); - } - // have to break up time because bytes are spread through uuid - byte[] timeBytes = Bytes.toBytes(now); - // Copy time low - System.arraycopy(timeBytes, TS_TIME_LO_IDX, uuid, IDX_TIME_LO, - TS_TIME_LO_LEN); - // Copy time mid - System.arraycopy(timeBytes, TS_TIME_MID_IDX, uuid, IDX_TIME_MID, - TS_TIME_MID_LEN); - // Copy time hi - System.arraycopy(timeBytes, TS_TIME_HI_IDX, uuid, IDX_TIME_HI, - TS_TIME_HI_LEN); - //Set version (time-based) - uuid[IDX_TYPE] |= TYPE_TIME_BASED; // 0001 0000 - return uuid; - } - /* - * Creates a type 4 UUID - */ - private byte[] createType4() { - UUID type4 = UUID.randomUUID(); - byte[] uuid = new byte[16]; - longToBytes(type4.getMostSignificantBits(), uuid, 0); - longToBytes(type4.getLeastSignificantBits(), uuid, 8); - return uuid; - } - /* - * Converts a long to byte values, setting them in a byte array - * at a given starting position. - */ - private void longToBytes(long longVal, byte[] buf, int sPos) { - sPos += 7; - for(int i = 0; i < 8; i++) - buf[sPos-i] = (byte)(longVal >>> (i * 8)); - } - - /** - * Return the next unique uuid value as a 16-character string. - */ - public String nextString(int type) { - byte[] bytes = next(type); - try { - return new String(bytes, "ISO-8859-1"); - } catch (Exception e) { - return new String(bytes); - } - } - /** - * Return the next unique uuid value as a 32-character hex string. - */ - public String nextHex(int type) { - return Base16Encoder.encode(next(type)); - } - /** - * Get the timestamp to be used for this uuid. Must be called from - * a synchronized block. - * - * @return long timestamp - */ - // package-visibility for testing - private long getTime() { - if (RANDOM == null) - initializeForType1(); - long newTime = getUUIDTime(); - if (newTime <= _lastMillis) { - incrementSequence(); - newTime = getUUIDTime(); - } - _lastMillis = newTime; - return newTime; - } - /** - * Gets the appropriately modified timestamep for the UUID. Must be called - * from a synchronized block. - * - * @return long timestamp in 100ns intervals since the Gregorian change - * offset - */ - private long getUUIDTime() { - if (_currentMillis != System.currentTimeMillis()) { - _currentMillis = System.currentTimeMillis(); - _counter = 0; // reset counter - } - // check to see if we have created too many uuid's for this timestamp - if (_counter + 1 >= MILLI_MULT) { - // Original algorithm threw exception. Seemed like overkill. - // Let's just increment the timestamp instead and start over... - _currentMillis++; - _counter = 0; - } - // calculate time as current millis plus offset times 100 ns ticks - long currentTime = (_currentMillis + GREG_OFFSET) * MILLI_MULT; - // return the uuid time plus the artificial tick counter incremented - return currentTime + _counter++; - } - /** - * Increments the clock sequence for this uuid. Must be called from a - * synchronized block. - */ - private void incrementSequence() { - // increment, but if it's greater than its 14-bits, reset it - if (++_seq > MAX_14BIT) { - _seq = (short) RANDOM.nextInt(MAX_14BIT); // semi-random - } - } - - //Add Dependant classes internally - - /** - * This class came from the Apache Commons Id sandbox project in support - * of the UUIDGenerator implementation. - * - *

Static methods for managing byte arrays (all methods follow Big - * Endian order where most significant bits are in front).

- */ - public static final class Bytes { - /** - *

Hide constructor in utility class.

- */ - private Bytes() { - } - /** - * Appends two bytes array into one. - * - * @param a A byte[]. - * @param b A byte[]. - * @return A byte[]. - */ - public static byte[] append(byte[] a, byte[] b) { - byte[] z = new byte[a.length + b.length]; - System.arraycopy(a, 0, z, 0, a.length); - System.arraycopy(b, 0, z, a.length, b.length); - return z; - } - /** - * Returns a 8-byte array built from a long. - * - * @param n The number to convert. - * @return A byte[]. - */ - public static byte[] toBytes(long n) { - return toBytes(n, new byte[8]); - } - /** - * Build a 8-byte array from a long. No check is performed on the - * array length. - * - * @param n The number to convert. - * @param b The array to fill. - * @return A byte[]. - */ - public static byte[] toBytes(long n, byte[] b) { - b[7] = (byte) (n); - n >>>= 8; - b[6] = (byte) (n); - n >>>= 8; - b[5] = (byte) (n); - n >>>= 8; - b[4] = (byte) (n); - n >>>= 8; - b[3] = (byte) (n); - n >>>= 8; - b[2] = (byte) (n); - n >>>= 8; - b[1] = (byte) (n); - n >>>= 8; - b[0] = (byte) (n); - - return b; - } - /** - * Build a long from first 8 bytes of the array. - * - * @param b The byte[] to convert. - * @return A long. - */ - public static long toLong(byte[] b) { - return ((((long) b[7]) & 0xFF) - + ((((long) b[6]) & 0xFF) << 8) - + ((((long) b[5]) & 0xFF) << 16) - + ((((long) b[4]) & 0xFF) << 24) - + ((((long) b[3]) & 0xFF) << 32) - + ((((long) b[2]) & 0xFF) << 40) - + ((((long) b[1]) & 0xFF) << 48) - + ((((long) b[0]) & 0xFF) << 56)); - } - /** - * Compares two byte arrays for equality. - * - * @param a A byte[]. - * @param b A byte[]. - * @return True if the arrays have identical contents. - */ - public static boolean areEqual(byte[] a, byte[] b) { - int aLength = a.length; - if (aLength != b.length) { - return false; - } - for (int i = 0; i < aLength; i++) { - if (a[i] != b[i]) { - return false; - } - } - return true; - } - /** - *

Compares two byte arrays as specified by Comparable. - * - * @param lhs - left hand value in the comparison operation. - * @param rhs - right hand value in the comparison operation. - * @return a negative integer, zero, or a positive integer as - * lhs is less than, equal to, or greater than - * rhs. - */ - public static int compareTo(byte[] lhs, byte[] rhs) { - if (lhs == rhs) { - return 0; - } - if (lhs == null) { - return -1; - } - if (rhs == null) { - return +1; - } - if (lhs.length != rhs.length) { - return ((lhs.length < rhs.length) ? -1 : +1); - } - for (int i = 0; i < lhs.length; i++) { - if (lhs[i] < rhs[i]) { - return -1; - } else if (lhs[i] > rhs[i]) { - return 1; - } - } - return 0; - } - /** - * Build a short from first 2 bytes of the array. - * - * @param b The byte[] to convert. - * @return A short. - */ - public static short toShort(byte[] b) { - return (short) ((b[1] & 0xFF) + ((b[0] & 0xFF) << 8)); - } - } - /** - * Base 16 encoder. - * - * @author Marc Prud'hommeaux - */ - public static final class Base16Encoder { - - private final static char[] HEX = new char[]{ - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - /** - * Convert bytes to a base16 string. - */ - public static String encode(byte[] byteArray) { - StringBuilder hexBuffer = new StringBuilder(byteArray.length * 2); - for (int i = 0; i < byteArray.length; i++) - for (int j = 1; j >= 0; j--) - hexBuffer.append(HEX[(byteArray[i] >> (j * 4)) & 0xF]); - return hexBuffer.toString(); - } - /** - * Convert a base16 string into a byte array. - */ - public static byte[] decode(String s) { - int len = s.length(); - byte[] r = new byte[len / 2]; - for (int i = 0; i < r.length; i++) { - int digit1 = s.charAt(i * 2), digit2 = s.charAt(i * 2 + 1); - if (digit1 >= '0' && digit1 <= '9') - digit1 -= '0'; - else if (digit1 >= 'A' && digit1 <= 'F') - digit1 -= 'A' - 10; - if (digit2 >= '0' && digit2 <= '9') - digit2 -= '0'; - else if (digit2 >= 'A' && digit2 <= 'F') - digit2 -= 'A' - 10; - - r[i] = (byte) ((digit1 << 4) + digit2); - } - return r; - } - } - - - -} - -//========================================= APACHE BLOCK ========================================= - diff --git a/src/Java/gtPlusPlus/core/util/uuid/UUIDUtils.java b/src/Java/gtPlusPlus/core/util/uuid/UUIDUtils.java deleted file mode 100644 index 13eaff5bc8..0000000000 --- a/src/Java/gtPlusPlus/core/util/uuid/UUIDUtils.java +++ /dev/null @@ -1,25 +0,0 @@ -package gtPlusPlus.core.util.uuid; - -import java.nio.ByteBuffer; -import java.util.UUID; - -public class UUIDUtils { - - //UUID Methods below created by https://gist.github.com/jeffjohnson9046 - //https://gist.github.com/jeffjohnson9046/c663dd22bbe6bb0b3f5e - - public static byte[] getBytesFromUUID(UUID uuid) { - ByteBuffer bb = ByteBuffer.wrap(new byte[16]); - bb.putLong(uuid.getMostSignificantBits()); - bb.putLong(uuid.getLeastSignificantBits()); - return bb.array(); - } - - public static UUID getUUIDFromBytes(byte[] bytes) { - ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); - Long high = byteBuffer.getLong(); - Long low = byteBuffer.getLong(); - return new UUID(high, low); - } - -} diff --git a/src/Java/gtPlusPlus/core/util/wrapper/var.java b/src/Java/gtPlusPlus/core/util/wrapper/var.java deleted file mode 100644 index 06de3cde73..0000000000 --- a/src/Java/gtPlusPlus/core/util/wrapper/var.java +++ /dev/null @@ -1,67 +0,0 @@ -package gtPlusPlus.core.util.wrapper; - -import gtPlusPlus.api.objects.Logger; -import gtPlusPlus.core.lib.LoadedMods; -import gtPlusPlus.core.util.item.ItemUtils; -import net.minecraft.item.ItemStack; - -public class var{ - - private ItemStack temp = null; - private final String sanitizedName; - private final String fqrn; - - public var(String o){ - final String t = this.sanitize('<', o); - final String t2 = this.sanitize('>', t); - this.sanitizedName = t2; - o = this.sanitize('"', t2); - this.fqrn = o; - } - - private String sanitize(final char token, String input){ - for (int i=0;i