diff --git a/.idea/gradle.xml b/.idea/gradle.xml deleted file mode 100644 index 97d8de6f..00000000 --- a/.idea/gradle.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 2dde0c65..00000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/README.md b/README.md index 1b285c3f..64bd85e9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,21 @@ AdventureBackpack2 ================== +###I do this out of my free time if you are a developer and want to help out please make an Pull Requests Mod for Minecraft + +This mod is under the GNU LESSER GENERAL PUBLIC LICENSE Version 3. + +You can include this mod in your modpack + +You can do video's with this fork of adventurebackpack mod + +My only request is to provide a link to this github if not its fine by me + +###This Adventure Backpack 2 Mod +* better Performance! +* little more adventure backpack to you to enjoy +* major bugfixe's +* fixes duplication bugs +* fixed missing texture's for holiday's +* more to come! diff --git a/build.gradle b/build.gradle index c144343c..86d96b02 100644 --- a/build.gradle +++ b/build.gradle @@ -1,44 +1,48 @@ buildscript { repositories { mavenCentral() - maven { - name = "forge" - url = "http://files.minecraftforge.net/maven" - } - maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" - } + maven { url = "http://files.minecraftforge.net/maven" } + maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" } } - dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + dependencies { classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' } +} +repositories { + maven { // WAILA + name "Mobius Repo" + url "http://mobiusstrip.eu/maven" + } + maven { // NEI + name 'CB Repo' + url "http://chickenbones.net/maven/" } } apply plugin: 'forge' -version = "1.7.10-0.8d" group = "com.darkona.adventurebackpack" // http://maven.apache.org/guides/mini/guide-naming-conventions.html archivesBaseName = "adventurebackpack" -minecraft { - version = "1.7.10-10.13.4.1558-1.7.10" - runDir = "eclipse" -} +version = "${minecraft_version}-${mod_version}-${buildnumber}" -dependencies { - // you may put jars on which you depend on in ./libs - // or you may define them like so.. - //compile "some.group:artifact:version:classifier" - //compile "some.group:artifact:version" +sourceCompatibility = 1.7 +targetCompatibility = 1.7 - // real examples +minecraft { + version = "${minecraft_version}-${forge_version}" + runDir = "eclipse" - //compile 'com.mod-buildcraft:buildcraft:6.0.18:dev' + replace "@VERSION@", project.version +} +dependencies +{ + compile "codechicken:CodeChickenCore:${minecraft_version}-${ccc_version}:dev" + compile "codechicken:CodeChickenLib:${minecraft_version}-${ccl_version}:dev" + compile "codechicken:NotEnoughItems:${minecraft_version}-${nei_version}:dev" + compile "mcp.mobius.waila:Waila:${waila_version}_${minecraft_version}" - //compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env + //compile "com.azanor.baubles:Baubles:${baubles_version}:deobf" // for more info... // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html @@ -46,24 +50,37 @@ dependencies { } -processResources - { - // this will ensure that this task is redone when the versions change. - inputs.property "version", project.version - inputs.property "mcversion", project.minecraft.version - - // replace stuff in mcmod.info, nothing else - from(sourceSets.main.resources.srcDirs) { - include 'mcmod.info' - exclude '\\arg' - // replace version and mcversion - expand 'version': project.version, 'mcversion': project.minecraft.version - } - - // copy everything else, thats not the mcmod.info - from(sourceSets.main.resources.srcDirs) { - exclude 'mcmod.info' - } +processResources { + // this will ensure that this task is redone when the versions change. + inputs.property "version", project.version + inputs.property "mcversion", project.minecraft.version + + // replace stuff in mcmod.info, nothing else + from(sourceSets.main.resources.srcDirs) { + include 'mcmod.info' + exclude '\\arg' + // replace version and mcversion + expand 'version': project.version, 'mcversion': project.minecraft.version + } + + // copy everything else, thats not the mcmod.info + from(sourceSets.main.resources.srcDirs) { + exclude 'mcmod.info' + } +} + +jar { + manifest { + attributes 'FMLAT': 'adventurebackpack_at.cfg' + } +} + +if (JavaVersion.current().isJava8Compatible()) { + allprojects { + tasks.withType(Javadoc) { + options.addStringOption('Xdoclint:none', '-quiet') } + } +} -idea { module { inheritOutputDirs = true } } \ No newline at end of file +idea { module { inheritOutputDirs = true } } diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..8c786c98 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,10 @@ +buildnumber=h8 +mod_version=0.9 + +minecraft_version=1.7.10 +forge_version=10.13.4.1614-1.7.10 + +ccc_version=1.0.7.47 +ccl_version=1.1.3.138 +nei_version=1.0.5.120 +waila_version=1.5.10 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index b7612167..7fbf96de 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 7352cf97..e641b8ac 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Thu Jan 29 21:00:46 VET 2015 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-3.4.1-all.zip diff --git a/gradlew b/gradlew index 91a7e269..4453ccea 100644 --- a/gradlew +++ b/gradlew @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +#!/usr/bin/env sh ############################################################################## ## @@ -6,12 +6,30 @@ ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" @@ -30,6 +48,7 @@ die ( ) { cygwin=false msys=false darwin=false +nonstop=false case "`uname`" in CYGWIN* ) cygwin=true @@ -40,31 +59,11 @@ case "`uname`" in MINGW* ) msys=true ;; + NONSTOP* ) + nonstop=true + ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -90,7 +89,7 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then @@ -114,6 +113,7 @@ fi if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` @@ -154,11 +154,19 @@ if $cygwin ; then esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") +# Escape application args +save ( ) { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " } -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 8a0b282a..f9553162 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -8,14 +8,14 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome @@ -46,10 +46,9 @@ echo location of your Java installation. goto fail :init -@rem Get command-line arguments, handling Windowz variants +@rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. @@ -60,11 +59,6 @@ set _SKIP=2 if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ :execute @rem Setup the command line diff --git a/libs/CodeChickenLib-1.7.10-1.1.3.140-universal.jar b/libs/CodeChickenLib-1.7.10-1.1.3.140-universal.jar new file mode 100644 index 00000000..9aa3d80a Binary files /dev/null and b/libs/CodeChickenLib-1.7.10-1.1.3.140-universal.jar differ diff --git a/src/main/java/adventurebackpack/api/FluidEffect.java b/src/main/java/adventurebackpack/api/FluidEffect.java index ff5a34ae..1546c514 100644 --- a/src/main/java/adventurebackpack/api/FluidEffect.java +++ b/src/main/java/adventurebackpack/api/FluidEffect.java @@ -68,5 +68,4 @@ public int getEffectID() * @param entity The entity that will be affected. */ public abstract void affectDrinker(World world, Entity entity); - } diff --git a/src/main/java/baubles/api/BaubleType.java b/src/main/java/baubles/api/BaubleType.java deleted file mode 100644 index 539b5159..00000000 --- a/src/main/java/baubles/api/BaubleType.java +++ /dev/null @@ -1,8 +0,0 @@ -package baubles.api; - -public enum BaubleType -{ - RING, - AMULET, - BELT -} diff --git a/src/main/java/baubles/api/BaublesApi.java b/src/main/java/baubles/api/BaublesApi.java deleted file mode 100644 index 3348974c..00000000 --- a/src/main/java/baubles/api/BaublesApi.java +++ /dev/null @@ -1,39 +0,0 @@ -package baubles.api; - -import cpw.mods.fml.common.FMLLog; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; - -import java.lang.reflect.Method; - - -/** - * @author Azanor - */ -public class BaublesApi -{ - - static Method getBaubles; - - /** - * Retrieves the baubles inventory for the supplied player - */ - public static IInventory getBaubles(EntityPlayer player) - { - IInventory ot = null; - try - { - if (getBaubles == null) - { - Class fake = Class.forName("baubles.common.lib.PlayerHandler"); - getBaubles = fake.getMethod("getPlayerBaubles", EntityPlayer.class); - } - ot = (IInventory) getBaubles.invoke(null, player); - } catch (Exception ex) - { - FMLLog.warning("[Baubles API] Could not invoke baubles.common.lib.PlayerHandler method getPlayerBaubles"); - } - return ot; - } - -} diff --git a/src/main/java/baubles/api/IBauble.java b/src/main/java/baubles/api/IBauble.java deleted file mode 100644 index 47a42ddd..00000000 --- a/src/main/java/baubles/api/IBauble.java +++ /dev/null @@ -1,45 +0,0 @@ -package baubles.api; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.item.ItemStack; - -/** - * @author Azanor - *

- * This interface should be extended by items that can be worn in bauble slots - */ - -public interface IBauble -{ - - /** - * This method return the type of bauble this is. - * Type is used to determine the slots it can go into. - */ - public BaubleType getBaubleType(ItemStack itemstack); - - /** - * This method is called once per tick if the bauble is being worn by a player - */ - public void onWornTick(ItemStack itemstack, EntityLivingBase player); - - /** - * This method is called when the bauble is equipped by a player - */ - public void onEquipped(ItemStack itemstack, EntityLivingBase player); - - /** - * This method is called when the bauble is unequipped by a player - */ - public void onUnequipped(ItemStack itemstack, EntityLivingBase player); - - /** - * can this bauble be placed in a bauble slot - */ - public boolean canEquip(ItemStack itemstack, EntityLivingBase player); - - /** - * Can this bauble be removed from a bauble slot - */ - public boolean canUnequip(ItemStack itemstack, EntityLivingBase player); -} diff --git a/src/main/java/codechicken/lib/colour/Colour.java b/src/main/java/codechicken/lib/colour/Colour.java deleted file mode 100644 index 4d39dd13..00000000 --- a/src/main/java/codechicken/lib/colour/Colour.java +++ /dev/null @@ -1,180 +0,0 @@ -package codechicken.lib.colour; - -import codechicken.lib.config.ConfigTag.IConfigType; -import codechicken.lib.math.MathHelper; -import codechicken.lib.util.Copyable; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import org.lwjgl.opengl.GL11; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public abstract class Colour implements Copyable -{ - public static IConfigType configRGB = new IConfigType() - { - private final Pattern patternRGB = Pattern.compile("(\\d+),(\\d+),(\\d+)"); - - @Override - public String configValue(Colour entry) - { - String s = Long.toString(((long) entry.rgb()) << 32 >>> 32, 16); - while (s.length() < 6) - s = "0" + s; - return "0x" + s.toUpperCase(); - } - - @Override - public Colour valueOf(String text) throws Exception - { - Matcher matcherRGB = patternRGB.matcher(text.replaceAll("\\s", "")); - if (matcherRGB.matches()) - { - return new ColourRGBA( - Integer.parseInt(matcherRGB.group(1)), - Integer.parseInt(matcherRGB.group(2)), - Integer.parseInt(matcherRGB.group(3)), - 0xFF); - } - - int hex = (int) Long.parseLong(text.replace("0x", ""), 16); - return new ColourRGBA(hex << 8 | 0xFF); - } - }; - - public byte r; - public byte g; - public byte b; - public byte a; - - public Colour(int r, int g, int b, int a) - { - this.r = (byte) r; - this.g = (byte) g; - this.b = (byte) b; - this.a = (byte) a; - } - - public Colour(Colour colour) - { - r = colour.r; - g = colour.g; - b = colour.b; - a = colour.a; - } - - @SideOnly(Side.CLIENT) - public void glColour() - { - GL11.glColor4ub(r, g, b, a); - } - - @SideOnly(Side.CLIENT) - public void glColour(int a) - { - GL11.glColor4ub(r, g, b, (byte) a); - } - - public abstract int pack(); - - @Override - public String toString() - { - return getClass().getSimpleName() + "[0x" + Integer.toHexString(pack()).toUpperCase() + "]"; - } - - public Colour add(Colour colour2) - { - a += colour2.a; - r += colour2.r; - g += colour2.g; - b += colour2.b; - return this; - } - - public Colour sub(Colour colour2) - { - int ia = (a & 0xFF) - (colour2.a & 0xFF); - int ir = (r & 0xFF) - (colour2.r & 0xFF); - int ig = (g & 0xFF) - (colour2.g & 0xFF); - int ib = (b & 0xFF) - (colour2.b & 0xFF); - a = (byte) (ia < 0 ? 0 : ia); - r = (byte) (ir < 0 ? 0 : ir); - g = (byte) (ig < 0 ? 0 : ig); - b = (byte) (ib < 0 ? 0 : ib); - return this; - } - - public Colour invert() - { - a = (byte) (0xFF - (a & 0xFF)); - r = (byte) (0xFF - (r & 0xFF)); - g = (byte) (0xFF - (g & 0xFF)); - b = (byte) (0xFF - (b & 0xFF)); - return this; - } - - public Colour multiply(Colour colour2) - { - a = (byte) ((a & 0xFF) * ((colour2.a & 0xFF) / 255D)); - r = (byte) ((r & 0xFF) * ((colour2.r & 0xFF) / 255D)); - g = (byte) ((g & 0xFF) * ((colour2.g & 0xFF) / 255D)); - b = (byte) ((b & 0xFF) * ((colour2.b & 0xFF) / 255D)); - return this; - } - - public Colour scale(double d) - { - a = (byte) ((a & 0xFF) * d); - r = (byte) ((r & 0xFF) * d); - g = (byte) ((g & 0xFF) * d); - b = (byte) ((b & 0xFF) * d); - return this; - } - - public Colour interpolate(Colour colour2, double d) - { - return this.add(colour2.copy().sub(this).scale(d)); - } - - public Colour multiplyC(double d) - { - r = (byte) MathHelper.clip((r & 0xFF) * d, 0, 255); - g = (byte) MathHelper.clip((g & 0xFF) * d, 0, 255); - b = (byte) MathHelper.clip((b & 0xFF) * d, 0, 255); - - return this; - } - - public abstract Colour copy(); - - public int rgb() - { - return (r & 0xFF) << 16 | (g & 0xFF) << 8 | (b & 0xFF); - } - - public int argb() - { - return (a & 0xFF) << 24 | (r & 0xFF) << 16 | (g & 0xFF) << 8 | (b & 0xFF); - } - - public int rgba() - { - return (r & 0xFF) << 24 | (g & 0xFF) << 16 | (b & 0xFF) << 8 | (a & 0xFF); - } - - public Colour set(Colour colour) - { - r = colour.r; - g = colour.g; - b = colour.b; - a = colour.a; - return this; - } - - public boolean equals(Colour colour) - { - return colour != null && rgba() == colour.rgba(); - } -} diff --git a/src/main/java/codechicken/lib/colour/ColourARGB.java b/src/main/java/codechicken/lib/colour/ColourARGB.java deleted file mode 100644 index 007c51f4..00000000 --- a/src/main/java/codechicken/lib/colour/ColourARGB.java +++ /dev/null @@ -1,34 +0,0 @@ -package codechicken.lib.colour; - -public class ColourARGB extends Colour -{ - public ColourARGB(int colour) - { - super((colour >> 16) & 0xFF, (colour >> 8) & 0xFF, colour & 0xFF, (colour >> 24) & 0xFF); - } - - public ColourARGB(int a, int r, int g, int b) - { - super(r, g, b, a); - } - - public ColourARGB(ColourARGB colour) - { - super(colour); - } - - public static int pack(Colour colour) - { - return (colour.a & 0xFF) << 24 | (colour.r & 0xFF) << 16 | (colour.g & 0xFF) << 8 | (colour.b & 0xFF); - } - - public ColourARGB copy() - { - return new ColourARGB(this); - } - - public int pack() - { - return pack(this); - } -} diff --git a/src/main/java/codechicken/lib/colour/ColourRGBA.java b/src/main/java/codechicken/lib/colour/ColourRGBA.java deleted file mode 100644 index 42763261..00000000 --- a/src/main/java/codechicken/lib/colour/ColourRGBA.java +++ /dev/null @@ -1,59 +0,0 @@ -package codechicken.lib.colour; - -public class ColourRGBA extends Colour -{ - public ColourRGBA(int colour) - { - super((colour >> 24) & 0xFF, (colour >> 16) & 0xFF, (colour >> 8) & 0xFF, colour & 0xFF); - } - - public ColourRGBA(double r, double g, double b, double a) - { - super((int) (255 * r), (int) (255 * g), (int) (255 * b), (int) (255 * a)); - } - - public ColourRGBA(int r, int g, int b, int a) - { - super(r, g, b, a); - } - - public ColourRGBA(ColourRGBA colour) - { - super(colour); - } - - public static int pack(Colour colour) - { - return (colour.r & 0xFF) << 24 | (colour.g & 0xFF) << 16 | (colour.b & 0xFF) << 8 | (colour.a & 0xFF); - } - - public static int multiply(int c1, int c2) - { - if (c1 == -1) return c2; - if (c2 == -1) return c1; - int r = (((c1 >>> 24) * (c2 >>> 24)) & 0xFF00) << 16; - int g = (((c1 >> 16 & 0xFF) * (c2 >> 16 & 0xFF)) & 0xFF00) << 8; - int b = ((c1 >> 8 & 0xFF) * (c2 >> 8 & 0xFF)) & 0xFF00; - int a = ((c1 & 0xFF) * (c2 & 0xFF)) >> 8; - return r | g | b | a; - } - - public static int multiplyC(int c, float f) - { - int r = (int) ((c >>> 24) * f); - int g = (int) ((c >> 16 & 0xFF) * f); - int b = (int) ((c >> 8 & 0xFF) * f); - return r << 24 | g << 16 | b << 8 | c & 0xFF; - } - - public int pack() - { - return pack(this); - } - - @Override - public Colour copy() - { - return new ColourRGBA(this); - } -} diff --git a/src/main/java/codechicken/lib/colour/CustomGradient.java b/src/main/java/codechicken/lib/colour/CustomGradient.java deleted file mode 100644 index 21496f88..00000000 --- a/src/main/java/codechicken/lib/colour/CustomGradient.java +++ /dev/null @@ -1,38 +0,0 @@ -package codechicken.lib.colour; - -import codechicken.lib.math.MathHelper; -import codechicken.lib.render.TextureUtils; -import net.minecraft.util.ResourceLocation; - -import java.awt.image.BufferedImage; - -public class CustomGradient -{ - public int[] gradient; - - public CustomGradient(ResourceLocation textureFile) - { - BufferedImage img = TextureUtils.loadBufferedImage(textureFile); - if (img == null) - { - throw new RuntimeException("File not found: " + textureFile.toString()); - } - - int[] data = new int[img.getWidth()]; - img.getRGB(0, 0, img.getWidth(), 1, data, 0, img.getWidth()); - gradient = new int[img.getWidth()]; - for (int i = 0; i < data.length; i++) - gradient[i] = (data[i] << 8) | (((data[i]) >> 24) & 0xFF); - } - - public ColourRGBA getColour(double position) - { - return new ColourRGBA(getColourI(position)); - } - - public int getColourI(double position) - { - int off = (int) MathHelper.clip(gradient.length * position, 0, gradient.length - 1); - return gradient[off]; - } -} diff --git a/src/main/java/codechicken/lib/config/ConfigFile.java b/src/main/java/codechicken/lib/config/ConfigFile.java deleted file mode 100644 index 2f33b668..00000000 --- a/src/main/java/codechicken/lib/config/ConfigFile.java +++ /dev/null @@ -1,141 +0,0 @@ -package codechicken.lib.config; - -import java.io.*; - -public class ConfigFile extends ConfigTagParent -{ - public static final byte[] crlf = new byte[]{0xD, 0xA}; - - public File file; - private boolean loading; - - public ConfigFile(File file) - { - newlinemode = 2; - load(file); - } - - protected ConfigFile() - { - } - - public static String readLine(BufferedReader reader) throws IOException - { - String line = reader.readLine(); - return line == null ? null : line.replace("\t", ""); - } - - public static void writeLine(PrintWriter writer, String line, int tabs) - { - for (int i = 0; i < tabs; i++) - writer.print('\t'); - - writer.println(line); - } - - protected void load(File file) - { - try - { - if (!file.getParentFile().exists()) - { - file.getParentFile().mkdirs(); - } - if (!file.exists()) - { - file.createNewFile(); - } - } catch (IOException e) - { - throw new RuntimeException(e); - } - this.file = file; - loadConfig(); - } - - protected void loadConfig() - { - loading = true; - BufferedReader reader; - try - { - reader = new BufferedReader(new FileReader(file)); - - while (true) - { - reader.mark(2000); - String line = reader.readLine(); - if (line != null && line.startsWith("#")) - { - if (comment == null || comment.equals("")) - { - comment = line.substring(1); - } else - { - comment = comment + "\n" + line.substring(1); - } - } else - { - reader.reset(); - break; - } - } - loadChildren(reader); - reader.close(); - - } catch (IOException e) - { - throw new RuntimeException(e); - } - - loading = false; - } - - @Override - public ConfigFile setComment(String header) - { - super.setComment(header); - return this; - } - - @Override - public ConfigFile setSortMode(int mode) - { - super.setSortMode(mode); - return this; - } - - @Override - public String getNameQualifier() - { - return ""; - } - - public void saveConfig() - { - if (loading) - { - return; - } - - PrintWriter writer; - try - { - writer = new PrintWriter(file); - } catch (FileNotFoundException e) - { - throw new RuntimeException(e); - } - - writeComment(writer, 0); - ConfigFile.writeLine(writer, "", 0); - saveTagTree(writer, 0, ""); - writer.flush(); - writer.close(); - } - - public boolean isLoading() - { - return loading; - } -} diff --git a/src/main/java/codechicken/lib/config/ConfigTag.java b/src/main/java/codechicken/lib/config/ConfigTag.java deleted file mode 100644 index 6e13f5b6..00000000 --- a/src/main/java/codechicken/lib/config/ConfigTag.java +++ /dev/null @@ -1,308 +0,0 @@ -package codechicken.lib.config; - -import java.io.PrintWriter; - -public class ConfigTag extends ConfigTagParent -{ - public ConfigTagParent parent; - public String name; - public String qualifiedname; - public String value; - public boolean brace; - public boolean newline; - public int position = Integer.MAX_VALUE; - private int IDBase; - - public ConfigTag(ConfigTagParent parent, String name) - { - this.parent = parent; - this.name = name; - qualifiedname = parent.getNameQualifier() + name; - newline = parent.newlinemode == 2; - parent.addChild(this); - } - - @Override - public String getNameQualifier() - { - return qualifiedname + "."; - } - - @Override - public void saveConfig() - { - parent.saveConfig(); - } - - /** - * Called when the tag is loaded from a config file as opposed to constructed by a mod - * - * @return this - */ - public ConfigTag onLoaded() - { - return this; - } - - public void setDefaultValue(String defaultValue) - { - if (value == null) - { - value = defaultValue; - saveConfig(); - } - } - - public void set(IConfigType type, T entry) - { - setValue(type.configValue(entry)); - } - - public String getValue() - { - return value; - } - - public void setValue(String value) - { - this.value = value; - saveConfig(); - } - - public String getValue(String defaultValue) - { - setDefaultValue(defaultValue); - return value; - } - - public int getIntValue() - { - return Integer.parseInt(getValue()); - } - - public void setIntValue(int i) - { - setValue(Integer.toString(i)); - } - - public int getIntValue(int defaultValue) - { - try - { - if (value != null) - { - return getIntValue(); - } - } catch (NumberFormatException ignored) - { - } - - setIntValue(defaultValue); - return defaultValue; - } - - public boolean getBooleanValue() - { - String value = getValue(); - if (value != null && (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes"))) - { - return true; - } else if (value != null && (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no"))) - { - return false; - } - - throw new NumberFormatException(qualifiedname + ".value=" + value); - } - - public void setBooleanValue(boolean b) - { - setValue(Boolean.toString(b)); - } - - public boolean getBooleanValue(boolean defaultValue) - { - try - { - if (value != null) - { - return getBooleanValue(); - } - } catch (NumberFormatException ignored) - { - } - - setBooleanValue(defaultValue); - return defaultValue; - } - - public int getHexValue() - { - return (int) Long.parseLong(getValue().replace("0x", ""), 16); - } - - public void setHexValue(int i) - { - setValue("0x" + Long.toString(((long) i) << 32 >>> 32, 16)); - } - - public int getHexValue(int defaultValue) - { - try - { - if (value != null) - { - return getHexValue(); - } - } catch (NumberFormatException ignored) - { - } - - setHexValue(defaultValue); - return defaultValue; - } - - public T get(IConfigType type) - { - try - { - return type.valueOf(getValue()); - } catch (Exception e) - { - throw new RuntimeException(e); - } - } - - public T get(IConfigType type, T defaultValue) - { - try - { - if (value != null) - { - return get(type); - } - } catch (Exception ignored) - { - } - - set(type, defaultValue); - return defaultValue; - } - - public void save(PrintWriter writer, int tabs, String bracequalifier, boolean first) - { - String vname; - if (qualifiedname.contains(".") && bracequalifier.length() > 0) - { - vname = qualifiedname.substring(bracequalifier.length() + 1); - } else - { - vname = qualifiedname; - } - - if (newline && !first) - { - ConfigFile.writeLine(writer, "", tabs); - } - - writeComment(writer, tabs); - if (value != null) - { - ConfigFile.writeLine(writer, vname + "=" + value, tabs); - } - - if (!hasChildTags()) - { - return; - } - - if (brace) - { - if (value == null) - { - ConfigFile.writeLine(writer, vname, tabs); - } - ConfigFile.writeLine(writer, "{", tabs); - saveTagTree(writer, tabs + 1, qualifiedname); - ConfigFile.writeLine(writer, "}", tabs); - } else - { - saveTagTree(writer, tabs, bracequalifier); - } - } - - @Override - public ConfigTag setComment(String comment) - { - super.setComment(comment); - return this; - } - - @Override - public ConfigTag setSortMode(int mode) - { - super.setSortMode(mode); - return this; - } - - public ConfigTag setNewLine(boolean b) - { - newline = b; - saveConfig(); - return this; - } - - public ConfigTag useBraces() - { - brace = true; - if (parent.newlinemode == 1) - { - newline = true; - } - - saveConfig(); - return this; - } - - public ConfigTag setPosition(int pos) - { - position = pos; - saveConfig(); - return this; - } - - public boolean containsTag(String tagname) - { - return getTag(tagname, false) != null; - } - - public int getId(String name, int defaultValue) - { - return getTag(name).getIntValue(defaultValue); - } - - public int getId(String name) - { - int ret = getId(name, IDBase); - IDBase = ret + 1; - return ret; - } - - public int getAcheivementId(String name, int defaultValue) - { - return getTag(name).getIntValue(defaultValue); - } - - public ConfigTag setBaseID(int i) - { - IDBase = i; - return this; - } - - public interface IConfigType - { - public String configValue(T entry); - - public T valueOf(String text) throws Exception; - } -} diff --git a/src/main/java/codechicken/lib/config/ConfigTagParent.java b/src/main/java/codechicken/lib/config/ConfigTagParent.java deleted file mode 100644 index 824778e7..00000000 --- a/src/main/java/codechicken/lib/config/ConfigTagParent.java +++ /dev/null @@ -1,263 +0,0 @@ -package codechicken.lib.config; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.*; -import java.util.Map.Entry; - -public abstract class ConfigTagParent -{ - public String comment; - /** - * 0 = name, 1 = value - */ - public int sortMode = 0; - /** - * The mode for determining when child tags should leave a blank line between them and the one above - * 0 = never, 1 = when braced, 2 = always - */ - public int newlinemode = 1; - private TreeMap childtags = new TreeMap(); - - public abstract void saveConfig(); - - public abstract String getNameQualifier(); - - public ConfigTagParent setComment(String comment) - { - this.comment = comment; - saveConfig(); - return this; - } - - public ConfigTagParent setSortMode(int mode) - { - sortMode = mode; - saveConfig(); - return this; - } - - public ConfigTagParent setNewLineMode(int mode) - { - newlinemode = mode; - for (Entry entry : childtags.entrySet()) - { - ConfigTag tag = entry.getValue(); - if (newlinemode == 0) - { - tag.newline = false; - } else if (newlinemode == 1) - { - tag.newline = tag.brace; - } else if (newlinemode == 2) - { - tag.newline = true; - } - } - saveConfig(); - return this; - } - - public Map childTagMap() - { - return childtags; - } - - public boolean hasChildTags() - { - return !childtags.isEmpty(); - } - - public boolean containsTag(String tagname) - { - return getTag(tagname, false) != null; - } - - public ConfigTag getNewTag(String tagname) - { - return new ConfigTag(this, tagname); - } - - public ConfigTag getTag(String tagname, boolean create) - { - int dotpos = tagname.indexOf("."); - String basetagname = dotpos == -1 ? tagname : tagname.substring(0, dotpos); - ConfigTag basetag = childtags.get(basetagname); - if (basetag == null) - { - if (!create) - { - return null; - } - - basetag = getNewTag(basetagname); - saveConfig(); - } - if (dotpos == -1) - { - return basetag; - } - - return basetag.getTag(tagname.substring(dotpos + 1), create); - } - - public ConfigTag getTag(String tagname) - { - return getTag(tagname, true); - } - - public boolean removeTag(String tagname) - { - ConfigTag tag = getTag(tagname, false); - if (tag == null) - { - return false; - } - - int dotpos = tagname.lastIndexOf("."); - String lastpart = dotpos == -1 ? tagname : tagname.substring(dotpos + 1, tagname.length()); - if (tag.parent != null) - { - boolean ret = tag.parent.childtags.remove(lastpart) != null; - if (ret) - { - saveConfig(); - } - return ret; - } - - return false; - } - - public void addChild(ConfigTag tag) - { - childtags.put(tag.name, tag); - } - - public ArrayList getSortedTagList() - { - ArrayList taglist = new ArrayList(childtags.size()); - for (Entry tag : childtags.entrySet()) - taglist.add((T) tag.getValue()); - - Collections.sort(taglist, new TagOrderComparator(sortMode)); - return taglist; - } - - public void loadChildren(BufferedReader reader) - { - String comment = ""; - String bracequalifier = ""; - try - { - while (true) - { - String line = ConfigFile.readLine(reader); - if (line == null) - { - break; - } - if (line.startsWith("#")) - { - if (comment.equals("")) - { - comment = line.substring(1); - } else - { - comment = comment + "\n" + line.substring(1); - } - } else if (line.contains("=")) - { - String qualifiedname = line.substring(0, line.indexOf("=")); - getTag(qualifiedname) - .onLoaded() - .setComment(comment) - .setValue(line.substring(line.indexOf("=") + 1)); - comment = ""; - bracequalifier = qualifiedname; - } else if (line.equals("{")) - { - getTag(bracequalifier).setComment(comment).useBraces().loadChildren(reader); - comment = ""; - bracequalifier = ""; - } else if (line.equals("}")) - { - break; - } else - { - bracequalifier = line; - } - } - } catch (IOException e) - { - throw new RuntimeException(e); - } - } - - public void saveTagTree(PrintWriter writer, int tabs, String bracequalifier) - { - boolean first = true; - for (ConfigTag tag : getSortedTagList()) - { - tag.save(writer, tabs, bracequalifier, first); - first = false; - } - } - - public void writeComment(PrintWriter writer, int tabs) - { - if (comment != null && !comment.equals("")) - { - String[] comments = comment.split("\n"); - for (int i = 0; i < comments.length; i++) - ConfigFile.writeLine(writer, "#" + comments[i], tabs); - } - } - - public static class TagOrderComparator implements Comparator - { - int sortMode; - - public TagOrderComparator(int sortMode) - { - this.sortMode = sortMode; - } - - public int compare(ConfigTag o1, ConfigTag o2) - { - if (o1.position != o2.position) - { - return compareInt(o1.position, o2.position); - } - if (o1.brace != o2.brace) - { - return o1.brace ? 1 : -1;//braced one goes after - } - switch (sortMode) - { - case 1: - if (o1.value.equals(o2.value)) - { - return 0; - } - if (o1.value == null) - { - return 1; - } - if (o2.value == null) - { - return -1; - } - return o1.value.compareTo(o2.value); - default: - return o1.name.compareTo(o2.name); - } - } - - private int compareInt(int a, int b) - { - return a == b ? 0 : a < b ? -1 : 1; - } - } -} diff --git a/src/main/java/codechicken/lib/config/DefaultingConfigFile.java b/src/main/java/codechicken/lib/config/DefaultingConfigFile.java deleted file mode 100644 index 075794b2..00000000 --- a/src/main/java/codechicken/lib/config/DefaultingConfigFile.java +++ /dev/null @@ -1,24 +0,0 @@ -package codechicken.lib.config; - -import java.io.File; - -public class DefaultingConfigFile extends ConfigFile -{ - public DefaultingConfigFile(File file) - { - super(); - if (file.exists()) - { - load(file); - } - } - - @Override - public void saveConfig() - { - if (file != null) - { - super.saveConfig(); - } - } -} diff --git a/src/main/java/codechicken/lib/config/SimpleProperties.java b/src/main/java/codechicken/lib/config/SimpleProperties.java deleted file mode 100644 index 5e273be4..00000000 --- a/src/main/java/codechicken/lib/config/SimpleProperties.java +++ /dev/null @@ -1,158 +0,0 @@ -package codechicken.lib.config; - -import java.io.*; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Map.Entry; - -public class SimpleProperties -{ - public HashMap propertyMap = new HashMap(); - public File propertyFile; - public boolean saveOnChange = false; - public String encoding; - - private boolean loading = false; - - public SimpleProperties(File file, boolean saveOnChange, String encoding) - { - propertyFile = file; - this.saveOnChange = saveOnChange; - this.encoding = encoding; - } - - public SimpleProperties(File file, boolean saveOnChange) - { - this(file, saveOnChange, Charset.defaultCharset().name()); - } - - public SimpleProperties(File file) - { - this(file, true); - } - - public void load() - { - clear(); - loading = true; - - try - { - BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(propertyFile), encoding)); - while (true) - { - String read = reader.readLine(); - if (read == null) - { - break; - } - - int equalIndex = read.indexOf('='); - if (equalIndex == -1) - { - continue; - } - - setProperty(read.substring(0, equalIndex), read.substring(equalIndex + 1)); - } - reader.close(); - } catch (Exception e) - { - throw new RuntimeException(e); - } - loading = false; - } - - public void save() - { - try - { - PrintStream writer = new PrintStream(propertyFile); - - for (Entry entry : propertyMap.entrySet()) - { - writer.println(entry.getKey() + "=" + entry.getValue()); - } - - writer.close(); - } catch (Exception e) - { - throw new RuntimeException(e); - } - } - - public void clear() - { - propertyMap.clear(); - } - - public boolean hasProperty(String key) - { - return propertyMap.containsKey(key); - } - - public void removeProperty(String key) - { - if (propertyMap.remove(key) != null && saveOnChange && !loading) - { - save(); - } - } - - public void setProperty(String key, int value) - { - setProperty(key, Integer.toString(value)); - } - - public void setProperty(String key, boolean value) - { - setProperty(key, Boolean.toString(value)); - } - - public void setProperty(String key, String value) - { - propertyMap.put(key, value); - if (saveOnChange && !loading) - { - save(); - } - } - - public int getProperty(String property, int defaultvalue) - { - try - { - return Integer.parseInt(getProperty(property, Integer.toString(defaultvalue))); - } catch (NumberFormatException nfe) - { - return defaultvalue; - } - } - - public boolean getProperty(String property, boolean defaultvalue) - { - try - { - return Boolean.parseBoolean(getProperty(property, Boolean.toString(defaultvalue))); - } catch (NumberFormatException nfe) - { - return defaultvalue; - } - } - - public String getProperty(String property, String defaultvalue) - { - String value = propertyMap.get(property); - if (value == null) - { - setProperty(property, defaultvalue); - return defaultvalue; - } - return value; - } - - public String getProperty(String property) - { - return propertyMap.get(property); - } -} diff --git a/src/main/java/codechicken/lib/lighting/LC.java b/src/main/java/codechicken/lib/lighting/LC.java deleted file mode 100644 index 4d054fd1..00000000 --- a/src/main/java/codechicken/lib/lighting/LC.java +++ /dev/null @@ -1,102 +0,0 @@ -package codechicken.lib.lighting; - -import codechicken.lib.render.CCModel; -import codechicken.lib.util.Copyable; -import codechicken.lib.vec.Rotation; -import codechicken.lib.vec.Vector3; - -public class LC implements Copyable -{ - public int side; - public float fa; - public float fb; - public float fc; - public float fd; - - public LC() - { - this(0, 0, 0, 0, 0); - } - - public LC(int s, float a, float b, float c, float d) - { - side = s; - fa = a; - fb = b; - fc = c; - fd = d; - } - - public LC set(int s, float a, float b, float c, float d) - { - side = s; - fa = a; - fb = b; - fc = c; - fd = d; - return this; - } - - public LC set(LC lc) - { - return set(lc.side, lc.fa, lc.fb, lc.fc, lc.fd); - } - - public LC compute(Vector3 vec, Vector3 normal) - { - int side = CCModel.findSide(normal); - if (side < 0) - { - return set(12, 1, 0, 0, 0); - } - return compute(vec, side); - } - - public LC compute(Vector3 vec, int side) - { - boolean offset = false; - switch (side) - { - case 0: - offset = vec.y <= 0; - break; - case 1: - offset = vec.y >= 1; - break; - case 2: - offset = vec.z <= 0; - break; - case 3: - offset = vec.z >= 1; - break; - case 4: - offset = vec.x <= 0; - break; - case 5: - offset = vec.x >= 1; - break; - } - if (!offset) - { - side += 6; - } - return computeO(vec, side); - } - - public LC computeO(Vector3 vec, int side) - { - Vector3 v1 = Rotation.axes[((side & 0xE) + 3) % 6]; - Vector3 v2 = Rotation.axes[((side & 0xE) + 5) % 6]; - float d1 = (float) vec.scalarProject(v1); - float d2 = 1 - d1; - float d3 = (float) vec.scalarProject(v2); - float d4 = 1 - d3; - return set(side, d2 * d4, d2 * d3, d1 * d4, d1 * d3); - } - - @Override - public LC copy() - { - return new LC(side, fa, fb, fc, fd); - } -} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/lighting/LightMatrix.java b/src/main/java/codechicken/lib/lighting/LightMatrix.java deleted file mode 100644 index fff9dcc5..00000000 --- a/src/main/java/codechicken/lib/lighting/LightMatrix.java +++ /dev/null @@ -1,188 +0,0 @@ -package codechicken.lib.lighting; - -import codechicken.lib.colour.ColourRGBA; -import codechicken.lib.render.CCRenderState; -import codechicken.lib.vec.BlockCoord; -import net.minecraft.block.Block; -import net.minecraft.client.Minecraft; -import net.minecraft.world.IBlockAccess; - -/** - * Note that when using the class as a vertex transformer, the vertices are assumed to be within the BB (x, y, z) -> (x+1, y+1, z+1) - */ -public class LightMatrix implements CCRenderState.IVertexOperation -{ - public static final int operationIndex = CCRenderState.registerOperation(); - /** - * The 9 positions in the sample array for each side, sides >= 6 are centered on sample 13 (the block itself) - */ - public static final int[][] ssamplem = new int[][]{ - {0, 1, 2, 3, 4, 5, 6, 7, 8}, - {18, 19, 20, 21, 22, 23, 24, 25, 26}, - {0, 9, 18, 1, 10, 19, 2, 11, 20}, - {6, 15, 24, 7, 16, 25, 8, 17, 26}, - {0, 3, 6, 9, 12, 15, 18, 21, 24}, - {2, 5, 8, 11, 14, 17, 20, 23, 26}, - {9, 10, 11, 12, 13, 14, 15, 16, 17}, - {9, 10, 11, 12, 13, 14, 15, 16, 17}, - {3, 12, 21, 4, 13, 22, 5, 14, 23}, - {3, 12, 21, 4, 13, 22, 5, 14, 23}, - {1, 4, 7, 10, 13, 16, 19, 22, 25}, - {1, 4, 7, 10, 13, 16, 19, 22, 25}, - {13, 13, 13, 13, 13, 13, 13, 13, 13}}; - public static final int[][] qsamplem = new int[][]{//the positions in the side sample array for each corner - {0, 1, 3, 4}, - {5, 1, 2, 4}, - {6, 7, 3, 4}, - {5, 7, 8, 4}}; - public static final float[] sideao = new float[]{ - 0.5F, 1F, 0.8F, 0.8F, 0.6F, 0.6F, - 0.5F, 1F, 0.8F, 0.8F, 0.6F, 0.6F, - 1F}; - public int computed = 0; - public float[][] ao = new float[13][4]; - public int[][] brightness = new int[13][4]; - public IBlockAccess access; - public BlockCoord pos = new BlockCoord(); - private int sampled = 0; - private float[] aSamples = new float[27]; - private int[] bSamples = new int[27]; - - /*static - { - int[][] os = new int[][]{ - {0,-1,0}, - {0, 1,0}, - {0,0,-1}, - {0,0, 1}, - {-1,0,0}, - { 1,0,0}}; - - for(int s = 0; s < 12; s++) - { - int[] d0 = s < 6 ? new int[]{os[s][0]+1, os[s][1]+1, os[s][2]+1} : new int[]{1, 1, 1}; - int[] d1 = os[((s&0xE)+3)%6]; - int[] d2 = os[((s&0xE)+5)%6]; - for(int a = -1; a <= 1; a++) - for(int b = -1; b <= 1; b++) - ssamplem[s][(a+1)*3+b+1] = (d0[1]+d1[1]*a+d2[1]*b)*9+(d0[2]+d1[2]*a+d2[2]*b)*3+(d0[0]+d1[0]*a+d2[0]*b); - } - System.out.println(Arrays.deepToString(ssamplem)); - }*/ - - public static float interpAO(float a, float b, float c, float d) - { - return (a + b + c + d) / 4F; - } - - public static int interpBrightness(int a, int b, int c, int d) - { - if (a == 0) - { - a = d; - } - if (b == 0) - { - b = d; - } - if (c == 0) - { - c = d; - } - return (a + b + c + d) >> 2 & 0xFF00FF; - } - - public void locate(IBlockAccess a, int x, int y, int z) - { - access = a; - pos.set(x, y, z); - computed = 0; - sampled = 0; - } - - public void sample(int i) - { - if ((sampled & 1 << i) == 0) - { - int x = pos.x + (i % 3) - 1; - int y = pos.y + (i / 9) - 1; - int z = pos.z + (i / 3 % 3) - 1; - Block b = access.getBlock(x, y, z); - bSamples[i] = access.getLightBrightnessForSkyBlocks(x, y, z, b.getLightValue(access, x, y, z)); - aSamples[i] = b.getAmbientOcclusionLightValue(); - sampled |= 1 << i; - } - } - - public int[] brightness(int side) - { - sideSample(side); - return brightness[side]; - } - - public float[] ao(int side) - { - sideSample(side); - return ao[side]; - } - - public void sideSample(int side) - { - if ((computed & 1 << side) == 0) - { - int[] ssample = ssamplem[side]; - for (int q = 0; q < 4; q++) - { - int[] qsample = qsamplem[q]; - if (Minecraft.isAmbientOcclusionEnabled()) - { - interp(side, q, ssample[qsample[0]], ssample[qsample[1]], ssample[qsample[2]], ssample[qsample[3]]); - } else - { - interp(side, q, ssample[4], ssample[4], ssample[4], ssample[4]); - } - } - computed |= 1 << side; - } - } - - private void interp(int s, int q, int a, int b, int c, int d) - { - sample(a); - sample(b); - sample(c); - sample(d); - ao[s][q] = interpAO(aSamples[a], aSamples[b], aSamples[c], aSamples[d]) * sideao[s]; - brightness[s][q] = interpBrightness(bSamples[a], bSamples[b], bSamples[c], bSamples[d]); - } - - @Override - public boolean load() - { - if (!CCRenderState.computeLighting) - { - return false; - } - - CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib); - CCRenderState.pipeline.addDependency(CCRenderState.lightCoordAttrib); - return true; - } - - @Override - public void operate() - { - LC lc = CCRenderState.lc; - float[] a = ao(lc.side); - float f = (a[0] * lc.fa + a[1] * lc.fb + a[2] * lc.fc + a[3] * lc.fd); - int[] b = brightness(lc.side); - CCRenderState.setColour(ColourRGBA.multiplyC(CCRenderState.colour, f)); - CCRenderState.setBrightness((int) (b[0] * lc.fa + b[1] * lc.fb + b[2] * lc.fc + b[3] * lc.fd) & 0xFF00FF); - } - - @Override - public int operationID() - { - return operationIndex; - } -} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/lighting/LightModel.java b/src/main/java/codechicken/lib/lighting/LightModel.java deleted file mode 100644 index d21bb5cc..00000000 --- a/src/main/java/codechicken/lib/lighting/LightModel.java +++ /dev/null @@ -1,129 +0,0 @@ -package codechicken.lib.lighting; - -import codechicken.lib.render.CCRenderState; -import codechicken.lib.vec.Rotation; -import codechicken.lib.vec.Vector3; - -public class LightModel implements CCRenderState.IVertexOperation -{ - public static final int operationIndex = CCRenderState.registerOperation(); - public static LightModel standardLightModel; - - static - { - standardLightModel = new LightModel() - .setAmbient(new Vector3(0.4, 0.4, 0.4)) - .addLight(new Light(new Vector3(0.2, 1, -0.7)) - .setDiffuse(new Vector3(0.6, 0.6, 0.6))) - .addLight(new Light(new Vector3(-0.2, 1, 0.7)) - .setDiffuse(new Vector3(0.6, 0.6, 0.6))); - } - - private Vector3 ambient = new Vector3(); - private Light[] lights = new Light[8]; - private int lightCount; - - public LightModel addLight(Light light) - { - lights[lightCount++] = light; - return this; - } - - public LightModel setAmbient(Vector3 vec) - { - ambient.set(vec); - return this; - } - - /** - * @param colour The pre-lighting vertex colour. RGBA format - * @param normal The normal at the vertex - * @return The lighting applied colour - */ - public int apply(int colour, Vector3 normal) - { - Vector3 n_colour = ambient.copy(); - for (int l = 0; l < lightCount; l++) - { - Light light = lights[l]; - double n_l = light.position.dotProduct(normal); - double f = n_l > 0 ? 1 : 0; - n_colour.x += light.ambient.x + f * light.diffuse.x * n_l; - n_colour.y += light.ambient.y + f * light.diffuse.y * n_l; - n_colour.z += light.ambient.z + f * light.diffuse.z * n_l; - } - - if (n_colour.x > 1) - { - n_colour.x = 1; - } - if (n_colour.y > 1) - { - n_colour.y = 1; - } - if (n_colour.z > 1) - { - n_colour.z = 1; - } - - n_colour.multiply((colour >>> 24) / 255D, (colour >> 16 & 0xFF) / 255D, (colour >> 8 & 0xFF) / 255D); - return (int) (n_colour.x * 255) << 24 | (int) (n_colour.y * 255) << 16 | (int) (n_colour.z * 255) << 8 | colour & 0xFF; - } - - @Override - public boolean load() - { - if (!CCRenderState.computeLighting) - { - return false; - } - - CCRenderState.pipeline.addDependency(CCRenderState.normalAttrib); - CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib); - return true; - } - - @Override - public void operate() - { - CCRenderState.setColour(apply(CCRenderState.colour, CCRenderState.normal)); - } - - @Override - public int operationID() - { - return operationIndex; - } - - public PlanarLightModel reducePlanar() - { - int[] colours = new int[6]; - for (int i = 0; i < 6; i++) - colours[i] = apply(-1, Rotation.axes[i]); - return new PlanarLightModel(colours); - } - - public static class Light - { - public Vector3 ambient = new Vector3(); - public Vector3 diffuse = new Vector3(); - public Vector3 position; - - public Light(Vector3 pos) - { - position = pos.copy().normalize(); - } - - public Light setDiffuse(Vector3 vec) - { - diffuse.set(vec); - return this; - } - - public Light setAmbient(Vector3 vec) - { - ambient.set(vec); - return this; - } - } -} diff --git a/src/main/java/codechicken/lib/lighting/PlanarLightMatrix.java b/src/main/java/codechicken/lib/lighting/PlanarLightMatrix.java deleted file mode 100644 index 37713417..00000000 --- a/src/main/java/codechicken/lib/lighting/PlanarLightMatrix.java +++ /dev/null @@ -1,61 +0,0 @@ -package codechicken.lib.lighting; - -import codechicken.lib.render.CCRenderState; -import codechicken.lib.vec.BlockCoord; -import net.minecraft.block.Block; -import net.minecraft.world.IBlockAccess; - -public class PlanarLightMatrix extends PlanarLightModel -{ - public static final int operationIndex = CCRenderState.registerOperation(); - public static PlanarLightMatrix instance = new PlanarLightMatrix(); - - public IBlockAccess access; - public BlockCoord pos = new BlockCoord(); - public int[] brightness = new int[6]; - private int sampled = 0; - - public PlanarLightMatrix() - { - super(PlanarLightModel.standardLightModel.colours); - } - - public PlanarLightMatrix locate(IBlockAccess a, int x, int y, int z) - { - access = a; - pos.set(x, y, z); - sampled = 0; - return this; - } - - public int brightness(int side) - { - if ((sampled & 1 << side) == 0) - { - Block b = access.getBlock(pos.x, pos.y, pos.z); - brightness[side] = access.getLightBrightnessForSkyBlocks(pos.x, pos.y, pos.z, b.getLightValue(access, pos.x, pos.y, pos.z)); - sampled |= 1 << side; - } - return brightness[side]; - } - - @Override - public boolean load() - { - CCRenderState.pipeline.addDependency(CCRenderState.sideAttrib); - return true; - } - - @Override - public void operate() - { - super.operate(); - CCRenderState.setBrightness(brightness(CCRenderState.side)); - } - - @Override - public int operationID() - { - return operationIndex; - } -} diff --git a/src/main/java/codechicken/lib/lighting/PlanarLightModel.java b/src/main/java/codechicken/lib/lighting/PlanarLightModel.java deleted file mode 100644 index b88bf8b3..00000000 --- a/src/main/java/codechicken/lib/lighting/PlanarLightModel.java +++ /dev/null @@ -1,44 +0,0 @@ -package codechicken.lib.lighting; - -import codechicken.lib.colour.ColourRGBA; -import codechicken.lib.render.CCRenderState; - -/** - * Faster precomputed version of LightModel that only works for axis planar sides - */ -public class PlanarLightModel implements CCRenderState.IVertexOperation -{ - public static PlanarLightModel standardLightModel = LightModel.standardLightModel.reducePlanar(); - - public int[] colours; - - public PlanarLightModel(int[] colours) - { - this.colours = colours; - } - - @Override - public boolean load() - { - if (!CCRenderState.computeLighting) - { - return false; - } - - CCRenderState.pipeline.addDependency(CCRenderState.sideAttrib); - CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib); - return true; - } - - @Override - public void operate() - { - CCRenderState.setColour(ColourRGBA.multiply(CCRenderState.colour, colours[CCRenderState.side])); - } - - @Override - public int operationID() - { - return LightModel.operationIndex; - } -} diff --git a/src/main/java/codechicken/lib/lighting/SimpleBrightnessModel.java b/src/main/java/codechicken/lib/lighting/SimpleBrightnessModel.java deleted file mode 100644 index 41e23789..00000000 --- a/src/main/java/codechicken/lib/lighting/SimpleBrightnessModel.java +++ /dev/null @@ -1,60 +0,0 @@ -package codechicken.lib.lighting; - -import codechicken.lib.render.CCRenderState; -import codechicken.lib.vec.BlockCoord; -import net.minecraft.block.Block; -import net.minecraft.world.IBlockAccess; - -/** - * Faster precomputed version of LightModel that only works for axis planar sides - */ -public class SimpleBrightnessModel implements CCRenderState.IVertexOperation -{ - public static final int operationIndex = CCRenderState.registerOperation(); - public static SimpleBrightnessModel instance = new SimpleBrightnessModel(); - - public IBlockAccess access; - public BlockCoord pos = new BlockCoord(); - - private int sampled = 0; - private int[] samples = new int[6]; - private BlockCoord c = new BlockCoord(); - - public void locate(IBlockAccess a, int x, int y, int z) - { - access = a; - pos.set(x, y, z); - sampled = 0; - } - - public int sample(int side) - { - if ((sampled & 1 << side) == 0) - { - c.set(pos).offset(side); - Block block = access.getBlock(c.x, c.y, c.z); - samples[side] = access.getLightBrightnessForSkyBlocks(c.x, c.y, c.z, block.getLightValue(access, c.x, c.y, c.z)); - sampled |= 1 << side; - } - return samples[side]; - } - - @Override - public boolean load() - { - CCRenderState.pipeline.addDependency(CCRenderState.sideAttrib); - return true; - } - - @Override - public void operate() - { - CCRenderState.setBrightness(sample(CCRenderState.side)); - } - - @Override - public int operationID() - { - return operationIndex; - } -} diff --git a/src/main/java/codechicken/lib/math/MathHelper.java b/src/main/java/codechicken/lib/math/MathHelper.java deleted file mode 100644 index 1be291d7..00000000 --- a/src/main/java/codechicken/lib/math/MathHelper.java +++ /dev/null @@ -1,186 +0,0 @@ -package codechicken.lib.math; - -public class MathHelper -{ - public static final double phi = 1.618033988749894; - public static final double pi = Math.PI; - public static final double todeg = 57.29577951308232; - public static final double torad = 0.017453292519943; - public static final double sqrt2 = 1.414213562373095; - - public static double[] SIN_TABLE = new double[65536]; - - static - { - for (int i = 0; i < 65536; ++i) - SIN_TABLE[i] = Math.sin(i / 65536D * 2 * Math.PI); - - SIN_TABLE[0] = 0; - SIN_TABLE[16384] = 1; - SIN_TABLE[32768] = 0; - SIN_TABLE[49152] = 1; - } - - public static double sin(double d) - { - return SIN_TABLE[(int) ((float) d * 10430.378F) & 65535]; - } - - public static double cos(double d) - { - return SIN_TABLE[(int) ((float) d * 10430.378F + 16384.0F) & 65535]; - } - - /** - * @param a The value - * @param b The value to approach - * @param max The maximum step - * @return the closed value to b no less than max from a - */ - public static float approachLinear(float a, float b, float max) - { - return (a > b) ? - (a - b < max ? b : a - max) : - (b - a < max ? b : a + max); - } - - /** - * @param a The value - * @param b The value to approach - * @param max The maximum step - * @return the closed value to b no less than max from a - */ - public static double approachLinear(double a, double b, double max) - { - return (a > b) ? - (a - b < max ? b : a - max) : - (b - a < max ? b : a + max); - } - - /** - * @param a The first value - * @param b The second value - * @param d The interpolation factor, between 0 and 1 - * @return a+(b-a)*d - */ - public static float interpolate(float a, float b, float d) - { - return a + (b - a) * d; - } - - /** - * @param a The first value - * @param b The second value - * @param d The interpolation factor, between 0 and 1 - * @return a+(b-a)*d - */ - public static double interpolate(double a, double b, double d) - { - return a + (b - a) * d; - } - - /** - * @param a The value - * @param b The value to approach - * @param ratio The ratio to reduce the difference by - * @return a+(b-a)*ratio - */ - public static double approachExp(double a, double b, double ratio) - { - return a + (b - a) * ratio; - } - - /** - * @param a The value - * @param b The value to approach - * @param ratio The ratio to reduce the difference by - * @param cap The maximum amount to advance by - * @return a+(b-a)*ratio - */ - public static double approachExp(double a, double b, double ratio, double cap) - { - double d = (b - a) * ratio; - if (Math.abs(d) > cap) - { - d = Math.signum(d) * cap; - } - return a + d; - } - - /** - * @param a The value - * @param b The value to approach - * @param ratio The ratio to reduce the difference by - * @param c The value to retreat from - * @param kick The difference when a == c - * @return - */ - public static double retreatExp(double a, double b, double c, double ratio, double kick) - { - double d = (Math.abs(c - a) + kick) * ratio; - if (d > Math.abs(b - a)) - { - return b; - } - return a + Math.signum(b - a) * d; - } - - /** - * @param value The value - * @param min The min value - * @param max The max value - * @return The clipped value between min and max - */ - public static double clip(double value, double min, double max) - { - if (value > max) - { - value = max; - } - if (value < min) - { - value = min; - } - return value; - } - - /** - * @return a <= x <= b - */ - public static boolean between(double a, double x, double b) - { - return a <= x && x <= b; - } - - public static int approachExpI(int a, int b, double ratio) - { - int r = (int) Math.round(approachExp(a, b, ratio)); - return r == a ? b : r; - } - - public static int retreatExpI(int a, int b, int c, double ratio, int kick) - { - int r = (int) Math.round(retreatExp(a, b, c, ratio, kick)); - return r == a ? b : r; - } - - public static int floor_double(double d) - { - return net.minecraft.util.MathHelper.floor_double(d); - } - - public static int roundAway(double d) - { - return (int) (d < 0 ? Math.floor(d) : Math.ceil(d)); - } - - public static int compare(int a, int b) - { - return a == b ? 0 : a < b ? -1 : 1; - } - - public static int compare(double a, double b) - { - return a == b ? 0 : a < b ? -1 : 1; - } -} diff --git a/src/main/java/codechicken/lib/render/BlockRenderer.java b/src/main/java/codechicken/lib/render/BlockRenderer.java deleted file mode 100644 index 10830925..00000000 --- a/src/main/java/codechicken/lib/render/BlockRenderer.java +++ /dev/null @@ -1,211 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.lighting.LC; -import codechicken.lib.render.CCRenderState.VertexAttribute; -import codechicken.lib.vec.Cuboid6; - -public class BlockRenderer -{ - public static FullBlock fullBlock = new FullBlock(); - private static BlockFace face = new BlockFace(); - - public static void renderFullBlock(int sideMask) - { - CCRenderState.setModel(fullBlock); - renderFaces(sideMask); - } - - /** - * Renders faces of a block-like model based on a sideMask. Eg for side 2, verts 8-11 will be rendered - * - * @param sideMask A mask of faces not to render - */ - public static void renderFaces(int sideMask) - { - if (sideMask == 0x3F) return; - for (int s = 0; s < 6; s++) - if ((sideMask & 1 << s) == 0) - { - CCRenderState.setVertexRange(s * 4, (s + 1) * 4); - CCRenderState.render(); - } - } - - /** - * Renders faces of a cuboid with texture coordinates mapped to match a standard minecraft block - * - * @param bounds The bounding cuboid to render - * @param sideMask A mask of faces not to render - */ - public static void renderCuboid(Cuboid6 bounds, int sideMask) - { - if (sideMask == 0x3F) return; - - CCRenderState.setModel(face); - for (int s = 0; s < 6; s++) - if ((sideMask & 1 << s) == 0) - { - face.loadCuboidFace(bounds, s); - CCRenderState.render(); - } - } - - public static class BlockFace implements CCRenderState.IVertexSource - { - public Vertex5[] verts = new Vertex5[]{new Vertex5(), new Vertex5(), new Vertex5(), new Vertex5()}; - public LC[] lightCoords = new LC[]{new LC(), new LC(), new LC(), new LC()}; - public boolean lcComputed = false; - public int side; - - @Override - public Vertex5[] getVertices() - { - return verts; - } - - @Override - public T getAttributes(CCRenderState.VertexAttribute attr) - { - return attr == CCRenderState.lightCoordAttrib && lcComputed ? (T) lightCoords : null; - } - - @Override - public boolean hasAttribute(CCRenderState.VertexAttribute attr) - { - return attr == CCRenderState.sideAttrib || attr == CCRenderState.lightCoordAttrib && lcComputed; - } - - @Override - public void prepareVertex() - { - CCRenderState.side = side; - } - - public BlockFace computeLightCoords() - { - if (!lcComputed) - { - for (int i = 0; i < 4; i++) - lightCoords[i].compute(verts[i].vec, side); - lcComputed = true; - } - return this; - } - - public BlockFace loadCuboidFace(Cuboid6 c, int side) - { - double x1 = c.min.x; - double x2 = c.max.x; - double y1 = c.min.y; - double y2 = c.max.y; - double z1 = c.min.z; - double z2 = c.max.z; - double u1; - double u2; - double v1; - double v2; - this.side = side; - lcComputed = false; - - switch (side) - { - case 0: - u1 = x1; - v1 = z1; - u2 = x2; - v2 = z2; - verts[0].set(x1, y1, z2, u1, v2, 0); - verts[1].set(x1, y1, z1, u1, v1, 0); - verts[2].set(x2, y1, z1, u2, v1, 0); - verts[3].set(x2, y1, z2, u2, v2, 0); - break; - case 1: - u1 = x1; - v1 = z1; - u2 = x2; - v2 = z2; - verts[0].set(x2, y2, z2, u2, v2, 1); - verts[1].set(x2, y2, z1, u2, v1, 1); - verts[2].set(x1, y2, z1, u1, v1, 1); - verts[3].set(x1, y2, z2, u1, v2, 1); - break; - case 2: - u1 = 1 - x1; - v1 = 1 - y2; - u2 = 1 - x2; - v2 = 1 - y1; - verts[0].set(x1, y1, z1, u1, v2, 2); - verts[1].set(x1, y2, z1, u1, v1, 2); - verts[2].set(x2, y2, z1, u2, v1, 2); - verts[3].set(x2, y1, z1, u2, v2, 2); - break; - case 3: - u1 = x1; - v1 = 1 - y2; - u2 = x2; - v2 = 1 - y1; - verts[0].set(x2, y1, z2, u2, v2, 3); - verts[1].set(x2, y2, z2, u2, v1, 3); - verts[2].set(x1, y2, z2, u1, v1, 3); - verts[3].set(x1, y1, z2, u1, v2, 3); - break; - case 4: - u1 = z1; - v1 = 1 - y2; - u2 = z2; - v2 = 1 - y1; - verts[0].set(x1, y1, z2, u2, v2, 4); - verts[1].set(x1, y2, z2, u2, v1, 4); - verts[2].set(x1, y2, z1, u1, v1, 4); - verts[3].set(x1, y1, z1, u1, v2, 4); - break; - case 5: - u1 = 1 - z1; - v1 = 1 - y2; - u2 = 1 - z2; - v2 = 1 - y1; - verts[0].set(x2, y1, z1, u1, v2, 5); - verts[1].set(x2, y2, z1, u1, v1, 5); - verts[2].set(x2, y2, z2, u2, v1, 5); - verts[3].set(x2, y1, z2, u2, v2, 5); - } - return this; - } - } - - public static class FullBlock implements CCRenderState.IVertexSource - { - public Vertex5[] verts = CCModel.quadModel(24).generateBlock(0, Cuboid6.full).verts; - public LC[] lightCoords = new LC[24]; - - public FullBlock() - { - for (int i = 0; i < 24; i++) - lightCoords[i] = new LC().compute(verts[i].vec, i / 4); - } - - @Override - public Vertex5[] getVertices() - { - return verts; - } - - @Override - public T getAttributes(VertexAttribute attr) - { - return attr == CCRenderState.lightCoordAttrib ? (T) lightCoords : null; - } - - @Override - public boolean hasAttribute(VertexAttribute attr) - { - return attr == CCRenderState.sideAttrib || attr == CCRenderState.lightCoordAttrib; - } - - @Override - public void prepareVertex() - { - CCRenderState.side = CCRenderState.vertexIndex >> 2; - } - } -} diff --git a/src/main/java/codechicken/lib/render/CCModel.java b/src/main/java/codechicken/lib/render/CCModel.java deleted file mode 100644 index 267419e4..00000000 --- a/src/main/java/codechicken/lib/render/CCModel.java +++ /dev/null @@ -1,1193 +0,0 @@ -package codechicken.lib.render; - - -import codechicken.lib.lighting.LC; -import codechicken.lib.lighting.LightModel; -import codechicken.lib.render.uv.UV; -import codechicken.lib.render.uv.UVTransformation; -import codechicken.lib.render.uv.UVTranslation; -import codechicken.lib.util.Copyable; -import codechicken.lib.vec.*; -import net.minecraft.client.Minecraft; -import net.minecraft.util.ResourceLocation; - -import java.io.*; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static codechicken.lib.vec.Rotation.sideRotations; - -public class CCModel implements CCRenderState.IVertexSource, Copyable -{ - private static class PositionNormalEntry - { - public Vector3 pos; - public LinkedList normals = new LinkedList(); - - public PositionNormalEntry(Vector3 position) - { - pos = position; - } - - public boolean positionEqual(Vector3 v) - { - return pos.x == v.x && pos.y == v.y && pos.z == v.z; - } - - public PositionNormalEntry addNormal(Vector3 normal) - { - normals.add(normal); - return this; - } - } - - public final int vertexMode; - public final int vp; - public Vertex5[] verts; - public ArrayList attributes = new ArrayList(); - - protected CCModel(int vertexMode) - { - if (vertexMode != 7 && vertexMode != 4) - { - throw new IllegalArgumentException("Models must be GL_QUADS or GL_TRIANGLES"); - } - - this.vertexMode = vertexMode; - vp = vertexMode == 7 ? 4 : 3; - } - - public Vector3[] normals() - { - return getAttributes(CCRenderState.normalAttrib); - } - - @Override - public Vertex5[] getVertices() - { - return verts; - } - - @Override - public T getAttributes(CCRenderState.VertexAttribute attr) - { - if (attr.attributeIndex < attributes.size()) - { - return (T) attributes.get(attr.attributeIndex); - } - - return null; - } - - @Override - public boolean hasAttribute(CCRenderState.VertexAttribute attrib) - { - return attrib.attributeIndex < attributes.size() && attributes.get(attrib.attributeIndex) != null; - } - - @Override - public void prepareVertex() - { - } - - public T getOrAllocate(CCRenderState.VertexAttribute attrib) - { - T array = getAttributes(attrib); - if (array == null) - { - while (attributes.size() <= attrib.attributeIndex) - attributes.add(null); - attributes.set(attrib.attributeIndex, array = attrib.newArray(verts.length)); - } - return array; - } - - /** - * Each pixel corresponds to one unit of position when generating the model - * - * @param i Vertex index to start generating at - * @param x1 The minX bound of the box - * @param y1 The minY bound of the box - * @param z1 The minZ bound of the box - * @param w The width of the box - * @param h The height of the box - * @param d The depth of the box - * @param tx The distance of the top left corner of the texture map from the left in pixels - * @param ty The distance of the top left corner of the texture map from the top in pixels - * @param tw The width of the texture in pixels - * @param th The height of the texture in pixels - * @param f The scale of the model, pixels per block, normally 16 - * @return The generated model - */ - public CCModel generateBox(int i, double x1, double y1, double z1, double w, double h, double d, double tx, double ty, double tw, double th, double f) - { - double u1, v1, u2, v2; - double x2 = x1 + w; - double y2 = y1 + h; - double z2 = z1 + d; - x1 /= f; - x2 /= f; - y1 /= f; - y2 /= f; - z1 /= f; - z2 /= f; - - //bottom face - u1 = (tx + d + w) / tw; - v1 = (ty + d) / th; - u2 = (tx + d * 2 + w) / tw; - v2 = ty / th; - verts[i++] = new Vertex5(x1, y1, z2, u1, v2); - verts[i++] = new Vertex5(x1, y1, z1, u1, v1); - verts[i++] = new Vertex5(x2, y1, z1, u2, v1); - verts[i++] = new Vertex5(x2, y1, z2, u2, v2); - - //top face - u1 = (tx + d) / tw; - v1 = (ty + d) / th; - u2 = (tx + d + w) / tw; - v2 = ty / th; - verts[i++] = new Vertex5(x2, y2, z2, u2, v2); - verts[i++] = new Vertex5(x2, y2, z1, u2, v1); - verts[i++] = new Vertex5(x1, y2, z1, u1, v1); - verts[i++] = new Vertex5(x1, y2, z2, u1, v2); - - //front face - u1 = (tx + d + w) / tw; - v1 = (ty + d) / th; - u2 = (tx + d) / tw; - v2 = (ty + d + h) / th; - verts[i++] = new Vertex5(x1, y2, z1, u2, v1); - verts[i++] = new Vertex5(x2, y2, z1, u1, v1); - verts[i++] = new Vertex5(x2, y1, z1, u1, v2); - verts[i++] = new Vertex5(x1, y1, z1, u2, v2); - - //back face - u1 = (tx + d * 2 + w * 2) / tw; - v1 = (ty + d) / th; - u2 = (tx + d * 2 + w) / tw; - v2 = (ty + d + h) / th; - verts[i++] = new Vertex5(x1, y2, z2, u1, v1); - verts[i++] = new Vertex5(x1, y1, z2, u1, v2); - verts[i++] = new Vertex5(x2, y1, z2, u2, v2); - verts[i++] = new Vertex5(x2, y2, z2, u2, v1); - - //left face - u1 = (tx + d) / tw; - v1 = (ty + d) / th; - u2 = (tx) / tw; - v2 = (ty + d + h) / th; - verts[i++] = new Vertex5(x1, y2, z2, u2, v1); - verts[i++] = new Vertex5(x1, y2, z1, u1, v1); - verts[i++] = new Vertex5(x1, y1, z1, u1, v2); - verts[i++] = new Vertex5(x1, y1, z2, u2, v2); - - //right face - u1 = (tx + d * 2 + w) / tw; - v1 = (ty + d) / th; - u2 = (tx + d + w) / tw; - v2 = (ty + d + h) / th; - verts[i++] = new Vertex5(x2, y1, z2, u1, v2); - verts[i++] = new Vertex5(x2, y1, z1, u2, v2); - verts[i++] = new Vertex5(x2, y2, z1, u2, v1); - verts[i++] = new Vertex5(x2, y2, z2, u1, v1); - - return this; - } - - /** - * Generates a box, uv mapped to be the same as a minecraft block with the same bounds - * - * @param i The vertex index to start generating at - * @param bounds The bounds of the block, 0 to 1 - * @return The generated model. When rendering an icon will need to be supplied for the UV transformation. - */ - public CCModel generateBlock(int i, Cuboid6 bounds) - { - return generateBlock(i, bounds, 0); - } - - public CCModel generateBlock(int i, Cuboid6 bounds, int mask) - { - return generateBlock(i, bounds.min.x, bounds.min.y, bounds.min.z, bounds.max.x, bounds.max.y, bounds.max.z, mask); - } - - public CCModel generateBlock(int i, double x1, double y1, double z1, double x2, double y2, double z2) - { - return generateBlock(i, x1, y1, z1, x2, y2, z2, 0); - } - - /** - * Generates a box, uv mapped to be the same as a minecraft block with the same bounds - * - * @param i The vertex index to start generating at - * @param x1 minX - * @param y1 minY - * @param z1 minZ - * @param x2 maxX - * @param y2 maxY - * @param z2 maxZ - * @param mask A bitmask of sides NOT to generate. I high bit at index s means side s will not be generated - * @return The generated model. When rendering an icon will need to be supplied for the UV transformation. - */ - public CCModel generateBlock(int i, double x1, double y1, double z1, double x2, double y2, double z2, int mask) - { - double u1, v1, u2, v2; - - if ((mask & 1) == 0) - {//bottom face - u1 = x1; - v1 = z1; - u2 = x2; - v2 = z2; - verts[i++] = new Vertex5(x1, y1, z2, u1, v2, 0); - verts[i++] = new Vertex5(x1, y1, z1, u1, v1, 0); - verts[i++] = new Vertex5(x2, y1, z1, u2, v1, 0); - verts[i++] = new Vertex5(x2, y1, z2, u2, v2, 0); - } - - if ((mask & 2) == 0) - {//top face - u1 = x1; - v1 = z1; - u2 = x2; - v2 = z2; - verts[i++] = new Vertex5(x2, y2, z2, u2, v2, 1); - verts[i++] = new Vertex5(x2, y2, z1, u2, v1, 1); - verts[i++] = new Vertex5(x1, y2, z1, u1, v1, 1); - verts[i++] = new Vertex5(x1, y2, z2, u1, v2, 1); - } - - if ((mask & 4) == 0) - {//east face - u1 = 1 - x1; - v1 = 1 - y2; - u2 = 1 - x2; - v2 = 1 - y1; - verts[i++] = new Vertex5(x1, y1, z1, u1, v2, 2); - verts[i++] = new Vertex5(x1, y2, z1, u1, v1, 2); - verts[i++] = new Vertex5(x2, y2, z1, u2, v1, 2); - verts[i++] = new Vertex5(x2, y1, z1, u2, v2, 2); - } - - if ((mask & 8) == 0) - {//west face - u1 = x1; - v1 = 1 - y2; - u2 = x2; - v2 = 1 - y1; - verts[i++] = new Vertex5(x2, y1, z2, u2, v2, 3); - verts[i++] = new Vertex5(x2, y2, z2, u2, v1, 3); - verts[i++] = new Vertex5(x1, y2, z2, u1, v1, 3); - verts[i++] = new Vertex5(x1, y1, z2, u1, v2, 3); - } - - if ((mask & 0x10) == 0) - {//north face - u1 = z1; - v1 = 1 - y2; - u2 = z2; - v2 = 1 - y1; - verts[i++] = new Vertex5(x1, y1, z2, u2, v2, 4); - verts[i++] = new Vertex5(x1, y2, z2, u2, v1, 4); - verts[i++] = new Vertex5(x1, y2, z1, u1, v1, 4); - verts[i++] = new Vertex5(x1, y1, z1, u1, v2, 4); - } - - if ((mask & 0x20) == 0) - {//south face - u1 = 1 - z1; - v1 = 1 - y2; - u2 = 1 - z2; - v2 = 1 - y1; - verts[i++] = new Vertex5(x2, y1, z1, u1, v2, 5); - verts[i++] = new Vertex5(x2, y2, z1, u1, v1, 5); - verts[i++] = new Vertex5(x2, y2, z2, u2, v1, 5); - verts[i++] = new Vertex5(x2, y1, z2, u2, v2, 5); - } - - return this; - } - - public CCModel computeNormals() - { - return computeNormals(0, verts.length); - } - - /** - * Computes the normals of all faces in the model. - * Uses the cross product of the vectors along 2 sides of the face - * - * @param start The first vertex to generate normals for - * @param length The number of vertices to generate normals for. Note this must be a multiple of 3 for triangles or 4 for quads - * @return The model - */ - public CCModel computeNormals(int start, int length) - { - if (length % vp != 0 || start % vp != 0) - { - throw new IllegalArgumentException("Cannot generate normals across polygons"); - } - - Vector3[] normals = getOrAllocate(CCRenderState.normalAttrib); - for (int k = 0; k < length; k += vp) - { - int i = k + start; - Vector3 diff1 = verts[i + 1].vec.copy().subtract(verts[i].vec); - Vector3 diff2 = verts[i + vp - 1].vec.copy().subtract(verts[i].vec); - normals[i] = diff1.crossProduct(diff2).normalize(); - for (int d = 1; d < vp; d++) - normals[i + d] = normals[i].copy(); - } - - return this; - } - - /** - * Computes lighting using the normals add a light model - * If the model is rotated, the lighting will no longer be valid - * - * @return The model - */ - public CCModel computeLighting(LightModel light) - { - Vector3[] normals = normals(); - int[] colours = getAttributes(CCRenderState.lightingAttrib); - if (colours == null) - { - colours = getOrAllocate(CCRenderState.lightingAttrib); - Arrays.fill(colours, -1); - } - for (int k = 0; k < verts.length; k++) - colours[k] = light.apply(colours[k], normals[k]); - return this; - } - - public CCModel setColour(int c) - { - int[] colours = getOrAllocate(CCRenderState.colourAttrib); - Arrays.fill(colours, c); - return this; - } - - /** - * Computes the minecraft lighting coordinates for use with a LightMatrix - * - * @return The model - */ - public CCModel computeLightCoords() - { - LC[] lcs = getOrAllocate(CCRenderState.lightCoordAttrib); - Vector3[] normals = normals(); - for (int i = 0; i < verts.length; i++) - lcs[i] = new LC().compute(verts[i].vec, normals[i]); - return this; - } - - /** - * Averages all normals at the same position to produce a smooth lighting effect. - * - * @return The model - */ - public CCModel smoothNormals() - { - ArrayList map = new ArrayList(); - Vector3[] normals = normals(); - nextvert: - for (int k = 0; k < verts.length; k++) - { - Vector3 vec = verts[k].vec; - for (PositionNormalEntry e : map) - if (e.positionEqual(vec)) - { - e.addNormal(normals[k]); - continue nextvert; - } - - map.add(new PositionNormalEntry(vec).addNormal(normals[k])); - } - - for (PositionNormalEntry e : map) - { - if (e.normals.size() <= 1) - { - continue; - } - - Vector3 new_n = new Vector3(); - for (Vector3 n : e.normals) - new_n.add(n); - - new_n.normalize(); - for (Vector3 n : e.normals) - n.set(new_n); - } - - return this; - } - - public CCModel apply(Transformation t) - { - for (int k = 0; k < verts.length; k++) - verts[k].apply(t); - - Vector3[] normals = normals(); - if (normals != null) - { - for (int k = 0; k < normals.length; k++) - t.applyN(normals[k]); - } - - return this; - } - - public CCModel apply(UVTransformation uvt) - { - for (int k = 0; k < verts.length; k++) - verts[k].apply(uvt); - - return this; - } - - public CCModel expand(int extraVerts) - { - int newLen = verts.length + extraVerts; - verts = Arrays.copyOf(verts, newLen); - for (int i = 0; i < attributes.size(); i++) - if (attributes.get(i) != null) - { - attributes.set(i, CCRenderState.copyOf((CCRenderState.VertexAttribute) CCRenderState.getAttribute(i), attributes.get(i), newLen)); - } - - return this; - } - - public void render(double x, double y, double z, double u, double v) - { - render(new Vector3(x, y, z).translation(), new UVTranslation(u, v)); - } - - public void render(double x, double y, double z, UVTransformation u) - { - render(new Vector3(x, y, z).translation(), u); - } - - public void render(Transformation t, double u, double v) - { - render(t, new UVTranslation(u, v)); - } - - public void render(CCRenderState.IVertexOperation... ops) - { - render(0, verts.length, ops); - } - - /** - * Renders vertices start through start+length-1 of the model - * - * @param start The first vertex index to render - * @param end The vertex index to render until - * @param ops Operations to apply - */ - public void render(int start, int end, CCRenderState.IVertexOperation... ops) - { - CCRenderState.setPipeline(this, start, end, ops); - CCRenderState.render(); - } - - public static CCModel quadModel(int numVerts) - { - return newModel(7, numVerts); - } - - public static CCModel triModel(int numVerts) - { - return newModel(4, numVerts); - } - - public static CCModel newModel(int vertexMode, int numVerts) - { - CCModel model = newModel(vertexMode); - model.verts = new Vertex5[numVerts]; - return model; - } - - public static CCModel newModel(int vertexMode) - { - return new CCModel(vertexMode); - } - - public static double[] parseDoubles(String s, String token) - { - String[] as = s.split(token); - double[] values = new double[as.length]; - for (int i = 0; i < as.length; i++) - values[i] = Double.parseDouble(as[i]); - return values; - } - - public static void illegalAssert(boolean b, String err) - { - if (!b) throw new IllegalArgumentException(err); - } - - public static void assertMatch(Matcher m, String s) - { - m.reset(s); - illegalAssert(m.matches(), "Malformed line: " + s); - } - - private static final Pattern vertPattern = Pattern.compile("v(?: ([\\d\\.+-]+))+"); - private static final Pattern uvwPattern = Pattern.compile("vt(?: ([\\d\\.+-]+))+"); - private static final Pattern normalPattern = Pattern.compile("vn(?: ([\\d\\.+-]+))+"); - private static final Pattern polyPattern = Pattern.compile("f(?: ((?:\\d*)(?:/\\d*)?(?:/\\d*)?))+"); - public static final Matcher vertMatcher = vertPattern.matcher(""); - public static final Matcher uvwMatcher = uvwPattern.matcher(""); - public static final Matcher normalMatcher = normalPattern.matcher(""); - public static final Matcher polyMatcher = polyPattern.matcher(""); - - /** - * Parses vertices, texture coords, normals and polygons from a WaveFront Obj file - * - * @param input An input stream to a obj file - * @param vertexMode The vertex mode to create the model for (GL_TRIANGLES or GL_QUADS) - * @param coordSystem The cooridnate system transformation to apply - * @return A map of group names to models - * @throws IOException - */ - public static Map parseObjModels(InputStream input, int vertexMode, Transformation coordSystem) throws IOException - { - if (coordSystem == null) - { - coordSystem = new RedundantTransformation(); - } - int vp = vertexMode == 7 ? 4 : 3; - - HashMap modelMap = new HashMap(); - ArrayList verts = new ArrayList(); - ArrayList uvs = new ArrayList(); - ArrayList normals = new ArrayList(); - ArrayList polys = new ArrayList(); - String modelName = "unnamed"; - - BufferedReader reader = new BufferedReader(new InputStreamReader(input)); - - String line; - while ((line = reader.readLine()) != null) - { - line = line.replaceAll("\\s+", " ").trim(); - if (line.startsWith("#") || line.length() == 0) - { - continue; - } - - if (line.startsWith("v ")) - { - assertMatch(vertMatcher, line); - double[] values = parseDoubles(line.substring(2), " "); - illegalAssert(values.length >= 3, "Vertices must have x, y and z components"); - Vector3 vert = new Vector3(values[0], values[1], values[2]); - coordSystem.apply(vert); - verts.add(vert); - continue; - } - if (line.startsWith("vt ")) - { - assertMatch(uvwMatcher, line); - double[] values = parseDoubles(line.substring(3), " "); - illegalAssert(values.length >= 2, "Tex Coords must have u, and v components"); - uvs.add(new Vector3(values[0], 1 - values[1], 0)); - continue; - } - if (line.startsWith("vn ")) - { - assertMatch(normalMatcher, line); - double[] values = parseDoubles(line.substring(3), " "); - illegalAssert(values.length >= 3, "Normals must have x, y and z components"); - Vector3 norm = new Vector3(values[0], values[1], values[2]).normalize(); - coordSystem.applyN(norm); - normals.add(norm); - continue; - } - if (line.startsWith("f ")) - { - assertMatch(polyMatcher, line); - String[] av = line.substring(2).split(" "); - illegalAssert(av.length >= 3, "Polygons must have at least 3 vertices"); - int[][] polyVerts = new int[av.length][3]; - for (int i = 0; i < av.length; i++) - { - String[] as = av[i].split("/"); - for (int p = 0; p < as.length; p++) - if (as[p].length() > 0) - { - polyVerts[i][p] = Integer.parseInt(as[p]); - } - } - if (vp == 3) - { - triangulate(polys, polyVerts); - } else - { - quadulate(polys, polyVerts); - } - } - if (line.startsWith("g ")) - { - if (!polys.isEmpty()) - { - modelMap.put(modelName, createModel(verts, uvs, normals, vertexMode, polys)); - polys.clear(); - } - modelName = line.substring(2); - } - } - - if (!polys.isEmpty()) - { - modelMap.put(modelName, createModel(verts, uvs, normals, vertexMode, polys)); - } - - return modelMap; - } - - public static void triangulate(List polys, int[][] polyVerts) - { - for (int i = 2; i < polyVerts.length; i++) - { - polys.add(polyVerts[0]); - polys.add(polyVerts[i]); - polys.add(polyVerts[i - 1]); - } - } - - public static void quadulate(List polys, int[][] polyVerts) - { - if (polyVerts.length == 4) - { - polys.add(polyVerts[0]); - polys.add(polyVerts[3]); - polys.add(polyVerts[2]); - polys.add(polyVerts[1]); - } else - { - for (int i = 2; i < polyVerts.length; i++) - { - polys.add(polyVerts[0]); - polys.add(polyVerts[i]); - polys.add(polyVerts[i - 1]); - polys.add(polyVerts[i - 1]); - } - } - } - - /** - * Parses vertices, texture coords, normals and polygons from a WaveFront Obj file - * - * @param res The resource for the obj file - * @return A map of group names to models - */ - public static Map parseObjModels(ResourceLocation res) - { - return parseObjModels(res, 4, null); - } - - /** - * Parses vertices, texture coords, normals and polygons from a WaveFront Obj file - * - * @param res The resource for the obj file - * @param coordSystem The cooridnate system transformation to apply - * @return A map of group names to models - */ - public static Map parseObjModels(ResourceLocation res, Transformation coordSystem) - { - try - { - return parseObjModels( - Minecraft.getMinecraft().getResourceManager().getResource(res).getInputStream(), - 4, coordSystem); - } catch (IOException e) - { - throw new RuntimeException("failed to load model: " + res, e); - } - } - - /** - * Parses vertices, texture coords, normals and polygons from a WaveFront Obj file - * - * @param res The resource for the obj file - * @param vertexMode The vertex mode to create the model for (GL_TRIANGLES or GL_QUADS) - * @param coordSystem The cooridnate system transformation to apply - * @return A map of group names to models - */ - public static Map parseObjModels(ResourceLocation res, int vertexMode, Transformation coordSystem) - { - try - { - return parseObjModels( - Minecraft.getMinecraft().getResourceManager().getResource(res).getInputStream(), - vertexMode, coordSystem); - } catch (Exception e) - { - throw new RuntimeException("failed to load model: " + res, e); - } - } - - public static CCModel createModel(List verts, List uvs, List normals, int vertexMode, List polys) - { - int vp = vertexMode == 7 ? 4 : 3; - if (polys.size() < vp || polys.size() % vp != 0) - { - throw new IllegalArgumentException("Invalid number of vertices for model: " + polys.size()); - } - - boolean hasNormals = polys.get(0)[2] > 0; - CCModel model = CCModel.newModel(vertexMode, polys.size()); - if (hasNormals) - { - model.getOrAllocate(CCRenderState.normalAttrib); - } - - for (int i = 0; i < polys.size(); i++) - { - int[] ai = polys.get(i); - Vector3 vert = verts.get(ai[0] - 1).copy(); - Vector3 uv = ai[1] <= 0 ? new Vector3() : uvs.get(ai[1] - 1).copy(); - if (ai[2] > 0 != hasNormals) - { - throw new IllegalArgumentException("Normals are an all or nothing deal here."); - } - - model.verts[i] = new Vertex5(vert, uv.x, uv.y); - if (hasNormals) - { - model.normals()[i] = normals.get(ai[2] - 1).copy(); - } - } - - return model; - } - - private static int addIndex(List list, T elem) - { - int i = list.indexOf(elem) + 1; - if (i == 0) - { - list.add(elem); - i = list.size(); - } - return i; - } - - private static String clean(double d) - { - return d == (int) d ? Integer.toString((int) d) : Double.toString(d); - } - - public static void exportObj(Map models, PrintWriter p) - { - List verts = new ArrayList(); - List uvs = new ArrayList(); - List normals = new ArrayList(); - List polys = new ArrayList(); - for (Map.Entry e : models.entrySet()) - { - p.println("g " + e.getKey()); - CCModel m = e.getValue(); - - int vStart = verts.size(); - int uStart = uvs.size(); - int nStart = normals.size(); - boolean hasNormals = m.normals() != null; - polys.clear(); - - for (int i = 0; i < m.verts.length; i++) - { - int[] ia = new int[hasNormals ? 3 : 2]; - ia[0] = addIndex(verts, m.verts[i].vec); - ia[1] = addIndex(uvs, m.verts[i].uv); - if (hasNormals) - { - ia[2] = addIndex(normals, m.normals()[i]); - } - polys.add(ia); - } - - if (vStart < verts.size()) - { - p.println(); - for (int i = vStart; i < verts.size(); i++) - { - Vector3 v = verts.get(i); - p.format("v %s %s %s\n", clean(v.x), clean(v.y), clean(v.z)); - } - } - if (uStart < uvs.size()) - { - p.println(); - for (int i = uStart; i < uvs.size(); i++) - { - UV uv = uvs.get(i); - p.format("vt %s %s\n", clean(uv.u), clean(uv.v)); - } - } - if (nStart < normals.size()) - { - p.println(); - for (int i = nStart; i < normals.size(); i++) - { - Vector3 n = normals.get(i); - p.format("vn %s %s %s\n", clean(n.x), clean(n.y), clean(n.z)); - } - } - - p.println(); - for (int i = 0; i < polys.size(); i++) - { - if (i % m.vp == 0) - { - p.format("f"); - } - int[] ia = polys.get(i); - if (hasNormals) - { - p.format(" %d/%d/%d", ia[0], ia[1], ia[2]); - } else - { - p.format(" %d/%d", ia[0], ia[1]); - } - if (i % m.vp == m.vp - 1) - { - p.println(); - } - } - } - } - - /** - * Brings the UV coordinates of each face closer to the center UV by d. - * Useful for fixing texture seams - */ - public CCModel shrinkUVs(double d) - { - for (int k = 0; k < verts.length; k += vp) - { - UV uv = new UV(); - for (int i = 0; i < vp; i++) - { - uv.add(verts[k + i].uv); - } - uv.multiply(1D / vp); - for (int i = 0; i < vp; i++) - { - Vertex5 vert = verts[k + i]; - vert.uv.u += vert.uv.u < uv.u ? d : -d; - vert.uv.v += vert.uv.v < uv.v ? d : -d; - } - } - return this; - } - - /** - * @param side1 The side of this model - * @param side2 The side of the new model - * @param point The point to rotate around - * @return A copy of this model rotated to the appropriate side - */ - public CCModel sidedCopy(int side1, int side2, Vector3 point) - { - return copy().apply(new TransformationList(sideRotations[side1].inverse(), sideRotations[side2]).at(point)); - } - - /** - * Copies length vertices and normals - */ - public static void copy(CCModel src, int srcpos, CCModel dst, int destpos, int length) - { - for (int k = 0; k < length; k++) - dst.verts[destpos + k] = src.verts[srcpos + k].copy(); - - for (int i = 0; i < src.attributes.size(); i++) - if (src.attributes.get(i) != null) - { - CCRenderState.arrayCopy(src.attributes.get(i), srcpos, dst.getOrAllocate(CCRenderState.getAttribute(i)), destpos, length); - } - } - - /** - * Generate models rotated to the other 5 sides of the block - * - * @param models An array of 6 models - * @param side The side of this model - * @param point The rotation point - */ - public static void generateSidedModels(CCModel[] models, int side, Vector3 point) - { - for (int s = 0; s < 6; s++) - { - if (s == side) - { - continue; - } - - models[s] = models[side].sidedCopy(side, s, point); - } - } - - /** - * Generate models rotated to the other 3 horizontal of the block - * - * @param models An array of 4 models - * @param side The side of this model - * @param point The rotation point - */ - public static void generateSidedModelsH(CCModel[] models, int side, Vector3 point) - { - for (int s = 2; s < 6; s++) - { - if (s == side) - { - continue; - } - - models[s] = models[side].sidedCopy(side, s, point); - } - } - - public CCModel backfacedCopy() - { - return generateBackface(this, 0, copy(), 0, verts.length); - } - - /** - * Generates copies of faces with clockwise vertices - * - * @return The model - */ - public static CCModel generateBackface(CCModel src, int srcpos, CCModel dst, int destpos, int length) - { - int vp = src.vp; - if (srcpos % vp != 0 || destpos % vp != 0 || length % vp != 0) - { - throw new IllegalArgumentException("Vertices do not align with polygons"); - } - - int[][] o = new int[][]{{0, 0}, {1, vp - 1}, {2, vp - 2}, {3, vp - 3}}; - for (int i = 0; i < length; i++) - { - int b = (i / vp) * vp; - int d = i % vp; - int di = destpos + b + o[d][1]; - int si = srcpos + b + o[d][0]; - dst.verts[di] = src.verts[si].copy(); - for (int a = 0; a < src.attributes.size(); a++) - if (src.attributes.get(a) != null) - { - CCRenderState.arrayCopy(src.attributes.get(a), si, dst.getOrAllocate(CCRenderState.getAttribute(a)), di, 1); - } - - if (dst.normals() != null && dst.normals()[di] != null) - { - dst.normals()[di].negate(); - } - } - return dst; - } - - /** - * Generates sided copies of vertices into this model. - * Assumes that your model has been generated at vertex side*(numVerts/6) - */ - public CCModel generateSidedParts(int side, Vector3 point) - { - if (verts.length % (6 * vp) != 0) - { - throw new IllegalArgumentException("Invalid number of vertices for sided part generation"); - } - int length = verts.length / 6; - - for (int s = 0; s < 6; s++) - { - if (s == side) - { - continue; - } - - generateSidedPart(side, s, point, length * side, length * s, length); - } - - return this; - } - - /** - * Generates sided copies of vertices into this model. - * Assumes that your model has been generated at vertex side*(numVerts/4) - */ - public CCModel generateSidedPartsH(int side, Vector3 point) - { - if (verts.length % (4 * vp) != 0) - { - throw new IllegalArgumentException("Invalid number of vertices for sided part generation"); - } - int length = verts.length / 4; - - for (int s = 2; s < 6; s++) - { - if (s == side) - { - continue; - } - - generateSidedPart(side, s, point, length * (side - 2), length * (s - 2), length); - } - - return this; - } - - /** - * Generates a sided copy of verts into this model - */ - public CCModel generateSidedPart(int side1, int side2, Vector3 point, int srcpos, int destpos, int length) - { - return apply(new TransformationList(sideRotations[side1].inverse(), sideRotations[side2]).at(point), srcpos, destpos, length); - } - - /** - * Generates a rotated copy of verts into this model - */ - public CCModel apply(Transformation t, int srcpos, int destpos, int length) - { - for (int k = 0; k < length; k++) - { - verts[destpos + k] = verts[srcpos + k].copy(); - verts[destpos + k].vec.apply(t); - } - - Vector3[] normals = normals(); - if (normals != null) - { - for (int k = 0; k < length; k++) - { - normals[destpos + k] = normals[srcpos + k].copy(); - t.applyN(normals[destpos + k]); - } - } - - return this; - } - - public static CCModel combine(Collection models) - { - if (models.isEmpty()) - { - return null; - } - - int numVerts = 0; - int vertexMode = -1; - for (CCModel model : models) - { - if (vertexMode == -1) - { - vertexMode = model.vertexMode; - } - if (vertexMode != model.vertexMode) - { - throw new IllegalArgumentException("Cannot combine models with different vertex modes"); - } - - numVerts += model.verts.length; - } - - CCModel c_model = newModel(vertexMode, numVerts); - int i = 0; - for (CCModel model : models) - { - copy(model, 0, c_model, i, model.verts.length); - i += model.verts.length; - } - - return c_model; - } - - public CCModel twoFacedCopy() - { - CCModel model = newModel(vertexMode, verts.length * 2); - copy(this, 0, model, 0, verts.length); - return generateBackface(model, 0, model, verts.length, verts.length); - } - - public CCModel copy() - { - CCModel model = newModel(vertexMode, verts.length); - copy(this, 0, model, 0, verts.length); - return model; - } - - /** - * @return The average of all vertices, for bones. - */ - public Vector3 collapse() - { - Vector3 v = new Vector3(); - for (Vertex5 vert : verts) - v.add(vert.vec); - v.multiply(1 / (double) verts.length); - return v; - } - - public CCModel zOffset(Cuboid6 offsets) - { - for (int k = 0; k < verts.length; k++) - { - Vertex5 vert = verts[k]; - Vector3 normal = normals()[k]; - switch (findSide(normal)) - { - case 0: - vert.vec.y += offsets.min.y; - break; - case 1: - vert.vec.y += offsets.max.y; - break; - case 2: - vert.vec.z += offsets.min.z; - break; - case 3: - vert.vec.z += offsets.max.z; - break; - case 4: - vert.vec.x += offsets.min.x; - break; - case 5: - vert.vec.x += offsets.max.x; - break; - } - } - return this; - } - - public static int findSide(Vector3 normal) - { - if (normal.y <= -0.99) return 0; - if (normal.y >= 0.99) return 1; - if (normal.z <= -0.99) return 2; - if (normal.z >= 0.99) return 3; - if (normal.x <= -0.99) return 4; - if (normal.x >= 0.99) return 5; - return -1; - } - - /** - * @return A Cuboid6 containing all the verts in this model - */ - public Cuboid6 bounds() - { - Vector3 vec1 = verts[0].vec; - Cuboid6 c = new Cuboid6(vec1.copy(), vec1.copy()); - for (int i = 1; i < verts.length; i++) - c.enclose(verts[i].vec); - return c; - } -} diff --git a/src/main/java/codechicken/lib/render/CCModelLibrary.java b/src/main/java/codechicken/lib/render/CCModelLibrary.java deleted file mode 100644 index a5bdce96..00000000 --- a/src/main/java/codechicken/lib/render/CCModelLibrary.java +++ /dev/null @@ -1,89 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.vec.*; - -import static codechicken.lib.math.MathHelper.phi; - -public class CCModelLibrary -{ - public static CCModel icosahedron4; - public static CCModel icosahedron7; - - private static int i; - - static - { - generateIcosahedron(); - } - - private static void generateIcosahedron() - { - Vector3[] verts = new Vector3[12]; - - verts[0] = new Vector3(-1, phi, 0); - verts[1] = new Vector3(1, phi, 0); - verts[2] = new Vector3(1, -phi, 0); - verts[3] = new Vector3(-1, -phi, 0); - - verts[4] = new Vector3(0, -1, phi); - verts[5] = new Vector3(0, 1, phi); - verts[6] = new Vector3(0, 1, -phi); - verts[7] = new Vector3(0, -1, -phi); - - verts[8] = new Vector3(phi, 0, -1); - verts[9] = new Vector3(phi, 0, 1); - verts[10] = new Vector3(-phi, 0, 1); - verts[11] = new Vector3(-phi, 0, -1); - - Quat quat = Quat.aroundAxis(0, 0, 1, Math.atan(1 / phi)); - for (Vector3 vec : verts) - quat.rotate(vec); - - icosahedron4 = CCModel.newModel(4, 60); - icosahedron7 = CCModel.newModel(7, 80); - - i = 0; - //top - addIcosahedronTriangle(verts[1], 0.5, 0, verts[0], 0, 0.25, verts[5], 1, 0.25); - addIcosahedronTriangle(verts[1], 0.5, 0, verts[5], 0, 0.25, verts[9], 1, 0.25); - addIcosahedronTriangle(verts[1], 0.5, 0, verts[9], 0, 0.25, verts[8], 1, 0.25); - addIcosahedronTriangle(verts[1], 0.5, 0, verts[8], 0, 0.25, verts[6], 1, 0.25); - addIcosahedronTriangle(verts[1], 0.5, 0, verts[6], 0, 0.25, verts[0], 1, 0.25); - //centre 1vert top - addIcosahedronTriangle(verts[0], 0.5, 0.25, verts[11], 0, 0.75, verts[10], 1, 0.75); - addIcosahedronTriangle(verts[5], 0.5, 0.25, verts[10], 0, 0.75, verts[4], 1, 0.75); - addIcosahedronTriangle(verts[9], 0.5, 0.25, verts[4], 0, 0.75, verts[2], 1, 0.75); - addIcosahedronTriangle(verts[8], 0.5, 0.25, verts[2], 0, 0.75, verts[7], 1, 0.75); - addIcosahedronTriangle(verts[6], 0.5, 0.25, verts[7], 0, 0.75, verts[11], 1, 0.75); - //centre 1vert bottom - addIcosahedronTriangle(verts[2], 0.5, 0.75, verts[8], 0, 0.25, verts[9], 1, 0.25); - addIcosahedronTriangle(verts[7], 0.5, 0.75, verts[6], 0, 0.25, verts[8], 1, 0.25); - addIcosahedronTriangle(verts[11], 0.5, 0.75, verts[0], 0, 0.25, verts[6], 1, 0.25); - addIcosahedronTriangle(verts[10], 0.5, 0.75, verts[5], 0, 0.25, verts[0], 1, 0.25); - addIcosahedronTriangle(verts[4], 0.5, 0.75, verts[9], 0, 0.25, verts[5], 1, 0.25); - //bottom - addIcosahedronTriangle(verts[3], 0.5, 1, verts[2], 0, 0.75, verts[4], 1, 0.75); - addIcosahedronTriangle(verts[3], 0.5, 1, verts[7], 0, 0.75, verts[2], 1, 0.75); - addIcosahedronTriangle(verts[3], 0.5, 1, verts[11], 0, 0.75, verts[7], 1, 0.75); - addIcosahedronTriangle(verts[3], 0.5, 1, verts[10], 0, 0.75, verts[11], 1, 0.75); - addIcosahedronTriangle(verts[3], 0.5, 1, verts[4], 0, 0.75, verts[10], 1, 0.75); - - icosahedron4.computeNormals().smoothNormals(); - icosahedron7.computeNormals().smoothNormals(); - } - - private static void addIcosahedronTriangle(Vector3 vec1, double u1, double v1, - Vector3 vec2, double u2, double v2, - Vector3 vec3, double u3, double v3) - { - icosahedron4.verts[i * 3] = icosahedron7.verts[i * 4] = new Vertex5(vec1, u1, v1); - icosahedron4.verts[i * 3 + 1] = icosahedron7.verts[i * 4 + 1] = new Vertex5(vec2, u2, v2); - icosahedron4.verts[i * 3 + 2] = icosahedron7.verts[i * 4 + 2] = icosahedron7.verts[i * 4 + 3] = new Vertex5(vec3, u3, v3); - i++; - } - - public static Matrix4 getRenderMatrix(Vector3 position, Rotation rotation, double scale) - { - return new Matrix4().translate(position).apply(new Scale(scale)).apply(rotation); - } -} diff --git a/src/main/java/codechicken/lib/render/CCRenderPipeline.java b/src/main/java/codechicken/lib/render/CCRenderPipeline.java deleted file mode 100644 index d4a1fc37..00000000 --- a/src/main/java/codechicken/lib/render/CCRenderPipeline.java +++ /dev/null @@ -1,168 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.render.CCRenderState.IVertexOperation; -import codechicken.lib.render.CCRenderState.VertexAttribute; - -import java.util.ArrayList; - -public class CCRenderPipeline -{ - private ArrayList attribs = new ArrayList(); - private ArrayList ops = new ArrayList(); - private ArrayList nodes = new ArrayList(); - private ArrayList sorted = new ArrayList(); - private PipelineNode loading; - private PipelineBuilder builder = new PipelineBuilder(); - - public void setPipeline(IVertexOperation... ops) - { - this.ops.clear(); - for (int i = 0; i < ops.length; i++) - this.ops.add(ops[i]); - rebuild(); - } - - public void reset() - { - ops.clear(); - unbuild(); - } - - private void unbuild() - { - for (int i = 0; i < attribs.size(); i++) - attribs.get(i).active = false; - attribs.clear(); - sorted.clear(); - } - - public void rebuild() - { - if (ops.isEmpty() || CCRenderState.model == null) - { - return; - } - - //ensure enough nodes for all ops - while (nodes.size() < CCRenderState.operationCount()) - nodes.add(new PipelineNode()); - unbuild(); - - if (CCRenderState.useNormals) - { - addAttribute(CCRenderState.normalAttrib); - } - if (CCRenderState.useColour) - { - addAttribute(CCRenderState.colourAttrib); - } - if (CCRenderState.computeLighting) - { - addAttribute(CCRenderState.lightingAttrib); - } - - for (int i = 0; i < ops.size(); i++) - { - IVertexOperation op = ops.get(i); - loading = nodes.get(op.operationID()); - boolean loaded = op.load(); - if (loaded) - { - loading.op = op; - } - - if (op instanceof VertexAttribute) - { - if (loaded) - { - attribs.add((VertexAttribute) op); - } else - { - ((VertexAttribute) op).active = false; - } - } - } - - for (int i = 0; i < nodes.size(); i++) - nodes.get(i).add(); - } - - public void addRequirement(int opRef) - { - loading.deps.add(nodes.get(opRef)); - } - - public void addDependency(VertexAttribute attrib) - { - loading.deps.add(nodes.get(attrib.operationID())); - addAttribute(attrib); - } - - public void addAttribute(VertexAttribute attrib) - { - if (!attrib.active) - { - ops.add(attrib); - attrib.active = true; - } - } - - public void operate() - { - for (int i = 0; i < sorted.size(); i++) - sorted.get(i).operate(); - } - - public PipelineBuilder builder() - { - ops.clear(); - return builder; - } - - public class PipelineBuilder - { - public PipelineBuilder add(IVertexOperation op) - { - ops.add(op); - return this; - } - - public PipelineBuilder add(IVertexOperation... ops) - { - for (int i = 0; i < ops.length; i++) - CCRenderPipeline.this.ops.add(ops[i]); - return this; - } - - public void build() - { - rebuild(); - } - - public void render() - { - rebuild(); - CCRenderState.render(); - } - } - - private class PipelineNode - { - public ArrayList deps = new ArrayList(); - public IVertexOperation op; - - public void add() - { - if (op == null) - { - return; - } - - for (int i = 0; i < deps.size(); i++) - deps.get(i).add(); - deps.clear(); - sorted.add(op); - op = null; - } - } -} diff --git a/src/main/java/codechicken/lib/render/CCRenderState.java b/src/main/java/codechicken/lib/render/CCRenderState.java deleted file mode 100644 index 3af2c784..00000000 --- a/src/main/java/codechicken/lib/render/CCRenderState.java +++ /dev/null @@ -1,519 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.colour.ColourRGBA; -import codechicken.lib.lighting.LC; -import codechicken.lib.lighting.LightMatrix; -import codechicken.lib.util.Copyable; -import codechicken.lib.vec.Rotation; -import codechicken.lib.vec.Transformation; -import codechicken.lib.vec.Vector3; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.IBlockAccess; - -import java.util.ArrayList; - -/** - * The core of the CodeChickenLib render system. - * Rendering operations are written to avoid object allocations by reusing static variables. - */ -public class CCRenderState -{ - private static int nextOperationIndex; - - public static int registerOperation() - { - return nextOperationIndex++; - } - - public static int operationCount() - { - return nextOperationIndex; - } - - /** - * Represents an operation to be run for each vertex that operates on and modifies the current state - */ - public static interface IVertexOperation - { - /** - * Load any required reference and add dependencies to the pipeline based on the current model (may be null) - * Return false if this operation is redundant in the pipeline with the given model - */ - public boolean load(); - - /** - * Perform the operation on the current render state - */ - public void operate(); - - /** - * Get the unique id representing this type of operation. Duplicate operation IDs within the pipeline may have unexpected results. - * ID shoulld be obtained from CCRenderState.registerOperation() and stored in a static variable - */ - public int operationID(); - } - - private static ArrayList> vertexAttributes = new ArrayList>(); - - private static int registerVertexAttribute(VertexAttribute attr) - { - vertexAttributes.add(attr); - return vertexAttributes.size() - 1; - } - - public static VertexAttribute getAttribute(int index) - { - return vertexAttributes.get(index); - } - - /** - * Management class for a vertex attrute such as colour, normal etc - * This class should handle the loading of the attrute from an array provided by IVertexSource.getAttributes or the computation of this attrute from others - * - * @param The array type for this attrute eg. int[], Vector3[] - */ - public static abstract class VertexAttribute implements IVertexOperation - { - public final int attributeIndex = registerVertexAttribute(this); - private final int operationIndex = registerOperation(); - /** - * Set to true when the attrute is part of the pipeline. Should only be managed by CCRenderState when constructing the pipeline - */ - public boolean active = false; - - /** - * Construct a new array for storage of vertex attrutes in a model - */ - public abstract T newArray(int length); - - @Override - public int operationID() - { - return operationIndex; - } - } - - public static void arrayCopy(Object src, int srcPos, Object dst, int destPos, int length) - { - System.arraycopy(src, srcPos, dst, destPos, length); - if (dst instanceof Copyable[]) - { - Object[] oa = (Object[]) dst; - Copyable[] c = (Copyable[]) dst; - for (int i = destPos; i < destPos + length; i++) - if (c[i] != null) - { - oa[i] = c[i].copy(); - } - } - } - - public static T copyOf(VertexAttribute attr, T src, int length) - { - T dst = attr.newArray(length); - arrayCopy(src, 0, dst, 0, ((Object[]) src).length); - return dst; - } - - public static interface IVertexSource - { - public Vertex5[] getVertices(); - - /** - * Gets an array of vertex attrutes - * - * @param attr The vertex attrute to get - * @param The attrute array type - * @return An array, or null if not computed - */ - public T getAttributes(VertexAttribute attr); - - /** - * @return True if the specified attrute is provided by this model, either by returning an array from getAttributes or by setting the state in prepareVertex - */ - public boolean hasAttribute(VertexAttribute attr); - - /** - * Callback to set CCRenderState for a vertex before the pipeline runs - */ - public void prepareVertex(); - } - - public static VertexAttribute normalAttrib = new VertexAttribute() - { - private Vector3[] normalRef; - - @Override - public Vector3[] newArray(int length) - { - return new Vector3[length]; - } - - @Override - public boolean load() - { - normalRef = model.getAttributes(this); - if (model.hasAttribute(this)) - { - return normalRef != null; - } - - if (model.hasAttribute(sideAttrib)) - { - pipeline.addDependency(sideAttrib); - return true; - } - throw new IllegalStateException("Normals requested but neither normal or side attrutes are provided by the model"); - } - - @Override - public void operate() - { - if (normalRef != null) - { - setNormal(normalRef[vertexIndex]); - } else - { - setNormal(Rotation.axes[side]); - } - } - }; - public static VertexAttribute colourAttrib = new VertexAttribute() - { - private int[] colourRef; - - @Override - public int[] newArray(int length) - { - return new int[length]; - } - - @Override - public boolean load() - { - colourRef = model.getAttributes(this); - return colourRef != null || !model.hasAttribute(this); - } - - @Override - public void operate() - { - if (colourRef != null) - { - setColour(ColourRGBA.multiply(baseColour, colourRef[vertexIndex])); - } else - { - setColour(baseColour); - } - } - }; - public static VertexAttribute lightingAttrib = new VertexAttribute() - { - private int[] colourRef; - - @Override - public int[] newArray(int length) - { - return new int[length]; - } - - @Override - public boolean load() - { - if (!computeLighting || !useColour || !model.hasAttribute(this)) - { - return false; - } - - colourRef = model.getAttributes(this); - if (colourRef != null) - { - pipeline.addDependency(colourAttrib); - return true; - } - return false; - } - - @Override - public void operate() - { - setColour(ColourRGBA.multiply(colour, colourRef[vertexIndex])); - } - }; - public static VertexAttribute sideAttrib = new VertexAttribute() - { - private int[] sideRef; - - @Override - public int[] newArray(int length) - { - return new int[length]; - } - - @Override - public boolean load() - { - sideRef = model.getAttributes(this); - if (model.hasAttribute(this)) - { - return sideRef != null; - } - - pipeline.addDependency(normalAttrib); - return true; - } - - @Override - public void operate() - { - if (sideRef != null) - { - side = sideRef[vertexIndex]; - } else - { - side = CCModel.findSide(normal); - } - } - }; - /** - * Uses the position of the lightmatrix to compute LC if not provided - */ - public static VertexAttribute lightCoordAttrib = new VertexAttribute() - { - private LC[] lcRef; - private Vector3 vec = new Vector3();//for computation - private Vector3 pos = new Vector3(); - - @Override - public LC[] newArray(int length) - { - return new LC[length]; - } - - @Override - public boolean load() - { - lcRef = model.getAttributes(this); - if (model.hasAttribute(this)) - { - return lcRef != null; - } - - pos.set(lightMatrix.pos.x, lightMatrix.pos.y, lightMatrix.pos.z); - pipeline.addDependency(sideAttrib); - pipeline.addRequirement(Transformation.operationIndex); - return true; - } - - @Override - public void operate() - { - if (lcRef != null) - { - lc.set(lcRef[vertexIndex]); - } else - { - lc.compute(vec.set(vert.vec).sub(pos), side); - } - } - }; - - //pipeline state - public static IVertexSource model; - public static int firstVertexIndex; - public static int lastVertexIndex; - public static int vertexIndex; - public static CCRenderPipeline pipeline = new CCRenderPipeline(); - - //context - public static int baseColour; - public static int alphaOverride; - public static boolean useNormals; - public static boolean computeLighting; - public static boolean useColour; - public static LightMatrix lightMatrix = new LightMatrix(); - - //vertex outputs - public static Vertex5 vert = new Vertex5(); - public static boolean hasNormal; - public static Vector3 normal = new Vector3(); - public static boolean hasColour; - public static int colour; - public static boolean hasBrightness; - public static int brightness; - - //attrute storage - public static int side; - public static LC lc = new LC(); - - public static void reset() - { - model = null; - pipeline.reset(); - useNormals = hasNormal = hasBrightness = hasColour = false; - useColour = computeLighting = true; - baseColour = alphaOverride = -1; - } - - public static void setPipeline(IVertexOperation... ops) - { - pipeline.setPipeline(ops); - } - - public static void setPipeline(IVertexSource model, int start, int end, IVertexOperation... ops) - { - pipeline.reset(); - setModel(model, start, end); - pipeline.setPipeline(ops); - } - - public static void bindModel(IVertexSource model) - { - if (CCRenderState.model != model) - { - CCRenderState.model = model; - pipeline.rebuild(); - } - } - - public static void setModel(IVertexSource source) - { - setModel(source, 0, source.getVertices().length); - } - - public static void setModel(IVertexSource source, int start, int end) - { - bindModel(source); - setVertexRange(start, end); - } - - public static void setVertexRange(int start, int end) - { - firstVertexIndex = start; - lastVertexIndex = end; - } - - public static void render(IVertexOperation... ops) - { - setPipeline(ops); - render(); - } - - public static void render() - { - Vertex5[] verts = model.getVertices(); - for (vertexIndex = firstVertexIndex; vertexIndex < lastVertexIndex; vertexIndex++) - { - model.prepareVertex(); - vert.set(verts[vertexIndex]); - runPipeline(); - writeVert(); - } - } - - public static void runPipeline() - { - pipeline.operate(); - } - - public static void writeVert() - { - if (hasNormal) - { - Tessellator.instance.setNormal((float) normal.x, (float) normal.y, (float) normal.z); - } - if (hasColour) - { - Tessellator.instance.setColorRGBA(colour >>> 24, colour >> 16 & 0xFF, colour >> 8 & 0xFF, alphaOverride >= 0 ? alphaOverride : colour & 0xFF); - } - if (hasBrightness) - { - Tessellator.instance.setBrightness(brightness); - } - Tessellator.instance.addVertexWithUV(vert.vec.x, vert.vec.y, vert.vec.z, vert.uv.u, vert.uv.v); - } - - public static void setNormal(double x, double y, double z) - { - hasNormal = true; - normal.set(x, y, z); - } - - public static void setNormal(Vector3 n) - { - hasNormal = true; - normal.set(n); - } - - public static void setColour(int c) - { - hasColour = true; - colour = c; - } - - public static void setBrightness(int b) - { - hasBrightness = true; - brightness = b; - } - - public static void setBrightness(IBlockAccess world, int x, int y, int z) - { - setBrightness(world.getBlock(x, y, z).getMixedBrightnessForBlock(world, x, y, z)); - } - - public static void pullLightmap() - { - setBrightness((int) OpenGlHelper.lastBrightnessY << 16 | (int) OpenGlHelper.lastBrightnessX); - } - - public static void pushLightmap() - { - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, brightness & 0xFFFF, brightness >>> 16); - } - - /** - * Compact helper for setting dynamic rendering context. Uses normals and doesn't compute lighting - */ - public static void setDynamic() - { - useNormals = true; - computeLighting = false; - } - - public static void changeTexture(String texture) - { - changeTexture(new ResourceLocation(texture)); - } - - public static void changeTexture(ResourceLocation texture) - { - Minecraft.getMinecraft().renderEngine.bindTexture(texture); - } - - public static void startDrawing() - { - startDrawing(7); - } - - public static void startDrawing(int mode) - { - Tessellator.instance.startDrawing(mode); - if (hasColour) - { - Tessellator.instance.setColorRGBA(colour >>> 24, colour >> 16 & 0xFF, colour >> 8 & 0xFF, alphaOverride >= 0 ? alphaOverride : colour & 0xFF); - } - if (hasBrightness) - { - Tessellator.instance.setBrightness(brightness); - } - } - - public static void draw() - { - Tessellator.instance.draw(); - } -} diff --git a/src/main/java/codechicken/lib/render/ColourMultiplier.java b/src/main/java/codechicken/lib/render/ColourMultiplier.java deleted file mode 100644 index d242af42..00000000 --- a/src/main/java/codechicken/lib/render/ColourMultiplier.java +++ /dev/null @@ -1,46 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.colour.ColourRGBA; - -public class ColourMultiplier implements CCRenderState.IVertexOperation -{ - public static final int operationIndex = CCRenderState.registerOperation(); - private static ColourMultiplier instance = new ColourMultiplier(-1); - public int colour; - - public ColourMultiplier(int colour) - { - this.colour = colour; - } - - public static ColourMultiplier instance(int colour) - { - instance.colour = colour; - return instance; - } - - @Override - public boolean load() - { - if (colour == -1) - { - CCRenderState.setColour(-1); - return false; - } - - CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib); - return true; - } - - @Override - public void operate() - { - CCRenderState.setColour(ColourRGBA.multiply(CCRenderState.colour, colour)); - } - - @Override - public int operationID() - { - return operationIndex; - } -} diff --git a/src/main/java/codechicken/lib/render/EntityDigIconFX.java b/src/main/java/codechicken/lib/render/EntityDigIconFX.java deleted file mode 100644 index 62f3e41f..00000000 --- a/src/main/java/codechicken/lib/render/EntityDigIconFX.java +++ /dev/null @@ -1,138 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.vec.Cuboid6; -import codechicken.lib.vec.Vector3; -import net.minecraft.client.particle.EffectRenderer; -import net.minecraft.client.particle.EntityFX; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - -public class EntityDigIconFX extends EntityFX -{ - public EntityDigIconFX(World world, double x, double y, double z, double dx, double dy, double dz, IIcon icon) - { - super(world, x, y, z, dx, dy, dz); - particleIcon = icon; - particleGravity = 1; - particleRed = particleGreen = particleBlue = 0.6F; - particleScale /= 2.0F; - } - - public static void addBlockHitEffects(World world, Cuboid6 bounds, int side, IIcon icon, EffectRenderer effectRenderer) - { - float border = 0.1F; - Vector3 diff = bounds.max.copy().subtract(bounds.min).add(-2 * border); - diff.x *= world.rand.nextDouble(); - diff.y *= world.rand.nextDouble(); - diff.z *= world.rand.nextDouble(); - Vector3 pos = diff.add(bounds.min).add(border); - - if (side == 0) - { - diff.y = bounds.min.y - border; - } - if (side == 1) - { - diff.y = bounds.max.y + border; - } - if (side == 2) - { - diff.z = bounds.min.z - border; - } - if (side == 3) - { - diff.z = bounds.max.z + border; - } - if (side == 4) - { - diff.x = bounds.min.x - border; - } - if (side == 5) - { - diff.x = bounds.max.x + border; - } - - effectRenderer.addEffect( - new EntityDigIconFX(world, pos.x, pos.y, pos.z, 0, 0, 0, icon) - .multiplyVelocity(0.2F).multipleParticleScaleBy(0.6F)); - } - - public static void addBlockDestroyEffects(World world, Cuboid6 bounds, IIcon[] icons, EffectRenderer effectRenderer) - { - Vector3 diff = bounds.max.copy().subtract(bounds.min); - Vector3 center = bounds.min.copy().add(bounds.max).multiply(0.5); - Vector3 density = diff.copy().multiply(4); - density.x = Math.ceil(density.x); - density.y = Math.ceil(density.y); - density.z = Math.ceil(density.z); - - for (int i = 0; i < density.x; ++i) - for (int j = 0; j < density.y; ++j) - for (int k = 0; k < density.z; ++k) - { - double x = bounds.min.x + (i + 0.5) * diff.x / density.x; - double y = bounds.min.y + (j + 0.5) * diff.y / density.y; - double z = bounds.min.z + (k + 0.5) * diff.z / density.z; - effectRenderer.addEffect( - new EntityDigIconFX(world, x, y, z, x - center.x, y - center.y, z - center.z, icons[world.rand.nextInt(icons.length)])); - } - } - - @Override - public int getFXLayer() - { - return 1; - } - - public float getScale() - { - return particleScale; - } - - public void setScale(float scale) - { - particleScale = scale; - } - - public int getMaxAge() - { - return particleMaxAge; - } - - public void setMaxAge(int age) - { - particleMaxAge = age; - } - - /** - * copy pasted from EntityDiggingFX - */ - @Override - public void renderParticle(Tessellator par1Tessellator, float par2, float par3, float par4, float par5, float par6, float par7) - { - float f6 = (particleTextureIndexX + particleTextureJitterX / 4.0F) / 16.0F; - float f7 = f6 + 0.015609375F; - float f8 = (particleTextureIndexY + particleTextureJitterY / 4.0F) / 16.0F; - float f9 = f8 + 0.015609375F; - float f10 = 0.1F * particleScale; - - if (particleIcon != null) - { - f6 = particleIcon.getInterpolatedU(particleTextureJitterX / 4.0F * 16.0F); - f7 = particleIcon.getInterpolatedU((particleTextureJitterX + 1.0F) / 4.0F * 16.0F); - f8 = particleIcon.getInterpolatedV(particleTextureJitterY / 4.0F * 16.0F); - f9 = particleIcon.getInterpolatedV((particleTextureJitterY + 1.0F) / 4.0F * 16.0F); - } - - float f11 = (float) (prevPosX + (posX - prevPosX) * par2 - interpPosX); - float f12 = (float) (prevPosY + (posY - prevPosY) * par2 - interpPosY); - float f13 = (float) (prevPosZ + (posZ - prevPosZ) * par2 - interpPosZ); - float f14 = 1.0F; - par1Tessellator.setColorOpaque_F(f14 * particleRed, f14 * particleGreen, f14 * particleBlue); - par1Tessellator.addVertexWithUV(f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, f6, f9); - par1Tessellator.addVertexWithUV(f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, f6, f8); - par1Tessellator.addVertexWithUV(f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, f7, f8); - par1Tessellator.addVertexWithUV(f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, f7, f9); - } -} diff --git a/src/main/java/codechicken/lib/render/FontUtils.java b/src/main/java/codechicken/lib/render/FontUtils.java deleted file mode 100644 index 35295b71..00000000 --- a/src/main/java/codechicken/lib/render/FontUtils.java +++ /dev/null @@ -1,74 +0,0 @@ -package codechicken.lib.render; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.item.ItemStack; -import org.lwjgl.opengl.GL11; - -public class FontUtils -{ - public static final String[] prefixes = new String[]{"K", "M", "G"}; - public static FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; - - public static void drawCenteredString(String s, int xCenter, int y, int colour) - { - fontRenderer.drawString(s, xCenter - fontRenderer.getStringWidth(s) / 2, y, colour); - } - - public static void drawRightString(String s, int xRight, int y, int colour) - { - fontRenderer.drawString(s, xRight - fontRenderer.getStringWidth(s), y, colour); - } - - public static void drawItemQuantity(int x, int y, ItemStack item, String quantity, int mode) - { - if (item == null || (quantity == null && item.stackSize <= 1)) - { - return; - } - - if (quantity == null) - { - switch (mode) - { - case 2: - int q = item.stackSize; - String postfix = ""; - for (int p = 0; p < 3 && q > 1000; p++) - { - q /= 1000; - postfix = prefixes[p]; - } - quantity = Integer.toString(q) + postfix; - case 1: - quantity = ""; - if (item.stackSize / 64 > 0) - { - quantity += item.stackSize / 64 + "s"; - } - if (item.stackSize % 64 > 0) - { - quantity += item.stackSize % 64; - } - break; - default: - quantity = Integer.toString(item.stackSize); - break; - } - } - - double scale = quantity.length() > 2 ? 0.5 : 1; - double sheight = 8 * scale; - double swidth = fontRenderer.getStringWidth(quantity) * scale; - - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glPushMatrix(); - GL11.glTranslated(x + 16 - swidth, y + 16 - sheight, 0); - GL11.glScaled(scale, scale, 1); - fontRenderer.drawStringWithShadow(quantity, 0, 0, 0xFFFFFF); - GL11.glPopMatrix(); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - } -} diff --git a/src/main/java/codechicken/lib/render/IFaceRenderer.java b/src/main/java/codechicken/lib/render/IFaceRenderer.java deleted file mode 100644 index d2ed2b45..00000000 --- a/src/main/java/codechicken/lib/render/IFaceRenderer.java +++ /dev/null @@ -1,6 +0,0 @@ -package codechicken.lib.render; - -public interface IFaceRenderer -{ - public void renderFace(Vertex5[] face, int side); -} diff --git a/src/main/java/codechicken/lib/render/ManagedTextureFX.java b/src/main/java/codechicken/lib/render/ManagedTextureFX.java deleted file mode 100644 index 03050ea5..00000000 --- a/src/main/java/codechicken/lib/render/ManagedTextureFX.java +++ /dev/null @@ -1,31 +0,0 @@ -package codechicken.lib.render; - -public class ManagedTextureFX extends TextureFX -{ - public boolean changed; - - public ManagedTextureFX(int size, String name) - { - super(size, name); - imageData = new int[size * size]; - } - - @Override - public void setup() - { - } - - public void setData(int[] data) - { - System.arraycopy(data, 0, imageData, 0, imageData.length); - changed = true; - } - - @Override - public boolean changed() - { - boolean r = changed; - changed = false; - return r; - } -} diff --git a/src/main/java/codechicken/lib/render/PlaceholderTexture.java b/src/main/java/codechicken/lib/render/PlaceholderTexture.java deleted file mode 100644 index 630f677a..00000000 --- a/src/main/java/codechicken/lib/render/PlaceholderTexture.java +++ /dev/null @@ -1,25 +0,0 @@ -package codechicken.lib.render; - -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.IResourceManager; -import net.minecraft.util.ResourceLocation; - -public class PlaceholderTexture extends TextureAtlasSprite -{ - protected PlaceholderTexture(String par1) - { - super(par1); - } - - @Override - public boolean hasCustomLoader(IResourceManager manager, ResourceLocation location) - { - return true; - } - - @Override - public boolean load(IResourceManager manager, ResourceLocation location) - { - return true; - } -} diff --git a/src/main/java/codechicken/lib/render/QBImporter.java b/src/main/java/codechicken/lib/render/QBImporter.java deleted file mode 100644 index 3cf2cc91..00000000 --- a/src/main/java/codechicken/lib/render/QBImporter.java +++ /dev/null @@ -1,926 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.render.uv.UV; -import codechicken.lib.render.uv.UVScale; -import codechicken.lib.vec.*; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; -import net.minecraft.util.ResourceLocation; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.*; -import java.util.*; - -public class QBImporter -{ - public static final int TEXTUREPLANES = 1; - public static final int SQUARETEXTURE = 2; - public static final int MERGETEXTURES = 4; - public static final int SCALEMC = 8; - private static final int[][] vertOrder = new int[][]{//clockwise because MC is left handed - {3, 0}, - {1, 0}, - {1, 2}, - {3, 2}}; - private static final int CODEFLAG = Integer.reverseBytes(2); - private static final int NEXTSLICEFLAG = Integer.reverseBytes(6); - - private static String readAsciiString(DataInputStream din) throws IOException - { - byte[] bytes = new byte[din.readByte() & 0xFF]; - din.readFully(bytes); - return new String(bytes, "US-ASCII"); - } - - private static int readTni(DataInputStream din) throws IOException - { - return Integer.reverseBytes(din.readInt()); - } - - public static QBModel loadQB(InputStream input) throws IOException - { - DataInputStream din = new DataInputStream(input); - - QBModel m = new QBModel(); - int version = din.readInt(); - int colorFormat = din.readInt(); - m.rightHanded = din.readInt() != 0; - boolean compressed = din.readInt() != 0; - boolean visEncoded = din.readInt() != 0; - - if (visEncoded) - { - throw new IllegalArgumentException("Encoded Visiblity States not supported"); - } - - m.matrices = new QBMatrix[readTni(din)]; - for (int i = 0; i < m.matrices.length; i++) - { - QBMatrix mat = new QBMatrix(); - m.matrices[i] = mat; - mat.name = readAsciiString(din); - mat.size = new BlockCoord(readTni(din), readTni(din), readTni(din)); - mat.pos = new BlockCoord(readTni(din), readTni(din), readTni(din)); - mat.matrix = new int[mat.size.x][mat.size.y][mat.size.z]; - mat.readMatrix(din, compressed); - if (colorFormat == 1) - { - mat.convertBGRAtoRGBA(); - } - } - - return m; - } - - public static QBModel loadQB(ResourceLocation res) - { - try - { - return loadQB(Minecraft.getMinecraft().getResourceManager().getResource(res).getInputStream()); - } catch (Exception e) - { - throw new RuntimeException("failed to load model: " + res, e); - } - } - - public static QBModel loadQB(File file) - { - try - { - FileInputStream fin = new FileInputStream(file); - try - { - return loadQB(fin); - } finally - { - fin.close(); - } - } catch (Exception e) - { - throw new RuntimeException("failed to load model: " + file.getPath(), e); - } - } - - private static class ImagePackNode - { - Rectangle4i rect; - ImagePackNode child1; - ImagePackNode child2; - QBImage packed; - - public ImagePackNode(int x, int y, int w, int h) - { - rect = new Rectangle4i(x, y, w, h); - } - - private static void nextSize(Rectangle4i rect, boolean square) - { - if (square) - { - rect.w <<= 1; - rect.h <<= 1; - } else - { - if (rect.w == rect.h) - { - rect.w *= 2; - } else - { - rect.h *= 2; - } - } - } - - public static ImagePackNode pack(List images, boolean square) - { - Collections.sort(images); - - int area = 0; - for (QBImage img : images) - area += img.area(); - - ImagePackNode node = new ImagePackNode(0, 0, 2, 2); - while (node.rect.area() < area) - nextSize(node.rect, square); - - while (true) - { - boolean packed = true; - for (QBImage img : images) - if (!node.pack(img)) - { - packed = false; - break; - } - - if (packed) - { - return node; - } - - node.child1 = node.child2 = null; - nextSize(node.rect, square); - } - } - - public boolean pack(QBImage img) - { - if (child1 != null) - { - return child1.pack(img) || child2.pack(img); - } - - if (packed != null) - { - return false; - } - - int fit = getFit(img.width(), img.height()); - if (fit == 0) - { - return false; - } - - if ((fit & 2) != 0) - {//exact fit - packed = img; - img.packSlot = rect; - img.packT = new ImageTransform((fit & 1) << 2); - return true; - } - - int w = (fit & 1) == 0 ? img.width() : img.height(); - int h = (fit & 1) == 0 ? img.height() : img.width(); - - if (rect.w - w > rect.h - h) - {//create split with biggest leftover space - child1 = new ImagePackNode(rect.x, rect.y, w, rect.h); - child2 = new ImagePackNode(rect.x + w, rect.y, rect.w - w, rect.h); - } else - { - child1 = new ImagePackNode(rect.x, rect.y, rect.w, h); - child2 = new ImagePackNode(rect.x, rect.y + h, rect.w, rect.h - h); - } - return child1.pack(img); - } - - private int getFit(int w, int h) - { - if (w == rect.w && h == rect.h) - { - return 2; - } - if (w == rect.h && h == rect.w) - { - return 3; - } - if (rect.w >= w && rect.h >= h) - { - return 4; - } - if (rect.w >= h && rect.h >= w) - { - return 5; - } - - return 0; - } - - public BufferedImage toImage() - { - BufferedImage img = new BufferedImage(rect.w, rect.h, BufferedImage.TYPE_INT_ARGB); - write(img); - return img; - } - - private void write(BufferedImage img) - { - if (child1 != null) - { - child1.write(img); - child2.write(img); - } else if (packed != null) - { - ImageTransform t = packed.packT; - for (int u = 0; u < rect.w; u++) - for (int v = 0; v < rect.h; v++) - { - int rgba = t.access(packed, u, v); - img.setRGB(u + rect.x, v + rect.y, rgba >>> 8 | rgba << 24); - } - } - } - } - - private static class ImageTransform - { - int transform; - - public ImageTransform(int i) - { - transform = i; - } - - public ImageTransform() - { - this(0); - } - - public boolean transpose() - { - return (transform & 4) != 0; - } - - public boolean flipU() - { - return (transform & 1) != 0; - } - - public boolean flipV() - { - return (transform & 2) != 0; - } - - public int access(QBImage img, int u, int v) - { - if (transpose()) - { - int tmp = u; - u = v; - v = tmp; - } - if (flipU()) - { - u = img.width() - 1 - u; - } - if (flipV()) - { - v = img.height() - 1 - v; - } - - return img.data[u][v]; - } - - public UV transform(UV uv) - { - if (transpose()) - { - double tmp = uv.u; - uv.u = uv.v; - uv.v = tmp; - } - if (flipU()) - { - uv.u = 1 - uv.u; - } - if (flipV()) - { - uv.v = 1 - uv.v; - } - - return uv; - } - } - - public static class QBImage implements Comparable - { - int[][] data; - ImageTransform packT; - Rectangle4i packSlot; - - public int width() - { - return data.length; - } - - public int height() - { - return data[0].length; - } - - public int area() - { - return width() * height(); - } - - @Override - public int compareTo(QBImage o) - { - int a = area(); - int b = o.area(); - return a > b ? -1 : a == b ? 0 : 1; - } - - public ImageTransform transformTo(QBImage img) - { - if (width() == img.width() && height() == img.height()) - { - for (int i = 0; i < 4; i++) - { - ImageTransform t = new ImageTransform(i); - if (equals(img, t)) - { - return t; - } - } - } - if (width() == img.height() && height() == img.width()) - { - for (int i = 4; i < 8; i++) - { - ImageTransform t = new ImageTransform(i); - if (equals(img, t)) - { - return t; - } - } - } - return null; - } - - public boolean equals(QBImage img, ImageTransform t) - { - for (int u = 0; u < img.width(); u++) - for (int v = 0; v < img.height(); v++) - if (t.access(this, u, v) != img.data[u][v]) - { - return false; - } - - return true; - } - - public void transform(UV uv) - { - packT.transform(uv); - uv.u *= packSlot.w; - uv.v *= packSlot.h; - uv.u += packSlot.x; - uv.v += packSlot.y; - } - } - - public static class QBQuad - { - public Vertex5[] verts = new Vertex5[4]; - public QBImage image = new QBImage(); - public ImageTransform t = new ImageTransform(); - public int side; - - public QBQuad(int side) - { - this.side = side; - } - - public static QBQuad restore(Rectangle4i flat, int side, double d, QBImage img) - { - QBQuad quad = new QBQuad(side); - quad.image = img; - - Transformation t = new Scale(-1, 1, -1).with(Rotation.sideOrientation(side, 0)).with(new Translation(new Vector3().setSide(side, d))); - quad.verts[0] = new Vertex5(flat.x, 0, flat.y, 0, 0); - quad.verts[1] = new Vertex5(flat.x + flat.w, 0, flat.y, 1, 0); - quad.verts[2] = new Vertex5(flat.x + flat.w, 0, flat.y + flat.h, 1, 1); - quad.verts[3] = new Vertex5(flat.x, 0, flat.y + flat.h, 0, 1); - for (Vertex5 vert : quad.verts) - vert.apply(t); - - return quad; - } - - public void applyImageT() - { - for (Vertex5 vert : verts) - { - t.transform(vert.uv); - image.transform(vert.uv); - } - } - - public Rectangle4i flatten() - { - Transformation t = Rotation.sideOrientation(side, 0).inverse().with(new Scale(-1, 0, -1)); - Vector3 vmin = verts[0].vec.copy().apply(t); - Vector3 vmax = verts[2].vec.copy().apply(t); - return new Rectangle4i((int) vmin.x, (int) vmin.z, (int) (vmax.x - vmin.x), (int) (vmax.z - vmin.z)); - } - } - - public static class QBCuboid - { - public QBMatrix mat; - public CuboidCoord c; - public int sides; - - public QBCuboid(QBMatrix mat, CuboidCoord c) - { - this.mat = mat; - this.c = c; - sides = 0; - } - - public static boolean intersects(QBCuboid a, QBCuboid b) - { - CuboidCoord c = a.c; - CuboidCoord d = b.c; - return c.min.x <= d.max.x && - d.min.x <= c.max.x && - c.min.y <= d.max.y && - d.min.y <= c.max.y && - c.min.z <= d.max.z && - d.min.z <= c.max.z; - } - - public static void clip(QBCuboid a, QBCuboid b) - { - if (intersects(a, b)) - { - a.clip(b); - b.clip(a); - } - } - - public void clip(QBCuboid o) - { - CuboidCoord d = o.c; - for (int a = 0; a < 6; a += 2) - { - int a1 = (a + 2) % 6; - int a2 = (a + 4) % 6; - if (c.getSide(a1 + 1) <= d.getSide(a1 + 1) && - c.getSide(a1) >= d.getSide(a1) && - c.getSide(a2 + 1) <= d.getSide(a2 + 1) && - c.getSide(a2) >= d.getSide(a2)) - { - - if (c.getSide(a) <= d.getSide(a + 1) && c.getSide(a) >= d.getSide(a)) - { - c.setSide(a, d.getSide(a + 1) + 1); - sides |= 1 << a; - } - if (c.getSide(a + 1) >= d.getSide(a) && c.getSide(a + 1) <= d.getSide(a + 1)) - { - c.setSide(a + 1, d.getSide(a) - 1); - sides |= 2 << a; - } - } - } - } - - public void extractQuads(List quads) - { - Cuboid6 box = c.bounds(); - for (int s = 0; s < 6; s++) - if ((sides & 1 << s) == 0) - { - quads.add(extractQuad(s, box)); - } - } - - private QBQuad extractQuad(int side, Cuboid6 box) - { - double[] da = new double[3]; - da[side >> 1] = box.getSide(side); - - QBQuad quad = new QBQuad(side); - for (int i = 0; i < 4; i++) - { - int rU = vertOrder[i][0]; - int rV = vertOrder[i][1]; - int sideU = Rotation.rotateSide(side, rU); - int sideV = Rotation.rotateSide(side, rV); - da[sideU >> 1] = box.getSide(sideU); - da[sideV >> 1] = box.getSide(sideV); - quad.verts[i] = new Vertex5(Vector3.fromAxes(da), (3 - rU) / 2, rV / 2); - } - - int sideU = Rotation.rotateSide(side, 1); - int sideV = Rotation.rotateSide(side, 2); - quad.image.data = new int[c.size(sideU)][c.size(sideV)]; - QBImage image = quad.image; - - int[] ia = new int[3]; - ia[side >> 1] = c.getSide(side); - ia[sideU >> 1] = c.getSide(sideU ^ 1); - ia[sideV >> 1] = c.getSide(sideV ^ 1); - BlockCoord b = BlockCoord.fromAxes(ia); - BlockCoord bU = BlockCoord.sideOffsets[sideU]; - BlockCoord bV = BlockCoord.sideOffsets[sideV]; - for (int u = 0; u < image.width(); u++) - for (int v = 0; v < image.height(); v++) - image.data[u][v] = mat.matrix[b.x + bU.x * u + bV.x * v][b.y + bU.y * u + bV.y * v][b.z + bU.z * u + bV.z * v]; - - return quad; - } - } - - public static class QBMatrix - { - public String name; - public BlockCoord pos; - public BlockCoord size; - public int[][][] matrix; - - private static void addImages(List quads, List images) - { - for (QBQuad q : quads) - { - QBImage img = q.image; - boolean matched = false; - for (QBImage img2 : images) - { - ImageTransform t = img.transformTo(img2); - if (t != null) - { - q.t = t; - q.image = img2; - matched = true; - break; - } - } - if (!matched) - { - images.add(img); - } - } - } - - public void readMatrix(DataInputStream din, boolean compressed) throws IOException - { - if (compressed) - { - int z = 0; - while (z < size.z) - { - int index = 0; - - while (true) - { - int data = din.readInt(); - - if (data == NEXTSLICEFLAG) - { - break; - } - - if (data == CODEFLAG) - { - int count = readTni(din); - data = din.readInt(); - - for (int j = 0; j < count; j++, index++) - matrix[index % size.x][index / size.x][z] = data; - } else - { - matrix[index % size.x][index / size.x][z] = data; - index++; - } - } - z++; - } - } else - { - for (int z = 0; z < size.z; z++) - for (int y = 0; y < size.y; y++) - for (int x = 0; x < size.x; x++) - matrix[x][y][z] = din.readInt(); - } - } - - public void convertBGRAtoRGBA() - { - for (int z = 0; z < size.z; z++) - for (int y = 0; y < size.y; y++) - for (int x = 0; x < size.x; x++) - { - int i = matrix[x][y][z]; - matrix[x][y][z] = Integer.reverseBytes(i >>> 8) | i & 0xFF; - } - } - - private boolean voxelFull(boolean[][][] solid, CuboidCoord c) - { - for (BlockCoord b : c) - if (matrix[b.x][b.y][b.z] == 0) - { - return false; - } - for (BlockCoord b : c) - solid[b.x][b.y][b.z] = false; - return true; - } - - private QBCuboid expand(boolean[][][] solid, BlockCoord b) - { - CuboidCoord c = new CuboidCoord(b); - solid[b.x][b.y][b.z] = false; - - for (int s = 0; s < 6; s++) - { - CuboidCoord slice = c.copy(); - slice.expand(s ^ 1, -(slice.size(s) - 1)); - slice.expand(s, 1); - - while (slice.getSide(s) >= 0 && slice.getSide(s) < size.getSide(s)) - { - if (!voxelFull(solid, slice)) - { - break; - } - slice.expand(s ^ 1, -1); - slice.expand(s, 1); - c.expand(s, 1); - } - } - return new QBCuboid(this, c); - } - - public List rectangulate() - { - List list = new ArrayList(); - boolean[][][] solid = new boolean[size.x][size.y][size.z]; - for (int z = 0; z < size.z; z++) - for (int y = 0; y < size.y; y++) - for (int x = 0; x < size.x; x++) - solid[x][y][z] = matrix[x][y][z] != 0; - - for (int x = 0; x < size.x; x++) - for (int z = 0; z < size.z; z++) - for (int y = 0; y < size.y; y++) - if (solid[x][y][z]) - { - list.add(expand(solid, new BlockCoord(x, y, z))); - } - - for (int i = 0; i < list.size(); i++) - for (int j = i + 1; j < list.size(); j++) - QBCuboid.clip(list.get(i), list.get(j)); - - return list; - } - - public List extractQuads(boolean texturePlanes) - { - List quads = new LinkedList(); - for (QBCuboid c : rectangulate()) - c.extractQuads(quads); - - if (texturePlanes) - { - optimisePlanes(quads); - } - - return quads; - } - - private void optimisePlanes(List quads) - { - Multimap map = HashMultimap.create(); - for (QBQuad quad : quads) - map.put(quad.side | ((int) quad.verts[0].vec.getSide(quad.side)) << 3, quad); - - quads.clear(); - for (Integer key : map.keySet()) - { - Collection plane = map.get(key); - if (plane.size() == 1) - { - quads.add(plane.iterator().next()); - continue; - } - - int side = key & 7; - Rectangle4i rect = null; - for (QBQuad q : plane) - if (rect == null) - { - rect = q.flatten(); - } else - { - rect.include(q.flatten()); - } - - QBImage img = new QBImage(); - img.data = new int[rect.w][rect.h]; - for (QBQuad q : plane) - { - QBImage from = q.image; - Rectangle4i r = q.flatten(); - int du = r.x - rect.x; - int dv = r.y - rect.y; - for (int u = 0; u < from.width(); u++) - for (int v = 0; v < from.height(); v++) - img.data[du + u][dv + v] = from.data[u][v]; - } - - quads.add(QBQuad.restore(rect, side, key >> 3, img)); - } - } - - public CCModel buildModel(List quads, BufferedImage img, boolean scaleMC) - { - CCModel m = CCModel.quadModel(quads.size() * 4); - int i = 0; - for (QBQuad quad : quads) - { - quad.applyImageT(); - m.verts[i++] = quad.verts[0]; - m.verts[i++] = quad.verts[1]; - m.verts[i++] = quad.verts[2]; - m.verts[i++] = quad.verts[3]; - } - m.apply(new UVScale(1D / img.getWidth(), 1D / img.getHeight())); - m.apply(new Translation(pos.x, pos.y, pos.z)); - if (scaleMC) - { - m.apply(new Scale(1 / 16D)); - } - m.computeNormals(); - return m; - } - } - - public static class QBModel - { - public QBMatrix[] matrices; - public boolean rightHanded; - - public RasterisedModel toRasterisedModel(int flags) - { - List qbImages = new ArrayList(); - List> modelQuads = new ArrayList>(); - List images = new ArrayList(); - - boolean texturePlanes = (flags & TEXTUREPLANES) != 0; - boolean squareTextures = (flags & SQUARETEXTURE) != 0; - boolean mergeTextures = (flags & MERGETEXTURES) != 0; - boolean scaleMC = (flags & SCALEMC) != 0; - - for (QBMatrix mat : matrices) - { - List quads = mat.extractQuads(texturePlanes); - modelQuads.add(quads); - QBMatrix.addImages(quads, qbImages); - if (!mergeTextures) - { - images.add(ImagePackNode.pack(qbImages, squareTextures).toImage()); - qbImages.clear(); - } - } - - if (mergeTextures) - { - images.add(ImagePackNode.pack(qbImages, squareTextures).toImage()); - } - - RasterisedModel m = new RasterisedModel(images); - for (int i = 0; i < matrices.length; i++) - { - QBMatrix mat = matrices[i]; - BufferedImage img = images.get(mergeTextures ? 0 : i); - m.add(mat.name, mat.buildModel(modelQuads.get(i), img, scaleMC)); - } - return m; - } - } - - public static class RasterisedModel - { - private Map map = new HashMap(); - private List images; - private String[] icons; - - public RasterisedModel(List images) - { - this.images = images; - icons = new String[images.size()]; - } - - public void add(String name, CCModel m) - { - map.put(name, new Holder(m, Math.min(map.size(), images.size() - 1))); - } - - public CCModel getModel(String key) - { - return map.get(key).m; - } - - public IIcon getIcon(String key, IIconRegister r, String iconName) - { - int img = map.get(key).img; - if (icons[img] != null && !iconName.equals(icons[img])) - { - throw new IllegalArgumentException("Attempted to get a previously registered icon by a different name: " + icons[img] + ", " + iconName); - } - if (icons[img] != null) - { - return r.registerIcon(iconName); - } - - icons[img] = iconName; - return TextureUtils.getTextureSpecial(r, iconName).addTexture(new TextureDataHolder(images.get(img))); - } - - private void exportImg(BufferedImage img, File imgFile) throws IOException - { - if (!imgFile.exists()) - { - imgFile.createNewFile(); - } - ImageIO.write(img, "PNG", imgFile); - } - - public void export(File objFile, File imgDir) - { - try - { - if (!objFile.exists()) - { - objFile.createNewFile(); - } - if (!imgDir.exists()) - { - imgDir.mkdirs(); - } - - Map modelMap = new HashMap(); - for (Map.Entry e : map.entrySet()) - modelMap.put(e.getKey(), e.getValue().m); - - PrintWriter p = new PrintWriter(objFile); - CCModel.exportObj(modelMap, p); - p.close(); - - if (images.size() < map.size()) - { - exportImg(images.get(0), new File(imgDir, objFile.getName().replaceAll("(.+)\\..+", "$1.png"))); - } else - { - for (Map.Entry e : map.entrySet()) - exportImg(images.get(e.getValue().img), new File(imgDir, e.getKey() + ".png")); - } - - } catch (IOException e) - { - throw new RuntimeException(e); - } - } - - private class Holder - { - CCModel m; - int img; - - public Holder(CCModel m, int img) - { - this.m = m; - this.img = img; - } - } - } -} diff --git a/src/main/java/codechicken/lib/render/RenderUtils.java b/src/main/java/codechicken/lib/render/RenderUtils.java deleted file mode 100644 index 6ee10f16..00000000 --- a/src/main/java/codechicken/lib/render/RenderUtils.java +++ /dev/null @@ -1,375 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.vec.Cuboid6; -import codechicken.lib.vec.Rectangle4i; -import codechicken.lib.vec.Vector3; -import net.minecraft.block.Block; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.entity.RenderItem; -import net.minecraft.client.renderer.entity.RenderManager; -import net.minecraft.entity.Entity; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraftforge.client.IItemRenderer; -import net.minecraftforge.client.MinecraftForgeClient; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import org.lwjgl.opengl.GL11; - -import static net.minecraftforge.client.IItemRenderer.ItemRenderType.ENTITY; -import static net.minecraftforge.client.IItemRenderer.ItemRendererHelper.BLOCK_3D; - -public class RenderUtils -{ - static Vector3[] vectors = new Vector3[8]; - static RenderItem uniformRenderItem = new RenderItem() - { - public boolean shouldBob() - { - return false; - } - }; - static EntityItem entityItem; - - static - { - for (int i = 0; i < vectors.length; i++) - vectors[i] = new Vector3(); - - uniformRenderItem.setRenderManager(RenderManager.instance); - - entityItem = new EntityItem(null); - entityItem.hoverStart = 0; - } - - public static void renderFluidQuad(Vector3 point1, Vector3 point2, Vector3 point3, Vector3 point4, IIcon icon, double res) - { - renderFluidQuad(point2, vectors[0].set(point4).subtract(point1), vectors[1].set(point1).subtract(point2), icon, res); - } - - /** - * Draws a tessellated quadrilateral bottom to top, left to right - * - * @param base The bottom left corner of the quad - * @param wide The bottom of the quad - * @param high The left side of the quad - * @param res Units per icon - */ - public static void renderFluidQuad(Vector3 base, Vector3 wide, Vector3 high, IIcon icon, double res) - { - Tessellator t = Tessellator.instance; - - double u1 = icon.getMinU(); - double du = icon.getMaxU() - icon.getMinU(); - double v2 = icon.getMaxV(); - double dv = icon.getMaxV() - icon.getMinV(); - - double wlen = wide.mag(); - double hlen = high.mag(); - - double x = 0; - while (x < wlen) - { - double rx = wlen - x; - if (rx > res) - { - rx = res; - } - - double y = 0; - while (y < hlen) - { - double ry = hlen - y; - if (ry > res) - { - ry = res; - } - - Vector3 dx1 = vectors[2].set(wide).multiply(x / wlen); - Vector3 dx2 = vectors[3].set(wide).multiply((x + rx) / wlen); - Vector3 dy1 = vectors[4].set(high).multiply(y / hlen); - Vector3 dy2 = vectors[5].set(high).multiply((y + ry) / hlen); - - t.addVertexWithUV(base.x + dx1.x + dy2.x, base.y + dx1.y + dy2.y, base.z + dx1.z + dy2.z, u1, v2 - ry / res * dv); - t.addVertexWithUV(base.x + dx1.x + dy1.x, base.y + dx1.y + dy1.y, base.z + dx1.z + dy1.z, u1, v2); - t.addVertexWithUV(base.x + dx2.x + dy1.x, base.y + dx2.y + dy1.y, base.z + dx2.z + dy1.z, u1 + rx / res * du, v2); - t.addVertexWithUV(base.x + dx2.x + dy2.x, base.y + dx2.y + dy2.y, base.z + dx2.z + dy2.z, u1 + rx / res * du, v2 - ry / res * dv); - - y += ry; - } - - x += rx; - } - } - - public static void translateToWorldCoords(Entity entity, float frame) - { - double interpPosX = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * frame; - double interpPosY = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * frame; - double interpPosZ = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * frame; - - GL11.glTranslated(-interpPosX, -interpPosY, -interpPosZ); - } - - public static void drawCuboidOutline(Cuboid6 c) - { - Tessellator var2 = Tessellator.instance; - var2.startDrawing(3); - var2.addVertex(c.min.x, c.min.y, c.min.z); - var2.addVertex(c.max.x, c.min.y, c.min.z); - var2.addVertex(c.max.x, c.min.y, c.max.z); - var2.addVertex(c.min.x, c.min.y, c.max.z); - var2.addVertex(c.min.x, c.min.y, c.min.z); - var2.draw(); - var2.startDrawing(3); - var2.addVertex(c.min.x, c.max.y, c.min.z); - var2.addVertex(c.max.x, c.max.y, c.min.z); - var2.addVertex(c.max.x, c.max.y, c.max.z); - var2.addVertex(c.min.x, c.max.y, c.max.z); - var2.addVertex(c.min.x, c.max.y, c.min.z); - var2.draw(); - var2.startDrawing(1); - var2.addVertex(c.min.x, c.min.y, c.min.z); - var2.addVertex(c.min.x, c.max.y, c.min.z); - var2.addVertex(c.max.x, c.min.y, c.min.z); - var2.addVertex(c.max.x, c.max.y, c.min.z); - var2.addVertex(c.max.x, c.min.y, c.max.z); - var2.addVertex(c.max.x, c.max.y, c.max.z); - var2.addVertex(c.min.x, c.min.y, c.max.z); - var2.addVertex(c.min.x, c.max.y, c.max.z); - var2.draw(); - } - - public static void renderFluidCuboid(Cuboid6 bound, IIcon tex, double res) - { - renderFluidQuad(//bottom - new Vector3(bound.min.x, bound.min.y, bound.min.z), - new Vector3(bound.max.x, bound.min.y, bound.min.z), - new Vector3(bound.max.x, bound.min.y, bound.max.z), - new Vector3(bound.min.x, bound.min.y, bound.max.z), - tex, res); - renderFluidQuad(//top - new Vector3(bound.min.x, bound.max.y, bound.min.z), - new Vector3(bound.min.x, bound.max.y, bound.max.z), - new Vector3(bound.max.x, bound.max.y, bound.max.z), - new Vector3(bound.max.x, bound.max.y, bound.min.z), - tex, res); - renderFluidQuad(//-x - new Vector3(bound.min.x, bound.max.y, bound.min.z), - new Vector3(bound.min.x, bound.min.y, bound.min.z), - new Vector3(bound.min.x, bound.min.y, bound.max.z), - new Vector3(bound.min.x, bound.max.y, bound.max.z), - tex, res); - renderFluidQuad(//+x - new Vector3(bound.max.x, bound.max.y, bound.max.z), - new Vector3(bound.max.x, bound.min.y, bound.max.z), - new Vector3(bound.max.x, bound.min.y, bound.min.z), - new Vector3(bound.max.x, bound.max.y, bound.min.z), - tex, res); - renderFluidQuad(//-z - new Vector3(bound.max.x, bound.max.y, bound.min.z), - new Vector3(bound.max.x, bound.min.y, bound.min.z), - new Vector3(bound.min.x, bound.min.y, bound.min.z), - new Vector3(bound.min.x, bound.max.y, bound.min.z), - tex, res); - renderFluidQuad(//+z - new Vector3(bound.min.x, bound.max.y, bound.max.z), - new Vector3(bound.min.x, bound.min.y, bound.max.z), - new Vector3(bound.max.x, bound.min.y, bound.max.z), - new Vector3(bound.max.x, bound.max.y, bound.max.z), - tex, res); - } - - public static void renderBlockOverlaySide(int x, int y, int z, int side, double tx1, double tx2, double ty1, double ty2) - { - double[] points = new double[]{x - 0.009, x + 1.009, y - 0.009, y + 1.009, z - 0.009, z + 1.009}; - - Tessellator tessellator = Tessellator.instance; - switch (side) - { - case 0: - tessellator.addVertexWithUV(points[0], points[2], points[4], tx1, ty1); - tessellator.addVertexWithUV(points[1], points[2], points[4], tx2, ty1); - tessellator.addVertexWithUV(points[1], points[2], points[5], tx2, ty2); - tessellator.addVertexWithUV(points[0], points[2], points[5], tx1, ty2); - break; - case 1: - tessellator.addVertexWithUV(points[1], points[3], points[4], tx2, ty1); - tessellator.addVertexWithUV(points[0], points[3], points[4], tx1, ty1); - tessellator.addVertexWithUV(points[0], points[3], points[5], tx1, ty2); - tessellator.addVertexWithUV(points[1], points[3], points[5], tx2, ty2); - break; - case 2: - tessellator.addVertexWithUV(points[0], points[3], points[4], tx2, ty1); - tessellator.addVertexWithUV(points[1], points[3], points[4], tx1, ty1); - tessellator.addVertexWithUV(points[1], points[2], points[4], tx1, ty2); - tessellator.addVertexWithUV(points[0], points[2], points[4], tx2, ty2); - break; - case 3: - tessellator.addVertexWithUV(points[1], points[3], points[5], tx2, ty1); - tessellator.addVertexWithUV(points[0], points[3], points[5], tx1, ty1); - tessellator.addVertexWithUV(points[0], points[2], points[5], tx1, ty2); - tessellator.addVertexWithUV(points[1], points[2], points[5], tx2, ty2); - break; - case 4: - tessellator.addVertexWithUV(points[0], points[3], points[5], tx2, ty1); - tessellator.addVertexWithUV(points[0], points[3], points[4], tx1, ty1); - tessellator.addVertexWithUV(points[0], points[2], points[4], tx1, ty2); - tessellator.addVertexWithUV(points[0], points[2], points[5], tx2, ty2); - break; - case 5: - tessellator.addVertexWithUV(points[1], points[3], points[4], tx2, ty1); - tessellator.addVertexWithUV(points[1], points[3], points[5], tx1, ty1); - tessellator.addVertexWithUV(points[1], points[2], points[5], tx1, ty2); - tessellator.addVertexWithUV(points[1], points[2], points[4], tx2, ty2); - break; - } - } - - public static boolean shouldRenderFluid(FluidStack stack) - { - return stack.amount > 0 && stack.getFluid() != null; - } - - /** - * @param stack The fluid stack to render - * @return The icon of the fluid - */ - public static IIcon prepareFluidRender(FluidStack stack, int alpha) - { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - - Fluid fluid = stack.getFluid(); - CCRenderState.setColour(fluid.getColor(stack) << 8 | alpha); - TextureUtils.bindAtlas(fluid.getSpriteNumber()); - return TextureUtils.safeIcon(fluid.getIcon(stack)); - } - - /** - * Re-enables lighting and disables blending. - */ - public static void postFluidRender() - { - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_BLEND); - } - - public static double fluidDensityToAlpha(double density) - { - return Math.pow(density, 0.4); - } - - /** - * Renders a fluid within a bounding box. - * If the fluid is a liquid it will render as a normal tank with height equal to density/bound.height. - * If the fluid is a gas, it will render the full box with an alpha equal to density. - * Warning, bound will be mutated if the fluid is a liquid - * - * @param stack The fluid to render. - * @param bound The box within which the fluid is contained. - * @param density The volume of fluid / the capacity of the tank. For gases this determines the alpha, for liquids this determines the height. - * @param res The resolution to render at. - */ - public static void renderFluidCuboid(FluidStack stack, Cuboid6 bound, double density, double res) - { - if (!shouldRenderFluid(stack)) - { - return; - } - - int alpha = 255; - if (stack.getFluid().isGaseous()) - { - alpha = (int) (fluidDensityToAlpha(density) * 255); - } else - { - bound.max.y = bound.min.y + (bound.max.y - bound.min.y) * density; - } - - IIcon tex = prepareFluidRender(stack, alpha); - CCRenderState.startDrawing(); - renderFluidCuboid(bound, tex, res); - CCRenderState.draw(); - postFluidRender(); - } - - public static void renderFluidGauge(FluidStack stack, Rectangle4i rect, double density, double res) - { - if (!shouldRenderFluid(stack)) - { - return; - } - - int alpha = 255; - if (stack.getFluid().isGaseous()) - { - alpha = (int) (fluidDensityToAlpha(density) * 255); - } else - { - int height = (int) (rect.h * density); - rect.y += rect.h - height; - rect.h = height; - } - - IIcon tex = prepareFluidRender(stack, alpha); - CCRenderState.startDrawing(); - renderFluidQuad( - new Vector3(rect.x, rect.y + rect.h, 0), - new Vector3(rect.w, 0, 0), - new Vector3(0, -rect.h, 0), tex, res); - CCRenderState.draw(); - postFluidRender(); - } - - - /** - * Renders item and blocks in the world at 0,0,0 with transformations that size them appropriately - */ - public static void renderItemUniform(ItemStack item) - { - renderItemUniform(item, 0); - } - - /** - * Renders item and blocks in the world at 0,0,0 with transformations that size them appropriately - * - * @param spin The spin angle of the item around the y axis in degrees - */ - public static void renderItemUniform(ItemStack item, double spin) - { - IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, ENTITY); - boolean is3D = customRenderer != null && customRenderer.shouldUseRenderHelper(ENTITY, item, BLOCK_3D); - - boolean larger = false; - if (item.getItem() instanceof ItemBlock && RenderBlocks.renderItemIn3d(Block.getBlockFromItem(item.getItem()).getRenderType())) - { - int renderType = Block.getBlockFromItem(item.getItem()).getRenderType(); - larger = !(renderType == 1 || renderType == 19 || renderType == 12 || renderType == 2); - } else if (is3D) - { - larger = true; - } - - double d = 2; - double d1 = 1 / d; - if (larger) - { - GL11.glScaled(d, d, d); - } - - GL11.glColor4f(1, 1, 1, 1); - - entityItem.setEntityItemStack(item); - uniformRenderItem.doRender(entityItem, 0, larger ? 0.09 : 0.06, 0, 0, (float) (spin * 9 / Math.PI)); - - if (larger) - { - GL11.glScaled(d1, d1, d1); - } - } -} diff --git a/src/main/java/codechicken/lib/render/ShaderProgram.java b/src/main/java/codechicken/lib/render/ShaderProgram.java deleted file mode 100644 index 31e33bf7..00000000 --- a/src/main/java/codechicken/lib/render/ShaderProgram.java +++ /dev/null @@ -1,149 +0,0 @@ -package codechicken.lib.render; - -import org.lwjgl.opengl.ARBShaderObjects; -import org.lwjgl.opengl.ARBVertexShader; -import org.lwjgl.opengl.GL11; -import org.lwjgl.util.vector.Matrix4f; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import static org.lwjgl.opengl.ARBShaderObjects.*; - -public class ShaderProgram -{ - int programID; - - public ShaderProgram() - { - programID = glCreateProgramObjectARB(); - if (programID == 0) - { - throw new RuntimeException("Unable to allocate shader program object."); - } - } - - public static void restore() - { - glUseProgramObjectARB(0); - } - - public static String asString(InputStream stream) throws IOException - { - StringBuilder sb = new StringBuilder(); - BufferedReader bin = new BufferedReader(new InputStreamReader(stream)); - String line; - while ((line = bin.readLine()) != null) - sb.append(line).append('\n'); - stream.close(); - return sb.toString(); - } - - private static String getInfoLog(int shaderID) - { - return glGetInfoLogARB(shaderID, glGetObjectParameteriARB(shaderID, GL_OBJECT_INFO_LOG_LENGTH_ARB)); - } - - public void attach(int shaderType, String resource) - { - InputStream stream = ShaderProgram.class.getResourceAsStream(resource); - if (stream == null) - { - throw new RuntimeException("Unable to locate resource: " + resource); - } - - attach(shaderType, stream); - } - - public void use() - { - glUseProgramObjectARB(programID); - } - - public void link() - { - glLinkProgramARB(programID); - if (glGetObjectParameteriARB(programID, GL_OBJECT_LINK_STATUS_ARB) == GL11.GL_FALSE) - { - throw new RuntimeException("Error linking program: " + getInfoLog(programID)); - } - - glValidateProgramARB(programID); - if (glGetObjectParameteriARB(programID, GL_OBJECT_VALIDATE_STATUS_ARB) == GL11.GL_FALSE) - { - throw new RuntimeException("Error validating program: " + getInfoLog(programID)); - } - - use(); - onLink(); - restore(); - } - - public void attach(int shaderType, InputStream stream) - { - if (stream == null) - { - throw new RuntimeException("Invalid shader inputstream"); - } - - int shaderID = 0; - try - { - shaderID = glCreateShaderObjectARB(shaderType); - if (shaderID == 0) - { - throw new RuntimeException("Unable to allocate shader object."); - } - - try - { - glShaderSourceARB(shaderID, asString(stream)); - } catch (IOException e) - { - throw new RuntimeException("Error reading inputstream.", e); - } - - glCompileShaderARB(shaderID); - if (glGetObjectParameteriARB(shaderID, GL_OBJECT_COMPILE_STATUS_ARB) == GL11.GL_FALSE) - { - throw new RuntimeException("Error compiling shader: " + getInfoLog(shaderID)); - } - - glAttachObjectARB(programID, shaderID); - } catch (RuntimeException e) - { - glDeleteObjectARB(shaderID); - throw e; - } - } - - public int getUniformLoc(String name) - { - return ARBShaderObjects.glGetUniformLocationARB(programID, name); - } - - public int getAttribLoc(String name) - { - return ARBVertexShader.glGetAttribLocationARB(programID, name); - } - - public void uniformTexture(String name, int textureIndex) - { - ARBShaderObjects.glUniform1iARB(getUniformLoc(name), textureIndex); - } - - public void onLink() - { - - } - - public void glVertexAttributeMat4(int loc, Matrix4f matrix) - { - ARBVertexShader.glVertexAttrib4fARB(loc, matrix.m00, matrix.m01, matrix.m02, matrix.m03); - ARBVertexShader.glVertexAttrib4fARB(loc + 1, matrix.m10, matrix.m11, matrix.m12, matrix.m13); - ARBVertexShader.glVertexAttrib4fARB(loc + 2, matrix.m20, matrix.m21, matrix.m22, matrix.m23); - ARBVertexShader.glVertexAttrib4fARB(loc + 3, matrix.m30, matrix.m31, matrix.m32, matrix.m33); - } -} diff --git a/src/main/java/codechicken/lib/render/SpriteSheetManager.java b/src/main/java/codechicken/lib/render/SpriteSheetManager.java deleted file mode 100644 index abfa2edf..00000000 --- a/src/main/java/codechicken/lib/render/SpriteSheetManager.java +++ /dev/null @@ -1,147 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.render.TextureUtils.IIconSelfRegister; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.util.IIcon; -import net.minecraft.util.ResourceLocation; - -import java.util.ArrayList; -import java.util.HashMap; - -public class SpriteSheetManager -{ - private static HashMap spriteSheets = new HashMap(); - - public static SpriteSheet getSheet(ResourceLocation resource) - { - return getSheet(16, 16, resource); - } - - @SideOnly(Side.CLIENT) - public static class SpriteSheet implements IIconSelfRegister - { - public int atlasIndex; - private int tilesX; - private int tilesY; - private ArrayList newSprites = new ArrayList(); - private TextureSpecial[] sprites; - private ResourceLocation resource; - private TextureDataHolder texture; - private int spriteWidth; - private int spriteHeight; - - private SpriteSheet(int tilesX, int tilesY, ResourceLocation textureFile) - { - this.tilesX = tilesX; - this.tilesY = tilesY; - this.resource = textureFile; - sprites = new TextureSpecial[tilesX * tilesY]; - } - - public void requestIndicies(int... indicies) - { - for (int i : indicies) - setupSprite(i); - } - - public void registerIcons(IIconRegister register) - { - TextureMap textureMap = (TextureMap) register; - - if (TextureUtils.refreshTexture(textureMap, resource.getResourcePath())) - { - reloadTexture(); - for (TextureSpecial sprite : sprites) - if (sprite != null) - { - textureMap.setTextureEntry(sprite.getIconName(), sprite); - } - } else - { - for (int i : newSprites) - textureMap.setTextureEntry(sprites[i].getIconName(), sprites[i]); - } - newSprites.clear(); - } - - public TextureSpecial setupSprite(int i) - { - if (sprites[i] == null) - { - String name = resource + "_" + i; - sprites[i] = new TextureSpecial(name).baseFromSheet(this, i); - newSprites.add(i); - } - return sprites[i]; - } - - private void reloadTexture() - { - texture = TextureUtils.loadTexture(resource); - spriteWidth = texture.width / tilesX; - spriteHeight = texture.height / tilesY; - } - - public IIcon getSprite(int index) - { - IIcon i = sprites[index]; - if (i == null) - { - throw new IllegalArgumentException("Sprite at index: " + index + " from texture file " + resource + " was not preloaded."); - } - return i; - } - - public TextureDataHolder createSprite(int spriteIndex) - { - int sx = spriteIndex % tilesX; - int sy = spriteIndex / tilesX; - TextureDataHolder sprite = new TextureDataHolder(spriteWidth, spriteHeight); - TextureUtils.copySubImg(texture.data, texture.width, sx * spriteWidth, sy * spriteHeight, - spriteWidth, spriteHeight, - sprite.data, spriteWidth, 0, 0); - return sprite; - } - - public int spriteWidth() - { - return spriteWidth; - } - - public int spriteHeight() - { - return spriteHeight; - } - - public TextureSpecial bindTextureFX(int i, TextureFX textureFX) - { - return setupSprite(i).addTextureFX(textureFX); - } - - public SpriteSheet selfRegister(int atlas) - { - TextureUtils.addIconRegistrar(this); - return this; - } - - @Override - public int atlasIndex() - { - return atlasIndex; - } - } - - - static SpriteSheet getSheet(int tilesX, int tilesY, ResourceLocation resource) - { - SpriteSheet sheet = spriteSheets.get(resource.toString()); - if (sheet == null) - { - spriteSheets.put(resource.toString(), sheet = new SpriteSheet(tilesX, tilesY, resource)); - } - return sheet; - } -} diff --git a/src/main/java/codechicken/lib/render/TextureDataHolder.java b/src/main/java/codechicken/lib/render/TextureDataHolder.java deleted file mode 100644 index 60b1e4ee..00000000 --- a/src/main/java/codechicken/lib/render/TextureDataHolder.java +++ /dev/null @@ -1,38 +0,0 @@ -package codechicken.lib.render; - -import java.awt.image.BufferedImage; - -public class TextureDataHolder -{ - public int width; - public int height; - public int[] data; - - public TextureDataHolder(int width, int height) - { - this.width = width; - this.height = height; - data = new int[width * height]; - } - - public TextureDataHolder(int[] data, int width) - { - this.data = data; - this.width = width; - height = data.length / width; - } - - public TextureDataHolder(BufferedImage img) - { - this(img.getWidth(), img.getHeight()); - img.getRGB(0, 0, width, height, data, 0, width); - } - - public TextureDataHolder copyData() - { - int[] copy = new int[data.length]; - System.arraycopy(data, 0, copy, 0, data.length); - data = copy; - return this; - } -} diff --git a/src/main/java/codechicken/lib/render/TextureFX.java b/src/main/java/codechicken/lib/render/TextureFX.java deleted file mode 100644 index f4b401f9..00000000 --- a/src/main/java/codechicken/lib/render/TextureFX.java +++ /dev/null @@ -1,69 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.render.SpriteSheetManager.SpriteSheet; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.client.Minecraft; - -@SideOnly(Side.CLIENT) -public class TextureFX -{ - public int[] imageData; - public int tileSizeBase = 16; - public int tileSizeSquare = 256; - public int tileSizeMask = 15; - public int tileSizeSquareMask = 255; - - public boolean anaglyphEnabled; - public TextureSpecial texture; - - public TextureFX(int spriteIndex, SpriteSheet sheet) - { - texture = sheet.bindTextureFX(spriteIndex, this); - } - - public TextureFX(int size, String name) - { - texture = new TextureSpecial(name).blank(size).selfRegister().addTextureFX(this); - } - - public TextureFX setAtlas(int index) - { - texture.atlasIndex = index; - return this; - } - - public void setup() - { - imageData = new int[tileSizeSquare]; - } - - public void onTextureDimensionsUpdate(int width, int height) - { - if (width != height) - { - throw new IllegalArgumentException("Non-Square textureFX not supported (" + width + ":" + height + ")"); - } - - tileSizeBase = width; - tileSizeSquare = tileSizeBase * tileSizeBase; - tileSizeMask = tileSizeBase - 1; - tileSizeSquareMask = tileSizeSquare - 1; - setup(); - } - - public void update() - { - anaglyphEnabled = Minecraft.getMinecraft().gameSettings.anaglyph; - onTick(); - } - - public void onTick() - { - } - - public boolean changed() - { - return true; - } -} diff --git a/src/main/java/codechicken/lib/render/TextureSpecial.java b/src/main/java/codechicken/lib/render/TextureSpecial.java deleted file mode 100644 index f1011014..00000000 --- a/src/main/java/codechicken/lib/render/TextureSpecial.java +++ /dev/null @@ -1,219 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.render.SpriteSheetManager.SpriteSheet; -import codechicken.lib.render.TextureUtils.IIconSelfRegister; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.client.renderer.texture.TextureUtil; -import net.minecraft.client.resources.IResourceManager; -import net.minecraft.client.resources.data.AnimationMetadataSection; -import net.minecraft.client.settings.GameSettings; -import net.minecraft.util.ResourceLocation; - -import java.awt.image.BufferedImage; -import java.util.ArrayList; - -@SideOnly(Side.CLIENT) -public class TextureSpecial extends TextureAtlasSprite implements IIconSelfRegister -{ - public int atlasIndex; - //sprite sheet fields - private int spriteIndex; - private SpriteSheet spriteSheet; - //textureFX fields - private TextureFX textureFX; - private int mipmapLevels; - private int rawWidth; - private int rawHeight; - private int blankSize = -1; - private ArrayList baseTextures; - private boolean selfRegister; - - protected TextureSpecial(String par1) - { - super(par1); - } - - public TextureSpecial addTexture(TextureDataHolder t) - { - if (baseTextures == null) - { - baseTextures = new ArrayList(); - } - baseTextures.add(t); - return this; - } - - public TextureSpecial baseFromSheet(SpriteSheet spriteSheet, int spriteIndex) - { - this.spriteSheet = spriteSheet; - this.spriteIndex = spriteIndex; - return this; - } - - public TextureSpecial addTextureFX(TextureFX fx) - { - textureFX = fx; - return this; - } - - @Override - public void initSprite(int sheetWidth, int sheetHeight, int originX, int originY, boolean rotated) - { - super.initSprite(sheetWidth, sheetHeight, originX, originY, rotated); - if (textureFX != null) - { - textureFX.onTextureDimensionsUpdate(rawWidth, rawHeight); - } - } - - @Override - public void updateAnimation() - { - if (textureFX != null) - { - textureFX.update(); - if (textureFX.changed()) - { - int[][] mipmaps = new int[mipmapLevels + 1][]; - mipmaps[0] = textureFX.imageData; - mipmaps = prepareAnisotropicFiltering(mipmaps); - mipmaps = TextureUtil.generateMipmapData(mipmapLevels, width, mipmaps); - TextureUtil.uploadTextureMipmap(mipmaps, width, height, originX, originY, false, false); - } - } - } - - - /** - * Copy paste mojang code because it's private, and CCL can't have access transformers or reflection - */ - public int[][] prepareAnisotropicFiltering(int[][] mipmaps) - { - if (Minecraft.getMinecraft().gameSettings.anisotropicFiltering <= 1) - { - return mipmaps; - } else - { - int[][] aint1 = new int[mipmaps.length][]; - - for (int k = 0; k < mipmaps.length; ++k) - { - int[] aint2 = mipmaps[k]; - - if (aint2 != null) - { - int[] aint3 = new int[(rawWidth + 16 >> k) * (rawHeight + 16 >> k)]; - System.arraycopy(aint2, 0, aint3, 0, aint2.length); - aint1[k] = TextureUtil.prepareAnisotropicData(aint3, rawWidth >> k, rawHeight >> k, 8 >> k); - } - } - - return aint1; - } - } - - @Override - public void loadSprite(BufferedImage[] images, AnimationMetadataSection animationMeta, boolean anisotropicFiltering) - { - rawWidth = images[0].getWidth(); - rawHeight = images[0].getHeight(); - super.loadSprite(images, animationMeta, anisotropicFiltering); - } - - @Override - public void generateMipmaps(int p_147963_1_) - { - super.generateMipmaps(p_147963_1_); - mipmapLevels = p_147963_1_; - } - - @Override - public boolean hasCustomLoader(IResourceManager manager, ResourceLocation location) - { - return true; - } - - public void addFrame(int[] data, int width, int height) - { - GameSettings settings = Minecraft.getMinecraft().gameSettings; - BufferedImage[] images = new BufferedImage[settings.mipmapLevels + 1]; - images[0] = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - images[0].setRGB(0, 0, width, height, data, 0, width); - - loadSprite(images, null, settings.anisotropicFiltering > 1); - } - - @Override - public boolean load(IResourceManager manager, ResourceLocation location) - { - if (baseTextures != null) - { - for (TextureDataHolder tex : baseTextures) - addFrame(tex.data, tex.width, tex.height); - } else if (spriteSheet != null) - { - TextureDataHolder tex = spriteSheet.createSprite(spriteIndex); - addFrame(tex.data, tex.width, tex.height); - } else if (blankSize > 0) - { - addFrame(new int[blankSize * blankSize], blankSize, blankSize); - } - - if (framesTextureData.isEmpty()) - { - throw new RuntimeException("No base frame for texture: " + getIconName()); - } - - return false; - } - - @Override - public boolean hasAnimationMetadata() - { - return textureFX != null || super.hasAnimationMetadata(); - } - - @Override - public int getFrameCount() - { - if (textureFX != null) - { - return 1; - } - - return super.getFrameCount(); - } - - public TextureSpecial blank(int size) - { - blankSize = size; - return this; - } - - public TextureSpecial selfRegister() - { - selfRegister = true; - TextureUtils.addIconRegistrar(this); - return this; - } - - @Override - public void registerIcons(IIconRegister register) - { - if (selfRegister) - { - ((TextureMap) register).setTextureEntry(getIconName(), this); - } - } - - @Override - public int atlasIndex() - { - return atlasIndex; - } -} diff --git a/src/main/java/codechicken/lib/render/TextureUtils.java b/src/main/java/codechicken/lib/render/TextureUtils.java deleted file mode 100644 index 9f26c7a1..00000000 --- a/src/main/java/codechicken/lib/render/TextureUtils.java +++ /dev/null @@ -1,192 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.colour.Colour; -import codechicken.lib.colour.ColourARGB; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.util.IIcon; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.common.MinecraftForge; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; - -public class TextureUtils -{ - private static ArrayList iconRegistrars = new ArrayList(); - - public static void addIconRegistrar(IIconSelfRegister registrar) - { - iconRegistrars.add(registrar); - } - - /** - * @return an array of ARGB pixel data - */ - public static int[] loadTextureData(ResourceLocation resource) - { - return loadTexture(resource).data; - } - - public static Colour[] loadTextureColours(ResourceLocation resource) - { - int[] idata = loadTextureData(resource); - Colour[] data = new Colour[idata.length]; - for (int i = 0; i < data.length; i++) - data[i] = new ColourARGB(idata[i]); - return data; - } - - public static InputStream getTextureResource(ResourceLocation textureFile) throws IOException - { - return Minecraft.getMinecraft().getResourceManager().getResource(textureFile).getInputStream(); - } - - public static BufferedImage loadBufferedImage(ResourceLocation textureFile) - { - try - { - return loadBufferedImage(getTextureResource(textureFile)); - } catch (Exception e) - { - System.err.println("Failed to load texture file: " + textureFile); - e.printStackTrace(); - } - return null; - } - - public static BufferedImage loadBufferedImage(InputStream in) throws IOException - { - BufferedImage img = ImageIO.read(in); - in.close(); - return img; - } - - public static TextureManager engine() - { - return Minecraft.getMinecraft().renderEngine; - } - - public static void copySubImg(int[] fromTex, int fromWidth, int fromX, int fromY, int width, int height, int[] toTex, int toWidth, int toX, int toY) - { - for (int y = 0; y < height; y++) - for (int x = 0; x < width; x++) - { - int fp = (y + fromY) * fromWidth + x + fromX; - int tp = (y + toX) * toWidth + x + toX; - - toTex[tp] = fromTex[fp]; - } - } - - public static void bindAtlas(int atlasIndex) - { - engine().bindTexture(atlasIndex == 0 ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture); - } - - public static IIcon getBlankIcon(int size, IIconRegister iconRegister) - { - TextureMap textureMap = (TextureMap) iconRegister; - String s = "blank_" + size; - if (textureMap.getTextureExtry(s) == null) - { - TextureSpecial icon = new TextureSpecial(s).blank(size); - textureMap.setTextureEntry(s, icon); - } - return iconRegister.registerIcon(s); - } - - public static TextureSpecial getTextureSpecial(IIconRegister iconRegister, String name) - { - TextureMap textureMap = (TextureMap) iconRegister; - IIcon entry = textureMap.getTextureExtry(name); - if (entry != null) - { - throw new IllegalStateException("Texture: " + name + " is already registered"); - } - - TextureSpecial icon = new TextureSpecial(name); - textureMap.setTextureEntry(name, icon); - return icon; - } - - public static void prepareTexture(int target, int texture, int min_mag_filter, int wrap) - { - GL11.glBindTexture(target, texture); - GL11.glTexParameteri(target, GL11.GL_TEXTURE_MIN_FILTER, min_mag_filter); - GL11.glTexParameteri(target, GL11.GL_TEXTURE_MAG_FILTER, min_mag_filter); - switch (target) - { - case GL12.GL_TEXTURE_3D: - GL11.glTexParameteri(target, GL12.GL_TEXTURE_WRAP_R, wrap); - case GL11.GL_TEXTURE_2D: - GL11.glTexParameteri(target, GL11.GL_TEXTURE_WRAP_T, wrap); - case GL11.GL_TEXTURE_1D: - GL11.glTexParameteri(target, GL11.GL_TEXTURE_WRAP_S, wrap); - } - } - - public static TextureDataHolder loadTexture(ResourceLocation resource) - { - BufferedImage img = loadBufferedImage(resource); - if (img == null) - { - throw new RuntimeException("Texture not found: " + resource); - } - return new TextureDataHolder(img); - } - - /** - * Uses an empty placeholder texture to tell if the map has been reloaded since the last call to refresh texture and the texture with name needs to be reacquired to be valid - */ - public static boolean refreshTexture(TextureMap map, String name) - { - if (map.getTextureExtry(name) == null) - { - map.setTextureEntry(name, new PlaceholderTexture(name)); - return true; - } - return false; - } - - public static IIcon safeIcon(IIcon icon) - { - if (icon == null) - { - icon = ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture(TextureMap.locationBlocksTexture)).getAtlasSprite("missingno"); - } - - return icon; - } - - @SubscribeEvent - public void textureLoad(TextureStitchEvent.Pre event) - { - for (IIconSelfRegister reg : iconRegistrars) - if (reg.atlasIndex() == event.map.getTextureType()) - { - reg.registerIcons(event.map); - } - } - - public static interface IIconSelfRegister - { - public void registerIcons(IIconRegister register); - - public int atlasIndex(); - } - - static - { - MinecraftForge.EVENT_BUS.register(new TextureUtils()); - } -} diff --git a/src/main/java/codechicken/lib/render/Vertex5.java b/src/main/java/codechicken/lib/render/Vertex5.java deleted file mode 100644 index 48243217..00000000 --- a/src/main/java/codechicken/lib/render/Vertex5.java +++ /dev/null @@ -1,93 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.render.uv.UV; -import codechicken.lib.render.uv.UVTransformation; -import codechicken.lib.util.Copyable; -import codechicken.lib.vec.Transformation; -import codechicken.lib.vec.Vector3; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class Vertex5 implements Copyable -{ - public Vector3 vec; - public UV uv; - - public Vertex5() - { - this(new Vector3(), new UV()); - } - - public Vertex5(Vector3 vert, UV uv) - { - this.vec = vert; - this.uv = uv; - } - - public Vertex5(Vector3 vert, double u, double v) - { - this(vert, new UV(u, v)); - } - - public Vertex5(double x, double y, double z, double u, double v) - { - this(x, y, z, u, v, 0); - } - - public Vertex5(double x, double y, double z, double u, double v, int tex) - { - this(new Vector3(x, y, z), new UV(u, v, tex)); - } - - public Vertex5(Vertex5 vertex5) - { - this(vertex5.vec.copy(), vertex5.uv.copy()); - } - - public Vertex5 set(double x, double y, double z, double u, double v) - { - vec.set(x, y, z); - uv.set(u, v); - return this; - } - - public Vertex5 set(double x, double y, double z, double u, double v, int tex) - { - vec.set(x, y, z); - uv.set(u, v, tex); - return this; - } - - public Vertex5 set(Vertex5 vert) - { - vec.set(vert.vec); - uv.set(vert.uv); - return this; - } - - public Vertex5 copy() - { - return new Vertex5(this); - } - - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "Vertex: (" + new BigDecimal(vec.x, cont) + ", " + new BigDecimal(vec.y, cont) + ", " + new BigDecimal(vec.z, cont) + ") " + - "(" + new BigDecimal(uv.u, cont) + ", " + new BigDecimal(uv.v, cont) + ") (" + uv.tex + ")"; - } - - public Vertex5 apply(Transformation t) - { - vec.apply(t); - return this; - } - - public Vertex5 apply(UVTransformation t) - { - uv.apply(t); - return this; - } -} diff --git a/src/main/java/codechicken/lib/render/uv/IconTransformation.java b/src/main/java/codechicken/lib/render/uv/IconTransformation.java deleted file mode 100644 index 357e5f52..00000000 --- a/src/main/java/codechicken/lib/render/uv/IconTransformation.java +++ /dev/null @@ -1,27 +0,0 @@ -package codechicken.lib.render.uv; - -import codechicken.lib.vec.IrreversibleTransformationException; -import net.minecraft.util.IIcon; - -public class IconTransformation extends UVTransformation -{ - public IIcon icon; - - public IconTransformation(IIcon icon) - { - this.icon = icon; - } - - @Override - public void apply(UV uv) - { - uv.u = icon.getInterpolatedU(uv.u * 16); - uv.v = icon.getInterpolatedV(uv.v * 16); - } - - @Override - public UVTransformation inverse() - { - throw new IrreversibleTransformationException(this); - } -} diff --git a/src/main/java/codechicken/lib/render/uv/MultiIconTransformation.java b/src/main/java/codechicken/lib/render/uv/MultiIconTransformation.java deleted file mode 100644 index 106aac98..00000000 --- a/src/main/java/codechicken/lib/render/uv/MultiIconTransformation.java +++ /dev/null @@ -1,28 +0,0 @@ -package codechicken.lib.render.uv; - -import codechicken.lib.vec.IrreversibleTransformationException; -import net.minecraft.util.IIcon; - -public class MultiIconTransformation extends UVTransformation -{ - public IIcon[] icons; - - public MultiIconTransformation(IIcon... icons) - { - this.icons = icons; - } - - @Override - public void apply(UV uv) - { - IIcon icon = icons[uv.tex % icons.length]; - uv.u = icon.getInterpolatedU(uv.u * 16); - uv.v = icon.getInterpolatedV(uv.v * 16); - } - - @Override - public UVTransformation inverse() - { - throw new IrreversibleTransformationException(this); - } -} diff --git a/src/main/java/codechicken/lib/render/uv/UV.java b/src/main/java/codechicken/lib/render/uv/UV.java deleted file mode 100644 index ddb02cf9..00000000 --- a/src/main/java/codechicken/lib/render/uv/UV.java +++ /dev/null @@ -1,95 +0,0 @@ -package codechicken.lib.render.uv; - -import codechicken.lib.util.Copyable; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class UV implements Copyable -{ - public double u; - public double v; - public int tex; - - public UV() - { - } - - public UV(double u, double v) - { - this(u, v, 0); - } - - public UV(double u, double v, int tex) - { - this.u = u; - this.v = v; - this.tex = tex; - } - - public UV(UV uv) - { - this(uv.u, uv.v, uv.tex); - } - - public UV set(double u, double v, int tex) - { - this.u = u; - this.v = v; - this.tex = tex; - return this; - } - - public UV set(double u, double v) - { - return set(u, v, tex); - } - - public UV set(UV uv) - { - return set(uv.u, uv.v, uv.tex); - } - - public UV copy() - { - return new UV(this); - } - - public UV add(UV uv) - { - u += uv.u; - v += uv.v; - return this; - } - - public UV multiply(double d) - { - u *= d; - v *= d; - return this; - } - - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "UV(" + new BigDecimal(u, cont) + ", " + new BigDecimal(v, cont) + ")"; - } - - public UV apply(UVTransformation t) - { - t.apply(this); - return this; - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof UV)) - { - return false; - } - UV uv = (UV) o; - return u == uv.u && v == uv.v; - } -} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/render/uv/UVRotation.java b/src/main/java/codechicken/lib/render/uv/UVRotation.java deleted file mode 100644 index e4b95bc6..00000000 --- a/src/main/java/codechicken/lib/render/uv/UVRotation.java +++ /dev/null @@ -1,60 +0,0 @@ -package codechicken.lib.render.uv; - -import codechicken.lib.math.MathHelper; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class UVRotation extends UVTransformation -{ - public double angle; - - /** - * @param angle The angle to rotate counterclockwise in radians - */ - public UVRotation(double angle) - { - this.angle = angle; - } - - @Override - public void apply(UV uv) - { - double c = MathHelper.cos(angle); - double s = MathHelper.sin(angle); - double u2 = c * uv.u + s * uv.v; - uv.v = -s * uv.u + c * uv.v; - uv.u = u2; - } - - @Override - public UVTransformation inverse() - { - return new UVRotation(-angle); - } - - @Override - public UVTransformation merge(UVTransformation next) - { - if (next instanceof UVRotation) - { - return new UVRotation(angle + ((UVRotation) next).angle); - } - - return null; - } - - @Override - public boolean isRedundant() - { - return MathHelper.between(-1E-5, angle, 1E-5); - } - - @Override - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "UVRotation(" + new BigDecimal(angle, cont) + ")"; - } -} diff --git a/src/main/java/codechicken/lib/render/uv/UVScale.java b/src/main/java/codechicken/lib/render/uv/UVScale.java deleted file mode 100644 index 6d16a095..00000000 --- a/src/main/java/codechicken/lib/render/uv/UVScale.java +++ /dev/null @@ -1,42 +0,0 @@ -package codechicken.lib.render.uv; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class UVScale extends UVTransformation -{ - double su; - double sv; - - public UVScale(double scaleu, double scalev) - { - su = scaleu; - sv = scalev; - } - - public UVScale(double d) - { - this(d, d); - } - - @Override - public void apply(UV uv) - { - uv.u *= su; - uv.v *= sv; - } - - @Override - public UVTransformation inverse() - { - return new UVScale(1 / su, 1 / sv); - } - - @Override - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "UVScale(" + new BigDecimal(su, cont) + ", " + new BigDecimal(sv, cont) + ")"; - } -} diff --git a/src/main/java/codechicken/lib/render/uv/UVTransformation.java b/src/main/java/codechicken/lib/render/uv/UVTransformation.java deleted file mode 100644 index befd8435..00000000 --- a/src/main/java/codechicken/lib/render/uv/UVTransformation.java +++ /dev/null @@ -1,42 +0,0 @@ -package codechicken.lib.render.uv; - -import codechicken.lib.render.CCRenderState; -import codechicken.lib.vec.ITransformation; - -/** - * Abstract supertype for any UV transformation - */ -public abstract class UVTransformation extends ITransformation implements CCRenderState.IVertexOperation -{ - public static final int operationIndex = CCRenderState.registerOperation(); - - public UVTransformation at(UV point) - { - return new UVTransformationList(new UVTranslation(-point.u, -point.v), this, new UVTranslation(point.u, point.v)); - } - - public UVTransformationList with(UVTransformation t) - { - return new UVTransformationList(this, t); - } - - @Override - public boolean load() - { - return !isRedundant(); - } - - @Override - public void operate() - { - apply(CCRenderState.vert.uv); - } - - @Override - public int operationID() - { - return operationIndex; - } -} - - diff --git a/src/main/java/codechicken/lib/render/uv/UVTransformationList.java b/src/main/java/codechicken/lib/render/uv/UVTransformationList.java deleted file mode 100644 index 2e04b1b7..00000000 --- a/src/main/java/codechicken/lib/render/uv/UVTransformationList.java +++ /dev/null @@ -1,133 +0,0 @@ -package codechicken.lib.render.uv; - -import java.util.ArrayList; -import java.util.Iterator; - -public class UVTransformationList extends UVTransformation -{ - private ArrayList transformations = new ArrayList(); - - public UVTransformationList(UVTransformation... transforms) - { - for (UVTransformation t : transforms) - if (t instanceof UVTransformationList) - { - transformations.addAll(((UVTransformationList) t).transformations); - } else - { - transformations.add(t); - } - - compact(); - } - - @Override - public void apply(UV uv) - { - for (int i = 0; i < transformations.size(); i++) - transformations.get(i).apply(uv); - } - - @Override - public UVTransformationList with(UVTransformation t) - { - if (t.isRedundant()) - { - return this; - } - - if (t instanceof UVTransformationList) - { - transformations.addAll(((UVTransformationList) t).transformations); - } else - { - transformations.add(t); - } - - compact(); - return this; - } - - public UVTransformationList prepend(UVTransformation t) - { - if (t.isRedundant()) - { - return this; - } - - if (t instanceof UVTransformationList) - { - transformations.addAll(0, ((UVTransformationList) t).transformations); - } else - { - transformations.add(0, t); - } - - compact(); - return this; - } - - private void compact() - { - ArrayList newList = new ArrayList(transformations.size()); - Iterator iterator = transformations.iterator(); - UVTransformation prev = null; - while (iterator.hasNext()) - { - UVTransformation t = iterator.next(); - if (t.isRedundant()) - { - continue; - } - - if (prev != null) - { - UVTransformation m = prev.merge(t); - if (m == null) - { - newList.add(prev); - } else if (m.isRedundant()) - { - t = null; - } else - { - t = m; - } - } - prev = t; - } - if (prev != null) - { - newList.add(prev); - } - - if (newList.size() < transformations.size()) - { - transformations = newList; - } - } - - @Override - public boolean isRedundant() - { - return transformations.size() == 0; - } - - @Override - public UVTransformation inverse() - { - UVTransformationList rev = new UVTransformationList(); - for (int i = transformations.size() - 1; i >= 0; i--) - rev.with(transformations.get(i).inverse()); - return rev; - } - - @Override - public String toString() - { - String s = ""; - for (UVTransformation t : transformations) - s += "\n" + t.toString(); - return s.trim(); - } -} diff --git a/src/main/java/codechicken/lib/render/uv/UVTranslation.java b/src/main/java/codechicken/lib/render/uv/UVTranslation.java deleted file mode 100644 index f4d0b3b9..00000000 --- a/src/main/java/codechicken/lib/render/uv/UVTranslation.java +++ /dev/null @@ -1,63 +0,0 @@ -package codechicken.lib.render.uv; - -import codechicken.lib.math.MathHelper; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class UVTranslation extends UVTransformation -{ - public double du; - public double dv; - - public UVTranslation(double u, double v) - { - du = u; - dv = v; - } - - @Override - public void apply(UV uv) - { - uv.u += du; - uv.v += dv; - } - - @Override - public UVTransformation at(UV point) - { - return this; - } - - @Override - public UVTransformation inverse() - { - return new UVTranslation(-du, -dv); - } - - @Override - public UVTransformation merge(UVTransformation next) - { - if (next instanceof UVTranslation) - { - UVTranslation t = (UVTranslation) next; - return new UVTranslation(du + t.du, dv + t.dv); - } - - return null; - } - - @Override - public boolean isRedundant() - { - return MathHelper.between(-1E-5, du, 1E-5) && MathHelper.between(-1E-5, dv, 1E-5); - } - - @Override - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "UVTranslation(" + new BigDecimal(du, cont) + ", " + new BigDecimal(dv, cont) + ")"; - } -} diff --git a/src/main/java/codechicken/lib/util/Copyable.java b/src/main/java/codechicken/lib/util/Copyable.java deleted file mode 100644 index 57be8301..00000000 --- a/src/main/java/codechicken/lib/util/Copyable.java +++ /dev/null @@ -1,6 +0,0 @@ -package codechicken.lib.util; - -public interface Copyable -{ - public T copy(); -} diff --git a/src/main/java/codechicken/lib/util/LangProxy.java b/src/main/java/codechicken/lib/util/LangProxy.java deleted file mode 100644 index 9282bd9d..00000000 --- a/src/main/java/codechicken/lib/util/LangProxy.java +++ /dev/null @@ -1,23 +0,0 @@ -package codechicken.lib.util; - -import net.minecraft.util.StatCollector; - -public class LangProxy -{ - public final String namespace; - - public LangProxy(String namespace) - { - this.namespace = namespace + "."; - } - - public String translate(String key) - { - return StatCollector.translateToLocal(namespace + key); - } - - public String format(String key, Object... params) - { - return StatCollector.translateToLocalFormatted(namespace + key, params); - } -} diff --git a/src/main/java/codechicken/lib/vec/AxisCycle.java b/src/main/java/codechicken/lib/vec/AxisCycle.java deleted file mode 100644 index 1ea4e2d5..00000000 --- a/src/main/java/codechicken/lib/vec/AxisCycle.java +++ /dev/null @@ -1,45 +0,0 @@ -package codechicken.lib.vec; - -public class AxisCycle -{ - public static Transformation[] cycles = new Transformation[]{ - new RedundantTransformation(), - new VariableTransformation(new Matrix4(0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - double d0 = vec.x; - double d1 = vec.y; - double d2 = vec.z; - vec.x = d2; - vec.y = d0; - vec.z = d1; - } - - @Override - public Transformation inverse() - { - return cycles[2]; - } - }, - new VariableTransformation(new Matrix4(0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - double d0 = vec.x; - double d1 = vec.y; - double d2 = vec.z; - vec.x = d1; - vec.y = d2; - vec.z = d0; - } - - @Override - public Transformation inverse() - { - return cycles[1]; - } - }}; -} diff --git a/src/main/java/codechicken/lib/vec/BlockCoord.java b/src/main/java/codechicken/lib/vec/BlockCoord.java deleted file mode 100644 index b032ba92..00000000 --- a/src/main/java/codechicken/lib/vec/BlockCoord.java +++ /dev/null @@ -1,256 +0,0 @@ -package codechicken.lib.vec; - -import codechicken.lib.math.MathHelper; -import codechicken.lib.util.Copyable; -import net.minecraft.tileentity.TileEntity; - -public class BlockCoord implements Comparable, Copyable -{ - public static final BlockCoord[] sideOffsets = new BlockCoord[]{ - new BlockCoord(0, -1, 0), - new BlockCoord(0, 1, 0), - new BlockCoord(0, 0, -1), - new BlockCoord(0, 0, 1), - new BlockCoord(-1, 0, 0), - new BlockCoord(1, 0, 0)}; - public int x; - public int y; - public int z; - - public BlockCoord(int x, int y, int z) - { - this.x = x; - this.y = y; - this.z = z; - } - - public BlockCoord(Vector3 v) - { - this(MathHelper.floor_double(v.x), MathHelper.floor_double(v.y), MathHelper.floor_double(v.z)); - } - - public BlockCoord(TileEntity tile) - { - this(tile.xCoord, tile.yCoord, tile.zCoord); - } - - public BlockCoord(int[] ia) - { - this(ia[0], ia[1], ia[2]); - } - - public BlockCoord() - { - } - - public static BlockCoord fromAxes(int[] ia) - { - return new BlockCoord(ia[2], ia[0], ia[1]); - } - - @Override - public boolean equals(Object obj) - { - if (!(obj instanceof BlockCoord)) - { - return false; - } - BlockCoord o2 = (BlockCoord) obj; - return x == o2.x && y == o2.y && z == o2.z; - } - - @Override - public int hashCode() - { - return (x ^ z) * 31 + y; - } - - public int compareTo(BlockCoord o) - { - if (x != o.x) return x < o.x ? 1 : -1; - if (y != o.y) return y < o.y ? 1 : -1; - if (z != o.z) return z < o.z ? 1 : -1; - return 0; - } - - public Vector3 toVector3Centered() - { - return new Vector3(x + 0.5, y + 0.5, z + 0.5); - } - - public BlockCoord multiply(int i) - { - x *= i; - y *= i; - z *= i; - return this; - } - - public double mag() - { - return Math.sqrt(x * x + y * y + z * z); - } - - public int mag2() - { - return x * x + y * y + z * z; - } - - public boolean isZero() - { - return x == 0 && y == 0 && z == 0; - } - - public boolean isAxial() - { - return x == 0 ? (y == 0 || z == 0) : (y == 0 && z == 0); - } - - public BlockCoord add(BlockCoord coord2) - { - x += coord2.x; - y += coord2.y; - z += coord2.z; - return this; - } - - public BlockCoord add(int i, int j, int k) - { - x += i; - y += j; - z += k; - return this; - } - - public BlockCoord sub(BlockCoord coord2) - { - x -= coord2.x; - y -= coord2.y; - z -= coord2.z; - return this; - } - - public BlockCoord sub(int i, int j, int k) - { - x -= i; - y -= j; - z -= k; - return this; - } - - public BlockCoord offset(int side) - { - return offset(side, 1); - } - - public BlockCoord offset(int side, int amount) - { - BlockCoord offset = sideOffsets[side]; - x += offset.x * amount; - y += offset.y * amount; - z += offset.z * amount; - return this; - } - - public BlockCoord inset(int side) - { - return inset(side, 1); - } - - public BlockCoord inset(int side, int amount) - { - return offset(side, -amount); - } - - public int getSide(int side) - { - switch (side) - { - case 0: - case 1: - return y; - case 2: - case 3: - return z; - case 4: - case 5: - return x; - } - throw new IndexOutOfBoundsException("Switch Falloff"); - } - - public BlockCoord setSide(int s, int v) - { - switch (s) - { - case 0: - case 1: - y = v; - break; - case 2: - case 3: - z = v; - break; - case 4: - case 5: - x = v; - break; - default: - throw new IndexOutOfBoundsException("Switch Falloff"); - } - return this; - } - - public int[] intArray() - { - return new int[]{x, y, z}; - } - - public BlockCoord copy() - { - return new BlockCoord(x, y, z); - } - - public BlockCoord set(int i, int j, int k) - { - x = i; - y = j; - z = k; - return this; - } - - public BlockCoord set(BlockCoord coord) - { - return set(coord.x, coord.y, coord.z); - } - - public BlockCoord set(int[] ia) - { - return set(ia[0], ia[1], ia[2]); - } - - public int toSide() - { - if (!isAxial()) return -1; - if (y < 0) return 0; - if (y > 0) return 1; - if (z < 0) return 2; - if (z > 0) return 3; - if (x < 0) return 4; - if (x > 0) return 5; - - return -1; - } - - public int absSum() - { - return (x < 0 ? -x : x) + - (y < 0 ? -y : y) + - (z < 0 ? -z : z); - } - - public String toString() - { - return "(" + x + ", " + y + ", " + z + ")"; - } -} diff --git a/src/main/java/codechicken/lib/vec/Cuboid6.java b/src/main/java/codechicken/lib/vec/Cuboid6.java deleted file mode 100644 index 0f1988e1..00000000 --- a/src/main/java/codechicken/lib/vec/Cuboid6.java +++ /dev/null @@ -1,231 +0,0 @@ -package codechicken.lib.vec; - -import codechicken.lib.util.Copyable; -import net.minecraft.block.Block; -import net.minecraft.util.AxisAlignedBB; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class Cuboid6 implements Copyable -{ - public static Cuboid6 full = new Cuboid6(0, 0, 0, 1, 1, 1); - - public Vector3 min; - public Vector3 max; - - public Cuboid6(Vector3 min, Vector3 max) - { - this.min = min; - this.max = max; - } - - public Cuboid6(AxisAlignedBB aabb) - { - min = new Vector3(aabb.minX, aabb.minY, aabb.minZ); - max = new Vector3(aabb.maxX, aabb.maxY, aabb.maxZ); - } - - public Cuboid6(Cuboid6 cuboid) - { - min = cuboid.min.copy(); - max = cuboid.max.copy(); - } - - public Cuboid6(double minx, double miny, double minz, double maxx, double maxy, double maxz) - { - min = new Vector3(minx, miny, minz); - max = new Vector3(maxx, maxy, maxz); - } - - public static boolean intersects(Cuboid6 a, Cuboid6 b) - { - return a != null && b != null && a.intersects(b); - } - - public AxisAlignedBB toAABB() - { - return AxisAlignedBB.getBoundingBox(min.x, min.y, min.z, max.x, max.y, max.z); - } - - public Cuboid6 copy() - { - return new Cuboid6(this); - } - - public Cuboid6 set(Cuboid6 c) - { - return set(c.min, c.max); - } - - public Cuboid6 set(Vector3 min, Vector3 max) - { - this.min.set(min); - this.max.set(max); - return this; - } - - public Cuboid6 set(double minx, double miny, double minz, double maxx, double maxy, double maxz) - { - min.set(minx, miny, minz); - max.set(maxx, maxy, maxz); - return this; - } - - public Cuboid6 add(Vector3 vec) - { - min.add(vec); - max.add(vec); - return this; - } - - public Cuboid6 sub(Vector3 vec) - { - min.subtract(vec); - max.subtract(vec); - return this; - } - - public Cuboid6 expand(double d) - { - return expand(new Vector3(d, d, d)); - } - - public Cuboid6 expand(Vector3 vec) - { - min.sub(vec); - max.add(vec); - return this; - } - - public void setBlockBounds(Block block) - { - block.setBlockBounds((float) min.x, (float) min.y, (float) min.z, (float) max.x, (float) max.y, (float) max.z); - } - - public boolean intersects(Cuboid6 b) - { - return max.x - 1E-5 > b.min.x && - b.max.x - 1E-5 > min.x && - max.y - 1E-5 > b.min.y && - b.max.y - 1E-5 > min.y && - max.z - 1E-5 > b.min.z && - b.max.z - 1E-5 > min.z; - } - - public Cuboid6 offset(Cuboid6 o) - { - min.add(o.min); - max.add(o.max); - return this; - } - - public Vector3 center() - { - return min.copy().add(max).multiply(0.5); - } - - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "Cuboid: (" + new BigDecimal(min.x, cont) + ", " + new BigDecimal(min.y, cont) + ", " + new BigDecimal(min.z, cont) + ") -> (" + - new BigDecimal(max.x, cont) + ", " + new BigDecimal(max.y, cont) + ", " + new BigDecimal(max.z, cont) + ")"; - } - - public Cuboid6 enclose(Vector3 vec) - { - if (min.x > vec.x) min.x = vec.x; - if (min.y > vec.y) min.y = vec.y; - if (min.z > vec.z) min.z = vec.z; - if (max.x < vec.x) max.x = vec.x; - if (max.y < vec.y) max.y = vec.y; - if (max.z < vec.z) max.z = vec.z; - return this; - } - - public Cuboid6 enclose(Cuboid6 c) - { - if (min.x > c.min.x) min.x = c.min.x; - if (min.y > c.min.y) min.y = c.min.y; - if (min.z > c.min.z) min.z = c.min.z; - if (max.x < c.max.x) max.x = c.max.x; - if (max.y < c.max.y) max.y = c.max.y; - if (max.z < c.max.z) max.z = c.max.z; - return this; - } - - public Cuboid6 apply(Transformation t) - { - t.apply(min); - t.apply(max); - double temp; - if (min.x > max.x) - { - temp = min.x; - min.x = max.x; - max.x = temp; - } - if (min.y > max.y) - { - temp = min.y; - min.y = max.y; - max.y = temp; - } - if (min.z > max.z) - { - temp = min.z; - min.z = max.z; - max.z = temp; - } - return this; - } - - public double getSide(int s) - { - switch (s) - { - case 0: - return min.y; - case 1: - return max.y; - case 2: - return min.z; - case 3: - return max.z; - case 4: - return min.x; - case 5: - return max.x; - } - throw new IndexOutOfBoundsException("Switch Falloff"); - } - - public Cuboid6 setSide(int s, double d) - { - switch (s) - { - case 0: - min.y = d; - break; - case 1: - max.y = d; - break; - case 2: - min.z = d; - break; - case 3: - max.z = d; - break; - case 4: - min.x = d; - break; - case 5: - max.x = d; - break; - default: - throw new IndexOutOfBoundsException("Switch Falloff"); - } - return this; - } -} diff --git a/src/main/java/codechicken/lib/vec/CuboidCoord.java b/src/main/java/codechicken/lib/vec/CuboidCoord.java deleted file mode 100644 index 8f4ad777..00000000 --- a/src/main/java/codechicken/lib/vec/CuboidCoord.java +++ /dev/null @@ -1,268 +0,0 @@ -package codechicken.lib.vec; - -import codechicken.lib.util.Copyable; -import net.minecraft.util.AxisAlignedBB; - -import java.util.Iterator; - -public class CuboidCoord implements Iterable, Copyable -{ - public BlockCoord min; - public BlockCoord max; - - public CuboidCoord() - { - min = new BlockCoord(); - max = new BlockCoord(); - } - - public CuboidCoord(BlockCoord min, BlockCoord max) - { - this.min = min; - this.max = max; - } - - public CuboidCoord(BlockCoord coord) - { - this(coord, coord.copy()); - } - - public CuboidCoord(int[] ia) - { - this(ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]); - } - - public CuboidCoord(int x1, int y1, int z1, int x2, int y2, int z2) - { - this(new BlockCoord(x1, y1, z1), new BlockCoord(x2, y2, z2)); - } - - public CuboidCoord expand(int amount) - { - return expand(amount, amount, amount); - } - - public CuboidCoord expand(int x, int y, int z) - { - max.add(x, y, z); - min.sub(x, y, z); - return this; - } - - public CuboidCoord expand(int side, int amount) - { - if (side % 2 == 0)//negative side - { - min = min.offset(side, amount); - } else - { - max = max.offset(side, amount); - } - return this; - } - - public int size(int s) - { - switch (s) - { - case 0: - case 1: - return max.y - min.y + 1; - case 2: - case 3: - return max.z - min.z + 1; - case 4: - case 5: - return max.x - min.x + 1; - default: - return 0; - } - } - - public int getSide(int s) - { - switch (s) - { - case 0: - return min.y; - case 1: - return max.y; - case 2: - return min.z; - case 3: - return max.z; - case 4: - return min.x; - case 5: - return max.x; - } - throw new IndexOutOfBoundsException("Switch Falloff"); - } - - public CuboidCoord setSide(int s, int v) - { - switch (s) - { - case 0: - min.y = v; - break; - case 1: - max.y = v; - break; - case 2: - min.z = v; - break; - case 3: - max.z = v; - break; - case 4: - min.x = v; - break; - case 5: - max.x = v; - break; - default: - throw new IndexOutOfBoundsException("Switch Falloff"); - } - return this; - } - - public int getVolume() - { - return (max.x - min.x + 1) * (max.y - min.y + 1) * (max.z - min.z + 1); - } - - public Vector3 getCenterVec() - { - return new Vector3(min.x + (max.x - min.x + 1) / 2D, min.y + (max.y - min.y + 1) / 2D, min.z + (max.z - min.z + 1) / 2D); - } - - public BlockCoord getCenter(BlockCoord store) - { - store.set(min.x + (max.x - min.x) / 2, min.y + (max.y - min.y) / 2, min.z + (max.z - min.z) / 2); - return store; - } - - public boolean contains(BlockCoord coord) - { - return contains(coord.x, coord.y, coord.z); - } - - public boolean contains(int x, int y, int z) - { - return x >= min.x && x <= max.x - && y >= min.y && y <= max.y - && z >= min.z && z <= max.z; - } - - public int[] intArray() - { - return new int[]{min.x, min.y, min.z, max.x, max.y, max.z}; - } - - public CuboidCoord copy() - { - return new CuboidCoord(min.copy(), max.copy()); - } - - public Cuboid6 bounds() - { - return new Cuboid6(min.x, min.y, min.z, max.x + 1, max.y + 1, max.z + 1); - } - - public AxisAlignedBB toAABB() - { - return bounds().toAABB(); - } - - public void set(BlockCoord min, BlockCoord max) - { - this.min.set(min); - this.max.set(max); - } - - public CuboidCoord set(int x1, int y1, int z1, int x2, int y2, int z2) - { - min.set(x1, y1, z1); - max.set(x2, y2, z2); - return this; - } - - public CuboidCoord set(BlockCoord coord) - { - min.set(coord); - max.set(coord); - return this; - } - - public CuboidCoord set(int[] ia) - { - return set(ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]); - } - - public CuboidCoord include(BlockCoord coord) - { - return include(coord.x, coord.y, coord.z); - } - - public CuboidCoord include(int x, int y, int z) - { - if (x < min.x) - { - min.x = x; - } else if (x > max.x) max.x = x; - if (y < min.y) - { - min.y = y; - } else if (y > max.y) max.y = y; - if (z < min.z) - { - min.z = z; - } else if (z > max.z) max.z = z; - return this; - } - - public Iterator iterator() - { - return new Iterator() - { - BlockCoord b = null; - - public boolean hasNext() - { - return b == null || !b.equals(max); - } - - public BlockCoord next() - { - if (b == null) - { - b = min.copy(); - } else - { - if (b.z != max.z) - { - b.z++; - } else - { - b.z = min.z; - if (b.y != max.y) - { - b.y++; - } else - { - b.y = min.y; - b.x++; - } - } - } - return b.copy(); - } - - public void remove() - { - throw new UnsupportedOperationException(); - } - }; - } -} diff --git a/src/main/java/codechicken/lib/vec/ITransformation.java b/src/main/java/codechicken/lib/vec/ITransformation.java deleted file mode 100644 index 68bc99ec..00000000 --- a/src/main/java/codechicken/lib/vec/ITransformation.java +++ /dev/null @@ -1,53 +0,0 @@ -package codechicken.lib.vec; - -/** - * Abstract supertype for any VectorN transformation - * - * @param The vector type - * @param The transformation type - */ -public abstract class ITransformation -{ - /** - * Applies this transformation to vec - */ - public abstract void apply(Vector vec); - - /** - * @param point The point to apply this transformation around - * @return Wraps this transformation in a translation to point and then back from point - */ - public abstract Transformation at(Vector point); - - /** - * Creates a TransformationList composed of this transformation followed by t - * If this is a TransformationList, the transformation will be appended and this returned - */ - public abstract Transformation with(Transformation t); - - /** - * Returns a simplified transformation that performs this, followed by next. If such a transformation does not exist, returns null - */ - public Transformation merge(Transformation next) - { - return null; - } - - /** - * Returns true if this transformation is redundant, eg. Scale(1, 1, 1), Translation(0, 0, 0) or Rotation(0, a, b, c) - */ - public boolean isRedundant() - { - return false; - } - - public abstract Transformation inverse(); - - /** - * Scala ++ operator - */ - public Transformation $plus$plus(Transformation t) - { - return with(t); - } -} diff --git a/src/main/java/codechicken/lib/vec/IrreversibleTransformationException.java b/src/main/java/codechicken/lib/vec/IrreversibleTransformationException.java deleted file mode 100644 index dfe49013..00000000 --- a/src/main/java/codechicken/lib/vec/IrreversibleTransformationException.java +++ /dev/null @@ -1,18 +0,0 @@ -package codechicken.lib.vec; - -@SuppressWarnings("serial") -public class IrreversibleTransformationException extends RuntimeException -{ - public ITransformation t; - - public IrreversibleTransformationException(ITransformation t) - { - this.t = t; - } - - @Override - public String getMessage() - { - return "The following transformation is irreversible:\n" + t; - } -} diff --git a/src/main/java/codechicken/lib/vec/Line3.java b/src/main/java/codechicken/lib/vec/Line3.java deleted file mode 100644 index abfb45ed..00000000 --- a/src/main/java/codechicken/lib/vec/Line3.java +++ /dev/null @@ -1,51 +0,0 @@ -package codechicken.lib.vec; - - -public class Line3 -{ - public static final double tol = 0.0001D; - - public Vector3 pt1; - public Vector3 pt2; - - public Line3(Vector3 pt1, Vector3 pt2) - { - this.pt1 = pt1; - this.pt2 = pt2; - } - - public Line3() - { - this(new Vector3(), new Vector3()); - } - - public static boolean intersection2D(Line3 line1, Line3 line2, Vector3 store) - { - // calculate differences - double xD1 = line1.pt2.x - line1.pt1.x; - double zD1 = line1.pt2.z - line1.pt1.z; - double xD2 = line2.pt2.x - line2.pt1.x; - double zD2 = line2.pt2.z - line2.pt1.z; - - double xD3 = line1.pt1.x - line2.pt1.x; - double zD3 = line1.pt1.z - line2.pt1.z; - - double div = zD2 * xD1 - xD2 * zD1; - if (div == 0)//lines are parallel - { - return false; - } - double ua = (xD2 * zD3 - zD2 * xD3) / div; - store.set(line1.pt1.x + ua * xD1, 0, line1.pt1.z + ua * zD1); - - if (store.x >= Math.min(line1.pt1.x, line1.pt2.x) - tol && store.x >= Math.min(line2.pt1.x, line2.pt2.x) - tol - && store.z >= Math.min(line1.pt1.z, line1.pt2.z) - tol && store.z >= Math.min(line2.pt1.z, line2.pt2.z) - tol - && store.x <= Math.max(line1.pt1.x, line1.pt2.x) + tol && store.x <= Math.max(line2.pt1.x, line2.pt2.x) + tol - && store.z <= Math.max(line1.pt1.z, line1.pt2.z) + tol && store.z <= Math.max(line2.pt1.z, line2.pt2.z) + tol) - { - return true; - } - - return false; - } -} diff --git a/src/main/java/codechicken/lib/vec/Matrix4.java b/src/main/java/codechicken/lib/vec/Matrix4.java deleted file mode 100644 index a6ad9a1b..00000000 --- a/src/main/java/codechicken/lib/vec/Matrix4.java +++ /dev/null @@ -1,353 +0,0 @@ -package codechicken.lib.vec; - -import codechicken.lib.util.Copyable; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import org.lwjgl.opengl.GL11; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.DoubleBuffer; - -public class Matrix4 extends Transformation implements Copyable -{ - private static DoubleBuffer glBuf = ByteBuffer.allocateDirect(16 * 8).order(ByteOrder.nativeOrder()).asDoubleBuffer(); - - //m - public double m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33; - - public Matrix4() - { - m00 = m11 = m22 = m33 = 1; - } - - public Matrix4(double d00, double d01, double d02, double d03, - double d10, double d11, double d12, double d13, - double d20, double d21, double d22, double d23, - double d30, double d31, double d32, double d33) - { - m00 = d00; - m01 = d01; - m02 = d02; - m03 = d03; - m10 = d10; - m11 = d11; - m12 = d12; - m13 = d13; - m20 = d20; - m21 = d21; - m22 = d22; - m23 = d23; - m30 = d30; - m31 = d31; - m32 = d32; - m33 = d33; - } - - public Matrix4(Matrix4 mat) - { - set(mat); - } - - public Matrix4 setIdentity() - { - m00 = m11 = m22 = m33 = 1; - m01 = m02 = m03 = m10 = m12 = m13 = m20 = m21 = m23 = m30 = m31 = m32 = 0; - - return this; - } - - public Matrix4 translate(Vector3 vec) - { - m03 += m00 * vec.x + m01 * vec.y + m02 * vec.z; - m13 += m10 * vec.x + m11 * vec.y + m12 * vec.z; - m23 += m20 * vec.x + m21 * vec.y + m22 * vec.z; - m33 += m30 * vec.x + m31 * vec.y + m32 * vec.z; - - return this; - } - - public Matrix4 scale(Vector3 vec) - { - m00 *= vec.x; - m10 *= vec.x; - m20 *= vec.x; - m30 *= vec.x; - m01 *= vec.y; - m11 *= vec.y; - m21 *= vec.y; - m31 *= vec.y; - m02 *= vec.z; - m12 *= vec.z; - m22 *= vec.z; - m32 *= vec.z; - - return this; - } - - public Matrix4 rotate(double angle, Vector3 axis) - { - double c = Math.cos(angle); - double s = Math.sin(angle); - double mc = 1.0f - c; - double xy = axis.x * axis.y; - double yz = axis.y * axis.z; - double xz = axis.x * axis.z; - double xs = axis.x * s; - double ys = axis.y * s; - double zs = axis.z * s; - - double f00 = axis.x * axis.x * mc + c; - double f10 = xy * mc + zs; - double f20 = xz * mc - ys; - - double f01 = xy * mc - zs; - double f11 = axis.y * axis.y * mc + c; - double f21 = yz * mc + xs; - - double f02 = xz * mc + ys; - double f12 = yz * mc - xs; - double f22 = axis.z * axis.z * mc + c; - - double t00 = m00 * f00 + m01 * f10 + m02 * f20; - double t10 = m10 * f00 + m11 * f10 + m12 * f20; - double t20 = m20 * f00 + m21 * f10 + m22 * f20; - double t30 = m30 * f00 + m31 * f10 + m32 * f20; - double t01 = m00 * f01 + m01 * f11 + m02 * f21; - double t11 = m10 * f01 + m11 * f11 + m12 * f21; - double t21 = m20 * f01 + m21 * f11 + m22 * f21; - double t31 = m30 * f01 + m31 * f11 + m32 * f21; - m02 = m00 * f02 + m01 * f12 + m02 * f22; - m12 = m10 * f02 + m11 * f12 + m12 * f22; - m22 = m20 * f02 + m21 * f12 + m22 * f22; - m32 = m30 * f02 + m31 * f12 + m32 * f22; - m00 = t00; - m10 = t10; - m20 = t20; - m30 = t30; - m01 = t01; - m11 = t11; - m21 = t21; - m31 = t31; - - return this; - } - - public Matrix4 rotate(Rotation rotation) - { - rotation.apply(this); - return this; - } - - public Matrix4 leftMultiply(Matrix4 mat) - { - double n00 = m00 * mat.m00 + m10 * mat.m01 + m20 * mat.m02 + m30 * mat.m03; - double n01 = m01 * mat.m00 + m11 * mat.m01 + m21 * mat.m02 + m31 * mat.m03; - double n02 = m02 * mat.m00 + m12 * mat.m01 + m22 * mat.m02 + m32 * mat.m03; - double n03 = m03 * mat.m00 + m13 * mat.m01 + m23 * mat.m02 + m33 * mat.m03; - double n10 = m00 * mat.m10 + m10 * mat.m11 + m20 * mat.m12 + m30 * mat.m13; - double n11 = m01 * mat.m10 + m11 * mat.m11 + m21 * mat.m12 + m31 * mat.m13; - double n12 = m02 * mat.m10 + m12 * mat.m11 + m22 * mat.m12 + m32 * mat.m13; - double n13 = m03 * mat.m10 + m13 * mat.m11 + m23 * mat.m12 + m33 * mat.m13; - double n20 = m00 * mat.m20 + m10 * mat.m21 + m20 * mat.m22 + m30 * mat.m23; - double n21 = m01 * mat.m20 + m11 * mat.m21 + m21 * mat.m22 + m31 * mat.m23; - double n22 = m02 * mat.m20 + m12 * mat.m21 + m22 * mat.m22 + m32 * mat.m23; - double n23 = m03 * mat.m20 + m13 * mat.m21 + m23 * mat.m22 + m33 * mat.m23; - double n30 = m00 * mat.m30 + m10 * mat.m31 + m20 * mat.m32 + m30 * mat.m33; - double n31 = m01 * mat.m30 + m11 * mat.m31 + m21 * mat.m32 + m31 * mat.m33; - double n32 = m02 * mat.m30 + m12 * mat.m31 + m22 * mat.m32 + m32 * mat.m33; - double n33 = m03 * mat.m30 + m13 * mat.m31 + m23 * mat.m32 + m33 * mat.m33; - - m00 = n00; - m01 = n01; - m02 = n02; - m03 = n03; - m10 = n10; - m11 = n11; - m12 = n12; - m13 = n13; - m20 = n20; - m21 = n21; - m22 = n22; - m23 = n23; - m30 = n30; - m31 = n31; - m32 = n32; - m33 = n33; - - return this; - } - - public Matrix4 multiply(Matrix4 mat) - { - double n00 = m00 * mat.m00 + m01 * mat.m10 + m02 * mat.m20 + m03 * mat.m30; - double n01 = m00 * mat.m01 + m01 * mat.m11 + m02 * mat.m21 + m03 * mat.m31; - double n02 = m00 * mat.m02 + m01 * mat.m12 + m02 * mat.m22 + m03 * mat.m32; - double n03 = m00 * mat.m03 + m01 * mat.m13 + m02 * mat.m23 + m03 * mat.m33; - double n10 = m10 * mat.m00 + m11 * mat.m10 + m12 * mat.m20 + m13 * mat.m30; - double n11 = m10 * mat.m01 + m11 * mat.m11 + m12 * mat.m21 + m13 * mat.m31; - double n12 = m10 * mat.m02 + m11 * mat.m12 + m12 * mat.m22 + m13 * mat.m32; - double n13 = m10 * mat.m03 + m11 * mat.m13 + m12 * mat.m23 + m13 * mat.m33; - double n20 = m20 * mat.m00 + m21 * mat.m10 + m22 * mat.m20 + m23 * mat.m30; - double n21 = m20 * mat.m01 + m21 * mat.m11 + m22 * mat.m21 + m23 * mat.m31; - double n22 = m20 * mat.m02 + m21 * mat.m12 + m22 * mat.m22 + m23 * mat.m32; - double n23 = m20 * mat.m03 + m21 * mat.m13 + m22 * mat.m23 + m23 * mat.m33; - double n30 = m30 * mat.m00 + m31 * mat.m10 + m32 * mat.m20 + m33 * mat.m30; - double n31 = m30 * mat.m01 + m31 * mat.m11 + m32 * mat.m21 + m33 * mat.m31; - double n32 = m30 * mat.m02 + m31 * mat.m12 + m32 * mat.m22 + m33 * mat.m32; - double n33 = m30 * mat.m03 + m31 * mat.m13 + m32 * mat.m23 + m33 * mat.m33; - - m00 = n00; - m01 = n01; - m02 = n02; - m03 = n03; - m10 = n10; - m11 = n11; - m12 = n12; - m13 = n13; - m20 = n20; - m21 = n21; - m22 = n22; - m23 = n23; - m30 = n30; - m31 = n31; - m32 = n32; - m33 = n33; - - return this; - } - - public Matrix4 transpose() - { - double n00 = m00; - double n10 = m01; - double n20 = m02; - double n30 = m03; - double n01 = m10; - double n11 = m11; - double n21 = m12; - double n31 = m13; - double n02 = m20; - double n12 = m21; - double n22 = m22; - double n32 = m23; - double n03 = m30; - double n13 = m31; - double n23 = m32; - double n33 = m33; - - m00 = n00; - m01 = n01; - m02 = n02; - m03 = n03; - m10 = n10; - m11 = n11; - m12 = n12; - m13 = n13; - m20 = n20; - m21 = n21; - m22 = n22; - m23 = n23; - m30 = n30; - m31 = n31; - m32 = n32; - m33 = n33; - - return this; - } - - public Matrix4 copy() - { - return new Matrix4(this); - } - - public Matrix4 set(Matrix4 mat) - { - m00 = mat.m00; - m01 = mat.m01; - m02 = mat.m02; - m03 = mat.m03; - m10 = mat.m10; - m11 = mat.m11; - m12 = mat.m12; - m13 = mat.m13; - m20 = mat.m20; - m21 = mat.m21; - m22 = mat.m22; - m23 = mat.m23; - m30 = mat.m30; - m31 = mat.m31; - m32 = mat.m32; - m33 = mat.m33; - - return this; - } - - @Override - public void apply(Matrix4 mat) - { - mat.multiply(this); - } - - private void mult3x3(Vector3 vec) - { - double x = m00 * vec.x + m01 * vec.y + m02 * vec.z; - double y = m10 * vec.x + m11 * vec.y + m12 * vec.z; - double z = m20 * vec.x + m21 * vec.y + m22 * vec.z; - - vec.x = x; - vec.y = y; - vec.z = z; - } - - @Override - public void apply(Vector3 vec) - { - mult3x3(vec); - vec.add(m03, m13, m23); - } - - @Override - public void applyN(Vector3 vec) - { - mult3x3(vec); - vec.normalize(); - } - - @Override - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "[" + new BigDecimal(m00, cont) + "," + new BigDecimal(m01, cont) + "," + new BigDecimal(m02, cont) + "," + new BigDecimal(m03, cont) + "]\n" + - "[" + new BigDecimal(m10, cont) + "," + new BigDecimal(m11, cont) + "," + new BigDecimal(m12, cont) + "," + new BigDecimal(m13, cont) + "]\n" + - "[" + new BigDecimal(m20, cont) + "," + new BigDecimal(m21, cont) + "," + new BigDecimal(m22, cont) + "," + new BigDecimal(m23, cont) + "]\n" + - "[" + new BigDecimal(m30, cont) + "," + new BigDecimal(m31, cont) + "," + new BigDecimal(m32, cont) + "," + new BigDecimal(m33, cont) + "]"; - } - - public Matrix4 apply(Transformation t) - { - t.apply(this); - return this; - } - - @Override - @SideOnly(Side.CLIENT) - public void glApply() - { - glBuf.put(m00).put(m10).put(m20).put(m30) - .put(m01).put(m11).put(m21).put(m31) - .put(m02).put(m12).put(m22).put(m32) - .put(m03).put(m13).put(m23).put(m33); - glBuf.flip(); - GL11.glMultMatrix(glBuf); - } - - @Override - public Transformation inverse() - { - throw new IrreversibleTransformationException(this);//Don't waste your cpu with matrix inverses - } -} diff --git a/src/main/java/codechicken/lib/vec/Quat.java b/src/main/java/codechicken/lib/vec/Quat.java deleted file mode 100644 index 52c1049d..00000000 --- a/src/main/java/codechicken/lib/vec/Quat.java +++ /dev/null @@ -1,157 +0,0 @@ -package codechicken.lib.vec; - -import codechicken.lib.math.MathHelper; -import codechicken.lib.util.Copyable; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class Quat implements Copyable -{ - public double x; - public double y; - public double z; - public double s; - - public Quat() - { - s = 1; - x = 0; - y = 0; - z = 0; - } - - public Quat(Quat quat) - { - x = quat.x; - y = quat.y; - z = quat.z; - s = quat.s; - } - - public Quat(double d, double d1, double d2, double d3) - { - x = d1; - y = d2; - z = d3; - s = d; - } - - public static Quat aroundAxis(double ax, double ay, double az, double angle) - { - return new Quat().setAroundAxis(ax, ay, az, angle); - } - - public static Quat aroundAxis(Vector3 axis, double angle) - { - return aroundAxis(axis.x, axis.y, axis.z, angle); - } - - public Quat set(Quat quat) - { - x = quat.x; - y = quat.y; - z = quat.z; - s = quat.s; - - return this; - } - - public Quat set(double d, double d1, double d2, double d3) - { - x = d1; - y = d2; - z = d3; - s = d; - - return this; - } - - public Quat setAroundAxis(double ax, double ay, double az, double angle) - { - angle *= 0.5; - double d4 = MathHelper.sin(angle); - return set(MathHelper.cos(angle), ax * d4, ay * d4, az * d4); - } - - public Quat setAroundAxis(Vector3 axis, double angle) - { - return setAroundAxis(axis.x, axis.y, axis.z, angle); - } - - public Quat multiply(Quat quat) - { - double d = s * quat.s - x * quat.x - y * quat.y - z * quat.z; - double d1 = s * quat.x + x * quat.s - y * quat.z + z * quat.y; - double d2 = s * quat.y + x * quat.z + y * quat.s - z * quat.x; - double d3 = s * quat.z - x * quat.y + y * quat.x + z * quat.s; - s = d; - x = d1; - y = d2; - z = d3; - - return this; - } - - public Quat rightMultiply(Quat quat) - { - double d = s * quat.s - x * quat.x - y * quat.y - z * quat.z; - double d1 = s * quat.x + x * quat.s + y * quat.z - z * quat.y; - double d2 = s * quat.y - x * quat.z + y * quat.s + z * quat.x; - double d3 = s * quat.z + x * quat.y - y * quat.x + z * quat.s; - s = d; - x = d1; - y = d2; - z = d3; - - return this; - } - - public double mag() - { - return Math.sqrt(x * x + y * y + z * z + s * s); - } - - public Quat normalize() - { - double d = mag(); - if (d != 0) - { - d = 1 / d; - x *= d; - y *= d; - z *= d; - s *= d; - } - - return this; - } - - public Quat copy() - { - return new Quat(this); - } - - public void rotate(Vector3 vec) - { - double d = -x * vec.x - y * vec.y - z * vec.z; - double d1 = s * vec.x + y * vec.z - z * vec.y; - double d2 = s * vec.y - x * vec.z + z * vec.x; - double d3 = s * vec.z + x * vec.y - y * vec.x; - vec.x = d1 * s - d * x - d2 * z + d3 * y; - vec.y = d2 * s - d * y + d1 * z - d3 * x; - vec.z = d3 * s - d * z - d1 * y + d2 * x; - } - - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "Quat(" + new BigDecimal(s, cont) + ", " + new BigDecimal(x, cont) + ", " + new BigDecimal(y, cont) + ", " + new BigDecimal(z, cont) + ")"; - } - - public Rotation rotation() - { - return new Rotation(this); - } -} diff --git a/src/main/java/codechicken/lib/vec/Rectangle4i.java b/src/main/java/codechicken/lib/vec/Rectangle4i.java deleted file mode 100644 index 92f030fd..00000000 --- a/src/main/java/codechicken/lib/vec/Rectangle4i.java +++ /dev/null @@ -1,116 +0,0 @@ -package codechicken.lib.vec; - -public class Rectangle4i -{ - public int x; - public int y; - public int w; - public int h; - - public Rectangle4i() - { - } - - public Rectangle4i(int x, int y, int w, int h) - { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } - - public int x1() - { - return x; - } - - public int y1() - { - return y; - } - - public int x2() - { - return x + w - 1; - } - - public int y2() - { - return y + h - 1; - } - - public void set(int x, int y, int w, int h) - { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } - - public Rectangle4i offset(int dx, int dy) - { - x += dx; - y += dy; - return this; - } - - @Deprecated - public Rectangle4i with(int px, int py) - { - return include(px, py); - } - - public Rectangle4i include(int px, int py) - { - if (px < x) expand(px - x, 0); - if (px >= x + w) expand(px - x - w + 1, 0); - if (py < y) expand(0, py - y); - if (py >= y + h) expand(0, py - y - h + 1); - return this; - } - - public Rectangle4i include(Rectangle4i r) - { - include(r.x, r.y); - return include(r.x2(), r.y2()); - } - - public Rectangle4i expand(int px, int py) - { - if (px > 0) - { - w += px; - } else - { - x += px; - w -= px; - } - if (py > 0) - { - h += py; - } else - { - y += py; - h -= py; - } - return this; - } - - public boolean contains(int px, int py) - { - return x <= px && px < x + w && y <= py && py < y + h; - } - - public boolean intersects(Rectangle4i r) - { - return r.x + r.w > x && - r.x < x + w && - r.y + r.h > y && - r.y < y + h; - } - - public int area() - { - return w * h; - } -} diff --git a/src/main/java/codechicken/lib/vec/RedundantTransformation.java b/src/main/java/codechicken/lib/vec/RedundantTransformation.java deleted file mode 100644 index 99382a8b..00000000 --- a/src/main/java/codechicken/lib/vec/RedundantTransformation.java +++ /dev/null @@ -1,58 +0,0 @@ -package codechicken.lib.vec; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -public class RedundantTransformation extends Transformation -{ - @Override - public void apply(Vector3 vec) - { - } - - @Override - public void apply(Matrix4 mat) - { - } - - @Override - public void applyN(Vector3 normal) - { - } - - @Override - public Transformation at(Vector3 point) - { - return this; - } - - @Override - @SideOnly(Side.CLIENT) - public void glApply() - { - } - - @Override - public Transformation inverse() - { - return this; - } - - @Override - public Transformation merge(Transformation next) - { - return next; - } - - @Override - public boolean isRedundant() - { - return true; - } - - @Override - public String toString() - { - return "Nothing()"; - } -} diff --git a/src/main/java/codechicken/lib/vec/Rotation.java b/src/main/java/codechicken/lib/vec/Rotation.java deleted file mode 100644 index 08d86402..00000000 --- a/src/main/java/codechicken/lib/vec/Rotation.java +++ /dev/null @@ -1,358 +0,0 @@ -package codechicken.lib.vec; - -import codechicken.lib.math.MathHelper; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import org.lwjgl.opengl.GL11; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class Rotation extends Transformation -{ - public static Vector3[] axes = new Vector3[]{ - new Vector3(0, -1, 0), - new Vector3(0, 1, 0), - new Vector3(0, 0, -1), - new Vector3(0, 0, 1), - new Vector3(-1, 0, 0), - new Vector3(1, 0, 0)}; - /** - * Clockwise pi/2 about y looking down - */ - public static Transformation[] quarterRotations = new Transformation[]{ - new RedundantTransformation(), - new VariableTransformation(new Matrix4(0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - double d1 = vec.x; - double d2 = vec.z; - vec.x = -d2; - vec.z = d1; - } - - @Override - public Transformation inverse() - { - return quarterRotations[3]; - } - }, - new VariableTransformation(new Matrix4(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - vec.x = -vec.x; - vec.z = -vec.z; - } - - @Override - public Transformation inverse() - { - return this; - } - }, - new VariableTransformation(new Matrix4(0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - double d1 = vec.x; - double d2 = vec.z; - vec.x = d2; - vec.z = -d1; - } - - @Override - public Transformation inverse() - { - return quarterRotations[1]; - } - } - }; - public static int[] sideRotMap = new int[]{ - 3, 4, 2, 5, - 3, 5, 2, 4, - 1, 5, 0, 4, - 1, 4, 0, 5, - 1, 2, 0, 3, - 1, 3, 0, 2}; - public static Transformation[] sideRotations = new Transformation[]{ - new RedundantTransformation(), - new VariableTransformation(new Matrix4(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - vec.y = -vec.y; - vec.z = -vec.z; - } - - @Override - public Transformation inverse() - { - return this; - } - }, - new VariableTransformation(new Matrix4(1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - double d1 = vec.y; - double d2 = vec.z; - vec.y = -d2; - vec.z = d1; - } - - @Override - public Transformation inverse() - { - return sideRotations[3]; - } - }, - new VariableTransformation(new Matrix4(1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - double d1 = vec.y; - double d2 = vec.z; - vec.y = d2; - vec.z = -d1; - } - - @Override - public Transformation inverse() - { - return sideRotations[2]; - } - }, - new VariableTransformation(new Matrix4(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - double d0 = vec.x; - double d1 = vec.y; - vec.x = d1; - vec.y = -d0; - } - - @Override - public Transformation inverse() - { - return sideRotations[5]; - } - }, - new VariableTransformation(new Matrix4(0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)) - { - @Override - public void apply(Vector3 vec) - { - double d0 = vec.x; - double d1 = vec.y; - vec.x = -d1; - vec.y = d0; - } - - @Override - public Transformation inverse() - { - return sideRotations[4]; - } - } - }; - public static int[] rotSideMap = new int[]{ - -1, -1, 2, 0, 1, 3, - -1, -1, 2, 0, 3, 1, - 2, 0, -1, -1, 3, 1, - 2, 0, -1, -1, 1, 3, - 2, 0, 1, 3, -1, -1, - 2, 0, 3, 1, -1, -1}; - /** - * Rotate pi/2 * this offset for [side] about y axis before rotating to the side for the rotation indicies to line up - */ - public static int[] sideRotOffsets = new int[]{0, 2, 2, 0, 1, 3}; - public double angle; - public Vector3 axis; - private Quat quat; - - public Rotation(double angle, Vector3 axis) - { - this.angle = angle; - this.axis = axis; - } - - public Rotation(double angle, double x, double y, double z) - { - this(angle, new Vector3(x, y, z)); - } - - public Rotation(Quat quat) - { - this.quat = quat; - - angle = Math.acos(quat.s) * 2; - if (angle == 0) - { - axis = new Vector3(0, 1, 0); - } else - { - double sa = Math.sin(angle * 0.5); - axis = new Vector3(quat.x / sa, quat.y / sa, quat.z / sa); - } - } - - public static int rotateSide(int s, int r) - { - return sideRotMap[s << 2 | r]; - } - - /** - * Reverse of rotateSide - */ - public static int rotationTo(int s1, int s2) - { - if ((s1 & 6) == (s2 & 6)) - { - throw new IllegalArgumentException("Faces " + s1 + " and " + s2 + " are opposites"); - } - return rotSideMap[s1 * 6 + s2]; - } - - /** - * @param player The placing player, used for obtaining the look vector - * @param side The side of the block being placed on - * @return The rotation for the face == side^1 - */ - public static int getSidedRotation(EntityPlayer player, int side) - { - Vector3 look = new Vector3(player.getLook(1)); - double max = 0; - int maxr = 0; - for (int r = 0; r < 4; r++) - { - Vector3 axis = Rotation.axes[rotateSide(side ^ 1, r)]; - double d = look.scalarProject(axis); - if (d > max) - { - max = d; - maxr = r; - } - } - return maxr; - } - - /** - * @return The rotation quat for side 0 and rotation 0 to side s with rotation r - */ - public static Transformation sideOrientation(int s, int r) - { - return quarterRotations[(r + sideRotOffsets[s]) % 4].with(sideRotations[s]); - } - - /** - * @param entity The placing com.darkona.adventurebackpack.entity, used for obtaining the look vector - * @return The side towards which the com.darkona.adventurebackpack.entity is most directly looking. - */ - public static int getSideFromLookAngle(EntityLivingBase entity) - { - Vector3 look = new Vector3(entity.getLook(1)); - double max = 0; - int maxs = 0; - for (int s = 0; s < 6; s++) - { - double d = look.scalarProject(axes[s]); - if (d > max) - { - max = d; - maxs = s; - } - } - return maxs; - } - - @Override - public void apply(Vector3 vec) - { - if (quat == null) - { - quat = Quat.aroundAxis(axis, angle); - } - - vec.rotate(quat); - } - - @Override - public void applyN(Vector3 normal) - { - apply(normal); - } - - @Override - public void apply(Matrix4 mat) - { - mat.rotate(angle, axis); - } - - public Quat toQuat() - { - if (quat == null) - { - quat = Quat.aroundAxis(axis, angle); - } - return quat; - } - - @Override - @SideOnly(Side.CLIENT) - public void glApply() - { - GL11.glRotatef((float) (angle * MathHelper.todeg), (float) axis.x, (float) axis.y, (float) axis.z); - } - - @Override - public Transformation inverse() - { - return new Rotation(-angle, axis); - } - - @Override - public Transformation merge(Transformation next) - { - if (next instanceof Rotation) - { - Rotation r = (Rotation) next; - if (r.axis.equalsT(axis)) - { - return new Rotation(angle + r.angle, axis); - } - - return new Rotation(toQuat().copy().multiply(r.toQuat())); - } - - return null; - } - - @Override - public boolean isRedundant() - { - return MathHelper.between(-1E-5, angle, 1E-5); - } - - @Override - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "Rotation(" + new BigDecimal(angle, cont) + ", " + new BigDecimal(axis.x, cont) + ", " + - new BigDecimal(axis.y, cont) + ", " + new BigDecimal(axis.z, cont) + ")"; - } - - -} diff --git a/src/main/java/codechicken/lib/vec/Scale.java b/src/main/java/codechicken/lib/vec/Scale.java deleted file mode 100644 index 712d5851..00000000 --- a/src/main/java/codechicken/lib/vec/Scale.java +++ /dev/null @@ -1,83 +0,0 @@ -package codechicken.lib.vec; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import org.lwjgl.opengl.GL11; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class Scale extends Transformation -{ - public Vector3 factor; - - public Scale(Vector3 factor) - { - this.factor = factor; - } - - public Scale(double factor) - { - this(new Vector3(factor, factor, factor)); - } - - public Scale(double x, double y, double z) - { - this(new Vector3(x, y, z)); - } - - @Override - public void apply(Vector3 vec) - { - vec.multiply(factor); - } - - @Override - public void applyN(Vector3 normal) - { - } - - @Override - public void apply(Matrix4 mat) - { - mat.scale(factor); - } - - @Override - @SideOnly(Side.CLIENT) - public void glApply() - { - GL11.glScaled(factor.x, factor.y, factor.z); - } - - @Override - public Transformation inverse() - { - return new Scale(1 / factor.x, 1 / factor.y, 1 / factor.z); - } - - @Override - public Transformation merge(Transformation next) - { - if (next instanceof Scale) - { - return new Scale(factor.copy().multiply(((Scale) next).factor)); - } - - return null; - } - - @Override - public boolean isRedundant() - { - return factor.equalsT(Vector3.one); - } - - @Override - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "Scale(" + new BigDecimal(factor.x, cont) + ", " + new BigDecimal(factor.y, cont) + ", " + new BigDecimal(factor.z, cont) + ")"; - } -} diff --git a/src/main/java/codechicken/lib/vec/SwapYZ.java b/src/main/java/codechicken/lib/vec/SwapYZ.java deleted file mode 100644 index 32085d96..00000000 --- a/src/main/java/codechicken/lib/vec/SwapYZ.java +++ /dev/null @@ -1,27 +0,0 @@ -package codechicken.lib.vec; - -public class SwapYZ extends VariableTransformation -{ - public SwapYZ() - { - super(new Matrix4( - 1, 0, 0, 0, - 0, 0, 1, 0, - 0, 1, 0, 0, - 0, 0, 0, 1)); - } - - @Override - public void apply(Vector3 vec) - { - double vz = vec.z; - vec.z = vec.y; - vec.y = vz; - } - - @Override - public Transformation inverse() - { - return this; - } -} diff --git a/src/main/java/codechicken/lib/vec/Transformation.java b/src/main/java/codechicken/lib/vec/Transformation.java deleted file mode 100644 index b6727c7b..00000000 --- a/src/main/java/codechicken/lib/vec/Transformation.java +++ /dev/null @@ -1,63 +0,0 @@ -package codechicken.lib.vec; - -import codechicken.lib.render.CCRenderState; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -/** - * Abstract supertype for any 3D vector transformation - */ -public abstract class Transformation extends ITransformation implements CCRenderState.IVertexOperation -{ - public static final int operationIndex = CCRenderState.registerOperation(); - - /** - * Applies this transformation to a normal (doesn't translate) - * - * @param normal The normal to transform - */ - public abstract void applyN(Vector3 normal); - - /** - * Applies this transformation to a matrix as a multiplication on the right hand side. - * - * @param mat The matrix to combine this transformation with - */ - public abstract void apply(Matrix4 mat); - - public Transformation at(Vector3 point) - { - return new TransformationList(new Translation(-point.x, -point.y, -point.z), this, point.translation()); - } - - public TransformationList with(Transformation t) - { - return new TransformationList(this, t); - } - - @SideOnly(Side.CLIENT) - public abstract void glApply(); - - @Override - public boolean load() - { - CCRenderState.pipeline.addRequirement(CCRenderState.normalAttrib.operationID()); - return !isRedundant(); - } - - @Override - public void operate() - { - apply(CCRenderState.vert.vec); - if (CCRenderState.normalAttrib.active) - { - applyN(CCRenderState.normal); - } - } - - @Override - public int operationID() - { - return operationIndex; - } -} diff --git a/src/main/java/codechicken/lib/vec/TransformationList.java b/src/main/java/codechicken/lib/vec/TransformationList.java deleted file mode 100644 index d40e3451..00000000 --- a/src/main/java/codechicken/lib/vec/TransformationList.java +++ /dev/null @@ -1,202 +0,0 @@ -package codechicken.lib.vec; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import java.util.ArrayList; -import java.util.Iterator; - -public class TransformationList extends Transformation -{ - private ArrayList transformations = new ArrayList(); - private Matrix4 mat; - - public TransformationList(Transformation... transforms) - { - for (Transformation t : transforms) - if (t instanceof TransformationList) - { - transformations.addAll(((TransformationList) t).transformations); - } else - { - transformations.add(t); - } - - compact(); - } - - public Matrix4 compile() - { - if (mat == null) - { - mat = new Matrix4(); - for (int i = transformations.size() - 1; i >= 0; i--) - transformations.get(i).apply(mat); - } - return mat; - } - - /** - * Returns a global space matrix as opposed to an object space matrix (reverse application order) - * - * @return - */ - public Matrix4 reverseCompile() - { - Matrix4 mat = new Matrix4(); - for (Transformation t : transformations) - t.apply(mat); - return mat; - } - - @Override - public void apply(Vector3 vec) - { - if (mat != null) - { - mat.apply(vec); - } else - { - for (int i = 0; i < transformations.size(); i++) - transformations.get(i).apply(vec); - } - } - - @Override - public void applyN(Vector3 normal) - { - if (mat != null) - { - mat.applyN(normal); - } else - { - for (int i = 0; i < transformations.size(); i++) - transformations.get(i).applyN(normal); - } - } - - @Override - public void apply(Matrix4 mat) - { - mat.multiply(compile()); - } - - @Override - public TransformationList with(Transformation t) - { - if (t.isRedundant()) - { - return this; - } - - mat = null;//matrix invalid - if (t instanceof TransformationList) - { - transformations.addAll(((TransformationList) t).transformations); - } else - { - transformations.add(t); - } - - compact(); - return this; - } - - public TransformationList prepend(Transformation t) - { - if (t.isRedundant()) - { - return this; - } - - mat = null;//matrix invalid - if (t instanceof TransformationList) - { - transformations.addAll(0, ((TransformationList) t).transformations); - } else - { - transformations.add(0, t); - } - - compact(); - return this; - } - - private void compact() - { - ArrayList newList = new ArrayList(transformations.size()); - Iterator iterator = transformations.iterator(); - Transformation prev = null; - while (iterator.hasNext()) - { - Transformation t = iterator.next(); - if (t.isRedundant()) - { - continue; - } - - if (prev != null) - { - Transformation m = prev.merge(t); - if (m == null) - { - newList.add(prev); - } else if (m.isRedundant()) - { - t = null; - } else - { - t = m; - } - } - prev = t; - } - if (prev != null) - { - newList.add(prev); - } - - if (newList.size() < transformations.size()) - { - transformations = newList; - mat = null; - } - - if (transformations.size() > 3 && mat == null) - { - compile(); - } - } - - @Override - public boolean isRedundant() - { - return transformations.size() == 0; - } - - @Override - @SideOnly(Side.CLIENT) - public void glApply() - { - for (int i = transformations.size() - 1; i >= 0; i--) - transformations.get(i).glApply(); - } - - @Override - public Transformation inverse() - { - TransformationList rev = new TransformationList(); - for (int i = transformations.size() - 1; i >= 0; i--) - rev.with(transformations.get(i).inverse()); - return rev; - } - - @Override - public String toString() - { - String s = ""; - for (Transformation t : transformations) - s += "\n" + t.toString(); - return s.trim(); - } -} diff --git a/src/main/java/codechicken/lib/vec/Translation.java b/src/main/java/codechicken/lib/vec/Translation.java deleted file mode 100644 index 2d7e8cd9..00000000 --- a/src/main/java/codechicken/lib/vec/Translation.java +++ /dev/null @@ -1,84 +0,0 @@ -package codechicken.lib.vec; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import org.lwjgl.opengl.GL11; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class Translation extends Transformation -{ - public Vector3 vec; - - public Translation(Vector3 vec) - { - this.vec = vec; - } - - public Translation(double x, double y, double z) - { - this(new Vector3(x, y, z)); - } - - @Override - public void apply(Vector3 vec) - { - vec.add(this.vec); - } - - @Override - public void applyN(Vector3 normal) - { - } - - @Override - public void apply(Matrix4 mat) - { - mat.translate(vec); - } - - @Override - public Transformation at(Vector3 point) - { - return this; - } - - @Override - @SideOnly(Side.CLIENT) - public void glApply() - { - GL11.glTranslated(vec.x, vec.y, vec.z); - } - - @Override - public Transformation inverse() - { - return new Translation(-vec.x, -vec.y, -vec.z); - } - - @Override - public Transformation merge(Transformation next) - { - if (next instanceof Translation) - { - return new Translation(vec.copy().add(((Translation) next).vec)); - } - - return null; - } - - @Override - public boolean isRedundant() - { - return vec.equalsT(Vector3.zero); - } - - @Override - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "Translation(" + new BigDecimal(vec.x, cont) + ", " + new BigDecimal(vec.y, cont) + ", " + new BigDecimal(vec.z, cont) + ")"; - } -} diff --git a/src/main/java/codechicken/lib/vec/VariableTransformation.java b/src/main/java/codechicken/lib/vec/VariableTransformation.java deleted file mode 100644 index 84018e2b..00000000 --- a/src/main/java/codechicken/lib/vec/VariableTransformation.java +++ /dev/null @@ -1,33 +0,0 @@ -package codechicken.lib.vec; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -public abstract class VariableTransformation extends Transformation -{ - public Matrix4 mat; - - public VariableTransformation(Matrix4 mat) - { - this.mat = mat; - } - - @Override - public void applyN(Vector3 normal) - { - apply(normal); - } - - @Override - public void apply(Matrix4 mat) - { - mat.multiply(this.mat); - } - - @Override - @SideOnly(Side.CLIENT) - public void glApply() - { - mat.glApply(); - } -} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/vec/Vector3.java b/src/main/java/codechicken/lib/vec/Vector3.java deleted file mode 100644 index 2d3e58e9..00000000 --- a/src/main/java/codechicken/lib/vec/Vector3.java +++ /dev/null @@ -1,545 +0,0 @@ -package codechicken.lib.vec; - -import codechicken.lib.math.MathHelper; -import codechicken.lib.util.Copyable; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.entity.Entity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Vec3; -import org.lwjgl.opengl.GL11; -import org.lwjgl.util.vector.Vector3f; -import org.lwjgl.util.vector.Vector4f; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class Vector3 implements Copyable -{ - public static Vector3 zero = new Vector3(); - public static Vector3 one = new Vector3(1, 1, 1); - public static Vector3 center = new Vector3(0.5, 0.5, 0.5); - - public double x; - public double y; - public double z; - - public Vector3() - { - } - - public Vector3(double d, double d1, double d2) - { - x = d; - y = d1; - z = d2; - } - - public Vector3(Vector3 vec) - { - x = vec.x; - y = vec.y; - z = vec.z; - } - - public Vector3(double[] da) - { - this(da[0], da[1], da[2]); - } - - public Vector3(Vec3 vec) - { - x = vec.xCoord; - y = vec.yCoord; - z = vec.zCoord; - } - - public Vector3(BlockCoord coord) - { - x = coord.x; - y = coord.y; - z = coord.z; - } - - public static Vector3 fromEntity(Entity e) - { - return new Vector3(e.posX, e.posY, e.posZ); - } - - public static Vector3 fromEntityCenter(Entity e) - { - return new Vector3(e.posX, e.posY - e.yOffset + e.height / 2, e.posZ); - } - - public static Vector3 fromTileEntity(TileEntity e) - { - return new Vector3(e.xCoord, e.yCoord, e.zCoord); - } - - public static Vector3 fromTileEntityCenter(TileEntity e) - { - return new Vector3(e.xCoord + 0.5, e.yCoord + 0.5, e.zCoord + 0.5); - } - - public static Vector3 fromAxes(double[] da) - { - return new Vector3(da[2], da[0], da[1]); - } - - public Vector3 copy() - { - return new Vector3(this); - } - - public Vector3 set(double d, double d1, double d2) - { - x = d; - y = d1; - z = d2; - return this; - } - - public Vector3 set(Vector3 vec) - { - x = vec.x; - y = vec.y; - z = vec.z; - return this; - } - - public double getSide(int side) - { - switch (side) - { - case 0: - case 1: - return y; - case 2: - case 3: - return z; - case 4: - case 5: - return x; - } - throw new IndexOutOfBoundsException("Switch Falloff"); - } - - public Vector3 setSide(int s, double v) - { - switch (s) - { - case 0: - case 1: - y = v; - break; - case 2: - case 3: - z = v; - break; - case 4: - case 5: - x = v; - break; - default: - throw new IndexOutOfBoundsException("Switch Falloff"); - } - return this; - } - - public double dotProduct(Vector3 vec) - { - double d = vec.x * x + vec.y * y + vec.z * z; - - if (d > 1 && d < 1.00001) - { - d = 1; - } else if (d < -1 && d > -1.00001) - { - d = -1; - } - return d; - } - - public double dotProduct(double d, double d1, double d2) - { - return d * x + d1 * y + d2 * z; - } - - public Vector3 crossProduct(Vector3 vec) - { - double d = y * vec.z - z * vec.y; - double d1 = z * vec.x - x * vec.z; - double d2 = x * vec.y - y * vec.x; - x = d; - y = d1; - z = d2; - return this; - } - - public Vector3 add(double d, double d1, double d2) - { - x += d; - y += d1; - z += d2; - return this; - } - - public Vector3 add(Vector3 vec) - { - x += vec.x; - y += vec.y; - z += vec.z; - return this; - } - - public Vector3 add(double d) - { - return add(d, d, d); - } - - public Vector3 sub(Vector3 vec) - { - return subtract(vec); - } - - public Vector3 subtract(Vector3 vec) - { - x -= vec.x; - y -= vec.y; - z -= vec.z; - return this; - } - - public Vector3 negate(Vector3 vec) - { - x = -x; - y = -y; - z = -z; - return this; - } - - public Vector3 multiply(double d) - { - x *= d; - y *= d; - z *= d; - return this; - } - - public Vector3 multiply(Vector3 f) - { - x *= f.x; - y *= f.y; - z *= f.z; - return this; - } - - public Vector3 multiply(double fx, double fy, double fz) - { - x *= fx; - y *= fy; - z *= fz; - return this; - } - - public double mag() - { - return Math.sqrt(x * x + y * y + z * z); - } - - public double magSquared() - { - return x * x + y * y + z * z; - } - - public Vector3 normalize() - { - double d = mag(); - if (d != 0) - { - multiply(1 / d); - } - return this; - } - - public String toString() - { - MathContext cont = new MathContext(4, RoundingMode.HALF_UP); - return "Vector3(" + new BigDecimal(x, cont) + ", " + new BigDecimal(y, cont) + ", " + new BigDecimal(z, cont) + ")"; - } - - public Vector3 perpendicular() - { - if (z == 0) - { - return zCrossProduct(); - } - return xCrossProduct(); - } - - public Vector3 xCrossProduct() - { - double d = z; - double d1 = -y; - x = 0; - y = d; - z = d1; - return this; - } - - public Vector3 zCrossProduct() - { - double d = y; - double d1 = -x; - x = d; - y = d1; - z = 0; - return this; - } - - public Vector3 yCrossProduct() - { - double d = -z; - double d1 = x; - x = d; - y = 0; - z = d1; - return this; - } - - public Vector3 rotate(double angle, Vector3 axis) - { - Quat.aroundAxis(axis.copy().normalize(), angle).rotate(this); - return this; - } - - public Vector3 rotate(Quat rotator) - { - rotator.rotate(this); - return this; - } - - public Vec3 toVec3D() - { - return Vec3.createVectorHelper(x, y, z); - } - - public double angle(Vector3 vec) - { - return Math.acos(copy().normalize().dotProduct(vec.copy().normalize())); - } - - public boolean isZero() - { - return x == 0 && y == 0 && z == 0; - } - - public boolean isAxial() - { - return x == 0 ? (y == 0 || z == 0) : (y == 0 && z == 0); - } - - @SideOnly(Side.CLIENT) - public Vector3f vector3f() - { - return new Vector3f((float) x, (float) y, (float) z); - } - - @SideOnly(Side.CLIENT) - public Vector4f vector4f() - { - return new Vector4f((float) x, (float) y, (float) z, 1); - } - - @SideOnly(Side.CLIENT) - public void glVertex() - { - GL11.glVertex3d(x, y, z); - } - - public Vector3 YZintercept(Vector3 end, double px) - { - double dx = end.x - x; - double dy = end.y - y; - double dz = end.z - z; - - if (dx == 0) - { - return null; - } - - double d = (px - x) / dx; - if (MathHelper.between(-1E-5, d, 1E-5)) - { - return this; - } - - if (!MathHelper.between(0, d, 1)) - { - return null; - } - - x = px; - y += d * dy; - z += d * dz; - return this; - } - - public Vector3 XZintercept(Vector3 end, double py) - { - double dx = end.x - x; - double dy = end.y - y; - double dz = end.z - z; - - if (dy == 0) - { - return null; - } - - double d = (py - y) / dy; - if (MathHelper.between(-1E-5, d, 1E-5)) - { - return this; - } - - if (!MathHelper.between(0, d, 1)) - { - return null; - } - - x += d * dx; - y = py; - z += d * dz; - return this; - } - - public Vector3 XYintercept(Vector3 end, double pz) - { - double dx = end.x - x; - double dy = end.y - y; - double dz = end.z - z; - - if (dz == 0) - { - return null; - } - - double d = (pz - z) / dz; - if (MathHelper.between(-1E-5, d, 1E-5)) - { - return this; - } - - if (!MathHelper.between(0, d, 1)) - { - return null; - } - - x += d * dx; - y += d * dy; - z = pz; - return this; - } - - public Vector3 negate() - { - x = -x; - y = -y; - z = -z; - return this; - } - - public Translation translation() - { - return new Translation(this); - } - - public double scalarProject(Vector3 b) - { - double l = b.mag(); - return l == 0 ? 0 : dotProduct(b) / l; - } - - public Vector3 project(Vector3 b) - { - double l = b.magSquared(); - if (l == 0) - { - set(0, 0, 0); - return this; - } - double m = dotProduct(b) / l; - set(b).multiply(m); - return this; - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof Vector3)) - { - return false; - } - Vector3 v = (Vector3) o; - return x == v.x && y == v.y && z == v.z; - } - - /** - * Equals method with tolerance - * - * @return true if this is equal to v within +-1E-5 - */ - public boolean equalsT(Vector3 v) - { - return MathHelper.between(x - 1E-5, v.x, x + 1E-5) && - MathHelper.between(y - 1E-5, v.y, y + 1E-5) && - MathHelper.between(z - 1E-5, v.z, z + 1E-5); - } - - public Vector3 apply(Transformation t) - { - t.apply(this); - return this; - } - - public Vector3 $tilde() - { - return normalize(); - } - - public Vector3 unary_$tilde() - { - return normalize(); - } - - public Vector3 $plus(Vector3 v) - { - return add(v); - } - - public Vector3 $minus(Vector3 v) - { - return subtract(v); - } - - public Vector3 $times(double d) - { - return multiply(d); - } - - public Vector3 $div(double d) - { - return multiply(1 / d); - } - - public Vector3 $times(Vector3 v) - { - return crossProduct(v); - } - - public double $dot$times(Vector3 v) - { - return dotProduct(v); - } -} diff --git a/src/main/java/com/darkona/adventurebackpack/AdventureBackpack.java b/src/main/java/com/darkona/adventurebackpack/AdventureBackpack.java index bfe15c11..e5915f3b 100644 --- a/src/main/java/com/darkona/adventurebackpack/AdventureBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/AdventureBackpack.java @@ -1,159 +1,91 @@ package com.darkona.adventurebackpack; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; -import com.darkona.adventurebackpack.handlers.ClientEventHandler; -import com.darkona.adventurebackpack.handlers.GeneralEventHandler; -import com.darkona.adventurebackpack.handlers.GuiHandler; -import com.darkona.adventurebackpack.handlers.PlayerEventHandler; -import com.darkona.adventurebackpack.init.*; -import com.darkona.adventurebackpack.proxy.IProxy; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Utils; -import com.darkona.adventurebackpack.util.calendar.ChineseCalendar; -import com.darkona.adventurebackpack.util.calendar.JewishCalendar; +import net.minecraftforge.common.MinecraftForge; import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkRegistry; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import java.util.Calendar; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; +import com.darkona.adventurebackpack.handlers.ClientEventHandler; +import com.darkona.adventurebackpack.handlers.GeneralEventHandler; +import com.darkona.adventurebackpack.handlers.GuiHandler; +import com.darkona.adventurebackpack.handlers.PlayerEventHandler; +import com.darkona.adventurebackpack.init.ModBlocks; +import com.darkona.adventurebackpack.init.ModDates; +import com.darkona.adventurebackpack.init.ModEntities; +import com.darkona.adventurebackpack.init.ModFluids; +import com.darkona.adventurebackpack.init.ModItems; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.init.ModRecipes; +import com.darkona.adventurebackpack.init.ModWorldGen; +import com.darkona.adventurebackpack.proxy.IProxy; +import com.darkona.adventurebackpack.reference.GeneralReference; +import com.darkona.adventurebackpack.reference.LoadedMods; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.reference.WailaTileAdventureBackpack; /** * Created on 10/10/2014 * * @author Javier Darkona */ -@Mod(modid = ModInfo.MOD_ID, - name = ModInfo.MOD_NAME, - version = ModInfo.MOD_VERSION, - guiFactory = ModInfo.GUI_FACTORY_CLASS -) +@Mod(modid = ModInfo.MOD_ID, name = ModInfo.MOD_NAME, version = ModInfo.MOD_VERSION, guiFactory = ModInfo.GUI_FACTORY_CLASS, + dependencies = "required-after:CodeChickenCore@[1.0.7.47,)") public class AdventureBackpack { - @SidedProxy(clientSide = ModInfo.MOD_CLIENT_PROXY, serverSide = ModInfo.MOD_SERVER_PROXY) public static IProxy proxy; @Mod.Instance(ModInfo.MOD_ID) public static AdventureBackpack instance; - //Static things - public static CreativeTabAB creativeTab = new CreativeTabAB(); - - - public boolean chineseNewYear; - public boolean hannukah; - public String Holiday; - PlayerEventHandler playerEventHandler; - ClientEventHandler clientEventHandler; - GeneralEventHandler generalEventHandler; - - GuiHandler guiHandler; - @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { - - int year = Calendar.getInstance().get(Calendar.YEAR), month = Calendar.getInstance().get(Calendar.MONTH) + 1, day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); - //Configuration FMLCommonHandler.instance().bus().register(new ConfigHandler()); ConfigHandler.init(event.getSuggestedConfigurationFile()); - chineseNewYear = ChineseCalendar.isChineseNewYear(year, month, day); - hannukah = JewishCalendar.isHannukah(year, month, day); - Holiday = Utils.getHoliday(); //ModStuff + ModDates.init(); ModItems.init(); ModBlocks.init(); ModFluids.init(); FluidEffectRegistry.init(); ModEntities.init(); ModNetwork.init(); - proxy.initNetwork(); - // EVENTS - playerEventHandler = new PlayerEventHandler(); - generalEventHandler = new GeneralEventHandler(); - clientEventHandler = new ClientEventHandler(); - - - MinecraftForge.EVENT_BUS.register(generalEventHandler); - MinecraftForge.EVENT_BUS.register(clientEventHandler); - MinecraftForge.EVENT_BUS.register(playerEventHandler); - - FMLCommonHandler.instance().bus().register(playerEventHandler); + //Events + MinecraftForge.EVENT_BUS.register(new GeneralEventHandler()); + MinecraftForge.EVENT_BUS.register(new ClientEventHandler()); + MinecraftForge.EVENT_BUS.register(new PlayerEventHandler()); + FMLCommonHandler.instance().bus().register(new PlayerEventHandler()); } @Mod.EventHandler public void init(FMLInitializationEvent event) { - + LoadedMods.init(); proxy.init(); ModRecipes.init(); - ModWorldGen.init(); + if (LoadedMods.WAILA) WailaTileAdventureBackpack.init(); + //GUIs - guiHandler = new GuiHandler(); - NetworkRegistry.INSTANCE.registerGuiHandler(instance, guiHandler); + NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler()); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { + GeneralReference.init(); - ConfigHandler.IS_TINKERS = Loader.isModLoaded("TConstruct"); - ConfigHandler.IS_THAUM = Loader.isModLoaded("Thaumcraft"); - ConfigHandler.IS_TWILIGHT = Loader.isModLoaded("TwilightForest"); - ConfigHandler.IS_ENVIROMINE = Loader.isModLoaded("EnviroMine"); - ConfigHandler.IS_BUILDCRAFT = Loader.isModLoaded("BuildCraft|Core"); - ConfigHandler.IS_RAILCRAFT = Loader.isModLoaded("Railcraft"); - - - if (ConfigHandler.IS_BUILDCRAFT) - { - LogHelper.info("Buildcraft is present. Acting accordingly"); - } - - if (ConfigHandler.IS_TWILIGHT) - { - LogHelper.info("Twilight Forest is present. Acting accordingly"); - } - - ConditionalFluidEffect.init(); - ModItems.conditionalInit(); - ModRecipes.conditionalInit(); - - - /* - LogHelper.info("DUMPING FLUID INFORMATION"); - LogHelper.info("-------------------------------------------------------------------------"); - for(Fluid fluid : FluidRegistry.getRegisteredFluids().values()) - { - - LogHelper.info("Unlocalized name: " + fluid.getUnlocalizedName()); - LogHelper.info("Name: " + fluid.getName()); - LogHelper.info(""); - } - LogHelper.info("-------------------------------------------------------------------------"); - */ - /* - LogHelper.info("DUMPING TILE INFORMATION"); - LogHelper.info("-------------------------------------------------------------------------"); - for (Block block : GameData.getBlockRegistry().typeSafeIterable()) - { - LogHelper.info("Block= " + block.getUnlocalizedName()); - } - LogHelper.info("-------------------------------------------------------------------------"); - */ + //ConditionalFluidEffect.init(); + //ModItems.conditionalInit(); + //ModRecipes.conditionalInit(); } - } diff --git a/src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java b/src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java index 46b13170..b082bc49 100644 --- a/src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java +++ b/src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java @@ -1,18 +1,19 @@ package com.darkona.adventurebackpack; -import com.darkona.adventurebackpack.init.ModItems; -import com.darkona.adventurebackpack.reference.ModInfo; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; +import com.darkona.adventurebackpack.init.ModItems; +import com.darkona.adventurebackpack.reference.ModInfo; + /** * Created on 11/10/2014. + * * @author Javier Darkona */ public class CreativeTabAB { - - public static final CreativeTabs ADVENTURE_BACKPACK_CREATIVE_TAB = new CreativeTabs(ModInfo.MOD_ID.toLowerCase()) + public static final CreativeTabs TAB_AB = new CreativeTabs(ModInfo.MOD_ID) { @Override public Item getTabIconItem() @@ -29,9 +30,7 @@ public String getTranslatedTabLabel() @Override public String getTabLabel() { - return ModInfo.MOD_ID.toLowerCase(); + return ModInfo.MOD_ID; } - }; - } diff --git a/src/main/java/com/darkona/adventurebackpack/block/BackpackMaterial.java b/src/main/java/com/darkona/adventurebackpack/block/BackpackMaterial.java index 3b5159e8..437012bc 100644 --- a/src/main/java/com/darkona/adventurebackpack/block/BackpackMaterial.java +++ b/src/main/java/com/darkona/adventurebackpack/block/BackpackMaterial.java @@ -10,158 +10,44 @@ */ public class BackpackMaterial extends Material { - - public BackpackMaterial() { super(MapColor.brownColor); } - /** - * Returns if blocks of these materials are liquids. - */ - @Override - public boolean isLiquid() - { - return false; - } - - @Override - public boolean isSolid() - { - return true; - } - - /** - * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true - */ @Override public boolean getCanBlockGrass() { return false; } - /** - * Returns if this material is considered solid or not - */ - @Override - public boolean blocksMovement() - { - return super.blocksMovement(); - } - - /** - * Makes blocks with this material require the correct tool to be harvested. - */ - @Override - protected Material setRequiresTool() - { - return super.setRequiresTool(); - } - - /** - * Set the canBurn bool to True and return the current object. - */ @Override protected Material setBurning() { return this; } - /** - * Returns if the block can burn or not. - */ @Override public boolean getCanBurn() { return false; } - /** - * Sets {@link #replaceable} to true. - */ - @Override - public Material setReplaceable() - { - return super.setReplaceable(); - } - - /** - * Returns whether the material can be replaced by other blocks when placed - eg snow, vines and tall grass. - */ @Override public boolean isReplaceable() { return false; } - /** - * Returns true if the material can be harvested without a tool (or with the wrong tool) - */ @Override public boolean isToolNotRequired() { return true; } - /** - * This type of material can't be pushed, but pistons can move over it. - */ - @Override - protected Material setNoPushMobility() - { - return super.setNoPushMobility(); - } - - /** - * @see #isAdventureModeExempt() - */ - @Override - protected Material setAdventureModeExempt() - { - return super.setAdventureModeExempt(); - } - - @Override - public MapColor getMaterialMapColor() - { - return super.getMaterialMapColor(); - } - - /** - * Returns true if blocks with this material can always be mined in adventure mode. - */ @Override public boolean isAdventureModeExempt() { return true; } - - /** - * This type of material can't be pushed, and pistons are blocked to move. - */ - @Override - protected Material setImmovableMobility() - { - return super.setImmovableMobility(); - } - - /** - * Returns the mobility information of the material, 0 = free, 1 = can't push but can move over, 2 = total - * immobility and stop pistons. - */ - @Override - public int getMaterialMobility() - { - return super.getMaterialMobility(); - } - - /** - * Indicate if the material is opaque - */ - @Override - public boolean isOpaque() - { - return super.isOpaque(); - } } diff --git a/src/main/java/com/darkona/adventurebackpack/block/BlockAdventureBackpack.java b/src/main/java/com/darkona/adventurebackpack/block/BlockAdventureBackpack.java index fef755c0..3edf7398 100644 --- a/src/main/java/com/darkona/adventurebackpack/block/BlockAdventureBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/block/BlockAdventureBackpack.java @@ -1,45 +1,56 @@ package com.darkona.adventurebackpack.block; -import com.darkona.adventurebackpack.AdventureBackpack; -import com.darkona.adventurebackpack.client.Icons; -import com.darkona.adventurebackpack.handlers.GuiHandler; -import com.darkona.adventurebackpack.init.ModItems; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Utils; -import cpw.mods.fml.common.network.internal.FMLNetworkHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.Random; + import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EnumCreatureType; -import net.minecraft.entity.boss.EntityDragon; -import net.minecraft.entity.boss.EntityWither; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.*; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.DamageSource; +import net.minecraft.util.IIcon; +import net.minecraft.util.MathHelper; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; import net.minecraft.world.Explosion; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +import cpw.mods.fml.common.network.internal.FMLNetworkHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; -import java.util.Random; +import com.darkona.adventurebackpack.AdventureBackpack; +import com.darkona.adventurebackpack.client.Icons; +import com.darkona.adventurebackpack.handlers.GuiHandler; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.reference.GeneralReference; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.CoordsUtils; + +import static com.darkona.adventurebackpack.reference.BackpackTypes.BOOKSHELF; +import static com.darkona.adventurebackpack.reference.BackpackTypes.CACTUS; +import static com.darkona.adventurebackpack.reference.BackpackTypes.GLOWSTONE; +import static com.darkona.adventurebackpack.reference.BackpackTypes.REDSTONE; +import static com.darkona.adventurebackpack.reference.BackpackTypes.UNKNOWN; /** * Created on 12/10/2014. + * * @author Javier Darkona */ public class BlockAdventureBackpack extends BlockContainer { - public BlockAdventureBackpack() { super(new BackpackMaterial()); @@ -50,21 +61,15 @@ public BlockAdventureBackpack() /** * Pretty effects for the bookshelf ;) - * - * @param world - * @param x - * @param y - * @param z - * @param random */ @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(World world, int x, int y, int z, Random random) { - if (getAssociatedTileColorName(world, x, y, z).equals("Bookshelf")) + if (getAssociatedTileBackpackType(world, x, y, z) == BOOKSHELF) { - ChunkCoordinates enchTable = Utils.findBlock3D(world, x, y, z, Blocks.enchanting_table, 2, 2); - if(enchTable !=null) + ChunkCoordinates enchTable = CoordsUtils.findBlock3D(world, x, y, z, Blocks.enchanting_table, 2, 2); + if (enchTable != null) { if (!world.isAirBlock((enchTable.posX - x) / 2 + x, enchTable.posY, (enchTable.posZ - z) / 2 + z)) { @@ -72,7 +77,7 @@ public void randomDisplayTick(World world, int x, int y, int z, Random random) } for (int o = 0; o < 4; o++) { - world.spawnParticle("enchantmenttable",enchTable.posX + 0.5D,enchTable.posY + 2.0D,enchTable.posZ + 0.5D, + world.spawnParticle("enchantmenttable", enchTable.posX + 0.5D, enchTable.posY + 2.0D, enchTable.posZ + 0.5D, ((x - enchTable.posX) + random.nextFloat()) - 0.5D, ((y - enchTable.posY) - random.nextFloat() - 1.0F), ((z - enchTable.posZ) + random.nextFloat()) - 0.5D); @@ -81,6 +86,7 @@ public void randomDisplayTick(World world, int x, int y, int z, Random random) } } + @Override public int getMobilityFlag() { return 0; @@ -104,10 +110,12 @@ public boolean isToolEffective(String type, int metadata) return true; } - private String getAssociatedTileColorName(IBlockAccess world, int x, int y, int z) + private BackpackTypes getAssociatedTileBackpackType(IBlockAccess world, int x, int y, int z) { - return ((TileAdventureBackpack) world.getTileEntity(x, y, z)).getColorName(); + final TileEntity tile = world.getTileEntity(x, y, z); + return (tile instanceof TileAdventureBackpack) ? ((TileAdventureBackpack) tile).getType() : UNKNOWN; } + @Override public boolean canRenderInPass(int pass) { @@ -123,7 +131,7 @@ public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity @Override public float getEnchantPowerBonus(World world, int x, int y, int z) { - return getAssociatedTileColorName(world, x, y, z).equals("Bookshelf") ? 10 : 0; + return getAssociatedTileBackpackType(world, x, y, z) == BOOKSHELF ? 10 : 0; } @Override @@ -165,47 +173,12 @@ public boolean canHarvestBlock(EntityPlayer player, int meta) @Override public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) { - if (getAssociatedTileColorName(world, x, y, z).equals("Cactus")) + if (getAssociatedTileBackpackType(world, x, y, z) == CACTUS) { entity.attackEntityFrom(DamageSource.cactus, 1.0F); } } - /** - * Called when a player hits the block. Args: world, x, y, z, player - * - * @param p_149699_1_ - * @param p_149699_2_ - * @param p_149699_3_ - * @param p_149699_4_ - * @param p_149699_5_ - */ - @Override - public void onBlockClicked(World p_149699_1_, int p_149699_2_, int p_149699_3_, int p_149699_4_, EntityPlayer p_149699_5_) - { - super.onBlockClicked(p_149699_1_, p_149699_2_, p_149699_3_, p_149699_4_, p_149699_5_); - } - - /** - * Called when a block is placed using its ItemBlock. Args: World, X, Y, Z, side, hitX, hitY, hitZ, block metadata - * - * @param world - * @param x - * @param y - * @param z - * @param side - * @param hitX - * @param hitY - * @param hitZ - * @param meta - */ - @Override - public int onBlockPlaced(World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int meta) - { - return super.onBlockPlaced(world, x, y, z, side, hitX, hitY, hitZ, meta); - } - - @Override public boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { @@ -220,7 +193,7 @@ public String getUnlocalizedName() @Override @SideOnly(Side.CLIENT) - public void registerBlockIcons(IIconRegister iconRegister) + public void registerBlockIcons(IIconRegister iconRegister) //TODO why this is HERE? { Icons.milkStill = iconRegister.registerIcon(ModInfo.MOD_ID + ":fluid.milk"); Icons.melonJuiceStill = iconRegister.registerIcon(ModInfo.MOD_ID + ":fluid.melonJuiceStill"); @@ -232,44 +205,47 @@ public void registerBlockIcons(IIconRegister iconRegister) @Override public int getLightValue(IBlockAccess world, int x, int y, int z) { - if (getAssociatedTileColorName(world, x, y, z).equals("Glowstone")) + if (getAssociatedTileBackpackType(world, x, y, z) == GLOWSTONE) { return 15; - } else if (world.getTileEntity(x, y, z) != null && world.getTileEntity(x, y, z) instanceof TileAdventureBackpack) + } + else if (world.getTileEntity(x, y, z) != null && world.getTileEntity(x, y, z) instanceof TileAdventureBackpack) { return ((TileAdventureBackpack) world.getTileEntity(x, y, z)).getLuminosity(); - } else + } + else { return 0; } } + @Override public int isProvidingWeakPower(IBlockAccess world, int x, int y, int z, int meta) { - return getAssociatedTileColorName(world, x, y, z).equals("Redstone") ? 15 : 0; + return getAssociatedTileBackpackType(world, x, y, z) == REDSTONE ? 15 : 0; } @Override public boolean canConnectRedstone(IBlockAccess world, int x, int y, int z, int side) { - return getAssociatedTileColorName(world, x, y, z).equals("Redstone"); + return getAssociatedTileBackpackType(world, x, y, z) == REDSTONE; } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) { - - FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.BACKPACK_TILE, world, x, y, z); - return true; + if (!world.isRemote && GeneralReference.isDimensionAllowed(player)) + { + FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.BACKPACK_TILE, world, x, y, z); + return true; + } + return false; } - @Override public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z, EntityPlayer player) { - ItemStack backpack = new ItemStack(ModItems.adventureBackpack, 1); - BackpackNames.setBackpackColorNameFromDamage(backpack, BackpackNames.getBackpackDamageFromName(getAssociatedTileColorName(world, x, y, z))); - return backpack; + return BackpackUtils.createBackpackStack(getAssociatedTileBackpackType(world, x, y, z)); } @Override @@ -332,13 +308,12 @@ public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase p } world.setBlockMetadataWithNotify(x, y, z, dir, 3); createNewTileEntity(world, world.getBlockMetadata(x, y, z)); - } @Override public boolean canPlaceBlockOnSide(World par1World, int par2, int par3, int par4, int side) { - return (ForgeDirection.getOrientation(side) == ForgeDirection.UP); + return ForgeDirection.getOrientation(side) == ForgeDirection.UP; } @Override @@ -359,7 +334,7 @@ public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, i @SideOnly(Side.CLIENT) public IIcon getIcon(int par1, int par2) { - return Blocks.wool.getIcon(par1,par2); + return Blocks.wool.getIcon(par1, par2); } @Override @@ -389,13 +364,14 @@ public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, i if (tile instanceof TileAdventureBackpack && !world.isRemote && player != null) { - if ((player.isSneaking()) ? - ((TileAdventureBackpack) tile).equip(world, player, x, y, z) : - ((TileAdventureBackpack) tile).drop(world, player, x, y, z)) + if ((player.isSneaking()) + ? ((TileAdventureBackpack) tile).equip(world, player, x, y, z) + : ((TileAdventureBackpack) tile).drop(world, player, x, y, z)) { return world.func_147480_a(x, y, z, false); } - } else + } + else { return world.func_147480_a(x, y, z, false); } @@ -430,8 +406,6 @@ public void breakBlock(World world, int x, int y, int z, Block block, int meta) world.spawnEntityInWorld(droppedItem); } } - - } super.breakBlock(world, x, y, z, world.getBlock(x, y, z), meta); @@ -456,12 +430,14 @@ public boolean canDropFromExplosion(Explosion p_149659_1_) } @Override - public void onBlockDestroyedByExplosion(World world, int x, int y, int z, Explosion explosion) { + public void onBlockDestroyedByExplosion(World world, int x, int y, int z, Explosion explosion) + { world.func_147480_a(x, y, z, false); } @Override - public void onBlockExploded(World world, int x, int y, int z, Explosion explosion) { + public void onBlockExploded(World world, int x, int y, int z, Explosion explosion) + { //DO NOTHING } } diff --git a/src/main/java/com/darkona/adventurebackpack/block/BlockCampFire.java b/src/main/java/com/darkona/adventurebackpack/block/BlockCampFire.java index 75987ede..a9879573 100644 --- a/src/main/java/com/darkona/adventurebackpack/block/BlockCampFire.java +++ b/src/main/java/com/darkona/adventurebackpack/block/BlockCampFire.java @@ -1,23 +1,23 @@ package com.darkona.adventurebackpack.block; -import com.darkona.adventurebackpack.CreativeTabAB; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.Utils; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.Random; + import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; -import java.util.Random; +import com.darkona.adventurebackpack.CreativeTabAB; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.util.CoordsUtils; /** * Created on 05/01/2015 @@ -32,18 +32,7 @@ public BlockCampFire() { super(Material.rock); this.setTickRandomly(true); - this.setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB); - - } - - private void func_149978_e() - { - this.setBlockBounds(0.2F, 0.0F, 0.2F, 0.8F, 0.15F, 0.8F); - } - - private void blockBoundsForRender() - { - this.func_149978_e(); + this.setCreativeTab(CreativeTabAB.TAB_AB); } @Override @@ -77,9 +66,6 @@ public boolean isOpaqueCube() return false; } - /** - * If this block doesn't render as an ordinary block it will return False (examples: signs, buttons, stairs, etc) - */ @Override public boolean renderAsNormalBlock() { @@ -98,18 +84,12 @@ public boolean isNormalCube() return false; } - /** - * Indicate if a material is a normal solid opaque cube - */ @Override public boolean isBlockNormalCube() { return false; } - /** - * A randomly called display update to be able to add particles or other items for display - */ @SideOnly(Side.CLIENT) @Override public void randomDisplayTick(World world, int posX, int posY, int posZ, Random rnd) @@ -126,7 +106,6 @@ public void randomDisplayTick(World world, int posX, int posY, int posZ, Random //world.spawnParticle("flame", posX+Math.sin(i/4), posY, posZ+Math.cos(i/4), 0.0D, 0.0D, 0.0D); world.spawnParticle("flame", rndX, rndY + 0.16, rndZ, 0.0D, 0.0D, 0.0D); } - } @Override @@ -153,65 +132,18 @@ public void setBlockBoundsBasedOnState(IBlockAccess blockAccess, int x, int y, i this.setBlockBounds(0.2F, 0.0F, 0.2F, 0.8F, 0.15F, 0.8F); } - /** - * Returns a bounding box from the pool of bounding boxes (this means this box can change after the pool has been - * cleared to be reused) - * - * @param p_149668_1_ - * @param p_149668_2_ - * @param p_149668_3_ - * @param p_149668_4_ - */ - @Override - public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_) - { - return super.getCollisionBoundingBoxFromPool(p_149668_1_, p_149668_2_, p_149668_3_, p_149668_4_); - } - - /** - * Returns the bounding box of the wired rectangular prism to render. - * - * @param p_149633_1_ - * @param p_149633_2_ - * @param p_149633_3_ - * @param p_149633_4_ - */ - @Override - public AxisAlignedBB getSelectedBoundingBoxFromPool(World p_149633_1_, int p_149633_2_, int p_149633_3_, int p_149633_4_) - { - return super.getSelectedBoundingBoxFromPool(p_149633_1_, p_149633_2_, p_149633_3_, p_149633_4_); - } - @Override public IIcon getIcon(IBlockAccess p_149673_1_, int p_149673_2_, int p_149673_3_, int p_149673_4_, int p_149673_5_) { return icon; } - /** - * Gets the block's texture. Args: side, meta - * - * @param p_149691_1_ - * @param p_149691_2_ - */ @Override public IIcon getIcon(int p_149691_1_, int p_149691_2_) { return icon; } - /** - * Determines if this block is classified as a Bed, Allowing - * players to sleep in it, though the block has to specifically - * perform the sleeping functionality in it's activated event. - * - * @param world The current world - * @param x X Position - * @param y Y Position - * @param z Z Position - * @param player The player or camera entity, null in some cases. - * @return True to treat this as a bed - */ @Override public boolean isBed(IBlockAccess world, int x, int y, int z, EntityLivingBase player) { @@ -223,11 +155,11 @@ public ChunkCoordinates getBedSpawnPosition(IBlockAccess world, int x, int y, in { for (int i = y - 5; i <= y + 5; i++) { - ChunkCoordinates spawn = Utils.getNearestEmptyChunkCoordinatesSpiral(world, x, z, x, i, z, 8, true, 1, (byte) 0, true); + ChunkCoordinates spawn = CoordsUtils.getNearestEmptyChunkCoordinatesSpiral(world, x, z, x, i, z, 8, true, 1, (byte) 0, true); if (spawn != null) { - return spawn; + return spawn; } } return null; diff --git a/src/main/java/com/darkona/adventurebackpack/block/BlockSleepingBag.java b/src/main/java/com/darkona/adventurebackpack/block/BlockSleepingBag.java index 64545a26..47c0fcdf 100644 --- a/src/main/java/com/darkona/adventurebackpack/block/BlockSleepingBag.java +++ b/src/main/java/com/darkona/adventurebackpack/block/BlockSleepingBag.java @@ -1,12 +1,8 @@ package com.darkona.adventurebackpack.block; -import com.darkona.adventurebackpack.init.ModBlocks; -import com.darkona.adventurebackpack.playerProperties.BackpackProperty; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Resources; -import com.darkona.adventurebackpack.util.Utils; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.Iterator; +import java.util.Random; + import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; import net.minecraft.block.material.Material; @@ -16,6 +12,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.Item; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.Direction; @@ -24,10 +21,17 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -import net.minecraft.world.chunk.IChunkProvider; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; -import java.util.Iterator; -import java.util.Random; +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.init.ModBlocks; +import com.darkona.adventurebackpack.inventory.InventoryBackpack; +import com.darkona.adventurebackpack.playerProperties.BackpackProperty; +import com.darkona.adventurebackpack.util.CoordsUtils; +import com.darkona.adventurebackpack.util.LogHelper; +import com.darkona.adventurebackpack.util.Resources; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 14/10/2014 @@ -36,8 +40,12 @@ */ public class BlockSleepingBag extends BlockDirectional { + private static final int[][] footBlockToHeadBlockMap = new int[][]{{0, 1}, {-1, 0}, {0, -1}, {1, 0}}; - public static final int[][] footBlockToHeadBlockMap = new int[][]{{0, 1}, {-1, 0}, {0, -1}, {1, 0}}; + private static final String TAG_STORED_SPAWN = "storedSpawn"; + private static final String TAG_SPAWN_POS_X = "posX"; + private static final String TAG_SPAWN_POS_Y = "posY"; + private static final String TAG_SPAWN_POS_Z = "posZ"; @SideOnly(Side.CLIENT) private IIcon[] endIcons; @@ -53,23 +61,19 @@ public BlockSleepingBag() setBlockName(getUnlocalizedName()); } - + @Override @SideOnly(Side.CLIENT) protected String getTextureName() { return this.textureName == null ? "MISSING_ICON_BLOCK_" + getIdFromBlock(this) + "_" + getUnlocalizedName() : this.textureName; } - /** - * Returns the unlocalized name of the block with "tile." appended to the front. - */ @Override public String getUnlocalizedName() { return "blockSleepingBag"; } - private void func_149978_e() { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.1F, 1.0F); @@ -78,31 +82,75 @@ private void func_149978_e() /** * Returns whether or not this bed block is the head of the bed. */ - - public static boolean isBlockHeadOfBed(int meta) + private static boolean isBlockHeadOfBed(int meta) { return (meta & 8) != 0; } - public static ChunkCoordinates verifyRespawnCoordinatesOnBlock(World world, ChunkCoordinates chunkCoordinates, boolean forced) + public static boolean isSleepingInPortableBag(EntityPlayer player) + { + return Wearing.isWearingBackpack(player) + && Wearing.getWearingBackpackInv(player).getExtendedProperties().hasKey(Constants.TAG_SLEEPING_IN_BAG); + } + + public static void packPortableSleepingBag(EntityPlayer player) + { + if (isSleepingInPortableBag(player)) + { + InventoryBackpack inv = Wearing.getWearingBackpackInv(player); + inv.removeSleepingBag(player.worldObj); + inv.getExtendedProperties().removeTag(Constants.TAG_SLEEPING_IN_BAG); + } + } + + public static void storeOriginalSpawn(EntityPlayer player, NBTTagCompound tag) { - IChunkProvider ichunkprovider = world.getChunkProvider(); - ichunkprovider.loadChunk(chunkCoordinates.posX - 3 >> 4, chunkCoordinates.posZ - 3 >> 4); - ichunkprovider.loadChunk(chunkCoordinates.posX + 3 >> 4, chunkCoordinates.posZ - 3 >> 4); - ichunkprovider.loadChunk(chunkCoordinates.posX - 3 >> 4, chunkCoordinates.posZ + 3 >> 4); - ichunkprovider.loadChunk(chunkCoordinates.posX + 3 >> 4, chunkCoordinates.posZ + 3 >> 4); + ChunkCoordinates spawn = player.getBedLocation(player.worldObj.provider.dimensionId); + if (spawn != null) + { + NBTTagCompound storedSpawn = new NBTTagCompound(); + storedSpawn.setInteger(TAG_SPAWN_POS_X, spawn.posX); + storedSpawn.setInteger(TAG_SPAWN_POS_Y, spawn.posY); + storedSpawn.setInteger(TAG_SPAWN_POS_Z, spawn.posZ); + tag.setTag(TAG_STORED_SPAWN, storedSpawn); + LogHelper.info("Stored spawn data for " + player.getDisplayName() + ": " + spawn.toString() + + " dimID: " + player.worldObj.provider.dimensionId); + } + else + { + LogHelper.warn("Cannot store spawn data for " + player.getDisplayName()); + } + } - if (world.getBlock(chunkCoordinates.posX, chunkCoordinates.posY, chunkCoordinates.posZ).isBed(world, chunkCoordinates.posX, chunkCoordinates.posY, chunkCoordinates.posZ, null)) + public static void restoreOriginalSpawn(EntityPlayer player, NBTTagCompound tag) + { + if (tag.hasKey(TAG_STORED_SPAWN)) + { + NBTTagCompound storedSpawn = tag.getCompoundTag(TAG_STORED_SPAWN); + ChunkCoordinates coords = new ChunkCoordinates( + storedSpawn.getInteger(TAG_SPAWN_POS_X), + storedSpawn.getInteger(TAG_SPAWN_POS_Y), + storedSpawn.getInteger(TAG_SPAWN_POS_Z)); + player.setSpawnChunk(coords, false, player.worldObj.provider.dimensionId); + tag.removeTag(TAG_STORED_SPAWN); + LogHelper.info("Restored spawn data for " + player.getDisplayName() + ": " + coords.toString() + + " dimID: " + player.worldObj.provider.dimensionId); + } + else { - ChunkCoordinates newChunkCoords = world.getBlock(chunkCoordinates.posX, chunkCoordinates.posY, chunkCoordinates.posZ).getBedSpawnPosition(world, chunkCoordinates.posX, chunkCoordinates.posY, chunkCoordinates.posZ, null); - return newChunkCoords; + LogHelper.warn("No spawn data to restore for " + player.getDisplayName()); } + } + + public void onPortableBlockActivated(World world, EntityPlayer player, int cX, int cY, int cZ) + { + if (world.isRemote) + return; + if (!isSleepingInPortableBag(player)) + return; - Material material = world.getBlock(chunkCoordinates.posX, chunkCoordinates.posY, chunkCoordinates.posZ).getMaterial(); - Material material1 = world.getBlock(chunkCoordinates.posX, chunkCoordinates.posY + 1, chunkCoordinates.posZ).getMaterial(); - boolean flag1 = (!material.isSolid()) && (!material.isLiquid()); - boolean flag2 = (!material1.isSolid()) && (!material1.isLiquid()); - return (forced) && (flag1) && (flag2) ? chunkCoordinates : null; + if (!onBlockActivated(world, cX, cY, cZ, player, 1, 0f, 0f, 0f)) + packPortableSleepingBag(player); } @Override @@ -111,7 +159,8 @@ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer p if (world.isRemote) { return true; - } else + } + else { int meta = world.getBlockMetadata(x, y, z); @@ -123,7 +172,7 @@ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer p if (world.getBlock(x, y, z) != this) { - return true; + return false; } meta = world.getBlockMetadata(x, y, z); @@ -154,7 +203,7 @@ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer p if (entityplayer1 != null) { player.addChatComponentMessage(new ChatComponentTranslation("tile.bed.occupied", new Object[0])); - return true; + return false; } setBedOccupied(world, x, y, z, false); @@ -167,28 +216,40 @@ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer p setBedOccupied(world, x, y, z, true); //This is so the wake up event can detect it. It fires before the player wakes up. //and the bed location isn't set until then, normally. - player.setSpawnChunk(new ChunkCoordinates(x,y,z),true,player.dimension); - LogHelper.info("Looking for a campfire nearby..."); - ChunkCoordinates campfire = Utils.findBlock3D(world, x, y, z, ModBlocks.blockCampFire, 8, 2); - if (campfire != null) + + if (isSleepingInPortableBag(player)) + { + storeOriginalSpawn(player, Wearing.getWearingBackpackInv(player).getExtendedProperties()); + player.setSpawnChunk(new ChunkCoordinates(x, y, z), true, player.dimension); + } + else { - LogHelper.info("Campfire Found, saving coordinates. " + LogHelper.print3DCoords(campfire)); - BackpackProperty.get(player).setCampFire(campfire); + player.setSpawnChunk(new ChunkCoordinates(x, y, z), true, player.dimension); + LogHelper.info("Looking for a campfire nearby..."); + ChunkCoordinates campfire = CoordsUtils.findBlock3D(world, x, y, z, ModBlocks.blockCampFire, 8, 2); + if (campfire != null) + { + LogHelper.info("Campfire Found, saving coordinates. " + campfire.toString()); + BackpackProperty.get(player).setCampFire(campfire); + } } return true; - } else + } + else { if (enumstatus == EntityPlayer.EnumStatus.NOT_POSSIBLE_NOW) { player.addChatComponentMessage(new ChatComponentTranslation("tile.bed.noSleep", new Object[0])); - } else if (enumstatus == EntityPlayer.EnumStatus.NOT_SAFE) + } + else if (enumstatus == EntityPlayer.EnumStatus.NOT_SAFE) { player.addChatComponentMessage(new ChatComponentTranslation("tile.bed.notSafe", new Object[0])); } - return true; + return false; } - } else + } + else { double d2 = (double) x + 0.5D; double d0 = (double) y + 0.5D; @@ -207,19 +268,21 @@ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer p } world.newExplosion((Entity) null, (double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F), 5.0F, true, true); - return true; + + return false; } } } - public static void setBedOccupied(World world, int x, int y, int z, boolean flag) + private static void setBedOccupied(World world, int x, int y, int z, boolean flag) { int l = world.getBlockMetadata(x, y, z); if (flag) { l |= 4; - } else + } + else { l &= -5; } @@ -227,11 +290,12 @@ public static void setBedOccupied(World world, int x, int y, int z, boolean flag world.setBlockMetadataWithNotify(x, y, z, l, 4); } - public static boolean isBedOccupied(int meta) + private static boolean isBedOccupied(int meta) { return (meta & 4) != 0; } + @Override public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { int meta = world.getBlockMetadata(x, y, z); @@ -243,7 +307,8 @@ public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { world.setBlockToAir(x, y, z); } - } else if (world.getBlock(x + footBlockToHeadBlockMap[dir][0], y, z + footBlockToHeadBlockMap[dir][1]) != this) + } + else if (world.getBlock(x + footBlockToHeadBlockMap[dir][0], y, z + footBlockToHeadBlockMap[dir][1]) != this) { world.setBlockToAir(x, y, z); @@ -254,6 +319,7 @@ public void onNeighborBlockChange(World world, int x, int y, int z, Block block) } } + @Override public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z) { this.blockBoundsForRender(); @@ -264,43 +330,12 @@ private void blockBoundsForRender() this.func_149978_e(); } + @Override public Item getItemDropped(int p_149650_1_, Random p_149650_2_, int p_149650_3_) { return null; } - public static ChunkCoordinates func_149977_a(World world, int x, int y, int z, int whatever) - { - int meta = world.getBlockMetadata(x, y, z); - int dir = BlockDirectional.getDirection(meta); - - for (int k1 = 0; k1 <= 1; ++k1) - { - int l1 = x - footBlockToHeadBlockMap[dir][0] * k1 - 1; - int i2 = z - footBlockToHeadBlockMap[dir][1] * k1 - 1; - int j2 = l1 + 2; - int k2 = i2 + 2; - - for (int l2 = l1; l2 <= j2; ++l2) - { - for (int i3 = i2; i3 <= k2; ++i3) - { - if (World.doesBlockHaveSolidTopSurface(world, l2, y - 1, i3) && !world.getBlock(l2, y, i3).getMaterial().isOpaque() && !world.getBlock(l2, y + 1, i3).getMaterial().isOpaque()) - { - if (whatever <= 0) - { - return new ChunkCoordinates(l2, y, i3); - } - - --whatever; - } - } - } - } - - return null; - } - @Override public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityPlayer player) { @@ -317,7 +352,6 @@ public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityP } } - @Override public void onBlockDestroyedByExplosion(World world, int x, int y, int z, Explosion boom) { @@ -327,6 +361,7 @@ public void onBlockDestroyedByExplosion(World world, int x, int y, int z, Explos @Override public void onBlockDestroyedByPlayer(World world, int x, int y, int z, int meta) { + //TODO make it work if player destroyed head block of sleeping bag (so backpack 1 more tile away) //LogHelper.info("onBlockDestroyedByPlayer() : BlockSleepingBag"); int direction = getDirection(meta); int tileZ = z; @@ -360,13 +395,15 @@ public boolean isBed(IBlockAccess world, int x, int y, int z, EntityLivingBase p return true; } + @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { if (side == 0) { return Blocks.planks.getBlockTextureFromSide(side); - } else + } + else { int k = getDirection(meta); int l = Direction.bedDirection[k][side]; @@ -375,6 +412,7 @@ public IIcon getIcon(int side, int meta) } } + @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister iconRegister) { @@ -394,6 +432,7 @@ public void registerBlockIcons(IIconRegister iconRegister) }; } + @Override public int getRenderType() { return 14; @@ -405,40 +444,21 @@ public boolean isNormalCube() return false; } - /** - * Indicate if a material is a normal solid opaque cube - */ @Override public boolean isBlockNormalCube() { return false; } - /** - * If this block doesn't render as an ordinary block it will return False (examples: signs, buttons, stairs, etc) - */ @Override public boolean renderAsNormalBlock() { return false; } - /** - * Is this block (a) opaque and (b) a full 1m cube? This determines whether or not to render the shared face of two - * adjacent blocks and also whether the player can attach torches, redstone wire, etc to this block. - */ @Override public boolean isOpaqueCube() { return false; } - - /** - * Returns if this block is collidable (only used by Fire). Args: x, y, z - */ - @Override - public boolean isCollidable() - { - return super.isCollidable(); - } } diff --git a/src/main/java/com/darkona/adventurebackpack/block/TileAdventure.java b/src/main/java/com/darkona/adventurebackpack/block/TileAdventure.java new file mode 100644 index 00000000..089ea259 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/block/TileAdventure.java @@ -0,0 +1,205 @@ +package com.darkona.adventurebackpack.block; + +import javax.annotation.Nullable; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; + +import com.darkona.adventurebackpack.inventory.IInventoryTanks; + +import static com.darkona.adventurebackpack.common.Constants.TAG_SLOT; + +/** + * Created on 26.02.2018 + * + * @author Ugachaga + */ +@SuppressWarnings("WeakerAccess") +abstract class TileAdventure extends TileEntity implements IInventoryTanks +{ + // when porting to java 8+ most this methods should move to IInventoryTanks + + protected final ItemStack[] inventory; + + protected TileAdventure(int inventorySize) + { + this.inventory = new ItemStack[inventorySize]; + } + + @Override + public int getSizeInventory() + { + return inventory.length; + } + + @Override + public ItemStack getStackInSlot(int slot) + { + return inventory[slot]; + } + + @Nullable + @Override + public ItemStack decrStackSize(int slot, int quantity) + { + ItemStack stack = getStackInSlot(slot); + if (stack != null) + { + if (stack.stackSize <= quantity) + { + setInventorySlotContents(slot, null); + } + else + { + stack = stack.splitStack(quantity); + dirtyInventory(); + } + } + return stack; + } + + @Nullable + @Override + public ItemStack getStackInSlotOnClosing(int slot) + { + for (int s : getSlotsOnClosing()) + if (slot == s) + return inventory[slot]; + + return null; + } + + @Override + public void setInventorySlotContents(int slot, @Nullable ItemStack stack) + { + setInventorySlotContentsNoSave(slot, stack); + dirtyInventory(); + } + + @Override + public String getInventoryName() + { + return ""; + } + + @Override + public boolean hasCustomInventoryName() + { + return getInventoryName() != null && !getInventoryName().isEmpty(); + } + + @Override + public int getInventoryStackLimit() + { + return 64; + } + + // we have to inherit markDirty() implemented in TileEntity.class + + @Override + public boolean isUseableByPlayer(EntityPlayer player) + { + return worldObj.getTileEntity(xCoord, yCoord, zCoord) == this + && player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) <= 64; + } + + @Override + public void openInventory() + { + // + } + + @Override + public void closeInventory() + { + dirtyInventory(); + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) + { + return false; // override when automation is allowed + } + + @Nullable + @Override + public ItemStack decrStackSizeNoSave(int slot, int quantity) + { + ItemStack stack = getStackInSlot(slot); + if (stack != null) + { + if (stack.stackSize <= quantity) + setInventorySlotContentsNoSave(slot, null); + else + stack = stack.splitStack(quantity); + } + return stack; + } + + @Override + public void setInventorySlotContentsNoSave(int slot, @Nullable ItemStack stack) + { + if (slot >= getSizeInventory()) + return; + + if (stack != null) + { + if (stack.stackSize > getInventoryStackLimit()) + stack.stackSize = getInventoryStackLimit(); + + if (stack.stackSize == 0) + stack = null; + } + + inventory[slot] = stack; + } + + @Override + public void dirtyInventory() + { + updateTankSlots(); + markDirty(); + } + + @Deprecated + @Override + public void dirtyTanks() + { + // if we really want to use it, we have to re-implement it, more efficient way + dirtyInventory(); + } + + protected void setInventoryFromTagList(NBTTagList items) + { + for (int i = 0; i < items.tagCount(); i++) + { + NBTTagCompound item = items.getCompoundTagAt(i); + byte slot = item.getByte(TAG_SLOT); + if (slot >= 0 && slot < getSizeInventory()) + { + inventory[slot] = ItemStack.loadItemStackFromNBT(item); + } + } + } + + protected NBTTagList getInventoryTagList() + { + NBTTagList items = new NBTTagList(); + for (int i = 0; i < getSizeInventory(); i++) + { + ItemStack stack = inventory[i]; + if (stack != null) + { + NBTTagCompound item = new NBTTagCompound(); + item.setByte(TAG_SLOT, (byte) i); + stack.writeToNBT(item); + items.appendTag(item); + } + } + return items; + } + +} diff --git a/src/main/java/com/darkona/adventurebackpack/block/TileAdventureBackpack.java b/src/main/java/com/darkona/adventurebackpack/block/TileAdventureBackpack.java index a8b4e319..e92572d5 100644 --- a/src/main/java/com/darkona/adventurebackpack/block/TileAdventureBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/block/TileAdventureBackpack.java @@ -1,17 +1,8 @@ package com.darkona.adventurebackpack.block; -import com.darkona.adventurebackpack.common.BackpackAbilities; -import com.darkona.adventurebackpack.common.Constants; -import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; -import com.darkona.adventurebackpack.init.ModBlocks; -import com.darkona.adventurebackpack.init.ModItems; -import com.darkona.adventurebackpack.inventory.InventoryActions; -import com.darkona.adventurebackpack.inventory.SlotTool; -import com.darkona.adventurebackpack.item.ItemAdventureBackpack; -import com.darkona.adventurebackpack.util.BackpackUtils; -import net.minecraft.block.Block; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -19,165 +10,83 @@ import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; -import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; -import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.fluids.FluidTank; +import com.darkona.adventurebackpack.common.BackpackAbilities; +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.init.ModBlocks; +import com.darkona.adventurebackpack.inventory.IInventoryBackpack; +import com.darkona.adventurebackpack.inventory.InventoryActions; +import com.darkona.adventurebackpack.inventory.SlotBackpack; +import com.darkona.adventurebackpack.inventory.SlotTool; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.reference.GeneralReference; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.CoordsUtils; +import com.darkona.adventurebackpack.util.Utils; +import com.darkona.adventurebackpack.util.Wearing; + +import static com.darkona.adventurebackpack.common.Constants.BUCKET_IN_LEFT; +import static com.darkona.adventurebackpack.common.Constants.BUCKET_IN_RIGHT; +import static com.darkona.adventurebackpack.common.Constants.BUCKET_OUT_LEFT; +import static com.darkona.adventurebackpack.common.Constants.BUCKET_OUT_RIGHT; +import static com.darkona.adventurebackpack.common.Constants.TAG_DISABLE_CYCLING; +import static com.darkona.adventurebackpack.common.Constants.TAG_DISABLE_NVISION; +import static com.darkona.adventurebackpack.common.Constants.TAG_EXTENDED_COMPOUND; +import static com.darkona.adventurebackpack.common.Constants.TAG_INVENTORY; +import static com.darkona.adventurebackpack.common.Constants.TAG_LEFT_TANK; +import static com.darkona.adventurebackpack.common.Constants.TAG_RIGHT_TANK; +import static com.darkona.adventurebackpack.common.Constants.TAG_TYPE; +import static com.darkona.adventurebackpack.common.Constants.TAG_WEARABLE_COMPOUND; +import static com.darkona.adventurebackpack.common.Constants.TOOL_LOWER; +import static com.darkona.adventurebackpack.common.Constants.TOOL_UPPER; + /** * Created by Darkona on 12/10/2014. */ -public class TileAdventureBackpack extends TileEntity implements IInventoryAdventureBackpack +public class TileAdventureBackpack extends TileAdventure implements IInventoryBackpack, ISidedInventory { + private static final int[] MAIN_INVENTORY_SLOTS = Utils.createSlotArray(0, Constants.INVENTORY_MAIN_SIZE); + + private BackpackTypes type = BackpackTypes.STANDARD; + private FluidTank leftTank = new FluidTank(Constants.BASIC_TANK_CAPACITY); + private FluidTank rightTank = new FluidTank(Constants.BASIC_TANK_CAPACITY); + private NBTTagCompound extendedProperties = new NBTTagCompound(); + + private NBTTagList ench; + private boolean disableCycling; + private boolean disableNVision; + private int lastTime = 0; - public ItemStack[] inventory; - private FluidTank leftTank; - private FluidTank rightTank; - public boolean sleepingBagDeployed; - private boolean special; + private boolean sleepingBagDeployed; private int sbdir; private int sbx; private int sby; private int sbz; - private int checkTime = 0; - private String colorName; - private int lastTime; - private int luminosity; - private NBTTagCompound extendedProperties; - - public int getLuminosity() - { - return luminosity; - } - - public int getLastTime() - { - return lastTime; - } - public void setLastTime(int lastTime) - { - this.lastTime = lastTime; - } - - public NBTTagCompound getExtendedProperties() - { - return extendedProperties; - } - - public void setExtendedProperties(NBTTagCompound extendedProperties) - { - this.extendedProperties = extendedProperties; - } + private int checkTime = 0; + private int luminosity = 0; public TileAdventureBackpack() { - leftTank = new FluidTank(Constants.basicTankCapacity); - rightTank = new FluidTank(Constants.basicTankCapacity); - inventory = new ItemStack[Constants.inventorySize]; - sleepingBagDeployed = false; - setColorName("Standard"); - luminosity = 0; - lastTime = 0; - checkTime = 0; - extendedProperties = new NBTTagCompound(); - } - - public boolean deploySleepingBag(EntityPlayer player, World world, int x, int y, int z, int meta) - { - if (world.isRemote) return false; - Block sleepingBag = ModBlocks.blockSleepingBag; - if (world.setBlock(x, y, z, sleepingBag, meta, 3)) - { - world.playSoundAtEntity(player, Block.soundTypeCloth.func_150496_b(), 0.5f, 1.0f); - sbx = x; - sby = y; - sbz = z; - sbdir = meta; - switch (meta & 3) - { - case 0: - ++z; - break; - case 1: - --x; - break; - case 2: - --z; - break; - case 3: - ++x; - break; - } - sleepingBagDeployed = world.setBlock(x, y, z, sleepingBag, meta + 8, 3); - //LogHelper.info("deploySleepingBag() => SleepingBagDeployed is: " + sleepingBagDeployed); - world.markBlockForUpdate(this.xCoord, this.yCoord, this.zCoord); - return sleepingBagDeployed; - } - return false; - } - - public void setSleepingBagDeployed(boolean state) - { - this.sleepingBagDeployed = state; - } - - public boolean removeSleepingBag(World world) - { - if (sleepingBagDeployed) - { - if (world.getBlock(sbx, sby, sbz) == ModBlocks.blockSleepingBag) - { - world.func_147480_a(sbx, sby, sbz, false); - this.sleepingBagDeployed = false; - markDirty(); - return true; - } - } else - { - this.sleepingBagDeployed = false; - markDirty(); - } - return false; - } - - //=====================================================GETTERS====================================================// - - public String getColorName() - { - return colorName; + super(Constants.INVENTORY_SIZE); } @Override - public ItemStack[] getInventory() + public BackpackTypes getType() { - return this.inventory; + return type; } @Override - public int getSizeInventory() - { - return inventory.length; - } - - @Override - public ItemStack getStackInSlot(int slot) - { - return inventory[slot]; - } - - @Override - public String getInventoryName() - { - return null; - } - - @Override - public int getInventoryStackLimit() + public ItemStack[] getInventory() { - return 64; + return inventory; } @Override @@ -192,38 +101,24 @@ public FluidTank getRightTank() return rightTank; } - //=====================================================SETTERS====================================================// - - - public void setColorName(String string) - { - this.colorName = string; - } - - //=====================================================BOOLEANS===================================================// @Override - public boolean hasCustomInventoryName() + public FluidTank[] getTanksArray() { - return false; + return new FluidTank[]{leftTank, rightTank}; } @Override - public boolean isUseableByPlayer(EntityPlayer player) + public int[] getSlotsOnClosing() { - return worldObj.getTileEntity(xCoord, yCoord, zCoord) == this && player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) <= 64; + return new int[]{BUCKET_IN_LEFT, BUCKET_IN_RIGHT, BUCKET_OUT_LEFT, BUCKET_OUT_RIGHT}; } - public boolean isSBDeployed() - { - return this.sleepingBagDeployed; - } - - public boolean isSpecial() + @Override + public NBTTagCompound getExtendedProperties() { - return special; + return extendedProperties; } - //=======================================================NBT======================================================// @Override public void readFromNBT(NBTTagCompound compound) { @@ -237,6 +132,26 @@ public void readFromNBT(NBTTagCompound compound) luminosity = compound.getInteger("lumen"); } + @Override + public void loadFromNBT(NBTTagCompound compound) + { + if (compound.hasKey("backpackData")) + convertFromOldNBTFormat(compound); + + if (compound.hasKey("ench")) + ench = compound.getTagList("ench", NBT.TAG_COMPOUND); + + NBTTagCompound backpackTag = compound.getCompoundTag(TAG_WEARABLE_COMPOUND); + type = BackpackTypes.getType(backpackTag.getByte(TAG_TYPE)); + setInventoryFromTagList(backpackTag.getTagList(TAG_INVENTORY, NBT.TAG_COMPOUND)); + leftTank.readFromNBT(backpackTag.getCompoundTag(TAG_LEFT_TANK)); + rightTank.readFromNBT(backpackTag.getCompoundTag(TAG_RIGHT_TANK)); + extendedProperties = backpackTag.getCompoundTag(TAG_EXTENDED_COMPOUND); + disableCycling = backpackTag.getBoolean(TAG_DISABLE_CYCLING); + disableNVision = backpackTag.getBoolean(TAG_DISABLE_NVISION); + lastTime = backpackTag.getInteger("lastTime"); + } + @Override public void writeToNBT(NBTTagCompound compound) { @@ -246,199 +161,203 @@ public void writeToNBT(NBTTagCompound compound) compound.setInteger("sbx", sbx); compound.setInteger("sby", sby); compound.setInteger("sbz", sbz); - compound.setInteger("lumen", luminosity); compound.setInteger("sbdir", sbdir); + compound.setInteger("lumen", luminosity); } @Override - public void loadFromNBT(NBTTagCompound compound) + public void saveToNBT(NBTTagCompound compound) { - if(compound.hasKey("backpackData")) - { - NBTTagCompound backpackData = compound.getCompoundTag("backpackData"); - NBTTagList items = backpackData.getTagList("ABPItems", net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND); - for (int i = 0; i < items.tagCount(); i++) - { - NBTTagCompound item = items.getCompoundTagAt(i); - byte slot = item.getByte("Slot"); - if (slot >= 0 && slot < inventory.length) - { - inventory[slot] = ItemStack.loadItemStackFromNBT(item); - } - } - leftTank.readFromNBT(backpackData.getCompoundTag("leftTank")); - rightTank.readFromNBT(backpackData.getCompoundTag("rightTank")); - colorName = backpackData.getString("colorName"); - lastTime = backpackData.getInteger("lastTime"); - special = backpackData.getBoolean("special"); - extendedProperties = backpackData.getCompoundTag("extended"); - } + if (ench != null) + compound.setTag("ench", ench); + + NBTTagCompound backpackTag = new NBTTagCompound(); + backpackTag.setByte(TAG_TYPE, BackpackTypes.getMeta(type)); + backpackTag.setTag(TAG_INVENTORY, getInventoryTagList()); + backpackTag.setTag(TAG_RIGHT_TANK, rightTank.writeToNBT(new NBTTagCompound())); + backpackTag.setTag(TAG_LEFT_TANK, leftTank.writeToNBT(new NBTTagCompound())); + backpackTag.setTag(TAG_EXTENDED_COMPOUND, extendedProperties); + backpackTag.setBoolean(TAG_DISABLE_CYCLING, disableCycling); + backpackTag.setBoolean(TAG_DISABLE_NVISION, disableNVision); + backpackTag.setInteger("lastTime", lastTime); + + compound.setTag(TAG_WEARABLE_COMPOUND, backpackTag); } @Override - public void saveToNBT(NBTTagCompound compound) + public boolean updateTankSlots() { - NBTTagCompound backpackData = new NBTTagCompound(); - NBTTagList items = new NBTTagList(); - for (int i = 0; i < inventory.length; i++) - { - ItemStack stack = inventory[i]; - if (stack != null) - { - NBTTagCompound item = new NBTTagCompound(); - item.setByte("Slot", (byte) i); - stack.writeToNBT(item); - items.appendTag(item); - } - } - backpackData.setTag("ABPItems", items); - backpackData.setString("colorName", colorName); - backpackData.setInteger("lastTime", lastTime); - backpackData.setBoolean("special", BackpackAbilities.hasAbility(colorName)); - backpackData.setTag("extended", extendedProperties); - backpackData.setTag("rightTank", rightTank.writeToNBT(new NBTTagCompound())); - backpackData.setTag("leftTank", leftTank.writeToNBT(new NBTTagCompound())); - - compound.setTag("backpackData",backpackData); + boolean changesMade = false; + while (InventoryActions.transferContainerTank(this, getLeftTank(), BUCKET_IN_LEFT)) + changesMade = true; + while (InventoryActions.transferContainerTank(this, getRightTank(), BUCKET_IN_RIGHT)) + changesMade = true; + return changesMade; } + @Deprecated @Override - public FluidTank[] getTanksArray() + public void dirtyExtended() { - FluidTank[] tanks = {leftTank,rightTank}; - return tanks; + // if we really want to use it, we have to re-implement it, more efficient way + dirtyInventory(); } - //====================================================INVENTORY===================================================// + @Deprecated @Override - public void openInventory() + public void dirtyTime() { + // if we really want to use it, we have to re-implement it, more efficient way + dirtyInventory(); } @Override - public void closeInventory() + public int getLastTime() { - markDirty(); + return lastTime; } @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) + public void setLastTime(int lastTime) { - if (stack.getItem() instanceof ItemAdventureBackpack || Block.getBlockFromItem(stack.getItem()) instanceof BlockAdventureBackpack) - { - return false; - } - if (slot == 6 || slot == 8) - { - return FluidContainerRegistry.isContainer(stack); - } - - return !(slot == 0 || slot == 3) || SlotTool.isValidTool(stack); + this.lastTime = lastTime; } @Override - public ItemStack decrStackSize(int i, int count) + public boolean hasItem(Item item) { - ItemStack itemstack = getStackInSlot(i); - - if (itemstack != null) - { - if (itemstack.stackSize <= count) - { - setInventorySlotContents(i, null); - } else - { - itemstack = itemstack.splitStack(count); - } - } - markDirty(); - return itemstack; + return InventoryActions.hasItem(this, item); } @Override - public ItemStack getStackInSlotOnClosing(int slot) + public void consumeInventoryItem(Item item) { - if (slot == Constants.bucketInLeft || slot == Constants.bucketInRight || slot == Constants.bucketOutLeft || slot == Constants.bucketOutRight) - { - return inventory[slot]; - } - return null; + InventoryActions.consumeItemInInventory(this, item); } - @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + // Logic: from tile to item + public boolean equip(World world, EntityPlayer player, int x, int y, int z) { + removeSleepingBag(world); + + ItemStack stacky = BackpackUtils.createBackpackStack(type); + transferCompoundToStack(stacky); - inventory[i] = itemstack; - if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) + if (BackpackUtils.equipWearable(stacky, player) != BackpackUtils.Reasons.SUCCESSFUL) { - itemstack.stackSize = getInventoryStackLimit(); + Wearing.WearableType wtype = Wearing.getWearingWearableType(player); + if (wtype != Wearing.WearableType.UNKNOWN) + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.already.equipped." + wtype.name().toLowerCase())); + + if (!player.inventory.addItemStackToInventory(stacky)) + return drop(world, player, x, y, z); } - markDirty(); + return true; } - @Override - public void markDirty() + public boolean drop(World world, EntityPlayer player, int x, int y, int z) { - for (int i = 0; i < inventory.length; i++) - { - if (i == Constants.bucketInLeft && inventory[i] != null) - { - updateTankSlots(getLeftTank(), i); - } + removeSleepingBag(world); - if (i == Constants.bucketInRight && inventory[i] != null) - { - updateTankSlots(getRightTank(), i); - } - } - super.markDirty(); + if (player.capabilities.isCreativeMode) + return true; + + ItemStack stacky = BackpackUtils.createBackpackStack(type); + transferCompoundToStack(stacky); + + float spawnX = x + world.rand.nextFloat(); + float spawnY = y + world.rand.nextFloat(); + float spawnZ = z + world.rand.nextFloat(); + EntityItem droppedItem = new EntityItem(world, spawnX, spawnY, spawnZ, stacky); + + float mult = 0.05F; + droppedItem.motionX = (-0.3F + world.rand.nextFloat()) * mult; + droppedItem.motionY = (3 + world.rand.nextFloat()) * mult; + droppedItem.motionZ = (-0.3F + world.rand.nextFloat()) * mult; + + return world.spawnEntityInWorld(droppedItem); } + private void transferCompoundToStack(ItemStack stack) + { + NBTTagCompound compound = new NBTTagCompound(); + saveToNBT(compound); + stack.setTagCompound(compound); + } + + // Sleeping Bag @Override - public void setInventorySlotContentsNoSave(int slot, ItemStack itemstack) + public boolean isSleepingBagDeployed() + { + return this.sleepingBagDeployed; + } + + public void setSleepingBagDeployed(boolean state) { - if (slot > inventory.length) return; - inventory[slot] = itemstack; - if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) + this.sleepingBagDeployed = state; + } + + public boolean deploySleepingBag(EntityPlayer player, World world, int meta, int cX, int cY, int cZ) + { + if (world.isRemote) + return false; + + sleepingBagDeployed = CoordsUtils.spawnSleepingBag(player, world, meta, cX, cY, cZ); + if (sleepingBagDeployed) { - itemstack.stackSize = getInventoryStackLimit(); + sbx = cX; + sby = cY; + sbz = cZ; + sbdir = meta; + world.markBlockForUpdate(this.xCoord, this.yCoord, this.zCoord); } + return sleepingBagDeployed; } + public void removeSleepingBag(World world) + { + if (sleepingBagDeployed && world.getBlock(sbx, sby, sbz) == ModBlocks.blockSleepingBag) + world.func_147480_a(sbx, sby, sbz, false); + + sleepingBagDeployed = false; + markDirty(); + } + + // Automation @Override - public ItemStack decrStackSizeNoSave(int slot, int amount) + public int[] getAccessibleSlotsFromSide(int side) { - ItemStack stack = getStackInSlot(slot); + if (GeneralReference.isDimensionAllowed(worldObj.provider.dimensionId)) + return MAIN_INVENTORY_SLOTS.clone(); - if (stack != null) - { - if (stack.stackSize <= amount) - { - setInventorySlotContentsNoSave(slot, null); - } else - { - stack = stack.splitStack(amount); - } - } - return stack; + return null; } @Override - public boolean hasItem(Item item) + public boolean canInsertItem(int slot, ItemStack item, int side) { - return InventoryActions.hasItem(this, item); + return this.isItemValidForSlot(slot, item); } @Override - public void consumeInventoryItem(Item item) + public boolean isItemValidForSlot(int slot, ItemStack stack) { - InventoryActions.consumeItemInInventory(this, item); + if (slot <= Constants.END_OF_INVENTORY) + return SlotBackpack.isValidItem(stack); + + return (slot == TOOL_UPPER || slot == TOOL_LOWER) && SlotTool.isValidTool(stack); } - //===================================================TILE ENTITY==================================================// + @Override + public boolean canExtractItem(int slot, ItemStack item, int side) + { + return true; + } - //SEND SYNC PACKET + /** + * Send sync packet. This is necessary for the TileEntity to load the nbt as soon as it is loaded + * and be rendered properly when the custom renderer reads it + */ @Override public Packet getDescriptionPacket() { @@ -447,8 +366,10 @@ public Packet getDescriptionPacket() return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 0, compound); } - //RECEIV SYNC PACKET - This is necessary for the TileEntity to load the nbt as soon as it is loaded and be rendered - //properly when the custom renderer reads it + /** + * Receive sync packet. This is necessary for the TileEntity to load the nbt as soon as it is loaded + * and be rendered properly when the custom renderer reads it + */ @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { @@ -456,13 +377,14 @@ public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) readFromNBT(pkt.func_148857_g()); } + // Ticking at World.updateEntities() @Override public void updateEntity() { - //Execute this backpack's ability. No, seriously. You might not infer that from the code. Just sayin' - if (isSpecial() && !colorName.isEmpty()) + //Execute this backpack's TILE ability. No, seriously. You might not infer that from the code. Just sayin' + if (ConfigHandler.backpackAbilities && BackpackTypes.hasProperty(type, BackpackTypes.Props.TILE)) { - BackpackAbilities.backpackAbilities.executeAbility(null, this.worldObj, this); + BackpackAbilities.backpackAbilities.executeTileAbility(this.worldObj, this); } //Check for backpack luminosity and a deployed sleeping bag, just in case because i'm super paranoid. @@ -478,130 +400,38 @@ public void updateEntity() worldObj.setBlock(xCoord, yCoord, zCoord, ModBlocks.blockBackpack, meta, 3); worldObj.setLightValue(EnumSkyBlock.Block, xCoord, yCoord, zCoord, luminosity); } - if (worldObj.getBlock(sbx, sby, sbz) != ModBlocks.blockSleepingBag) - { - sleepingBagDeployed = false; - } - checkTime = 20; - } else - { - checkTime--; - } - } - public void updateTankSlots(FluidTank tank, int slotIn) - { - InventoryActions.transferContainerTank(this, tank, slotIn); - } + if (sleepingBagDeployed && worldObj.getBlock(sbx, sby, sbz) != ModBlocks.blockSleepingBag) + sleepingBagDeployed = false; - @Override - public void saveTanks(NBTTagCompound compound) - { - NBTTagCompound backpackData; - if(compound.hasKey("backpackData")) - { - backpackData = compound.getCompoundTag("backpackData"); - }else{ - backpackData = new NBTTagCompound(); + checkTime = 20; } - backpackData.setTag("rightTank", rightTank.writeToNBT(new NBTTagCompound())); - backpackData.setTag("leftTank", leftTank.writeToNBT(new NBTTagCompound())); - compound.setTag("backpackData",backpackData); - } - - @Override - public void loadTanks(NBTTagCompound compound) - { - if(compound.hasKey("backpackData")) + else { - NBTTagCompound backpackData = compound.getCompoundTag("backpackData"); - leftTank.readFromNBT(backpackData.getCompoundTag("leftTank")); - rightTank.readFromNBT(backpackData.getCompoundTag("rightTank")); - } - } - - @Override - public TileAdventureBackpack getTile() - { - return this; - } - - @Override - public ItemStack getParentItemStack() - { - return null; - } - - - private ItemStack transferToItemStack(ItemStack stack) - { - NBTTagCompound compound = new NBTTagCompound(); - saveToNBT(compound); - stack.setTagCompound(compound); - return stack; - } - - //=====================================================BACKPACK===================================================// - public boolean equip(World world, EntityPlayer player, int x, int y, int z) - { - ItemStack stacky = new ItemStack(ModItems.adventureBackpack, 1); - transferToItemStack(stacky); - removeSleepingBag(world); - if (BackpackUtils.equipWearable(stacky, player) != BackpackUtils.reasons.SUCCESFUL) - { - player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:already.equipped")); - if (!player.inventory.addItemStackToInventory(stacky)) - { - return drop(world, player, x, y, z); - } + checkTime--; } - return true; } - public boolean drop(World world, EntityPlayer player, int x, int y, int z) - { - removeSleepingBag(world); - if (player.capabilities.isCreativeMode) return true; - ItemStack stacky = new ItemStack(ModItems.adventureBackpack, 1); - transferToItemStack(stacky); - float spawnX = x + world.rand.nextFloat(); - float spawnY = y + world.rand.nextFloat(); - float spawnZ = z + world.rand.nextFloat(); - - EntityItem droppedItem = new EntityItem(world, spawnX, spawnY, spawnZ, stacky); - - float mult = 0.05F; - - droppedItem.motionX = (-0.5F + world.rand.nextFloat()) * mult; - droppedItem.motionY = (4 + world.rand.nextFloat()) * mult; - droppedItem.motionZ = (-0.5F + world.rand.nextFloat()) * mult; - - return world.spawnEntityInWorld(droppedItem); - } - - - @Override - public boolean updateTankSlots() - { - return false; - } - - public void dirtyTanks() - { - - } - - public void dirtyTime() + public int getLuminosity() { + return luminosity; } - public void dirtyExtended() + private void convertFromOldNBTFormat(NBTTagCompound compound) // backwards compatibility { + NBTTagCompound oldBackpackTag = compound.getCompoundTag("backpackData"); + NBTTagList oldItems = oldBackpackTag.getTagList("ABPItems", NBT.TAG_COMPOUND); + leftTank.readFromNBT(oldBackpackTag.getCompoundTag("leftTank")); + rightTank.readFromNBT(oldBackpackTag.getCompoundTag("rightTank")); + type = BackpackTypes.getType(oldBackpackTag.getString("colorName")); - } - - public void dirtyInventory() - { + NBTTagCompound newBackpackTag = new NBTTagCompound(); + newBackpackTag.setTag(TAG_INVENTORY, oldItems); + newBackpackTag.setTag(TAG_RIGHT_TANK, rightTank.writeToNBT(new NBTTagCompound())); + newBackpackTag.setTag(TAG_LEFT_TANK, leftTank.writeToNBT(new NBTTagCompound())); + newBackpackTag.setByte(TAG_TYPE, BackpackTypes.getMeta(type)); + compound.setTag(TAG_WEARABLE_COMPOUND, newBackpackTag); + compound.removeTag("backpackData"); } -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/block/TileCampfire.java b/src/main/java/com/darkona/adventurebackpack/block/TileCampfire.java index 3d49ed9f..ec6e9d86 100644 --- a/src/main/java/com/darkona/adventurebackpack/block/TileCampfire.java +++ b/src/main/java/com/darkona/adventurebackpack/block/TileCampfire.java @@ -10,10 +10,11 @@ */ public class TileCampfire extends TileEntity { + private int burnTicks; + private ItemStack[] foodCooking = new ItemStack[4]; + public TileCampfire() { - } - private int burnTicks; - private ItemStack[] foodCooking = new ItemStack[4]; + } } diff --git a/src/main/java/com/darkona/adventurebackpack/client/ClientActions.java b/src/main/java/com/darkona/adventurebackpack/client/ClientActions.java index 5f342344..76c8a95e 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/ClientActions.java +++ b/src/main/java/com/darkona/adventurebackpack/client/ClientActions.java @@ -1,15 +1,20 @@ package com.darkona.adventurebackpack.client; -import com.darkona.adventurebackpack.client.audio.*; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; -import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; -import cpw.mods.fml.client.FMLClientHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.audio.SoundHandler; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; +import cpw.mods.fml.client.FMLClientHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import com.darkona.adventurebackpack.client.audio.BoilingBoilerSound; +import com.darkona.adventurebackpack.client.audio.CopterPackSound; +import com.darkona.adventurebackpack.client.audio.JetpackSoundOn; +import com.darkona.adventurebackpack.client.audio.LeakingBoilerSound; +import com.darkona.adventurebackpack.client.audio.NyanMovingSound; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; +import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; /** * Created on 11/10/2014 @@ -21,7 +26,6 @@ */ public class ClientActions { - @SideOnly(Side.CLIENT) public static void showParticlesAtEntity(Entity entity, byte particleCode) { @@ -56,7 +60,7 @@ public static void playSoundAtEntity(Entity entity, byte soundCode) switch (soundCode) { case EntitySoundPacket.COPTER_SOUND: - if (ConfigHandler.ALLOW_COPTER_SOUND) + if (ConfigHandler.allowSoundCopter) { snd.playSound(new CopterPackSound(player)); } @@ -65,16 +69,24 @@ public static void playSoundAtEntity(Entity entity, byte soundCode) snd.playSound(new NyanMovingSound(player)); break; case EntitySoundPacket.JETPACK_FIZZ: - snd.playSound(new JetpackSoundOn(player)); + if (ConfigHandler.allowSoundJetpack) + { + snd.playSound(new JetpackSoundOn(player)); + } break; case EntitySoundPacket.BOILING_BUBBLES: - snd.playSound(new BoilingBoilerSound(player)); + if (ConfigHandler.allowSoundJetpack) + { + snd.playSound(new BoilingBoilerSound(player)); + } break; case EntitySoundPacket.LEAKING_STEAM: - snd.playSound(new LeakingBoilerSound(player)); + if (ConfigHandler.allowSoundJetpack) + { + snd.playSound(new LeakingBoilerSound(player)); + } break; } } } - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/Visuals.java b/src/main/java/com/darkona/adventurebackpack/client/Visuals.java index 92407568..5139264a 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/Visuals.java +++ b/src/main/java/com/darkona/adventurebackpack/client/Visuals.java @@ -1,6 +1,5 @@ package com.darkona.adventurebackpack.client; -import com.darkona.adventurebackpack.entity.fx.SteamFX; import net.minecraft.client.Minecraft; import net.minecraft.client.particle.EntityFX; import net.minecraft.entity.player.EntityPlayer; @@ -8,6 +7,8 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; +import com.darkona.adventurebackpack.entity.fx.SteamFX; + /** * Created on 17/10/2014 * @@ -15,10 +16,8 @@ */ public class Visuals { - public static void NyanParticles(EntityPlayer player, World world) { - // World world = player.worldObj; int i = 2; for (int j = 0; j < i * 3; ++j) { @@ -67,14 +66,13 @@ public static void JetpackParticles(EntityPlayer player, World world) victoria.rotateAroundY(-player.renderYawOffset * 3.141593F / 180.0F); Vec3 leftPosition = victor.addVector(playerPosition.xCoord, playerPosition.yCoord, playerPosition.zCoord); Vec3 rightPosition = victoria.addVector(playerPosition.xCoord, playerPosition.yCoord, playerPosition.zCoord); - for(int i = 0; i< 4; i++) + for (int i = 0; i < 4; i++) { - spawnParticle("steam", leftPosition.xCoord, leftPosition.yCoord, leftPosition.zCoord, 0.04*world.rand.nextGaussian(), -0.8, 0.04 * world.rand.nextGaussian()); + spawnParticle("steam", leftPosition.xCoord, leftPosition.yCoord, leftPosition.zCoord, 0.04 * world.rand.nextGaussian(), -0.8, 0.04 * world.rand.nextGaussian()); spawnParticle("steam", rightPosition.xCoord, rightPosition.yCoord, rightPosition.zCoord, 0.04 * world.rand.nextGaussian(), -0.8, 0.04 * world.rand.nextGaussian()); } } - private static Minecraft mc = Minecraft.getMinecraft(); private static World theWorld = mc.theWorld; @@ -108,17 +106,6 @@ else if (particleSetting > 1) if (particleName.equals("steam")) { entityFX = new SteamFX(theWorld, x, y, z, (float) motionX, (float) motionY, (float) motionZ); - /* - try - { - entityFX = (EntityFX) Class.forName("mods.railcraft.client.particles.EntitySteamFX") - .getConstructor(World.class,int.class,int.class,int.class,float.class,float.class,float.class) - .newInstance(theWorld, x, y, z, (float) motionX, (float) motionY, (float) motionZ); - }catch(Exception ex) - { - entityFX = new SteamFX(theWorld, x, y, z, (float) motionX, (float) motionY, (float) motionZ); - } - */ } mc.effectRenderer.addEffect(entityFX); return entityFX; diff --git a/src/main/java/com/darkona/adventurebackpack/client/audio/BoilingBoilerSound.java b/src/main/java/com/darkona/adventurebackpack/client/audio/BoilingBoilerSound.java index 3e1435a3..bf0c9f93 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/audio/BoilingBoilerSound.java +++ b/src/main/java/com/darkona/adventurebackpack/client/audio/BoilingBoilerSound.java @@ -1,12 +1,13 @@ package com.darkona.adventurebackpack.client.audio; -import com.darkona.adventurebackpack.inventory.InventorySteamJetpack; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.Wearing; import net.minecraft.client.audio.MovingSound; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.util.Wearing; + /** * Created on 16/01/2015 * @@ -14,12 +15,10 @@ */ public class BoilingBoilerSound extends MovingSound { - - public EntityPlayer thePlayer; - protected boolean repeat = true; - protected int repeatDelay = 0; - - protected float pitch; + private EntityPlayer thePlayer; + private boolean repeat = true; + private int repeatDelay = 0; + private float pitch; public BoilingBoilerSound(EntityPlayer player) { @@ -29,16 +28,7 @@ public BoilingBoilerSound(EntityPlayer player) thePlayer = player; } - public EntityPlayer getThePlayer() - { - return thePlayer; - } - - public void setThePlayer(EntityPlayer player){ - thePlayer = player; - } - - public void setDonePlaying() + public void setDonePlaying() { repeat = false; donePlaying = true; @@ -54,20 +44,20 @@ public boolean isDonePlaying() @Override public void update() { - - if (thePlayer == null || thePlayer.isDead || thePlayer.worldObj == null || !Wearing.isWearingSteam(thePlayer)) + if (thePlayer == null || thePlayer.isDead || thePlayer.worldObj == null || !Wearing.isWearingJetpack(thePlayer)) { setDonePlaying(); return; } - InventorySteamJetpack inv = new InventorySteamJetpack(Wearing.getWearingSteam(thePlayer)); - if(inv.isBoiling() && inv.getWaterTank().getFluidAmount() > 0) + InventoryCoalJetpack inv = new InventoryCoalJetpack(Wearing.getWearingJetpack(thePlayer)); + if (inv.isBoiling() && inv.getWaterTank().getFluidAmount() > 0) { - xPosF = (float)thePlayer.posX; - yPosF = (float)thePlayer.posY; - zPosF = (float)thePlayer.posZ; - }else + xPosF = (float) thePlayer.posX; + yPosF = (float) thePlayer.posY; + zPosF = (float) thePlayer.posZ; + } + else { setDonePlaying(); } @@ -92,12 +82,14 @@ public float getPitch() } @Override - public int getRepeatDelay(){ return this.repeatDelay; } + public int getRepeatDelay() + { + return this.repeatDelay; + } @Override public AttenuationType getAttenuationType() { return AttenuationType.LINEAR; } - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/audio/CopterPackSound.java b/src/main/java/com/darkona/adventurebackpack/client/audio/CopterPackSound.java index 6c1a4787..f1ba46f6 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/audio/CopterPackSound.java +++ b/src/main/java/com/darkona/adventurebackpack/client/audio/CopterPackSound.java @@ -1,14 +1,18 @@ package com.darkona.adventurebackpack.client.audio; -import com.darkona.adventurebackpack.item.ItemCopterPack; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Wearing; import net.minecraft.client.audio.MovingSound; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; +import com.darkona.adventurebackpack.item.ItemCopterPack; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.LogHelper; +import com.darkona.adventurebackpack.util.Wearing; + +import static com.darkona.adventurebackpack.common.Constants.Copter.TAG_STATUS; + /** * Created on 16/10/2014 * @@ -16,37 +20,25 @@ */ public class CopterPackSound extends MovingSound { - - public EntityPlayer thePlayer; - protected boolean repeat = true; - protected int repeatDelay = 0; - - protected float pitch; - + private EntityPlayer thePlayer; + private boolean repeat = true; + private int repeatDelay = 0; + private float pitch; public CopterPackSound(EntityPlayer player) { - super(new ResourceLocation(ModInfo.MOD_ID, "helicopter")); + super(new ResourceLocation(ModInfo.MOD_ID, "helicopter3")); volume = 0.6f; pitch = 1.0F; thePlayer = player; } - public EntityPlayer getThePlayer() + public void setRepeat(boolean newRepeat) { - return thePlayer; - } - - public void setThePlayer(EntityPlayer player){ - thePlayer = player; - } - - public void setRepeat(boolean newRepeat){ LogHelper.info("Setting sound repeat"); repeat = newRepeat; } - public void setDonePlaying() { this.repeat = false; @@ -65,39 +57,32 @@ public void update() { ItemStack copter = Wearing.getWearingCopter(thePlayer); byte status = 0; - if(thePlayer == null || thePlayer.worldObj == null || copter ==null || !(copter.getItem() instanceof ItemCopterPack)) + if (thePlayer == null || thePlayer.isDead || thePlayer.worldObj == null || copter == null || !(copter.getItem() instanceof ItemCopterPack)) { setDonePlaying(); return; } - if (copter.hasTagCompound() && copter.getTagCompound().hasKey("status")) + + status = BackpackUtils.getWearableCompound(copter).getByte(TAG_STATUS); + if (status == ItemCopterPack.OFF_MODE) { - status = copter.getTagCompound().getByte("status"); - if (status == ItemCopterPack.OFF_MODE) - { - setDonePlaying(); - }else{ - if(status == ItemCopterPack.HOVER_MODE) - { - pitch = (thePlayer.motionY > 0) ? 1.2f : (thePlayer.motionY < -0.1) ? 0.8f : 1.0f; - } - if(status == ItemCopterPack.NORMAL_MODE) - { - if(thePlayer.onGround) - { - pitch = 0.8f; - }else - { - pitch = (thePlayer.motionY > 0) ? 1.2f : (thePlayer.isSneaking()) ? 0.8f : 1.0f; - } - } - } - }else{ setDonePlaying(); } - xPosF = (float)thePlayer.posX; - yPosF = (float)thePlayer.posY; - zPosF = (float)thePlayer.posZ; + else if (status == ItemCopterPack.HOVER_MODE) + { + pitch = (thePlayer.motionY > 0) ? 1.2f : (thePlayer.motionY < -0.1) ? 0.8f : 1.0f; + } + else if (status == ItemCopterPack.NORMAL_MODE) + { + if (thePlayer.onGround) + pitch = 0.8f; + else + pitch = (thePlayer.motionY > 0) ? 1.2f : (thePlayer.isSneaking()) ? 0.8f : 1.0f; + } + + xPosF = (float) thePlayer.posX; + yPosF = (float) thePlayer.posY; + zPosF = (float) thePlayer.posZ; } @Override @@ -119,12 +104,14 @@ public float getPitch() } @Override - public int getRepeatDelay(){ return this.repeatDelay; } + public int getRepeatDelay() + { + return this.repeatDelay; + } @Override public AttenuationType getAttenuationType() { return AttenuationType.LINEAR; } - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/audio/JetpackSoundOn.java b/src/main/java/com/darkona/adventurebackpack/client/audio/JetpackSoundOn.java index 7a16510e..911d299c 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/audio/JetpackSoundOn.java +++ b/src/main/java/com/darkona/adventurebackpack/client/audio/JetpackSoundOn.java @@ -1,12 +1,13 @@ package com.darkona.adventurebackpack.client.audio; -import com.darkona.adventurebackpack.inventory.InventorySteamJetpack; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.Wearing; import net.minecraft.client.audio.MovingSound; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.util.Wearing; + /** * Created on 16/01/2015 * @@ -14,12 +15,10 @@ */ public class JetpackSoundOn extends MovingSound { - - public EntityPlayer thePlayer; - protected boolean repeat = true; - protected int repeatDelay = 0; - - protected float pitch; + private EntityPlayer thePlayer; + private boolean repeat = true; + private int repeatDelay = 0; + private float pitch; public JetpackSoundOn(EntityPlayer player) { @@ -29,16 +28,7 @@ public JetpackSoundOn(EntityPlayer player) thePlayer = player; } - public EntityPlayer getThePlayer() - { - return thePlayer; - } - - public void setThePlayer(EntityPlayer player){ - thePlayer = player; - } - - public void setDonePlaying() + public void setDonePlaying() { repeat = false; donePlaying = true; @@ -54,19 +44,20 @@ public boolean isDonePlaying() @Override public void update() { - if (thePlayer == null || thePlayer.isDead || thePlayer.worldObj == null || !Wearing.isWearingSteam(thePlayer)) + if (thePlayer == null || thePlayer.isDead || thePlayer.worldObj == null || !Wearing.isWearingJetpack(thePlayer)) { setDonePlaying(); return; } - InventorySteamJetpack inv = new InventorySteamJetpack(Wearing.getWearingSteam(thePlayer)); - if(inv.isInUse()) + InventoryCoalJetpack inv = new InventoryCoalJetpack(Wearing.getWearingJetpack(thePlayer)); + if (inv.isInUse()) { - xPosF = (float)thePlayer.posX; - yPosF = (float)thePlayer.posY; - zPosF = (float)thePlayer.posZ; - }else + xPosF = (float) thePlayer.posX; + yPosF = (float) thePlayer.posY; + zPosF = (float) thePlayer.posZ; + } + else { setDonePlaying(); } @@ -91,12 +82,14 @@ public float getPitch() } @Override - public int getRepeatDelay(){ return this.repeatDelay; } + public int getRepeatDelay() + { + return this.repeatDelay; + } @Override public AttenuationType getAttenuationType() { return AttenuationType.LINEAR; } - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/audio/LeakingBoilerSound.java b/src/main/java/com/darkona/adventurebackpack/client/audio/LeakingBoilerSound.java index 155d5c5d..d013a2bd 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/audio/LeakingBoilerSound.java +++ b/src/main/java/com/darkona/adventurebackpack/client/audio/LeakingBoilerSound.java @@ -1,12 +1,13 @@ package com.darkona.adventurebackpack.client.audio; -import com.darkona.adventurebackpack.inventory.InventorySteamJetpack; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.Wearing; import net.minecraft.client.audio.MovingSound; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.util.Wearing; + /** * Created on 16/01/2015 * @@ -14,12 +15,10 @@ */ public class LeakingBoilerSound extends MovingSound { - - public EntityPlayer thePlayer; - protected boolean repeat = true; - protected int repeatDelay = 0; - - protected float pitch; + private EntityPlayer thePlayer; + private boolean repeat = true; + private int repeatDelay = 0; + private float pitch; public LeakingBoilerSound(EntityPlayer player) { @@ -29,16 +28,7 @@ public LeakingBoilerSound(EntityPlayer player) thePlayer = player; } - public EntityPlayer getThePlayer() - { - return thePlayer; - } - - public void setThePlayer(EntityPlayer player){ - thePlayer = player; - } - - public void setDonePlaying() + public void setDonePlaying() { repeat = false; donePlaying = true; @@ -54,19 +44,20 @@ public boolean isDonePlaying() @Override public void update() { - if (thePlayer == null || thePlayer.isDead || thePlayer.worldObj == null || !Wearing.isWearingSteam(thePlayer)) + if (thePlayer == null || thePlayer.isDead || thePlayer.worldObj == null || !Wearing.isWearingJetpack(thePlayer)) { setDonePlaying(); return; } - InventorySteamJetpack inv = new InventorySteamJetpack(Wearing.getWearingSteam(thePlayer)); - if(inv.isLeaking()) + InventoryCoalJetpack inv = new InventoryCoalJetpack(Wearing.getWearingJetpack(thePlayer)); + if (inv.isLeaking()) { - xPosF = (float)thePlayer.posX; - yPosF = (float)thePlayer.posY; - zPosF = (float)thePlayer.posZ; - }else + xPosF = (float) thePlayer.posX; + yPosF = (float) thePlayer.posY; + zPosF = (float) thePlayer.posZ; + } + else { setDonePlaying(); } @@ -91,12 +82,14 @@ public float getPitch() } @Override - public int getRepeatDelay(){ return this.repeatDelay; } + public int getRepeatDelay() + { + return this.repeatDelay; + } @Override public AttenuationType getAttenuationType() { return AttenuationType.LINEAR; } - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/audio/NyanMovingSound.java b/src/main/java/com/darkona/adventurebackpack/client/audio/NyanMovingSound.java index c4329e25..667402c1 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/audio/NyanMovingSound.java +++ b/src/main/java/com/darkona/adventurebackpack/client/audio/NyanMovingSound.java @@ -1,11 +1,13 @@ package com.darkona.adventurebackpack.client.audio; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.Wearing; import net.minecraft.client.audio.MovingSound; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.util.Wearing; + /** * Created on 16/10/2014 * @@ -13,22 +15,11 @@ */ public class NyanMovingSound extends MovingSound { - public static NyanMovingSound instance = new NyanMovingSound(); - public EntityPlayer getPlayer() - { - return player; - } - - public NyanMovingSound setPlayer(EntityPlayer p) - { - this.player = p; - return this; - } - private EntityPlayer player; + public NyanMovingSound(EntityPlayer player) { super(new ResourceLocation(ModInfo.MOD_ID, "nyan")); @@ -52,12 +43,14 @@ public void update() if (player == null || player.isDead) { this.donePlaying = true; - } else + } + else { - if (Wearing.isWearingTheRightBackpack(player, "Rainbow")) + if (Wearing.isWearingTheRightBackpack(player, BackpackTypes.RAINBOW)) { this.volume = 0.8f; - } else + } + else { this.donePlaying = true; // this.volume = 0.0f; diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiAdvBackpack.java b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiAdvBackpack.java index fc511525..0d6cc736 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiAdvBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiAdvBackpack.java @@ -1,23 +1,29 @@ package com.darkona.adventurebackpack.client.gui; +import org.lwjgl.input.Keyboard; +import org.lwjgl.opengl.GL11; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.MathHelper; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fluids.FluidTank; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + import com.darkona.adventurebackpack.block.TileAdventureBackpack; -import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.common.Constants.Source; import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.config.Keybindings; import com.darkona.adventurebackpack.init.ModNetwork; import com.darkona.adventurebackpack.inventory.ContainerBackpack; +import com.darkona.adventurebackpack.inventory.IInventoryBackpack; import com.darkona.adventurebackpack.inventory.InventoryBackpack; -import com.darkona.adventurebackpack.network.EquipUnequipBackWearablePacket; +import com.darkona.adventurebackpack.network.PlayerActionPacket; import com.darkona.adventurebackpack.network.SleepingBagPacket; +import com.darkona.adventurebackpack.reference.LoadedMods; import com.darkona.adventurebackpack.util.Resources; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fluids.FluidTank; -import org.lwjgl.input.Keyboard; -import org.lwjgl.opengl.GL11; +import com.darkona.adventurebackpack.util.TinkersUtils; /** * Created on 12/10/2014 @@ -27,115 +33,89 @@ @SideOnly(Side.CLIENT) public class GuiAdvBackpack extends GuiWithTanks { + private static final ResourceLocation TEXTURE = Resources.guiTextures("guiBackpackNew"); + private static final int TINKERS_SLOT = 38; //ContainerBackpack.CRAFT_MATRIX_EMULATION[4] - protected IInventoryAdventureBackpack inventory; - protected boolean isTile; - protected boolean wearing; - protected int X; - protected int Y; - protected int Z; - private EntityPlayer player; - private static final ResourceLocation texture = Resources.guiTextures("guiBackpackNew"); private static GuiImageButtonNormal bedButton = new GuiImageButtonNormal(5, 91, 18, 18); private static GuiImageButtonNormal equipButton = new GuiImageButtonNormal(5, 91, 18, 18); private static GuiImageButtonNormal unequipButton = new GuiImageButtonNormal(5, 91, 18, 18); - private static GuiTank tankLeft = new GuiTank(25, 7, 100, 16, ConfigHandler.GUI_TANK_RENDER); - private static GuiTank tankRight = new GuiTank(207, 7, 100, 16, ConfigHandler.GUI_TANK_RENDER); - private FluidTank lft; - private FluidTank rgt; - public int lefties; - public int topsies; - - public GuiAdvBackpack(EntityPlayer player, TileAdventureBackpack tileBackpack) + private static GuiTank tankLeft = new GuiTank(25, 7, 100, 16, ConfigHandler.typeTankRender); + private static GuiTank tankRight = new GuiTank(207, 7, 100, 16, ConfigHandler.typeTankRender); + + private IInventoryBackpack inventory; + + private boolean isHoldingSpace; + + public GuiAdvBackpack(EntityPlayer player, TileAdventureBackpack tileBackpack, Source source) { - super(new ContainerBackpack(player, tileBackpack, ContainerBackpack.SOURCE_TILE)); - this.inventory = tileBackpack; - this.isTile = true; + super(new ContainerBackpack(player, tileBackpack, source)); + this.player = player; + inventory = tileBackpack; + this.source = source; xSize = 248; ySize = 207; - this.X = tileBackpack.xCoord; - this.Y = tileBackpack.yCoord; - this.Z = tileBackpack.zCoord; - this.player = player; - this.lefties = guiLeft; - this.topsies = guiTop; } - public GuiAdvBackpack(EntityPlayer player, InventoryBackpack inventoryBackpack, boolean wearing) + public GuiAdvBackpack(EntityPlayer player, InventoryBackpack inventoryBackpack, Source source) { - super(new ContainerBackpack(player, inventoryBackpack, wearing ? ContainerBackpack.SOURCE_WEARING : ContainerBackpack.SOURCE_HOLDING)); - this.inventory = inventoryBackpack; - this.wearing = wearing; - this.isTile = false; + super(new ContainerBackpack(player, inventoryBackpack, source)); + this.player = player; + inventory = inventoryBackpack; + this.source = source; xSize = 248; ySize = 207; - this.player = player; - this.lefties = guiLeft; - this.topsies = guiTop; } - @Override - public void onGuiClosed() + private boolean isBedButtonCase() { - if (inventory != null) - { - inventory.closeInventory(); - } - super.onGuiClosed(); + return source == Source.TILE + || (ConfigHandler.portableSleepingBag && source == Source.WEARING && GuiScreen.isShiftKeyDown()); } @Override protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { GL11.glColor4f(1, 1, 1, 1); - - this.mc.renderEngine.bindTexture(texture); - + this.mc.renderEngine.bindTexture(TEXTURE); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); // Buttons and button highlight - if (isTile) + if (isBedButtonCase()) { if (bedButton.inButton(this, mouseX, mouseY)) - { bedButton.draw(this, 20, 227); - } else - { + else bedButton.draw(this, 1, 227); - } - }else + } + else if (source == Source.WEARING) { - if(wearing) - { - if(unequipButton.inButton(this,mouseX,mouseY)) - { - unequipButton.draw(this,96,227); - }else - { - unequipButton.draw(this,77,227); - } - }else - { - if(equipButton.inButton(this,mouseX,mouseY)) - { - equipButton.draw(this,96,208); - }else - { - equipButton.draw(this,77,208); - } - } + if (unequipButton.inButton(this, mouseX, mouseY)) + unequipButton.draw(this, 96, 227); + else + unequipButton.draw(this, 77, 227); } - //zLevel +=1; - if(ConfigHandler.HOVERING_TEXT_TANKS) + else if (source == Source.HOLDING) + { + if (equipButton.inButton(this, mouseX, mouseY)) + equipButton.draw(this, 96, 208); + else + equipButton.draw(this, 77, 208); + } + if (ConfigHandler.tanksHoveringText) { if (tankLeft.inTank(this, mouseX, mouseY)) - { drawHoveringText(tankLeft.getTankTooltip(), mouseX, mouseY, fontRendererObj); - } if (tankRight.inTank(this, mouseX, mouseY)) - { drawHoveringText(tankRight.getTankTooltip(), mouseX, mouseY, fontRendererObj); + } + + if (LoadedMods.TCONSTRUCT && ConfigHandler.tinkerToolsMaintenance) + { + if (inventory.getStackInSlot(TINKERS_SLOT) == null) + { + this.mc.getTextureManager().bindTexture(TinkersUtils.GUI_ICONS); + this.drawTexturedModalRect(this.guiLeft + 169, this.guiTop + 77, 0, 233, 18, 18); } } } @@ -143,105 +123,73 @@ protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - inventory.openInventory(); - lft = inventory.getLeftTank(); - rgt = inventory.getRightTank(); + FluidTank lft = inventory.getLeftTank(); + FluidTank rgt = inventory.getRightTank(); tankLeft.draw(this, lft); tankRight.draw(this, rgt); GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_BLEND); - /* - if(!ConfigHandler.HOVERING_TEXT_TANKS){ - GL11.glPushMatrix(); - //GL11.glTranslatef(8f,64f,0f); - GL11.glScalef(0.6f, 0.6f, 0.6f); - String name = (lft.getFluid() != null) ? lft.getFluid().getLocalizedName() : "None"; - String amount = (lft.getFluid() != null ? lft.getFluid().amount : "Empty").toString(); - String capacity = Integer.toString(inventory.getLeftTank().getCapacity()); - int offsetY = 32; - int offsetX = 8; - fontRendererObj.drawString(Utils.getFirstWord(name), 1 + offsetX, 64 + offsetY, 0x373737, false); - fontRendererObj.drawString(amount, 1 + offsetX, 79 + offsetY, 0x373737, false); - fontRendererObj.drawString(capacity, 1 + offsetX, 94 + offsetY, 0x373737, false); - - name = (rgt.getFluid() != null) ? rgt.getFluid().getLocalizedName() : "None"; - amount = (rgt.getFluid() != null ? rgt.getFluid().amount : "Empty").toString(); - fontRendererObj.drawString(Utils.getFirstWord(name), 369 + offsetX, 64 + offsetY, 0x373737, false); - fontRendererObj.drawString(amount, 369 + offsetX, 79 + offsetY, 0x373737, false); - fontRendererObj.drawString(capacity, 369 + offsetX, 94 + offsetY, 0x373737, false); - - GL11.glPopMatrix(); - } - */ - } - - @Override - public float getZLevel() - { - return this.zLevel; - } - - @Override - public void initGui() - { - super.initGui(); - } @Override - public int getLeft() + protected GuiImageButtonNormal getEquipButton() { - return guiLeft; + return equipButton; } @Override - public int getTop() + protected GuiImageButtonNormal getUnequipButton() { - return guiTop; + return unequipButton; } @Override protected void mouseClicked(int mouseX, int mouseY, int button) { - int sneakKey = Minecraft.getMinecraft().gameSettings.keyBindSneak.getKeyCode(); - if(isTile) + if (isBedButtonCase() && bedButton.inButton(this, mouseX, mouseY)) { - if (bedButton.inButton(this, mouseX, mouseY)) + if (source == Source.TILE) { TileAdventureBackpack te = (TileAdventureBackpack) inventory; - ModNetwork.net.sendToServer(new SleepingBagPacket.SleepingBagMessage(te.xCoord, te.yCoord, te.zCoord)); + ModNetwork.net.sendToServer(new SleepingBagPacket.SleepingBagMessage(true, te.xCoord, te.yCoord, te.zCoord)); } - }else - { - if(wearing) + else { - if(unequipButton.inButton(this,mouseX,mouseY)) - { - ModNetwork.net.sendToServer(new EquipUnequipBackWearablePacket.Message(EquipUnequipBackWearablePacket.UNEQUIP_WEARABLE,false)); - player.closeScreen(); - } - } else - { - if(equipButton.inButton(this,mouseX,mouseY)) - { - ModNetwork.net.sendToServer(new EquipUnequipBackWearablePacket.Message(EquipUnequipBackWearablePacket.EQUIP_WEARABLE, Keyboard.isKeyDown(sneakKey))); - player.closeScreen(); - } - + int posX = MathHelper.floor_double(player.posX); + int posY = MathHelper.floor_double(player.posY) - 1; + int posZ = MathHelper.floor_double(player.posZ); + ModNetwork.net.sendToServer(new SleepingBagPacket.SleepingBagMessage(false, posX, posY, posZ)); } } - super.mouseClicked(mouseX, mouseY, button); + else + { + super.mouseClicked(mouseX, mouseY, button); + } } @Override - protected void keyTyped(char key, int keycode) + public void updateScreen() { - if (keycode == Keybindings.openBackpack.getKeyCode()) + super.updateScreen(); + + if (!isHoldingSpace) + { + if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) + { + isHoldingSpace = true; + ModNetwork.net.sendToServer(new PlayerActionPacket.ActionMessage(PlayerActionPacket.GUI_HOLDING_SPACE)); + inventory.getExtendedProperties().setBoolean(Constants.TAG_HOLDING_SPACE, true); + } + } + else { - player.closeScreen(); + if (!Keyboard.isKeyDown(Keyboard.KEY_SPACE)) + { + isHoldingSpace = false; + ModNetwork.net.sendToServer(new PlayerActionPacket.ActionMessage(PlayerActionPacket.GUI_NOT_HOLDING_SPACE)); + inventory.getExtendedProperties().removeTag(Constants.TAG_HOLDING_SPACE); + } } - super.keyTyped(key, keycode); } } - diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiCoalJetpack.java b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiCoalJetpack.java new file mode 100644 index 00000000..c74b8b9f --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiCoalJetpack.java @@ -0,0 +1,153 @@ +package com.darkona.adventurebackpack.client.gui; + +import org.apache.commons.lang3.text.WordUtils; +import org.lwjgl.opengl.GL11; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidTank; + +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.common.Constants.Source; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.inventory.ContainerJetpack; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; +import com.darkona.adventurebackpack.util.Resources; + +/** + * Created on 15/01/2015 + * + * @author Darkona + */ +public class GuiCoalJetpack extends GuiWithTanks +{ + private static final ResourceLocation TEXTURE = Resources.guiTextures("guiCoalJetpack"); + + private static GuiImageButtonNormal equipButton = new GuiImageButtonNormal(150, 64, 18, 18); + private static GuiImageButtonNormal unequipButton = new GuiImageButtonNormal(150, 64, 18, 18); + private static GuiTank waterTank = new GuiTank(8, 8, 72, 16, ConfigHandler.typeTankRender); + private static GuiTank steamTank = new GuiTank(116, 8, 72, 16, ConfigHandler.typeTankRender); + + private InventoryCoalJetpack inventory; + + private int boiling = 0; + + public GuiCoalJetpack(EntityPlayer player, InventoryCoalJetpack inv, Source source) + { + super(new ContainerJetpack(player, inv, source)); + this.player = player; + inventory = inv; + this.source = source; + xSize = 176; + ySize = 166; + } + + @Override + protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int mouseX, int mouseY) + { + inventory.openInventory(); + this.mc.renderEngine.bindTexture(TEXTURE); + drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); + + if (source == Source.WEARING) + { + if (unequipButton.inButton(this, mouseX, mouseY)) + { + unequipButton.draw(this, 20, 186); + } + else + { + unequipButton.draw(this, 1, 186); + } + } + else if (source == Source.HOLDING) + { + if (equipButton.inButton(this, mouseX, mouseY)) + { + equipButton.draw(this, 20, 167); + } + else + { + equipButton.draw(this, 1, 167); + } + } + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) + { + this.mc.renderEngine.bindTexture(TEXTURE); + inventory.openInventory(); + FluidTank water = inventory.getWaterTank(); + FluidTank steam = inventory.getSteamTank(); + GL11.glPushMatrix(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + if (inventory.isBoiling() && steam.getFluidAmount() < steam.getCapacity() && water.getFluidAmount() > 0) + { + if (boiling < 83) + { + drawTexturedModalRect(28, 40, 50, 172, boiling++, 37); + } + else + { + boiling = 0; + } + } + if (inventory.getBurnTicks() > 0) + { + int i1 = inventory.getBurnTimeRemainingScaled(13); + this.drawTexturedModalRect(78, 48 + 12 - i1, 176, 12 - i1, 14, i1 + 1); + } + + int H = Math.round(((float) 72 / (float) Constants.Jetpack.MAX_TEMPERATURE) * (float) inventory.getTemperature()); + drawTexturedModalRect(139, 8 + (72 - H), 40, 167 + (72 - H), 5, H); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glPopMatrix(); + GL11.glDisable(GL11.GL_LIGHTING); + + waterTank.draw(this, water); + steamTank.draw(this, steam); + + float factor = 0.7f; + + String show = ((water.getFluidAmount() > 0) ? WordUtils.capitalize(FluidRegistry.getFluidName(water.getFluid())) : "None") + "-" + water.getFluidAmount(); + + GL11.glPushMatrix(); + GL11.glTranslatef(70, 10, 0); + GL11.glScalef(factor, factor, factor); + fontRendererObj.drawString(show, 0, 0, 0x373737, false); + GL11.glScalef(1, 1, 1); + GL11.glPopMatrix(); + + show = ((steam.getFluidAmount() > 0) ? WordUtils.capitalize(FluidRegistry.getFluidName(steam.getFluid())) : "None") + "-" + steam.getFluidAmount(); + + GL11.glPushMatrix(); + GL11.glTranslatef(70, 20, 0); + GL11.glScalef(factor, factor, factor); + fontRendererObj.drawString(show, 0, 0, 0x373737, false); + GL11.glScalef(1, 1, 1); + GL11.glPopMatrix(); + + GL11.glPushMatrix(); + GL11.glTranslatef(145, 8, 0); + GL11.glScalef(0.9f, 0.9f, 0.9f); + fontRendererObj.drawString((inventory.getTemperature()) + " C", 0, 0, 0x373737, false); + GL11.glScalef(1, 1, 1); + GL11.glPopMatrix(); + } + + @Override + protected GuiImageButtonNormal getEquipButton() + { + return equipButton; + } + + @Override + protected GuiImageButtonNormal getUnequipButton() + { + return unequipButton; + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiCopterPack.java b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiCopterPack.java index 639c1f3c..2b7a6145 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiCopterPack.java +++ b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiCopterPack.java @@ -1,20 +1,18 @@ package com.darkona.adventurebackpack.client.gui; +import org.apache.commons.lang3.text.WordUtils; +import org.lwjgl.opengl.GL11; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fluids.FluidTank; + +import com.darkona.adventurebackpack.common.Constants.Source; import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.config.Keybindings; -import com.darkona.adventurebackpack.init.ModNetwork; import com.darkona.adventurebackpack.inventory.ContainerCopter; import com.darkona.adventurebackpack.inventory.InventoryCopterPack; -import com.darkona.adventurebackpack.network.EquipUnequipBackWearablePacket; import com.darkona.adventurebackpack.reference.GeneralReference; import com.darkona.adventurebackpack.util.Resources; -import com.darkona.adventurebackpack.util.Utils; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fluids.FluidTank; -import org.lwjgl.input.Keyboard; -import org.lwjgl.opengl.GL11; /** * Created on 03/01/2015 @@ -23,53 +21,53 @@ */ public class GuiCopterPack extends GuiWithTanks { - private InventoryCopterPack inventory; - private static final ResourceLocation texture = Resources.guiTextures("guiCopterPack"); - private static GuiTank fuelTank = new GuiTank(8, 8,72, 32, ConfigHandler.GUI_TANK_RENDER); + private static final ResourceLocation TEXTURE = Resources.guiTextures("guiCopterPack"); + private static GuiImageButtonNormal equipButton = new GuiImageButtonNormal(150, 64, 18, 18); private static GuiImageButtonNormal unequipButton = new GuiImageButtonNormal(150, 64, 18, 18); + private static GuiTank fuelTank = new GuiTank(8, 8, 72, 32, ConfigHandler.typeTankRender); - private boolean wearing; - EntityPlayer player; + private InventoryCopterPack inventory; - public GuiCopterPack(EntityPlayer player, InventoryCopterPack inv, boolean wearing) + public GuiCopterPack(EntityPlayer player, InventoryCopterPack inv, Source source) { - super(new ContainerCopter(player, inv, wearing)); - this.inventory = inv; + super(new ContainerCopter(player, inv, source)); + this.player = player; + inventory = inv; + this.source = source; xSize = 176; ySize = 166; - this.wearing = wearing; - this.player = player; } @Override protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int mouseX, int mouseY) { GL11.glColor4f(1, 1, 1, 1); - this.mc.renderEngine.bindTexture(texture); + this.mc.renderEngine.bindTexture(TEXTURE); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); - if(wearing) + if (source == Source.WEARING) { - if(unequipButton.inButton(this,mouseX,mouseY)) + if (unequipButton.inButton(this, mouseX, mouseY)) { - unequipButton.draw(this,20,186); - }else + unequipButton.draw(this, 20, 186); + } + else { - unequipButton.draw(this,1,186); + unequipButton.draw(this, 1, 186); } - }else + } + else if (source == Source.HOLDING) { - if(equipButton.inButton(this,mouseX,mouseY)) + if (equipButton.inButton(this, mouseX, mouseY)) { - equipButton.draw(this,20,167); - }else + equipButton.draw(this, 20, 167); + } + else { - equipButton.draw(this,1,167); + equipButton.draw(this, 1, 167); } } - - } @Override @@ -78,86 +76,38 @@ protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_BLEND); inventory.openInventory(); - FluidTank fuel = inventory.getFuelTank(); - fuelTank.draw(this, fuel); + FluidTank tank = inventory.getFuelTank(); + fuelTank.draw(this, tank); GL11.glPushMatrix(); - String name = (fuel.getFluid() != null) ? Utils.capitalize(fuel.getFluid().getFluid().getName()) : "None"; - String amount = (fuel.getFluid() != null) ? ""+ fuel.getFluid().amount : "0"; - String capacity = Integer.toString(fuel.getCapacity()); + boolean isFilled = tank.getFluid() != null; + String name = isFilled ? WordUtils.capitalize(tank.getFluid().getFluid().getName()) : "None"; + String amount = isFilled ? "" + tank.getFluid().amount : "0"; + String capacity = Integer.toString(tank.getCapacity()); int offsetY = 8; int offsetX = 83; fontRendererObj.drawString(name, 1 + offsetX, offsetY, 0x373737, false); fontRendererObj.drawString(amount, 1 + offsetX, 10 + offsetY, 0x373737, false); fontRendererObj.drawString(capacity, 1 + offsetX, 20 + offsetY, 0x373737, false); - if(fuel.getFluid()!=null) + if (isFilled) { - Float f = GeneralReference.liquidFuels.get(name); - String conLev = (f != null) ? f.toString() : "0"; - if(conLev != null && !conLev.isEmpty()) - fontRendererObj.drawString("Consumption: " + conLev , 1 + offsetX, 40 + offsetY, 0x373737, false); + Float rate = GeneralReference.getFuelRate(name.toLowerCase()); + String conLev = (rate != null) ? rate.toString() : "0"; + fontRendererObj.drawString("Consumption: " + conLev, 1 + offsetX, 40 + offsetY, 0x373737, false); } GL11.glPopMatrix(); } @Override - public int getLeft() - { - return guiLeft; - } - - @Override - public int getTop() + protected GuiImageButtonNormal getEquipButton() { - return guiTop; + return equipButton; } @Override - public float getZLevel() + protected GuiImageButtonNormal getUnequipButton() { - return zLevel; - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) - { - int sneakKey = Minecraft.getMinecraft().gameSettings.keyBindSneak.getKeyCode(); - if(wearing) - { - if(unequipButton.inButton(this,mouseX,mouseY)) - { - ModNetwork.net.sendToServer(new EquipUnequipBackWearablePacket.Message(EquipUnequipBackWearablePacket.UNEQUIP_WEARABLE,false)); - player.closeScreen(); - } - } else - { - if(equipButton.inButton(this,mouseX,mouseY)) - { - ModNetwork.net.sendToServer(new EquipUnequipBackWearablePacket.Message(EquipUnequipBackWearablePacket.EQUIP_WEARABLE, Keyboard.isKeyDown(sneakKey))); - player.closeScreen(); - } - } - super.mouseClicked(mouseX, mouseY, mouseButton); - } - - @Override - protected void keyTyped(char key, int keycode) - { - if (keycode == Keybindings.openBackpack.getKeyCode()) - { - player.closeScreen(); - } - super.keyTyped(key, keycode); - } - - @Override - public void onGuiClosed() - { - if (inventory != null) - { - inventory.closeInventory(); - } - super.onGuiClosed(); + return unequipButton; } } diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiFactory.java b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiFactory.java index de9d38fc..0022e52c 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiFactory.java +++ b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiFactory.java @@ -1,10 +1,10 @@ package com.darkona.adventurebackpack.client.gui; -import cpw.mods.fml.client.IModGuiFactory; +import java.util.Set; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; - -import java.util.Set; +import cpw.mods.fml.client.IModGuiFactory; /** * Created on 10/10/2014 diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiOverlay.java b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiOverlay.java index 2d8e79a7..c06b8e6a 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiOverlay.java +++ b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiOverlay.java @@ -1,35 +1,46 @@ package com.darkona.adventurebackpack.client.gui; -import codechicken.lib.render.TextureUtils; -import com.darkona.adventurebackpack.common.Constants; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.inventory.IInventoryTanks; -import com.darkona.adventurebackpack.item.ItemHose; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import java.util.Collection; +import java.util.Iterator; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.entity.boss.BossStatus; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.client.GuiIngameForge; +import net.minecraftforge.client.IItemRenderer; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; +import cpw.mods.fml.common.eventhandler.EventPriority; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import codechicken.lib.render.TextureUtils; -import java.util.Collection; -import java.util.Iterator; +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.inventory.IInventoryTanks; +import com.darkona.adventurebackpack.item.ItemHose; +import com.darkona.adventurebackpack.reference.LoadedMods; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.reference.ToolHandler; +import com.darkona.adventurebackpack.util.GregtechUtils; +import com.darkona.adventurebackpack.util.LogHelper; +import com.darkona.adventurebackpack.util.ThaumcraftUtils; +import com.darkona.adventurebackpack.util.TinkersUtils; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 09/01/2015 @@ -38,94 +49,132 @@ */ public class GuiOverlay extends Gui { + private static final ResourceLocation GUI_ICONS = new ResourceLocation("textures/gui/icons.png"); + private static final ResourceLocation GUI_INVENTORY = new ResourceLocation("textures/gui/container/inventory.png"); + private static final ResourceLocation TANKS_OVERLAY = new ResourceLocation(ModInfo.MOD_ID, "textures/gui/overlay.png"); + private static final int BUFF_ICON_SIZE = 18; + private static final int BUFF_ICON_SPACING = 2; // 2 pixels between buff icons + private static final int BUFF_ICON_BASE_U_OFFSET = 0; + private static final int BUFF_ICON_BASE_V_OFFSET = 198; + private static final int BUFF_ICONS_PER_ROW = 8; + + private static RenderItem itemRender = new RenderItem(); + private Minecraft mc; + private FontRenderer fontRenderer; + private int screenWidth; private int screenHeight; - protected static RenderItem itemRender = new RenderItem(); - protected FontRenderer fontRendererObj; - ScaledResolution resolution; + public GuiOverlay(Minecraft mc) { super(); // We need this to invoke the render engine. this.mc = mc; - this.itemRender.renderWithColor = false; - this.fontRendererObj = mc.fontRenderer; + this.fontRenderer = mc.fontRenderer; + itemRender.renderWithColor = false; } - private static final int BUFF_ICON_SIZE = 18; - private static final int BUFF_ICON_SPACING = BUFF_ICON_SIZE + 2; // 2 pixels between buff icons - private static final int BUFF_ICON_BASE_U_OFFSET = 0; - private static final int BUFF_ICON_BASE_V_OFFSET = 198; - private static final int BUFF_ICONS_PER_ROW = 8; - - @SubscribeEvent(priority = EventPriority.NORMAL) public void onRenderExperienceBar(RenderGameOverlayEvent.Post event) { - if(event.type != RenderGameOverlayEvent.ElementType.EXPERIENCE) - { + if (event.type != RenderGameOverlayEvent.ElementType.EXPERIENCE) return; - } - resolution = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight); + + EntityPlayer player = mc.thePlayer; + ScaledResolution resolution = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight); screenWidth = resolution.getScaledWidth(); screenHeight = resolution.getScaledHeight(); - if(ConfigHandler.STATUS_OVERLAY) + + if (ConfigHandler.bossBarIndent != 0) { - int xPos = 2; - int yPos = 2; - Collection collection = this.mc.thePlayer.getActivePotionEffects(); - if (!collection.isEmpty()) + if (GuiIngameForge.renderBossHealth) + { + GuiIngameForge.renderBossHealth = false; + LogHelper.info("Forge boss bar render: disabled"); + } + drawBossBar(); + } + + if (ConfigHandler.statusOverlay) + { + int xStep = ConfigHandler.statusOverlayLeft + ? BUFF_ICON_SIZE + BUFF_ICON_SPACING + : -BUFF_ICON_SIZE - BUFF_ICON_SPACING; + int xPos = ConfigHandler.statusOverlayLeft + ? ConfigHandler.statusOverlayIndentH + : screenWidth - BUFF_ICON_SIZE - ConfigHandler.statusOverlayIndentH; + int yPos = ConfigHandler.statusOverlayTop + ? ConfigHandler.statusOverlayIndentV + : screenHeight - BUFF_ICON_SIZE - ConfigHandler.statusOverlayIndentV; + + if (LoadedMods.THAUMCRAFT + && ConfigHandler.statusOverlayThaumcraft && ConfigHandler.statusOverlayLeft + && ConfigHandler.statusOverlayTop == !ThaumcraftUtils.DIAL_BOTTOM + && ThaumcraftUtils.isTool(player.inventory.getCurrentItem())) + { + xPos += 50; // do not overlap thaumcraft GUI + } + + Collection activePotionEffects = this.mc.thePlayer.getActivePotionEffects(); + if (!activePotionEffects.isEmpty()) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); - this.mc.renderEngine.bindTexture(new ResourceLocation("textures/gui/container/inventory.png")); + this.mc.renderEngine.bindTexture(GUI_INVENTORY); - for (Iterator iterator = this.mc.thePlayer.getActivePotionEffects() - .iterator(); iterator.hasNext(); xPos += BUFF_ICON_SPACING) + for (Iterator activeEffect = activePotionEffects.iterator(); activeEffect.hasNext(); xPos += xStep) { - PotionEffect potioneffect = (PotionEffect) iterator.next(); - Potion potion = Potion.potionTypes[potioneffect.getPotionID()]; + PotionEffect potionEffect = (PotionEffect) activeEffect.next(); + Potion potion = Potion.potionTypes[potionEffect.getPotionID()]; - if (potion.hasStatusIcon()) + // yes potion should not be null here, but it sometimes does + // let the vanilla crash itself, no need to report this to us + if (potion != null && potion.hasStatusIcon()) { int iconIndex = potion.getStatusIconIndex(); this.drawTexturedModalRect( xPos, yPos, - BUFF_ICON_BASE_U_OFFSET + iconIndex % BUFF_ICONS_PER_ROW * BUFF_ICON_SIZE, BUFF_ICON_BASE_V_OFFSET + iconIndex / BUFF_ICONS_PER_ROW * BUFF_ICON_SIZE, + BUFF_ICON_BASE_U_OFFSET + iconIndex % BUFF_ICONS_PER_ROW * BUFF_ICON_SIZE, + BUFF_ICON_BASE_V_OFFSET + iconIndex / BUFF_ICONS_PER_ROW * BUFF_ICON_SIZE, BUFF_ICON_SIZE, BUFF_ICON_SIZE); } } } } - if(ConfigHandler.TANKS_OVERLAY) + if (ConfigHandler.tanksOverlay) { - EntityPlayer player= mc.thePlayer; - if(Wearing.isWearingWearable(player)) + if (Wearing.isWearingWearable(player)) { - IInventoryTanks inv = Wearing.getWearableInv(player); + IInventoryTanks inv = Wearing.getWearingWearableInv(player); assert inv != null; inv.openInventory(); int textureHeight = 23; int textureWidth = 10; - int xPos = screenWidth - (textureWidth*3) - 4 ; - //int yPos = ((screenHeight / 3) * 2) - textureHeight - 2; - int yPos = (screenHeight) - textureHeight - 2; + int xPos = ConfigHandler.tanksOverlayRight + ? screenWidth - (textureWidth * 2) - ConfigHandler.tanksOverlayIndentH + : ConfigHandler.tanksOverlayIndentH; + int yPos = ConfigHandler.tanksOverlayBottom + ? screenHeight - textureHeight - ConfigHandler.tanksOverlayIndentV + : ConfigHandler.tanksOverlayIndentV; + int tankX = xPos; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); - - int tankX = xPos; GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + if (inv.getTanksArray().length == 1 && ConfigHandler.tanksOverlayRight) + { + tankX += textureWidth + 1; // case for copter, stick lonely tank to window border + } for (FluidTank tank : inv.getTanksArray()) { - - mc.renderEngine.bindTexture(new ResourceLocation(ModInfo.MOD_ID.toLowerCase(), "textures/gui/overlay.png")); + mc.renderEngine.bindTexture(TANKS_OVERLAY); drawTexturedModalRect(tankX, yPos, 10, 0, textureWidth, textureHeight); drawTank(tank, tankX + 1, yPos + 1, textureHeight - 2, textureWidth - 2); ++tankX; @@ -133,12 +182,12 @@ public void onRenderExperienceBar(RenderGameOverlayEvent.Post event) } if (Wearing.isWearingBackpack(player)) { - int u[] = {10, 10}; - int v[] = {0, 0}; + int[] u = {10, 10}; + int[] v = {0, 0}; int[] xStart = {xPos, xPos + textureWidth + 1}; int[] yStart = {yPos, yPos}; short tank = -1; - if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof ItemHose) + if (Wearing.isHoldingHose(player)) { tank = (short) (ItemHose.getHoseTank(player.getHeldItem())); } @@ -147,22 +196,23 @@ public void onRenderExperienceBar(RenderGameOverlayEvent.Post event) u[0] = (tank == 0) ? 0 : 10; u[1] = (tank == 1) ? 0 : 10; } - mc.renderEngine.bindTexture(new ResourceLocation(ModInfo.MOD_ID.toLowerCase(), "textures/gui/overlay.png")); - - //Left Tank - drawTexturedModalRect(xStart[0], yStart[0], u[0], v[0], textureWidth, textureHeight); - //Right Tank - drawTexturedModalRect(xStart[1], yStart[0], u[1], v[1], textureWidth, textureHeight); + mc.renderEngine.bindTexture(TANKS_OVERLAY); + drawTexturedModalRect(xStart[0], yStart[0], u[0], v[0], textureWidth, textureHeight); //Left Tank + drawTexturedModalRect(xStart[1], yStart[0], u[1], v[1], textureWidth, textureHeight); //Right Tank RenderHelper.enableStandardItemLighting(); RenderHelper.enableGUIStandardItemLighting(); GL11.glPushMatrix(); - GL11.glTranslatef(xStart[1] + textureWidth + 2, yStart[0], 0); + GL11.glTranslatef(xStart[0] - textureWidth, yStart[0], 0); GL11.glScalef(0.5f, 0.5f, 0.5f); - drawItemStack(inv.getStackInSlot(Constants.upperTool), 0, 0); - drawItemStack(inv.getStackInSlot(Constants.lowerTool), 0, 16); + if (ConfigHandler.enableToolsRender) + { + ItemStack upperStack = inv.getStackInSlot(Constants.TOOL_UPPER); + ItemStack lowerStack = inv.getStackInSlot(Constants.TOOL_LOWER); + drawItemStack(upperStack, ToolHandler.getToolHandler(upperStack),0, 0); + drawItemStack(lowerStack, ToolHandler.getToolHandler(lowerStack), 0, 16); + } GL11.glPopMatrix(); RenderHelper.disableStandardItemLighting(); - } GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glDisable(GL11.GL_BLEND); @@ -189,32 +239,90 @@ private void drawTank(FluidTank tank, int startX, int startY, int height, int wi if (j >= top + 5) { GL11.glColor4f(0.9f, 0.9f, 0.9f, 1); - } else + } + else { GL11.glColor4f(1, 1, 1, 1); } - GuiTank.drawFluidPixelFromIcon(i, j, icon, 1, 1, 0, 0, 0, 0,1); + GuiTank.drawFluidPixelFromIcon(i, j, icon, 1, 1, 0, 0, 0, 0, 1); GL11.glPopMatrix(); } } - } catch (Exception oops) + } + catch (Exception oops) { LogHelper.error("Exception while trying to render the fluid in the GUI"); } } } - private void drawItemStack(ItemStack stack, int x, int y) + private void drawItemStack(ItemStack stack, ToolHandler toolHandler, int x, int y) { - if(stack == null)return; - GL11.glTranslatef(0.0F, 0.0F, 32.0F); + if (stack == null) + return; + this.zLevel = 200.0F; itemRender.zLevel = 200.0F; - FontRenderer font = null; - font = stack.getItem().getFontRenderer(stack); - if (font == null) font = fontRendererObj; - itemRender.renderItemIntoGUI(font,mc.getTextureManager(),stack,x,y); + + switch (toolHandler) + { + case GREGTECH: + GL11.glTranslatef(x, y, 32.0F); + GregtechUtils.renderTool(stack, IItemRenderer.ItemRenderType.INVENTORY); + break; + case TCONSTRUCT: + TextureManager tm = mc.getTextureManager(); + tm.bindTexture(tm.getResourceLocation(stack.getItemSpriteNumber())); + GL11.glTranslatef(x, y, 32.0F); + TinkersUtils.renderTool(stack, IItemRenderer.ItemRenderType.INVENTORY); + break; + case THAUMCRAFT: + // Forge PreRender: net.minecraftforge.client.ForgeHooksClient.renderInventoryItem + GL11.glPushMatrix(); + GL11.glTranslatef(x - 2, y + 3, -3.0F + zLevel); + GL11.glScalef(10F, 10F, 10F); + GL11.glTranslatef(1.0F, 0.5F, 1.0F); + GL11.glScalef(1.0F, 1.0F, -1F); + GL11.glRotatef(210F, 1.0F, 0.0F, 0.0F); + GL11.glRotatef(-135F, 0.0F, 1.0F, 0.0F); + // Thaumcraft Render + ThaumcraftUtils.renderTool(stack, IItemRenderer.ItemRenderType.INVENTORY); + GL11.glPopMatrix(); + break; + case VANILLA: + default: + GL11.glTranslatef(0F, 0F, 32.0F); + FontRenderer font = null; + font = stack.getItem().getFontRenderer(stack); + if (font == null) font = fontRenderer; + itemRender.renderItemIntoGUI(font, mc.getTextureManager(), stack, x, y); + break; + } + this.zLevel = 0.0F; itemRender.zLevel = 0.0F; } + + private void drawBossBar() + { + if (BossStatus.bossName != null && BossStatus.statusBarTime > 0) + { + --BossStatus.statusBarTime; + GL11.glEnable(GL11.GL_BLEND); + int barWidth = 182; + int posX = screenWidth / 2 - barWidth / 2; + int posY = ConfigHandler.bossBarIndent; + int bossHealthWidth = (int) (BossStatus.healthScale * (barWidth + 1)); + this.mc.getTextureManager().bindTexture(GUI_ICONS); + this.drawTexturedModalRect(posX, posY, 0, 74, barWidth, 5); + this.drawTexturedModalRect(posX, posY, 0, 74, barWidth, 5); + if (bossHealthWidth > 0) + this.drawTexturedModalRect(posX, posY, 0, 79, bossHealthWidth, 5); + String s = BossStatus.bossName; + fontRenderer.drawStringWithShadow(s, screenWidth / 2 - fontRenderer.getStringWidth(s) / 2, posY - 10, 16777215); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glDisable(GL11.GL_BLEND); + } + } + } diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiSteamJetpack.java b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiSteamJetpack.java deleted file mode 100644 index e3bda14a..00000000 --- a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiSteamJetpack.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.darkona.adventurebackpack.client.gui; - -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.config.Keybindings; -import com.darkona.adventurebackpack.init.ModNetwork; -import com.darkona.adventurebackpack.inventory.ContainerJetpack; -import com.darkona.adventurebackpack.inventory.InventorySteamJetpack; -import com.darkona.adventurebackpack.network.EquipUnequipBackWearablePacket; -import com.darkona.adventurebackpack.util.Resources; -import com.darkona.adventurebackpack.util.Utils; -import com.darkona.adventurebackpack.util.Wearing; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidTank; -import org.lwjgl.input.Keyboard; -import org.lwjgl.opengl.GL11; - -/** - * Created on 15/01/2015 - * - * @author Darkona - */ -public class GuiSteamJetpack extends GuiWithTanks -{ - private static final ResourceLocation texture = Resources.guiTextures("guiSteamJetpack"); - private static GuiTank waterTank = new GuiTank(8, 8,72, 16, ConfigHandler.GUI_TANK_RENDER); - private static GuiTank steamTank = new GuiTank(116, 8,72, 16, ConfigHandler.GUI_TANK_RENDER); - private static GuiImageButtonNormal equipButton = new GuiImageButtonNormal(150, 64, 18, 18); - private static GuiImageButtonNormal unequipButton = new GuiImageButtonNormal(150, 64, 18, 18); - private boolean wearing; - EntityPlayer player; - InventorySteamJetpack inventory; - int boiling = 0; - public GuiSteamJetpack(EntityPlayer player, InventorySteamJetpack inventory, boolean wearing) - { - super(new ContainerJetpack(player, inventory,wearing)); - this.wearing = wearing; - this.player = player; - this.inventory = inventory; - xSize = 176; - ySize = 166; - } - - - - @Override - protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int mouseX, int mouseY) - { - inventory.openInventory(); - this.mc.renderEngine.bindTexture(texture); - drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); - - if(wearing) - { - if(unequipButton.inButton(this,mouseX,mouseY)) - { - unequipButton.draw(this,20,186); - }else - { - unequipButton.draw(this,1,186); - } - }else - { - if(equipButton.inButton(this,mouseX,mouseY)) - { - equipButton.draw(this,20,167); - }else - { - equipButton.draw(this,1,167); - } - } - - - - - - // if(wearing) inventory = new InventorySteamJetpack(Wearing.getWearingSteam(player)); - - - - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) - { - this.mc.renderEngine.bindTexture(texture); - if(wearing) inventory = new InventorySteamJetpack(Wearing.getWearingSteam(player)); - FluidTank water = inventory.getWaterTank(); - FluidTank steam = inventory.getSteamTank(); - GL11.glPushMatrix(); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - if( inventory.isBoiling() - && steam.getFluidAmount() < steam.getCapacity() - && water.getFluidAmount() > 0) - { - if(boiling < 83) - { - drawTexturedModalRect(28,40,50,172,boiling++,37); - }else boiling = 0; - } - if(inventory.getBurnTicks() > 0) - { - int i1 =inventory.getBurnTimeRemainingScaled(13); - this.drawTexturedModalRect(78, 48 + 12 - i1, 176, 12 - i1, 14, i1 + 1); - } - - int H = Math.round(((float)72 / (float)InventorySteamJetpack.MAX_TEMPERATURE) * (float)inventory.getTemperature()); - drawTexturedModalRect( 139, 8 + (72- H), 40, 167 + (72 - H), 5, H); - - GL11.glDisable(GL11.GL_BLEND); - GL11.glPopMatrix(); - GL11.glDisable(GL11.GL_LIGHTING); - - - waterTank.draw(this, water); - steamTank.draw(this,steam); - - float factor = 0.7f; - - String show = ((water.getFluidAmount() > 0) ? Utils.capitalize(FluidRegistry.getFluidName(water.getFluid())) : "None")+ "-" + water.getFluidAmount(); - - GL11.glPushMatrix(); - GL11.glTranslatef(70, 10, 0); - GL11.glScalef(factor, factor, factor); - fontRendererObj.drawString(show, 0, 0, 0x373737, false); - GL11.glScalef(1, 1, 1); - GL11.glPopMatrix(); - - show = ((steam.getFluidAmount() > 0) ? Utils.capitalize(FluidRegistry.getFluidName(steam.getFluid())) : "None") + "-" + steam.getFluidAmount(); - - GL11.glPushMatrix(); - GL11.glTranslatef(70, 20, 0); - GL11.glScalef(factor, factor, factor); - fontRendererObj.drawString(show, 0, 0, 0x373737, false); - GL11.glScalef(1, 1, 1); - GL11.glPopMatrix(); - - GL11.glPushMatrix(); - GL11.glTranslatef(145,8,0); - GL11.glScalef(0.9f, 0.9f, 0.9f); - fontRendererObj.drawString((inventory.getTemperature()) + " C", 0, 0, 0x373737, false); - GL11.glScalef(1, 1, 1); - GL11.glPopMatrix(); - - - - - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) - { - int sneakKey = Minecraft.getMinecraft().gameSettings.keyBindSneak.getKeyCode(); - if(wearing) - { - if(unequipButton.inButton(this,mouseX,mouseY)) - { - ModNetwork.net.sendToServer(new EquipUnequipBackWearablePacket.Message(EquipUnequipBackWearablePacket.UNEQUIP_WEARABLE,false)); - player.closeScreen(); - } - } else - { - if(equipButton.inButton(this,mouseX,mouseY)) - { - ModNetwork.net.sendToServer(new EquipUnequipBackWearablePacket.Message(EquipUnequipBackWearablePacket.EQUIP_WEARABLE, Keyboard.isKeyDown(sneakKey))); - player.closeScreen(); - } - } - super.mouseClicked(mouseX, mouseY, mouseButton); - } - - @Override - public int getLeft() - { - return guiLeft; - } - - @Override - public int getTop() - { - return guiTop; - } - - @Override - public float getZLevel() - { - return zLevel; - } - - @Override - protected void keyTyped(char key, int keycode) - { - if (keycode == Keybindings.openBackpack.getKeyCode()) - { - player.closeScreen(); - } - super.keyTyped(key, keycode); - } -} diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiTank.java b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiTank.java index 0f79b777..e342d7a4 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiTank.java +++ b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiTank.java @@ -1,19 +1,21 @@ package com.darkona.adventurebackpack.client.gui; -import codechicken.lib.render.TextureUtils; -import com.darkona.adventurebackpack.common.Constants; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.util.LogHelper; +import java.util.ArrayList; +import java.util.List; + +import org.lwjgl.opengl.GL11; + import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; -import org.lwjgl.opengl.GL11; +import codechicken.lib.render.TextureUtils; -import java.util.ArrayList; -import java.util.List; +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.util.LogHelper; /** * Created by Darkona on 12/10/2014. @@ -34,7 +36,7 @@ public class GuiTank /** * Draws the fluid from a fluidTank in a GUI. * - * @param X The startX coordinate to start drawing from. + * @param X The startX coordinate to start drawing from. * @param Y The startY coordinate to start drawing from. * @param H The height in pixels of the tank. * @param W The width in pixels of the tank. @@ -57,24 +59,19 @@ public List getTankTooltip() { FluidStack fluid = tank.getFluid(); String fluidName = (fluid != null) ? fluid.getLocalizedName() : "None"; - String fluidAmount = (fluid != null) ? fluid.amount + "/" + Constants.basicTankCapacity : "Empty"; + String fluidAmount = (fluid != null) ? fluid.amount + "/" + Constants.BASIC_TANK_CAPACITY : "Empty"; ArrayList tankTips = new ArrayList(); tankTips.add(fluidName); tankTips.add(fluidAmount); return tankTips; } - /** - * @param gui - * @param theFluid - */ public void draw(GuiWithTanks gui, FluidTank theFluid) { - tank = theFluid; liquidPerPixel = tank.getCapacity() / this.height; - this.zLevel = gui.getZLevel()+1; - switch (ConfigHandler.GUI_TANK_RENDER) + this.zLevel = gui.getZLevel() + 1; + switch (ConfigHandler.typeTankRender) { case 1: drawMethodOne(gui); @@ -89,7 +86,6 @@ public void draw(GuiWithTanks gui, FluidTank theFluid) drawMethodThree(); break; } - } public void draw(GuiWithTanks gui, FluidTank theFluid, int X, int Y) @@ -99,13 +95,9 @@ public void draw(GuiWithTanks gui, FluidTank theFluid, int X, int Y) draw(gui, theFluid); } - /** - * @param gui - * @param - */ private void drawMethodOne(GuiWithTanks gui) { - if(tank.getFluid() != null) + if (tank.getFluid() != null) { FluidStack fluid = tank.getFluid(); @@ -126,12 +118,9 @@ private void drawMethodOne(GuiWithTanks gui) } } - /** - * @param - */ private void drawMethodTwo() { - if(tank.getFluid() != null) + if (tank.getFluid() != null) { FluidStack fluid = tank.getFluid(); @@ -155,12 +144,9 @@ private void drawMethodTwo() } } - /** - * @param - */ private void drawMethodThree() { - if(tank.getFluid() != null) + if (tank.getFluid() != null) { FluidStack fluid = tank.getFluid(); @@ -177,7 +163,8 @@ private void drawMethodThree() if (j >= top + 5) { GL11.glColor4f(0.9f, 0.9f, 0.9f, 1); - } else + } + else { GL11.glColor4f(1, 1, 1, 1); } @@ -185,7 +172,8 @@ private void drawMethodThree() GL11.glPopMatrix(); } } - } catch (Exception oops) + } + catch (Exception oops) { LogHelper.error("Exception while trying to render the fluid in the GUI"); //oops.printStackTrace(); @@ -193,12 +181,6 @@ private void drawMethodThree() } } - /** - * @param gui - * @param mouseX - * @param mouseY - * @return - */ public boolean inTank(GuiWithTanks gui, int mouseX, int mouseY) { mouseX -= gui.getLeft(); @@ -214,14 +196,10 @@ public boolean inTank(GuiWithTanks gui, int mouseX, int mouseY) * @param icon The icon to draw from. * @param w The Width of the drawed box. * @param h The height of the drawed box. - * @param srcX The startX coordinate from the icon to start drawing from. Starts - * at 0. - * @param srcY The startY coordinate from the icon to start drawing from. Starts - * at 0. - * @param srcW The width of the selection in the icon to draw from. Starts at - * 0. - * @param srcH The height of the selection in the icon to draw from. Starts - * at 0. + * @param srcX The startX coordinate from the icon to start drawing from. Starts at 0. + * @param srcY The startY coordinate from the icon to start drawing from. Starts at 0. + * @param srcW The width of the selection in the icon to draw from. Starts at 0. + * @param srcH The height of the selection in the icon to draw from. Starts at 0. */ public static void drawFluidPixelFromIcon(int x, int y, IIcon icon, int w, int h, int srcX, int srcY, int srcW, int srcH, float zLevel) { @@ -246,7 +224,5 @@ public static void drawFluidPixelFromIcon(int x, int y, IIcon icon, int w, int h tessellator.addVertexWithUV(x + w, y, zLevel, newMaxU, newMinV); tessellator.addVertexWithUV(x, y, zLevel, newMinU, newMinV); tessellator.draw(); - - } } diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiWithTanks.java b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiWithTanks.java index 4e2b1b2f..1c09babd 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/gui/GuiWithTanks.java +++ b/src/main/java/com/darkona/adventurebackpack/client/gui/GuiWithTanks.java @@ -1,8 +1,16 @@ package com.darkona.adventurebackpack.client.gui; +import org.lwjgl.input.Mouse; + import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; +import com.darkona.adventurebackpack.common.Constants.Source; +import com.darkona.adventurebackpack.config.Keybindings; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.network.EquipUnequipBackWearablePacket; + /** * Created on 06/01/2015 * @@ -10,21 +18,88 @@ */ public abstract class GuiWithTanks extends GuiContainer { - public GuiWithTanks(Container p_i1072_1_) + protected EntityPlayer player; + protected Source source; + + GuiWithTanks(Container container) { - super(p_i1072_1_); + super(container); } - public int getLeft() + int getLeft() { return guiLeft; } - public int getTop() + int getTop() { return guiTop; } - public float getZLevel() {return zLevel;} + float getZLevel() + { + return zLevel; + } + + protected abstract GuiImageButtonNormal getEquipButton(); + + protected abstract GuiImageButtonNormal getUnequipButton(); + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) + { + if (source == Source.WEARING) + { + if (getUnequipButton().inButton(this, mouseX, mouseY)) + { + ModNetwork.net.sendToServer(new EquipUnequipBackWearablePacket.Message(EquipUnequipBackWearablePacket.UNEQUIP_WEARABLE)); + player.closeScreen(); + } + } + else if (source == Source.HOLDING) + { + if (getEquipButton().inButton(this, mouseX, mouseY)) + { + ModNetwork.net.sendToServer(new EquipUnequipBackWearablePacket.Message(EquipUnequipBackWearablePacket.EQUIP_WEARABLE)); + player.closeScreen(); + } + } + + super.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + protected void keyTyped(char key, int keycode) + { + if (keycode == Keybindings.openInventory.getKeyCode()) + { + player.closeScreen(); + } + + super.keyTyped(key, keycode); + } + + @Override + public void handleMouseInput() + { + if (Mouse.getEventDWheel() != 0) + { + int i = Mouse.getEventX() * this.width / this.mc.displayWidth; + int j = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + int marginX = (width - xSize) / 2; + int marginY = (height - ySize) / 2; + + if (i > marginX && i < marginX + xSize) + { + if (j > marginY && j < marginY + ySize) + { + return; + // forbid mouseWheel when mouse over our GUI, + // Shift+Wheel on stacks of fluid containers places them to clients bucket slots, causes desync + } + } + } + + super.handleMouseInput(); + } } diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/IBackpackGui.java b/src/main/java/com/darkona/adventurebackpack/client/gui/IBackpackGui.java deleted file mode 100644 index 682d1254..00000000 --- a/src/main/java/com/darkona/adventurebackpack/client/gui/IBackpackGui.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.darkona.adventurebackpack.client.gui; - -import net.minecraft.util.IIcon; - -/** - * Created on 12/10/2014 - * - * @author Darkona - */ -public interface IBackpackGui -{ - - public void drawTexturedModelRectFromIcon(int i, int j, IIcon icon, int h, int w); - - public int getLeft(); - - public int getTop(); - - //public void drawTexturedModalRect(int i, int j, int srcX, int srcY, int w, int h); - - public float getZLevel(); -} diff --git a/src/main/java/com/darkona/adventurebackpack/client/gui/ModGuiConfig.java b/src/main/java/com/darkona/adventurebackpack/client/gui/ModGuiConfig.java index dc296233..3edba703 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/gui/ModGuiConfig.java +++ b/src/main/java/com/darkona/adventurebackpack/client/gui/ModGuiConfig.java @@ -1,25 +1,39 @@ package com.darkona.adventurebackpack.client.gui; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.reference.ModInfo; -import cpw.mods.fml.client.config.GuiConfig; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.common.config.Configuration; +import cpw.mods.fml.client.config.GuiConfig; +import cpw.mods.fml.client.config.IConfigElement; + +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.reference.ModInfo; /** * Created by Darkona on 10/10/2014. */ public class ModGuiConfig extends GuiConfig { - public ModGuiConfig(GuiScreen guiScreen) { - super(guiScreen, - new ConfigElement(ConfigHandler.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), - ModInfo.MOD_ID, - false, - false, - GuiConfig.getAbridgedConfigPath(ConfigHandler.config.toString())); + super(guiScreen, getConfigElements(), ModInfo.MOD_ID, false, false, ModInfo.MOD_NAME); + } + + private static List getConfigElements() + { + List configElements = new ArrayList<>(); + + List topCategories = Arrays.asList("gameplay", "graphics", "sound", "items", "worldgen", "experimental"); + for (String categoryName : topCategories) + { + ConfigCategory category = ConfigHandler.config.getCategory(categoryName); + configElements.add(new ConfigElement(category)); + } + return configElements; } } + diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelAdventureHat.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelAdventureHat.java index 57b91b43..01b16a0b 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelAdventureHat.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelAdventureHat.java @@ -6,10 +6,9 @@ public class ModelAdventureHat extends ModelBiped { - //fields - ModelRenderer wing; - ModelRenderer top; - ModelRenderer thing; + private ModelRenderer wing; + private ModelRenderer top; + private ModelRenderer thing; public static ModelAdventureHat instance = new ModelAdventureHat(); @@ -44,6 +43,7 @@ public ModelAdventureHat() this.bipedHead.addChild(thing); } + @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { setRotationAngles(entity, f, f1, f2, f3, f4, f5); @@ -54,12 +54,9 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f ((ModelRenderer) part).rotateAngleY = bipedHead.rotateAngleY; ((ModelRenderer) part).rotateAngleZ = bipedHead.rotateAngleZ; } - /*GL11.glPushMatrix(); - GL11.glScalef(1.2f, 1.2f, 1.2f);*/ wing.render(f5); thing.render(f5); top.render(f5); - /* GL11.glPopMatrix();*/ } private void setRotation(ModelRenderer model, float x, float y, float z) @@ -73,5 +70,4 @@ public void setRotationAngles(Entity entity, float f, float f1, float f2, float { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); } - } \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelBackpackArmor.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelBackpackArmor.java index fe5e9b35..387e027c 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelBackpackArmor.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelBackpackArmor.java @@ -1,15 +1,22 @@ package com.darkona.adventurebackpack.client.models; +import java.util.List; + +import org.lwjgl.opengl.GL11; + +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.entity.Entity; +import net.minecraft.item.ItemStack; import codechicken.lib.vec.Vector3; + import com.darkona.adventurebackpack.client.render.RendererStack; import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.config.ConfigHandler; import com.darkona.adventurebackpack.inventory.InventoryBackpack; -import net.minecraft.client.model.ModelRenderer; -import net.minecraft.entity.Entity; -import net.minecraft.item.ItemStack; -import org.lwjgl.opengl.GL11; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.reference.ToolHandler; -import java.util.List; +import static com.darkona.adventurebackpack.reference.BackpackTypes.*; /** * Created on 17/12/2014 @@ -59,7 +66,6 @@ private void init() this.textureHeight = 64; //Main Backpack - this.mainBody = new ModelRenderer(this, 0, 9); this.mainBody.addBox(-5.0F, 0.0F, -3.0F, 10, 9, 5); this.mainBody.setRotationPoint(0.0F, 0.0F, 0.0F); @@ -90,7 +96,6 @@ private void init() this.mainBody.addChild(this.pocketFace); //Left Tank - this.tankLeftTop = new ModelRenderer(this, 0, 40); this.tankLeftTop.setRotationPoint(5.0F, -1.0F, -2.5F); this.tankLeftTop.addBox(0.0F, 0.0F, 0.0F, 4, 1, 4); @@ -121,7 +126,6 @@ private void init() this.tankLeftBottom.addChild(this.tankLeftWall4); //Right Tank - this.tankRightTop = new ModelRenderer(this, 17, 40); this.tankRightTop.setRotationPoint(-9.0F, -1.0F, -2.5F); this.tankRightTop.addBox(0.0F, 0.0F, 0.0F, 4, 1, 4); @@ -152,7 +156,6 @@ private void init() this.tankRightBottom.addChild(this.tankRightWall4); //Bed - this.bed = new ModelRenderer(this, 31, 0); this.bed.setRotationPoint(-7.0F, 7.0F, 2.0F); this.bed.addBox(0.0F, 0.0F, 0.0F, 14, 2, 2); @@ -188,7 +191,6 @@ private void init() this.bed.addChild(this.bedStrapLeftBottom); //Noses - this.villagerNose = new ModelRenderer(this, 64, 0); this.villagerNose.setRotationPoint(-1.0F, 4.0F, 4.0F); this.villagerNose.addBox(0.0F, 0.0F, 0.0F, 2, 4, 2); @@ -204,7 +206,6 @@ private void init() lowerTool = new RendererStack(this, true); upperTool = new RendererStack(this, false); - bipedBody.addChild(mainBody); bipedBody.addChild(bed); bipedBody.addChild(tankLeftTop); @@ -215,11 +216,9 @@ private void init() mainBody.addChild(lowerTool); mainBody.addChild(upperTool); - float offsetZ = 0.4F; float offsetY = 0.2F; - for (ModelRenderer part : (List) bipedBody.childModels) { setOffset(part, part.offsetX + 0, part.offsetY + offsetY, part.offsetZ + offsetZ); @@ -232,6 +231,7 @@ public ModelBackpackArmor setWearable(ItemStack wearable) this.backpack = wearable; return this; } + public ModelBackpackArmor() { init(); @@ -242,12 +242,13 @@ public ModelBackpackArmor(ItemStack backpack) init(); this.backpack = backpack; } + @SuppressWarnings("unchecked") private void renderBackpack(Float scale) { InventoryBackpack backpack = new InventoryBackpack(this.backpack); backpack.openInventory(); - String color = backpack.getColorName(); + BackpackTypes type = backpack.getType(); for (ModelRenderer model : (List) bipedBody.childModels) { model.mirror = false; @@ -257,15 +258,21 @@ private void renderBackpack(Float scale) setOffset(lowerTool, -.28F, 0.8F, -.1F); setOffset(upperTool, 0.0f, 0.04f, 0.25f); - lowerTool.stack = backpack.getStackInSlot(Constants.lowerTool); - upperTool.stack = backpack.getStackInSlot(Constants.upperTool); + if (ConfigHandler.enableToolsRender) + { + ItemStack upperStack = backpack.getStackInSlot(Constants.TOOL_UPPER); + ItemStack lowerStack = backpack.getStackInSlot(Constants.TOOL_LOWER); + upperTool.setStack(upperStack, ToolHandler.getToolHandler(upperStack)); + lowerTool.setStack(lowerStack, ToolHandler.getToolHandler(lowerStack)); + } - if (color.equals("Quartz") || color.equals("Slime") || color.equals("Snow")) + if (type == QUARTZ || type == SLIME || type == SNOW) { startBlending(); this.mainBody.render(scale); stopBlending(); - } else + } + else { this.mainBody.render(scale); } @@ -276,15 +283,15 @@ private void renderBackpack(Float scale) tankRightTop.render(scale); bed.render(scale); - if (color.equals("Pig") || color.equals("Horse")) + if (type == PIG || type == HORSE) { pigNose.render(scale); } - if (color.equals("Villager") || color.equals("IronGolem")) + if (type == VILLAGER || type == IRON_GOLEM) { villagerNose.render(scale); } - if (color.equals("Ocelot")) + if (type == OCELOT) { ocelotNose.render(scale); } @@ -293,16 +300,15 @@ private void renderBackpack(Float scale) GL11.glPushMatrix(); GL11.glTranslatef(bipedBody.offsetX + 0, bipedBody.offsetY + 0.2F, bipedBody.offsetZ + 0.3f); - renderFluidInTank(backpack.getLeftTank(), new Vector3(0f,.5f,0f), new Vector3(.17f,0,.17f), new Vector3(-.17f, .05f, .2f), tankLeftTop); + renderFluidInTank(backpack.getLeftTank(), new Vector3(0f, .5f, 0f), new Vector3(.17f, 0, .17f), new Vector3(-.17f, .05f, .2f), tankLeftTop); - renderFluidInTank(backpack.getRightTank(), new Vector3(0f,.5f,0f), new Vector3(.17f,0,.17f), new Vector3(.41f, .05f, .2f), tankRightTop); + renderFluidInTank(backpack.getRightTank(), new Vector3(0f, .5f, 0f), new Vector3(.17f, 0, .17f), new Vector3(.41f, .05f, .2f), tankRightTop); GL11.glPopMatrix(); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { - isSneak = ((entity != null) && (entity).isSneaking()); setRotationAngles(f, f1, f2, f3, f4, f5, entity); float oV = (isSneak) ? 0 : .3F; @@ -319,13 +325,15 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f if (bipedBody.rotationPointX == 0.0F && bipedBody.rotationPointY == 0.0F && bipedBody.rotationPointZ == 0.0F) { renderBackpack(scale); - } else + } + else { GL11.glTranslatef(bipedBody.rotationPointX * f5, bipedBody.rotationPointY * f5, bipedBody.rotationPointZ * f5); renderBackpack(scale); GL11.glTranslatef(-bipedBody.rotationPointX * f5, -bipedBody.rotationPointY * f5, -bipedBody.rotationPointZ * f5); } - } else + } + else { GL11.glPushMatrix(); GL11.glTranslatef(bipedBody.rotationPointX * f5, bipedBody.rotationPointY * f5, bipedBody.rotationPointZ * f5); @@ -355,6 +363,6 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5, ItemStack stack) { this.backpack = stack; - render(entity, f, f1,f2,f3,f4,f5); + render(entity, f, f1, f2, f3, f4, f5); } } diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelBackpackBlock.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelBackpackBlock.java index 87875268..5cf69fd2 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelBackpackBlock.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelBackpackBlock.java @@ -1,16 +1,21 @@ package com.darkona.adventurebackpack.client.models; +import org.lwjgl.opengl.GL11; + +import net.minecraft.client.model.ModelBase; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.entity.Entity; +import net.minecraftforge.fluids.FluidTank; import codechicken.lib.render.CCRenderState; import codechicken.lib.render.RenderUtils; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; + import com.darkona.adventurebackpack.common.Constants; -import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; -import net.minecraft.client.model.ModelBase; -import net.minecraft.client.model.ModelRenderer; -import net.minecraft.entity.Entity; -import net.minecraftforge.fluids.FluidTank; -import org.lwjgl.opengl.GL11; +import com.darkona.adventurebackpack.inventory.IInventoryBackpack; +import com.darkona.adventurebackpack.reference.BackpackTypes; + +import static com.darkona.adventurebackpack.reference.BackpackTypes.*; /** * Created on 17/12/2014 @@ -66,7 +71,6 @@ public ModelBackpackBlock() this.textureHeight = 64; //Main Backpack - this.mainBody = new ModelRenderer(this, 0, 9); this.mainBody.setRotationPoint(0.0F, 0.0F, 0.0F); this.mainBody.addBox(-5.0F, 0.0F, -3.0F, 10, 9, 5); @@ -97,7 +101,6 @@ public ModelBackpackBlock() this.mainBody.addChild(this.pocketFace); //Left Tank - this.tankLeftTop = new ModelRenderer(this, 0, 40); this.tankLeftTop.setRotationPoint(5.0F, 0.0F, -2.5F); this.tankLeftTop.addBox(0.0F, 0.0F, 0.0F, 4, 1, 4); @@ -128,7 +131,6 @@ public ModelBackpackBlock() this.tankLeftBottom.addChild(this.tankLeftWall4); //Right Tank - this.tankRightTop = new ModelRenderer(this, 17, 40); this.tankRightTop.setRotationPoint(-9.0F, 0.0F, -2.5F); this.tankRightTop.addBox(0.0F, 0.0F, 0.0F, 4, 1, 4); @@ -159,7 +161,6 @@ public ModelBackpackBlock() this.tankRightBottom.addChild(this.tankRightWall4); //Bed - this.bed = new ModelRenderer(this, 31, 0); this.bed.setRotationPoint(-7.0F, 7.0F, 2.0F); this.bed.addBox(0.0F, 0.0F, 0.0F, 14, 2, 2); @@ -195,7 +196,6 @@ public ModelBackpackBlock() this.bed.addChild(this.bedStrapLeftBottom); //Lamp - this.lampPole1 = new ModelRenderer(this, 32, 24); this.lampPole1.setRotationPoint(5.0F, -10.0F, -1.0F); this.lampPole1.addBox(0.0F, 0.0F, 0.0F, 1, 10, 1); @@ -245,7 +245,6 @@ public ModelBackpackBlock() this.lampLight.addBox(0.0F, 0.0F, 0.0F, 3, 4, 3); //Kitchen - this.kitchenBase = new ModelRenderer(this, 49, 46); this.kitchenBase.setRotationPoint(-9.0F, -1.0F, -1.5F); this.kitchenBase.addBox(0.0F, 0.0F, 0.0F, 3, 1, 2); @@ -256,7 +255,6 @@ public ModelBackpackBlock() this.kitchenBase.addChild(this.kitchen); //Noses - this.villagerNose = new ModelRenderer(this, 64, 0); this.villagerNose.setRotationPoint(-1.0F, 4.0F, 4.0F); this.villagerNose.addBox(0.0F, 0.0F, 0.0F, 2, 4, 2); @@ -268,14 +266,12 @@ public ModelBackpackBlock() this.pigNose = new ModelRenderer(this, 74, 0); this.pigNose.setRotationPoint(-2.0F, 4.0F, 4.0F); this.pigNose.addBox(0.0F, 0.0F, 0.0F, 4, 3, 1); - } - public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float scale, IInventoryAdventureBackpack backpack) + public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float scale, IInventoryBackpack backpack) { - //scale*=0.9; - boolean sleepingbag = backpack.isSBDeployed(); + boolean sleepingbag = backpack.isSleepingBagDeployed(); FluidTank tankLeft = backpack.getLeftTank(); FluidTank tankRight = backpack.getRightTank(); setRotationAngles(f, f1, f2, f3, f4, scale, entity); @@ -287,7 +283,9 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f if (tankLeft != null && tankLeft.getFluid() != null && tankLeft.getFluid().getFluid().getIcon() != null) { - Vector3 victor = new Vector3((tankLeftTop.rotationPointX * 0.1f - 0.22f), (tankLeftTop.rotationPointY * 0.1f + 0.05f), + Vector3 victor = new Vector3( + (tankLeftTop.rotationPointX * 0.1f - 0.22f), + (tankLeftTop.rotationPointY * 0.1f + 0.05f), (tankLeftTop.rotationPointZ * 0.1f + 0.15f)); GL11.glPushMatrix(); CCRenderState.reset(); @@ -301,7 +299,9 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f if (tankRight != null && tankRight.getFluid() != null && tankRight.getFluid().getFluid().getIcon() != null) { - Vector3 victor = new Vector3((tankRightTop.rotationPointX * 0.1f + 0.48f), (tankRightTop.rotationPointY * 0.1f + 0.05f), + Vector3 victor = new Vector3( + (tankRightTop.rotationPointX * 0.1f + 0.48f), + (tankRightTop.rotationPointY * 0.1f + 0.05f), (tankRightTop.rotationPointZ * 0.1f + 0.15f)); GL11.glPushMatrix(); CCRenderState.reset(); @@ -341,7 +341,7 @@ private void renderFluidsInTanks(FluidTank tankLeft, FluidTank tankRight, float Cuboid6 left = new Cuboid6(minX, minY, minZ, maxX, maxY, maxZ); //Thanks Chickenbones! - RenderUtils.renderFluidCuboid(tankLeft.getFluid(), left.add(victor), ((1.0F * tankLeft.getFluidAmount()) / (1.0F * Constants.basicTankCapacity)), 0.2); + RenderUtils.renderFluidCuboid(tankLeft.getFluid(), left.add(victor), ((1.0F * tankLeft.getFluidAmount()) / (1.0F * Constants.BASIC_TANK_CAPACITY)), 0.2); } if (tankRight != null && tankRight.getFluid() != null && tankRight.getFluid().getFluid().getIcon() != null) @@ -359,16 +359,16 @@ private void renderFluidsInTanks(FluidTank tankLeft, FluidTank tankRight, float CCRenderState.useNormals = true; Cuboid6 right = new Cuboid6(minX, minY, minZ, maxX, maxY, maxZ); - RenderUtils.renderFluidCuboid(tankRight.getFluid(), right.add(victor), ((1.0F * tankRight.getFluidAmount()) / (1.0F * Constants.basicTankCapacity)), 0.2); + RenderUtils.renderFluidCuboid(tankRight.getFluid(), right.add(victor), ((1.0F * tankRight.getFluidAmount()) / (1.0F * Constants.BASIC_TANK_CAPACITY)), 0.2); } } - private void renderBackpack(IInventoryAdventureBackpack backpack, float scale) + private void renderBackpack(IInventoryBackpack backpack, float scale) { - String color = backpack.getColorName(); + BackpackTypes type = backpack.getType(); - if (color.equals("Quartz") || color.equals("Slime") || color.equals("Snow")) + if (type == QUARTZ || type == SLIME || type == SNOW) { GL11.glPushMatrix(); GL11.glEnable(GL11.GL_BLEND); @@ -380,30 +380,30 @@ private void renderBackpack(IInventoryAdventureBackpack backpack, float scale) GL11.glPopMatrix(); //GL11.glDisable(GL11.GL_CULL_FACE); GL11.glDisable(GL11.GL_BLEND); - - } else + } + else { this.mainBody.render(scale); } tankLeftTop.render(scale); tankRightTop.render(scale); - if (!backpack.isSBDeployed()) bed.render(scale); + if (!backpack.isSleepingBagDeployed()) bed.render(scale); - if (color.equals("Pig") || color.equals("Horse")) + if (type == PIG || type == HORSE) { pigNose.render(scale); } - if (color.equals("Villager") || color.equals("IronGolem")) + if (type == VILLAGER || type == IRON_GOLEM) { villagerNose.render(scale); } - if (color.equals("Ocelot")) + if (type == OCELOT) { ocelotNose.render(scale); } - /*if(color.equals("Standard")) + /*if(type == STANDARD) { GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelCampFire.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelCampFire.java index f04fd5de..687137b5 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelCampFire.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelCampFire.java @@ -146,5 +146,4 @@ public void setRotateAngle(ModelRenderer modelRenderer, float x, float y, float modelRenderer.rotateAngleY = y; modelRenderer.rotateAngleZ = z; } - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelClockworkCrossbow.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelClockworkCrossbow.java index 0580c0d8..9082545c 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelClockworkCrossbow.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelClockworkCrossbow.java @@ -1,13 +1,16 @@ package com.darkona.adventurebackpack.client.models; -import com.darkona.adventurebackpack.client.render.RendererStack; -import com.darkona.adventurebackpack.util.Utils; +import org.lwjgl.opengl.GL11; + import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import org.lwjgl.opengl.GL11; + +import com.darkona.adventurebackpack.client.render.RendererStack; +import com.darkona.adventurebackpack.reference.ToolHandler; +import com.darkona.adventurebackpack.util.Utils; /** * clockworkCrossbow - Darkona @@ -99,8 +102,6 @@ public ModelClockworkCrossbow() this.sniperLeg1_1.addBox(-0.5F, 0.0F, -0.5F, 1, 7, 1, 0.0F); this.setRotateAngle(sniperLeg1_1, 0.0F, 0.0F, -0.4363323129985824F); - - this.hookTooth2 = new ModelRenderer(this, 0, 0); this.hookTooth2.setRotationPoint(0.0F, -1.0F, -1.0F); this.hookTooth2.addBox(0.0F, 0.0F, 0.0F, 3, 1, 1, 0.0F); @@ -155,7 +156,6 @@ public ModelClockworkCrossbow() this.leftArc3.addBox(0.0F, 0.0F, 0.0F, 8, 2, 2, 0.0F); this.setRotateAngle(leftArc3, 0.0F, -0.7853981633974483F, 0.0F); - this.reloader2 = new ModelRenderer(this, 0, 44); this.reloader2.setRotationPoint(6.0F, 1.0F, 0.0F); this.reloader2.addBox(0.0F, -0.5F, -0.5F, 1, 4, 1, 0.0F); @@ -173,7 +173,6 @@ public ModelClockworkCrossbow() this.hookTooth3.setRotationPoint(0.0F, 3.0F, 3.0F); this.hookTooth3.addBox(0.0F, 0.0F, 0.0F, 3, 1, 1, 0.0F); - this.hookHead.addChild(this.hookTooth1); this.reloader2.addChild(this.reloader3); this.sniperLeg1_1.addChild(this.shape38); @@ -194,18 +193,18 @@ public ModelClockworkCrossbow() this.hookHead.addChild(this.hookTooth3); arrow = new RendererStack(this, true); - arrow.stack = new ItemStack(Items.arrow, 1); + arrow.setStack(new ItemStack(Items.arrow, 1), ToolHandler.VANILLA); } public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5, ItemStack xbow) { this.xbow = xbow; - render(entity,f,f1,f2,f3,f4,f5); + render(entity, f, f1, f2, f3, f4, f5); } + @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { - this.wheel.render(f5); this.reloader1.render(f5); this.sniperLeg1.render(f5); @@ -217,13 +216,11 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f this.point.render(f5); this.handle2.render(f5); - this.handle.render(1/18f); + this.handle.render(1 / 18f); this.magazine.render(f5); - ModelRenderer[] arrows = {arrow1, arrow2, arrow3}; - setRotateAngle(arrow, Utils.degreesToRadians(-90), Utils.degreesToRadians(0), Utils.degreesToRadians(0)); for (ModelRenderer model : arrows) { @@ -233,17 +230,20 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f setOffset(arrow, -.75f, .1f, -.2f); arrow.render(f5); } - if(xbow != null && xbow.hasTagCompound() && xbow.stackTagCompound.hasKey("Shot")) + if (xbow != null && xbow.hasTagCompound() && xbow.stackTagCompound.hasKey("Shot")) { - if((xbow.stackTagCompound.getByte("Shot")>0)) + if ((xbow.stackTagCompound.getByte("Shot") > 0)) { setRotateAngle(stringLeft, 1.5707963267948966F, -0.5235987755982988F, 0.0F); setRotateAngle(stringRight, -1.5707963267948966F, 0.5235987755982988F, 0.0F); - }else + } + else { - renderNormal(); + renderNormal(); } - }else{ + } + else + { renderNormal(); } this.leftArc1.render(f5); @@ -258,7 +258,7 @@ private void renderNormal() setRotateAngle(arrow, Utils.degreesToRadians(-90), Utils.degreesToRadians(0), Utils.degreesToRadians(90)); arrow.setRotationPoint(xbowBody.rotationPointX, xbowBody.rotationPointY, xbowBody.rotationPointZ); GL11.glPushMatrix(); - GL11.glScalef(1.0f,1.0f,2f); + GL11.glScalef(1.0f, 1.0f, 2f); arrow.render(1 / 14); GL11.glPopMatrix(); } diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelSteamJetpack.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelCoalJetpack.java similarity index 87% rename from src/main/java/com/darkona/adventurebackpack/client/models/ModelSteamJetpack.java rename to src/main/java/com/darkona/adventurebackpack/client/models/ModelCoalJetpack.java index 0b815d9b..1a9d135d 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelSteamJetpack.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelCoalJetpack.java @@ -1,18 +1,20 @@ package com.darkona.adventurebackpack.client.models; -import codechicken.lib.vec.Vector3; -import com.darkona.adventurebackpack.inventory.InventorySteamJetpack; +import java.util.List; + +import org.lwjgl.opengl.GL11; + import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -import org.lwjgl.opengl.GL11; - -import java.util.List; +import codechicken.lib.vec.Vector3; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; -public class ModelSteamJetpack extends ModelWearable { - public ModelRenderer Base; +public class ModelCoalJetpack extends ModelWearable +{ + public ModelRenderer base; public ModelRenderer tubeStraightLeft; public ModelRenderer tubeStraightRight; public ModelRenderer tubeEndLeft; @@ -30,7 +32,8 @@ public class ModelSteamJetpack extends ModelWearable { private ItemStack jetpack; @SuppressWarnings("unchecked") - public ModelSteamJetpack() { + public ModelCoalJetpack() + { this.textureWidth = 64; this.textureHeight = 32; @@ -57,9 +60,9 @@ public ModelSteamJetpack() { this.tubeEndRight.setRotationPoint(-7.7F, 1.6F, 8.3F); this.tubeEndRight.addBox(-1.0F, 0.0F, 0.0F, 1, 4, 1, -0.1F); this.setRotateAngle(tubeEndRight, 0.0F, 0.0F, 0.2617993877991494F); - this.Base = new ModelRenderer(this, 0, 0); - this.Base.setRotationPoint(0.0F, 0.0F, 0.0F); - this.Base.addBox(-4.0F, 0.0F, 2.0F, 8, 12, 1, 0.0F); + this.base = new ModelRenderer(this, 0, 0); + this.base.setRotationPoint(0.0F, 0.0F, 0.0F); + this.base.addBox(-4.0F, 0.0F, 2.0F, 8, 12, 1, 0.0F); this.waterTube1 = new ModelRenderer(this, 10, 17); this.waterTube1.setRotationPoint(0.0F, 1.0F, 0.0F); this.waterTube1.addBox(-2.0F, 1.0F, 1.0F, 1, 1, 1, 0.0F); @@ -86,16 +89,16 @@ public ModelSteamJetpack() { this.tubeStraightLeft.setRotationPoint(2.7F, 1.0F, 8.3F); this.tubeStraightLeft.addBox(0.0F, 0.0F, 0.0F, 6, 1, 1, 0.0F); - this.Base.addChild(this.tankBottom); + this.base.addChild(this.tankBottom); this.pressureTank.addChild(this.tubeBendLeft); this.waterTube1.addChild(this.waterTube2); this.tankBottom.addChild(this.waterTube1); this.pressureTank.addChild(this.tubeBendRight); - this.Base.addChild(this.pressureTank); - this.Base.addChild(this.fireBox); - this.Base.addChild(this.tankTop); + this.base.addChild(this.pressureTank); + this.base.addChild(this.fireBox); + this.base.addChild(this.tankTop); - bipedBody.addChild(Base); + bipedBody.addChild(base); bipedBody.addChild(tubeStraightLeft); bipedBody.addChild(tubeStraightRight); bipedBody.addChild(tubeEndLeft); @@ -103,7 +106,6 @@ public ModelSteamJetpack() { bipedBody.addChild(tankWallLeft); bipedBody.addChild(tankWallRight); - float offsetZ = 0.08F; float offsetY = 0.0F; for (ModelRenderer part : (List) bipedBody.childModels) @@ -112,16 +114,17 @@ public ModelSteamJetpack() { } } - public ModelSteamJetpack setWearable(ItemStack wearable) + public ModelCoalJetpack setWearable(ItemStack wearable) { this.jetpack = wearable; return this; } + @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5, ItemStack stack) { this.jetpack = stack; - render(entity, f, f1,f2,f3,f4,f5); + render(entity, f, f1, f2, f3, f4, f5); } @Override @@ -142,14 +145,16 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f { if (bipedBody.rotationPointX == 0.0F && bipedBody.rotationPointY == 0.0F && bipedBody.rotationPointZ == 0.0F) { - renderSteamPack(f5); - } else + renderCoalJetpack(f5); + } + else { GL11.glTranslatef(bipedBody.rotationPointX * f5, bipedBody.rotationPointY * f5, bipedBody.rotationPointZ * f5); - renderSteamPack(f5); + renderCoalJetpack(f5); GL11.glTranslatef(-bipedBody.rotationPointX * f5, -bipedBody.rotationPointY * f5, -bipedBody.rotationPointZ * f5); } - } else + } + else { GL11.glPushMatrix(); GL11.glTranslatef(bipedBody.rotationPointX * f5, bipedBody.rotationPointY * f5, bipedBody.rotationPointZ * f5); @@ -168,25 +173,24 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f { GL11.glRotatef(bipedBody.rotateAngleX * (180F / (float) Math.PI), 1.0F, 0.0F, 0.0F); } - renderSteamPack(f5); + renderCoalJetpack(f5); GL11.glPopMatrix(); } GL11.glTranslatef(-bipedBody.offsetX, -bipedBody.offsetY, -(bipedBody.offsetZ)); GL11.glPopMatrix(); } - } - public void renderSteamPack(float f5) + public void renderCoalJetpack(float f5) { - InventorySteamJetpack inv = new InventorySteamJetpack(jetpack); + InventoryCoalJetpack inv = new InventoryCoalJetpack(jetpack); this.fireBox.setTextureOffset((inv.getBurnTicks() > 0) ? 9 : 26, 25); tubeStraightRight.render(f5); tubeEndLeft.render(f5); tubeEndRight.render(f5); - Base.render(f5); + base.render(f5); tankWallLeft.render(f5); tankWallRight.render(f5); tubeStraightLeft.render(f5); @@ -194,7 +198,5 @@ public void renderSteamPack(float f5) GL11.glPushMatrix(); renderFluidInTank(inv.getWaterTank(), new Vector3(0, .5f, 0), new Vector3(.155f, 0, .135f), new Vector3(0.18f, 0.0625f, -0.045f), tankTop); GL11.glPopMatrix(); - } - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelCopterPack.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelCopterPack.java index 27f3c147..6eff580d 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelCopterPack.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelCopterPack.java @@ -1,16 +1,21 @@ package com.darkona.adventurebackpack.client.models; -import codechicken.lib.vec.Vector3; -import com.darkona.adventurebackpack.inventory.InventoryCopterPack; -import com.darkona.adventurebackpack.item.ItemCopterPack; -import com.darkona.adventurebackpack.util.Utils; +import java.util.List; + +import org.lwjgl.opengl.GL11; + import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -import org.lwjgl.opengl.GL11; +import codechicken.lib.vec.Vector3; -import java.util.List; +import com.darkona.adventurebackpack.inventory.InventoryCopterPack; +import com.darkona.adventurebackpack.item.ItemCopterPack; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.Utils; + +import static com.darkona.adventurebackpack.common.Constants.Copter.TAG_STATUS; /** * Created on 31/12/2014 @@ -19,7 +24,6 @@ */ public class ModelCopterPack extends ModelWearable { - public static ModelCopterPack instance = new ModelCopterPack(); public ModelRenderer Base; public ModelRenderer EngineBody; @@ -55,9 +59,7 @@ private void init() this.Base.setRotationPoint(0.0F, 0.0F, 0.0F); this.Base.addBox(-4.0F, 0.0F, 2.0F, 8, 12, 1); - //TANK - this.TankTop = new ModelRenderer(this, 0, 33); this.TankTop.setRotationPoint(1.0F, 0.0F, 3.0F); this.TankTop.addBox(0.0F, 0.0F, 0.0F, 5, 1, 5, 0.0F); @@ -98,7 +100,6 @@ private void init() this.FuelLine2.addBox(1.0F, 1.0F, 2.0F, 1, 1, 1, 0.0F); this.TankBottom.addChild(this.FuelLine2); - //ENGINE this.EngineBody = new ModelRenderer(this, 0, 23); this.EngineBody.setRotationPoint(0.0F, 0.0F, 0.0F); @@ -145,7 +146,6 @@ private void init() this.Axis.addChild(this.Blade4); //ESCAPE - this.Escape1 = new ModelRenderer(this, 9, 35); this.Escape1.setRotationPoint(-4.0F, 9.0F, 4.0F); this.Escape1.addBox(0.0F, 0.0F, 0.0F, 2, 1, 1); @@ -181,11 +181,6 @@ public ModelCopterPack setWearable(ItemStack wearable) this.copterPack = wearable; return this; } - public ModelCopterPack(ItemStack wearable) - { - this.copterPack = wearable; - init(); - } public ModelCopterPack() { @@ -197,33 +192,32 @@ private void renderCopterPack(Entity entity, float scale) InventoryCopterPack copterInv = new InventoryCopterPack(this.copterPack); copterInv.openInventory(); Axis.isHidden = true; - if (copterPack != null && copterPack.stackTagCompound != null && copterPack.stackTagCompound.hasKey("status")) + if (BackpackUtils.getWearableCompound(copterPack).getByte(TAG_STATUS) != ItemCopterPack.OFF_MODE) { - if (copterPack.stackTagCompound.getByte("status") != ItemCopterPack.OFF_MODE) + Axis.isHidden = false; + int degrees; + if (entity.onGround || (entity.isSneaking())) { - Axis.isHidden = false; - int degrees; - if (entity.onGround || (entity.isSneaking())) - { - degrees = 16; - } else - { - degrees = entity.motionY > 0 ? 36 : 28; - } - float deg = Utils.radiansToDegrees(this.Axis.rotateAngleY); - this.Axis.rotateAngleY = (deg <= 360 + degrees) ? Utils.degreesToRadians(deg + degrees) : 0; + degrees = 16; + } + else + { + degrees = entity.motionY > 0 ? 36 : 28; } + float deg = Utils.radiansToDegrees(this.Axis.rotateAngleY); + this.Axis.rotateAngleY = (deg <= 360 + degrees) ? Utils.degreesToRadians(deg + degrees) : 0; } this.Base.render(scale); this.Axis.render(scale); renderFluidInTank(copterInv.getFuelTank(), new Vector3(0, .25f, 0), new Vector3(.25f, 0, .25f), new Vector3(0f, 0.0625f, 0.0f), TankTop); } - public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5, ItemStack stack) - { - this.copterPack = stack; - render(entity, f, f1,f2,f3,f4,f5); - } + @Override + public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5, ItemStack stack) + { + this.copterPack = stack; + render(entity, f, f1, f2, f3, f4, f5); + } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) @@ -245,13 +239,15 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f { renderCopterPack(entity, f5); - } else + } + else { GL11.glTranslatef(bipedBody.rotationPointX * f5, bipedBody.rotationPointY * f5, bipedBody.rotationPointZ * f5); renderCopterPack(entity, f5); GL11.glTranslatef(-bipedBody.rotationPointX * f5, -bipedBody.rotationPointY * f5, -bipedBody.rotationPointZ * f5); } - } else + } + else { GL11.glPushMatrix(); GL11.glTranslatef(bipedBody.rotationPointX * f5, bipedBody.rotationPointY * f5, bipedBody.rotationPointZ * f5); diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelFullArmor.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelFullArmor.java index b9ce460a..1eaa097b 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelFullArmor.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelFullArmor.java @@ -15,28 +15,27 @@ public class ModelFullArmor extends ModelBiped { public ModelFullArmor() { - super(0.1F); + super(0.2F); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { - - setRotationAngles(f,f1,f2,f3,f4,f5,entity); - if(entity instanceof EntityLivingBase) + setRotationAngles(f, f1, f2, f3, f4, f5, entity); + if (entity instanceof EntityLivingBase) { - EntityLivingBase owner = (EntityLivingBase)entity; + EntityLivingBase owner = (EntityLivingBase) entity; this.isSneak = owner.isSneaking(); this.onGround = entity.onGround ? 1 : 0; this.heldItemRight = (owner.getHeldItem() != null) ? 1 : 0; this.isRiding = entity.isRiding(); - if(owner instanceof EntityPlayer) + if (owner instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) owner; this.aimedBow = player.isUsingItem() && player.getItemInUse() != null && player.getItemInUse().getItemUseAction() == EnumAction.bow; this.heldItemRight = (player.getCurrentEquippedItem() != null) ? 1 : 0; } } - super.render(entity, f, f1, f2, f3, f4, f5); + super.render(entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelInflatableBoat.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelInflatableBoat.java index bb91d0f8..a20c3ba5 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelInflatableBoat.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelInflatableBoat.java @@ -1,11 +1,12 @@ package com.darkona.adventurebackpack.client.models; -import com.darkona.adventurebackpack.entity.EntityInflatableBoat; -import com.darkona.adventurebackpack.util.Utils; +import org.lwjgl.opengl.GL11; + import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; -import org.lwjgl.opengl.GL11; + +import com.darkona.adventurebackpack.entity.EntityInflatableBoat; /** * InflatableBoat - Darkona @@ -124,20 +125,21 @@ public ModelInflatableBoat() @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { - if(Utils.notNullAndInstanceOf(entity,EntityInflatableBoat.class)) + if (entity instanceof EntityInflatableBoat) { - EntityInflatableBoat theBoat = (EntityInflatableBoat)entity; - - if(theBoat.isMotorized() && theBoat.isInflated()) + EntityInflatableBoat theBoat = (EntityInflatableBoat) entity; + + if (theBoat.isMotorized() && theBoat.isInflated()) { Axis.isHidden = EngineBody.isHidden = false; - }else + } + else { Axis.isHidden = EngineBody.isHidden = true; } GL11.glPushMatrix(); - GL11.glScalef(theBoat.inflation,theBoat.inflation,theBoat.inflation); + GL11.glScalef(theBoat.inflation, theBoat.inflation, theBoat.inflation); this.boatSides5.render(f5); this.boatSides3.render(f5); @@ -147,9 +149,10 @@ public void render(Entity entity, float f, float f1, float f2, float f3, float f this.Axis.render(f5); this.EngineBody.render(f5); - GL11.glPopMatrix(); - }else{ + } + else + { this.boatSides5.render(f5); this.boatSides3.render(f5); this.boatSides2.render(f5); diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelSleepingBag.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelSleepingBag.java index e1c52911..8edd5465 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelSleepingBag.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelSleepingBag.java @@ -13,7 +13,6 @@ public class ModelSleepingBag extends ModelBase { - //fields ModelRenderer footer; ModelRenderer header; ModelRenderer pillow; @@ -67,5 +66,4 @@ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, f { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); } - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/models/ModelWearable.java b/src/main/java/com/darkona/adventurebackpack/client/models/ModelWearable.java index 6f85c9af..65a02e58 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/models/ModelWearable.java +++ b/src/main/java/com/darkona/adventurebackpack/client/models/ModelWearable.java @@ -1,14 +1,15 @@ package com.darkona.adventurebackpack.client.models; -import codechicken.lib.render.RenderUtils; -import codechicken.lib.vec.Cuboid6; -import codechicken.lib.vec.Vector3; +import org.lwjgl.opengl.GL11; + import net.minecraft.client.model.ModelBiped; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidTank; -import org.lwjgl.opengl.GL11; +import codechicken.lib.render.RenderUtils; +import codechicken.lib.vec.Cuboid6; +import codechicken.lib.vec.Vector3; /** * Created on 10/01/2015 @@ -17,7 +18,6 @@ */ public abstract class ModelWearable extends ModelBiped { - protected void startBlending() { GL11.glEnable(GL11.GL_BLEND); @@ -57,14 +57,13 @@ public void renderFluidInTank(FluidTank tank, Vector3 minCoords, Vector3 maxCoor if (tank != null && tank.getFluid() != null && tank.getFluid().getFluid().getIcon() != null) { Vector3 victor = new Vector3( - (parent.rotationPointX * 0.1f + parent.offsetX * 0.1 + offset.x) , // + (parent.rotationPointX * 0.1f + parent.offsetX * 0.1 + offset.x), // (parent.rotationPointY * 0.1f + parent.offsetY * 0.1 + offset.y), (parent.rotationPointZ * 0.1f + parent.offsetZ * 0.1 + offset.z)); - Cuboid6 cat = new Cuboid6(minCoords.x,minCoords.y,minCoords.z, maxCoords.x, maxCoords.y, maxCoords.z); + Cuboid6 cat = new Cuboid6(minCoords.x, minCoords.y, minCoords.z, maxCoords.x, maxCoords.y, maxCoords.z); //Thanks Chickenbones! - RenderUtils.renderFluidCuboid(tank.getFluid(), cat.add(victor),((1.0F * tank.getFluidAmount()) / (1.0F * tank.getCapacity())), 0.8); + RenderUtils.renderFluidCuboid(tank.getFluid(), cat.add(victor), ((1.0F * tank.getFluidAmount()) / (1.0F * tank.getCapacity())), 0.8); } } - } diff --git a/src/main/java/copy/betterstorage/utils/RenderUtils.java b/src/main/java/com/darkona/adventurebackpack/client/render/CopygirlRenderUtils.java similarity index 70% rename from src/main/java/copy/betterstorage/utils/RenderUtils.java rename to src/main/java/com/darkona/adventurebackpack/client/render/CopygirlRenderUtils.java index 2046e1f8..f68a2bea 100644 --- a/src/main/java/copy/betterstorage/utils/RenderUtils.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/CopygirlRenderUtils.java @@ -1,7 +1,8 @@ -package copy.betterstorage.utils; +package com.darkona.adventurebackpack.client.render; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.Tessellator; @@ -11,22 +12,45 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +/** + * The MIT License (MIT) + * + * Copyright (c) 2014 copygirl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ @SideOnly(Side.CLIENT) -public final class RenderUtils +public final class CopygirlRenderUtils { - private static final ResourceLocation glint = new ResourceLocation("textures/misc/enchanted_item_glint.png"); - private RenderUtils() + private CopygirlRenderUtils() { + } public static void renderItemIn3d(ItemStack stack) { - TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); // Not sure why but this can be null when the world loads. if (textureManager == null) @@ -47,12 +71,15 @@ public static void renderItemIn3d(ItemStack stack) { textureManager.bindTexture(((stack.getItemSpriteNumber() == 0) ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture)); IIcon icon = item.getIcon(stack, pass); - float minU = icon.getMinU(); - float maxU = icon.getMaxU(); - float minV = icon.getMinV(); - float maxV = icon.getMaxV(); - RenderUtils.setColorFromInt(item.getColorFromItemStack(stack, pass)); - ItemRenderer.renderItemIn2D(tessellator, maxU, minV, minU, maxV, icon.getIconWidth(), icon.getIconHeight(), 0.0625F); + if (icon != null) + { + float minU = icon.getMinU(); + float maxU = icon.getMaxU(); + float minV = icon.getMinV(); + float maxV = icon.getMaxV(); + CopygirlRenderUtils.setColorFromInt(item.getColorFromItemStack(stack, pass)); + ItemRenderer.renderItemIn2D(tessellator, maxU, minV, minU, maxV, icon.getIconWidth(), icon.getIconHeight(), 0.0625F); + } } if (stack.hasEffect(0)) @@ -89,7 +116,6 @@ public static void renderItemIn3d(ItemStack stack) GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); - } public static void setColorFromInt(int color) diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RenderRideableSpider.java b/src/main/java/com/darkona/adventurebackpack/client/render/RenderRideableSpider.java index 019f9e13..375bf109 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RenderRideableSpider.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RenderRideableSpider.java @@ -1,14 +1,16 @@ package com.darkona.adventurebackpack.client.render; -import com.darkona.adventurebackpack.entity.EntityFriendlySpider; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import org.lwjgl.opengl.GL11; + import net.minecraft.client.model.ModelSpider; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL11; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import com.darkona.adventurebackpack.entity.EntityFriendlySpider; @SideOnly(Side.CLIENT) public class RenderRideableSpider extends RenderLiving @@ -56,7 +58,7 @@ protected int shouldRenderPass(EntityFriendlySpider p_77032_1_, int p_77032_2_, char c0 = 61680; int j = c0 % 65536; int k = c0 / 65536; - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float)j / 1.0F, (float)k / 1.0F); + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); return 1; } @@ -73,8 +75,9 @@ protected ResourceLocation getEntityTexture(EntityFriendlySpider p_110775_1_) /** * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture. */ + @Override protected ResourceLocation getEntityTexture(Entity p_110775_1_) { - return this.getEntityTexture((EntityFriendlySpider)p_110775_1_); + return this.getEntityTexture((EntityFriendlySpider) p_110775_1_); } } \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RendererAdventureBackpackBlock.java b/src/main/java/com/darkona/adventurebackpack/client/render/RendererAdventureBackpackBlock.java index 5abb49a8..1084fe02 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RendererAdventureBackpackBlock.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RendererAdventureBackpackBlock.java @@ -1,16 +1,15 @@ package com.darkona.adventurebackpack.client.render; -import com.darkona.adventurebackpack.AdventureBackpack; -import com.darkona.adventurebackpack.block.TileAdventureBackpack; -import com.darkona.adventurebackpack.client.models.ModelBackpackBlock; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.util.Resources; -import com.darkona.adventurebackpack.util.Utils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; + +import com.darkona.adventurebackpack.block.TileAdventureBackpack; +import com.darkona.adventurebackpack.client.models.ModelBackpackBlock; +import com.darkona.adventurebackpack.util.Resources; /** * Created on 12/10/2014 @@ -20,8 +19,6 @@ public class RendererAdventureBackpackBlock extends TileEntitySpecialRenderer { - - // private ModelAdventureBackpackBlock model; private ModelBackpackBlock model; public RendererAdventureBackpackBlock() @@ -32,6 +29,7 @@ public RendererAdventureBackpackBlock() @Override public void renderTileEntityAt(TileEntity te, double x, double y, double z, float par8) { + TileAdventureBackpack tileBackpack = (TileAdventureBackpack) te; int dir = te.getBlockMetadata(); if ((dir & 8) >= 8) { @@ -62,23 +60,14 @@ public void renderTileEntityAt(TileEntity te, double x, double y, double z, floa { GL11.glRotatef(dir * (-180F), 0.0F, 1.0F, 0.0F); } - ResourceLocation modelTexture; - if (BackpackNames.getBackpackColorName((TileAdventureBackpack) te).equals("Standard")) - { - modelTexture = Resources.backpackTextureFromString(Utils.getHoliday()); - } else - { - modelTexture = Resources.backpackTextureFromColor((TileAdventureBackpack) te); - } + ResourceLocation modelTexture = Resources.getBackpackTexture(tileBackpack.getType()); bindTexture(modelTexture); - model.render(null, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1 / 20F, (TileAdventureBackpack) te); + model.render(null, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1 / 20F, tileBackpack); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); GL11.glPopMatrix(); GL11.glPopMatrix(); } - - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RendererCampFire.java b/src/main/java/com/darkona/adventurebackpack/client/render/RendererCampFire.java index 205659ef..66eea57b 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RendererCampFire.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RendererCampFire.java @@ -1,12 +1,14 @@ package com.darkona.adventurebackpack.client.render; -import com.darkona.adventurebackpack.client.models.ModelCampFire; -import com.darkona.adventurebackpack.util.Resources; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; + +import com.darkona.adventurebackpack.client.models.ModelCampFire; +import com.darkona.adventurebackpack.util.Resources; /** * Created on 05/01/2015 @@ -15,8 +17,6 @@ */ public class RendererCampFire extends TileEntitySpecialRenderer { - - // private ModelAdventureBackpackBlock model; private ModelCampFire model; public RendererCampFire() @@ -41,6 +41,4 @@ public void renderTileEntityAt(TileEntity te, double x, double y, double z, floa GL11.glPopMatrix(); GL11.glPopMatrix(); } - - } diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RendererHose.java b/src/main/java/com/darkona/adventurebackpack/client/render/RendererHose.java index 3f66f493..60d08070 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RendererHose.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RendererHose.java @@ -1,14 +1,15 @@ package com.darkona.adventurebackpack.client.render; -import com.darkona.adventurebackpack.config.ConfigHandler; +import org.lwjgl.opengl.GL11; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.client.IItemRenderer; -import org.lwjgl.opengl.GL11; + +import com.darkona.adventurebackpack.config.ConfigHandler; /** * Created on 13/10/2014 @@ -17,10 +18,8 @@ */ public class RendererHose implements IItemRenderer { - private static RenderItem renderHose = new RenderItem(); private FontRenderer fontRenderer; - private Tessellator tessellator = Tessellator.instance; @Override public boolean handleRenderType(ItemStack item, ItemRenderType type) @@ -34,11 +33,9 @@ public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRe return false; } - @SuppressWarnings("incomplete-switch") @Override public void renderItem(ItemRenderType type, ItemStack hose, Object... data) { - if (type == ItemRenderType.INVENTORY) { // ====================Render the item===================== // @@ -72,7 +69,7 @@ public void renderItem(ItemRenderType type, ItemStack hose, Object... data) if (fontRenderer != null) { fontRenderer.drawString(mode, 0, 0, 0xFFFFFF); - if (!ConfigHandler.TANKS_OVERLAY) + if (!ConfigHandler.tanksOverlay) { fontRenderer.drawString(amount, 0, 18, 0xFFFFFF); fontRenderer.drawString(name, 0, 24, 0xFFFFFF); diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RendererInflatableBoat.java b/src/main/java/com/darkona/adventurebackpack/client/render/RendererInflatableBoat.java index 6a83ec67..15b9cc43 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RendererInflatableBoat.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RendererInflatableBoat.java @@ -1,13 +1,15 @@ package com.darkona.adventurebackpack.client.render; -import com.darkona.adventurebackpack.client.models.ModelInflatableBoat; -import com.darkona.adventurebackpack.entity.EntityInflatableBoat; -import com.darkona.adventurebackpack.util.Resources; +import org.lwjgl.opengl.GL11; + import net.minecraft.client.renderer.entity.Render; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL11; + +import com.darkona.adventurebackpack.client.models.ModelInflatableBoat; +import com.darkona.adventurebackpack.entity.EntityInflatableBoat; +import com.darkona.adventurebackpack.util.Resources; /** * Created on 05/01/2015 @@ -16,9 +18,8 @@ */ public class RendererInflatableBoat extends Render { - - private ResourceLocation boatTexture = Resources.modelTextures("inflatableBoat"); - private ModelInflatableBoat boatModel = new ModelInflatableBoat(); + private ResourceLocation boatTexture = Resources.modelTextures("inflatableBoat"); + private ModelInflatableBoat boatModel = new ModelInflatableBoat(); public RendererInflatableBoat() { @@ -55,8 +56,6 @@ public void doRender(EntityInflatableBoat entity, double x, double y, double z, /** * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture. - * - * @param p_110775_1_ */ @Override protected ResourceLocation getEntityTexture(Entity p_110775_1_) diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemAdventureBackpack.java b/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemAdventureBackpack.java index 73a248ce..2c3a0955 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemAdventureBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemAdventureBackpack.java @@ -1,21 +1,23 @@ package com.darkona.adventurebackpack.client.render; -import com.darkona.adventurebackpack.AdventureBackpack; -import com.darkona.adventurebackpack.client.models.ModelBackpackBlock; -import com.darkona.adventurebackpack.inventory.InventoryBackpack; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.util.Resources; +import org.lwjgl.opengl.GL11; + import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; -import org.lwjgl.opengl.GL11; + +import com.darkona.adventurebackpack.client.models.ModelBackpackBlock; +import com.darkona.adventurebackpack.inventory.InventoryBackpack; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.Resources; /** * Created on 12/10/2014 * * @author Darkona */ + public class RendererItemAdventureBackpack implements IItemRenderer { private final ModelBackpackBlock model; @@ -25,6 +27,7 @@ public RendererItemAdventureBackpack() model = new ModelBackpackBlock(); } + @Override public boolean handleRenderType(ItemStack item, IItemRenderer.ItemRenderType type) { switch (type) @@ -43,6 +46,7 @@ public boolean handleRenderType(ItemStack item, IItemRenderer.ItemRenderType typ return false; } + @Override public boolean shouldUseRenderHelper(IItemRenderer.ItemRenderType type, ItemStack item, IItemRenderer.ItemRendererHelper helper) { switch (type) @@ -61,20 +65,14 @@ public boolean shouldUseRenderHelper(IItemRenderer.ItemRenderType type, ItemStac return false; } - public void renderItem(IItemRenderer.ItemRenderType type, ItemStack backpack, Object... data) + @Override + public void renderItem(IItemRenderer.ItemRenderType renderType, ItemStack backpack, Object... data) { InventoryBackpack inv = new InventoryBackpack(backpack); - ResourceLocation modelTexture; - if (BackpackNames.getBackpackColorName(backpack).equals("Standard")) - { - modelTexture = Resources.backpackTextureFromString(AdventureBackpack.instance.Holiday); - } else - { - modelTexture = Resources.backpackTextureFromColor(inv); - } - switch (type) - { + ResourceLocation modelTexture = Resources.getBackpackTexture(BackpackTypes.getType(backpack)); + switch (renderType) + { case INVENTORY: Minecraft.getMinecraft().renderEngine.bindTexture(modelTexture); { @@ -181,4 +179,4 @@ public void renderItem(IItemRenderer.ItemRenderType type, ItemStack backpack, Ob } } -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemAdventureHat.java b/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemAdventureHat.java index e770243a..9ddf9ca9 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemAdventureHat.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemAdventureHat.java @@ -1,24 +1,21 @@ package com.darkona.adventurebackpack.client.render; +import org.lwjgl.opengl.GL11; -import com.darkona.adventurebackpack.client.models.ModelAdventureHat; -import com.darkona.adventurebackpack.util.Resources; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; -import org.lwjgl.opengl.GL11; +import com.darkona.adventurebackpack.client.models.ModelAdventureHat; +import com.darkona.adventurebackpack.util.Resources; /** * Created by Darkona on 11/10/2014. */ - - public class RendererItemAdventureHat implements IItemRenderer { - private final ModelAdventureHat model; public RendererItemAdventureHat() @@ -26,6 +23,7 @@ public RendererItemAdventureHat() model = ModelAdventureHat.instance; } + @Override public boolean handleRenderType(ItemStack item, IItemRenderer.ItemRenderType type) { switch (type) @@ -44,6 +42,7 @@ public boolean handleRenderType(ItemStack item, IItemRenderer.ItemRenderType typ return false; } + @Override public boolean shouldUseRenderHelper(IItemRenderer.ItemRenderType type, ItemStack item, IItemRenderer.ItemRendererHelper helper) { switch (type) @@ -62,9 +61,10 @@ public boolean shouldUseRenderHelper(IItemRenderer.ItemRenderType type, ItemStac return false; } + @Override public void renderItem(IItemRenderer.ItemRenderType type, ItemStack item, Object... data) { - ResourceLocation modelTexture = Resources.modelTextures("adventureHat"); + ResourceLocation modelTexture = Resources.modelTextures("adventureHat_texture"); Minecraft.getMinecraft().renderEngine.bindTexture(modelTexture); switch (type) { @@ -172,5 +172,4 @@ public void renderItem(IItemRenderer.ItemRenderType type, ItemStack item, Object break; } } - } \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemClockworkCrossbow.java b/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemClockworkCrossbow.java index 16af1a2e..0534c7fe 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemClockworkCrossbow.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RendererItemClockworkCrossbow.java @@ -1,24 +1,23 @@ package com.darkona.adventurebackpack.client.render; -import com.darkona.adventurebackpack.client.models.ModelClockworkCrossbow; -import com.darkona.adventurebackpack.util.Resources; +import org.lwjgl.opengl.GL11; + import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; -import org.lwjgl.opengl.GL11; + +import com.darkona.adventurebackpack.client.models.ModelClockworkCrossbow; +import com.darkona.adventurebackpack.util.Resources; /** * Created by Darkona on 11/10/2014. */ - - public class RendererItemClockworkCrossbow implements IItemRenderer { - private final ModelClockworkCrossbow model; private ResourceLocation modelTexture = Resources.modelTextures("clockworkCrossbow"); @@ -39,7 +38,6 @@ public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRe public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - Minecraft.getMinecraft().renderEngine.bindTexture(modelTexture); EntityPlayer player; switch (type) @@ -139,5 +137,4 @@ public void renderItem(ItemRenderType type, ItemStack item, Object... data) break; } } - } \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RendererStack.java b/src/main/java/com/darkona/adventurebackpack/client/render/RendererStack.java index 7702d5ec..eefcded4 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RendererStack.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RendererStack.java @@ -1,26 +1,42 @@ package com.darkona.adventurebackpack.client.render; -import copy.betterstorage.utils.RenderUtils; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import org.lwjgl.opengl.GL11; + +import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; +import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.item.ItemStack; -import org.lwjgl.opengl.GL11; +import net.minecraftforge.client.IItemRenderer; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import com.darkona.adventurebackpack.reference.ToolHandler; +import com.darkona.adventurebackpack.util.GregtechUtils; +import com.darkona.adventurebackpack.util.ThaumcraftUtils; +import com.darkona.adventurebackpack.util.TinkersUtils; public class RendererStack extends ModelRenderer { + private static final Minecraft MC = Minecraft.getMinecraft(); - public ItemStack stack; - private boolean which; + private boolean isLowerSlot; + private ItemStack stack; + private ToolHandler toolHandler = ToolHandler.VANILLA; - public RendererStack(ModelBase modelBase, boolean which) + public RendererStack(ModelBase modelBase, boolean isLowerSlot) { super(modelBase); - this.which = which; + this.isLowerSlot = isLowerSlot; addChild(new Thing(modelBase)); } + public void setStack(ItemStack stack, ToolHandler toolHandler) + { + this.stack = stack; + this.toolHandler = toolHandler; + } + private class Thing extends ModelRenderer { public Thing(ModelBase modelBase) @@ -33,31 +49,63 @@ public Thing(ModelBase modelBase) public void render(float par1) { if (stack == null) - { return; - } + GL11.glPushMatrix(); GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); - if (which) + if (isLowerSlot) { GL11.glScalef(0.6F, 0.6F, 0.6F); GL11.glPushMatrix(); GL11.glRotatef(-90F, 0, 1, 0); - GL11.glRotatef(-225F, 0, 0, 1); - - } else + } + else { GL11.glScalef(0.7F, 0.7F, 0.7F); GL11.glPushMatrix(); - GL11.glRotatef(45F, 0, 0, 1); + } + GL11.glRotatef(getToolRotationAngle(stack, isLowerSlot, toolHandler), 0, 0, 1); + switch (toolHandler) + { + case GREGTECH: + GregtechUtils.renderTool(stack, IItemRenderer.ItemRenderType.ENTITY); + break; + case TCONSTRUCT: + TextureManager tm = MC.getTextureManager(); + tm.bindTexture(tm.getResourceLocation(stack.getItemSpriteNumber())); + GL11.glTranslatef(-0.06F, -0.1F, 0F); + TinkersUtils.renderTool(stack, IItemRenderer.ItemRenderType.ENTITY); + break; + case THAUMCRAFT: + GL11.glTranslatef(0F, -0.375F, 0F); + ThaumcraftUtils.renderTool(stack, IItemRenderer.ItemRenderType.ENTITY); + break; + case VANILLA: + default: + CopygirlRenderUtils.renderItemIn3d(stack); + break; } - RenderUtils.renderItemIn3d(stack); + GL11.glPopAttrib(); GL11.glPopMatrix(); GL11.glPopMatrix(); + } + private float getToolRotationAngle(ItemStack stack, boolean isLowerSlot, ToolHandler toolHandler) + { + switch (toolHandler) + { + case GREGTECH: + return GregtechUtils.getToolRotationAngle(stack, isLowerSlot); + case TCONSTRUCT: + return TinkersUtils.getToolRotationAngle(stack, isLowerSlot); + case THAUMCRAFT: + return ThaumcraftUtils.getToolRotationAngle(stack, isLowerSlot); + case VANILLA: + default: + return isLowerSlot ? -225F : 45F; + } } } - } \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/client/render/RendererWearableEquipped.java b/src/main/java/com/darkona/adventurebackpack/client/render/RendererWearableEquipped.java index 88460e91..cc8aa8f8 100644 --- a/src/main/java/com/darkona/adventurebackpack/client/render/RendererWearableEquipped.java +++ b/src/main/java/com/darkona/adventurebackpack/client/render/RendererWearableEquipped.java @@ -1,7 +1,8 @@ package com.darkona.adventurebackpack.client.render; -import com.darkona.adventurebackpack.item.IBackWearableItem; -import com.darkona.adventurebackpack.util.Wearing; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.OpenGlHelper; @@ -12,8 +13,9 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; + +import com.darkona.adventurebackpack.item.IBackWearableItem; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 25/12/2014 @@ -22,7 +24,6 @@ */ public class RendererWearableEquipped extends RendererLivingEntity { - public ResourceLocation texture; public ModelBiped modelBipedMain; @@ -56,7 +57,8 @@ public void render(Entity entity, double x, double y, double z, float rotX, floa { GL11.glEnable(GL12.GL_RESCALE_NORMAL); renderMainModel((EntityPlayer) entity, 0, 0, 0, 0, 0, 0.0625f); - } catch (Exception oops) + } + catch (Exception oops) { } @@ -64,7 +66,8 @@ public void render(Entity entity, double x, double y, double z, float rotX, floa GL11.glEnable(GL11.GL_TEXTURE_2D); OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); GL11.glPopMatrix(); - }catch(Exception ex) + } + catch (Exception ex) { //discard silently because NO ONE CARES } @@ -76,8 +79,8 @@ protected void renderMainModel(EntityLivingBase entity, float limbSwing1, float if (!entity.isInvisible()) { modelBipedMain.render(entity, limbSwing1, limbswing2, z, yaw, whatever, scale); - } else - if (!entity.isInvisibleToPlayer(Minecraft.getMinecraft().thePlayer)) + } + else if (!entity.isInvisibleToPlayer(Minecraft.getMinecraft().thePlayer)) { GL11.glPushMatrix(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.15F); @@ -90,7 +93,8 @@ protected void renderMainModel(EntityLivingBase entity, float limbSwing1, float GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F); GL11.glPopMatrix(); GL11.glDepthMask(true); - } else + } + else { modelBipedMain.setRotationAngles(limbSwing1, limbswing2, z, yaw, whatever, scale, entity); } diff --git a/src/main/java/com/darkona/adventurebackpack/common/BackpackAbilities.java b/src/main/java/com/darkona/adventurebackpack/common/BackpackAbilities.java index 52f126b8..379dacc2 100644 --- a/src/main/java/com/darkona/adventurebackpack/common/BackpackAbilities.java +++ b/src/main/java/com/darkona/adventurebackpack/common/BackpackAbilities.java @@ -1,14 +1,9 @@ package com.darkona.adventurebackpack.common; -import com.darkona.adventurebackpack.block.TileAdventureBackpack; -import com.darkona.adventurebackpack.entity.ai.EntityAIAvoidPlayerWithBackpack; -import com.darkona.adventurebackpack.init.ModFluids; -import com.darkona.adventurebackpack.init.ModNetwork; -import com.darkona.adventurebackpack.inventory.InventoryBackpack; -import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Utils; +import java.util.Iterator; +import java.util.List; + +import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.ai.EntityAITasks; @@ -25,8 +20,17 @@ import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import java.util.Iterator; -import java.util.List; +import com.darkona.adventurebackpack.block.TileAdventureBackpack; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.entity.ai.EntityAIAvoidPlayerWithBackpack; +import com.darkona.adventurebackpack.init.ModFluids; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.inventory.InventoryBackpack; +import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.LogHelper; +import com.darkona.adventurebackpack.util.Utils; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 12/10/2014 @@ -36,121 +40,70 @@ * @see com.darkona.adventurebackpack.item.ItemAdventureBackpack * @see com.darkona.adventurebackpack.block.BlockAdventureBackpack */ +@SuppressWarnings("unused") public class BackpackAbilities { - public static BackpackAbilities backpackAbilities = new BackpackAbilities(); public static BackpackRemovals backpackRemovals = new BackpackRemovals(); /** - * - * @param colorName - * @return + * Executes the ability of any given backpack, be it on the ground or be it on a player. */ - public static boolean hasAbility(String colorName) + public void executeAbility(EntityPlayer player, World world, ItemStack backpack) { - for (String valid : validWearingBackpacks) + String skinName = BackpackTypes.getSkinName(backpack); + try { - if (valid.equals(colorName)) - { - return true; - } + //This is black magic and shouldn't be attempted by the faint of heart. + this.getClass() + .getMethod("item" + skinName, EntityPlayer.class, World.class, ItemStack.class) + .invoke(backpackAbilities, player, world, backpack); } - return false; - } - - public static boolean hasRemoval(String colorName) - { - for (String valid : validRemovalBackpacks) + catch (Exception oops) { - if (valid.equals(colorName)) - { - return true; - } + //NOBODY CARES } - return false; } - /** - * Executes the ability of any given backpack, be it on the ground or be it on a player. - * - * @param player An entity player, can be null in the case of the tile entity. - * @param world This is necessary, so get it from wherever you can inside the class you're calling this. - * @param backpack An object representing a backpack, either in its ItemStack form or its TileEntity form. - */ - public void executeAbility(EntityPlayer player, World world, Object backpack) + public void executeTileAbility(World world, TileAdventureBackpack backpack) { - if (backpack instanceof ItemStack) + String skinName = BackpackTypes.getSkinName(backpack.getType()); + try { - String colorName = BackpackNames.getBackpackColorName((ItemStack)backpack); - try - { - //This is black magic and shouldn't be attempted by the faint of heart. - this.getClass() - .getMethod("item" + colorName, EntityPlayer.class, World.class, ItemStack.class). - invoke(backpackAbilities, player, world, backpack); - } catch (Exception oops) - { - //NOBODY CARES - } + /* + This is witchery, witchery I say! + But seriously, if you want to know how this works just pay very close attention: + invoke will execute any method of a given class, okay? so this should be obvious. + Look at the names of the methods in this class and you'll figure it out. + You have to indicate exactly the classes that the method should use as parameters so + be very careful with "getMethod". + */ + this.getClass() + .getMethod("tile" + skinName, World.class, TileAdventureBackpack.class) + .invoke(backpackAbilities, world, backpack); } - - if (backpack instanceof TileAdventureBackpack) + catch (Exception oops) { - String colorName = ((TileAdventureBackpack) backpack).getColorName(); - try - { - /* - This is witchery, witchery I say! - But seriously, if you want to know how this works just pay very close attention: - invoke will execute any method of a given class, okay? so this should be obvious. - Look at the names of the methods in this class and you'll figure it out. - You have to indicate exactly the classes that the method should use as parameters so - be very careful with "getMethod". - */ - this.getClass() - .getMethod("tile" + colorName, World.class, TileAdventureBackpack.class) - .invoke(backpackAbilities, world, backpack); - } catch (Exception oops) - { - //Seriously, nobody cares if this can't work, this is just so the game won't explode. - } + //Seriously, nobody cares if this can't work, this is just so the game won't explode. } - } - public void executeRemoval(EntityPlayer player, World world,ItemStack backpack ) + public void executeRemoval(EntityPlayer player, World world, ItemStack backpack) { - - String colorName = BackpackNames.getBackpackColorName(backpack); + String skinName = BackpackTypes.getSkinName(backpack); try { //This is black magic and shouldn't be attempted by the faint of heart. backpackRemovals.getClass() - .getMethod("item" + colorName, EntityPlayer.class, World.class, ItemStack.class). - invoke(backpackRemovals, player, world, backpack); - } catch (Exception oops) + .getMethod("item" + skinName, EntityPlayer.class, World.class, ItemStack.class) + .invoke(backpackRemovals, player, world, backpack); + } + catch (Exception oops) { LogHelper.error("---Something bad happened when removing a backpack---"); oops.printStackTrace(); } } - /** - * These are the colorNames of the backpacks that have abilities when being worn. - */ - private static String[] validWearingBackpacks = { - "Bat", "Squid", "Pigman", "Cactus", "Cow", "Pig", "Dragon", "Slime", "Chicken", "Wolf", "Ocelot", "Creeper", "Rainbow", "Melon", "Sunflower","Mooshroom"}; - - private static String[] validRemovalBackpacks = { - "Bat", "Squid", "Dragon", "Rainbow" - }; - /** - * These are the colorNames of the backpacks that have abilities while being blocks. Note that not all the - * backpacks that have particularities while in block form necessarily have abilities. - * - * @see com.darkona.adventurebackpack.block.BlockAdventureBackpack - */ - private static String[] validTileBackpacks = {"Cactus","Melon"}; /** * Detects if a player is under the rain. For detecting when it is Under The Sea (maybe to sing a nice Disney tune) @@ -161,17 +114,12 @@ public void executeRemoval(EntityPlayer player, World world,ItemStack backpack ) */ private boolean isUnderRain(EntityPlayer player) { - return player.worldObj.canLightningStrikeAt(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), - MathHelper.floor_double(player.posZ)) - || player.worldObj.canLightningStrikeAt(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY + player.height), - MathHelper.floor_double(player.posZ)); + return player.worldObj.canLightningStrikeAt(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)) + || player.worldObj.canLightningStrikeAt(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY + player.height), MathHelper.floor_double(player.posZ)); } /** * This backpack will feed you while you stay in the sun, slowly. At the very least you shouldn't starve. - * @param player - * @param world - * @param backpack */ public void itemSunflower(EntityPlayer player, World world, ItemStack backpack) { @@ -179,14 +127,17 @@ public void itemSunflower(EntityPlayer player, World world, ItemStack backpack) if (inv.getLastTime() <= 0) { - if(world.isDaytime() && + if (world.isDaytime() && /*!world.isRemote &&*/ - world.canBlockSeeTheSky(MathHelper.floor_double(player.posX),MathHelper.floor_double(player.posY+1),MathHelper.floor_double(player.posZ))) { + world.canBlockSeeTheSky(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY + 1), MathHelper.floor_double(player.posZ))) + { player.getFoodStats().addStats(2, 0.2f); //LogHelper.info("OMNOMNOMNOM"); } inv.setLastTime(Utils.secondsToTicks(120)); - }else{ + } + else + { inv.setLastTime(inv.getLastTime() - 1); } inv.dirtyTime(); @@ -194,52 +145,149 @@ public void itemSunflower(EntityPlayer player, World world, ItemStack backpack) /** * Nana nana nana nana Bat - Batpack! See in the dark! - * @param player - * @param world - * @param backpack */ public void itemBat(EntityPlayer player, World world, ItemStack backpack) { //Shameless rip-off from Machinemuse. Thanks Claire, I don't have to reinvent the wheel thanks to you. //I will use a different potion id to avoid conflicting with her modular suits + PotionEffect nightVision = null; - if (player.isPotionActive(Potion.nightVision.id)) { + + if (player.isPotionActive(Potion.nightVision.id)) + { nightVision = player.getActivePotionEffect(Potion.nightVision); } - if (nightVision == null || nightVision.getDuration() < 40 && nightVision.getAmplifier() != -4) + if ((nightVision == null || nightVision.getDuration() < 222) && !Wearing.getWearingBackpackInv(player).getDisableNVision()) { - player.addPotionEffect(new PotionEffect(Potion.nightVision.id, 5000, -4)); + player.addPotionEffect(new PotionEffect(Potion.nightVision.id, 239, -1, true)); + } + else if (nightVision != null && Wearing.getWearingBackpackInv(player).getDisableNVision()) + { + backpackRemovals.itemBat(player, world, backpack); } } public void itemSquid(EntityPlayer player, World world, ItemStack backpack) { - if (player.isInWater()) + if (player.isInsideOfMaterial(Material.water)) { - player.addPotionEffect(new PotionEffect(Potion.waterBreathing.getId(), 1, -5)); + player.addPotionEffect(new PotionEffect(Potion.waterBreathing.getId(), 19, -1, true)); itemBat(player, world, backpack); - }else{ - backpackRemovals.itemSquid(player,world, backpack); + } + else if (player.isPotionActive(Potion.waterBreathing.id) && player.getActivePotionEffect(Potion.waterBreathing).getAmplifier() == -1) + { + backpackRemovals.itemSquid(player, world, backpack); } } - public void itemIronGolem(EntityPlayer player, World world, ItemStack backpack) + public void itemPigman(EntityPlayer player, World world, ItemStack backpack) { + PotionEffect potion = null; + if (player.isPotionActive(Potion.fireResistance.id)) + { + potion = player.getActivePotionEffect(Potion.fireResistance); + } + if (potion == null || potion.getDuration() < 222) + { + player.addPotionEffect(new PotionEffect(Potion.fireResistance.id, 239, -1, true)); + } } - public void itemPigman(EntityPlayer player, World world, ItemStack backpack) + /** + * The Dragon Backpack does something awesome. + */ + public void itemDragon(EntityPlayer player, World world, ItemStack backpack) { + itemBat(player, world, backpack); + itemPigman(player, world, backpack); + PotionEffect potion = null; - if (player.isPotionActive(Potion.fireResistance.id)) { - potion = player.getActivePotionEffect(Potion.fireResistance); + + if (ConfigHandler.dragonBackpackRegen != 0) + { + if (player.isPotionActive(Potion.regeneration.id)) + { + potion = player.getActivePotionEffect(Potion.regeneration); + } + if (player.getHealth() < player.getMaxHealth()) + { + if (potion == null || potion.getDuration() < 20) + { + player.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), 900, ConfigHandler.dragonBackpackRegen - 1, true)); + } + } + else if (potion != null && potion.getAmplifier() == ConfigHandler.dragonBackpackRegen - 1) + { + if (player.worldObj.isRemote) + { + player.removePotionEffectClient(Potion.regeneration.id); + } + else + { + player.removePotionEffect(Potion.regeneration.id); + } + } } - if (potion == null || potion.getDuration() < 5 && potion.getAmplifier() != -5) + + if (ConfigHandler.dragonBackpackDamage != 0) { - player.addPotionEffect(new PotionEffect(Potion.fireResistance.id, 5000, -5)); + if (player.isPotionActive(Potion.damageBoost.id)) + { + potion = player.getActivePotionEffect(Potion.damageBoost); + } + if (potion == null || potion.getDuration() < 222) + { + player.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), 239, ConfigHandler.dragonBackpackDamage - 1, true)); + } } } + public void itemRainbow(EntityPlayer player, World world, ItemStack backpack) + { + InventoryBackpack inv = new InventoryBackpack(backpack); + int noteTime = inv.getLastTime() - 1; + + if (noteTime >= 0 && noteTime < Utils.secondsToTicks(147)) + { + //player.setSprinting(true); + if (ConfigHandler.rainbowBackpackSSpeed != 0) + { + player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 60, ConfigHandler.rainbowBackpackSSpeed - 1, true)); + } + if (ConfigHandler.rainbowBackpackSJump != 0) + { + player.addPotionEffect(new PotionEffect(Potion.jump.getId(), 60, ConfigHandler.rainbowBackpackSJump - 1, true)); + } + if (noteTime % 2 == 0) + { + //Visuals.NyanParticles(player, world); + if (!world.isRemote) + { + ModNetwork.sendToNearby(new EntityParticlePacket.Message(EntityParticlePacket.NYAN_PARTICLE, player), player); + } + } + } + + PotionEffect moveSpeed = null; + + if (player.isPotionActive(Potion.moveSpeed.id)) + { + moveSpeed = player.getActivePotionEffect(Potion.moveSpeed); + } + if (ConfigHandler.rainbowBackpackSpeed != 0 && (moveSpeed == null || moveSpeed.getDuration() < 222)) + { + player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 239, ConfigHandler.rainbowBackpackSpeed - 1, true)); + } + inv.setLastTime(noteTime); + inv.markDirty(); + } + + public void itemIronGolem(EntityPlayer player, World world, ItemStack backpack) + { + + } + /** * Mirroring real life cactii, the Cactus Backpack fills with water slowly or rapidly depending where is the player. * If it's raining it will fill 1milibucket of water each tick. @@ -254,7 +302,7 @@ public void itemPigman(EntityPlayer player, World world, ItemStack backpack) public void itemCactus(EntityPlayer player, World world, ItemStack backpack) { //lastTime is in ticks for this backpack. - if(world.isRemote)return; + if (world.isRemote) return; InventoryBackpack inv = new InventoryBackpack(backpack); int drops = 0; if (player.isInWater()) @@ -272,7 +320,9 @@ public void itemCactus(EntityPlayer player, World world, ItemStack backpack) FluidStack raindrop = new FluidStack(FluidRegistry.WATER, drops); inv.getLeftTank().fill(raindrop, true); inv.getRightTank().fill(raindrop, true); - }else{ + } + else + { inv.setLastTime(inv.getLastTime() - 1); } inv.dirtyTime(); @@ -306,10 +356,6 @@ public void itemPig(EntityPlayer player, World world, ItemStack backpack) /** * Squishy! The Slime Backpack has an incredibly useless "ability". Makes the player leave a slimy trail of * particles whenever he or she is running, and make that splishy splashy squishy sound on each step as well!. - * - * @param player - * @param world - * @param backpack */ public void itemSlime(EntityPlayer player, World world, ItemStack backpack) { @@ -318,12 +364,12 @@ public void itemSlime(EntityPlayer player, World world, ItemStack backpack) // 4 is New Moon, 5 is Waxing Crescent, 6 is First Quarter and 7 is Waxing Gibbous if (world.getMoonPhase() == 0 && !world.isDaytime()) { - player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 1, 1)); + player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 100, 0, true)); } if (player.onGround) { - if ((player.moveForward == 0 && player.moveStrafing == 0) && (Math.abs(player.moveForward) < 3 && Math.abs(player.moveStrafing)<3) ) + if ((player.moveForward == 0 && player.moveStrafing == 0) && (Math.abs(player.moveForward) < 3 && Math.abs(player.moveStrafing) < 3)) { player.addVelocity(player.motionX *= 0.828, 0, player.motionZ *= 0.828); } @@ -348,15 +394,11 @@ public void itemSlime(EntityPlayer player, World world, ItemStack backpack) /** * The Chicken Backpack will go and *plop* an egg for you randomly each so many seconds. It's very rare though. - * - * @param player - * @param world - * @param backpack */ public void itemChicken(EntityPlayer player, World world, ItemStack backpack) { InventoryBackpack inv = new InventoryBackpack(backpack); - int eggTime = inv.getLastTime() - 1 ; + int eggTime = inv.getLastTime() - 1; if (eggTime <= 0) { player.playSound("mob.chicken.plop", 1.0F, (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F + 1.0F); @@ -370,15 +412,11 @@ public void itemChicken(EntityPlayer player, World world, ItemStack backpack) /** * The Melon Backpack, like his cousin the Cactus Backpack, will fill itself, but with delicious * and refreshing Melon Juice, if the backpack is wet in any way. - * - * @param player - * @param world - * @param backpack */ public void itemMelon(EntityPlayer player, World world, ItemStack backpack) { //lastTime is in ticks for this backpack. - if(world.isRemote)return; + if (world.isRemote) return; InventoryBackpack inv = new InventoryBackpack(backpack); int drops = 0; if (player.isInWater()) @@ -396,49 +434,20 @@ public void itemMelon(EntityPlayer player, World world, ItemStack backpack) FluidStack raindrop = new FluidStack(ModFluids.melonJuice, drops); inv.getLeftTank().fill(raindrop, true); inv.getRightTank().fill(raindrop, true); - }else{ + } + else + { inv.setLastTime(inv.getLastTime() - 1); } inv.dirtyTime(); inv.dirtyTanks(); } - /** - * The Dragon Backpack does something awesome. - * - * @param player - * @param world - * @param backpack - */ - public void itemDragon(EntityPlayer player, World world, ItemStack backpack) - { - itemPigman(player,world,backpack); - itemSquid(player, world, backpack); - PotionEffect potion = null; - if (player.isPotionActive(Potion.regeneration.id)) { - potion = player.getActivePotionEffect(Potion.regeneration); - } - if (potion == null || potion.getDuration() < 40 && potion.getAmplifier() != -5) - { - player.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), 5000, -5)); - } - potion = null; - if (player.isPotionActive(Potion.damageBoost.id)) { - potion = player.getActivePotionEffect(Potion.damageBoost); - } - if (potion == null || potion.getDuration() < 40 && potion.getAmplifier() != -5) { - player.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), 5000, -5)); - } - } - /** * Sneaky! Scare your friends! Or your enemies! * Sneak on another player to make them jump in confusion as they think one of those green bastards is behind him/her. * You can only do it once every so often. A couple of minutes. Remember, you must be sneaking. * - * @param player - * @param world - * @param backpack * @see com.darkona.adventurebackpack.handlers.PlayerEventHandler */ @SuppressWarnings("unchecked") @@ -453,10 +462,8 @@ public void itemCreeper(EntityPlayer player, World world, ItemStack backpack) pssstTime = 20; if (player.isSneaking()) { - List entities = player.worldObj.getEntitiesWithinAABBExcludingEntity(player, - AxisAlignedBB.getBoundingBox(player.posX, player.posY, player.posZ, - player.posX + 1.0D, player.posY + 1.0D, - player.posZ + 1.0D).expand(5.0D, 1.0D, 5.0D)); + List entities = player.worldObj.getEntitiesWithinAABBExcludingEntity + (player, AxisAlignedBB.getBoundingBox(player.posX, player.posY, player.posZ, player.posX + 1.0D, player.posY + 1.0D, player.posZ + 1.0D).expand(5.0D, 1.0D, 5.0D)); if (entities.isEmpty()) { pssstTime -= 1; @@ -488,14 +495,10 @@ public void itemCreeper(EntityPlayer player, World world, ItemStack backpack) * The Cow Backpack fills itself with milk when there is wheat in the backpack's inventory, but it will do so slowly * and will eat the wheat. It's like having a cow in your backpack. Each 16 wheat makes a bucket. It only happens * when it is being worn. For not-player related milk generation go get a cow. Moo! - * - * @param player - * @param world - * @param backpack */ public void itemCow(EntityPlayer player, World world, ItemStack backpack) { - if (world.isRemote) return; + if (world.isRemote) return; //TODO not syncing properly with client if GUI is open (see unused CowAbilityPacket?) InventoryBackpack inv = new InventoryBackpack(backpack); inv.openInventory(); @@ -508,10 +511,10 @@ public void itemCow(EntityPlayer player, World world, ItemStack backpack) int milkTime = -1; if (inv.getExtendedProperties() != null) { - if (inv.extendedProperties.hasKey("wheatConsumed")) + if (inv.getExtendedProperties().hasKey("wheatConsumed")) { - wheatConsumed = inv.extendedProperties.getInteger("wheatConsumed"); - milkTime = inv.extendedProperties.getInteger("milkTime") - 1; + wheatConsumed = inv.getExtendedProperties().getInteger("wheatConsumed"); + milkTime = inv.getExtendedProperties().getInteger("milkTime") - 1; } } @@ -542,10 +545,10 @@ public void itemCow(EntityPlayer player, World world, ItemStack backpack) inv.dirtyTanks(); } if (milkTime < -1) milkTime = -1; - inv.extendedProperties.setInteger("wheatConsumed", wheatConsumed); - inv.extendedProperties.setInteger("milkTime", milkTime); + inv.getExtendedProperties().setInteger("wheatConsumed", wheatConsumed); + inv.getExtendedProperties().setInteger("milkTime", milkTime); inv.setLastTime(eatTime); - // inv.setLastTime(eatTime); + //inv.setLastTime(eatTime); inv.dirtyExtended(); //inv.dirtyTanks(); inv.dirtyTime(); @@ -569,10 +572,10 @@ public void itemMooshroom(EntityPlayer player, World world, ItemStack backpack) int milkTime = -1; if (inv.getExtendedProperties() != null) { - if (inv.extendedProperties.hasKey("wheatConsumed")) + if (inv.getExtendedProperties().hasKey("wheatConsumed")) { - wheatConsumed = inv.extendedProperties.getInteger("wheatConsumed"); - milkTime = inv.extendedProperties.getInteger("milkTime") - 1; + wheatConsumed = inv.getExtendedProperties().getInteger("wheatConsumed"); + milkTime = inv.getExtendedProperties().getInteger("milkTime") - 1; } } @@ -603,10 +606,10 @@ public void itemMooshroom(EntityPlayer player, World world, ItemStack backpack) inv.dirtyTanks(); } if (milkTime < -1) milkTime = -1; - inv.extendedProperties.setInteger("wheatConsumed", wheatConsumed); - inv.extendedProperties.setInteger("milkTime", milkTime); + inv.getExtendedProperties().setInteger("wheatConsumed", wheatConsumed); + inv.getExtendedProperties().setInteger("milkTime", milkTime); inv.setLastTime(eatTime); - // inv.setLastTime(eatTime); + //inv.setLastTime(eatTime); inv.dirtyExtended(); //inv.dirtyTanks(); inv.dirtyTime(); @@ -619,26 +622,20 @@ public void itemMooshroom(EntityPlayer player, World world, ItemStack backpack) * The Wolf Backpack is a handy one if you're out in the wild. It checks around for any wolves that may lurk around. * If any of them gets mad at you, it will smell the scent of it's kin on you and promptly forget about the whole * deal. Smelling like dog is awesome. - * - * @param player the player - * @param world the world - * @param backpack the backpack */ @SuppressWarnings("unchecked") public void itemWolf(EntityPlayer player, World world, ItemStack backpack) { //lastTime is in Ticks for this backpack InventoryBackpack inv = new InventoryBackpack(backpack); - int lastCheckTime = inv.getLastTime() - 1; + int lastCheckTime = inv.getLastTime() - 1; if (lastCheckTime <= 0) { lastCheckTime = 20; - List wolves = world.getEntitiesWithinAABB( - EntityWolf.class, - AxisAlignedBB.getBoundingBox(player.posX, player.posY, player.posZ, - player.posX + 1.0D, player.posY + 1.0D, - player.posZ + 1.0D).expand(16.0D, 4.0D, 16.0D)); + List wolves = world.getEntitiesWithinAABB + (EntityWolf.class, AxisAlignedBB.getBoundingBox + (player.posX, player.posY, player.posZ, player.posX + 1.0D, player.posY + 1.0D, player.posZ + 1.0D).expand(16.0D, 4.0D, 16.0D)); if (wolves.isEmpty()) return; for (EntityWolf wolf : wolves) @@ -664,10 +661,6 @@ public void itemWolf(EntityPlayer player, World world, ItemStack backpack) * The Blaze Backpack will make you inmune to fire and lava and burning and heat and... not really. You're supposed * to die a fiery death if you are not careful, but this backpack will protect you against those burning fire * elemental inhabitants of the Nether. Any blast of fire directed your way will be stopped, deflected or whatever. - * - * @param player - * @param world - * @param backpack */ public void itemBlaze(EntityPlayer player, World world, ItemStack backpack) { @@ -677,10 +670,6 @@ public void itemBlaze(EntityPlayer player, World world, ItemStack backpack) /** * Like actual Ocelots and Cats, the Ocelot Backpack will scare the hell out of Creepers, so they won't creep on you * while you're busy doing something else, paying no attention whatsoever at your surroundings like a mindless chicken. - * - * @param player - * @param world - * @param backpack */ @SuppressWarnings("unchecked") public void itemOcelot(EntityPlayer player, World world, ItemStack backpack) @@ -691,17 +680,14 @@ public void itemOcelot(EntityPlayer player, World world, ItemStack backpack) if (lastCheckTime <= 0) { lastCheckTime = 20; - List creepers = player.worldObj.getEntitiesWithinAABB( - EntityCreeper.class, - AxisAlignedBB.getBoundingBox(player.posX, player.posY, player.posZ, - player.posX + 1.0D, player.posY + 1.0D, - player.posZ + 1.0D).expand(16.0D, 4.0D, 16.0D)); + List creepers = player.worldObj.getEntitiesWithinAABB + (EntityCreeper.class, AxisAlignedBB.getBoundingBox + (player.posX, player.posY, player.posZ, player.posX + 1.0D, player.posY + 1.0D, player.posZ + 1.0D).expand(16.0D, 4.0D, 16.0D)); for (EntityCreeper creeper : creepers) { boolean set = true; - EntityAIAvoidPlayerWithBackpack task = new EntityAIAvoidPlayerWithBackpack(creeper, EntityPlayer.class, 10.0F, 1.0, 1.3, "Ocelot"); - + EntityAIAvoidPlayerWithBackpack task = new EntityAIAvoidPlayerWithBackpack(creeper, EntityPlayer.class, 10.0F, 1.0, 1.3, BackpackTypes.OCELOT); for (Object entry : creeper.tasks.taskEntries) { if (((EntityAITasks.EntityAITaskEntry) entry).action instanceof EntityAIAvoidPlayerWithBackpack) @@ -722,35 +708,6 @@ public void itemOcelot(EntityPlayer player, World world, ItemStack backpack) inv.markDirty(); } - - public void itemRainbow(EntityPlayer player, World world, ItemStack backpack) - { - InventoryBackpack inv = new InventoryBackpack(backpack); - int noteTime = inv.getLastTime() - 1; - if (noteTime >= 0 && noteTime < Utils.secondsToTicks(147)) - { - player.setSprinting(true); - player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 40, 2)); - player.addPotionEffect(new PotionEffect(Potion.jump.getId(), 40, 2)); - if (noteTime % 2 == 0) - { - //Visuals.NyanParticles(player, world); - if (!world.isRemote) - { - ModNetwork.sendToNearby(new EntityParticlePacket.Message(EntityParticlePacket.NYAN_PARTICLE, player), player); - } - } - } - PotionEffect potion = null; - if (player.isPotionActive(Potion.moveSpeed.id)) { - potion = player.getActivePotionEffect(Potion.moveSpeed); - } - if (potion == null || potion.getDuration() < 40 && potion.getAmplifier() != -5) { - player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 5000, -5)); - } - inv.setLastTime(noteTime); - inv.markDirty(); - } /* ==================================== TILE ABILITIES ==========================================*/ private void fillWithRain(World world, TileAdventureBackpack backpack, FluidStack fluid, int time) @@ -771,19 +728,19 @@ private void fillWithRain(World world, TileAdventureBackpack backpack, FluidStac /** * Like real life cactii, this backpack will fill slowly while it's raining with refreshing water. - * - * @param world - * @param backpack */ public void tileCactus(World world, TileAdventureBackpack backpack) { fillWithRain(world, backpack, new FluidStack(FluidRegistry.WATER, 2), 5); } - public void tileMelon(World world, TileAdventureBackpack backpack) { fillWithRain(world, backpack, new FluidStack(ModFluids.melonJuice, 2), 5); } + /*public void tileCow(World world, TileAdventureBackpack backpack) + { + IInventoryBackpack inv = backpack; //TODO make CowBackpack (and others) working in tile form + }*/ } diff --git a/src/main/java/com/darkona/adventurebackpack/common/BackpackRemovals.java b/src/main/java/com/darkona/adventurebackpack/common/BackpackRemovals.java index f899b331..94fa1781 100644 --- a/src/main/java/com/darkona/adventurebackpack/common/BackpackRemovals.java +++ b/src/main/java/com/darkona/adventurebackpack/common/BackpackRemovals.java @@ -1,13 +1,15 @@ package com.darkona.adventurebackpack.common; -import com.darkona.adventurebackpack.inventory.InventoryBackpack; -import com.darkona.adventurebackpack.util.Wearing; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.inventory.InventoryBackpack; +import com.darkona.adventurebackpack.util.Wearing; + /** * Created on 09/01/2015 * @@ -18,13 +20,18 @@ public class BackpackRemovals public void itemBat(EntityPlayer player, World world, ItemStack backpack) { PotionEffect potion = null; - if (player.isPotionActive(Potion.nightVision.id)) { + if (player.isPotionActive(Potion.nightVision.id)) + { potion = player.getActivePotionEffect(Potion.nightVision); - if (potion != null && potion.getAmplifier() == -4) { - if (player.worldObj.isRemote) { + if (potion != null && potion.getAmplifier() == -1) + { + if (player.worldObj.isRemote) + { player.removePotionEffectClient(Potion.nightVision.id); - } else { + } + else + { player.removePotionEffect(Potion.nightVision.id); } } @@ -35,13 +42,18 @@ public void itemSquid(EntityPlayer player, World world, ItemStack backpack) { itemBat(player, world, backpack); PotionEffect potion = null; - if (player.isPotionActive(Potion.waterBreathing.id)) { + if (player.isPotionActive(Potion.waterBreathing.id)) + { potion = player.getActivePotionEffect(Potion.waterBreathing); - if (potion != null && potion.getAmplifier() == -5) { - if (player.worldObj.isRemote) { + if (potion != null && potion.getAmplifier() == -1) + { + if (player.worldObj.isRemote) + { player.removePotionEffectClient(Potion.waterBreathing.id); - } else { + } + else + { player.removePotionEffect(Potion.waterBreathing.id); } } @@ -51,41 +63,57 @@ public void itemSquid(EntityPlayer player, World world, ItemStack backpack) public void itemPigman(EntityPlayer player, World world, ItemStack backpack) { PotionEffect potion = null; - if (player.isPotionActive(Potion.fireResistance.id)) { + if (player.isPotionActive(Potion.fireResistance.id)) + { potion = player.getActivePotionEffect(Potion.fireResistance); - if (potion != null && potion.getAmplifier() == -5) { - if (player.worldObj.isRemote) { + if (potion != null && potion.getAmplifier() == -1) + { + if (player.worldObj.isRemote) + { player.removePotionEffectClient(Potion.fireResistance.id); - } else { + } + else + { player.removePotionEffect(Potion.fireResistance.id); } } } } + public void itemDragon(EntityPlayer player, World world, ItemStack backpack) { itemBat(player, world, backpack); - itemPigman(player,world,backpack); + itemPigman(player, world, backpack); PotionEffect potion = null; - if (player.isPotionActive(Potion.damageBoost.id)) { + if (player.isPotionActive(Potion.damageBoost.id)) + { potion = player.getActivePotionEffect(Potion.damageBoost); - if (potion != null && potion.getAmplifier() == -5) { - if (player.worldObj.isRemote) { + if (potion != null && potion.getAmplifier() == ConfigHandler.dragonBackpackDamage - 1) + { + if (player.worldObj.isRemote) + { player.removePotionEffectClient(Potion.damageBoost.id); - } else { + } + else + { player.removePotionEffect(Potion.damageBoost.id); } } } potion = null; - if (player.isPotionActive(Potion.regeneration.id)) { + if (player.isPotionActive(Potion.regeneration.id)) + { potion = player.getActivePotionEffect(Potion.regeneration); - if (potion != null && potion.getAmplifier() == -5) { - if (player.worldObj.isRemote) { + if (potion != null && potion.getAmplifier() == ConfigHandler.dragonBackpackRegen - 1) + { + if (player.worldObj.isRemote) + { player.removePotionEffectClient(Potion.regeneration.id); - } else { + } + else + { player.removePotionEffect(Potion.regeneration.id); } } @@ -99,24 +127,18 @@ public void itemRainbow(EntityPlayer player, World world, ItemStack backpack) inv.setLastTime(0); inv.dirtyTime(); PotionEffect potion = null; - if (player.isPotionActive(Potion.moveSpeed.id)) { + if (player.isPotionActive(Potion.moveSpeed.id)) + { potion = player.getActivePotionEffect(Potion.moveSpeed); - if (potion != null && potion.getAmplifier() == 2) { - if (player.worldObj.isRemote) { + if (potion != null && potion.getAmplifier() == ConfigHandler.rainbowBackpackSpeed - 1) + { + if (player.worldObj.isRemote) + { player.removePotionEffectClient(Potion.moveSpeed.id); - } else { - player.removePotionEffect(Potion.moveSpeed.id); } - } - } - potion = null; - if (player.isPotionActive(Potion.jump.id)) { - potion = player.getActivePotionEffect(Potion.jump); - if (potion != null && potion.getAmplifier() == 2) { - if (player.worldObj.isRemote) { - player.removePotionEffectClient(Potion.jump.id); - } else { - player.removePotionEffect(Potion.jump.id); + else + { + player.removePotionEffect(Potion.moveSpeed.id); } } } diff --git a/src/main/java/com/darkona/adventurebackpack/common/Constants.java b/src/main/java/com/darkona/adventurebackpack/common/Constants.java index ab583709..9ce11ba1 100644 --- a/src/main/java/com/darkona/adventurebackpack/common/Constants.java +++ b/src/main/java/com/darkona/adventurebackpack/common/Constants.java @@ -4,25 +4,91 @@ /** * Created on 11/10/2014. + * * @author Javier Darkona */ public class Constants { + public enum Source //TODO move to separate class? + { + TILE, HOLDING, WEARING + } - public static final int inventorySize = 45; - public static final int bucket = FluidContainerRegistry.BUCKET_VOLUME; - public static final int basicTankCapacity = bucket * 4; - public static final int advancedTankCapacity = bucket * 8; - public static final int heroicTankCapacity = bucket * 12; + // General + public static final int BUCKET = FluidContainerRegistry.BUCKET_VOLUME; - //Inventory Special Slots - private static final int endOfInventory = inventorySize - 7; - public static final int upperTool = endOfInventory + 1; - public static final int lowerTool = upperTool + 1; + // Wearable NBT + public static final String TAG_WEARABLE_COMPOUND = "wearableData"; + public static final String TAG_EXTENDED_COMPOUND = "extendedProperties"; + public static final String TAG_INVENTORY = "inventory"; + public static final String TAG_SLOT = "Slot"; - public static final int bucketInLeft = lowerTool + 1; - public static final int bucketOutLeft = bucketInLeft + 1; - public static final int bucketInRight = bucketOutLeft + 1; - public static final int bucketOutRight = bucketInRight + 1; + /** + * ### Adventure Backpack ### + */ + public static final int BASIC_TANK_CAPACITY = BUCKET * 4; + //public static final int ADVANCED_TANK_CAPACITY = BUCKET * 8; // upgrade system? + //public static final int HEROIC_TANK_CAPACITY = BUCKET * 12; + // Inventory Slots + public static final int INVENTORY_SIZE = 54; + public static final int INVENTORY_SPECIAL_SIZE = 6; // tooSlot * 2, bucketIn * 2, bucketOut * 2 + public static final int INVENTORY_MAIN_SIZE = INVENTORY_SIZE - INVENTORY_SPECIAL_SIZE; // 0 excluded + public static final int END_OF_INVENTORY = INVENTORY_MAIN_SIZE - 1; // 0 included + + public static final int TOOL_UPPER = END_OF_INVENTORY + 1; + public static final int TOOL_LOWER = TOOL_UPPER + 1; + + public static final int BUCKET_IN_LEFT = TOOL_LOWER + 1; + public static final int BUCKET_OUT_LEFT = BUCKET_IN_LEFT + 1; + public static final int BUCKET_IN_RIGHT = BUCKET_OUT_LEFT + 1; + public static final int BUCKET_OUT_RIGHT = BUCKET_IN_RIGHT + 1; + + // NBT + public static final String TAG_TYPE = "type"; + public static final String TAG_LEFT_TANK = "leftTank"; + public static final String TAG_RIGHT_TANK = "rightTank"; + public static final String TAG_DISABLE_CYCLING = "disableCycling"; + public static final String TAG_DISABLE_NVISION = "disableNVision"; + + // NBT: Extended Properties + public static final String TAG_HOLDING_SPACE = "holdingSpace"; + public static final String TAG_SLEEPING_IN_BAG = "sleepingInBag"; + + public class Jetpack + { + /** + * ### Coal Jetpack ### + */ + public static final int MAX_TEMPERATURE = 200; + public static final int WATER_CAPACITY = BUCKET * 6; + public static final int STEAM_CAPACITY = BUCKET * 12; + + // Inventory Slots + public static final int INVENTORY_SIZE = 3; + public static final int BUCKET_IN = 0; + public static final int BUCKET_OUT = 1; + public static final int FUEL_SLOT = 2; + + // NBT + public static final String TAG_WATER_TANK = "waterTank"; + public static final String TAG_STEAM_TANK = "steamTank"; + } + + public class Copter + { + /** + * ### Copter Pack ### + */ + public static final int FUEL_CAPACITY = BUCKET * 6; + + // Inventory Slots + public static final int INVENTORY_SIZE = 2; + public static final int BUCKET_IN = 0; + public static final int BUCKET_OUT = 1; + + // NBT + public static final String TAG_STATUS = "status"; + public static final String TAG_FUEL_TANK = "fuelTank"; + } } diff --git a/src/main/java/com/darkona/adventurebackpack/common/IInventoryAdventureBackpack.java b/src/main/java/com/darkona/adventurebackpack/common/IInventoryAdventureBackpack.java deleted file mode 100644 index 9d058966..00000000 --- a/src/main/java/com/darkona/adventurebackpack/common/IInventoryAdventureBackpack.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.darkona.adventurebackpack.common; - -import com.darkona.adventurebackpack.block.TileAdventureBackpack; -import com.darkona.adventurebackpack.inventory.IInventoryTanks; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.FluidTank; - -/** - * Created by Darkona on 12/10/2014. - */ -public interface IInventoryAdventureBackpack extends IInventoryTanks -{ - - public FluidTank getLeftTank(); - - public FluidTank getRightTank(); - - public ItemStack[] getInventory(); - - public TileAdventureBackpack getTile(); - - public ItemStack getParentItemStack(); - - public String getColorName(); - - public int getLastTime(); - - public NBTTagCompound getExtendedProperties(); - - public void setExtendedProperties(NBTTagCompound properties); - - public boolean isSpecial(); - - public void saveTanks(NBTTagCompound compound); - - public void loadTanks(NBTTagCompound compound); - - public boolean hasItem(Item item); - - void consumeInventoryItem(Item item); - - boolean isSBDeployed(); - - void setLastTime(int time); - - - public void dirtyTime(); - - public void dirtyExtended(); - -} diff --git a/src/main/java/com/darkona/adventurebackpack/common/ServerActions.java b/src/main/java/com/darkona/adventurebackpack/common/ServerActions.java index 79c48a42..42994874 100644 --- a/src/main/java/com/darkona/adventurebackpack/common/ServerActions.java +++ b/src/main/java/com/darkona/adventurebackpack/common/ServerActions.java @@ -1,31 +1,45 @@ package com.darkona.adventurebackpack.common; -import com.darkona.adventurebackpack.block.TileAdventureBackpack; -import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; -import com.darkona.adventurebackpack.init.ModNetwork; -import com.darkona.adventurebackpack.inventory.InventoryBackpack; -import com.darkona.adventurebackpack.inventory.InventorySteamJetpack; -import com.darkona.adventurebackpack.item.ItemCopterPack; -import com.darkona.adventurebackpack.item.ItemHose; -import com.darkona.adventurebackpack.network.WearableModePacket; -import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Wearing; +import java.util.Random; + +import net.minecraft.block.Block; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; -import java.util.Random; +import com.darkona.adventurebackpack.block.BlockSleepingBag; +import com.darkona.adventurebackpack.block.TileAdventureBackpack; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.inventory.InventoryBackpack; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; +import com.darkona.adventurebackpack.inventory.SlotTool; +import com.darkona.adventurebackpack.item.ItemCopterPack; +import com.darkona.adventurebackpack.item.ItemHose; +import com.darkona.adventurebackpack.network.WearableModePacket; +import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; +import com.darkona.adventurebackpack.playerProperties.BackpackProperty; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.reference.GeneralReference; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.CoordsUtils; +import com.darkona.adventurebackpack.util.Wearing; + +import static com.darkona.adventurebackpack.common.Constants.BUCKET; +import static com.darkona.adventurebackpack.common.Constants.Copter.TAG_STATUS; +import static com.darkona.adventurebackpack.common.Constants.TOOL_LOWER; +import static com.darkona.adventurebackpack.common.Constants.TOOL_UPPER; /** * Created on 23/12/2014 @@ -38,42 +52,26 @@ public class ServerActions public static final boolean HOSE_TOGGLE = true; /** - * Cycles tools. In a cycle. The tool in your hand with the tools in the special tool slots of the backpack, to be precise. + * Cycles tools. In a cycle. The tool in your hand with the tools in the special tool playerSlot of the backpack, + * to be precise. * - * @param player - Duh - * @param direction - An integer indicating the direction of the switch. Nobody likes to swith always inthe same + * @param player Duh + * @param isWheelUp A boolean indicating the direction of the switch. Nobody likes to swith always in the same * direction all the timeInSeconds. That's stupid. - * @param slot The slot that will be switched with the backpack. */ - public static void cycleTool(EntityPlayer player, int direction, int slot) + public static void cycleTool(EntityPlayer player, boolean isWheelUp) { - try - { - InventoryBackpack backpack = Wearing.getBackpackInv(player, true); - ItemStack current = player.getCurrentEquippedItem(); - backpack.openInventory(); - if (direction < 0) - { - //LogHelper.info("Item of class " + backpack.getStackInSlot(Constants.lowerTool).getItem().getClass().getName()); - player.inventory.mainInventory[slot] = backpack.getStackInSlot(Constants.upperTool); - backpack.setInventorySlotContentsNoSave(Constants.upperTool, backpack.getStackInSlot(Constants.lowerTool)); - backpack.setInventorySlotContentsNoSave(Constants.lowerTool, current); + if (!GeneralReference.isDimensionAllowed(player)) + return; - } else - { - if (direction > 0) - { - player.inventory.mainInventory[slot] = backpack.getStackInSlot(Constants.lowerTool); - backpack.setInventorySlotContentsNoSave(Constants.lowerTool, backpack.getStackInSlot(Constants.upperTool)); - backpack.setInventorySlotContentsNoSave(Constants.upperTool, current); - } - } - backpack.markDirty(); - player.inventory.closeInventory(); - } catch (Exception oops) + int playerSlot = player.inventory.currentItem; + ItemStack current = player.getCurrentEquippedItem(); + if (SlotTool.isValidTool(current)) { - LogHelper.debug("Exception trying to cycle tools."); - oops.printStackTrace(); + int backpackSlot = isWheelUp ? TOOL_UPPER : TOOL_LOWER; + InventoryBackpack backpack = Wearing.getWearingBackpackInv(player); + player.inventory.setInventorySlotContents(playerSlot, backpack.getStackInSlot(backpackSlot)); + backpack.setInventorySlotContents(backpackSlot, current); } } @@ -87,9 +85,9 @@ public static void cycleTool(EntityPlayer player, int direction, int slot) */ public static boolean setFluidEffect(World world, EntityPlayer player, FluidTank tank) { - FluidStack drained = tank.drain(Constants.bucket, false); + FluidStack drained = tank.drain(BUCKET, false); boolean done = false; - if (drained != null && drained.amount >= Constants.bucket && FluidEffectRegistry.hasFluidEffect(drained.getFluid())) + if (drained != null && drained.amount >= BUCKET && FluidEffectRegistry.hasFluidEffect(drained.getFluid())) { done = FluidEffectRegistry.executeFluidEffectsForFluid(drained.getFluid(), player, world); } @@ -98,25 +96,29 @@ public static boolean setFluidEffect(World world, EntityPlayer player, FluidTank /** * @param player Duh! - * @param direction The direction in which the hose modes will switch. + * @param isWheelUp The direction in which the hose modes will switch. * @param action The type of the action to be performed on the hose. * Can be HOSE_SWITCH for mode or HOSE_TOGGLE for tank - * @param slot The slot in which the hose gleefully frolicks in the inventory. */ - public static void switchHose(EntityPlayer player, boolean action, int direction, int slot) + public static void switchHose(EntityPlayer player, boolean isWheelUp, boolean action) { - - ItemStack hose = player.inventory.mainInventory[slot]; - if (hose != null && hose.getItem() instanceof ItemHose) + if (Wearing.isHoldingHose(player)) { + ItemStack hose = player.inventory.getCurrentItem(); NBTTagCompound tag = hose.hasTagCompound() ? hose.stackTagCompound : new NBTTagCompound(); + if (!action) { int mode = ItemHose.getHoseMode(hose); - if (direction > 0) + if (!ConfigHandler.enableHoseDrink) + { + mode = (mode + 1) % 2; + } + else if (isWheelUp) { mode = (mode + 1) % 3; - } else if (direction < 0) + } + else { mode = (mode - 1 < 0) ? 2 : mode - 1; } @@ -129,6 +131,7 @@ public static void switchHose(EntityPlayer player, boolean action, int direction tank = (tank + 1) % 2; tag.setInteger("tank", tank); } + hose.setTagCompound(tag); } } @@ -141,21 +144,17 @@ public static void switchHose(EntityPlayer player, boolean action, int direction public static void electrify(EntityPlayer player) { ItemStack backpack = Wearing.getWearingBackpack(player); - if (BackpackNames.getBackpackColorName(backpack).equals("Pig")) + + if (BackpackTypes.getType(backpack) == BackpackTypes.PIG) { - BackpackNames.setBackpackColorName(backpack, "Pigman"); + BackpackUtils.setBackpackType(backpack, BackpackTypes.PIGMAN); } - if (BackpackNames.getBackpackColorName(backpack).equals("Diamond")) + else if (BackpackTypes.getType(backpack) == BackpackTypes.DIAMOND) { - BackpackNames.setBackpackColorName(backpack, "Electric"); + BackpackUtils.setBackpackType(backpack, BackpackTypes.ELECTRIC); } } - /** - * @param player - * @param bow - * @param charge - */ public static void leakArrow(EntityPlayer player, ItemStack bow, int charge) { World world = player.worldObj; @@ -204,20 +203,21 @@ public static void leakArrow(EntityPlayer player, ItemStack bow, int charge) if (flag) { entityarrow.canBePickedUp = 2; - } else + } + else { /* - * From here, instead of leaking an arrow to the player inventory, which may be full and then it would be - * pointless, leak an arrow straight from the backpack ^_^ - * - * It could be possible to switch a whole stack with the player inventory, fire the arrow, and then - * switch back, but that's stupid. - * - * That's how you make a quiver (for vanilla bows at least, or anything that uses the events and vanilla - * arrows) Until we have an event that fires when a player consumes items in his/her inventory. - * - * I should make a pull request. Too lazy, though. - * */ + * From here, instead of leaking an arrow to the player inventory, which may be full and then it would be + * pointless, leak an arrow straight from the backpack ^_^ + * + * It could be possible to switch a whole stack with the player inventory, fire the arrow, and then + * switch back, but that's stupid. + * + * That's how you make a quiver (for vanilla bows at least, or anything that uses the events and vanilla + * arrows) Until we have an event that fires when a player consumes items in his/her inventory. + * + * I should make a pull request. Too lazy, though. + * */ backpack.consumeInventoryItem(Items.arrow); backpack.dirtyInventory(); } @@ -229,96 +229,63 @@ public static void leakArrow(EntityPlayer player, ItemStack bow, int charge) } } - /** - * @param player - * @param coordX - * @param coordY - * @param coordZ - */ - public static void toggleSleepingBag(EntityPlayer player, int coordX, int coordY, int coordZ) + public static void toggleSleepingBag(EntityPlayer player, boolean isTile, int cX, int cY, int cZ) { World world = player.worldObj; - if (world.getTileEntity(coordX, coordY, coordZ) instanceof TileAdventureBackpack) + + if (!world.provider.canRespawnHere() || world.getBiomeGenForCoords(cX, cZ) == BiomeGenBase.hell) { - TileAdventureBackpack te = (TileAdventureBackpack) world.getTileEntity(coordX, coordY, coordZ); - if (!te.isSBDeployed()) + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.cant.sleep.here")); + player.closeScreen(); + return; + } + + if (isTile && world.getTileEntity(cX, cY, cZ) instanceof TileAdventureBackpack) + { + TileAdventureBackpack te = (TileAdventureBackpack) world.getTileEntity(cX, cY, cZ); + if (!te.isSleepingBagDeployed()) { - int can[] = canDeploySleepingBag(world, coordX, coordY, coordZ); + int can[] = CoordsUtils.canDeploySleepingBag(world, player, cX, cY, cZ, true); if (can[0] > -1) { - if (te.deploySleepingBag(player, world, can[1], can[2], can[3], can[0])) + if (te.deploySleepingBag(player, world, can[0], can[1], can[2], can[3])) { player.closeScreen(); } - } else if (world.isRemote) + } + else if (!world.isRemote) { - player.addChatComponentMessage(new ChatComponentText("Can't deploy the sleeping bag! Check the surrounding area.")); + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.backpack.cant.bag")); } - } else + } + else { te.removeSleepingBag(world); } player.closeScreen(); } - - } - - public static int[] canDeploySleepingBag(World world, int coordX, int coordY, int coordZ) - { - TileAdventureBackpack te = (TileAdventureBackpack) world.getTileEntity(coordX, coordY, coordZ); - int newMeta = -1; - - if (!te.isSBDeployed()) + else if (!isTile && Wearing.isWearingBackpack(player)) { - int meta = world.getBlockMetadata(coordX, coordY, coordZ); - switch (meta & 3) + int can[] = CoordsUtils.canDeploySleepingBag(world, player, cX, cY, cZ, false); + if (can[0] > -1) { - case 0: - --coordZ; - if (world.isAirBlock(coordX, coordY, coordZ) && world.getBlock(coordX, coordY - 1, coordZ).getMaterial().isSolid()) - { - if (world.isAirBlock(coordX, coordY, coordZ - 1) && world.getBlock(coordX, coordY - 1, coordZ - 1).getMaterial().isSolid()) - { - newMeta = 2; - } - } - break; - case 1: - ++coordX; - if (world.isAirBlock(coordX, coordY, coordZ) && world.getBlock(coordX, coordY - 1, coordZ).getMaterial().isSolid()) - { - if (world.isAirBlock(coordX + 1, coordY, coordZ) && world.getBlock(coordX + 1, coordY - 1, coordZ).getMaterial().isSolid()) - { - newMeta = 3; - } - } - break; - case 2: - ++coordZ; - if (world.isAirBlock(coordX, coordY, coordZ) && world.getBlock(coordX, coordY - 1, coordZ).getMaterial().isSolid()) - { - if (world.isAirBlock(coordX, coordY, coordZ + 1) && world.getBlock(coordX, coordY - 1, coordZ + 1).getMaterial().isSolid()) - { - newMeta = 0; - } - } - break; - case 3: - --coordX; - if (world.isAirBlock(coordX, coordY, coordZ) && world.getBlock(coordX, coordY - 1, coordZ).getMaterial().isSolid()) + InventoryBackpack inv = Wearing.getWearingBackpackInv(player); + if (inv.deploySleepingBag(player, world, can[0], can[1], can[2], can[3])) + { + Block portableBag = world.getBlock(can[1], can[2], can[3]); + if (portableBag instanceof BlockSleepingBag) { - if (world.isAirBlock(coordX - 1, coordY, coordZ) && world.getBlock(coordX - 1, coordY - 1, coordZ).getMaterial().isSolid()) - { - newMeta = 1; - } + inv.getExtendedProperties().setBoolean(Constants.TAG_SLEEPING_IN_BAG, true); + ((BlockSleepingBag) portableBag).onPortableBlockActivated(world, player, can[1], can[2], can[3]); } - break; - default: - break; + } + } + else if (!world.isRemote) + { + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.backpack.cant.bag")); } + player.closeScreen(); } - int result[] = {newMeta, coordX, coordY, coordZ}; - return result; } /** @@ -330,28 +297,40 @@ public static int[] canDeploySleepingBag(World world, int coordX, int coordY, in */ public static void pistonBootsJump(EntityPlayer player) { - //TODO add configuration for the playing of the sound effect. - //TODO Maybe configurable jump height too, because why not. - player.playSound("tile.piston.out", 0.5F, player.getRNG().nextFloat() * 0.25F + 0.6F); - player.motionY += 0.30; + if (ConfigHandler.allowSoundPiston) + { + player.playSound("tile.piston.out", 0.5F, player.getRNG().nextFloat() * 0.25F + 0.6F); + } + player.motionY += ConfigHandler.pistonBootsJumpHeight / 10.0F; player.jumpMovementFactor += 0.3; } - public static void toggleCopterPack(EntityPlayer player, ItemStack copter, byte type) + public static void copterSoundAtLogin(EntityPlayer player) { - String message = ""; - boolean actionPerformed = false; + byte status = BackpackUtils.getWearableCompound(BackpackProperty.get(player).getWearable()).getByte(TAG_STATUS); - if (!copter.hasTagCompound()) + if (!player.worldObj.isRemote && status != ItemCopterPack.OFF_MODE) { - copter.stackTagCompound = new NBTTagCompound(); + ModNetwork.sendToNearby(new EntitySoundPacket.Message(EntitySoundPacket.COPTER_SOUND, player), player); } - if (!copter.stackTagCompound.hasKey("status")) + } + + public static void jetpackSoundAtLogin(EntityPlayer player) + { + boolean isBoiling = BackpackUtils.getWearableCompound(BackpackProperty.get(player).getWearable()).getBoolean("boiling"); + + if (!player.worldObj.isRemote && isBoiling) { - copter.stackTagCompound.setByte("status", ItemCopterPack.OFF_MODE); + //ModNetwork.sendToNearby(new EntitySoundPacket.Message(EntitySoundPacket.BOILING_BUBBLES, player), player); //TODO difference? + ModNetwork.net.sendTo(new EntitySoundPacket.Message(EntitySoundPacket.BOILING_BUBBLES, player), (EntityPlayerMP) player); } + } - byte mode = copter.stackTagCompound.getByte("status"); + public static void toggleCopterPack(EntityPlayer player, ItemStack copter, byte type) + { + String message = ""; + boolean actionPerformed = false; + byte mode = BackpackUtils.getWearableCompound(copter).getByte(TAG_STATUS); byte newMode = ItemCopterPack.OFF_MODE; if (type == WearableModePacket.COPTER_ON_OFF) @@ -363,10 +342,10 @@ public static void toggleCopterPack(EntityPlayer player, ItemStack copter, byte actionPerformed = true; if (!player.worldObj.isRemote) { - ModNetwork.sendToNearby(new EntitySoundPacket.Message(EntitySoundPacket.COPTER_SOUND,player), player); - + ModNetwork.sendToNearby(new EntitySoundPacket.Message(EntitySoundPacket.COPTER_SOUND, player), player); } - } else + } + else { newMode = ItemCopterPack.OFF_MODE; message = "adventurebackpack:messages.copterpack.off"; @@ -392,19 +371,69 @@ public static void toggleCopterPack(EntityPlayer player, ItemStack copter, byte if (actionPerformed) { - copter.stackTagCompound.setByte("status", newMode); + BackpackUtils.getWearableCompound(copter).setByte(TAG_STATUS, newMode); if (player.worldObj.isRemote) { player.addChatComponentMessage(new ChatComponentTranslation(message)); } + } + } + + public static void toggleToolCycling(EntityPlayer player, ItemStack backpack) + { + InventoryBackpack inv = new InventoryBackpack(backpack); + if (ConfigHandler.enableToolsCycling) + { + if (inv.getDisableCycling()) + { + inv.setDisableCycling(false); + inv.markDirty(); + if (player.worldObj.isRemote) + { + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.cycling.on")); + } + } + else + { + inv.setDisableCycling(true); + inv.markDirty(); + if (player.worldObj.isRemote) + { + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.cycling.off")); + } + } + } + } + public static void toggleNightVision(EntityPlayer player, ItemStack backpack) + { + InventoryBackpack inv = new InventoryBackpack(backpack); + if (inv.getDisableNVision()) + { + inv.setDisableNVision(false); + inv.markDirty(); + if (player.worldObj.isRemote) + { + player.playSound("mob.bat.idle", 0.2F, 1.0F); + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.nightvision.on")); + } + } + else + { + inv.setDisableNVision(true); + inv.markDirty(); + if (player.worldObj.isRemote) + { + player.playSound("mob.bat.death", 0.2F, 2.0F); + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.nightvision.off")); + } } } - public static void toggleSteamJetpack(EntityPlayer player, ItemStack jetpack, byte on_off) + public static void toggleCoalJetpack(EntityPlayer player, ItemStack jetpack) { - InventorySteamJetpack inv = new InventorySteamJetpack(jetpack); - if(inv.getStatus()) + InventoryCoalJetpack inv = new InventoryCoalJetpack(jetpack); + if (inv.getStatus()) { inv.setStatus(false); inv.markDirty(); @@ -412,7 +441,9 @@ public static void toggleSteamJetpack(EntityPlayer player, ItemStack jetpack, by { player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.jetpack.off")); } - }else{ + } + else + { inv.setStatus(true); inv.markDirty(); if (player.worldObj.isRemote) @@ -421,4 +452,4 @@ public static void toggleSteamJetpack(EntityPlayer player, ItemStack jetpack, by } } } -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/config/ConfigHandler.java b/src/main/java/com/darkona/adventurebackpack/config/ConfigHandler.java index 719f914c..36d9762a 100644 --- a/src/main/java/com/darkona/adventurebackpack/config/ConfigHandler.java +++ b/src/main/java/com/darkona/adventurebackpack/config/ConfigHandler.java @@ -1,47 +1,94 @@ package com.darkona.adventurebackpack.config; -import com.darkona.adventurebackpack.reference.ModInfo; +import java.io.File; + +import net.minecraftforge.common.config.Configuration; import cpw.mods.fml.client.event.ConfigChangedEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.common.config.Configuration; -import java.io.File; +import com.darkona.adventurebackpack.reference.ModInfo; /** * Created on 10/10/2014. + * * @author Javier Darkona */ public class ConfigHandler { - - public static Configuration config; - public static boolean IS_BUILDCRAFT = false; - public static boolean IS_BAUBLES = false; - public static boolean IS_TINKERS = false; - public static boolean IS_THAUM = false; - public static boolean IS_TWILIGHT = false; - public static boolean IS_ENVIROMINE = false; - public static boolean IS_RAILCRAFT = false; - - public static int GUI_TANK_RENDER = 2; - public static boolean BONUS_CHEST_ALLOWED = false; - public static boolean PIGMAN_ALLOWED = false; - - public static boolean BACKPACK_DEATH_PLACE = true; - public static boolean BACKPACK_ABILITIES = true; - - public static boolean ALLOW_COPTER_SOUND = true; - public static boolean ALLOW_JETPACK_SOUNDS = true; - - - public static boolean STATUS_OVERLAY = true; - public static boolean TANKS_OVERLAY = true; - public static boolean HOVERING_TEXT_TANKS = false; - public static boolean SADDLE_RECIPE = true; - public static boolean FIX_LEAD = true; - + public static boolean allowSoulBound = true; + public static boolean backpackDeathPlace = true; + public static boolean backpackAbilities = true; + public static boolean enableCampfireSpawn = false; + public static boolean enableHoseDrink = true; + public static boolean enableToolsCycling = true; + public static boolean fixLead = true; + public static boolean portableSleepingBag = true; + public static boolean tinkerToolsMaintenance = true; + + public static boolean enableFullnessBar = false; + public static boolean enableTemperatureBar = false; + public static boolean enableToolsRender = true; + public static int typeTankRender = 2; + public static boolean tanksHoveringText = false; + + public static boolean statusOverlay = true; + public static boolean statusOverlayLeft = true; + public static boolean statusOverlayTop = true; + public static int statusOverlayIndentH = 2; + public static int statusOverlayIndentV = 2; + public static boolean statusOverlayThaumcraft = true; + + public static boolean tanksOverlay = true; + public static boolean tanksOverlayRight = true; + public static boolean tanksOverlayBottom = true; + public static int tanksOverlayIndentH = 2; + public static int tanksOverlayIndentV = 1; + + public static boolean allowSoundCopter = true; + public static boolean allowSoundJetpack = true; + public static boolean allowSoundPiston = true; + + public static boolean enableItemFilters = false; + public static String[] forbiddenDimensions; + public static String[] copterFuels; + private static String[] defaultFuels = {"biodiesel, 1.0", "biofuel, 1.0", "bioethanol, 1.5", "creosote, 7.0", + "fuel, 0.8", "lava, 5.0", "liquid_light_oil, 3.0", "liquid_medium_oil, 3.0", "liquid_heavy_oil, 3.0", + "liquid_light_fuel, 1.0", "liquid_heavy_fuel, 1.3", "nitrofuel, 0.4", "oil, 3.0", "rocket_fuel, 0.8"}; + + public static String[] nameLocalized; + public static String[] nameInternalID; + public static String[] nameInternalIDs; + public static String[] nameUnlocalized; + private static String[] nameDefault = {}; + + public static boolean consumeDragonEgg = false; + public static boolean recipeAdventuresSet = true; + public static boolean recipeInflatableBoat = true; + public static boolean recipeInflatableBoatM = false; + public static boolean recipeClockCrossbow = true; + public static boolean recipeCoalJetpack = true; + public static boolean recipeCopterPack = true; + public static boolean recipePitonBoots = true; + public static boolean recipeSaddle = true; + public static boolean recipeMachete = true; + + public static boolean pistonBootsAutoStep = true; + public static int pistonBootsJumpHeight = 3; + public static int pistonBootsSprintBoost = 1; + public static int dragonBackpackRegen = 1; + public static int dragonBackpackDamage = 2; + public static int rainbowBackpackSpeed = 1; + public static int rainbowBackpackSSpeed = 3; + public static int rainbowBackpackSJump = 1; + + public static boolean allowBatGen = true; + public static boolean allowBonusGen = false; + public static boolean allowGolemGen = true; + public static boolean allowPigmanGen = false; + + public static int bossBarIndent = 12; public static void init(File configFile) { @@ -52,22 +99,89 @@ public static void init(File configFile) } } - private static void loadConfiguration() { - GUI_TANK_RENDER = config.getInt("TankRenderType", config.CATEGORY_GENERAL, 3, 1, 3, "1,2 or 3 for different rendering of fluids in the Backpack GUI"); - BONUS_CHEST_ALLOWED = config.getBoolean("BonusBackpack", config.CATEGORY_GENERAL, false, "Include a Standard Adventure Backpack in bonus chest?"); - PIGMAN_ALLOWED = config.getBoolean("PigmanBackpacks", config.CATEGORY_GENERAL, false, "Allow generation of Pigman Backpacks in dungeon loot and villager trades"); - ALLOW_COPTER_SOUND = config.getBoolean("CopterPackSound", config.CATEGORY_GENERAL, true, "Allow playing the CopterPack sound (Client Only, other players may hear it)"); - BACKPACK_ABILITIES = config.getBoolean("BackpackAbilities", config.CATEGORY_GENERAL, true, "Allow the backpacks to execute their special abilities, or be only cosmetic (Doesn't affect lightning transformation) Must be " + + // Gameplay + allowSoulBound = config.getBoolean("Allow SoulBound", "gameplay", true, "Allow SoulBound enchant on wearable packs"); + backpackAbilities = config.getBoolean("Backpack Abilities", "gameplay", true, "Allow the backpacks to execute their special abilities, or be only cosmetic (Doesn't affect lightning transformation) Must be " + "disabled in both Client and Server to work properly"); - STATUS_OVERLAY = config.getBoolean("StatusOverlay", config.CATEGORY_GENERAL,true, "Show player status effects on screen?"); - TANKS_OVERLAY = config.getBoolean("BackpackOverlay", config.CATEGORY_GENERAL,true, "Show the different wearable overlays on screen?"); - HOVERING_TEXT_TANKS = config.getBoolean("HoveringText", config.CATEGORY_GENERAL,false, "Show hovering text on fluid tanks?"); - FIX_LEAD = config.getBoolean("FixVanillaLead", config.CATEGORY_GENERAL,true, "Fix the vanilla Lead? (Checks mobs falling on a leash to not die of fall damage if they're not falling so fast)"); - BACKPACK_DEATH_PLACE = config.getBoolean("BackpackDeathPlace", config.CATEGORY_GENERAL,true,"Place backpacks as a block when you die?"); - //RECIPES - SADDLE_RECIPE = config.getBoolean("SaddleRecipe", config.CATEGORY_GENERAL,true, "Add recipe for saddle?"); + backpackDeathPlace = config.getBoolean("Backpack Death Place", "gameplay", true, "Place backpacks as a block when you die?"); + fixLead = config.getBoolean("Fix Vanilla Lead", "gameplay", true, "Fix the vanilla Lead? (Checks mobs falling on a leash to not die of fall damage if they're not falling so fast)"); + enableCampfireSpawn = config.getBoolean("Enable Campfire Spawn", "gameplay", false, "Enable/Disable ability to spawn at campfire"); + enableHoseDrink = config.getBoolean("Enable Hose Drink", "gameplay", true, "Enable/Disable hose drink mode"); + enableToolsCycling = config.getBoolean("Enable Tools Cycling", "gameplay", true, "Enable/Disable tool cycling"); + portableSleepingBag = config.getBoolean("Portable Sleeping Bag", "gameplay", true, "Allows to use sleeping bag directly from wearing backpacks. Sleep by one touch"); + tinkerToolsMaintenance = config.getBoolean("Maintenance Tinker Tools", "gameplay", true, "Allows to maintenance (repair/upgarde) Tinkers Construct tools in backpacks as if it's Crafting Station"); + + // Graphics + typeTankRender = config.getInt("Tank Render Type", "graphics", 3, 1, 3, "1,2 or 3 for different rendering of fluids in the Backpack GUI"); + enableFullnessBar = config.getBoolean("Enable Fullness Bar", "graphics", false, "Enable durability bar showing fullness of backpacks inventory"); + enableTemperatureBar = config.getBoolean("Enable Temperature Bar", "graphics", false, "Enable durability bar showing temperature of jetpack"); + enableToolsRender = config.getBoolean("Enable Tools Render", "graphics", true, "Enable rendering for tools in the backpack tool slots"); + tanksHoveringText = config.getBoolean("Hovering Text", "graphics", false, "Show hovering text on fluid tanks?"); + + // Graphics.Status + statusOverlay = config.getBoolean("Enable Overlay", "graphics.status", true, "Show player status effects on screen?"); + statusOverlayLeft = config.getBoolean("Stick To Left", "graphics.status", true, "Stick to left? Icons will appears from left to right. If false: stick to right, icons will appears from right to left"); + statusOverlayTop = config.getBoolean("Stick To Top", "graphics.status", true, "Stick to top?"); + statusOverlayIndentH = config.getInt("Indent Horizontal", "graphics.status", 2, 0, 1000, "Horizontal indent from the window border"); + statusOverlayIndentV = config.getInt("Indent Vertical", "graphics.status", 2, 0, 500, "Vertical indent from the window border"); + statusOverlayThaumcraft = config.getBoolean("Respect Thaumcraft", "graphics.status", true, "Take into account Thaumcraft wands GUI and do not overlap it"); + + // Graphics.Tanks + tanksOverlay = config.getBoolean("Enable Overlay", "graphics.tanks", true, "Show the different wearable overlays on screen?"); + tanksOverlayRight = config.getBoolean("Stick To Right", "graphics.tanks", true, "Stick to right?"); + tanksOverlayBottom = config.getBoolean("Stick To Bottom", "graphics.tanks", true, "Stick to bottom?"); + tanksOverlayIndentH = config.getInt("Indent Horizontal", "graphics.tanks", 2, 0, 1000, "Horizontal indent from the window border"); + tanksOverlayIndentV = config.getInt("Indent Vertical", "graphics.tanks", 1, 0, 500, "Vertical indent from the window border"); + + // Sound + allowSoundCopter = config.getBoolean("Copter Pack", "sound", true, "Allow playing the CopterPack sound (Client Only, other players may hear it)"); + allowSoundJetpack = config.getBoolean("Coal Jetpack", "sound", true, "Allow playing the CoalJetpack sound (Client Only, other players may hear it)"); + allowSoundPiston = config.getBoolean("Piston Boots", "sound", true, "Allow playing the PistonBoots sound"); + + // Items + enableItemFilters = config.getBoolean("Enable Item Filters", "items", true, "Enable filters from Disallow category"); + forbiddenDimensions = config.getStringList("Forbidden Dimensions", "items", nameDefault, "Disallow opening backpack inventory for specific dimension ID"); + copterFuels = config.getStringList("Valid Copter Fuels", "items", defaultFuels, "List of valid fuels for Copter. Consumption rate range: 0.05 ~ 20.0. Format: 'fluid, rate', ex.: 'water, 0.0'"); + + // Items.Disallowed + nameLocalized = config.getStringList("By Displayed Name", "items.disallowed", nameDefault, "Disallow items by displayed (localized) name. Not case sensitive. Worst option, use only when there is no choice. Example: Dirt"); + nameInternalID = config.getStringList("By Internal ID", "items.disallowed", nameDefault, "Disallow items by internal ID. Case sensitive. Example: minecraft:dirt"); + nameInternalIDs = config.getStringList("By Internal IDs", "items.disallowed", nameDefault, "Disallow items by internal ID. Case sensitive. Will be disallowed all items containing that word in their IDs. Use with caution. Example: minecraft:di"); + nameUnlocalized = config.getStringList("By Internal Name", "items.disallowed", nameDefault, "Disallow items by internal (unlocalized) name. Not case sensitive. Example: tile.dirt"); + + // Items.Recipes + consumeDragonEgg = config.getBoolean("Consume Dragon Egg", "items.recipes", false, "Consume Dragon Egg when Dragon backpack crafted?"); + recipeAdventuresSet = config.getBoolean("Adventures Set", "items.recipes", true, "Enable/Disable recipe for Adventure's Hat, Suit and Pants"); + recipeInflatableBoat = config.getBoolean("Inflatable Boat", "items.recipes", true, "Enable/Disable recipe for Inflatable Boat"); + recipeInflatableBoatM = config.getBoolean("Inflatable Boat Motorized", "items.recipes", false, "Enable/Disable recipe for Inflatable Boat (motorized). For aesthetic only, not fully implemented (yet?)"); + recipeClockCrossbow = config.getBoolean("Clockwork Crossbow", "items.recipes", true, "Enable/Disable Clockwork Crossbow recipe"); + recipeCopterPack = config.getBoolean("Copter Pack", "items.recipes", true, "Enable/Disable CopterPack recipe"); + recipeCoalJetpack = config.getBoolean("Coal Jetpack", "items.recipes", true, "Enable/Disable CoalJetpack recipe"); + recipePitonBoots = config.getBoolean("Piston Boots", "items.recipes", true, "Enable/Disable PistonBoots recipe"); + recipeSaddle = config.getBoolean("Saddle", "items.recipes", true, "Add recipe for saddle?"); + recipeMachete = config.getBoolean("Machete", "items.recipes", true, "Enable/Disable Machete recipe"); + + // Items.Settings + pistonBootsAutoStep = config.getBoolean("Piston Boots Auto Step", "items.settings", true, "Allow Piston Boots auto step blocks"); + pistonBootsJumpHeight = config.getInt("Piston Boots Jump Height", "items.settings", 3, 1, 8, "Piston Boots jump height in blocks"); + pistonBootsSprintBoost = config.getInt("Piston Boots Sprint", "items.settings", 1, 0, 4, "Piston Boots sprint boost. 0 - disable"); + dragonBackpackRegen = config.getInt("Dragon Regeneration", "items.settings", 1, 0, 4, "Dragon Backpack regeneration level. 0 - disable"); + dragonBackpackDamage = config.getInt("Dragon Damage Boost", "items.settings", 2, 0, 4, "Dragon Backpack damage boost. 0 - disable"); + rainbowBackpackSpeed = config.getInt("Rainbow Speed", "items.settings", 1, 0, 4, "Rainbow Backpack speed boost. 0 - disable"); + rainbowBackpackSSpeed = config.getInt("Rainbow Special Speed", "items.settings", 3, 0, 4, "Rainbow Backpack special speed. 0 - disable"); + rainbowBackpackSJump = config.getInt("Rainbow Special Jump", "items.settings", 1, 0, 4, "Rainbow Backpack special jump. 0 - disable"); + + // WorldGen + allowBatGen = config.getBoolean("Bat Backpacks", "worldgen", true, "Allow generation of Bat Backpacks in dungeon and mineshaft loot. It cannot be obtained by crafting"); + allowBonusGen = config.getBoolean("Bonus Backpack", "worldgen", false, "Include a Standard Adventure Backpack in bonus chest?"); + allowGolemGen = config.getBoolean("IronGolem Backpacks", "worldgen", true, "Allow generation of IronGolem Backpacks in village blacksmith loot. It cannot be obtained by crafting"); + allowPigmanGen = config.getBoolean("Pigman Backpacks", "worldgen", false, "Allow generation of Pigman Backpacks in dungeon loot and villager trades"); + + // Experimental + bossBarIndent = config.getInt("Boss Bar Indent", "experimental", 0, 0, 500, "Boss health bar indent from top border, 0 = standard Forge render"); + if (config.hasChanged()) { config.save(); @@ -83,5 +197,4 @@ public void onConfigChangeEvent(ConfigChangedEvent.OnConfigChangedEvent event) } } - -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/config/GeneralConfig.java b/src/main/java/com/darkona/adventurebackpack/config/GeneralConfig.java deleted file mode 100644 index 4d86a968..00000000 --- a/src/main/java/com/darkona/adventurebackpack/config/GeneralConfig.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.darkona.adventurebackpack.config; - -/** - * Created by Darkona on 12/10/2014. - */ -public class GeneralConfig -{ - - - public static final String GUI_TANK_KEY = "Tank_GUI_Resolution"; - public static final String GUI_TANK_COMMENT = "Resolution can take values of 1,2,4,8 or 16, other values will bork your game. The higher the value the smaller the fluids will look in your GUI"; -} - diff --git a/src/main/java/com/darkona/adventurebackpack/config/Keybindings.java b/src/main/java/com/darkona/adventurebackpack/config/Keybindings.java index a8af9db1..f856cf6e 100644 --- a/src/main/java/com/darkona/adventurebackpack/config/Keybindings.java +++ b/src/main/java/com/darkona/adventurebackpack/config/Keybindings.java @@ -1,9 +1,10 @@ package com.darkona.adventurebackpack.config; -import com.darkona.adventurebackpack.reference.Names; -import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; +import net.minecraft.client.settings.GameSettings; +import net.minecraft.client.settings.KeyBinding; + /** * Created on 14/10/2014 * @@ -11,9 +12,20 @@ */ public class Keybindings { - public static KeyBinding openBackpack = new KeyBinding(Names.keys.OPEN_BACKPACK_INVENTORY, Keyboard.KEY_B, Names.keys.CATEGORY); - public static KeyBinding toggleHose = new KeyBinding(Names.keys.TOGGLE_HOSE_TANK, Keyboard.KEY_N, Names.keys.CATEGORY); -// public static KeyBinding jumpKey = -} + private static final String KEYS_CATEGORY = "keys.adventureBackpack.category"; + private static final String OPEN_INVENTORY = "keys.adventureBackpack.openInventory"; + private static final String TOGGLE_ACTIONS = "keys.adventureBackpack.toggleActions"; + + public static KeyBinding openInventory = new KeyBinding(OPEN_INVENTORY, Keyboard.KEY_B, KEYS_CATEGORY); + public static KeyBinding toggleActions = new KeyBinding(TOGGLE_ACTIONS, Keyboard.KEY_N, KEYS_CATEGORY); + public static String getInventoryKeyName() + { + return GameSettings.getKeyDisplayString(openInventory.getKeyCode()); + } + public static String getActionKeyName() + { + return GameSettings.getKeyDisplayString(toggleActions.getKeyCode()); + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/config/ManualConfigHandler.java b/src/main/java/com/darkona/adventurebackpack/config/ManualConfigHandler.java deleted file mode 100644 index 43530cc6..00000000 --- a/src/main/java/com/darkona/adventurebackpack/config/ManualConfigHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.darkona.adventurebackpack.config; - -import net.minecraftforge.common.config.Configuration; - -import java.io.File; - -/** - * Created on 04/01/2015 - * - * @author Darkona - */ -public class ManualConfigHandler -{ - - public static Configuration config; - - public static void init(File configFile) - { - if (config == null) - { - config = new Configuration(configFile); - loadConfiguration(); - } - } - - private static void loadConfiguration() - { - - if (config.hasChanged()) - { - config.save(); - } - } - -} diff --git a/src/main/java/com/darkona/adventurebackpack/entity/EntityBolt.java b/src/main/java/com/darkona/adventurebackpack/entity/EntityBolt.java index 2679a751..1b1beef3 100644 --- a/src/main/java/com/darkona/adventurebackpack/entity/EntityBolt.java +++ b/src/main/java/com/darkona/adventurebackpack/entity/EntityBolt.java @@ -25,8 +25,6 @@ protected void entityInit() /** * (abstract) Protected helper method to read subclass entity data from NBT. - * - * @param compound */ @Override protected void readEntityFromNBT(NBTTagCompound compound) @@ -36,8 +34,6 @@ protected void readEntityFromNBT(NBTTagCompound compound) /** * (abstract) Protected helper method to write subclass entity data to NBT. - * - * @param compound */ @Override protected void writeEntityToNBT(NBTTagCompound compound) @@ -47,12 +43,6 @@ protected void writeEntityToNBT(NBTTagCompound compound) /** * Similar to setArrowHeading, it's point the throwable entity to a x, y, z direction. - * - * @param x - * @param y - * @param z - * @param speedMultiplier - * @param whatever */ @Override public void setThrowableHeading(double x, double y, double z, float speedMultiplier, float whatever) diff --git a/src/main/java/com/darkona/adventurebackpack/entity/EntityCrossbowProjectile.java b/src/main/java/com/darkona/adventurebackpack/entity/EntityCrossbowProjectile.java index 38ac208a..0c91f721 100644 --- a/src/main/java/com/darkona/adventurebackpack/entity/EntityCrossbowProjectile.java +++ b/src/main/java/com/darkona/adventurebackpack/entity/EntityCrossbowProjectile.java @@ -25,8 +25,6 @@ protected void entityInit() /** * (abstract) Protected helper method to read subclass entity data from NBT. - * - * @param p_70037_1_ */ @Override protected void readEntityFromNBT(NBTTagCompound p_70037_1_) @@ -36,8 +34,6 @@ protected void readEntityFromNBT(NBTTagCompound p_70037_1_) /** * (abstract) Protected helper method to write subclass entity data to NBT. - * - * @param p_70014_1_ */ @Override protected void writeEntityToNBT(NBTTagCompound p_70014_1_) @@ -47,12 +43,6 @@ protected void writeEntityToNBT(NBTTagCompound p_70014_1_) /** * Similar to setArrowHeading, it's point the throwable entity to a x, y, z direction. - * - * @param p_70186_1_ - * @param p_70186_3_ - * @param p_70186_5_ - * @param p_70186_7_ - * @param p_70186_8_ */ @Override public void setThrowableHeading(double p_70186_1_, double p_70186_3_, double p_70186_5_, float p_70186_7_, float p_70186_8_) diff --git a/src/main/java/com/darkona/adventurebackpack/entity/EntityFriendlySpider.java b/src/main/java/com/darkona/adventurebackpack/entity/EntityFriendlySpider.java index ca460a52..3da598b2 100644 --- a/src/main/java/com/darkona/adventurebackpack/entity/EntityFriendlySpider.java +++ b/src/main/java/com/darkona/adventurebackpack/entity/EntityFriendlySpider.java @@ -1,9 +1,19 @@ package com.darkona.adventurebackpack.entity; -import com.darkona.adventurebackpack.util.Wearing; +import java.util.Random; + import net.minecraft.block.Block; -import net.minecraft.entity.*; -import net.minecraft.entity.ai.*; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityCreature; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.EnumCreatureAttribute; +import net.minecraft.entity.IEntityLivingData; +import net.minecraft.entity.SharedMonsterAttributes; +import net.minecraft.entity.ai.EntityAIControlledByPlayer; +import net.minecraft.entity.ai.EntityAILookIdle; +import net.minecraft.entity.ai.EntityAISwimming; +import net.minecraft.entity.ai.EntityAIWander; +import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; @@ -14,7 +24,8 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; -import java.util.Random; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 11/01/2015 @@ -23,7 +34,6 @@ */ public class EntityFriendlySpider extends EntityCreature { - private float prevRearingAmount; private int jumpTicks; private EntityPlayer owner; @@ -31,9 +41,10 @@ public class EntityFriendlySpider extends EntityCreature private final EntityAIControlledByPlayer aiControlledByPlayer; @Override - protected void entityInit() { + protected void entityInit() + { super.entityInit(); - this.dataWatcher.addObject(16, (byte)0); + this.dataWatcher.addObject(16, (byte) 0); } @Override @@ -45,7 +56,8 @@ protected void applyEntityAttributes() this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(40.0D); } - public EntityFriendlySpider(World world) { + public EntityFriendlySpider(World world) + { super(world); this.setSize(1.4F, 0.9F); this.tasks.addTask(0, new EntityAISwimming(this)); @@ -54,37 +66,31 @@ public EntityFriendlySpider(World world) { this.tasks.addTask(7, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); this.tasks.addTask(8, new EntityAILookIdle(this)); } + @Override protected boolean isAIEnabled() { return true; } + @Override public int getTalkInterval() { return 300; } - /** - * Returns the sound this mob makes while it's alive. - */ + @Override protected String getLivingSound() { return "mob.spider.say"; } - /** - * Returns the sound this mob makes when it is hurt. - */ @Override protected String getHurtSound() { return "mob.spider.say"; } - /** - * Returns the sound this mob makes on death. - */ @Override protected String getDeathSound() { @@ -140,19 +146,12 @@ else if (super.attackEntityFrom(damageSource, amount)) } } - /** - * Takes a coordinate in and returns a weight to determine how likely this creature will try to path to the block. - * Args: x, y, z - */ @Override public float getBlockPathWeight(int p_70783_1_, int p_70783_2_, int p_70783_3_) { return 0.5F - this.worldObj.getLightBrightness(p_70783_1_, p_70783_2_, p_70783_3_); } - /** - * Checks if the entity's current position is a valid location to spawn this entity. - */ @Override public boolean getCanSpawnHere() { @@ -164,30 +163,19 @@ protected boolean func_146066_aG() { return true; } - /** - * Returns the item that this EntityLiving is holding, if any. - */ + @Override public ItemStack getHeldItem() { return null; } - /** - * 0: Tool in Hand; 1-4: Armor - * */ @Override public ItemStack getEquipmentInSlot(int slot) { return null; } - /** - * Sets the held item, or an armor slot. Slot 0 is held item. Slot 1-4 is armor. Params: Item, slot - * - * @param slot - * @param stack - */ @Override public void setCurrentItemOrArmor(int slot, ItemStack stack) { @@ -201,21 +189,23 @@ public ItemStack[] getLastActiveItems() } @Override - public boolean canRiderInteract() { + public boolean canRiderInteract() + { return false; } @Override - protected boolean interact(EntityPlayer player) { - + protected boolean interact(EntityPlayer player) + { try { - if (!this.worldObj.isRemote && Wearing.isWearingTheRightBackpack(player, "Spider")) + if (!this.worldObj.isRemote && Wearing.isWearingTheRightBackpack(player, BackpackTypes.SPIDER)) { player.mountEntity(this); return true; } - } catch (Exception oops) + } + catch (Exception oops) { return false; } @@ -223,35 +213,42 @@ protected boolean interact(EntityPlayer player) { } @Override - public boolean canBeSteered() { + public boolean canBeSteered() + { return true; } @Override - protected Entity findPlayerToAttack() { + protected Entity findPlayerToAttack() + { if (this.riddenByEntity != null) return null; + float f = this.getBrightness(1.0F); if (f < 0.5F) { double d0 = 16.0D; return this.worldObj.getClosestVulnerablePlayerToEntity(this, d0); - } else + } + else { return null; } } @Override - public boolean canBeCollidedWith() { + public boolean canBeCollidedWith() + { return !isDead; } @Override - public boolean shouldRiderFaceForward(EntityPlayer player) { + public boolean shouldRiderFaceForward(EntityPlayer player) + { return true; } + public boolean isBesideClimbableBlock() { return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; @@ -267,7 +264,7 @@ public void setBesideClimbableBlock(boolean p_70839_1_) if (p_70839_1_) { - b0 = (byte)(b0 | 1); + b0 = (byte) (b0 | 1); } else { @@ -278,7 +275,8 @@ public void setBesideClimbableBlock(boolean p_70839_1_) } @Override - public void onUpdate() { + public void onUpdate() + { super.onUpdate(); if (this.worldObj.isRemote && this.dataWatcher.hasChanges()) { @@ -298,7 +296,8 @@ public void onUpdate() { } } - private void normalLivingUpdateWithNoAI(){ + private void normalLivingUpdateWithNoAI() + { if (this.jumpTicks > 0) { --this.jumpTicks; @@ -306,12 +305,12 @@ private void normalLivingUpdateWithNoAI(){ if (this.newPosRotationIncrements > 0) { - double d0 = this.posX + (this.newPosX - this.posX) / (double)this.newPosRotationIncrements; - double d1 = this.posY + (this.newPosY - this.posY) / (double)this.newPosRotationIncrements; - double d2 = this.posZ + (this.newPosZ - this.posZ) / (double)this.newPosRotationIncrements; + double d0 = this.posX + (this.newPosX - this.posX) / (double) this.newPosRotationIncrements; + double d1 = this.posY + (this.newPosY - this.posY) / (double) this.newPosRotationIncrements; + double d2 = this.posZ + (this.newPosZ - this.posZ) / (double) this.newPosRotationIncrements; double d3 = MathHelper.wrapAngleTo180_double(this.newRotationYaw - (double) this.rotationYaw); - this.rotationYaw = (float)((double)this.rotationYaw + d3 / (double)this.newPosRotationIncrements); - this.rotationPitch = (float)((double)this.rotationPitch + (this.newRotationPitch - (double)this.rotationPitch) / (double)this.newPosRotationIncrements); + this.rotationYaw = (float) ((double) this.rotationYaw + d3 / (double) this.newPosRotationIncrements); + this.rotationPitch = (float) ((double) this.rotationPitch + (this.newRotationPitch - (double) this.rotationPitch) / (double) this.newPosRotationIncrements); --this.newPosRotationIncrements; this.setPosition(d0, d1, d2); this.setRotation(this.rotationYaw, this.rotationPitch); @@ -393,11 +392,13 @@ else if (this.isClientWorld()) } @Override - public void onLivingUpdate() { + public void onLivingUpdate() + { if (this.riddenByEntity != null) { normalLivingUpdateWithNoAI(); - } else + } + else { super.onLivingUpdate(); } @@ -405,20 +406,22 @@ public void onLivingUpdate() { } @Override - public double getMountedYOffset() { + public double getMountedYOffset() + { return super.getMountedYOffset(); } @Override - public void moveEntityWithHeading(float strafe, float forward) { + public void moveEntityWithHeading(float strafe, float forward) + { if (this.riddenByEntity != null) { this.prevRotationYaw = this.rotationYaw = this.riddenByEntity.rotationYaw; this.rotationPitch = this.riddenByEntity.rotationPitch * 0.5F; this.setRotation(this.rotationYaw, this.rotationPitch); this.rotationYawHead = this.renderYawOffset = this.rotationYaw; - strafe = ((EntityLivingBase)this.riddenByEntity).moveStrafing * 0.5F; - forward = ((EntityLivingBase)this.riddenByEntity).moveForward; + strafe = ((EntityLivingBase) this.riddenByEntity).moveStrafing * 0.5F; + forward = ((EntityLivingBase) this.riddenByEntity).moveForward; if (forward <= 0.0F) { @@ -429,7 +432,7 @@ public void moveEntityWithHeading(float strafe, float forward) { if (!this.worldObj.isRemote) { - this.setAIMoveSpeed((float)this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue()); + this.setAIMoveSpeed((float) this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue()); super.moveEntityWithHeading(strafe, forward); } @@ -455,27 +458,28 @@ public void moveEntityWithHeading(float strafe, float forward) { } @Override - public void updateRiderPosition() { + public void updateRiderPosition() + { super.updateRiderPosition(); - if (this.prevRearingAmount > 0.0F) - { - float f = MathHelper.sin(this.renderYawOffset * (float) Math.PI / 180.0F); - float f1 = MathHelper.cos(this.renderYawOffset * (float) Math.PI / 180.0F); - float f2 = 0.7F * this.prevRearingAmount; - float f3 = 0.15F * this.prevRearingAmount; - this.riddenByEntity.setPosition(this.posX + (f2 * f), this.posY + this.getMountedYOffset() + this.riddenByEntity.getYOffset() - + f3, this.posZ - (f2 * f1)); + if (this.prevRearingAmount > 0.0F) + { + float f = MathHelper.sin(this.renderYawOffset * (float) Math.PI / 180.0F); + float f1 = MathHelper.cos(this.renderYawOffset * (float) Math.PI / 180.0F); + float f2 = 0.7F * this.prevRearingAmount; + float f3 = 0.15F * this.prevRearingAmount; + this.riddenByEntity.setPosition(this.posX + (f2 * f), this.posY + this.getMountedYOffset() + this.riddenByEntity.getYOffset() + + f3, this.posZ - (f2 * f1)); - if (this.riddenByEntity instanceof EntityLivingBase) - { - ((EntityLivingBase) this.riddenByEntity).renderYawOffset = this.renderYawOffset; - } - } + if (this.riddenByEntity instanceof EntityLivingBase) + { + ((EntityLivingBase) this.riddenByEntity).renderYawOffset = this.renderYawOffset; + } + } } - public void spiderJump() + public void spiderJump() //TODO { this.getJumpHelper().setJumping(); //this.getJumpHelper().doJump(); @@ -509,9 +513,6 @@ else if (i <= 4) } } - /** - * Basic mob attack. Default to touch of death in EntityCreature. Overridden by each mob to define their attack. - */ @Override protected void attackEntity(Entity p_70785_1_, float p_70785_2_) { @@ -530,8 +531,8 @@ protected void attackEntity(Entity p_70785_1_, float p_70785_2_) double d0 = p_70785_1_.posX - this.posX; double d1 = p_70785_1_.posZ - this.posZ; float f2 = MathHelper.sqrt_double(d0 * d0 + d1 * d1); - this.motionX = d0 / (double)f2 * 0.5D * 0.800000011920929D + this.motionX * 0.20000000298023224D; - this.motionZ = d1 / (double)f2 * 0.5D * 0.800000011920929D + this.motionZ * 0.20000000298023224D; + this.motionX = d0 / (double) f2 * 0.5D * 0.800000011920929D + this.motionX * 0.20000000298023224D; + this.motionZ = d1 / (double) f2 * 0.5D * 0.800000011920929D + this.motionZ * 0.20000000298023224D; this.motionY = 0.4000000059604645D; } } @@ -548,10 +549,6 @@ protected Item getDropItem() return Items.string; } - /** - * Drop 0-2 items of this living's type. @param par1 - Whether this entity has recently been hit by a player. @param - * par2 - Level of Looting used to kill this mob. - */ @Override protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) { @@ -563,24 +560,18 @@ protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) } } - /** - * returns true if this entity is by a ladder, false otherwise - */ @Override public boolean isOnLadder() { return this.isBesideClimbableBlock(); } - /** - * Sets the Entity inside a web block. - */ @Override - public void setInWeb() {} + public void setInWeb() + { + + } - /** - * Get this Entity's EnumCreatureAttribute - */ @Override public EnumCreatureAttribute getCreatureAttribute() { diff --git a/src/main/java/com/darkona/adventurebackpack/entity/EntityInflatableBoat.java b/src/main/java/com/darkona/adventurebackpack/entity/EntityInflatableBoat.java index f0a7e1b7..4dda1d95 100644 --- a/src/main/java/com/darkona/adventurebackpack/entity/EntityInflatableBoat.java +++ b/src/main/java/com/darkona/adventurebackpack/entity/EntityInflatableBoat.java @@ -1,9 +1,9 @@ package com.darkona.adventurebackpack.entity; -import com.darkona.adventurebackpack.init.ModItems; -import com.darkona.adventurebackpack.inventory.IInventoryTanks; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; + +import io.netty.buffer.ByteBuf; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; @@ -20,15 +20,18 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidTank; +import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; -import java.util.List; +import com.darkona.adventurebackpack.init.ModItems; /** * Created on 05/01/2015 * * @author Darkona */ -public class EntityInflatableBoat extends EntityBoat implements IInventoryTanks +public class EntityInflatableBoat extends EntityBoat implements /*IInventoryTanks, */IEntityAdditionalSpawnData { private FluidTank fuelTank; private boolean isBoatEmpty; @@ -48,13 +51,15 @@ public class EntityInflatableBoat extends EntityBoat implements IInventoryTanks private boolean inflated = false; public float inflation = 0.25f; + private boolean motorized; + + // boat is in EARLY ALPHA stage + public boolean isMotorized() { return motorized; } - private boolean motorized; - public EntityInflatableBoat(World world) { super(world); @@ -72,13 +77,12 @@ public boolean isInflated() return inflated; } - /** - * Called to update the entity's position/logic. - */ @Override public void onUpdate() { - if(!inflated) + this.onEntityUpdate(); + + if (!inflated) { inflation += 0.025; if (inflation >= 1.0f) @@ -86,7 +90,9 @@ public void onUpdate() inflation = 1; inflated = true; } - }else{ + } + else + { inflation = 1; } @@ -140,7 +146,8 @@ public void onUpdate() d8 = this.posX - d2 * d5 * 0.8D + d4 * d6; d9 = this.posZ - d4 * d5 * 0.8D - d2 * d6; this.worldObj.spawnParticle("splash", d8, this.posY - 0.125D, d9, this.motionX, this.motionY, this.motionZ); - } else + } + else { d8 = this.posX + d2 + d4 * d5 * 0.7D; d9 = this.posZ + d4 - d2 * d5 * 0.7D; @@ -165,7 +172,8 @@ public void onUpdate() --this.boatPosRotationIncrements; this.setPosition(d2, d4, d11); this.setRotation(this.rotationYaw, this.rotationPitch); - } else + } + else { d2 = this.posX + this.motionX; d4 = this.posY + this.motionY; @@ -183,13 +191,15 @@ public void onUpdate() this.motionY *= 0.949999988079071D; this.motionZ *= 0.9900000095367432D; } - } else + } + else { if (d0 < 1.0D) { d2 = d0 * 2.0D - 1.0D; this.motionY += 0.03999999910593033D * d2; - } else + } + else { if (this.motionY < 0.0D) { @@ -225,7 +235,8 @@ public void onUpdate() { this.speedMultiplier = 0.35D; } - } else + } + else { this.speedMultiplier -= (this.speedMultiplier - 0.07D) / 35.0D; @@ -251,7 +262,8 @@ public void onUpdate() { this.worldObj.setBlockToAir(i1, k, j); this.isCollidedHorizontally = false; - } else if (block == Blocks.waterlily) + } + else if (block == Blocks.waterlily) { this.worldObj.func_147480_a(i1, k, j, true); this.isCollidedHorizontally = false; @@ -268,7 +280,7 @@ public void onUpdate() this.moveEntity(this.motionX, this.motionY, this.motionZ); - /* if (this.isCollidedHorizontally && d10 > 0.2D) + /* if (this.isCollidedHorizontally && d10 > 0.2D) { if (!this.worldObj.isRemote && !this.isDead) { @@ -348,7 +360,8 @@ public boolean attackEntityFrom(DamageSource damageSource, float damage) if (this.isEntityInvulnerable()) { return false; - } else if (!this.worldObj.isRemote && !this.isDead) + } + else if (!this.worldObj.isRemote && !this.isDead) { this.setForwardDirection(-this.getForwardDirection()); this.setTimeSinceHit(10); @@ -365,14 +378,15 @@ public boolean attackEntityFrom(DamageSource damageSource, float damage) if (!flag) { - this.entityDropItem(new ItemStack(ModItems.component, 1, motorized ? 8:7), 0.0f); + this.entityDropItem(new ItemStack(ModItems.component, 1, motorized ? 8 : 7), 0.0f); } this.setDead(); } return true; - } else + } + else { return true; } @@ -387,7 +401,7 @@ public EntityItem func_145778_a(Item item, int quantity, float someFloat) @Override public boolean interactFirst(EntityPlayer p_130002_1_) { - if(inflation < 1.0f) return false; + if (inflation < 1.0f) return false; if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityPlayer && this.riddenByEntity != p_130002_1_) { return true; @@ -403,11 +417,6 @@ public boolean interactFirst(EntityPlayer p_130002_1_) } } - /** - * Save the entity to NBT (calls an abstract helper method to write extra data) - * - * @param compound - */ @Override public void writeToNBT(NBTTagCompound compound) { @@ -415,11 +424,6 @@ public void writeToNBT(NBTTagCompound compound) writeEntityToNBT(compound); } - /** - * Reads the entity from NBT (calls an abstract helper method to read specialized data) - * - * @param compound - */ @Override public void readFromNBT(NBTTagCompound compound) { @@ -428,19 +432,21 @@ public void readFromNBT(NBTTagCompound compound) } @Override - protected void writeEntityToNBT(NBTTagCompound compound) { - compound.setFloat("Inflation",inflation); - compound.setBoolean("Motorized",motorized); - compound.setBoolean("Inflated",inflated); + protected void writeEntityToNBT(NBTTagCompound compound) + { + compound.setFloat("Inflation", inflation); + compound.setBoolean("Motorized", motorized); + compound.setBoolean("Inflated", inflated); } @Override - protected void readEntityFromNBT(NBTTagCompound compound) { + protected void readEntityFromNBT(NBTTagCompound compound) + { if (compound.hasKey("Inflation")) { inflation = compound.getFloat("Inflation"); } - if(compound.hasKey("Motorized")) + if (compound.hasKey("Motorized")) { motorized = compound.getBoolean("Motorized"); } @@ -456,179 +462,14 @@ public void setMotorized(boolean motorized) } @Override - public boolean updateTankSlots() - { - return false; - } - - @Override - public void loadFromNBT(NBTTagCompound compound) - { - - } - - @Override - public void saveToNBT(NBTTagCompound compound) - { - - } - - @Override - public FluidTank[] getTanksArray() - { - return new FluidTank[0]; - } - - @Override - public void dirtyInventory() + public void writeSpawnData(ByteBuf data) { - - } - - @Override - public void dirtyTanks() - { - - } - - @Override - public void setInventorySlotContentsNoSave(int slot, ItemStack stack) - { - - } - - @Override - public ItemStack decrStackSizeNoSave(int slot, int amount) - { - return null; - } - - /** - * Returns the number of slots in the inventory. - */ - @Override - public int getSizeInventory() - { - return 0; - } - - /** - * Returns the stack in slot i - * - * @param p_70301_1_ - */ - @Override - public ItemStack getStackInSlot(int p_70301_1_) - { - return null; - } - - /** - * Removes from an inventory slot (first arg) up to a specified number (second arg) of items and returns them in a - * new stack. - * - * @param p_70298_1_ - * @param p_70298_2_ - */ - @Override - public ItemStack decrStackSize(int p_70298_1_, int p_70298_2_) - { - return null; - } - - /** - * When some containers are closed they call this on each slot, then drop whatever it returns as an EntityItem - - * like when you close a workbench GUI. - * - * @param p_70304_1_ - */ - @Override - public ItemStack getStackInSlotOnClosing(int p_70304_1_) - { - return null; - } - - /** - * Sets the given item stack to the specified slot in the inventory (can be crafting or armor sections). - * - * @param p_70299_1_ - * @param p_70299_2_ - */ - @Override - public void setInventorySlotContents(int p_70299_1_, ItemStack p_70299_2_) - { - - } - - /** - * Returns the name of the inventory - */ - @Override - public String getInventoryName() - { - return null; - } - - /** - * Returns if the inventory is named - */ - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - /** - * Returns the maximum stack size for a inventory slot. - */ - @Override - public int getInventoryStackLimit() - { - return 0; - } - - /** - * For tile entities, ensures the chunk containing the tile entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - @Override - public void markDirty() - { - - } - - /** - * Do not make give this method the name canInteractWith because it clashes with Container - * - * @param p_70300_1_ - */ - @Override - public boolean isUseableByPlayer(EntityPlayer p_70300_1_) - { - return false; - } - - @Override - public void openInventory() - { - - } - - @Override - public void closeInventory() - { - + data.writeBoolean(this.motorized); } - /** - * Returns true if automation is allowed to insert the given stack (ignoring stack size) into the given slot. - * - * @param p_94041_1_ - * @param p_94041_2_ - */ @Override - public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_) + public void readSpawnData(ByteBuf data) { - return false; + this.motorized = data.readBoolean(); } } diff --git a/src/main/java/com/darkona/adventurebackpack/entity/ai/AvoidEntitySelector.java b/src/main/java/com/darkona/adventurebackpack/entity/ai/AvoidEntitySelector.java index 5c066815..86e5c4d9 100644 --- a/src/main/java/com/darkona/adventurebackpack/entity/ai/AvoidEntitySelector.java +++ b/src/main/java/com/darkona/adventurebackpack/entity/ai/AvoidEntitySelector.java @@ -5,8 +5,6 @@ public class AvoidEntitySelector implements IEntitySelector { - - final EntityAIAvoidPlayerWithBackpack entityAvoiderAI; AvoidEntitySelector(EntityAIAvoidPlayerWithBackpack par1EntityAIAvoidEntity) @@ -14,13 +12,9 @@ public class AvoidEntitySelector implements IEntitySelector this.entityAvoiderAI = par1EntityAIAvoidEntity; } - - /** - * Return whether the specified com.darkona.adventurebackpack.entity is applicable to this filter. - */ + @Override public boolean isEntityApplicable(Entity par1Entity) { return par1Entity.isEntityAlive() && EntityAIAvoidPlayerWithBackpack.func_98217_a(this.entityAvoiderAI).getEntitySenses().canSee(par1Entity); } - } diff --git a/src/main/java/com/darkona/adventurebackpack/entity/ai/EntityAIAvoidPlayerWithBackpack.java b/src/main/java/com/darkona/adventurebackpack/entity/ai/EntityAIAvoidPlayerWithBackpack.java index b8fdd997..f4752534 100644 --- a/src/main/java/com/darkona/adventurebackpack/entity/ai/EntityAIAvoidPlayerWithBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/entity/ai/EntityAIAvoidPlayerWithBackpack.java @@ -1,7 +1,7 @@ package com.darkona.adventurebackpack.entity.ai; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.util.Wearing; +import java.util.List; + import net.minecraft.command.IEntitySelector; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; @@ -13,14 +13,15 @@ import net.minecraft.pathfinding.PathNavigate; import net.minecraft.util.Vec3; -import java.util.List; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.Wearing; /** * Created by Darkona on 12/10/2014. */ public class EntityAIAvoidPlayerWithBackpack extends EntityAIBase { - private String backpackName; + private BackpackTypes type; public final IEntitySelector field_98218_a = new AvoidEntitySelector(this); @@ -48,7 +49,7 @@ public class EntityAIAvoidPlayerWithBackpack extends EntityAIBase */ private Class targetEntityClass; - public EntityAIAvoidPlayerWithBackpack(EntityCreature par1EntityCreature, Class par2Class, float par3, double par4, double par6, String colorName) + public EntityAIAvoidPlayerWithBackpack(EntityCreature par1EntityCreature, Class par2Class, float par3, double par4, double par6, BackpackTypes type) { this.theEntity = par1EntityCreature; this.targetEntityClass = par2Class; @@ -57,12 +58,10 @@ public EntityAIAvoidPlayerWithBackpack(EntityCreature par1EntityCreature, Class this.nearSpeed = par6; this.entityPathNavigate = par1EntityCreature.getNavigator(); this.setMutexBits(1); - this.backpackName = colorName; + this.type = type; } - /** - * Returns whether the EntityAIBase should begin execution. - */ + @Override public boolean shouldExecute() { if (this.targetEntityClass == EntityPlayer.class) @@ -81,7 +80,7 @@ public boolean shouldExecute() for (Object player : list) { - if (BackpackNames.getBackpackColorName(Wearing.getWearingBackpack((EntityPlayer) player)).equals(backpackName)) + if (BackpackTypes.getType(Wearing.getWearingBackpack((EntityPlayer) player)) == type) { this.closestLivingEntity = (Entity) player; } @@ -92,16 +91,17 @@ public boolean shouldExecute() return false; } - Vec3 vec3 = RandomPositionGenerator.findRandomTargetBlockAwayFrom(this.theEntity, 16, 7, Vec3.createVectorHelper(this.closestLivingEntity.posX, this.closestLivingEntity.posY, this.closestLivingEntity.posZ)); if (vec3 == null) { return false; - } else if (this.closestLivingEntity.getDistanceSq(vec3.xCoord, vec3.yCoord, vec3.zCoord) < this.closestLivingEntity.getDistanceSqToEntity(this.theEntity)) + } + else if (this.closestLivingEntity.getDistanceSq(vec3.xCoord, vec3.yCoord, vec3.zCoord) < this.closestLivingEntity.getDistanceSqToEntity(this.theEntity)) { return false; - } else + } + else { this.entityPathEntity = this.entityPathNavigate.getPathToXYZ(vec3.xCoord, vec3.yCoord, vec3.zCoord); return this.entityPathEntity != null && this.entityPathEntity.isDestinationSame(vec3); @@ -110,39 +110,32 @@ public boolean shouldExecute() return false; } - /** - * Returns whether an in-progress EntityAIBase should continue executing - */ + @Override public boolean continueExecuting() { return !this.entityPathNavigate.noPath(); } - /** - * Execute a one shot task or start executing a continuous task - */ + @Override public void startExecuting() { this.entityPathNavigate.setPath(this.entityPathEntity, this.farSpeed); } - /** - * Resets the task - */ + @Override public void resetTask() { this.closestLivingEntity = null; } - /** - * Updates the task - */ + @Override public void updateTask() { if (this.theEntity.getDistanceSqToEntity(this.closestLivingEntity) < 49.0D) { this.theEntity.getNavigator().setSpeed(this.nearSpeed); - } else + } + else { this.theEntity.getNavigator().setSpeed(this.farSpeed); } diff --git a/src/main/java/com/darkona/adventurebackpack/entity/ai/EntityAIHorseFollowOwner.java b/src/main/java/com/darkona/adventurebackpack/entity/ai/EntityAIHorseFollowOwner.java index b794ed00..29b98b63 100644 --- a/src/main/java/com/darkona/adventurebackpack/entity/ai/EntityAIHorseFollowOwner.java +++ b/src/main/java/com/darkona/adventurebackpack/entity/ai/EntityAIHorseFollowOwner.java @@ -1,13 +1,15 @@ package com.darkona.adventurebackpack.entity.ai; -import com.darkona.adventurebackpack.util.Wearing; +import java.util.UUID; + import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.pathfinding.PathNavigate; import net.minecraft.world.World; -import java.util.UUID; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 09/01/2015 @@ -16,91 +18,92 @@ */ public class EntityAIHorseFollowOwner extends EntityAIBase { - private EntityHorse theHorse; - private EntityPlayer theOwner; - World theWorld; - private double speed; - private PathNavigate petPathfinder; - private int tickCounter; - float maxDist; - float minDist; - private boolean avoidWater; - private static final String __OBFID = "CL_00001585"; - - public EntityAIHorseFollowOwner(EntityHorse horse, double speed, float minDist, float maxDist) + private EntityHorse theHorse; + private EntityPlayer theOwner; + World theWorld; + private double speed; + private PathNavigate petPathfinder; + private int tickCounter; + float maxDist; + float minDist; + private boolean avoidWater; + private static final String __OBFID = "CL_00001585"; + + public EntityAIHorseFollowOwner(EntityHorse horse, double speed, float minDist, float maxDist) + { + theHorse = horse; + theWorld = horse.worldObj; + theOwner = theWorld.func_152378_a(UUID.fromString(theHorse.func_152119_ch())); + this.speed = speed * 2; + petPathfinder = horse.getNavigator(); + this.minDist = minDist; + this.maxDist = maxDist; + } + + public double getDistanceSquaredToOwner() + { + double relX = theHorse.posX - theOwner.posX; + double relY = theHorse.posY - theOwner.posY; + double relZ = theHorse.posZ - theOwner.posZ; + return relX * relX + relY * relY + relZ * relZ; + } + + @Override + public boolean shouldExecute() + { + if (!theHorse.isTame() || theHorse.getLeashed() || !theHorse.hasCustomNameTag()) return false; + if (theOwner == null) { - theHorse = horse; - theWorld = horse.worldObj; theOwner = theWorld.func_152378_a(UUID.fromString(theHorse.func_152119_ch())); - this.speed = speed * 2; - petPathfinder = horse.getNavigator(); - this.minDist = minDist; - this.maxDist = maxDist; - } - - - public double getDistanceSquaredToOwner() - { - double relX = theHorse.posX - theOwner.posX; - double relY = theHorse.posY - theOwner.posY; - double relZ = theHorse.posZ - theOwner.posZ; - return relX * relX + relY * relY + relZ * relZ; - } - - - - public boolean shouldExecute() - { - if(!theHorse.isTame() || theHorse.getLeashed() || !theHorse.hasCustomNameTag())return false; - if (theOwner == null) { - theOwner = theWorld.func_152378_a(UUID.fromString(theHorse.func_152119_ch())); - if (theOwner == null) - { - return false; - } - } - if(!Wearing.isWearingTheRightBackpack(theOwner, "Horse"))return false; - if (theHorse.getDistanceSqToEntity(theOwner) < minDist * minDist * 20) { + if (theOwner == null) + { return false; } - return true; } - - public boolean continueExecuting() + if (!Wearing.isWearingTheRightBackpack(theOwner, BackpackTypes.HORSE)) return false; + if (theHorse.getDistanceSqToEntity(theOwner) < minDist * minDist * 20) { - return (Wearing.isWearingTheRightBackpack(theOwner,"Horse") && !this.petPathfinder.noPath() && theHorse.getDistanceSqToEntity(theOwner) > this.maxDist * this.maxDist * 2); + return false; } - - public void startExecuting() + return true; + } + + @Override + public boolean continueExecuting() + { + return (Wearing.isWearingTheRightBackpack(theOwner, BackpackTypes.HORSE) && !this.petPathfinder.noPath() && theHorse.getDistanceSqToEntity(theOwner) > this.maxDist * this.maxDist * 2); + } + + @Override + public void startExecuting() + { + tickCounter = 0; + avoidWater = this.theHorse.getNavigator().getAvoidsWater(); + petPathfinder = theHorse.getNavigator(); + } + + @Override + public void resetTask() + { + theOwner = null; + petPathfinder.clearPathEntity(); + theHorse.getNavigator().setAvoidsWater(this.avoidWater); + } + + @Override + public void updateTask() + { + //theHorse.getLookHelper().setLookPositionWithEntity(theOwner, 10.0F, this.theHorse.getVerticalFaceSpeed()); + if (--tickCounter <= 0) { - tickCounter = 0; - avoidWater = this.theHorse.getNavigator().getAvoidsWater(); - petPathfinder = theHorse.getNavigator(); - } - - public void resetTask() - { - theOwner = null; - petPathfinder.clearPathEntity(); - theHorse.getNavigator().setAvoidsWater(this.avoidWater); - } - - - public void updateTask() - { - //theHorse.getLookHelper().setLookPositionWithEntity(theOwner, 10.0F, this.theHorse.getVerticalFaceSpeed()); - if (--tickCounter <= 0) + tickCounter = 10; + if (!theHorse.getLeashed()) { - tickCounter = 10; - if (!theHorse.getLeashed()) + if (!petPathfinder.tryMoveToEntityLiving(theOwner, speed)) { - if (!petPathfinder.tryMoveToEntityLiving(theOwner, speed)) - { - return; - } + return; } } } - - + } } diff --git a/src/main/java/com/darkona/adventurebackpack/entity/fx/SteamFX.java b/src/main/java/com/darkona/adventurebackpack/entity/fx/SteamFX.java index cab49e21..7fd2fd12 100644 --- a/src/main/java/com/darkona/adventurebackpack/entity/fx/SteamFX.java +++ b/src/main/java/com/darkona/adventurebackpack/entity/fx/SteamFX.java @@ -1,10 +1,10 @@ package com.darkona.adventurebackpack.entity.fx; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.particle.EntityFX; import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.World; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; /** * Created on 19/01/2015 @@ -13,8 +13,7 @@ */ @SideOnly(Side.CLIENT) -public class SteamFX - extends EntityFX +public class SteamFX extends EntityFX { private float smokeParticleScale; @@ -43,6 +42,7 @@ public SteamFX(World world, double x, double y, double z, double velX, double ve this.noClip = true; } + @Override public void renderParticle(Tessellator par1Tessellator, float par2, float par3, float par4, float par5, float par6, float par7) { float age = (this.particleAge + par2) / this.particleMaxAge * 32.0F; @@ -58,6 +58,7 @@ public void renderParticle(Tessellator par1Tessellator, float par2, float par3, super.renderParticle(par1Tessellator, par2, par3, par4, par5, par6, par7); } + @Override public void onUpdate() { this.prevPosX = this.posX; diff --git a/src/main/java/com/darkona/adventurebackpack/events/WearableEvent.java b/src/main/java/com/darkona/adventurebackpack/events/WearableEvent.java index c16b3670..e6ce434b 100644 --- a/src/main/java/com/darkona/adventurebackpack/events/WearableEvent.java +++ b/src/main/java/com/darkona/adventurebackpack/events/WearableEvent.java @@ -11,7 +11,6 @@ */ public class WearableEvent extends PlayerEvent { - public final ItemStack wearable; public WearableEvent(EntityPlayer player, ItemStack wearable) @@ -35,5 +34,4 @@ public EquipWearableEvent(EntityPlayer player, ItemStack wearable) super(player, wearable); } } - } diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/FluidEffectRegistry.java b/src/main/java/com/darkona/adventurebackpack/fluids/FluidEffectRegistry.java index 02834e54..acb70830 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/FluidEffectRegistry.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/FluidEffectRegistry.java @@ -1,17 +1,22 @@ package com.darkona.adventurebackpack.fluids; -import adventurebackpack.api.FluidEffect; -import com.darkona.adventurebackpack.fluids.effects.*; -import com.darkona.adventurebackpack.util.LogHelper; +import java.util.ArrayList; +import java.util.Map; + import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableMap; + import net.minecraft.entity.Entity; import net.minecraft.world.World; import net.minecraftforge.fluids.Fluid; -import java.util.ArrayList; -import java.util.Map; +import com.darkona.adventurebackpack.fluids.effects.LavaEffect; +import com.darkona.adventurebackpack.fluids.effects.MelonJuiceEffect; +import com.darkona.adventurebackpack.fluids.effects.MilkEffect; +import com.darkona.adventurebackpack.fluids.effects.MushroomStewEffect; +import com.darkona.adventurebackpack.util.LogHelper; +import adventurebackpack.api.FluidEffect; /** * Created on 12/10/2014 @@ -22,7 +27,6 @@ public class FluidEffectRegistry { static BiMap EFFECT_REGISTRY = HashBiMap.create(); - public static FluidEffect WATER_EFFECT; public static FluidEffect LAVA_EFFECT; public static FluidEffect MILK_EFFECT; public static FluidEffect MELON_EFFECT; @@ -33,17 +37,12 @@ public class FluidEffectRegistry public static void init() { EFFECT_REGISTRY.clear(); - WATER_EFFECT = new WaterEffect(); LAVA_EFFECT = new LavaEffect(); MILK_EFFECT = new MilkEffect(); MELON_EFFECT = new MelonJuiceEffect(); SOUP_EFFECT = new MushroomStewEffect(); } - /** - * @param effect - * @return - */ public static int registerFluidEffect(FluidEffect effect) { String className = effect.getClass().getName(); diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/FluidMelonJuice.java b/src/main/java/com/darkona/adventurebackpack/fluids/FluidMelonJuice.java index 3805c3ab..77602a04 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/FluidMelonJuice.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/FluidMelonJuice.java @@ -1,17 +1,17 @@ package com.darkona.adventurebackpack.fluids; -import com.darkona.adventurebackpack.client.Icons; import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; +import com.darkona.adventurebackpack.client.Icons; + /** * Created by Darkona on 12/10/2014. */ public class FluidMelonJuice extends Fluid { - public FluidMelonJuice() { super("melonJuice"); diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/FluidMilk.java b/src/main/java/com/darkona/adventurebackpack/fluids/FluidMilk.java index ca06b4cd..a21fb15c 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/FluidMilk.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/FluidMilk.java @@ -1,19 +1,20 @@ package com.darkona.adventurebackpack.fluids; -import com.darkona.adventurebackpack.client.Icons; import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; +import com.darkona.adventurebackpack.client.Icons; + /** * Created on 12/10/2014. + * * @author Javier Darkona */ public class FluidMilk extends Fluid { - public FluidMilk() { super("milk"); @@ -22,7 +23,6 @@ public FluidMilk() setLuminosity(0); } - @Override public IIcon getStillIcon() { @@ -52,6 +52,4 @@ public boolean isGaseous(World world, int x, int y, int z) { return false; } - - } \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/FluidMushroomStew.java b/src/main/java/com/darkona/adventurebackpack/fluids/FluidMushroomStew.java index ebbcec88..238c734a 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/FluidMushroomStew.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/FluidMushroomStew.java @@ -1,11 +1,12 @@ package com.darkona.adventurebackpack.fluids; -import com.darkona.adventurebackpack.client.Icons; import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; +import com.darkona.adventurebackpack.client.Icons; + /** * Created on 11/01/2015 * diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/TankWrapper.java b/src/main/java/com/darkona/adventurebackpack/fluids/TankWrapper.java index fc1f472f..543b9497 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/TankWrapper.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/TankWrapper.java @@ -35,5 +35,4 @@ public boolean isEmpty() { return this.fluid == null || (this.getFluidAmount() == this.capacity); } - } diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/effects/FuelEffect.java b/src/main/java/com/darkona/adventurebackpack/fluids/effects/FuelEffect.java index bef8dab5..56f2cd1e 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/effects/FuelEffect.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/effects/FuelEffect.java @@ -1,7 +1,5 @@ package com.darkona.adventurebackpack.fluids.effects; -import adventurebackpack.api.FluidEffect; -import com.darkona.adventurebackpack.util.Utils; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; @@ -9,30 +7,22 @@ import net.minecraft.world.World; import net.minecraftforge.fluids.FluidRegistry; +import com.darkona.adventurebackpack.util.Utils; +import adventurebackpack.api.FluidEffect; + /** * Created on 12/10/2014 * * @author Darkona */ - public class FuelEffect extends FluidEffect { - public FuelEffect() { super(FluidRegistry.getFluid("fuel"), 20); } - /** - * This method determines what will happen to the player when drinking the - * corresponding fluid. For example set potion effects, set player on fire, - * heal, fill hunger, etc. You can use the world parameter to make - * conditions based on where the player is. - * - * @param world The World. - * @param player The Player. - */ @Override public void affectDrinker(World world, Entity entity) { diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/effects/LavaEffect.java b/src/main/java/com/darkona/adventurebackpack/fluids/effects/LavaEffect.java index 704cf129..a11f0f0c 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/effects/LavaEffect.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/effects/LavaEffect.java @@ -1,6 +1,5 @@ package com.darkona.adventurebackpack.fluids.effects; -import adventurebackpack.api.FluidEffect; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; @@ -8,6 +7,8 @@ import net.minecraft.world.World; import net.minecraftforge.fluids.FluidRegistry; +import adventurebackpack.api.FluidEffect; + /** * Created by Darkona on 12/10/2014. */ @@ -30,5 +31,4 @@ public void affectDrinker(World world, Entity entity) player.addPotionEffect(new PotionEffect(Potion.digSlowdown.id, timeInSeconds * 20 * 6, 3, false)); } } - } diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/effects/MelonJuiceEffect.java b/src/main/java/com/darkona/adventurebackpack/fluids/effects/MelonJuiceEffect.java index 362e848a..1998784b 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/effects/MelonJuiceEffect.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/effects/MelonJuiceEffect.java @@ -1,34 +1,25 @@ package com.darkona.adventurebackpack.fluids.effects; -import adventurebackpack.api.FluidEffect; -import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; -import com.darkona.adventurebackpack.init.ModFluids; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; +import com.darkona.adventurebackpack.init.ModFluids; +import com.darkona.adventurebackpack.util.Utils; +import adventurebackpack.api.FluidEffect; + /** * Created by Darkona on 12/10/2014. */ public class MelonJuiceEffect extends FluidEffect { - public MelonJuiceEffect() { super(ModFluids.melonJuice, 30); } - /** - * This method determines what will happen to the player when drinking the - * corresponding fluid. For example set potion effects, set player on fire, - * heal, fill hunger, etc. You can use the world parameter to make - * conditions based on where the player is. - * - * @param world The World. - * @param player The Player. - */ @Override public void affectDrinker(World world, Entity entity) { @@ -36,7 +27,7 @@ public void affectDrinker(World world, Entity entity) { EntityPlayer player = (EntityPlayer) entity; player.addPotionEffect(new PotionEffect(Potion.digSpeed.getId(), timeInTicks, 0)); - FluidEffectRegistry.WATER_EFFECT.affectDrinker(world, player); + player.addPotionEffect(new PotionEffect(Potion.regeneration.id, Utils.secondsToTicks(timeInSeconds), 0)); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/effects/MilkEffect.java b/src/main/java/com/darkona/adventurebackpack/fluids/effects/MilkEffect.java index 36f0e860..326ac25e 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/effects/MilkEffect.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/effects/MilkEffect.java @@ -1,11 +1,12 @@ package com.darkona.adventurebackpack.fluids.effects; -import adventurebackpack.api.FluidEffect; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidRegistry; +import adventurebackpack.api.FluidEffect; + /** * Created on 12/10/2014. * diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/effects/MushroomStewEffect.java b/src/main/java/com/darkona/adventurebackpack/fluids/effects/MushroomStewEffect.java index 088b9086..62be71b9 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/effects/MushroomStewEffect.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/effects/MushroomStewEffect.java @@ -1,12 +1,12 @@ package com.darkona.adventurebackpack.fluids.effects; -import adventurebackpack.api.FluidEffect; -import com.darkona.adventurebackpack.init.ModFluids; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidRegistry; +import adventurebackpack.api.FluidEffect; + /** * Created on 11/01/2015 * @@ -18,12 +18,13 @@ public MushroomStewEffect() { super(FluidRegistry.getFluid("mushroomstew")); } + @Override public void affectDrinker(World world, Entity entity) { - if(entity instanceof EntityPlayer) + if (entity instanceof EntityPlayer) { - ((EntityPlayer)entity).getFoodStats().addStats(6,0.6F); + ((EntityPlayer) entity).getFoodStats().addStats(6, 0.6F); } } } diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/effects/OilEffect.java b/src/main/java/com/darkona/adventurebackpack/fluids/effects/OilEffect.java index 76c9f508..fb56a454 100644 --- a/src/main/java/com/darkona/adventurebackpack/fluids/effects/OilEffect.java +++ b/src/main/java/com/darkona/adventurebackpack/fluids/effects/OilEffect.java @@ -1,6 +1,5 @@ package com.darkona.adventurebackpack.fluids.effects; -import adventurebackpack.api.FluidEffect; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; @@ -8,6 +7,8 @@ import net.minecraft.world.World; import net.minecraftforge.fluids.FluidRegistry; +import adventurebackpack.api.FluidEffect; + /** * Created by Darkona on 12/10/2014. */ @@ -18,15 +19,6 @@ public OilEffect() super(FluidRegistry.getFluid("oil"), 20); } - /** - * This method determines what will happen to the player when drinking the - * corresponding fluid. For example set potion effects, set player on fire, - * heal, fill hunger, etc. You can use the world parameter to make - * conditions based on where the player is. - * - * @param world The World. - * @param entity The Player. - */ @Override public void affectDrinker(World world, Entity entity) { diff --git a/src/main/java/com/darkona/adventurebackpack/fluids/effects/WaterEffect.java b/src/main/java/com/darkona/adventurebackpack/fluids/effects/WaterEffect.java deleted file mode 100644 index 2f38135e..00000000 --- a/src/main/java/com/darkona/adventurebackpack/fluids/effects/WaterEffect.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.darkona.adventurebackpack.fluids.effects; - -import adventurebackpack.api.FluidEffect; -import com.darkona.adventurebackpack.util.Utils; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.potion.Potion; -import net.minecraft.potion.PotionEffect; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; -import net.minecraftforge.common.BiomeDictionary; -import net.minecraftforge.fluids.FluidRegistry; - -/** - * Created on 12/10/2014. - * - * @author Javier Darkona - */ -public class WaterEffect extends FluidEffect -{ - - public WaterEffect() - { - super(FluidRegistry.WATER, 7); - } - - @Override - public void affectDrinker(World world, Entity entity) - { - if (entity instanceof EntityPlayer) - { - EntityPlayer player = (EntityPlayer) entity; - BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(player.serverPosX, player.serverPosZ); - - //If it's hot - if ( - BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.HOT) || - BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.DRY) || - BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.SANDY) || - BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.WASTELAND) || - BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.NETHER) - ) - { - // player.getFoodStats().addStats(1, 0.1f); - if (player.isBurning()) - { - player.extinguish(); - }else { - player.addPotionEffect(new PotionEffect(Potion.regeneration.id, Utils.secondsToTicks(timeInSeconds), 0)); - } - } - - } - } -} diff --git a/src/main/java/com/darkona/adventurebackpack/handlers/ClientEventHandler.java b/src/main/java/com/darkona/adventurebackpack/handlers/ClientEventHandler.java index fc74438e..5043a4b0 100644 --- a/src/main/java/com/darkona/adventurebackpack/handlers/ClientEventHandler.java +++ b/src/main/java/com/darkona/adventurebackpack/handlers/ClientEventHandler.java @@ -1,27 +1,23 @@ package com.darkona.adventurebackpack.handlers; -import com.darkona.adventurebackpack.common.Constants; -import com.darkona.adventurebackpack.common.ServerActions; -import com.darkona.adventurebackpack.init.ModNetwork; -import com.darkona.adventurebackpack.inventory.SlotTool; -import com.darkona.adventurebackpack.item.ItemAdventureBackpack; -import com.darkona.adventurebackpack.item.ItemHose; -import com.darkona.adventurebackpack.network.CycleToolPacket; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.client.event.MouseEvent; -import net.minecraftforge.event.entity.player.ItemTooltipEvent; -import net.minecraftforge.fluids.FluidTank; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import com.darkona.adventurebackpack.common.ServerActions; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.init.ModItems; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.inventory.SlotTool; +import com.darkona.adventurebackpack.network.CycleToolPacket; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 17/10/2014 @@ -30,83 +26,35 @@ */ public class ClientEventHandler { - /** - * Makes the tool tips of the backpacks have the Tank information displayed below. - */ - @SubscribeEvent - @SideOnly(Side.CLIENT) - public void toolTips(ItemTooltipEvent event) - { - if (event.itemStack.getItem() instanceof ItemAdventureBackpack) - { - NBTTagCompound compound = event.itemStack.stackTagCompound; - FluidTank tank = new FluidTank(Constants.basicTankCapacity); - String tankInfo = ""; - if (compound != null) - { - if (compound.hasKey("leftTank")) - { - tank.readFromNBT(compound.getCompoundTag("leftTank")); - String name = tank.getFluid() == null ? "" : tank.getFluid().getLocalizedName(); - tankInfo = EnumChatFormatting.BLUE + "Left Tank: " + tank.getFluidAmount() + "/" + tank.getCapacity() + " " + name; - - event.toolTip.add(tankInfo); - } - if (compound.hasKey("rightTank")) - { - tank.readFromNBT(compound.getCompoundTag("rightTank")); - String name = tank.getFluid() == null ? "" : tank.getFluid().getLocalizedName(); - tankInfo = EnumChatFormatting.RED + "Right Tank: " + tank.getFluidAmount() + "/" + tank.getCapacity() + " " + name; - - event.toolTip.add(tankInfo); - } - } - } - } - - /** - * @param event - */ @SubscribeEvent @SideOnly(Side.CLIENT) public void mouseWheelDetect(MouseEvent event) { /*Special thanks go to MachineMuse, both for inspiration and the event. God bless you girl.*/ - Minecraft mc = Minecraft.getMinecraft(); - int dWheel = event.dwheel; - if (dWheel != 0) - { - //LogHelper.debug("Mouse Wheel moving"); - EntityClientPlayerMP player = mc.thePlayer; - if (player != null && !player.isDead && player.isSneaking()) - { - ItemStack backpack = Wearing.getWearingBackpack(player); - if (backpack != null && backpack.getItem() instanceof ItemAdventureBackpack) - { - if (player.getCurrentEquippedItem() != null) - { - int slot = player.inventory.currentItem; - ItemStack heldItem = player.inventory.getStackInSlot(slot); - Item theItem = heldItem.getItem(); + EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; + if (event.dwheel == 0 || player == null || player.isDead || !player.isSneaking()) + return; + + ItemStack backpack = Wearing.getWearingBackpack(player); + ItemStack heldItem = player.getCurrentEquippedItem(); + if (backpack == null || heldItem == null) + return; - if (SlotTool.isValidTool(heldItem) || - (BackpackNames.getBackpackColorName(backpack).equals("Skeleton") && theItem.equals(Items.bow))) - { - ModNetwork.net.sendToServer(new CycleToolPacket.CycleToolMessage(dWheel, slot, CycleToolPacket.CYCLE_TOOL_ACTION)); - ServerActions.cycleTool(player, dWheel, slot); - event.setCanceled(true); - } + boolean isWheelUp = event.dwheel > 0; + Item theItem = heldItem.getItem(); - if (theItem instanceof ItemHose) - { - ModNetwork.net.sendToServer(new CycleToolPacket.CycleToolMessage(dWheel, slot, CycleToolPacket.SWITCH_HOSE_ACTION)); - ServerActions.switchHose(player, ServerActions.HOSE_SWITCH, dWheel, slot); - event.setCanceled(true); - } - } - } - } + if (ConfigHandler.enableToolsCycling && !Wearing.getWearingBackpackInv(player).getDisableCycling() && SlotTool.isValidTool(heldItem) + || BackpackTypes.getType(backpack) == BackpackTypes.SKELETON && theItem.equals(Items.bow)) //TODO add bow case to server + { + ModNetwork.net.sendToServer(new CycleToolPacket.CycleToolMessage(isWheelUp, CycleToolPacket.CYCLE_TOOL_ACTION)); + ServerActions.cycleTool(player, isWheelUp); + event.setCanceled(true); + } + else if (theItem == ModItems.hose) + { + ModNetwork.net.sendToServer(new CycleToolPacket.CycleToolMessage(isWheelUp, CycleToolPacket.SWITCH_HOSE_ACTION)); + ServerActions.switchHose(player, isWheelUp, ServerActions.HOSE_SWITCH); + event.setCanceled(true); } } - -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/handlers/GeneralEventHandler.java b/src/main/java/com/darkona/adventurebackpack/handlers/GeneralEventHandler.java index 9b7c5af7..46e5c672 100644 --- a/src/main/java/com/darkona/adventurebackpack/handlers/GeneralEventHandler.java +++ b/src/main/java/com/darkona/adventurebackpack/handlers/GeneralEventHandler.java @@ -1,36 +1,33 @@ package com.darkona.adventurebackpack.handlers; -import com.darkona.adventurebackpack.common.ServerActions; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.entity.ai.EntityAIHorseFollowOwner; -import com.darkona.adventurebackpack.events.WearableEvent; -import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; -import com.darkona.adventurebackpack.init.ModNetwork; -import com.darkona.adventurebackpack.inventory.InventoryBackpack; -import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Utils; -import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import java.util.UUID; + import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAITasks; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; -import net.minecraft.item.Item; import net.minecraft.item.ItemAppleGold; -import net.minecraft.item.ItemGlassBottle; import net.minecraft.item.ItemPotion; import net.minecraft.util.ChatComponentText; -import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.EntityStruckByLightningEvent; import net.minecraftforge.event.entity.player.ArrowLooseEvent; import net.minecraftforge.event.entity.player.ArrowNockEvent; import net.minecraftforge.event.entity.player.PlayerUseItemEvent; import net.minecraftforge.fluids.FluidRegistry; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import java.util.UUID; +import com.darkona.adventurebackpack.common.ServerActions; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.entity.ai.EntityAIHorseFollowOwner; +import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.inventory.InventoryBackpack; +import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.Utils; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 17/10/2014 @@ -39,42 +36,31 @@ */ public class GeneralEventHandler { - /** - * @param event - */ @SubscribeEvent public void eatGoldenApple(PlayerUseItemEvent.Finish event) { EntityPlayer player = event.entityPlayer; - if (ConfigHandler.BACKPACK_ABILITIES) + + if (ConfigHandler.backpackAbilities) { - if (event.item.getItem() instanceof ItemAppleGold && - //((ItemAppleGold) event.item.getItem()).getRarity(event.item) == EnumRarity.epic && - Wearing.isWearingTheRightBackpack(player, "Rainbow")) + if (event.item.getItem() instanceof ItemAppleGold + //&& ((ItemAppleGold) event.item.getItem()).getRarity(event.item) == EnumRarity.epic + && Wearing.isWearingTheRightBackpack(player, BackpackTypes.RAINBOW)) { - InventoryBackpack inv = new InventoryBackpack(Wearing.getWearingBackpack(player)); if (inv.getLastTime() > 0) return; inv.setLastTime(Utils.secondsToTicks(150)); inv.dirtyTime(); if (!player.worldObj.isRemote) { - String nyanString = - EnumChatFormatting.RED + "N" + - EnumChatFormatting.GOLD + "Y" + - EnumChatFormatting.YELLOW + "A" + - EnumChatFormatting.GREEN + "N" + - EnumChatFormatting.AQUA + "C" + - EnumChatFormatting.BLUE + "A" + - EnumChatFormatting.DARK_PURPLE + "T"; + String nyanString = Utils.makeItRainbow("NYANCAT"); player.addChatComponentMessage(new ChatComponentText(nyanString)); ModNetwork.sendToNearby(new EntitySoundPacket.Message(EntitySoundPacket.NYAN_SOUND, player), player); } } } - if (event.item.getItem() instanceof ItemPotion - && (event.item.getItem()).getDamage(event.item) == 0) + if (event.item.getItem() instanceof ItemPotion && (event.item.getItem()).getDamage(event.item) == 0) { if (!player.worldObj.isRemote) { @@ -86,8 +72,10 @@ public void eatGoldenApple(PlayerUseItemEvent.Finish event) @SubscribeEvent public void detectBow(ArrowNockEvent event) { - if (!ConfigHandler.BACKPACK_ABILITIES) return; - if (Wearing.isWearingTheRightBackpack(event.entityPlayer, "Skeleton")) + if (!ConfigHandler.backpackAbilities) + return; + + if (Wearing.isWearingTheRightBackpack(event.entityPlayer, BackpackTypes.SKELETON)) { InventoryBackpack backpack = new InventoryBackpack(Wearing.getWearingBackpack(event.entityPlayer)); if (backpack.hasItem(Items.arrow)) @@ -101,8 +89,10 @@ public void detectBow(ArrowNockEvent event) @SubscribeEvent public void detectArrow(ArrowLooseEvent event) { - if (!ConfigHandler.BACKPACK_ABILITIES) return; - if (Wearing.isWearingTheRightBackpack(event.entityPlayer, "Skeleton")) + if (!ConfigHandler.backpackAbilities) + return; + + if (Wearing.isWearingTheRightBackpack(event.entityPlayer, BackpackTypes.SKELETON)) { InventoryBackpack backpack = new InventoryBackpack(Wearing.getWearingBackpack(event.entityPlayer)); if (backpack.hasItem(Items.arrow)) @@ -113,13 +103,10 @@ public void detectArrow(ArrowLooseEvent event) } } - /** - * @param event - */ @SubscribeEvent public void detectLightning(EntityStruckByLightningEvent event) { - if (event.entity != null && event.entity instanceof EntityPlayer) + if (event.entity instanceof EntityPlayer) { ServerActions.electrify((EntityPlayer) event.entity); } @@ -128,45 +115,47 @@ public void detectLightning(EntityStruckByLightningEvent event) @SubscribeEvent public void makeHorsesFollowOwner(EntityJoinWorldEvent event) { - if(!ConfigHandler.BACKPACK_ABILITIES)return; - if(event.entity instanceof EntityHorse && ((EntityHorse)event.entity).isTame()) + if (!ConfigHandler.backpackAbilities) return; + if (event.entity instanceof EntityHorse) { - - EntityHorse horse = ((EntityHorse)event.entity); - if(!horse.isDead && horse.hasCustomNameTag()) + EntityHorse horse = ((EntityHorse) event.entity); + if (!horse.isDead && horse.isTame() && horse.hasCustomNameTag()) { - boolean set = true; - if(horse.worldObj.func_152378_a(UUID.fromString(horse.func_152119_ch())) != null) + String ownerUUIDstring = horse.func_152119_ch(); + if (ownerUUIDstring != null && !ownerUUIDstring.isEmpty()) { - for (Object entry : horse.tasks.taskEntries) + boolean set = true; + if (horse.worldObj.func_152378_a(UUID.fromString(ownerUUIDstring)) != null) { - if (((EntityAITasks.EntityAITaskEntry) entry).action instanceof EntityAIHorseFollowOwner) + for (Object entry : horse.tasks.taskEntries) { - set = false; + if (((EntityAITasks.EntityAITaskEntry) entry).action instanceof EntityAIHorseFollowOwner) + { + set = false; + } } } - } - if(set) - { - horse.tasks.addTask(4, new EntityAIHorseFollowOwner(horse, 1.5d, 2.0f, 20.0f)); - - if (horse.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.followRange) != null) + if (set) { - horse.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.followRange).setBaseValue(100.0D); + horse.tasks.addTask(4, new EntityAIHorseFollowOwner(horse, 1.5d, 2.0f, 20.0f)); + + if (horse.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.followRange) != null) + { + horse.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.followRange).setBaseValue(100.0D); + } } } } } } - @SubscribeEvent + /*@SubscribeEvent public void backpackUnequipped(WearableEvent.UnequipWearableEvent event) { + }*/ - } - - /* @SubscribeEvent + /*@SubscribeEvent public void listFluids(FluidRegistry.FluidRegisterEvent event) { LogHelper.info("Registered fluid " + event.fluidName + " with id " + event.fluidID); diff --git a/src/main/java/com/darkona/adventurebackpack/handlers/GuiHandler.java b/src/main/java/com/darkona/adventurebackpack/handlers/GuiHandler.java index 9750abe4..f7a5a5e8 100644 --- a/src/main/java/com/darkona/adventurebackpack/handlers/GuiHandler.java +++ b/src/main/java/com/darkona/adventurebackpack/handlers/GuiHandler.java @@ -1,14 +1,21 @@ package com.darkona.adventurebackpack.handlers; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; +import cpw.mods.fml.common.network.IGuiHandler; + import com.darkona.adventurebackpack.block.TileAdventureBackpack; import com.darkona.adventurebackpack.client.gui.GuiAdvBackpack; +import com.darkona.adventurebackpack.client.gui.GuiCoalJetpack; import com.darkona.adventurebackpack.client.gui.GuiCopterPack; -import com.darkona.adventurebackpack.client.gui.GuiSteamJetpack; -import com.darkona.adventurebackpack.inventory.*; +import com.darkona.adventurebackpack.common.Constants.Source; +import com.darkona.adventurebackpack.inventory.ContainerBackpack; +import com.darkona.adventurebackpack.inventory.ContainerCopter; +import com.darkona.adventurebackpack.inventory.ContainerJetpack; +import com.darkona.adventurebackpack.inventory.InventoryBackpack; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; +import com.darkona.adventurebackpack.inventory.InventoryCopterPack; import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.common.network.IGuiHandler; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; /** * Created on 12/10/2014 @@ -21,13 +28,13 @@ public class GuiHandler implements IGuiHandler public static final byte JETPACK_HOLDING = 5; public static final byte COPTER_WEARING = 4; public static final byte COPTER_HOLDING = 3; - public static final byte BACKPACK_HOLDING = 2; - public static final byte BACKPACK_WEARING = 1; + public static final byte BACKPACK_WEARING = 2; + public static final byte BACKPACK_HOLDING = 1; public static final byte BACKPACK_TILE = 0; - public GuiHandler() { + } @Override @@ -38,43 +45,43 @@ public Object getServerGuiElement(int ID, EntityPlayer player, World world, int case BACKPACK_TILE: if (world.getTileEntity(x, y, z) != null && world.getTileEntity(x, y, z) instanceof TileAdventureBackpack) { - return new ContainerBackpack(player, (TileAdventureBackpack) world.getTileEntity(x, y, z), ContainerBackpack.SOURCE_TILE); + return new ContainerBackpack(player, (TileAdventureBackpack) world.getTileEntity(x, y, z), Source.TILE); } break; - case BACKPACK_WEARING: - if (Wearing.isWearingBackpack(player)) + case BACKPACK_HOLDING: + if (Wearing.isHoldingBackpack(player)) { - return new ContainerBackpack(player, new InventoryBackpack(Wearing.getWearingBackpack(player)), ContainerBackpack.SOURCE_WEARING); + return new ContainerBackpack(player, new InventoryBackpack(Wearing.getHoldingBackpack(player)), Source.HOLDING); } break; - case BACKPACK_HOLDING: - if (Wearing.isHoldingBackpack(player)) + case BACKPACK_WEARING: + if (Wearing.isWearingBackpack(player)) { - return new ContainerBackpack(player, new InventoryBackpack(Wearing.getHoldingBackpack(player)), ContainerBackpack.SOURCE_HOLDING); + return new ContainerBackpack(player, new InventoryBackpack(Wearing.getWearingBackpack(player)), Source.WEARING); } break; case COPTER_HOLDING: if (Wearing.isHoldingCopter(player)) { - return new ContainerCopter(player, new InventoryCopterPack(Wearing.getHoldingCopter(player)),false); + return new ContainerCopter(player, new InventoryCopterPack(Wearing.getHoldingCopter(player)), Source.HOLDING); } break; case COPTER_WEARING: if (Wearing.isWearingCopter(player)) { - return new ContainerCopter(player, new InventoryCopterPack(Wearing.getWearingCopter(player)), true); + return new ContainerCopter(player, new InventoryCopterPack(Wearing.getWearingCopter(player)), Source.WEARING); } break; case JETPACK_HOLDING: - if (Wearing.isHoldingSteam(player)) + if (Wearing.isHoldingJetpack(player)) { - return new ContainerJetpack(player, new InventorySteamJetpack(Wearing.getHoldingSteam(player)),false); + return new ContainerJetpack(player, new InventoryCoalJetpack(Wearing.getHoldingJetpack(player)), Source.HOLDING); } break; case JETPACK_WEARING: - if (Wearing.isWearingSteam(player)) + if (Wearing.isWearingJetpack(player)) { - return new ContainerJetpack(player, new InventorySteamJetpack(Wearing.getWearingSteam(player)), true); + return new ContainerJetpack(player, new InventoryCoalJetpack(Wearing.getWearingJetpack(player)), Source.WEARING); } break; default: @@ -83,7 +90,6 @@ public Object getServerGuiElement(int ID, EntityPlayer player, World world, int } return null; - } @Override @@ -94,43 +100,43 @@ public Object getClientGuiElement(int ID, EntityPlayer player, World world, int case BACKPACK_TILE: if (world.getTileEntity(x, y, z) != null && world.getTileEntity(x, y, z) instanceof TileAdventureBackpack) { - return new GuiAdvBackpack(player, (TileAdventureBackpack) world.getTileEntity(x, y, z)); + return new GuiAdvBackpack(player, (TileAdventureBackpack) world.getTileEntity(x, y, z), Source.TILE); } break; - case BACKPACK_WEARING: - if (Wearing.isWearingBackpack(player)) + case BACKPACK_HOLDING: + if (Wearing.isHoldingBackpack(player)) { - return new GuiAdvBackpack(player, new InventoryBackpack(Wearing.getWearingBackpack(player)), true); + return new GuiAdvBackpack(player, new InventoryBackpack(Wearing.getHoldingBackpack(player)), Source.HOLDING); } break; - case BACKPACK_HOLDING: - if (Wearing.isHoldingBackpack(player)) + case BACKPACK_WEARING: + if (Wearing.isWearingBackpack(player)) { - return new GuiAdvBackpack(player, new InventoryBackpack(Wearing.getHoldingBackpack(player)), false); + return new GuiAdvBackpack(player, new InventoryBackpack(Wearing.getWearingBackpack(player)), Source.WEARING); } break; case COPTER_HOLDING: if (Wearing.isHoldingCopter(player)) { - return new GuiCopterPack(player, new InventoryCopterPack(Wearing.getHoldingCopter(player)),false); + return new GuiCopterPack(player, new InventoryCopterPack(Wearing.getHoldingCopter(player)), Source.HOLDING); } break; case COPTER_WEARING: if (Wearing.isWearingCopter(player)) { - return new GuiCopterPack(player, new InventoryCopterPack(Wearing.getWearingCopter(player)), true); + return new GuiCopterPack(player, new InventoryCopterPack(Wearing.getWearingCopter(player)), Source.WEARING); } break; case JETPACK_HOLDING: - if (Wearing.isHoldingSteam(player)) + if (Wearing.isHoldingJetpack(player)) { - return new GuiSteamJetpack(player, new InventorySteamJetpack(Wearing.getHoldingSteam(player)),false); + return new GuiCoalJetpack(player, new InventoryCoalJetpack(Wearing.getHoldingJetpack(player)), Source.HOLDING); } break; case JETPACK_WEARING: - if (Wearing.isWearingSteam(player)) + if (Wearing.isWearingJetpack(player)) { - return new GuiSteamJetpack(player, new InventorySteamJetpack(Wearing.getWearingSteam(player)), true); + return new GuiCoalJetpack(player, new InventoryCoalJetpack(Wearing.getWearingJetpack(player)), Source.WEARING); } break; default: diff --git a/src/main/java/com/darkona/adventurebackpack/handlers/KeyInputEventHandler.java b/src/main/java/com/darkona/adventurebackpack/handlers/KeyInputEventHandler.java new file mode 100644 index 00000000..16ea66f4 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/handlers/KeyInputEventHandler.java @@ -0,0 +1,169 @@ +package com.darkona.adventurebackpack.handlers; + +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.InputEvent; + +import com.darkona.adventurebackpack.common.ServerActions; +import com.darkona.adventurebackpack.config.Keybindings; +import com.darkona.adventurebackpack.entity.EntityFriendlySpider; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.network.CycleToolPacket; +import com.darkona.adventurebackpack.network.GUIPacket; +import com.darkona.adventurebackpack.network.PlayerActionPacket; +import com.darkona.adventurebackpack.network.SyncPropertiesPacket; +import com.darkona.adventurebackpack.network.WearableModePacket; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.Wearing; + +/** + * Created by Darkona on 11/10/2014. + */ +public class KeyInputEventHandler +{ + public enum Key + { + UNKNOWN, INVENTORY, ACTION, JUMP + } + + @SubscribeEvent + public void handleKeyInputEvent(InputEvent.KeyInputEvent event) + { + Key pressedKey = getPressedKeyBinding(); + Minecraft mc = Minecraft.getMinecraft(); + EntityPlayer player = mc.thePlayer; + + if (pressedKey == Key.UNKNOWN || player == null || player.isDead) + return; + + if (pressedKey == Key.INVENTORY && mc.inGameHasFocus) + { + sendSyncPropertiesPacket(); + + if (player.isSneaking()) + { + if (Wearing.isHoldingBackpack(player)) + { + sendGUIPacket(GUIPacket.BACKPACK_GUI, GUIPacket.FROM_HOLDING); + } + } + else + { + if (Wearing.isWearingBackpack(player)) + { + sendGUIPacket(GUIPacket.BACKPACK_GUI, GUIPacket.FROM_WEARING); + } + else if (Wearing.isHoldingBackpack(player)) + { + sendGUIPacket(GUIPacket.BACKPACK_GUI, GUIPacket.FROM_HOLDING); + } + else if (Wearing.isWearingCopter(player)) + { + sendGUIPacket(GUIPacket.COPTER_GUI, GUIPacket.FROM_WEARING); + } + else if (Wearing.isWearingJetpack(player)) + { + sendGUIPacket(GUIPacket.JETPACK_GUI, GUIPacket.FROM_WEARING); + } + } + } + + if (pressedKey == Key.ACTION) + { + if (Wearing.isHoldingHose(player)) + { + sendCycleToolPacket(CycleToolPacket.TOGGLE_HOSE_TANK); + ServerActions.switchHose(player, false, ServerActions.HOSE_TOGGLE); + } + else if (Wearing.isWearingBackpack(player)) + { + if (player.isSneaking()) + { + if (BackpackTypes.isNightVision(Wearing.getWearingBackpackInv(player).getType())) + { + sendWearableModePacket(WearableModePacket.NIGHTVISION_ON_OFF); + ServerActions.toggleNightVision(player, Wearing.getWearingBackpack(player)); + } + } + else + { + sendWearableModePacket(WearableModePacket.CYCLING_ON_OFF); + ServerActions.toggleToolCycling(player, Wearing.getWearingBackpack(player)); + } + } + else if (Wearing.isWearingCopter(player)) + { + if (player.isSneaking()) + { + sendWearableModePacket(WearableModePacket.COPTER_ON_OFF); + ServerActions.toggleCopterPack(player, Wearing.getWearingCopter(player), WearableModePacket.COPTER_ON_OFF); + } + else + { + sendWearableModePacket(WearableModePacket.COPTER_TOGGLE); + ServerActions.toggleCopterPack(player, Wearing.getWearingCopter(player), WearableModePacket.COPTER_TOGGLE); + } + } + else if (Wearing.isWearingJetpack(player)) + { + if (player.isSneaking()) + { + sendWearableModePacket(WearableModePacket.JETPACK_ON_OFF); + ServerActions.toggleCoalJetpack(player, Wearing.getWearingJetpack(player)); + } + } + } + + if (pressedKey == Key.JUMP) + { + if (player.ridingEntity instanceof EntityFriendlySpider) + { + sendPlayerActionPacket(PlayerActionPacket.SPIDER_JUMP); + ((EntityFriendlySpider) player.ridingEntity).setJumping(true); + } + } + } + + private static Key getPressedKeyBinding() + { + if (Keybindings.openInventory.isPressed()) + { + return Key.INVENTORY; + } + if (Keybindings.toggleActions.isPressed()) + { + return Key.ACTION; + } + if (Minecraft.getMinecraft().gameSettings.keyBindJump.isPressed()) + { + return Key.JUMP; + } + return Key.UNKNOWN; + } + + private void sendSyncPropertiesPacket() + { + ModNetwork.net.sendToServer(new SyncPropertiesPacket.Message()); + } + + private void sendGUIPacket(byte type, byte from) + { + ModNetwork.net.sendToServer(new GUIPacket.GUImessage(type, from)); + } + + private void sendWearableModePacket(byte type) + { + ModNetwork.net.sendToServer(new WearableModePacket.Message(type)); + } + + private void sendCycleToolPacket(byte type) + { + ModNetwork.net.sendToServer(new CycleToolPacket.CycleToolMessage(false, type)); + } + + private void sendPlayerActionPacket(byte type) + { + ModNetwork.net.sendToServer(new PlayerActionPacket.ActionMessage(type)); + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/handlers/KeybindHandler.java b/src/main/java/com/darkona/adventurebackpack/handlers/KeybindHandler.java deleted file mode 100644 index 5e12560d..00000000 --- a/src/main/java/com/darkona/adventurebackpack/handlers/KeybindHandler.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.darkona.adventurebackpack.handlers; - -import com.darkona.adventurebackpack.common.ServerActions; -import com.darkona.adventurebackpack.config.Keybindings; -import com.darkona.adventurebackpack.entity.EntityFriendlySpider; -import com.darkona.adventurebackpack.init.ModNetwork; -import com.darkona.adventurebackpack.item.ItemHose; -import com.darkona.adventurebackpack.network.*; -import com.darkona.adventurebackpack.reference.Key; -import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.InputEvent; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; - -/** - * Created by Darkona on 11/10/2014. - */ -public class KeybindHandler -{ - - private static Key getPressedKeyBinding() - { - if (Keybindings.openBackpack.isPressed()) - { - return Key.INVENTORY_KEY; - } - if (Keybindings.toggleHose.isPressed()) - { - return Key.TOGGLE_KEY; - } - - if (Minecraft.getMinecraft().gameSettings.keyBindJump.isPressed()) - { - return Key.JUMP; - } - return Key.UNKNOWN; - } - - @SubscribeEvent - public void handleKeyInputEvent(InputEvent.KeyInputEvent event) - { - Key keypressed = getPressedKeyBinding(); - Minecraft mc = Minecraft.getMinecraft(); - EntityPlayer player = mc.thePlayer; - - if(player != null) - { - if (keypressed == Key.INVENTORY_KEY) - { - if (mc.inGameHasFocus) - { - ModNetwork.net.sendToServer(new SyncPropertiesPacket.Message()); - if (Wearing.isWearingBackpack(player)) - { - ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.BACKPACK_GUI, GUIPacket.FROM_KEYBIND)); - } - if (Wearing.isWearingCopter(player)) - { - ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.COPTER_GUI, GUIPacket.FROM_KEYBIND)); - } - if (Wearing.isWearingSteam(player)) - { - ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.JETPACK_GUI, GUIPacket.FROM_KEYBIND)); - } - } - } - - if (keypressed == Key.TOGGLE_KEY) - { - if(player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() instanceof ItemHose) - { - ModNetwork.net.sendToServer(new CycleToolPacket.CycleToolMessage(0, (player).inventory.currentItem, CycleToolPacket.TOGGLE_HOSE_TANK)); - ServerActions.switchHose(player, ServerActions.HOSE_TOGGLE, 0, (player).inventory.currentItem); - } - if (Wearing.isWearingCopter(player)) - { - if (!player.isSneaking()) - { - ModNetwork.net.sendToServer(new WearableModePacket.Message(WearableModePacket.COPTER_TOGGLE, "")); - ServerActions.toggleCopterPack(player, Wearing.getWearingCopter(player), WearableModePacket.COPTER_TOGGLE); - } else - { - ModNetwork.net.sendToServer(new WearableModePacket.Message(WearableModePacket.COPTER_ON_OFF, "")); - ServerActions.toggleCopterPack(player, Wearing.getWearingCopter(player), WearableModePacket.COPTER_ON_OFF); - } - } - if (Wearing.isWearingSteam(player)) - { - if (player.isSneaking()) - { - ModNetwork.net.sendToServer(new WearableModePacket.Message(WearableModePacket.JETPACK_ON_OFF, "")); - ServerActions.toggleSteamJetpack(player, Wearing.getWearingSteam(player), WearableModePacket.JETPACK_ON_OFF); - } - } - } - - if(keypressed == Key.JUMP ) - { - if(player.ridingEntity != null && player.ridingEntity instanceof EntityFriendlySpider) - { - ModNetwork.net.sendToServer(new PlayerActionPacket.ActionMessage(PlayerActionPacket.spiderJump)); - ((EntityFriendlySpider)player.ridingEntity).setJumping(true); - } - } - } - } -} diff --git a/src/main/java/com/darkona/adventurebackpack/handlers/PlayerEventHandler.java b/src/main/java/com/darkona/adventurebackpack/handlers/PlayerEventHandler.java index fefc6bfb..180770e4 100644 --- a/src/main/java/com/darkona/adventurebackpack/handlers/PlayerEventHandler.java +++ b/src/main/java/com/darkona/adventurebackpack/handlers/PlayerEventHandler.java @@ -1,25 +1,8 @@ package com.darkona.adventurebackpack.handlers; -import com.darkona.adventurebackpack.common.ServerActions; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.entity.EntityFriendlySpider; -import com.darkona.adventurebackpack.entity.ai.EntityAIHorseFollowOwner; -import com.darkona.adventurebackpack.init.ModBlocks; -import com.darkona.adventurebackpack.init.ModItems; -import com.darkona.adventurebackpack.item.IBackWearableItem; -import com.darkona.adventurebackpack.playerProperties.BackpackProperty; -import com.darkona.adventurebackpack.proxy.ServerProxy; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Utils; -import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.common.eventhandler.Event; -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.PlayerEvent; -import cpw.mods.fml.common.gameevent.TickEvent; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.SharedMonsterAttributes; +import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.monster.EntitySpider; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; @@ -35,7 +18,29 @@ import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.player.EntityInteractEvent; +import net.minecraftforge.event.entity.player.PlayerDropsEvent; import net.minecraftforge.event.entity.player.PlayerWakeUpEvent; +import cpw.mods.fml.common.eventhandler.Event; +import cpw.mods.fml.common.eventhandler.EventPriority; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.PlayerEvent; +import cpw.mods.fml.common.gameevent.TickEvent; + +import com.darkona.adventurebackpack.block.BlockSleepingBag; +import com.darkona.adventurebackpack.common.ServerActions; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.entity.EntityFriendlySpider; +import com.darkona.adventurebackpack.entity.ai.EntityAIHorseFollowOwner; +import com.darkona.adventurebackpack.init.ModBlocks; +import com.darkona.adventurebackpack.init.ModItems; +import com.darkona.adventurebackpack.item.IBackWearableItem; +import com.darkona.adventurebackpack.item.ItemAdventureBackpack; +import com.darkona.adventurebackpack.playerProperties.BackpackProperty; +import com.darkona.adventurebackpack.proxy.ServerProxy; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.EnchUtils; +import com.darkona.adventurebackpack.util.LogHelper; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 11/10/2014 @@ -46,50 +51,49 @@ */ public class PlayerEventHandler { - - private static int tickCounter = 0; @SubscribeEvent public void registerBackpackProperty(EntityEvent.EntityConstructing event) { if (event.entity instanceof EntityPlayer && BackpackProperty.get((EntityPlayer) event.entity) == null) { BackpackProperty.register((EntityPlayer) event.entity); - /*if (!event.entity.worldObj.isRemote) - { - AdventureBackpack.proxy.joinPlayer((EntityPlayer)event.entity); - }*/ } - } @SubscribeEvent public void joinPlayer(EntityJoinWorldEvent event) { - if (!event.world.isRemote) + if (!event.world.isRemote && event.entity instanceof EntityPlayer) { - if (Utils.notNullAndInstanceOf(event.entity, EntityPlayer.class)) + EntityPlayer player = (EntityPlayer) event.entity; + LogHelper.info("Joined EntityPlayer of name: " + event.entity.getCommandSenderName()); + NBTTagCompound playerData = ServerProxy.extractPlayerProps(player.getUniqueID()); + if (playerData != null) { - EntityPlayer player = (EntityPlayer) event.entity; - LogHelper.info("Joined EntityPlayer of name: " + event.entity.getCommandSenderName()); - NBTTagCompound playerData = ServerProxy.extractPlayerProps(player.getUniqueID()); - if (playerData != null) - { - BackpackProperty.get(player).loadNBTData(playerData); - BackpackProperty.syncToNear(player); - LogHelper.info("Stored properties retrieved"); - } + BackpackProperty.get(player).loadNBTData(playerData); + BackpackProperty.sync(player); + LogHelper.info("Stored properties retrieved"); } } - } - @SubscribeEvent public void playerLogsIn(PlayerEvent.PlayerLoggedInEvent event) { if (event.player instanceof EntityPlayerMP) { - BackpackProperty.sync(event.player); + EntityPlayer player = event.player; + + BackpackProperty.sync(player); + + if (Wearing.isWearingCopter(player)) + { + ServerActions.copterSoundAtLogin(player); + } + if (Wearing.isWearingJetpack(player)) + { + ServerActions.jetpackSoundAtLogin(player); + } } } @@ -104,18 +108,14 @@ public void playerTravelsAcrossDimensions(PlayerEvent.PlayerChangedDimensionEven /** * Used for the Piston Boots to give them their amazing powers. - * - * @param event */ @SubscribeEvent public void onPlayerJump(LivingEvent.LivingJumpEvent event) { - if (event.entity != null && - event.entityLiving instanceof EntityPlayer) + if (event.entity != null && event.entityLiving instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) event.entity; - if (Wearing.isWearingBoots(player) && player.onGround) { ServerActions.pistonBootsJump(player); @@ -123,17 +123,41 @@ public void onPlayerJump(LivingEvent.LivingJumpEvent event) } } + private boolean pistonBootsStepHeight = false; + + @SubscribeEvent + public void pistonBootsUnequipped(LivingEvent.LivingUpdateEvent event) + { + if (event.entityLiving instanceof EntityPlayer) + { + EntityPlayer player = (EntityPlayer) event.entityLiving; + if (Wearing.isWearingBoots(player)) + { + if (!pistonBootsStepHeight) + { + pistonBootsStepHeight = true; + } + } + else + { + if (pistonBootsStepHeight) + { + player.stepHeight = 0.5001F; + pistonBootsStepHeight = false; + } + } + } + } + /** * Used by the Piston boots to lessen the fall damage. It's hacky, but I don't care. - * - * @param event */ @SubscribeEvent public void onFall(LivingFallEvent event) { if (event.entity != null) { - if (event.entityLiving instanceof EntityCreature && ConfigHandler.FIX_LEAD) + if (event.entityLiving instanceof EntityCreature && ConfigHandler.fixLead) { EntityCreature creature = (EntityCreature) event.entityLiving; if (creature.getLeashed() && creature.getLeashedToEntity() != null && creature.getLeashedToEntity() instanceof EntityPlayer) @@ -162,7 +186,7 @@ public void onFall(LivingFallEvent event) { event.setCanceled(true); } - if(Wearing.isWearingTheRightBackpack((EntityPlayer)event.entityLiving,"IronGolem") && ConfigHandler.BACKPACK_ABILITIES) + if (Wearing.isWearingTheRightBackpack((EntityPlayer) event.entityLiving, BackpackTypes.IRON_GOLEM) && ConfigHandler.backpackAbilities) { event.setCanceled(true); } @@ -170,50 +194,87 @@ public void onFall(LivingFallEvent event) } } - @SubscribeEvent(priority = EventPriority.LOW) public void playerDies(LivingDeathEvent event) { - if (Utils.notNullAndInstanceOf(event.entity, EntityPlayer.class)) + if (event.entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) event.entity; + if (!player.worldObj.isRemote) { - //LogHelper.info("Player died"); BackpackProperty props = BackpackProperty.get(player); - if (props.hasWearable()) + if (ConfigHandler.enableCampfireSpawn && props.isForcedCampFire()) { - //We want to keep the wearables on the player if KeepInventory is active. - if (!player.getEntityWorld().getGameRules().getGameRuleBooleanValue("keepInventory")) + ChunkCoordinates lastCampFire = props.getCampFire(); + if (lastCampFire != null) { - //So if it isn't, we drop it like it's hot, drop it like it's hot, drop it like it's hot. - ((IBackWearableItem) props.getWearable().getItem()).onPlayerDeath(player.worldObj, player, props.getWearable()); + player.setSpawnChunk(lastCampFire, false, player.dimension); } + //Set the forced spawn coordinates on the campfire. False, because the player must respawn at spawn point if there's no campfire. } - if (props.isForcedCampFire()) + if (Wearing.isWearingWearable(player)) { - ChunkCoordinates lastCampFire = BackpackProperty.get(player).getCampFire(); - if (lastCampFire != null) + if (Wearing.isWearingTheRightBackpack(player, BackpackTypes.CREEPER)) { - player.setSpawnChunk(lastCampFire, false, player.dimension); + player.worldObj.createExplosion(player, player.posX, player.posY, player.posZ, 4.0F, false); + } + + if (player.getEntityWorld().getGameRules().getGameRuleBooleanValue("keepInventory")) + { + ((IBackWearableItem) props.getWearable().getItem()).onPlayerDeath(player.worldObj, player, props.getWearable()); + ServerProxy.storePlayerProps(player); } - //Set the forced spawn coordinates on the campfire. False, because the player must respawn at spawn point if there's no campfire. } - ServerProxy.storePlayerProps(player); } } event.setResult(Event.Result.ALLOW); } + @SubscribeEvent + public void playerDeathDrop(PlayerDropsEvent event) + { + EntityPlayer player = event.entityPlayer; + + if (Wearing.isWearingWearable(player)) + { + ItemStack pack = Wearing.getWearingWearable(player); + BackpackProperty props = BackpackProperty.get(player); + + if (EnchUtils.isSoulBounded(pack) + || (ConfigHandler.backpackDeathPlace && pack.getItem() instanceof ItemAdventureBackpack)) + { + ((IBackWearableItem) props.getWearable().getItem()).onPlayerDeath(player.worldObj, player, props.getWearable()); + ServerProxy.storePlayerProps(player); + } + else + { + event.drops.add(new EntityItem(player.worldObj, player.posX, player.posY, player.posZ, pack)); + props.setWearable(null); + } + } + } + + @SubscribeEvent + public void playerRespawn(PlayerEvent.PlayerRespawnEvent event) + { + if (event.player instanceof EntityPlayerMP) + { + BackpackProperty.sync(event.player); + } + } + @SubscribeEvent public void playerCraftsBackpack(PlayerEvent.ItemCraftedEvent event) { if (event.crafting.getItem() == ModItems.adventureBackpack) { - LogHelper.info("Player crafted a backpack, and that backpack's appearance is: " + event.crafting.getTagCompound().getString("colorName")); - if (BackpackNames.getBackpackColorName(event.crafting).equals("Dragon")) + LogHelper.info("Player crafted a backpack, and that backpack's appearance is: " + + BackpackTypes.getSkinName(event.crafting)); + + if (!ConfigHandler.consumeDragonEgg && BackpackTypes.getType(event.crafting) == BackpackTypes.DRAGON) { event.player.dropPlayerItemWithRandomChoice(new ItemStack(Blocks.dragon_egg, 1), false); event.player.playSound("mob.enderdragon.growl", 1.0f, 5.0f); @@ -225,11 +286,12 @@ public void playerCraftsBackpack(PlayerEvent.ItemCraftedEvent event) public void interactWithCreatures(EntityInteractEvent event) { EntityPlayer player = event.entityPlayer; - if (!event.entityPlayer.worldObj.isRemote) + + if (!player.worldObj.isRemote) { - if (Utils.notNullAndInstanceOf(event.target, EntitySpider.class)) + if (event.target instanceof EntitySpider) { - if (Wearing.isWearingTheRightBackpack(player, "Spider")) + if (Wearing.isWearingTheRightBackpack(player, BackpackTypes.SPIDER)) { EntityFriendlySpider pet = new EntityFriendlySpider(event.target.worldObj); pet.setLocationAndAngles(event.target.posX, event.target.posY, event.target.posZ, event.target.rotationYaw, event.target.rotationPitch); @@ -238,10 +300,11 @@ public void interactWithCreatures(EntityInteractEvent event) event.entityPlayer.mountEntity(pet); } } - if (Utils.notNullAndInstanceOf(event.target, EntityHorse.class)) + if (event.target instanceof EntityHorse) { - ItemStack stack = player.getCurrentEquippedItem(); EntityHorse horse = (EntityHorse) event.target; + ItemStack stack = player.getCurrentEquippedItem(); + if (stack != null && stack.getItem() != null && stack.getItem() instanceof ItemNameTag && stack.hasDisplayName()) { if (horse.getCustomNameTag() == null || horse.getCustomNameTag().equals("") && horse.isTame()) @@ -264,49 +327,55 @@ public void interactWithCreatures(EntityInteractEvent event) @SubscribeEvent public void playerWokeUp(PlayerWakeUpEvent event) { - if (event.entity.worldObj.isRemote) return; - ChunkCoordinates bedLocation = event.entityPlayer.getBedLocation(event.entityPlayer.dimension); - if (bedLocation != null && event.entityPlayer.worldObj.getBlock(bedLocation.posX, bedLocation.posY, bedLocation.posZ) == ModBlocks.blockSleepingBag) + if (event.entity.worldObj.isRemote) + return; + + EntityPlayer player = event.entityPlayer; + ChunkCoordinates bedLocation = player.getBedLocation(player.dimension); + if (bedLocation != null && player.worldObj.getBlock(bedLocation.posX, bedLocation.posY, bedLocation.posZ) == ModBlocks.blockSleepingBag) { //If the player wakes up in one of those super confortable SleepingBags (tm) (Patent Pending) - BackpackProperty.get(event.entityPlayer).setForceCampFire(true); - LogHelper.info("Player just woke up in a sleeping bag, forcing respawn in the last lighted campfire, if there's any"); - } else + if (BlockSleepingBag.isSleepingInPortableBag(player)) + { + BlockSleepingBag.packPortableSleepingBag(player); + BackpackProperty.get(player).setWakingUpInPortableBag(true); + LogHelper.info("Player just woke up in a portable sleeping bag."); + } + else + { + BackpackProperty.get(player).setForceCampFire(true); + LogHelper.info("Player just woke up in a sleeping bag, forcing respawn in the last lighted campfire, if there's any"); + } + } + else { //If it's a regular bed or whatever - BackpackProperty.get(event.entityPlayer).setForceCampFire(false); + BackpackProperty.get(player).setForceCampFire(false); } } - @SubscribeEvent public void tickPlayer(TickEvent.PlayerTickEvent event) { - if (event.player != null && !event.player.isDead && Wearing.isWearingWearable(event.player)) + EntityPlayer player = event.player; + if (player != null && !player.isDead && Wearing.isWearingWearable(player)) { - if(event.phase == TickEvent.Phase.START) + if (event.phase == TickEvent.Phase.START) { - BackpackProperty.get(event.player).executeWearableUpdateProtocol(); + BackpackProperty.get(player).executeWearableUpdateProtocol(); } if (event.phase == TickEvent.Phase.END) { - if (event.side.isServer()) + if (!player.worldObj.isRemote) { - EntityPlayerMP playerMP = (EntityPlayerMP) event.player; - BackpackProperty.syncToNear(event.player); -// if (Utils.notNullAndInstanceOf(event.player.openContainer, IWearableContainer.class)) -// { -// //playerMP.sendContainerAndContentsToPlayer(playerMP.openContainer, playerMP.openContainer.getInventory()); -// BackpackProperty.syncToNear(event.player); -// }else -// { -// BackpackProperty.syncToNear(event.player); -// } + if (BackpackProperty.get(player).isWakingUpInPortableBag() && Wearing.isWearingBackpack(player)) + { + BlockSleepingBag.restoreOriginalSpawn(player, Wearing.getWearingBackpackInv(player).getExtendedProperties()); + BackpackProperty.get(player).setWakingUpInPortableBag(false); + } } } } } - } - diff --git a/src/main/java/com/darkona/adventurebackpack/handlers/RenderHandler.java b/src/main/java/com/darkona/adventurebackpack/handlers/RenderHandler.java index 49acc7b1..05902582 100644 --- a/src/main/java/com/darkona/adventurebackpack/handlers/RenderHandler.java +++ b/src/main/java/com/darkona/adventurebackpack/handlers/RenderHandler.java @@ -1,10 +1,11 @@ package com.darkona.adventurebackpack.handlers; -import com.darkona.adventurebackpack.proxy.ClientProxy; +import net.minecraftforge.client.event.RenderPlayerEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import net.minecraftforge.client.event.RenderPlayerEvent; + +import com.darkona.adventurebackpack.proxy.ClientProxy; /** * Created on 25/12/2014 diff --git a/src/main/java/com/darkona/adventurebackpack/init/ConditionalFluidEffect.java b/src/main/java/com/darkona/adventurebackpack/init/ConditionalFluidEffect.java index fc1fa25f..8ad5fb90 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/ConditionalFluidEffect.java +++ b/src/main/java/com/darkona/adventurebackpack/init/ConditionalFluidEffect.java @@ -1,9 +1,9 @@ package com.darkona.adventurebackpack.init; -import adventurebackpack.api.FluidEffect; -import com.darkona.adventurebackpack.config.ConfigHandler; import com.darkona.adventurebackpack.fluids.effects.FuelEffect; import com.darkona.adventurebackpack.fluids.effects.OilEffect; +import com.darkona.adventurebackpack.reference.LoadedMods; +import adventurebackpack.api.FluidEffect; /** * Created on 28/12/2014 @@ -17,7 +17,7 @@ public class ConditionalFluidEffect public static void init() { - if (ConfigHandler.IS_BUILDCRAFT) + if (LoadedMods.BUILDCRAFT) { oilEffect = new OilEffect(); fuelEffect = new FuelEffect(); diff --git a/src/main/java/com/darkona/adventurebackpack/init/ModBlocks.java b/src/main/java/com/darkona/adventurebackpack/init/ModBlocks.java index 6d2cab7f..9c5259a2 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/ModBlocks.java +++ b/src/main/java/com/darkona/adventurebackpack/init/ModBlocks.java @@ -1,15 +1,19 @@ package com.darkona.adventurebackpack.init; -import com.darkona.adventurebackpack.block.*; import cpw.mods.fml.common.registry.GameRegistry; +import com.darkona.adventurebackpack.block.BlockAdventureBackpack; +import com.darkona.adventurebackpack.block.BlockCampFire; +import com.darkona.adventurebackpack.block.BlockSleepingBag; +import com.darkona.adventurebackpack.block.TileAdventureBackpack; +import com.darkona.adventurebackpack.block.TileCampfire; + /** * Created by Darkona on 12/10/2014. */ public class ModBlocks { - public static BlockAdventureBackpack blockBackpack = new BlockAdventureBackpack(); public static BlockSleepingBag blockSleepingBag = new BlockSleepingBag(); public static BlockCampFire blockCampFire = new BlockCampFire(); @@ -23,5 +27,4 @@ public static void init() GameRegistry.registerTileEntity(TileCampfire.class, "tileCampFire"); GameRegistry.registerTileEntity(TileAdventureBackpack.class, "adventureBackpackTileEntity"); } - } diff --git a/src/main/java/com/darkona/adventurebackpack/init/ModDates.java b/src/main/java/com/darkona/adventurebackpack/init/ModDates.java new file mode 100644 index 00000000..05bc2111 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/init/ModDates.java @@ -0,0 +1,123 @@ +package com.darkona.adventurebackpack.init; + +import java.util.Calendar; + +/** + * Created by Ugachaga on 06.07.2017. + */ +public class ModDates +{ + private static String holiday; + + private static int year = Calendar.getInstance().get(Calendar.YEAR); + private static int month = Calendar.getInstance().get(Calendar.MONTH) + 1; + private static int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); + + public static void init() + { + holiday = setHoliday(); + } + + public static String getHoliday() + { + //TODO add check for current day, change skin if new day is holiday + return holiday; + } + + private static String setHoliday() + { + // here and below commented lines: textures are missing. + /*if (ChineseCalendar.isChineseNewYear(year, month, day)) + { + return "ChinaNewYear"; + } + if (JewishCalendar.isHannukah(year, month, day)) + { + return "Hannukah"; + } + if (month == calculateEaster(year)[0] && day == calculateEaster(year)[1]) + { + return "Easter"; + }*/ + + String result = "Standard"; + if (month == 1) + { + if (day == 1) result = "NewYear"; + if (day == 28) result = "Shuttle"; //Challenger + } + if (month == 2) + { + if (day == 1) result = "Shuttle"; //Columbia + if (day == 14) result = "Valentines"; + //if (day == 23) result = "Fatherland"; + } + if (month == 3) + { + if (day == 17) result = "Patrick"; + } + if (month == 4) + { + if (day == 1) result = "Fools"; + //if (day == 25) result = "Italy"; + } + if (month == 5) + { + //if (day == 8 || day == 9 || day == 10) result = "Liberation"; + } + if (month == 6) + { + + } + if (month == 7) + { + if (day == 4) result = "USA"; + if (day == 24) result = "Bolivar"; + //if (day == 14) result = "Bastille"; + } + if (month == 8) + { + + } + if (month == 9) + { + //if (day == 19) result = "Pirate"; + } + if (month == 10) + { + //if (day == 3) result = "Germany"; + //if (day == 12) result = "Columbus"; + //if (day == 31) result = "Halloween"; + } + if (month == 11) + { + //if (day == 2) result = "Muertos"; + } + if (month == 12) + { + if (day >= 22 && day <= 26) result = "Christmas"; + if (day == 31) result = "NewYear"; + } + //LogHelper.info("Today is: " + day + "/" + month + "/" + year + ". Which means today is: " + result); + return result; + } + + private static int[] calculateEaster(int year) + { + int a = year % 19, + b = year / 100, + c = year % 100, + d = b / 4, + e = b % 4, + g = (8 * b + 13) / 25, + h = (19 * a + b - d - g + 15) % 30, + j = c / 4, + k = c % 4, + m = (a + 11 * h) / 319, + r = (2 * e + 2 * j - k - h + m + 32) % 7, + n = (h - m + r + 90) / 25, + p = (h - m + r + n + 19) % 32; + + return new int[]{n, p}; + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/init/ModEntities.java b/src/main/java/com/darkona/adventurebackpack/init/ModEntities.java index 7ea8c023..75d73cbf 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/ModEntities.java +++ b/src/main/java/com/darkona/adventurebackpack/init/ModEntities.java @@ -1,9 +1,10 @@ package com.darkona.adventurebackpack.init; +import cpw.mods.fml.common.registry.EntityRegistry; + import com.darkona.adventurebackpack.AdventureBackpack; import com.darkona.adventurebackpack.entity.EntityFriendlySpider; import com.darkona.adventurebackpack.entity.EntityInflatableBoat; -import cpw.mods.fml.common.registry.EntityRegistry; /** * Created on 12/10/2014 @@ -12,17 +13,10 @@ */ public class ModEntities { - public static void init() { - //Color color1 = new Color(227,129,216); - // Color color2 = new Color(0, 0, 0); - //int color_int1 = (color1.getRed() << 16) + (color1.getGreen() << 8) + color1.getBlue(); - //int color_int2 = (color2.getRed() << 16) + (color2.getGreen() << 8) + color2.getBlue(); int counter = 0; EntityRegistry.registerModEntity(EntityInflatableBoat.class, "inflatableBoat", counter++, AdventureBackpack.instance, 64, 1, true); - EntityRegistry.registerModEntity(EntityFriendlySpider.class, "rideableSpider", counter++, AdventureBackpack.instance, 64, 2, true); - //EntityRegistry.registerGlobalEntityID(EntityRideableSpider.class, "rideableSpider", EntityRegistry.findGlobalUniqueEntityId(),color_int2,color_int1); } } diff --git a/src/main/java/com/darkona/adventurebackpack/init/ModFluids.java b/src/main/java/com/darkona/adventurebackpack/init/ModFluids.java index b487faa1..adb334b6 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/ModFluids.java +++ b/src/main/java/com/darkona/adventurebackpack/init/ModFluids.java @@ -1,14 +1,14 @@ package com.darkona.adventurebackpack.init; -import com.darkona.adventurebackpack.fluids.FluidMelonJuice; -import com.darkona.adventurebackpack.fluids.FluidMilk; -import com.darkona.adventurebackpack.fluids.FluidMushroomStew; -import com.darkona.adventurebackpack.reference.GeneralReference; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidRegistry; +import com.darkona.adventurebackpack.fluids.FluidMelonJuice; +import com.darkona.adventurebackpack.fluids.FluidMilk; +import com.darkona.adventurebackpack.fluids.FluidMushroomStew; + /** * Created on 12/10/2014. * @@ -19,6 +19,7 @@ public class ModFluids public static FluidMilk milk; public static FluidMelonJuice melonJuice; public static FluidMushroomStew mushroomStew; + public static void init() { milk = new FluidMilk(); @@ -33,8 +34,5 @@ public static void init() FluidRegistry.registerFluid(mushroomStew); FluidContainerRegistry.registerFluidContainer(mushroomStew, new ItemStack(Items.mushroom_stew), new ItemStack(Items.bowl)); - - GeneralReference.init(); } - } diff --git a/src/main/java/com/darkona/adventurebackpack/init/ModItems.java b/src/main/java/com/darkona/adventurebackpack/init/ModItems.java index 01ae6fbd..ccdca0aa 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/ModItems.java +++ b/src/main/java/com/darkona/adventurebackpack/init/ModItems.java @@ -1,53 +1,68 @@ package com.darkona.adventurebackpack.init; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.item.*; import cpw.mods.fml.common.registry.GameRegistry; +import com.darkona.adventurebackpack.item.ArmorAB; +import com.darkona.adventurebackpack.item.ItemAdventureBackpack; +import com.darkona.adventurebackpack.item.ItemAdventureHat; +import com.darkona.adventurebackpack.item.ItemAdventurePants; +import com.darkona.adventurebackpack.item.ItemAdventureSuit; +import com.darkona.adventurebackpack.item.ItemCoalJetpack; +import com.darkona.adventurebackpack.item.ItemComponent; +import com.darkona.adventurebackpack.item.ItemCopterPack; +import com.darkona.adventurebackpack.item.ItemCrossbow; +import com.darkona.adventurebackpack.item.ItemHose; +import com.darkona.adventurebackpack.item.ItemJuiceBottle; +import com.darkona.adventurebackpack.item.ItemMachete; +import com.darkona.adventurebackpack.item.ItemPistonBoots; + /** * Created on 10/10/2014 - * @author Darkona * + * @author Darkona */ public class ModItems { - public static final ItemMachete machete = new ItemMachete(); - public static final ItemComponent component = new ItemComponent(); - public static final ItemHose hose = new ItemHose(); + public static final ItemCrossbow cwxbow = new ItemCrossbow(); public static final ArmorAB adventureHat = new ItemAdventureHat(); + public static final ArmorAB adventureSuit = new ItemAdventureSuit(); + public static final ArmorAB adventurePants = new ItemAdventurePants(); public static final ArmorAB pistonBoots = new ItemPistonBoots(); - //public static final ArmorAB adventureSuit = new ItemAdventureJacket(); + public static final ItemCopterPack copterPack = new ItemCopterPack(); + public static final ItemCoalJetpack coalJetpack = new ItemCoalJetpack(); public static final ItemAdventureBackpack adventureBackpack = new ItemAdventureBackpack(); + public static final ItemComponent component = new ItemComponent(); + public static final ItemHose hose = new ItemHose(); public static final ItemJuiceBottle melonJuiceBottle = new ItemJuiceBottle(); - public static final ItemCopterPack copterPack = new ItemCopterPack(); - public static final ItemCrossbow cwxbow = new ItemCrossbow(); - public static final ItemSteamJetpack steamJetpack = new ItemSteamJetpack(); public static void init() { - GameRegistry.registerItem(component, "backpackComponent"); + // Sequence affect location in NEI and CreativeTab, so keep it logically grouped GameRegistry.registerItem(machete, "machete"); + GameRegistry.registerItem(cwxbow, "clockworkCrossbow"); GameRegistry.registerItem(adventureHat, "adventureHat"); + GameRegistry.registerItem(adventureSuit, "adventureSuit"); + GameRegistry.registerItem(adventurePants, "adventurePants"); GameRegistry.registerItem(pistonBoots, "pistonBoots"); - // GameRegistry.registerItem(adventureSuit, "adventureSuit"); + GameRegistry.registerItem(copterPack, "copterPack"); + GameRegistry.registerItem(coalJetpack, "coalJetpack"); GameRegistry.registerItem(adventureBackpack, "adventureBackpack"); + GameRegistry.registerItem(component, "backpackComponent"); GameRegistry.registerItem(hose, "backpackHose"); GameRegistry.registerItem(melonJuiceBottle, "melonJuiceBottle"); - GameRegistry.registerItem(cwxbow, "clockworkCrossbow"); - } - public static void conditionalInit() + /*public static void conditionalInit() { - if (ConfigHandler.IS_BUILDCRAFT) + if (LoadedMods.BUILDCRAFT) { GameRegistry.registerItem(copterPack, "copterPack"); } - if (ConfigHandler.IS_RAILCRAFT) + if (LoadedMods.RAILCRAFT) { GameRegistry.registerItem(steamJetpack, "steamJetpack"); } - } + }*/ } diff --git a/src/main/java/com/darkona/adventurebackpack/init/ModMaterials.java b/src/main/java/com/darkona/adventurebackpack/init/ModMaterials.java index 0a9d94ec..07574c34 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/ModMaterials.java +++ b/src/main/java/com/darkona/adventurebackpack/init/ModMaterials.java @@ -6,13 +6,11 @@ /** * Created on 11/10/2014 - * @author Darkona * + * @author Darkona */ public class ModMaterials { - public static Item.ToolMaterial ruggedIron = EnumHelper.addToolMaterial("RUGGED_IRON", 2, 350, 6.5F, 5.2F, 10); - public static ItemArmor.ArmorMaterial ruggedLeather = EnumHelper.addArmorMaterial("RUGGED_LEATHER", 15, new int[]{2, 5, 4, 2}, 12); } diff --git a/src/main/java/com/darkona/adventurebackpack/init/ModNetwork.java b/src/main/java/com/darkona/adventurebackpack/init/ModNetwork.java index 6a22c8cf..f072942e 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/ModNetwork.java +++ b/src/main/java/com/darkona/adventurebackpack/init/ModNetwork.java @@ -1,20 +1,29 @@ package com.darkona.adventurebackpack.init; -import com.darkona.adventurebackpack.network.*; -import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; -import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; -import com.darkona.adventurebackpack.reference.ModInfo; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.WorldServer; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.WorldServer; + +import com.darkona.adventurebackpack.network.CowAbilityPacket; +import com.darkona.adventurebackpack.network.CycleToolPacket; +import com.darkona.adventurebackpack.network.EquipUnequipBackWearablePacket; +import com.darkona.adventurebackpack.network.GUIPacket; +import com.darkona.adventurebackpack.network.PlayerActionPacket; +import com.darkona.adventurebackpack.network.SleepingBagPacket; +import com.darkona.adventurebackpack.network.SyncPropertiesPacket; +import com.darkona.adventurebackpack.network.WearableModePacket; +import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; +import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; +import com.darkona.adventurebackpack.playerProperties.BackpackProperty; +import com.darkona.adventurebackpack.reference.ModInfo; /** * Created on 12/10/2014 - * @author Darkona * + * @author Darkona */ public class ModNetwork { @@ -36,7 +45,6 @@ public static void init() registerMessage(CowAbilityPacket.class, CowAbilityPacket.CowAbilityMessage.class); registerMessage(PlayerActionPacket.class, PlayerActionPacket.ActionMessage.class); registerMessage(EquipUnequipBackWearablePacket.class, EquipUnequipBackWearablePacket.Message.class); - } @SuppressWarnings("unchecked") @@ -56,12 +64,13 @@ private static void registerMessage(Class handler, Class message) public static void sendToNearby(IMessage message, EntityPlayer player) { - if(player!=null && player.worldObj instanceof WorldServer) + if (player != null && player.worldObj instanceof WorldServer) { try { ((WorldServer) player.worldObj).getEntityTracker().func_151248_b(player, ModNetwork.net.getPacketFrom(message)); - } catch (Exception ex) + } + catch (Exception ex) { ex.printStackTrace(); } @@ -71,5 +80,6 @@ public static void sendToNearby(IMessage message, EntityPlayer player) public static void sendToDimension(IMessage message, EntityPlayer player) { net.sendToDimension(message, player.dimension); + BackpackProperty.sync(player); } } diff --git a/src/main/java/com/darkona/adventurebackpack/init/ModRecipes.java b/src/main/java/com/darkona/adventurebackpack/init/ModRecipes.java index 955bc6b8..acf45dfa 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/ModRecipes.java +++ b/src/main/java/com/darkona/adventurebackpack/init/ModRecipes.java @@ -1,16 +1,19 @@ package com.darkona.adventurebackpack.init; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.init.recipes.BackpackRecipesList; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.util.LogHelper; -import cpw.mods.fml.common.registry.GameRegistry; +import java.lang.reflect.Field; + import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.ShapedOreRecipe; +import cpw.mods.fml.common.registry.GameRegistry; -import java.lang.reflect.Field; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.init.recipes.BackpackRecipesList; +import com.darkona.adventurebackpack.init.recipes.ShapedBackpackRecipe; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.LogHelper; /** * Created on 20/10/2014 @@ -19,13 +22,18 @@ */ public class ModRecipes { - private static ItemStack bc(int damage) - { - return BackpackNames.setBackpackColorNameFromDamage(new ItemStack(ModItems.adventureBackpack), damage); - } - public static void init() { + if (ConfigHandler.recipeSaddle) + { + //Saddle + GameRegistry.addRecipe(new ItemStack(Items.saddle), + "LLL", + "L L", + "I I", + 'L', Items.leather, + 'I', Items.iron_ingot); + } //CampFire GameRegistry.addRecipe(new ShapedOreRecipe(ModBlocks.blockCampFire, @@ -34,25 +42,118 @@ public static void init() "ccc", 'S', "stickWood", 'x', Items.coal, - 'c', "cobblestone" - )); + 'c', "cobblestone")); - //Sleeping Bag - GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 1), - " X", - "CCC", - 'X', Blocks.wool, - 'C', Blocks.carpet - ); + if (ConfigHandler.recipeCopterPack) + { + //Copter Pack + GameRegistry.addRecipe(BackpackUtils.createCopterStack(), + "WBW", + "TEI", + "CDI", + 'W', Blocks.planks, + 'B', new ItemStack(ModItems.component, 1, 6), + 'T', new ItemStack(ModItems.component, 1, 2), + 'E', new ItemStack(ModItems.component, 1, 5), + 'C', new ItemStack(Items.dye, 1, 2), + 'D', Items.diamond, + 'I', Items.iron_ingot); + } - //Backpack Tank - GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 2), - "GIG", - "GGG", - "GIG", - 'G', Blocks.glass, - 'I', Items.iron_ingot - ); + if (ConfigHandler.recipeCoalJetpack) + { + //CoalJetpack + GameRegistry.addRecipe(BackpackUtils.createJetpackStack(), + "SWT", + "GIG", + "FWS", + 'W', Blocks.planks, + 'G', Items.gold_ingot, + 'I', Items.iron_ingot, + 'S', Blocks.stone, + 'F', Blocks.furnace, + 'T', new ItemStack(ModItems.component, 1, 2)); + } + + if (ConfigHandler.recipeMachete) + { + //Machete Handle + GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 4), + "YIY", + "BSB", + "RbR", + 'Y', new ItemStack(Items.dye, 1, 11), + 'B', new ItemStack(Items.dye, 1, 4), + 'R', new ItemStack(Items.dye, 1, 1), + 'b', new ItemStack(Items.dye, 1, 0), + 'I', Items.iron_ingot, + 'S', Items.stick); + + //Machete + GameRegistry.addRecipe(new ItemStack(ModItems.machete), + " I ", + " I ", + " H ", + 'I', Items.iron_ingot, + 'H', new ItemStack(ModItems.component, 1, 4)); + } + + if (ConfigHandler.recipeClockCrossbow) + { + //Clockwork Crossbow + GameRegistry.addRecipe(new ItemStack(ModItems.cwxbow), + " ", + "BA ", + "SW ", + 'B', Items.bow, + 'A', Items.arrow, + 'S', Items.stick, + 'W', Blocks.planks); + } + + if (ConfigHandler.recipeAdventuresSet) + { + //Adventure Hat + GameRegistry.addRecipe(new ItemStack(ModItems.adventureHat), + " ", + "nC ", + "LLL", + 'n', Items.gold_nugget, + 'C', Items.leather_helmet, + 'L', Items.leather); + + //Adventure Suit + GameRegistry.addRecipe(new ItemStack(ModItems.adventureSuit), + "LWL", + "LVL", + " ", + 'V', Items.leather_chestplate, + 'W', Blocks.wool, + 'L', Items.leather); + + //Adventure Pants + GameRegistry.addRecipe(new ItemStack(ModItems.adventurePants), + "LVL", + "LWL", + " ", + 'V', Items.leather_leggings, + 'W', Blocks.wool, + 'L', Items.leather); + } + + if (ConfigHandler.recipePitonBoots) + { + //Piston Boots + GameRegistry.addRecipe(new ItemStack(ModItems.pistonBoots), + " B ", + "PSP", + 'B', Items.leather_boots, + 'P', Blocks.piston, + 'S', Items.slime_ball); + } + + //Melon Juice Bottle + GameRegistry.addShapelessRecipe(new ItemStack(ModItems.melonJuiceBottle), Items.melon, Items.potionitem); //Hose Nozzle GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 3), @@ -61,141 +162,31 @@ public static void init() " ", 'G', Items.gold_ingot, 'I', Items.iron_ingot, - 'L', Blocks.lever - ); - - //Machete Handle - GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 4), - "YIY", - "BSB", - "RbR", - 'Y', new ItemStack(Items.dye, 1, 11), - 'B', new ItemStack(Items.dye, 1, 4), - 'R', new ItemStack(Items.dye, 1, 1), - 'b', new ItemStack(Items.dye, 1, 0), - 'I', Items.iron_ingot, - 'S', Items.stick - ); - - - GameRegistry.addRecipe(new ItemStack(ModItems.machete), - " I ", - " I ", - " H ", - 'I', Items.iron_ingot, - 'H', new ItemStack(ModItems.component, 1, 4) - ); - - GameRegistry.addRecipe(new ItemStack(ModItems.adventureHat), - " ", - "nC ", - "LLL", - 'n', Items.gold_nugget, - 'C', Items.leather_helmet, - 'L', Items.leather - ); -/* - GameRegistry.addRecipe(new ItemStack(ModItems.adventureSuit), - " V ", - " W ", - " P ", - 'V', Items.leather_chestplate, - 'W', Blocks.wool, - 'P', Items.leather_leggings - ); -*/ - GameRegistry.addRecipe(new ItemStack(ModItems.pistonBoots), - " B ", - "PSP", - 'B', Items.leather_boots, - 'P', Blocks.piston, - 'S', Items.slime_ball - ); - - GameRegistry.addShapelessRecipe(new ItemStack(ModItems.melonJuiceBottle), - Items.melon, Items.potionitem - ); + 'L', Blocks.lever); + //Hose GameRegistry.addRecipe(new ItemStack(ModItems.hose), "NGG", " G", - " G", 'N', new ItemStack(ModItems.component, 1, 3), - 'G', new ItemStack(Items.dye, 1, 2) - ); - - /*GameRegistry.addRecipe(a, - "LGL", - "TCT", - "LSL", - 'L', Items.leather, - 'G', Items.gold_ingot, - 'T', new ItemStack(ModItems.component, 1, 2), - 'S', new ItemStack(ModItems.component, 1, 1), - 'C', Blocks.chest - );*/ - - BackpackRecipesList br = new BackpackRecipesList(); - int counter = 0; - for (int i = 0; i < BackpackNames.backpackNames.length; i++) - { - for (Field field : BackpackRecipesList.class.getFields()) - { - try - { - if (field.getName().equals((BackpackNames.backpackNames[i]))) - { - GameRegistry.addRecipe(new ShapedOreRecipe(BackpackNames.setBackpackColorNameFromDamage(new ItemStack(ModItems.adventureBackpack), i), (Object[]) field.get(br))); - counter++; - } - } catch (Exception oops) - { - LogHelper.error("Huge mistake during reflection. Some bad things might happen: " + oops.getClass().getName()); - oops.printStackTrace(); - } - } - - } - LogHelper.info("Loaded " + counter + " backpack recipes."); + 'G', new ItemStack(Items.dye, 1, 2)); - //GameRegistry.addRecipe(new AbstractBackpackRecipe()); - /*BackpackRecipes br = new BackpackRecipes(); - int i = 0; - for (Field field : BackpackRecipes.class.getFields()) - { - try - { - if (field.getType() == ItemStack[].class) - { - AbstractBackpackRecipeTwo recipe = new AbstractBackpackRecipeTwo(field.getName(), (ItemStack[]) field.get(br)); - GameRegistry.addRecipe(recipe); - //LogHelper.info("Loaded recipe for " + field.getName() + " backpack."); - i++; - } - } catch (Exception oops) - { - LogHelper.error("Huge mistake during reflection. Some bad things might happen."); - } - } - LogHelper.info("Loaded " + i + " backpack recipes."); - RecipeSorter.register(ModInfo.MOD_ID + ":adventureBackpack", AbstractBackpackRecipeTwo.class, RecipeSorter.Category.SHAPED, "after:minecraft:shapeless"); - */ - } + //Sleeping Bag + GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 1), + " X", + "CCC", + 'X', Blocks.wool, + 'C', Blocks.carpet); - public static void conditionalInit() - { - if(ConfigHandler.SADDLE_RECIPE) - { - GameRegistry.addRecipe(new ItemStack(Items.saddle), - "LLL", - "L L", - "I I", - 'L', Items.leather, - 'I', Items.iron_ingot - ); - } + //Backpack Tank + GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 2), + "GIG", + "GGG", + "GIG", + 'G', Blocks.glass, + 'I', Items.iron_ingot); - if(ConfigHandler.IS_BUILDCRAFT) + if (ConfigHandler.recipeCopterPack) { //Copter Engine GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 5), @@ -207,62 +198,82 @@ public static void conditionalInit() 'P', Blocks.piston, 'F', Blocks.furnace, 'C', Items.cauldron, - 'O', Blocks.obsidian - ); + 'O', Blocks.obsidian); + } + if (ConfigHandler.recipeCopterPack || ConfigHandler.recipeInflatableBoatM) + { //Copter Blades GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 6), "III", " F ", " F ", 'I', Items.iron_ingot, - 'F', Blocks.fence - ); + 'F', Blocks.fence); + } - //Copter Pack - GameRegistry.addRecipe(new ItemStack(ModItems.copterPack), - "WBW", - "TEI", - "CDI", - 'W', Blocks.planks, - 'B', new ItemStack(ModItems.component, 1, 6), - 'T', new ItemStack(ModItems.component, 1, 2), - 'E', new ItemStack(ModItems.component, 1, 5), - 'C', new ItemStack(Items.dye, 1, 2), - 'D', Items.diamond, - 'I', Items.iron_ingot - ); + + if (ConfigHandler.recipeInflatableBoat) + { + //Inflatable Boat + GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 7), + " ", + "w w", + "sws", + 'w', Blocks.wool, + 's', Blocks.sand); + + if (ConfigHandler.recipeInflatableBoatM) + { + //Inflatable Boat (Motorized) + GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 8), + " B ", + " E ", + " H ", + 'B', new ItemStack(ModItems.component, 1, 7), + 'H', new ItemStack(ModItems.component, 1, 9), + 'E', new ItemStack(ModItems.component, 1, 5)); + + //Hydro Blades + GameRegistry.addRecipe(new ItemStack(ModItems.component, 1, 9), + " F ", + " F ", + "III", + 'I', Items.iron_ingot, + 'F', Blocks.fence); + } } - //Ok let's try getting railcraft stuff. - //Seriously this is hard - if(ConfigHandler.IS_RAILCRAFT) + BackpackRecipesList br = new BackpackRecipesList(); + int counter = 0; + for (BackpackTypes type : BackpackTypes.values()) { - try + for (Field field : BackpackRecipesList.class.getFields()) { - LogHelper.info("Railcraft is present. Adding Steam Jetpack."); - ItemStack firebox = GameRegistry.findItemStack("Railcraft", "machine.beta.boiler.firebox.solid", 1); - ItemStack boiler = GameRegistry.findItemStack("Railcraft", "machine.beta.boiler.tank.pressure.low", 1); - if(firebox != null && boiler != null) + try { - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.steamJetpack), - "BWT", - "GIG", - "xWC", - 'W', "plankWood", - 'G', "ingotGold", - 'I',"ingotIron", - 'B', boiler, - 'x', firebox, - 'C', new ItemStack(Items.dye, 1, 2), - 'T', new ItemStack(ModItems.component, 1, 2) - )); + if (field.getName().equals(BackpackTypes.getSkinName(type))) + { + GameRegistry.addRecipe(new ShapedBackpackRecipe(BackpackUtils.createBackpackStack(type), (Object[]) field.get(br))); + counter++; + } + } + catch (Exception oops) + { + LogHelper.error("Huge mistake during reflection. Some bad things might happen: " + oops.getClass().getName()); + oops.printStackTrace(); } - - }catch(Exception ex) - { - ex.printStackTrace(); } + } + LogHelper.info("Loaded " + counter + " backpack recipes."); } -} + + /*public static void conditionalInit() + { + if (LoadedMods.BUILDCRAFT) + { + + } + }*/ +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/init/ModWorldGen.java b/src/main/java/com/darkona/adventurebackpack/init/ModWorldGen.java index 5f8c5bc0..cd2be860 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/ModWorldGen.java +++ b/src/main/java/com/darkona/adventurebackpack/init/ModWorldGen.java @@ -1,8 +1,7 @@ package com.darkona.adventurebackpack.init; -import com.darkona.adventurebackpack.config.ConfigHandler; -import com.darkona.adventurebackpack.reference.BackpackNames; -import cpw.mods.fml.common.registry.VillagerRegistry; +import java.util.Random; + import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; @@ -10,8 +9,17 @@ import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; import net.minecraftforge.common.ChestGenHooks; +import cpw.mods.fml.common.registry.VillagerRegistry; -import java.util.Random; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.BackpackUtils; + +import static com.darkona.adventurebackpack.reference.BackpackTypes.BAT; +import static com.darkona.adventurebackpack.reference.BackpackTypes.IRON_GOLEM; +import static com.darkona.adventurebackpack.reference.BackpackTypes.PIGMAN; +import static com.darkona.adventurebackpack.reference.BackpackTypes.STANDARD; +import static com.darkona.adventurebackpack.reference.BackpackTypes.VILLAGER; /** * Created on 24/12/2014 @@ -22,46 +30,38 @@ public class ModWorldGen { public static void init() { - - //Dungeon Generation - - for (int i = 0; i < BackpackNames.backpackNames.length; i++) { - if (BackpackNames.backpackNames[i].equals("IronGolem")) - { - ItemStack backpack = BackpackNames.setBackpackColorNameFromDamage(new ItemStack(ModItems.adventureBackpack), i); - ChestGenHooks.addItem(ChestGenHooks.VILLAGE_BLACKSMITH, new WeightedRandomChestContent(backpack, 1, 1, 2)); - } else if (BackpackNames.backpackNames[i].equals("Bat")) - { - ItemStack backpack = BackpackNames.setBackpackColorNameFromDamage(new ItemStack(ModItems.adventureBackpack), i); - ChestGenHooks.addItem(ChestGenHooks.DUNGEON_CHEST, new WeightedRandomChestContent(backpack, 1, 1, 2)); - ChestGenHooks.addItem(ChestGenHooks.MINESHAFT_CORRIDOR, new WeightedRandomChestContent(backpack, 1, 1, 12)); - } else if (BackpackNames.backpackNames[i].equals("Pigman") && ConfigHandler.PIGMAN_ALLOWED) - { - ItemStack backpack = BackpackNames.setBackpackColorNameFromDamage(new ItemStack(ModItems.adventureBackpack), i); - ChestGenHooks.addItem(ChestGenHooks.PYRAMID_DESERT_CHEST, new WeightedRandomChestContent(backpack, 1, 1, 12)); - VillagerRegistry.instance().registerVillageTradeHandler(i, new ModWorldGen.TradeHandler(backpack)); - } else if (BackpackNames.backpackNames[i].equals("Villager")) - { - ItemStack backpack = BackpackNames.setBackpackColorNameFromDamage(new ItemStack(ModItems.adventureBackpack), i); - VillagerRegistry.instance().registerVillageTradeHandler(1, new ModWorldGen.TradeHandler(backpack)); - VillagerRegistry.instance().registerVillageTradeHandler(2, new ModWorldGen.TradeHandler(backpack)); - VillagerRegistry.instance().registerVillageTradeHandler(3, new ModWorldGen.TradeHandler(backpack)); - } else if (BackpackNames.backpackNames[i].equals("Standard") && ConfigHandler.BONUS_CHEST_ALLOWED) - { - ItemStack backpack = BackpackNames.setBackpackColorNameFromDamage(new ItemStack(ModItems.adventureBackpack), i); - ChestGenHooks.addItem(ChestGenHooks.BONUS_CHEST, new WeightedRandomChestContent(backpack, 0, 1, 5)); - } + ItemStack backpack = BackpackUtils.createBackpackStack(VILLAGER); + VillagerRegistry.instance().registerVillageTradeHandler(1, new ModWorldGen.TradeHandler(backpack)); + VillagerRegistry.instance().registerVillageTradeHandler(2, new ModWorldGen.TradeHandler(backpack)); + VillagerRegistry.instance().registerVillageTradeHandler(3, new ModWorldGen.TradeHandler(backpack)); + } + if (ConfigHandler.allowGolemGen) + { + ItemStack backpack = BackpackUtils.createBackpackStack(IRON_GOLEM); + ChestGenHooks.addItem(ChestGenHooks.VILLAGE_BLACKSMITH, new WeightedRandomChestContent(backpack, 1, 1, 2)); + } + if (ConfigHandler.allowBatGen) + { + ItemStack backpack = BackpackUtils.createBackpackStack(BAT); + ChestGenHooks.addItem(ChestGenHooks.DUNGEON_CHEST, new WeightedRandomChestContent(backpack, 1, 1, 2)); + ChestGenHooks.addItem(ChestGenHooks.MINESHAFT_CORRIDOR, new WeightedRandomChestContent(backpack, 1, 1, 12)); + } + if (ConfigHandler.allowPigmanGen) + { + ItemStack backpack = BackpackUtils.createBackpackStack(PIGMAN); + ChestGenHooks.addItem(ChestGenHooks.PYRAMID_DESERT_CHEST, new WeightedRandomChestContent(backpack, 1, 1, 12)); + VillagerRegistry.instance().registerVillageTradeHandler(BackpackTypes.getMeta(PIGMAN), new ModWorldGen.TradeHandler(backpack)); + } + if (ConfigHandler.allowBonusGen) + { + ItemStack backpack = BackpackUtils.createBackpackStack(STANDARD); + ChestGenHooks.addItem(ChestGenHooks.BONUS_CHEST, new WeightedRandomChestContent(backpack, 0, 1, 5)); } - - //Villager Trade - - } public static class TradeHandler implements VillagerRegistry.IVillageTradeHandler { - ItemStack backpack; TradeHandler(ItemStack backpack) @@ -69,30 +69,21 @@ public static class TradeHandler implements VillagerRegistry.IVillageTradeHandle this.backpack = backpack; } - /** - * Called to allow changing the content of the {@link net.minecraft.village.MerchantRecipeList} for the villager - * supplied during creation - * - * @param villager - * @param recipeList - * @param random - */ @Override + @SuppressWarnings("unchecked") public void manipulateTradesForVillager(EntityVillager villager, MerchantRecipeList recipeList, Random random) { //0 Farmer, 1 Librarian, 2Priest, 3 Blacksmith, 4 Butcher if (villager.getProfession() == 1 || villager.getProfession() == 2) { - ItemStack payment = BackpackNames.setBackpackColorNameFromDamage(new ItemStack(ModItems.adventureBackpack), 0); + ItemStack payment = BackpackUtils.createBackpackStack(STANDARD); recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 10), payment, this.backpack)); } if (villager.getProfession() == 3) { - ItemStack payment = new ItemStack(ModItems.adventureBackpack); - BackpackNames.setBackpackColorName(payment, "IronGolem"); + ItemStack payment = BackpackUtils.createBackpackStack(IRON_GOLEM); recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 10), payment, this.backpack)); } } } - } diff --git a/src/main/java/com/darkona/adventurebackpack/init/recipes/AbstractBackpackRecipe.java b/src/main/java/com/darkona/adventurebackpack/init/recipes/AbstractBackpackRecipe.java deleted file mode 100644 index 5699c5a6..00000000 --- a/src/main/java/com/darkona/adventurebackpack/init/recipes/AbstractBackpackRecipe.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.darkona.adventurebackpack.init.recipes; - -import com.darkona.adventurebackpack.init.ModItems; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.util.LogHelper; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - -/** - * Created on 20/10/2014 - * - * @author Darkona - */ -public class AbstractBackpackRecipe implements IRecipe -{ - - final BackpackRecipes br = new BackpackRecipes(); - private ItemStack result; - private ItemStack[] recipe; - - public boolean compareStacksForColor(ItemStack stack1, ItemStack stack2) - { - - if (stack1 == null && stack2 == null) - { - return true; - } else if (stack1 != null && stack2 != null) - { - if (stack1.getItem() != stack2.getItem()) - { - return false; - } else - { - return (stack1.getItemDamage() == stack2.getItemDamage()); - } - } - return false; - } - - - public AbstractBackpackRecipe() - { - recipes = new HashMap(); - int i = 0; - for (Field field : BackpackRecipes.class.getFields()) - { - try - { - if (field.getType() == ItemStack[].class) - { - recipes.put(field.getName(), (ItemStack[]) field.get(br)); - i++; - } - } catch (Exception oops) - { - LogHelper.error("Huge mistake during reflection. Some bad things might happen."); - } - } - LogHelper.info("Loaded " + i + " recipes for backpack coloration."); - } - - public HashMap recipes; - - - public ItemStack makeBackpack(ItemStack backpackIn, String colorName) - { - if (backpackIn == null) return null; - - ItemStack newBackpack = backpackIn.copy(); //new ItemStack(ModItems.adventureBackpack,1); - if (backpackIn.stackTagCompound == null) - { - backpackIn.setTagCompound(new NBTTagCompound()); - backpackIn.stackTagCompound.setString("colorName", "Standard"); - } - NBTTagCompound compound = (NBTTagCompound) backpackIn.getTagCompound().copy(); - newBackpack.setTagCompound(compound); - newBackpack.stackTagCompound.setString("colorName", colorName); - return newBackpack; - } - - - public boolean match(ItemStack[] model, InventoryCrafting invC) - { - if (model == null || invC == null) return false; - for (int i = 0; i < invC.getSizeInventory(); i++) - { - ItemStack m = model[i]; - ItemStack c = invC.getStackInSlot(i); - if (!compareStacksForColor(m, c)) - { - return false; - } - if (i == 4) - { - if (!BackpackNames.getBackpackColorName(c).equals("Standard")) - { - return false; - } - } - } - - return true; - } - - @Override - public boolean matches(InventoryCrafting invC, World world) - { - result = null; - if (invC != null) - { - for (Map.Entry recipe : recipes.entrySet()) - { - if (match(recipe.getValue(), invC)) - { - result = makeBackpack(invC.getStackInSlot(4), recipe.getKey()); - break; - } - } - } - return result != null; - } - - /** - * Returns an Item that is the result of this recipe - */ - @Override - public ItemStack getCraftingResult(InventoryCrafting invC) - { - //result = null; - if (invC != null) - { - for (Map.Entry recipe : recipes.entrySet()) - { - if (match(recipe.getValue(), invC)) - { - return makeBackpack(invC.getStackInSlot(4), recipe.getKey()); - } - } - } - return this.result; - // return result.copy(); - } - - /** - * Returns the size of the recipe area - */ - @Override - public int getRecipeSize() - { - return 9; - } - - @Override - public ItemStack getRecipeOutput() - { - ItemStack backpack = new ItemStack(ModItems.adventureBackpack, 1); - backpack.setTagCompound(new NBTTagCompound()); - backpack.stackTagCompound.setString("colorName", "Standard"); - return backpack; - } - - -} diff --git a/src/main/java/com/darkona/adventurebackpack/init/recipes/AbstractBackpackRecipeTwo.java b/src/main/java/com/darkona/adventurebackpack/init/recipes/AbstractBackpackRecipeTwo.java index fb58f82b..0103fd77 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/recipes/AbstractBackpackRecipeTwo.java +++ b/src/main/java/com/darkona/adventurebackpack/init/recipes/AbstractBackpackRecipeTwo.java @@ -1,69 +1,70 @@ package com.darkona.adventurebackpack.init.recipes; -import com.darkona.adventurebackpack.init.ModItems; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; +import com.darkona.adventurebackpack.init.ModItems; +import com.darkona.adventurebackpack.reference.BackpackTypes; + +import static com.darkona.adventurebackpack.common.Constants.TAG_TYPE; + /** * Created on 24/12/2014 * * @author Darkona */ -public class AbstractBackpackRecipeTwo implements IRecipe +public class AbstractBackpackRecipeTwo implements IRecipe //TODO unused class { private ItemStack result; private ItemStack[] recipe; - private String name; + private BackpackTypes type; - public AbstractBackpackRecipeTwo(String name, ItemStack[] recipe) + public AbstractBackpackRecipeTwo(BackpackTypes type, ItemStack[] recipe) { this.recipe = recipe; - this.name = name; - this.result = makeBackpack(new ItemStack(ModItems.adventureBackpack), this.name); + this.type = type; + this.result = makeBackpack(new ItemStack(ModItems.adventureBackpack), this.type); } - public boolean compareStacks(ItemStack stack1, ItemStack stack2) + private boolean compareStacks(ItemStack stack1, ItemStack stack2) { - if (stack1 == null && stack2 == null) { return true; - } else if (stack1 != null && stack2 != null) + } + else if (stack1 != null && stack2 != null) { if (stack1.getItem().equals(stack2.getItem())) { - /*if(stack1.getItem() instanceof ItemAdventureBackpack) - { - return stack1.stackTagCompound.getString("colorName").equals("Standard"); - }*/ return ((stack1.getItemDamage() == stack2.getItemDamage())); } } return false; } - public static ItemStack makeBackpack(ItemStack backpackIn, String colorName) + private static ItemStack makeBackpack(ItemStack backpackIn, BackpackTypes type) { - if (backpackIn == null) return null; + if (backpackIn == null) + return null; + if (backpackIn.stackTagCompound == null) { backpackIn.setTagCompound(new NBTTagCompound()); - backpackIn.stackTagCompound.setString("colorName", colorName); + backpackIn.stackTagCompound.setByte(TAG_TYPE, BackpackTypes.getMeta(type)); } ItemStack newBackpack = backpackIn.copy(); NBTTagCompound compound = (NBTTagCompound) backpackIn.getTagCompound().copy(); newBackpack.setTagCompound(compound); - newBackpack.stackTagCompound.setString("colorName", colorName); + newBackpack.stackTagCompound.setByte(TAG_TYPE, BackpackTypes.getMeta(type)); return newBackpack; } @Override public boolean matches(InventoryCrafting invC, World world) { - //LogHelper.info("Matching recipe"); if (this.recipe == null || invC == null) return false; for (int i = 0; i < invC.getSizeInventory(); i++) { @@ -71,7 +72,6 @@ public boolean matches(InventoryCrafting invC, World world) { return false; } - } return true; } @@ -81,7 +81,7 @@ public ItemStack getCraftingResult(InventoryCrafting invC) { if (matches(invC, null)) { - return makeBackpack(invC.getStackInSlot(4), this.name); + return makeBackpack(invC.getStackInSlot(4), this.type); } return null; } diff --git a/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipe.java b/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipe.java index 01d381bb..3dd3c2ee 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipe.java +++ b/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipe.java @@ -2,6 +2,8 @@ import net.minecraft.item.ItemStack; +import com.darkona.adventurebackpack.reference.BackpackTypes; + /** * Created on 24/12/2014 * @@ -10,15 +12,16 @@ public class BackpackRecipe { public ItemStack[] array; - public String name; + public BackpackTypes type; BackpackRecipe() { + } - BackpackRecipe(String name, ItemStack[] array) + BackpackRecipe(BackpackTypes type, ItemStack[] array) { - this.name = name; + this.type = type; this.array = array; } } diff --git a/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipes.java b/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipes.java deleted file mode 100644 index 62d59ab0..00000000 --- a/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipes.java +++ /dev/null @@ -1,668 +0,0 @@ -package com.darkona.adventurebackpack.init.recipes; - -import com.darkona.adventurebackpack.init.ModItems; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import java.util.HashMap; -import java.util.List; - -/** - * Created on 20/10/2014 - * - * @author Darkona - */ -public class BackpackRecipes -{ - - public List recipes; - - public BackpackRecipes() - { - String[] covered = {"XXX", "XaX", "XXX"}; - Black = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 15), - 'a', ModItems.adventureBackpack - ); - - Blaze = reviewRecipe( - "BFB", - "BaB", - "PLP", - 'B', Items.blaze_rod, - 'F', Items.fire_charge, - 'a', ModItems.adventureBackpack, - 'P', Items.blaze_powder, - 'L', Items.lava_bucket - ); - - Blue = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 11), - 'a', ModItems.adventureBackpack - ); - - Bookshelf = reviewRecipe( - "BDB", - "BaB", - "bbb", - 'B', Blocks.bookshelf, - 'a', ModItems.adventureBackpack, - 'b', Items.book - ); - - Brown = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 12), - 'a', ModItems.adventureBackpack - ); - - BrownMushroom = reviewRecipe(covered, - 'X', Blocks.brown_mushroom, - 'a', ModItems.adventureBackpack - ); - - Cactus = reviewRecipe( - "CGC", - "CaC", - "SSS", - 'C', Blocks.cactus, - 'G', new ItemStack(Items.dye, 1, 2), - 'a', ModItems.adventureBackpack, - 'S', Blocks.sand - ); - - Cake = reviewRecipe( - "ECE", - "WaW", - "SmS", - 'a', ModItems.adventureBackpack, - 'E', Items.egg, - 'C', Items.cake, - 'W', Items.wheat, - 'S', Items.sugar, - 'm', Items.milk_bucket - ); - - Chest = reviewRecipe( - "CWC", - "WaW", - "CWC", - 'C', Blocks.chest, - 'W', Blocks.planks, - 'a', ModItems.adventureBackpack - ); - - Chicken = reviewRecipe( - "FnF", - "FaF", - "nEn", - 'F', Items.feather, - 'n', Items.gold_nugget, - 'a', ModItems.adventureBackpack, - 'E', Items.egg - ); - - Coal = reviewRecipe( - "cCc", - "CaC", - "ccc", - 'c', Items.coal, - 'C', Blocks.coal_block, - 'a', ModItems.adventureBackpack - ); - - Cookie = reviewRecipe( - "cCc", - "WaW", - "ccc", - 'c', Items.cookie, - 'C', new ItemStack(Items.dye, 1, 3), - 'W', Items.wheat, - 'a', ModItems.adventureBackpack - ); - - Cow = reviewRecipe( - "BLB", - "BaB", - "LML", - 'B', Items.beef, - 'a', ModItems.adventureBackpack, - 'L', Items.leather, - 'M', Items.milk_bucket - ); - - Creeper = reviewRecipe( - "GHG", - "GaG", - "TNT",//see what I did there? ;D - 'G', Items.gunpowder, - 'H', new ItemStack(Items.skull, 1, 4), //Creeper Skull - 'a', ModItems.adventureBackpack, - 'T', Blocks.tnt, - 'N', Blocks.tnt - ); - - Cyan = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 9), - 'a', ModItems.adventureBackpack - ); - - Diamond = reviewRecipe( - "GDG", - "GaG", - "GdG", - 'G', Blocks.glass, - 'D', Blocks.diamond_block, - 'a', ModItems.adventureBackpack, - 'd', Items.diamond - ); - - Dragon = reviewRecipe( - "EDE", - "OaO", - "POP", - 'E', Blocks.end_stone, - 'D', new ItemStack(Blocks.dragon_egg, 1), - 'O', Blocks.obsidian, - 'a', ModItems.adventureBackpack, - 'P', Items.ender_pearl - ); - - Egg = reviewRecipe(covered, - 'X', Items.egg, - 'a', ModItems.adventureBackpack - ); - - Emerald = reviewRecipe( - "GEG", - "GaG", - "eGe", - 'G', Blocks.glass, - 'E', Blocks.emerald_block, - 'a', ModItems.adventureBackpack, - 'e', Items.emerald - ); - - End = reviewRecipe( - "eEe", - "EaE", - "eEe", - 'E', Blocks.end_stone, - 'e', Items.ender_eye, - 'a', ModItems.adventureBackpack - ); - - Enderman = reviewRecipe( - "PXP", - "XaX", - "PXP", - 'X', new ItemStack(Blocks.wool, 1, 15), - 'P', Items.ender_pearl, - 'a', ModItems.adventureBackpack - ); - - Ghast = reviewRecipe( - "GFG", - "TaT", - "GTG", - 'G', Items.ghast_tear, - 'F', Items.fire_charge, - 'T', Items.gunpowder, - 'a', ModItems.adventureBackpack - ); - - Glowstone = reviewRecipe( - "GgG", - "GaG", - "GgG", - 'G', Blocks.glowstone, - 'g', Items.glowstone_dust, - 'a', ModItems.adventureBackpack - ); - - Gold = reviewRecipe( - "FGF", - "FaF", - "gFg", - 'F', Blocks.glass, - 'G', Blocks.gold_block, - 'a', ModItems.adventureBackpack, - 'g', Items.gold_ingot - ); - - Gray = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 7), - 'a', ModItems.adventureBackpack - ); - - Green = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 13), - 'a', ModItems.adventureBackpack - ); - - Haybale = reviewRecipe(covered, - 'X', Blocks.hay_block, - 'a', ModItems.adventureBackpack - ); - - Iron = reviewRecipe( - "GIG", - "GaG", - "iGi", - 'G', Blocks.glass, - 'I', Blocks.iron_block, - 'a', ModItems.adventureBackpack, - 'i', Items.iron_ingot - ); - - Lapis = reviewRecipe( - "GLG", - "GaG", - "lGl", - 'G', Blocks.glass, - 'L', Blocks.lapis_block, - 'l', new ItemStack(Items.dye, 1, 4), - 'a', ModItems.adventureBackpack - ); - - Leather = reviewRecipe(covered, - 'X', Items.leather, - 'a', ModItems.adventureBackpack - ); - - LightBlue = reviewRecipe( - "XXX", - "XaX", - "XXX", - 'X', new ItemStack(Blocks.wool, 1, 3), - 'a', ModItems.adventureBackpack - ); - - LightGray = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 8), - 'a', ModItems.adventureBackpack - ); - - Lime = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 5), - 'a', ModItems.adventureBackpack - ); - - Magenta = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 2), - 'a', ModItems.adventureBackpack - ); - - MagmaCube = reviewRecipe( - "MLM", - "MaM", - "MLM", - 'M', Items.magma_cream, - 'a', ModItems.adventureBackpack, - 'L', Items.lava_bucket - ); - - Melon = reviewRecipe( - "mMm", - "mam", - "msm", - 'm', Items.melon, - 'M', Blocks.melon_block, - 'a', ModItems.adventureBackpack, - 's', Items.melon_seeds - ); - - Mooshroom = reviewRecipe( - "SRL", - "BaB", - "LRS", - 'R', Blocks.red_mushroom, - 'B', Blocks.brown_mushroom, - 'a', ModItems.adventureBackpack, - 'S', Items.mushroom_stew, - 'L', Blocks.mycelium - ); - - Nether = reviewRecipe( - "QwQ", - "NaN", - "QLQ", - 'Q', Items.quartz, - 'N', Blocks.netherrack, - 'w', Items.nether_wart, - 'L', Items.lava_bucket, - 'a', ModItems.adventureBackpack - ); - - Obsidian = reviewRecipe( - covered, - 'X', Blocks.obsidian, - 'a', ModItems.adventureBackpack - ); - - Ocelot = reviewRecipe( - "FYF", - "YaY", - "FYF", - 'F', Items.fish, - 'Y', new ItemStack(Blocks.wool, 1, 4), - 'a', ModItems.adventureBackpack - ); - - Orange = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 1), - 'a', ModItems.adventureBackpack - ); - - Pig = reviewRecipe(covered, - 'X', Items.porkchop, - 'a', ModItems.adventureBackpack - ); - - Pink = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 6), - 'a', ModItems.adventureBackpack - ); - - Pumpkin = reviewRecipe( - "PPP", - "PaP", - "PsP", - 'P', Blocks.pumpkin, - 'a', ModItems.adventureBackpack, - 's', Items.pumpkin_seeds - ); - - Purple = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 10), - 'a', ModItems.adventureBackpack - ); - - Quartz = reviewRecipe( - "QqQ", - "qaq", - "QqQ", - 'Q', Blocks.quartz_block, - 'q', Items.quartz, - 'a', ModItems.adventureBackpack - ); - - Rainbow = reviewRecipe( - "RCP", - "OaB", - "YGF", - 'R', new ItemStack(Items.dye, 1, 1), //RED - 'O', new ItemStack(Items.dye, 1, 14),//ORANGE - 'Y', new ItemStack(Items.dye, 1, 11),//YELLOW - 'G', new ItemStack(Items.dye, 1, 10),//LIME - 'F', new ItemStack(Items.dye, 1, 6),//CYAN - 'B', new ItemStack(Items.dye, 1, 4),//BLUE - 'P', new ItemStack(Items.dye, 1, 5),//PURPLE - 'C', Items.record_cat, - 'a', ModItems.adventureBackpack - ); - - Red = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 14), - 'a', ModItems.adventureBackpack - ); - - RedMushroom = reviewRecipe(covered, - 'X', Blocks.red_mushroom, - 'a', ModItems.adventureBackpack - ); - - Redstone = reviewRecipe( - "rRr", - "RaR", - "rRr", - 'R', Blocks.redstone_block, - 'r', Items.redstone, - 'a', ModItems.adventureBackpack - ); - - Sandstone = reviewRecipe( - "CSC", - "SaS", - "CSC", - 'S', new ItemStack(Blocks.sandstone, 1, 0), - 'C', new ItemStack(Blocks.sandstone, 1, 1), - 'a', ModItems.adventureBackpack - ); - - Sheep = reviewRecipe( - "WPW", - "WaW", - "WWW", - 'W', new ItemStack(Blocks.wool, 1, 0), - 'P', new ItemStack(Blocks.wool, 1, 6), - 'a', ModItems.adventureBackpack - ); - - Skeleton = reviewRecipe( - "BSB", - "bab", - "BAB", - 'B', Items.bone, - 'S', new ItemStack(Items.skull, 1, 0),//Skeleton skull - 'b', Items.bow, - 'A', Items.arrow, - 'a', ModItems.adventureBackpack - ); - - Slime = reviewRecipe(covered, - 'X', Items.slime_ball, - 'a', ModItems.adventureBackpack - ); - - Snow = reviewRecipe( - "sSs", - "SaS", - "sSs", - 'S', Blocks.snow, - 's', Items.snowball, - 'a', ModItems.adventureBackpack - ); - - Spider = reviewRecipe( - "ESE", - "LaL", - "ESE", - 'E', Items.spider_eye, - 'S', Items.string, - 'L', Blocks.ladder, - 'a', ModItems.adventureBackpack - ); - - White = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 0), - 'a', ModItems.adventureBackpack - ); - - Wither = reviewRecipe( - "SSS", - "sas", - "NsD", - 'S', new ItemStack(Items.skull, 1, 1),//WitherSkelleton Skull - 's', Blocks.soul_sand, - 'N', Items.nether_star, - 'D', Items.diamond, - 'a', ModItems.adventureBackpack - ); - - WitherSkeleton = reviewRecipe( - "BsB", - "SaS", - "CBC", - 'B', Items.bone, - 'S', Items.stone_sword, - 'a', ModItems.adventureBackpack, - 'C', Items.coal, - 's', new ItemStack(Items.skull, 1, 1) - ); - - Wolf = reviewRecipe( - "BWB", - "WaW", - "BWB", - 'B', Items.bone, - 'W', new ItemStack(Blocks.wool, 1, 0), - 'a', ModItems.adventureBackpack - ); - - Yellow = reviewRecipe(covered, - 'X', new ItemStack(Blocks.wool, 1, 4), - 'a', ModItems.adventureBackpack - ); - - Zombie = reviewRecipe( - "FSF", - "FaF", - "FFF", - 'F', Items.rotten_flesh, - 'S', new ItemStack(Items.skull, 1, 2), - 'a', ModItems.adventureBackpack - ); - } - - public final ItemStack[] Black; - public final ItemStack[] Blaze; - public final ItemStack[] Blue; - public final ItemStack[] Bookshelf; - public final ItemStack[] Brown; - public final ItemStack[] BrownMushroom; - public final ItemStack[] Cactus; - public final ItemStack[] Cake; - public final ItemStack[] Chicken; - public final ItemStack[] Chest; - public final ItemStack[] Coal; - public final ItemStack[] Cookie; - public final ItemStack[] Cow; - public final ItemStack[] Creeper; - public final ItemStack[] Cyan; - public final ItemStack[] Diamond; - public final ItemStack[] Dragon; - public final ItemStack[] Egg; - public final ItemStack[] Emerald; - public final ItemStack[] End; - public final ItemStack[] Enderman; - public final ItemStack[] Ghast; - public final ItemStack[] Glowstone; - public final ItemStack[] Gold; - public final ItemStack[] Gray; - public final ItemStack[] Green; - public final ItemStack[] Haybale; - public final ItemStack[] Iron; - public final ItemStack[] Lapis; - public final ItemStack[] Leather; - public final ItemStack[] LightBlue; - public final ItemStack[] LightGray; - public final ItemStack[] Lime; - public final ItemStack[] Magenta; - public final ItemStack[] MagmaCube; - public final ItemStack[] Melon; - public final ItemStack[] Mooshroom; - public final ItemStack[] Nether; - public final ItemStack[] Obsidian; - public final ItemStack[] Ocelot; - public final ItemStack[] Orange; - public final ItemStack[] Pig; - public final ItemStack[] Pink; - public final ItemStack[] Pumpkin; - public final ItemStack[] Purple; - public final ItemStack[] Quartz; - public final ItemStack[] Rainbow; - public final ItemStack[] Red; - public final ItemStack[] RedMushroom; - public final ItemStack[] Redstone; - public final ItemStack[] Sandstone; - public final ItemStack[] Sheep; - public final ItemStack[] Skeleton; - public final ItemStack[] Slime; - public final ItemStack[] Snow; - public final ItemStack[] Spider; - //public final ItemStack[] Sponge; - public final ItemStack[] White; - public final ItemStack[] Wither; - public final ItemStack[] WitherSkeleton; - public final ItemStack[] Wolf; - public final ItemStack[] Yellow; - public final ItemStack[] Zombie; - - - public static ItemStack[] reviewRecipe(Object... objects) - { - String s = ""; - //BackpackRecipe recipe = new BackpackRecipe(); - int i = 0; - int j = 0; - int k = 0; - /*if(objects[i] instanceof String) - { - recipe.name = (String)objects[i]; - i++; - }*/ - if (objects[i] instanceof String[]) - { - String[] astring = (String[]) ((String[]) objects[i++]); - - for (int l = 0; l < astring.length; ++l) - { - String s1 = astring[l]; - ++k; - j = s1.length(); - s = s + s1; - } - } else - { - while (objects[i] instanceof String) - { - String s2 = (String) objects[i++]; - ++k; - j = s2.length(); - s = s + s2; - } - } - - HashMap hashmap; - - for (hashmap = new HashMap(); i < objects.length; i += 2) - { - Character character = (Character) objects[i]; - ItemStack itemstack1 = null; - - if (objects[i + 1] instanceof Item) - { - itemstack1 = new ItemStack((Item) objects[i + 1]); - } else if (objects[i + 1] instanceof Block) - { - itemstack1 = new ItemStack((Block) objects[i + 1], 1); - } else if (objects[i + 1] instanceof ItemStack) - { - itemstack1 = (ItemStack) objects[i + 1]; - } - - hashmap.put(character, itemstack1); - } - - ItemStack[] aitemstack = new ItemStack[j * k]; - - for (int i1 = 0; i1 < j * k; ++i1) - { - char c0 = s.charAt(i1); - - if (hashmap.containsKey(Character.valueOf(c0))) - { - aitemstack[i1] = ((ItemStack) hashmap.get(Character.valueOf(c0))).copy(); - } else - { - aitemstack[i1] = null; - } - } - //recipe.array = aitemstack; - return aitemstack; - } - -} diff --git a/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipesList.java b/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipesList.java index a0d92538..6c610d76 100644 --- a/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipesList.java +++ b/src/main/java/com/darkona/adventurebackpack/init/recipes/BackpackRecipesList.java @@ -1,12 +1,14 @@ package com.darkona.adventurebackpack.init.recipes; -import com.darkona.adventurebackpack.init.ModItems; -import com.darkona.adventurebackpack.reference.BackpackNames; +import java.util.List; + import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import java.util.List; +import com.darkona.adventurebackpack.init.ModItems; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.BackpackUtils; /** * Created on 20/10/2014 @@ -15,13 +17,12 @@ */ public class BackpackRecipesList { - public List recipes; public BackpackRecipesList() { String[] covered = {"XXX", "XaX", "XXX"}; - ItemStack backpack = BackpackNames.setBackpackColorNameFromDamage(new ItemStack(ModItems.adventureBackpack), 0); + ItemStack backpack = BackpackUtils.createBackpackStack(BackpackTypes.STANDARD); ItemStack woolWhite = new ItemStack(Blocks.wool, 1, 0); ItemStack woolOrange = new ItemStack(Blocks.wool, 1, 1); @@ -40,7 +41,6 @@ public BackpackRecipesList() ItemStack woolRed = new ItemStack(Blocks.wool, 1, 14); ItemStack woolBlack = new ItemStack(Blocks.wool, 1, 15); - Standard = reviewRecipe( "LGL", "TCT", @@ -114,6 +114,15 @@ public BackpackRecipesList() 'm', Items.milk_bucket ); + ModdedNetwork = reviewRecipe( + "EEE", + "DaD", + "DDD", + 'a', backpack, + 'E', Items.emerald, + 'D', Items.diamond + ); + Chest = reviewRecipe( "CWC", "WaW", @@ -678,11 +687,10 @@ public BackpackRecipesList() public final Object[] Wolf; public final Object[] Yellow; public final Object[] Zombie; - + public final Object[] ModdedNetwork; public static Object[] reviewRecipe(Object... objects) { return objects; } - } diff --git a/src/main/java/com/darkona/adventurebackpack/init/recipes/ShapedBackpackRecipe.java b/src/main/java/com/darkona/adventurebackpack/init/recipes/ShapedBackpackRecipe.java new file mode 100644 index 00000000..3d729d76 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/init/recipes/ShapedBackpackRecipe.java @@ -0,0 +1,62 @@ +package com.darkona.adventurebackpack.init.recipes; + +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.oredict.RecipeSorter; +import net.minecraftforge.oredict.ShapedOreRecipe; + +import com.darkona.adventurebackpack.init.ModItems; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.LogHelper; + +import static com.darkona.adventurebackpack.common.Constants.TAG_INVENTORY; + +/** + * Created on 03.03.2018 + * + * @author Ugachaga + */ +public class ShapedBackpackRecipe extends ShapedOreRecipe +{ + static + { + RecipeSorter.register(ModInfo.MOD_ID + ":shapedbackpackrecipe", ShapedBackpackRecipe.class, + RecipeSorter.Category.SHAPED,"after:forge:shapedore before:minecraft:shapeless"); + } + + public ShapedBackpackRecipe(ItemStack result, Object... recipe) + { + super(result, recipe); + } + + @Override + public ItemStack getCraftingResult(InventoryCrafting craftMatrix) + { + ItemStack craftResult = super.getCraftingResult(craftMatrix); + + if (!(craftResult.getItem() == ModItems.adventureBackpack)) + return craftResult; // in case recipe is using backpack only as ingredient + + for (int i = 0; i < craftMatrix.getSizeInventory(); i++) + { + ItemStack matrixStack = craftMatrix.getStackInSlot(i); + if (matrixStack != null && matrixStack.getItem() == ModItems.adventureBackpack + && BackpackUtils.getWearableCompound(matrixStack).hasKey(TAG_INVENTORY)) + { + NBTTagList itemList = BackpackUtils.getWearableInventory(matrixStack); + BackpackUtils.getWearableCompound(craftResult).setTag(TAG_INVENTORY, itemList); + + LogHelper.info("Successfully transferred inventory from the ingredient backpack [" + + BackpackTypes.getSkinName(matrixStack) + "] to the crafted backpack [" + + BackpackTypes.getSkinName(craftResult) + "]"); + + break; // copy inventory content only from the 1st found backpack in the craftMatrix + } + } + + return craftResult; + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/ContainerAdventure.java b/src/main/java/com/darkona/adventurebackpack/inventory/ContainerAdventure.java new file mode 100644 index 00000000..7ca6b29d --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/ContainerAdventure.java @@ -0,0 +1,281 @@ +package com.darkona.adventurebackpack.inventory; + +import javax.annotation.Nullable; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +import com.darkona.adventurebackpack.common.Constants.Source; + +/** + * Created on 10.04.2017 + * + * @author Ugachaga + */ +@SuppressWarnings("WeakerAccess") +public abstract class ContainerAdventure extends Container +{ + protected static final int PLAYER_INV_ROWS = 3; + protected static final int PLAYER_INV_COLUMNS = 9; + protected static final int PLAYER_HOT_START = 0; + protected static final int PLAYER_HOT_END = PLAYER_HOT_START + PLAYER_INV_COLUMNS - 1; + protected static final int PLAYER_INV_END = PLAYER_HOT_END + PLAYER_INV_COLUMNS * PLAYER_INV_ROWS; + protected static final int PLAYER_INV_LENGTH = PLAYER_INV_END + 1; + + protected final EntityPlayer player; + protected final IInventoryTanks inventory; + protected final Source source; + + private final int[] fluidsAmount; + private int itemsCount; + private boolean requestedUpdate; + + protected ContainerAdventure(EntityPlayer player, IInventoryTanks inventory, Source source) + { + this.player = player; + this.inventory = inventory; + this.source = source; + this.fluidsAmount = new int[this.inventory.getTanksArray().length]; + } + + protected void bindPlayerInventory(InventoryPlayer invPlayer, int startX, int startY) + { + for (int col = 0; col < PLAYER_INV_COLUMNS; col++) // hotbar - 9 slots + addSlotToContainer(new Slot(invPlayer, col, (startX + 18 * col), (58 + startY))); + + for (int row = 0; row < PLAYER_INV_ROWS; row++) // inventory - 3*9, 27 slots + for (int col = 0; col < PLAYER_INV_COLUMNS; col++) + addSlotToContainer(new Slot(invPlayer, (PLAYER_INV_COLUMNS + row * PLAYER_INV_COLUMNS + col), (startX + 18 * col), (startY + row * 18))); + } + + @Override + public void detectAndSendChanges() + { + super.detectAndSendChanges(); + + if (source == Source.HOLDING) // used for refresh tooltips and redraw tanks content while GUI is open + { + // intentionally update container with 1 tick delay after detect changes due to visual glitches + // in rare cases on some modded items, ex.: shift+q on blood magic lava crystals + if (requestedUpdate && player instanceof EntityPlayerMP) + { + ((EntityPlayerMP) player).sendContainerAndContentsToPlayer(this, this.getInventory()); + requestedUpdate = false; + } + + if (detectItemChanges() | detectFluidChanges()) + { + requestedUpdate = true; + } + } + } + + protected boolean detectItemChanges() + { + ItemStack[] inv = inventory.getInventory(); + int tempCount = 0; + for (int i = 0; i < inv.length - inventory.getSlotsOnClosing().length; i++) + { + if (inv[i] != null) + tempCount++; + } + if (itemsCount != tempCount) + { + itemsCount = tempCount; + return true; + } + return false; + } + + private boolean detectFluidChanges() + { + boolean changesDetected = false; + for (int i = 0; i < fluidsAmount.length; i++) + { + int amount = inventory.getTanksArray()[i].getFluidAmount(); + if (fluidsAmount[i] != amount) + { + fluidsAmount[i] = amount; + changesDetected = true; + } + } + return changesDetected; + } + + @Nullable + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int fromSlot) + { + Slot slot = getSlot(fromSlot); + + if (slot == null || slot.getStack() == null) + return null; + + ItemStack stack = slot.getStack(); + ItemStack result = stack.copy(); + + if (fromSlot < PLAYER_INV_LENGTH) + { + if (!transferStackToPack(stack)) + return null; + } + else + { + if (!mergePlayerInv(stack)) + return null; + } + + if (stack.stackSize == 0) + { + slot.putStack(null); + } + else + { + slot.onSlotChanged(); + } + + if (stack.stackSize == result.stackSize) + return null; + + slot.onPickupFromSlot(player, stack); + return result; + } + + protected boolean mergePlayerInv(ItemStack stack) + { + return mergeItemStack(stack, PLAYER_HOT_START, PLAYER_INV_END + 1, false); + } + + protected abstract boolean transferStackToPack(ItemStack stack); + + @Nullable + @Override + public ItemStack slotClick(int slot, int button, int flag, EntityPlayer player) + { + if (source == Source.HOLDING && slot >= 0) + { + if (getSlot(slot) != null && getSlot(slot).getStack() == player.getHeldItem()) + { + return null; + } + if (flag == 2 && getSlot(button).getStack() == player.getHeldItem()) + { + return null; + } + } + return super.slotClick(slot, button, flag, player); + } + + @Override + public boolean canInteractWith(EntityPlayer player) + { + return inventory.isUseableByPlayer(player); + } + + @Override + protected boolean mergeItemStack(ItemStack initStack, int minIndex, int maxIndex, boolean backward) + { + boolean changesMade = false; + int activeIndex = (backward ? maxIndex - 1 : minIndex); + Slot activeSlot; + ItemStack activeStack; + + if (initStack.isStackable()) + { + while (initStack.stackSize > 0 && (!backward && activeIndex < maxIndex || backward && activeIndex >= minIndex)) + { + activeSlot = (Slot) this.inventorySlots.get(activeIndex); + activeStack = activeSlot.getStack(); + + if (activeStack != null && activeStack.getItem() == initStack.getItem() + && (!initStack.getHasSubtypes() || initStack.getItemDamage() == activeStack.getItemDamage()) + && ItemStack.areItemStackTagsEqual(initStack, activeStack)) + { + int mergedSize = activeStack.stackSize + initStack.stackSize; + int maxStackSize = Math.min(initStack.getMaxStackSize(), activeSlot.getSlotStackLimit()); + + if (mergedSize <= maxStackSize) + { + initStack.stackSize = 0; + activeStack.stackSize = mergedSize; + activeSlot.onSlotChanged(); + changesMade = true; + } + else if (activeStack.stackSize < maxStackSize && !(activeSlot instanceof SlotFluid)) + { + initStack.stackSize -= maxStackSize - activeStack.stackSize; + activeStack.stackSize = maxStackSize; + activeSlot.onSlotChanged(); + changesMade = true; + } + } + activeIndex += (backward ? -1 : 1); + } + } + + if (initStack.stackSize > 0) + { + activeIndex = (backward ? maxIndex - 1 : minIndex); + + while (!backward && activeIndex < maxIndex || backward && activeIndex >= minIndex) + { + activeSlot = (Slot) this.inventorySlots.get(activeIndex); + activeStack = activeSlot.getStack(); + + if (activeStack == null /*&& activeSlot.isItemValid(initStack)*/) + { + ItemStack copyStack = initStack.copy(); + int mergedSize = copyStack.stackSize = Math.min(copyStack.stackSize, activeSlot.getSlotStackLimit()); + + activeSlot.putStack(copyStack); + if (mergedSize >= initStack.stackSize) + { + initStack.stackSize = 0; + } + else + { + initStack.stackSize -= mergedSize; + } + changesMade = true; + break; + } + activeIndex += (backward ? -1 : 1); + } + } + + return changesMade; + } + + @Override + public void onContainerClosed(EntityPlayer player) + { + super.onContainerClosed(player); + + if (source == Source.WEARING) //TODO no idea why this is here (preventing dupe on closing?), and why only for wearing + { + this.crafters.remove(player); + } + + if (!player.worldObj.isRemote) + { + dropContentOnClose(); + } + } + + protected void dropContentOnClose() + { + for (int i = 0; i < inventory.getSizeInventory(); i++) + { + ItemStack itemstack = inventory.getStackInSlotOnClosing(i); + if (itemstack != null) + { + inventory.setInventorySlotContents(i, null); + player.dropPlayerItemWithRandomChoice(itemstack, false); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/ContainerBackpack.java b/src/main/java/com/darkona/adventurebackpack/inventory/ContainerBackpack.java index 205371fc..c200cd23 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/ContainerBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/ContainerBackpack.java @@ -1,378 +1,288 @@ package com.darkona.adventurebackpack.inventory; -import com.darkona.adventurebackpack.common.Constants; -import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; -import com.darkona.adventurebackpack.item.ItemAdventureBackpack; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.*; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCraftResult; +import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; +import net.minecraftforge.fluids.FluidTank; + +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.common.Constants.Source; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.util.TinkersUtils; + +import static com.darkona.adventurebackpack.common.Constants.BUCKET_IN_LEFT; +import static com.darkona.adventurebackpack.common.Constants.BUCKET_IN_RIGHT; +import static com.darkona.adventurebackpack.common.Constants.BUCKET_OUT_LEFT; +import static com.darkona.adventurebackpack.common.Constants.BUCKET_OUT_RIGHT; +import static com.darkona.adventurebackpack.common.Constants.TOOL_LOWER; +import static com.darkona.adventurebackpack.common.Constants.TOOL_UPPER; /** * Created on 12/10/2014 - * @author Darkona * + * @author Darkona */ -public class ContainerBackpack extends Container implements IWearableContainer +public class ContainerBackpack extends ContainerAdventure { - - public IInventoryAdventureBackpack inventory; - public static byte SOURCE_TILE = 0; - public static byte SOURCE_WEARING = 1; - public static byte SOURCE_HOLDING = 2; - public byte source; - public InventoryCrafting craftMatrix = new InventoryCrafting(this, 3, 3); - public IInventory craftResult = new InventoryCraftResult(); - EntityPlayer player; - - private final int - PLAYER_HOT_START = 0, - PLAYER_HOT_END = PLAYER_HOT_START + 8, - PLAYER_INV_START = PLAYER_HOT_END + 1, - PLAYER_INV_END = PLAYER_INV_START + 26, - BACK_INV_START = PLAYER_INV_END + 1, - BACK_INV_END = BACK_INV_START + 38, - TOOL_START = BACK_INV_END + 1, - TOOL_END = TOOL_START + 1, - BUCKET_LEFT = TOOL_END + 1, - BUCKET_RIGHT = BUCKET_LEFT + 2; - - public ContainerBackpack(EntityPlayer player, IInventoryAdventureBackpack backpack, byte source) + private static final int BACK_INV_ROWS = 6; + private static final int BACK_INV_COLUMNS = 8; + private static final int BACK_INV_START = PLAYER_INV_END + 1; + private static final int BACK_INV_END = PLAYER_INV_END + (BACK_INV_ROWS * BACK_INV_COLUMNS); + private static final int TOOL_START = BACK_INV_END + 1; + private static final int TOOL_END = TOOL_START + 1; + private static final int BUCKET_LEFT = TOOL_END + 1; + private static final int BUCKET_RIGHT = BUCKET_LEFT + 2; + private static final int MATRIX_DIMENSION = 3; + private static final int CRAFT_RESULT = BUCKET_RIGHT + 2 + (MATRIX_DIMENSION * MATRIX_DIMENSION); + private static final int[] CRAFT_MATRIX_EMULATION = findCraftMatrixEmulationIDs(); + + private InventoryCraftingBackpack craftMatrix = new InventoryCraftingBackpack(this, MATRIX_DIMENSION, MATRIX_DIMENSION); + private IInventory craftResult = new InventoryCraftResult(); + + public ContainerBackpack(EntityPlayer player, IInventoryBackpack backpack, Source source) { - this.player = player; - inventory = backpack; + super(player, backpack, source); makeSlots(player.inventory); inventory.openInventory(); - this.source = source; } - public IInventoryAdventureBackpack getInventoryBackpack() + public IInventoryBackpack getInventoryBackpack() { - return inventory; + return (IInventoryBackpack) inventory; } - private void bindPlayerInventory(InventoryPlayer invPlayer) + private void makeSlots(InventoryPlayer invPlayer) { - int startX = 44; - int startY = 125; + bindPlayerInventory(invPlayer, 44, 125); // 4*9 playerInventory, 36 Slots [0-35] - // Player's Hotbar - for (int x = 0; x < 9; x++) - { - addSlotToContainer(new Slot(invPlayer, x, startX + 18 * x, 183)); - } + int startX = 62; + int startY = 7; + for (int row = 0; row < BACK_INV_ROWS; row++) // 6*8 inventory, 48 Slots (#1-#48) [36-83] + for (int col = 0; col < BACK_INV_COLUMNS; col++) + addSlotToContainer(new SlotBackpack(inventory, (row * BACK_INV_COLUMNS + col), (startX + 18 * col), (startY + 18 * row))); + + addSlotToContainer(new SlotTool(inventory, TOOL_UPPER, 44, 79)); // #49 [84] + addSlotToContainer(new SlotTool(inventory, TOOL_LOWER, 44, 97)); // #50 [85] + + addSlotToContainer(new SlotFluid(inventory, BUCKET_IN_LEFT, 6, 7)); // #51 [86] + addSlotToContainer(new SlotFluid(inventory, BUCKET_OUT_LEFT, 6, 37)); // #52 [87] + addSlotToContainer(new SlotFluid(inventory, BUCKET_IN_RIGHT, 226, 7)); // #53 [88] + addSlotToContainer(new SlotFluid(inventory, BUCKET_OUT_RIGHT, 226, 37)); // #54 [89] + + startX = 215; + startY = -2500; //startY = LoadedMods.DEV_ENV ? 125 : -2500; + for (int row = 0; row < MATRIX_DIMENSION; row++) // craftMatrix, usually 9 slots, [90-98] + for (int col = 0; col < MATRIX_DIMENSION; col++) + addSlotToContainer(new SlotCraftMatrix(craftMatrix, (row * MATRIX_DIMENSION + col), (startX + 18 * col), (startY + 18 * row))); + + addSlotToContainer(new SlotCraftResult(this, invPlayer.player, craftMatrix, craftResult, 0, 226, 97)); // craftResult [99] + syncCraftMatrixWithInventory(true); + } - // Player's Inventory - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlotToContainer(new Slot(invPlayer, (x + y * 9 + 9), (startX + 18 * x), (startY + y * 18))); - } - } - //Total 36 slots + @Override + public void detectAndSendChanges() + { + syncCraftResultToServer(); + super.detectAndSendChanges(); } - private void makeSlots(InventoryPlayer invPlayer) + @SuppressWarnings("unchecked") + private void syncCraftResultToServer() { + ItemStack stackA = ((Slot) inventorySlots.get(CRAFT_RESULT)).getStack(); + ItemStack stackB = (ItemStack) inventoryItemStacks.get(CRAFT_RESULT); - bindPlayerInventory(invPlayer); + if (!ItemStack.areItemStacksEqual(stackB, stackA)) + { + stackB = stackA == null ? null : stackA.copy(); + inventoryItemStacks.set(CRAFT_RESULT, stackB); - // Backpack Inventory - int startX = 62; - int startY = 7; - int slot = 0; + if (player instanceof EntityPlayerMP) + ((EntityPlayerMP) player).sendContainerAndContentsToPlayer(this, this.getInventory()); + } + } - // 24 Slots - for (int i = 0; i < 3; i++) + @Override + protected boolean transferStackToPack(ItemStack stack) + { + if (SlotTool.isValidTool(stack)) { - for (int j = 0; j < 8; j++) - { - int offsetX = startX + (18 * j); - int offsetY = startY + (18 * i); - addSlotToContainer(new SlotBackpack(inventory, slot++, offsetX, offsetY)); - } + if (!mergeToolSlot(stack)) + if (SlotBackpack.isValidItem(stack)) + return mergeBackpackInv(stack); } - - // 15 Slots - startY = 61; - for (int i = 0; i < 3; i++) + else if (SlotFluid.isContainer(stack) && !isHoldingSpace()) { - for (int j = 0; j < 5; j++) - { - int offsetX = startX + (18 * j); - int offsetY = startY + (18 * i); - addSlotToContainer(new SlotBackpack(inventory, slot++, offsetX, offsetY)); - } + return transferFluidContainer(stack); } + else if (SlotBackpack.isValidItem(stack)) + { + return mergeBackpackInv(stack); + } + return true; + } - //Upper Tool Slot - addSlotToContainer(new SlotTool(inventory, Constants.upperTool, 44, 79));// Upper Tool 16 - //Lower Tool slot - addSlotToContainer(new SlotTool(inventory, Constants.lowerTool, 44, 97));// Lower Tool 17 - - //Bucket Slots - - // bucket in left 18 - addSlotToContainer(new SlotFluid(inventory, Constants.bucketInLeft, 6, 7)); - // bucket out left 19 - addSlotToContainer(new SlotFluid(inventory, Constants.bucketOutLeft, 6, 37)); - // bucket in right 20 - addSlotToContainer(new SlotFluid(inventory, Constants.bucketInRight, 226, 7)); - // bucket out right 21 - addSlotToContainer(new SlotFluid(inventory, Constants.bucketOutRight, 226, 37)); + private boolean mergeToolSlot(ItemStack stack) + { + return mergeItemStack(stack, TOOL_START, TOOL_END + 1, false); + } + private boolean mergeBackpackInv(ItemStack stack) + { + return mergeItemStack(stack, BACK_INV_START, BACK_INV_END + 1, false); + } - //Craft Matrix - startX = 152; - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 3; x++) - { - int offsetX = startX + (18 * x); - int offsetY = startY + (18 * y); - addSlotToContainer(new Slot(craftMatrix, (x + y * 3), offsetX, offsetY)); - } - } - addSlotToContainer(new SlotCrafting(invPlayer.player, craftMatrix, craftResult, 0, 226, 97)); - this.onCraftMatrixChanged(craftMatrix); + private boolean mergeLeftBucket(ItemStack stack) + { + return mergeItemStack(stack, BUCKET_LEFT, BUCKET_LEFT + 1, false); } - @Override - public boolean canInteractWith(EntityPlayer player) + private boolean mergeRightBucket(ItemStack stack) { - return inventory.isUseableByPlayer(player); + return mergeItemStack(stack, BUCKET_RIGHT, BUCKET_RIGHT + 1, false); } - @Override - public void onCraftMatrixChanged(IInventory par1IInventory) + private boolean isHoldingSpace() { - craftResult.setInventorySlotContents(0, CraftingManager.getInstance().findMatchingRecipe(craftMatrix, player.worldObj)); + return getInventoryBackpack().getExtendedProperties().hasKey(Constants.TAG_HOLDING_SPACE); } - @Override - public void onContainerClosed(EntityPlayer player) + private boolean transferFluidContainer(ItemStack container) { - super.onContainerClosed(player); - if(source == SOURCE_WEARING) + FluidTank leftTank = getInventoryBackpack().getLeftTank(); + FluidTank rightTank = getInventoryBackpack().getRightTank(); + ItemStack leftStackOut = getSlot(BUCKET_LEFT + 1).getStack(); + ItemStack rightStackOut = getSlot(BUCKET_RIGHT + 1).getStack(); + + boolean isLeftTankEmpty = SlotFluid.isEmpty(leftTank); + boolean isRightTankEmpty = SlotFluid.isEmpty(rightTank); + boolean suitableToLeft = SlotFluid.isEqualAndCanFit(container, leftTank); + boolean suitableToRight = SlotFluid.isEqualAndCanFit(container, rightTank); + boolean areLeftSameType = InventoryActions.areContainersOfSameType(container, leftStackOut); + boolean areRightSameType = InventoryActions.areContainersOfSameType(container, rightStackOut); + + if (SlotFluid.isFilled(container)) { - this.crafters.remove(player); + if (isLeftTankEmpty) + { + if (!isRightTankEmpty && suitableToRight && (rightStackOut == null || areRightSameType)) + return mergeRightBucket(container); + else if (leftStackOut == null || areLeftSameType) + return mergeLeftBucket(container); + } + else + { + if (suitableToLeft && (leftStackOut == null || areLeftSameType)) + return mergeLeftBucket(container); + else if ((isRightTankEmpty || suitableToRight) && (rightStackOut == null || areRightSameType)) + return mergeRightBucket(container); + else if (leftStackOut == null && rightStackOut == null && SlotBackpack.isValidItem(container)) + return mergeBackpackInv(container); + } } - if (!player.worldObj.isRemote) + else if (SlotFluid.isEmpty(container)) { - for (int i = 0; i < inventory.getSizeInventory(); i++) + if (isLeftTankEmpty) { - ItemStack itemstack = this.inventory.getStackInSlotOnClosing(i); - if (itemstack != null) - { - inventory.setInventorySlotContents(i, null); - player.dropPlayerItemWithRandomChoice(itemstack, false); - } + if (!isRightTankEmpty && (rightStackOut == null || areRightSameType)) + return mergeRightBucket(container); + else if (leftStackOut == null && rightStackOut == null && SlotBackpack.isValidItem(container)) + return mergeBackpackInv(container); } - - for (int i = 0; i < 9; i++) + else { - ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i); - - if (itemstack != null) - { - player.dropPlayerItemWithRandomChoice(itemstack, false); - } + if (leftStackOut == null || areLeftSameType) + return mergeLeftBucket(container); } } + return false; } @Override public ItemStack slotClick(int slot, int button, int flag, EntityPlayer player) { - if (slot >= 0 && getSlot(slot) != null && getSlot(slot).getStack() == player.getHeldItem() && source == SOURCE_HOLDING) - { - return null; - } - return super.slotClick(slot, button, flag, player); + final ItemStack result = super.slotClick(slot, button, flag, player); + syncCraftMatrixWithInventory(true); + return result; } @Override - protected boolean mergeItemStack(ItemStack stack, int minSlot, int maxSlot, boolean direction) + protected void dropContentOnClose() { - boolean changesMade = false; - int slotInit = minSlot; - - if (direction) - { - slotInit = maxSlot - 1; - } - - Slot slot; - ItemStack newItemStack; - - if (stack.isStackable()) + for (int i = 0; i < craftMatrix.getSizeInventory(); i++) { - while (stack.stackSize > 0 && (!direction && slotInit < maxSlot || direction && slotInit >= minSlot)) - { - slot = (Slot) this.inventorySlots.get(slotInit); - newItemStack = slot.getStack(); - - if (newItemStack != null && newItemStack.getItem() == stack.getItem() && (!stack.getHasSubtypes() || stack.getItemDamage() == newItemStack.getItemDamage()) && ItemStack.areItemStackTagsEqual(stack, newItemStack)) - { - - int newStackSize = newItemStack.stackSize + stack.stackSize; - - if (newStackSize <= stack.getMaxStackSize()) - { - stack.stackSize = 0; - newItemStack.stackSize = newStackSize; - slot.onSlotChanged(); - changesMade = true; - } else if (newItemStack.stackSize < stack.getMaxStackSize()) - { - stack.stackSize -= stack.getMaxStackSize() - newItemStack.stackSize; - newItemStack.stackSize = stack.getMaxStackSize(); - slot.onSlotChanged(); - changesMade = true; - } - } - - if (direction) - { - --slotInit; - } else - { - ++slotInit; - } - } - } - - if (stack.stackSize > 0) - { - if (direction) - { - slotInit = maxSlot - 1; - } else - { - slotInit = minSlot; - } - - while (!direction && slotInit < maxSlot || direction && slotInit >= minSlot) - { - slot = (Slot) this.inventorySlots.get(slotInit); - newItemStack = slot.getStack(); - - if (newItemStack == null) - { - slot.putStack(stack.copy()); - slot.onSlotChanged(); - stack.stackSize = 0; - changesMade = true; - break; - } - - if (direction) - { - --slotInit; - } else - { - ++slotInit; - } - } + this.craftMatrix.setInventorySlotContentsNoUpdate(i, null); } + onCraftMatrixChanged(craftMatrix); - return changesMade; + super.dropContentOnClose(); } @Override - public Slot getSlotFromInventory(IInventory inv, int slot) + public void onCraftMatrixChanged(IInventory inventory) { - return super.getSlotFromInventory(inv, slot); + if (ConfigHandler.tinkerToolsMaintenance && TinkersUtils.isToolOrWeapon(craftMatrix.getStackInSlot(4))) + craftResult.setInventorySlotContents(0, TinkersUtils.getTinkersRecipe(craftMatrix)); + else + craftResult.setInventorySlotContents(0, CraftingManager.getInstance().findMatchingRecipe(craftMatrix, player.worldObj)); } - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int i) + protected void syncCraftMatrixWithInventory(boolean preCraft) { - if(source == SOURCE_WEARING)refresh(); - Slot slot = getSlot(i); - ItemStack result = null; - if (slot != null && slot.getHasStack()) + boolean changesMade = false; + + for (int craftSlotID = 0; craftSlotID < CRAFT_MATRIX_EMULATION.length; craftSlotID++) { - ItemStack stack = slot.getStack(); - result = stack.copy(); - if (i >= 36) + int invSlotID = CRAFT_MATRIX_EMULATION[craftSlotID]; + ItemStack invStack = inventory.getStackInSlot(invSlotID); + ItemStack craftStack = craftMatrix.getStackInSlot(craftSlotID); + + if (!ItemStack.areItemStacksEqual(invStack, craftStack)) { - if (!mergeItemStack(stack, PLAYER_HOT_START, PLAYER_INV_END + 1, false)) + if (preCraft) { - return null; + craftStack = invStack == null ? null : invStack.copy(); + craftMatrix.setInventorySlotContentsNoUpdate(craftSlotID, craftStack); } - } - if (i < 36) - { - if (SlotTool.isValidTool(stack)) - { - if (!mergeItemStack(stack, TOOL_START, TOOL_END + 1, false)) - { - if (!mergeItemStack(stack, BACK_INV_START, BACK_INV_END + 1, false)) - { - return null; - } - } - } else if (SlotFluid.valid(stack)) + else { - if (!mergeItemStack(stack, BUCKET_LEFT, BUCKET_LEFT + 1, false)) - { - if (!mergeItemStack(stack, BUCKET_RIGHT, BUCKET_RIGHT + 1, false)) - { - if (!mergeItemStack(stack, BACK_INV_START, BACK_INV_END + 1, false)) - { - return null; - } - } - } - - - } else if (!(stack.getItem() instanceof ItemAdventureBackpack)) - { - if (!mergeItemStack(stack, BACK_INV_START, BACK_INV_END + 1, false)) - { - return null; - } + invStack = craftStack == null ? null : craftStack.copy(); + inventory.setInventorySlotContentsNoSave(invSlotID, invStack); } + changesMade = true; } - if (stack.stackSize == 0) - { - slot.putStack(null); - } else - { - slot.onSlotChanged(); - } + } - if (stack.stackSize == result.stackSize) - { - return null; - } - slot.onPickupFromSlot(player, stack); + if (changesMade) + { + if (preCraft) + onCraftMatrixChanged(craftMatrix); + else + inventory.markDirty(); } - return result; } /** - * Looks for changes made in the container, sends them to every listener. + * Returns the array of inventory slotIDs, emulates the craftMatrix in the lower right corner of the inventory. */ - @Override - public void detectAndSendChanges() + private static int[] findCraftMatrixEmulationIDs() { - refresh(); - super.detectAndSendChanges(); - /* if(source == SOURCE_WEARING && player instanceof EntityPlayerMP) - { - ((EntityPlayerMP) player).sendContainerAndContentsToPlayer(this, inventoryItemStacks); - BackpackProperty.syncToNear(player); - }*/ - } - - @Override - public void refresh() - { - inventory.openInventory(); - this.onCraftMatrixChanged(craftMatrix); + int[] slotsArray = new int[MATRIX_DIMENSION * MATRIX_DIMENSION]; + for (int row = 0; row < MATRIX_DIMENSION; row++) + { + for (int col = 0; col < MATRIX_DIMENSION; col++) + { + int id = row * MATRIX_DIMENSION + col; + int fullRowSum = (BACK_INV_ROWS - (MATRIX_DIMENSION - 1) + row) * BACK_INV_COLUMNS; + int columnShift = (MATRIX_DIMENSION - 1) - col; + slotsArray[id] = fullRowSum - columnShift - 1; + } + } + return slotsArray; } -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/ContainerCopter.java b/src/main/java/com/darkona/adventurebackpack/inventory/ContainerCopter.java index 74560074..f7cfc555 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/ContainerCopter.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/ContainerCopter.java @@ -2,165 +2,68 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidTank; + +import com.darkona.adventurebackpack.common.Constants.Source; + +import static com.darkona.adventurebackpack.common.Constants.Copter.BUCKET_IN; +import static com.darkona.adventurebackpack.common.Constants.Copter.BUCKET_OUT; /** * Created on 03/01/2015 * * @author Darkona */ -public class ContainerCopter extends Container implements IWearableContainer +public class ContainerCopter extends ContainerAdventure { + private static final int COPTER_INV_START = PLAYER_INV_END + 1; - public InventoryCopterPack inventory; - private final int - PLAYER_HOT_START = 0; - private final int PLAYER_HOT_END = PLAYER_HOT_START + 8; - private final int PLAYER_INV_START = PLAYER_HOT_END + 1; - private final int PLAYER_INV_END = PLAYER_INV_START + 26; - EntityPlayer player; - boolean wearing; - - public ContainerCopter(EntityPlayer player, InventoryCopterPack copterPack, boolean wearing) + public ContainerCopter(EntityPlayer player, InventoryCopterPack copter, Source source) { - this.inventory = copterPack; + super(player, copter, source); makeSlots(player.inventory); inventory.openInventory(); - this.player = player; - this.wearing = wearing; - } - - private void bindPlayerInventory(InventoryPlayer invPlayer) - { - int startX = 8; - int startY = 84; - - // Player's Hotbar - for (int x = 0; x < 9; x++) - { - addSlotToContainer(new Slot(invPlayer, x, startX + 18 * x, 142)); - } - - // Player's Inventory - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlotToContainer(new Slot(invPlayer, (x + y * 9 + 9), (startX + 18 * x), (startY + y * 18))); - } - } - //Total 36 slots } private void makeSlots(InventoryPlayer invPlayer) { + bindPlayerInventory(invPlayer, 8, 84); - bindPlayerInventory(invPlayer); - int slot = 0; - //Bucket Slots - // bucket in - addSlotToContainer(new SlotFluid(inventory, slot++, 44, 23)); - // bucket out - addSlotToContainer(new SlotFluid(inventory, slot++, 44, 53)); - } - - @Override - public boolean canInteractWith(EntityPlayer p_75145_1_) - { - return true; + addSlotToContainer(new SlotFluidFuel(inventory, BUCKET_IN, 44, 23)); + addSlotToContainer(new SlotFluidFuel(inventory, BUCKET_OUT, 44, 53)); } @Override - public void onContainerClosed(EntityPlayer player) + public boolean transferStackToPack(ItemStack stack) { - super.onContainerClosed(player); - if (wearing) + if (SlotFluid.isContainer(stack)) { - this.crafters.remove(player); - } - if (!player.worldObj.isRemote) - { - for (int i = 0; i < inventory.getSizeInventory(); i++) - { - ItemStack itemstack = this.inventory.getStackInSlotOnClosing(i); - if (itemstack != null) - { - inventory.setInventorySlotContents(i, null); - player.dropPlayerItemWithRandomChoice(itemstack, false); - } - } - } - } + FluidTank fuelTank = ((InventoryCopterPack) inventory).getFuelTank(); + ItemStack stackOut = getSlot(COPTER_INV_START + 1).getStack(); - @Override - public ItemStack slotClick(int slot, int button, int flag, EntityPlayer player) - { - if (slot >= 0 && getSlot(slot) != null && getSlot(slot).getStack() == player.getHeldItem() && !wearing) - { - return null; - } - return super.slotClick(slot, button, flag, player); - } - - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int i) - { - Slot slot = getSlot(i); - ItemStack result = null; - - if (slot != null && slot.getHasStack()) - { - ItemStack stack = slot.getStack(); - result = stack.copy(); - if (i >= 36) - { - if (!mergeItemStack(stack, PLAYER_HOT_START, PLAYER_INV_END + 1, false)) - { - return null; - } - } - if (i < 36) - { - if (SlotFluid.valid(stack)) - { - int COPTER_INV_START = PLAYER_INV_END + 1; - if (!mergeItemStack(stack, COPTER_INV_START, COPTER_INV_START + 1, false)) - { - return null; - } - } - } + boolean isFuelTankEmpty = SlotFluid.isEmpty(fuelTank); + boolean suitableToTank = SlotFluid.isEqualAndCanFit(stack, fuelTank); + boolean areSameType = InventoryActions.areContainersOfSameType(stack, stackOut); - if (stack.stackSize == 0) + if (SlotFluid.isFilled(stack)) { - slot.putStack(null); - } else - { - slot.onSlotChanged(); + if ((stackOut == null || areSameType) && SlotFluidFuel.isValidItem(stack)) + if (isFuelTankEmpty || suitableToTank) + return mergeBucket(stack); } - - if (stack.stackSize == result.stackSize) + else if (SlotFluid.isEmpty(stack)) { - return null; + if ((stackOut == null || areSameType) && SlotFluidFuel.isValidItem(stack)) + if (!isFuelTankEmpty) + return mergeBucket(stack); } - slot.onPickupFromSlot(player, stack); } - return result; - } - - @Override - public void detectAndSendChanges() - { - refresh(); - super.detectAndSendChanges(); + return true; } - @Override - public void refresh() + private boolean mergeBucket(ItemStack stack) { - inventory.openInventory(); + return mergeItemStack(stack, COPTER_INV_START, COPTER_INV_START + 1, false); } } diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/ContainerJetpack.java b/src/main/java/com/darkona/adventurebackpack/inventory/ContainerJetpack.java index ac3de1e8..db18ade1 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/ContainerJetpack.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/ContainerJetpack.java @@ -1,176 +1,96 @@ package com.darkona.adventurebackpack.inventory; -import com.darkona.adventurebackpack.playerProperties.BackpackProperty; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidTank; + +import com.darkona.adventurebackpack.common.Constants.Source; + +import static com.darkona.adventurebackpack.common.Constants.Jetpack.BUCKET_IN; +import static com.darkona.adventurebackpack.common.Constants.Jetpack.BUCKET_OUT; +import static com.darkona.adventurebackpack.common.Constants.Jetpack.FUEL_SLOT; /** * Created on 15/01/2015 * * @author Darkona */ -public class ContainerJetpack extends Container implements IWearableContainer +public class ContainerJetpack extends ContainerAdventure { - InventorySteamJetpack inventory; - EntityPlayer player; - private final int - PLAYER_HOT_START = 0; - private final int PLAYER_HOT_END = PLAYER_HOT_START + 8; - private final int PLAYER_INV_START = PLAYER_HOT_END + 1; - private final int PLAYER_INV_END = PLAYER_INV_START + 26; - boolean wearing; + private static final int JETPACK_INV_START = PLAYER_INV_END + 1; + private static final int JETPACK_FUEL_START = PLAYER_INV_END + 3; - public ContainerJetpack(EntityPlayer player, InventorySteamJetpack inventory, boolean wearing) - { - this.player = player; - this.inventory = inventory; - makeSlots(player.inventory); - this.inventory.openInventory(); - this.wearing = wearing; - } + private ItemStack fuelStack; - private void bindPlayerInventory(InventoryPlayer invPlayer) + public ContainerJetpack(EntityPlayer player, InventoryCoalJetpack jetpack, Source source) { - int startX = 8; - int startY = 84; - - // Player's Hotbar - for (int x = 0; x < 9; x++) - { - addSlotToContainer(new Slot(invPlayer, x, startX + 18 * x, 142)); - } - - // Player's Inventory - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlotToContainer(new Slot(invPlayer, (x + y * 9 + 9), (startX + 18 * x), (startY + y * 18))); - } - } - //Total 36 slots + super(player, jetpack, source); + makeSlots(player.inventory); + inventory.openInventory(); } private void makeSlots(InventoryPlayer invPlayer) { + bindPlayerInventory(invPlayer, 8, 84); - bindPlayerInventory(invPlayer); - - //Bucket Slots - // bucket in - addSlotToContainer(new SlotFluid(inventory, InventorySteamJetpack.BUCKET_IN_SLOT, 30, 22)); - // bucket out - addSlotToContainer(new SlotFluid(inventory, InventorySteamJetpack.BUCKET_OUT_SLOT, 30, 52)); - // fuel - addSlotToContainer(new SlotFuel(inventory,InventorySteamJetpack.FUEL_SLOT, 77, 64)); - - } - @Override - public boolean canInteractWith(EntityPlayer p_75145_1_) - { - return true; + addSlotToContainer(new SlotFluidWater(inventory, BUCKET_IN, 30, 22)); + addSlotToContainer(new SlotFluidWater(inventory, BUCKET_OUT, 30, 52)); + addSlotToContainer(new SlotFuel(inventory, FUEL_SLOT, 77, 64)); } @Override - public void detectAndSendChanges() + protected boolean detectItemChanges() { - if(wearing) + // determine not only the presence of item in the slot but also check if the item type same as tick before + ItemStack[] inv = inventory.getInventory(); + if (inv[FUEL_SLOT] != fuelStack) { - refresh(); - super.detectAndSendChanges(); - if (wearing && player instanceof EntityPlayerMP) - { - ((EntityPlayerMP) player).sendContainerAndContentsToPlayer(this, inventoryItemStacks); - BackpackProperty.syncToNear(player); - } - }else{ - super.detectAndSendChanges(); - } - } - - public void onContainerClosed(EntityPlayer player) - { - super.onContainerClosed(player); - if (wearing) - { - this.crafters.remove(player); - } - if (!player.worldObj.isRemote) - { - for (int i = 0; i < 3; i++) - { - ItemStack itemstack = this.inventory.getStackInSlotOnClosing(i); - if (itemstack != null) - { - inventory.setInventorySlotContents(i, null); - player.dropPlayerItemWithRandomChoice(itemstack, false); - } - } + fuelStack = inv[FUEL_SLOT]; + return true; } + return false; } @Override - public ItemStack transferStackInSlot(EntityPlayer player, int i) + public boolean transferStackToPack(ItemStack stack) { - refresh(); - Slot slot = getSlot(i); - ItemStack result = null; - - if (slot != null && slot.getHasStack()) + if (SlotFluid.isContainer(stack)) { - ItemStack stack = slot.getStack(); - result = stack.copy(); - if (i >= 36) - { - if (!mergeItemStack(stack, PLAYER_HOT_START, PLAYER_INV_END + 1, false)) - { - return null; - } - } - if (i < 36) - { - if (SlotFluid.valid(stack)) - { - int JETPACK_INV_START = PLAYER_INV_END + 1; - if (!mergeItemStack(stack, JETPACK_INV_START, JETPACK_INV_START + 1, false)) - { + FluidTank waterTank = ((InventoryCoalJetpack ) inventory).getWaterTank(); + ItemStack stackOut = getSlot(JETPACK_INV_START + 1).getStack(); - } - } - else - { - int JETPACK_FUEL_START = PLAYER_INV_END + 3; - if (inventory.isFuel(stack) && !mergeItemStack(stack, JETPACK_FUEL_START, JETPACK_FUEL_START + 1, false)) - { - return null; - } - } - } + boolean isWaterTankEmpty = SlotFluid.isEmpty(waterTank); + boolean suitableToTank = SlotFluid.isEqualAndCanFit(stack, waterTank); + boolean areSameType = InventoryActions.areContainersOfSameType(stack, stackOut); - if (stack.stackSize == 0) - { - slot.putStack(null); - } else + if (SlotFluid.isFilled(stack)) { - slot.onSlotChanged(); + if ((stackOut == null || areSameType) && SlotFluidWater.isValidItem(stack)) + if (isWaterTankEmpty || suitableToTank) + return mergeBucket(stack); } - - if (stack.stackSize == result.stackSize) + else if (SlotFluid.isEmpty(stack)) { - return null; + if ((stackOut == null || areSameType) && SlotFluidWater.isValidItem(stack)) + if (!isWaterTankEmpty) + return mergeBucket(stack); } - slot.onPickupFromSlot(player, stack); } - return result; + else if (SlotFuel.isValidItem(stack)) + { + return mergeFuel(stack); + } + return true; } - @Override - public void refresh() + private boolean mergeBucket(ItemStack stack) { - inventory.openInventory(); + return mergeItemStack(stack, JETPACK_INV_START, JETPACK_INV_START + 1, false); + } + + private boolean mergeFuel(ItemStack stack) + { + return mergeItemStack(stack, JETPACK_FUEL_START, JETPACK_FUEL_START + 1, false); } } diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/IAsynchronousInventory.java b/src/main/java/com/darkona/adventurebackpack/inventory/IAsynchronousInventory.java index 49c15233..3e8a6d33 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/IAsynchronousInventory.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/IAsynchronousInventory.java @@ -1,5 +1,7 @@ package com.darkona.adventurebackpack.inventory; +import javax.annotation.Nullable; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -10,7 +12,7 @@ */ public interface IAsynchronousInventory extends IInventory { - public void setInventorySlotContentsNoSave(int slot, ItemStack stack); + void setInventorySlotContentsNoSave(int slot, @Nullable ItemStack stack); - public ItemStack decrStackSizeNoSave(int slot, int amount); + ItemStack decrStackSizeNoSave(int slot, int amount); } diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/IInventoryBackpack.java b/src/main/java/com/darkona/adventurebackpack/inventory/IInventoryBackpack.java new file mode 100644 index 00000000..7404e5dc --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/IInventoryBackpack.java @@ -0,0 +1,35 @@ +package com.darkona.adventurebackpack.inventory; + +import net.minecraft.item.Item; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.FluidTank; + +import com.darkona.adventurebackpack.reference.BackpackTypes; + +/** + * Created by Darkona on 12/10/2014. + */ +public interface IInventoryBackpack extends IInventoryTanks +{ + BackpackTypes getType(); + + FluidTank getLeftTank(); + + FluidTank getRightTank(); + + NBTTagCompound getExtendedProperties(); //TODO move to IInventoryTanks to use with Copter/Jet? + + void dirtyExtended(); + + void dirtyTime(); + + int getLastTime(); + + void setLastTime(int time); + + boolean hasItem(Item item); + + void consumeInventoryItem(Item item); + + boolean isSleepingBagDeployed(); +} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/IInventoryTanks.java b/src/main/java/com/darkona/adventurebackpack/inventory/IInventoryTanks.java index 8c5e30a6..2b4456ba 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/IInventoryTanks.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/IInventoryTanks.java @@ -1,5 +1,6 @@ package com.darkona.adventurebackpack.inventory; +import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidTank; @@ -10,15 +11,19 @@ */ public interface IInventoryTanks extends IAsynchronousInventory { - public boolean updateTankSlots(); + ItemStack[] getInventory(); - public void loadFromNBT(NBTTagCompound compound); + FluidTank[] getTanksArray(); - public void saveToNBT(NBTTagCompound compound); + int[] getSlotsOnClosing(); - public FluidTank[] getTanksArray(); + void loadFromNBT(NBTTagCompound compound); - public void dirtyInventory(); + void saveToNBT(NBTTagCompound compound); - public void dirtyTanks(); + void dirtyInventory(); + + boolean updateTankSlots(); + + void dirtyTanks(); } diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/IWearableContainer.java b/src/main/java/com/darkona/adventurebackpack/inventory/IWearableContainer.java deleted file mode 100644 index 5f0faaee..00000000 --- a/src/main/java/com/darkona/adventurebackpack/inventory/IWearableContainer.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.darkona.adventurebackpack.inventory; - -/** - * Created on 12/01/2015 - * - * @author Darkona - */ -public interface IWearableContainer -{ - public void refresh(); -} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/InventoryActions.java b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryActions.java index e4884903..0eb43c99 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/InventoryActions.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryActions.java @@ -1,8 +1,5 @@ package com.darkona.adventurebackpack.inventory; -import com.darkona.adventurebackpack.common.Constants; -import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; -import com.darkona.adventurebackpack.util.FluidUtils; import net.minecraft.block.Block; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; @@ -11,6 +8,10 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.item.ItemHose; +import com.darkona.adventurebackpack.util.FluidUtils; + /** * Created on 16/10/2014 * @@ -18,7 +19,6 @@ */ public class InventoryActions { - /** * What a complicated mess. I hated every minute of coding this. * This code takes a fluid container item. If its filled, it empties it out into a tank. @@ -27,88 +27,89 @@ public class InventoryActions * it simply fills the tank. * * @param inventory The inventory type thing that will have its tank updated. - * @param tank The tank that's going to be updated. - * @param slotIn The slot in which the fluid container item must be to update the tank. + * @param tank The tank that's going to be updated. + * @param slotIn The slot in which the fluid container item must be to update the tank. * @return True if the tank was filled and the resulting filled or empty container item was placed in the other slot. */ public static boolean transferContainerTank(IInventoryTanks inventory, FluidTank tank, int slotIn) { - ItemStack stackIn = inventory.getStackInSlot(slotIn); - if (tank == null || stackIn == null) return false; - - //Set slot out for whatever number the output slot should be. + if (tank == null) return false; int slotOut = slotIn + 1; + ItemStack stackHose = inventory.getStackInSlot(slotOut); + + if (stackHose != null && stackHose.getItem() instanceof ItemHose) + { + if (tank.getFluidAmount() > 0) + { + tank.drain(tank.getFluidAmount(), true); //Hose in the bucketOut slot will empty the tank + return true; + } + //return false; + } + + ItemStack stackIn = inventory.getStackInSlot(slotIn); + if (stackIn == null) return false; //CONTAINER ===========> TANK if (FluidContainerRegistry.isFilledContainer(stackIn)) { - //See if the tank can accept moar fluid. - int fill = tank.fill(FluidContainerRegistry.getFluidForFilledItem(stackIn), false); + int fill = tank.fill(FluidContainerRegistry.getFluidForFilledItem(stackIn), false); //See if the tank can accept moar fluid - if (fill > 0)//If can accept the fluid + if (fill > 0) //If can accept the fluid { - //Get the empty container for the input, if there's any. - ItemStack stackOut = FluidContainerRegistry.drainFluidContainer(stackIn); - - if (inventory.getStackInSlot(slotOut) == null || stackOut == null) + if (FluidContainerRegistry.getContainerCapacity(stackIn) + tank.getFluidAmount() <= tank.getCapacity()) { + ItemStack stackOut = FluidContainerRegistry.drainFluidContainer(stackIn); //Get the empty container for the input, if there's any - tank.fill(FluidContainerRegistry.getFluidForFilledItem(stackIn), true); - //inventory.dirtyTanks(); - inventory.decrStackSizeNoSave(slotIn, 1); - inventory.setInventorySlotContentsNoSave(slotOut, stackOut); - //inventory.dirtyInventory(); - return true; - } else if (inventory.getStackInSlot(slotOut).getItem() == stackOut.getItem()) - { - int maxStack = inventory.getStackInSlot(slotOut).getMaxStackSize(); - if (maxStack > 1 && (inventory.getStackInSlot(slotOut).stackSize + 1) <= maxStack) + if (inventory.getStackInSlot(slotOut) == null || stackOut == null) { - tank.fill(FluidContainerRegistry.getFluidForFilledItem(stackIn), true); - //inventory.dirtyTanks(); inventory.decrStackSizeNoSave(slotIn, 1); - inventory.getStackInSlot(slotOut).stackSize++; - // inventory.dirtyInventory(); + inventory.setInventorySlotContentsNoSave(slotOut, stackOut); return true; } + else if (inventory.getStackInSlot(slotOut).getItem().equals(stackOut.getItem()) + && stackOut.getItemDamage() == inventory.getStackInSlot(slotOut).getItemDamage()) + { + int maxStack = inventory.getStackInSlot(slotOut).getMaxStackSize(); + if (maxStack > 1 && (inventory.getStackInSlot(slotOut).stackSize + 1) <= maxStack) + { + tank.fill(FluidContainerRegistry.getFluidForFilledItem(stackIn), true); + inventory.decrStackSizeNoSave(slotIn, 1); + inventory.getStackInSlot(slotOut).stackSize++; + return true; + } + } } } } //TANK =====> CONTAINER - - if (tank.getFluid() != null && tank.getFluidAmount() > 0 && FluidUtils.isEmptyContainerForFluid(stackIn, tank.getFluid().getFluid())) + else if (tank.getFluid() != null && tank.getFluidAmount() > 0 && FluidUtils.isEmptyContainerForFluid(stackIn, tank.getFluid().getFluid())) { - //How much fluid can this container hold. - int amount = FluidContainerRegistry.getContainerCapacity(tank.getFluid(), stackIn); - //Let's see how much can we drain this tank - FluidStack drain = tank.drain(amount, false); - - ItemStack stackOut = FluidContainerRegistry.fillFluidContainer(drain, stackIn); + int amount = FluidContainerRegistry.getContainerCapacity(tank.getFluid(), stackIn); //How much fluid can this container hold + FluidStack drain = tank.drain(amount, false); //Let's see how much can we drain this tank - if (drain.amount == amount) + if (amount > 0 && drain.amount == amount) { - if (inventory.getStackInSlot(slotOut) == null) + ItemStack stackOut = FluidContainerRegistry.fillFluidContainer(drain, stackIn); + + if (inventory.getStackInSlot(slotOut) == null || stackOut == null) { tank.drain(amount, true); - //inventory.dirtyTanks(); inventory.decrStackSizeNoSave(slotIn, 1); inventory.setInventorySlotContentsNoSave(slotOut, stackOut); - //inventory.dirtyInventory(); return true; - } else - if (stackOut.getItem() != null - && stackOut.getItem() == inventory.getStackInSlot(slotOut).getItem()) + } + else if (stackOut.getItem().equals(inventory.getStackInSlot(slotOut).getItem()) + && stackOut.getItemDamage() == inventory.getStackInSlot(slotOut).getItemDamage()) { int maxStack = inventory.getStackInSlot(slotOut).getMaxStackSize(); if (maxStack > 1 && (inventory.getStackInSlot(slotOut).stackSize + 1) <= maxStack) { tank.drain(amount, true); - //inventory.dirtyTanks(); inventory.decrStackSizeNoSave(slotIn, 1); inventory.getStackInSlot(slotOut).stackSize++; - // inventory.dirtyInventory(); return true; } } @@ -117,10 +118,17 @@ public static boolean transferContainerTank(IInventoryTanks inventory, FluidTank return false; } + public static boolean areStacksCompatible(ItemStack stackA, ItemStack stackB) + { + return stackA.getItem() == stackB.getItem() + && (!stackA.getHasSubtypes() || stackA.getItemDamage() == stackB.getItemDamage()) + && ItemStack.areItemStackTagsEqual(stackA, stackB); + } + public static void consumeItemInInventory(IInventory backpack, Item item) { int i = -1; - for (int j = 0; j < Constants.inventorySize - 7; ++j) + for (int j = 0; j < Constants.END_OF_INVENTORY; ++j) { if (backpack.getStackInSlot(j) != null && backpack.getStackInSlot(j).getItem() == item) { @@ -130,17 +138,16 @@ public static void consumeItemInInventory(IInventory backpack, Item item) } if (i >= 0) { - backpack.decrStackSize(i,1); + backpack.decrStackSize(i, 1); } } - public static boolean hasItem(IInventoryAdventureBackpack backpack, Item item) + public static boolean hasItem(IInventoryBackpack backpack, Item item) { ItemStack[] inventory = backpack.getInventory(); - for (int i = 0; i < inventory.length; i++) + for (ItemStack slotStack : inventory) { - if (inventory[i] != null && - inventory[i].getItem().equals(item)) + if (slotStack != null && slotStack.getItem().equals(item)) { return true; } @@ -148,13 +155,12 @@ public static boolean hasItem(IInventoryAdventureBackpack backpack, Item item) return false; } - public static boolean hasBlockItem(IInventoryAdventureBackpack backpack, Block item) + public static boolean hasBlockItem(IInventoryBackpack backpack, Block item) { ItemStack[] inventory = backpack.getInventory(); - for (int i = 0; i < inventory.length; i++) + for (ItemStack slotStack : inventory) { - if (inventory[i] != null && - inventory[i].getItem().equals(Item.getItemFromBlock(item))) + if (slotStack != null && slotStack.getItem().equals(Item.getItemFromBlock(item))) { return true; } @@ -162,4 +168,21 @@ public static boolean hasBlockItem(IInventoryAdventureBackpack backpack, Block i return false; } + public static boolean areContainersOfSameType(ItemStack stackIn, ItemStack stackOut) + { + if (stackIn == null || stackOut == null) + return false; + + if (SlotFluid.isFilled(stackIn) && SlotFluid.isEmpty(stackOut)) + { + ItemStack emptyIn = SlotFluid.getEmptyContainer(stackIn); + return stackOut.isStackable() && areStacksCompatible(emptyIn, stackOut); + } + else if (SlotFluid.isEmpty(stackIn) && SlotFluid.isFilled(stackOut)) + { + ItemStack emptyOut = SlotFluid.getEmptyContainer(stackOut); + return stackOut.isStackable() && areStacksCompatible(stackIn, emptyOut); + } + return false; + } } diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/InventoryAdventure.java b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryAdventure.java new file mode 100644 index 00000000..4622a383 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryAdventure.java @@ -0,0 +1,205 @@ +package com.darkona.adventurebackpack.inventory; + +import javax.annotation.Nullable; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +import com.darkona.adventurebackpack.util.BackpackUtils; + +import static com.darkona.adventurebackpack.common.Constants.TAG_INVENTORY; +import static com.darkona.adventurebackpack.common.Constants.TAG_SLOT; + +/** + * Created on 15.07.2017 + * + * @author Ugachaga + */ +@SuppressWarnings("WeakerAccess") +abstract class InventoryAdventure implements IInventoryTanks +{ + // when porting to java 8+ most this methods should move to IInventoryTanks + + protected final ItemStack containerStack; + protected final ItemStack[] inventory; + + protected InventoryAdventure(ItemStack container, int inventorySize) + { + this.containerStack = container; + this.inventory = new ItemStack[inventorySize]; + } + + @Override + public int getSizeInventory() + { + return inventory.length; + } + + @Override + public ItemStack getStackInSlot(int slot) + { + return inventory[slot]; + } + + @Nullable + @Override + public ItemStack decrStackSize(int slot, int quantity) + { + ItemStack stack = getStackInSlot(slot); + if (stack != null) + { + if (stack.stackSize <= quantity) + setInventorySlotContents(slot, null); + else + stack = stack.splitStack(quantity); + } + return stack; + } + + @Nullable + @Override + public ItemStack getStackInSlotOnClosing(int slot) + { + for (int s : getSlotsOnClosing()) + if (slot == s) + return inventory[slot]; + + return null; + } + + @Override + public void setInventorySlotContents(int slot, @Nullable ItemStack stack) + { + setInventorySlotContentsNoSave(slot, stack); + dirtyInventory(); + } + + + @Override + public String getInventoryName() + { + return ""; //TODO name heirs + } + + @Override + public boolean hasCustomInventoryName() + { + return getInventoryName() != null && !getInventoryName().isEmpty(); + } + + @Override + public int getInventoryStackLimit() + { + return 64; + } + + @Override + public void markDirty() + { + saveToNBT(containerStack.stackTagCompound); + } + + @Override + public boolean isUseableByPlayer(EntityPlayer player) + { + return true; + } + + @Override + public void openInventory() + { + loadFromNBT(containerStack.stackTagCompound); + } + + @Override + public void closeInventory() + { + saveToNBT(containerStack.stackTagCompound); + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) + { + return false; + } + + @Nullable + @Override + public ItemStack decrStackSizeNoSave(int slot, int quantity) + { + ItemStack stack = getStackInSlot(slot); + if (stack != null) + { + if (stack.stackSize <= quantity) + setInventorySlotContentsNoSave(slot, null); + else + stack = stack.splitStack(quantity); + } + return stack; + } + + @Override + public void setInventorySlotContentsNoSave(int slot, @Nullable ItemStack stack) + { + if (slot >= getSizeInventory()) + return; + + if (stack != null) + { + if (stack.stackSize > getInventoryStackLimit()) + stack.stackSize = getInventoryStackLimit(); + + if (stack.stackSize == 0) + stack = null; + } + + inventory[slot] = stack; + } + + @Override + public void dirtyInventory() + { + if (updateTankSlots()) //TODO this can be generalized too + dirtyTanks(); //TODO and also this + + getWearableCompound().removeTag(TAG_INVENTORY); //TODO why? sync related? + getWearableCompound().setTag(TAG_INVENTORY, getInventoryTagList()); + } + + protected NBTTagCompound getWearableCompound() + { + return BackpackUtils.getWearableCompound(containerStack); + } + + protected void setInventoryFromTagList(NBTTagList items) + { + for (int i = 0; i < items.tagCount(); i++) + { + NBTTagCompound item = items.getCompoundTagAt(i); + byte slot = item.getByte(TAG_SLOT); + if (slot >= 0 && slot < getSizeInventory()) + { + inventory[slot] = ItemStack.loadItemStackFromNBT(item); + } + } + } + + protected NBTTagList getInventoryTagList() + { + NBTTagList items = new NBTTagList(); + for (int i = 0; i < getSizeInventory(); i++) + { + ItemStack stack = inventory[i]; + if (stack != null) + { + NBTTagCompound item = new NBTTagCompound(); + item.setByte(TAG_SLOT, (byte) i); + stack.writeToNBT(item); + items.appendTag(item); + } + } + return items; + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/InventoryBackpack.java b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryBackpack.java index 51e96f05..b8d48d5d 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/InventoryBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryBackpack.java @@ -1,69 +1,69 @@ package com.darkona.adventurebackpack.inventory; - -import com.darkona.adventurebackpack.block.BlockAdventureBackpack; -import com.darkona.adventurebackpack.block.TileAdventureBackpack; -import com.darkona.adventurebackpack.common.BackpackAbilities; -import com.darkona.adventurebackpack.common.Constants; -import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; -import com.darkona.adventurebackpack.item.ItemAdventureBackpack; -import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraft.world.World; +import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.fluids.FluidTank; +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.init.ModBlocks; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.util.CoordsUtils; + +import static com.darkona.adventurebackpack.common.Constants.BUCKET_IN_LEFT; +import static com.darkona.adventurebackpack.common.Constants.BUCKET_IN_RIGHT; +import static com.darkona.adventurebackpack.common.Constants.BUCKET_OUT_LEFT; +import static com.darkona.adventurebackpack.common.Constants.BUCKET_OUT_RIGHT; +import static com.darkona.adventurebackpack.common.Constants.TAG_DISABLE_CYCLING; +import static com.darkona.adventurebackpack.common.Constants.TAG_DISABLE_NVISION; +import static com.darkona.adventurebackpack.common.Constants.TAG_EXTENDED_COMPOUND; +import static com.darkona.adventurebackpack.common.Constants.TAG_INVENTORY; +import static com.darkona.adventurebackpack.common.Constants.TAG_LEFT_TANK; +import static com.darkona.adventurebackpack.common.Constants.TAG_RIGHT_TANK; +import static com.darkona.adventurebackpack.common.Constants.TAG_TYPE; +import static com.darkona.adventurebackpack.common.Constants.TAG_WEARABLE_COMPOUND; + /** * Created on 12/10/2014 * * @author Darkona */ -public class InventoryBackpack implements IInventoryAdventureBackpack +public class InventoryBackpack extends InventoryAdventure implements IInventoryBackpack { - public ItemStack[] inventory = new ItemStack[Constants.inventorySize]; - private FluidTank leftTank = new FluidTank(Constants.basicTankCapacity); - private FluidTank rightTank = new FluidTank(Constants.basicTankCapacity); - - public ItemStack getContainerStack() - { - return containerStack; - } - - public void setContainerStack(ItemStack containerStack) - { - this.containerStack = containerStack; - } - - private ItemStack containerStack; - private String colorName = "Standard"; + private static final String TAG_IS_SLEEPING_BAG = "sleepingBag"; + private static final String TAG_SLEEPING_BAG_X = "sleepingBagX"; + private static final String TAG_SLEEPING_BAG_Y = "sleepingBagY"; + private static final String TAG_SLEEPING_BAG_Z = "sleepingBagZ"; + + private BackpackTypes type = BackpackTypes.STANDARD; + private FluidTank leftTank = new FluidTank(Constants.BASIC_TANK_CAPACITY); + private FluidTank rightTank = new FluidTank(Constants.BASIC_TANK_CAPACITY); + private NBTTagCompound extendedProperties = new NBTTagCompound(); + + private boolean sleepingBagDeployed = false; + private int sleepingBagX; + private int sleepingBagY; + private int sleepingBagZ; + + private boolean disableNVision = false; + private boolean disableCycling = false; private int lastTime = 0; - private boolean special = false; - public NBTTagCompound extendedProperties = new NBTTagCompound(); public InventoryBackpack(ItemStack backpack) { - containerStack = backpack; - if(!backpack.hasTagCompound()) - { - backpack.stackTagCompound = new NBTTagCompound(); - saveToNBT(backpack.stackTagCompound); - } - loadFromNBT(backpack.stackTagCompound); + super(backpack, Constants.INVENTORY_SIZE); + detectAndConvertFromOldNBTFormat(containerStack.stackTagCompound); + openInventory(); } @Override - public FluidTank getLeftTank() + public BackpackTypes getType() { - return leftTank; - } - - @Override - public FluidTank getRightTank() - { - return rightTank; + return type; } @Override @@ -73,27 +73,27 @@ public ItemStack[] getInventory() } @Override - public TileAdventureBackpack getTile() + public FluidTank getLeftTank() { - return null; + return leftTank; } @Override - public ItemStack getParentItemStack() + public FluidTank getRightTank() { - return this.containerStack; + return rightTank; } @Override - public String getColorName() + public FluidTank[] getTanksArray() { - return colorName; + return new FluidTank[]{leftTank, rightTank}; } @Override - public int getLastTime() + public int[] getSlotsOnClosing() { - return this.lastTime; + return new int[]{BUCKET_IN_LEFT, BUCKET_IN_RIGHT, BUCKET_OUT_LEFT, BUCKET_OUT_RIGHT}; } @Override @@ -103,48 +103,75 @@ public NBTTagCompound getExtendedProperties() } @Override - public void setExtendedProperties(NBTTagCompound properties) + public void loadFromNBT(NBTTagCompound compound) { - this.extendedProperties = properties; + if (compound == null) + return; // this need for NEI and WAILA trying to render tile.backpack and comes here w/o nbt + + NBTTagCompound backpackTag = compound.getCompoundTag(TAG_WEARABLE_COMPOUND); + type = BackpackTypes.getType(backpackTag.getByte(TAG_TYPE)); + setInventoryFromTagList(backpackTag.getTagList(TAG_INVENTORY, NBT.TAG_COMPOUND)); + leftTank.readFromNBT(backpackTag.getCompoundTag(TAG_LEFT_TANK)); + rightTank.readFromNBT(backpackTag.getCompoundTag(TAG_RIGHT_TANK)); + extendedProperties = backpackTag.getCompoundTag(TAG_EXTENDED_COMPOUND); + loadSleepingBag(); + disableCycling = backpackTag.getBoolean(TAG_DISABLE_CYCLING); + disableNVision = backpackTag.getBoolean(TAG_DISABLE_NVISION); + lastTime = backpackTag.getInteger("lastTime"); } @Override - public boolean isSpecial() + public void saveToNBT(NBTTagCompound compound) { - return special; + NBTTagCompound backpackTag = new NBTTagCompound(); + backpackTag.setByte(TAG_TYPE, BackpackTypes.getMeta(type)); + backpackTag.setTag(TAG_INVENTORY, getInventoryTagList()); + backpackTag.setTag(TAG_RIGHT_TANK, rightTank.writeToNBT(new NBTTagCompound())); + backpackTag.setTag(TAG_LEFT_TANK, leftTank.writeToNBT(new NBTTagCompound())); + backpackTag.setTag(TAG_EXTENDED_COMPOUND, extendedProperties); + saveSleepingBag(); + backpackTag.setBoolean(TAG_DISABLE_CYCLING, disableCycling); + backpackTag.setBoolean(TAG_DISABLE_NVISION, disableNVision); + backpackTag.setInteger("lastTime", lastTime); + + compound.setTag(TAG_WEARABLE_COMPOUND, backpackTag); } @Override - public void saveTanks(NBTTagCompound compound) + public boolean updateTankSlots() { - compound.setTag("rightTank", rightTank.writeToNBT(new NBTTagCompound())); - compound.setTag("leftTank", leftTank.writeToNBT(new NBTTagCompound())); + boolean changesMade = false; + while (InventoryActions.transferContainerTank(this, getLeftTank(), BUCKET_IN_LEFT)) + changesMade = true; + while (InventoryActions.transferContainerTank(this, getRightTank(), BUCKET_IN_RIGHT)) + changesMade = true; + return changesMade; } @Override - public void loadTanks(NBTTagCompound compound) + public void dirtyTanks() { - leftTank.readFromNBT(compound.getCompoundTag("leftTank")); - rightTank.readFromNBT(compound.getCompoundTag("rightTank")); + getWearableCompound().setTag(TAG_LEFT_TANK, leftTank.writeToNBT(new NBTTagCompound())); + getWearableCompound().setTag(TAG_RIGHT_TANK, rightTank.writeToNBT(new NBTTagCompound())); } @Override - public boolean hasItem(Item item) + public void dirtyExtended() //TODO is it redundant? { - return InventoryActions.hasItem(this, item); + getWearableCompound().removeTag(TAG_EXTENDED_COMPOUND); //TODO again: why? + getWearableCompound().setTag(TAG_EXTENDED_COMPOUND, extendedProperties); } @Override - public void consumeInventoryItem(Item item) + public void dirtyTime() { - InventoryActions.consumeItemInInventory(this, item); + getWearableCompound().setInteger("lastTime", lastTime); } - @Override - public boolean isSBDeployed() + public int getLastTime() { - return false; + return this.lastTime; } @Override @@ -154,255 +181,121 @@ public void setLastTime(int time) } @Override - public void setInventorySlotContents(int slot, ItemStack stack) + public boolean hasItem(Item item) { - if (slot > inventory.length) return; - inventory[slot] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) - { - stack.stackSize = this.getInventoryStackLimit(); - } - dirtyInventory(); + return InventoryActions.hasItem(this, item); } @Override - public void setInventorySlotContentsNoSave(int slot, ItemStack stack) + public void consumeInventoryItem(Item item) { - if (slot > inventory.length) return; - inventory[slot] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) - { - stack.stackSize = this.getInventoryStackLimit(); - } + InventoryActions.consumeItemInInventory(this, item); } - @Override - public ItemStack decrStackSize(int slot, int quantity) + public boolean getDisableCycling() { - ItemStack itemstack = getStackInSlot(slot); - if (itemstack != null) - { - if (itemstack.stackSize <= quantity) - { - setInventorySlotContents(slot, null); - } else - { - itemstack = itemstack.splitStack(quantity); - } - } - return itemstack; - } - @Override - public ItemStack decrStackSizeNoSave(int slot, int quantity) - { - ItemStack stack = getStackInSlot(slot); - if (stack != null) - { - if (stack.stackSize <= quantity) - { - setInventorySlotContentsNoSave(slot, null); - } else - { - stack = stack.splitStack(quantity); - } - } - return stack; + return disableCycling; } - public boolean updateTankSlots() + public void setDisableCycling(boolean b) { - return InventoryActions.transferContainerTank(this, getLeftTank(), Constants.bucketInLeft) || - InventoryActions.transferContainerTank(this, getRightTank(), Constants.bucketInRight); + this.disableCycling = b; } - @Override - public void loadFromNBT(NBTTagCompound compound) + public boolean getDisableNVision() { - if(compound.hasKey("backpackData")) - { - NBTTagCompound backpackData = compound.getCompoundTag("backpackData"); - NBTTagList items = backpackData.getTagList("ABPItems", net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND); - for (int i = 0; i < items.tagCount(); i++) - { - NBTTagCompound item = items.getCompoundTagAt(i); - byte slot = item.getByte("Slot"); - if (slot >= 0 && slot < inventory.length) - { - inventory[slot] = ItemStack.loadItemStackFromNBT(item); - } - } - - leftTank.readFromNBT(backpackData.getCompoundTag("leftTank")); - rightTank.readFromNBT(backpackData.getCompoundTag("rightTank")); - colorName = backpackData.getString("colorName"); - lastTime = backpackData.getInteger("lastTime"); - special = backpackData.getBoolean("special"); - extendedProperties = backpackData.getCompoundTag("extendedProperties"); - } + return disableNVision; } - @Override - public void saveToNBT(NBTTagCompound compound) + public void setDisableNVision(boolean b) { - // if(Utils.inServer()) - // { - NBTTagCompound backpackData = new NBTTagCompound(); - NBTTagList items = new NBTTagList(); - for (int i = 0; i < inventory.length; i++) - { - ItemStack stack = inventory[i]; - if (stack != null) - { - NBTTagCompound item = new NBTTagCompound(); - item.setByte("Slot", (byte) i); - stack.writeToNBT(item); - items.appendTag(item); - } - } - backpackData.removeTag("ABPItems"); - backpackData.setTag("ABPItems", items); - backpackData.setString("colorName", colorName); - backpackData.setInteger("lastTime", lastTime); - backpackData.setBoolean("special", BackpackAbilities.hasAbility(colorName)); - backpackData.setTag("extendedProperties", extendedProperties); - backpackData.setTag("rightTank", rightTank.writeToNBT(new NBTTagCompound())); - backpackData.setTag("leftTank", leftTank.writeToNBT(new NBTTagCompound())); - - compound.setTag("backpackData",backpackData); - //} + this.disableNVision = b; } + // Sleeping Bag @Override - public FluidTank[] getTanksArray() + public boolean isSleepingBagDeployed() { - FluidTank[] array = {leftTank,rightTank}; - return array; + return sleepingBagDeployed; } - @Override - public ItemStack getStackInSlotOnClosing(int slot) + private void loadSleepingBag() { - if (slot == Constants.bucketInLeft || slot == Constants.bucketInRight || slot == Constants.bucketOutLeft || slot == Constants.bucketOutRight) + sleepingBagDeployed = extendedProperties.getBoolean(TAG_IS_SLEEPING_BAG); + if (sleepingBagDeployed) { - return inventory[slot]; + sleepingBagX = extendedProperties.getInteger(TAG_SLEEPING_BAG_X); + sleepingBagY = extendedProperties.getInteger(TAG_SLEEPING_BAG_Y); + sleepingBagZ = extendedProperties.getInteger(TAG_SLEEPING_BAG_Z); } - return null; - } - - @Override - public String getInventoryName() - { - return "Adventure Backpack"; - } - - @Override - public boolean hasCustomInventoryName() - { - return true; } - @Override - public int getInventoryStackLimit() + private void saveSleepingBag() { - return 64; - } - - @Override - public void markDirty() - { - - saveToNBT(containerStack.stackTagCompound); - } - - @Override - public boolean isUseableByPlayer(EntityPlayer player) - { - return true; - } - - @Override - public void openInventory() - { - loadFromNBT(containerStack.stackTagCompound); - } - - @Override - public void closeInventory() - { - /* if(Utils.inServer()) - {*/ - saveToNBT(containerStack.stackTagCompound); - // } - } - - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) - { - if (stack.getItem() instanceof ItemAdventureBackpack || Block.getBlockFromItem(stack.getItem()) instanceof BlockAdventureBackpack) + if (sleepingBagDeployed) { - return false; + extendedProperties.setBoolean(TAG_IS_SLEEPING_BAG, sleepingBagDeployed); + extendedProperties.setInteger(TAG_SLEEPING_BAG_X, sleepingBagX); + extendedProperties.setInteger(TAG_SLEEPING_BAG_Y, sleepingBagY); + extendedProperties.setInteger(TAG_SLEEPING_BAG_Z, sleepingBagZ); } - if (slot == Constants.bucketInRight || slot == Constants.bucketInLeft) + else { - return FluidContainerRegistry.isContainer(stack); + extendedProperties.removeTag(TAG_IS_SLEEPING_BAG); + extendedProperties.removeTag(TAG_SLEEPING_BAG_X); + extendedProperties.removeTag(TAG_SLEEPING_BAG_Y); + extendedProperties.removeTag(TAG_SLEEPING_BAG_Z); } - - return !(slot == Constants.upperTool || slot == Constants.lowerTool) || SlotTool.isValidTool(stack); - } - - @Override - public int getSizeInventory() - { - return inventory.length; - } - - @Override - public ItemStack getStackInSlot(int slot) - { - return inventory[slot]; } - public void dirtyTanks() + public boolean deploySleepingBag(EntityPlayer player, World world, int meta, int cX, int cY, int cZ) { - containerStack.stackTagCompound.getCompoundTag("backpackData").setTag("leftTank",leftTank.writeToNBT(new NBTTagCompound())); - containerStack.stackTagCompound.getCompoundTag("backpackData").setTag("rightTank",rightTank.writeToNBT(new NBTTagCompound())); - } + if (world.isRemote) + return false; - public void dirtyTime() - { - containerStack.stackTagCompound.getCompoundTag("backpackData").setInteger("lastTime",lastTime); - } + if (sleepingBagDeployed) + removeSleepingBag(world); - public void dirtyExtended() - { - containerStack.stackTagCompound.getCompoundTag("backpackData").removeTag("extendedProperties"); - containerStack.stackTagCompound.getCompoundTag("backpackData").setTag("extendedProperties",extendedProperties); + sleepingBagDeployed = CoordsUtils.spawnSleepingBag(player, world, meta, cX, cY, cZ); + if (sleepingBagDeployed) + { + sleepingBagX = cX; + sleepingBagY = cY; + sleepingBagZ = cZ; + markDirty(); + } + return sleepingBagDeployed; } - public void dirtyInventory() + public void removeSleepingBag(World world) { - if(updateTankSlots()){ - dirtyTanks(); - } - NBTTagList items = new NBTTagList(); - for (int i = 0; i < inventory.length; i++) + if (this.sleepingBagDeployed) { - ItemStack stack = inventory[i]; - if (stack != null) - { - NBTTagCompound item = new NBTTagCompound(); - item.setByte("Slot", (byte) i); - stack.writeToNBT(item); - items.appendTag(item); - } + if (world.getBlock(sleepingBagX, sleepingBagY, sleepingBagZ) == ModBlocks.blockSleepingBag) + world.func_147480_a(sleepingBagX, sleepingBagY, sleepingBagZ, false); } - containerStack.stackTagCompound.getCompoundTag("backpackData").removeTag("ABPItems"); - containerStack.stackTagCompound.getCompoundTag("backpackData").setTag("ABPItems", items); + this.sleepingBagDeployed = false; + markDirty(); } - public boolean hasBlock(Block block) + private void detectAndConvertFromOldNBTFormat(NBTTagCompound compound) // backwards compatibility { - return InventoryActions.hasBlockItem(this, block); - } -} + if (compound == null || !compound.hasKey("backpackData")) + return; + NBTTagCompound oldBackpackTag = compound.getCompoundTag("backpackData"); + NBTTagList oldItems = oldBackpackTag.getTagList("ABPItems", NBT.TAG_COMPOUND); + leftTank.readFromNBT(oldBackpackTag.getCompoundTag("leftTank")); + rightTank.readFromNBT(oldBackpackTag.getCompoundTag("rightTank")); + type = BackpackTypes.getType(oldBackpackTag.getString("colorName")); + + NBTTagCompound newBackpackTag = new NBTTagCompound(); + newBackpackTag.setTag(TAG_INVENTORY, oldItems); + newBackpackTag.setTag(TAG_RIGHT_TANK, rightTank.writeToNBT(new NBTTagCompound())); + newBackpackTag.setTag(TAG_LEFT_TANK, leftTank.writeToNBT(new NBTTagCompound())); + newBackpackTag.setByte(TAG_TYPE, BackpackTypes.getMeta(type)); + + compound.setTag(TAG_WEARABLE_COMPOUND, newBackpackTag); + compound.removeTag("backpackData"); + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCoalJetpack.java b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCoalJetpack.java new file mode 100644 index 00000000..62310b1a --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCoalJetpack.java @@ -0,0 +1,276 @@ +package com.darkona.adventurebackpack.inventory; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntityFurnace; +import net.minecraftforge.common.util.Constants.NBT; +import net.minecraftforge.fluids.FluidTank; + +import com.darkona.adventurebackpack.common.Constants; + +import static com.darkona.adventurebackpack.common.Constants.Jetpack.BUCKET_IN; +import static com.darkona.adventurebackpack.common.Constants.Jetpack.BUCKET_OUT; +import static com.darkona.adventurebackpack.common.Constants.Jetpack.FUEL_SLOT; +import static com.darkona.adventurebackpack.common.Constants.Jetpack.TAG_STEAM_TANK; +import static com.darkona.adventurebackpack.common.Constants.Jetpack.TAG_WATER_TANK; +import static com.darkona.adventurebackpack.common.Constants.TAG_INVENTORY; +import static com.darkona.adventurebackpack.common.Constants.TAG_WEARABLE_COMPOUND; + +/** + * Created on 15/01/2015 + * + * @author Darkona + */ +public class InventoryCoalJetpack extends InventoryAdventure +{ + private FluidTank waterTank = new FluidTank(Constants.Jetpack.WATER_CAPACITY); + private FluidTank steamTank = new FluidTank(Constants.Jetpack.STEAM_CAPACITY); + + private boolean inUse = false; + private boolean status = false; + private boolean boiling = false; + private boolean leaking = false; + private int temperature = 25; + private int burnTicks = 0; + private int coolTicks = 5000; + private int currentItemBurnTime = 0; + + public InventoryCoalJetpack(final ItemStack jetpack) + { + super(jetpack, Constants.Jetpack.INVENTORY_SIZE); + detectAndConvertFromOldNBTFormat(containerStack.stackTagCompound); + openInventory(); + } + + @Override + public ItemStack[] getInventory() + { + return inventory; + } + + public FluidTank getWaterTank() + { + return waterTank; + } + + public FluidTank getSteamTank() + { + return steamTank; + } + + @Override + public FluidTank[] getTanksArray() + { + return new FluidTank[]{waterTank, steamTank}; + } + + @Override + public int[] getSlotsOnClosing() + { + return new int[]{BUCKET_IN, BUCKET_OUT}; + } + + @Override + public void loadFromNBT(NBTTagCompound compound) + { + NBTTagCompound jetpackTag = compound.getCompoundTag(TAG_WEARABLE_COMPOUND); + setInventoryFromTagList(jetpackTag.getTagList(TAG_INVENTORY, NBT.TAG_COMPOUND)); + waterTank.readFromNBT(jetpackTag.getCompoundTag(TAG_WATER_TANK)); + steamTank.readFromNBT(jetpackTag.getCompoundTag(TAG_STEAM_TANK)); + inUse = jetpackTag.getBoolean("inUse"); + status = jetpackTag.getBoolean("status"); + boiling = jetpackTag.getBoolean("boiling"); + leaking = jetpackTag.getBoolean("leaking"); + temperature = jetpackTag.getInteger("temperature"); + burnTicks = jetpackTag.getInteger("burnTicks"); + coolTicks = jetpackTag.getInteger("coolTicks"); + currentItemBurnTime = jetpackTag.getInteger("currentBurn"); + } + + @Override + public void saveToNBT(NBTTagCompound compound) + { + NBTTagCompound jetpackTag = new NBTTagCompound(); + jetpackTag.setTag(TAG_INVENTORY, getInventoryTagList()); + jetpackTag.setTag(TAG_WATER_TANK, waterTank.writeToNBT(new NBTTagCompound())); + jetpackTag.setTag(TAG_STEAM_TANK, steamTank.writeToNBT(new NBTTagCompound())); + jetpackTag.setBoolean("inUse", inUse); + jetpackTag.setBoolean("status", status); + jetpackTag.setBoolean("boiling", boiling); + jetpackTag.setBoolean("leaking", leaking); + jetpackTag.setInteger("temperature", temperature); + jetpackTag.setInteger("burnTicks", burnTicks); + jetpackTag.setInteger("coolTicks", coolTicks); + jetpackTag.setInteger("currentBurn", currentItemBurnTime); + + compound.setTag(TAG_WEARABLE_COMPOUND, jetpackTag); + } + + @Override + public boolean updateTankSlots() + { + boolean changesMade = false; + while (InventoryActions.transferContainerTank(this, getWaterTank(), BUCKET_IN)) + changesMade = true; + return changesMade; + } + + @Override + public void dirtyTanks() + { + getWearableCompound().setTag(TAG_WATER_TANK, waterTank.writeToNBT(new NBTTagCompound())); + getWearableCompound().setTag(TAG_STEAM_TANK, steamTank.writeToNBT(new NBTTagCompound())); + } + + public void dirtyBoiler() + { + NBTTagCompound jetpackTag = getWearableCompound(); + jetpackTag.setBoolean("boiling", boiling); + jetpackTag.setBoolean("leaking", leaking); + jetpackTag.setInteger("temperature", temperature); + jetpackTag.setInteger("burnTicks", burnTicks); + jetpackTag.setInteger("coolTicks", coolTicks); + jetpackTag.setInteger("currentBurn", currentItemBurnTime); + } + + public int getBurnTimeRemainingScaled(int scale) + { + if (this.currentItemBurnTime == 0) + this.currentItemBurnTime = 200; + + return this.burnTicks * scale / this.currentItemBurnTime; + } + + public int consumeFuel() + { + int result = 0; + if (isFuel(inventory[FUEL_SLOT])) + { + result = TileEntityFurnace.getItemBurnTime(inventory[FUEL_SLOT]); + --inventory[FUEL_SLOT].stackSize; + if (inventory[FUEL_SLOT].stackSize == 0) + { + inventory[FUEL_SLOT] = inventory[FUEL_SLOT].getItem().getContainerItem(inventory[FUEL_SLOT]); + } + dirtyInventory(); + } + return result; + } + + private boolean isFuel(ItemStack stack) + { + return TileEntityFurnace.isItemFuel(stack); + } + + public int getIncreasingFactor() + { + if (temperature < 50) return 20; + if (temperature < 100) return 15; + if (temperature < 150) return 10; + return 5; + } + + public int getDecreasingFactor() + { + if (temperature > 150) return 40; + if (temperature > 100) return 80; + if (temperature > 50) return 120; + return 5; + } + + + public boolean isInUse() + { + return inUse; + } + + public void setInUse(boolean inUse) + { + this.inUse = inUse; + } + + public boolean getStatus() + { + return status; + } + + public void setStatus(boolean status) + { + this.status = status; + } + + public boolean isBoiling() + { + return boiling; + } + + public void setBoiling(boolean boiling) + { + this.boiling = boiling; + } + + public boolean isLeaking() + { + return leaking; + } + + public void setLeaking(boolean leaking) + { + this.leaking = leaking; + } + + public int getTemperature() + { + return temperature; + } + + public void setTemperature(int temperature) + { + this.temperature = temperature; + } + + public int getBurnTicks() + { + return burnTicks; + } + + public void setBurnTicks(int burnTicks) + { + this.burnTicks = burnTicks; + } + + public int getCoolTicks() + { + return coolTicks; + } + + public void setCoolTicks(int coolTicks) + { + this.coolTicks = coolTicks; + } + + public void setCurrentItemBurnTime(int currentItemBurnTime) + { + this.currentItemBurnTime = currentItemBurnTime; + } + + private void detectAndConvertFromOldNBTFormat(NBTTagCompound compound) // backwards compatibility + { + if (compound == null || !compound.hasKey("jetpackData")) + return; + + NBTTagCompound oldJetpackTag = compound.getCompoundTag("jetpackData"); + NBTTagList oldItems = oldJetpackTag.getTagList("inventory", NBT.TAG_COMPOUND); + waterTank.readFromNBT(oldJetpackTag.getCompoundTag("waterTank")); + steamTank.readFromNBT(oldJetpackTag.getCompoundTag("steamTank")); + + NBTTagCompound newJetpackTag = new NBTTagCompound(); + newJetpackTag.setTag(TAG_INVENTORY, oldItems); + newJetpackTag.setTag(TAG_WATER_TANK, waterTank.writeToNBT(new NBTTagCompound())); + newJetpackTag.setTag(TAG_STEAM_TANK, steamTank.writeToNBT(new NBTTagCompound())); + + compound.setTag(TAG_WEARABLE_COMPOUND, newJetpackTag); + compound.removeTag("jetpackData"); + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCopterPack.java b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCopterPack.java index 81a47362..e1716264 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCopterPack.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCopterPack.java @@ -1,229 +1,125 @@ package com.darkona.adventurebackpack.inventory; -import com.darkona.adventurebackpack.item.ItemCopterPack; -import com.darkona.adventurebackpack.reference.GeneralReference; -import com.darkona.adventurebackpack.util.FluidUtils; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.fluids.FluidTank; +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.item.ItemCopterPack; + +import static com.darkona.adventurebackpack.common.Constants.Copter.BUCKET_IN; +import static com.darkona.adventurebackpack.common.Constants.Copter.BUCKET_OUT; +import static com.darkona.adventurebackpack.common.Constants.Copter.TAG_FUEL_TANK; +import static com.darkona.adventurebackpack.common.Constants.Copter.TAG_STATUS; +import static com.darkona.adventurebackpack.common.Constants.TAG_INVENTORY; +import static com.darkona.adventurebackpack.common.Constants.TAG_WEARABLE_COMPOUND; + /** * Created on 02/01/2015 * * @author Darkona */ -public class InventoryCopterPack implements IInventoryTanks +public class InventoryCopterPack extends InventoryAdventure { - private ItemStack containerStack; - public FluidTank fuelTank = new FluidTank(6000); - public int tickCounter = 0; - public byte status = ItemCopterPack.OFF_MODE; - private ItemStack[] inventory = new ItemStack[2]; - + private FluidTank fuelTank = new FluidTank(Constants.Copter.FUEL_CAPACITY); + private byte status = ItemCopterPack.OFF_MODE; + private int tickCounter = 0; public InventoryCopterPack(ItemStack copterPack) { - status = ItemCopterPack.OFF_MODE; - containerStack = copterPack; - if(!copterPack.hasTagCompound()) - { - copterPack.stackTagCompound = new NBTTagCompound(); - saveToNBT(copterPack.stackTagCompound); - } - + super(copterPack, Constants.Copter.INVENTORY_SIZE); + detectAndConvertFromOldNBTFormat(containerStack.stackTagCompound); openInventory(); } - public FluidTank getFuelTank() - { - return fuelTank; - } - - public void consumeFuel(int quantity) - { - fuelTank.drain(quantity, true); - dirtyTanks(); - } - - public boolean canConsumeFuel(int quantity) - { - return fuelTank.drain(quantity, false) != null && fuelTank.drain(quantity, false).amount > 0; - } - - @Override - public int getSizeInventory() - { - return inventory.length; - } - @Override - public ItemStack getStackInSlot(int i) + public ItemStack[] getInventory() { - return inventory[i]; + return inventory; } - @Override - public ItemStack decrStackSize(int slot, int quantity) + public FluidTank getFuelTank() { - ItemStack itemstack = getStackInSlot(slot); - - if (itemstack != null) - { - if (itemstack.stackSize <= quantity) - { - setInventorySlotContents(slot, null); - } else - { - itemstack = itemstack.splitStack(quantity); - } - } - return itemstack; + return fuelTank; } @Override - public ItemStack getStackInSlotOnClosing(int i) + public FluidTank[] getTanksArray() { - return inventory[i]; + return new FluidTank[]{fuelTank}; } @Override - public void setInventorySlotContents(int slot, ItemStack stack) + public int[] getSlotsOnClosing() { - inventory[slot] = stack; - if (stack != null && stack.stackSize > getInventoryStackLimit()) - { - stack.stackSize = getInventoryStackLimit(); - } - if(FluidContainerRegistry.isFilledContainer(stack) && GeneralReference.isValidFuel(FluidContainerRegistry.getFluidForFilledItem(stack).getFluid())) - { - InventoryActions.transferContainerTank(this, fuelTank, 0); - }else - if(FluidContainerRegistry.isEmptyContainer(stack) && fuelTank.getFluid()!=null && FluidUtils.isContainerForFluid(stack, fuelTank.getFluid().getFluid())) - { - InventoryActions.transferContainerTank(this, fuelTank, 0); - } - dirtyTanks(); - dirtyInventory(); + return new int[]{BUCKET_IN, BUCKET_OUT}; } @Override - public String getInventoryName() + public void loadFromNBT(NBTTagCompound compound) { - return "Copter Pack"; + NBTTagCompound copterTag = compound.getCompoundTag(TAG_WEARABLE_COMPOUND); + setInventoryFromTagList(copterTag.getTagList(TAG_INVENTORY, NBT.TAG_COMPOUND)); + fuelTank.readFromNBT(copterTag.getCompoundTag(TAG_FUEL_TANK)); + status = copterTag.getByte(TAG_STATUS); + tickCounter = copterTag.getInteger("tickCounter"); } @Override - public boolean hasCustomInventoryName() + public void saveToNBT(NBTTagCompound compound) { - return true; - } + NBTTagCompound copterTag = new NBTTagCompound(); + copterTag.setTag(TAG_INVENTORY, getInventoryTagList()); + copterTag.setTag(TAG_FUEL_TANK, fuelTank.writeToNBT(new NBTTagCompound())); + copterTag.setByte(TAG_STATUS, status); + copterTag.setInteger("tickCounter", this.tickCounter); - @Override - public int getInventoryStackLimit() - { - return 64; + compound.setTag(TAG_WEARABLE_COMPOUND, copterTag); } @Override - public void markDirty() + public boolean updateTankSlots() { - containerStack.stackTagCompound.setTag("fuelTank", fuelTank.writeToNBT(new NBTTagCompound())); - containerStack.stackTagCompound.setByte("status", status); - containerStack.stackTagCompound.setInteger("tickCounter", this.tickCounter); + boolean changesMade = false; + while (InventoryActions.transferContainerTank(this, getFuelTank(), BUCKET_IN)) + changesMade = true; + return changesMade; } @Override public void dirtyTanks() { - containerStack.stackTagCompound.setTag("fuelTank", fuelTank.writeToNBT(new NBTTagCompound())); - } - - @Override - public void dirtyInventory() - { - - } - - public void dirtyCounter() - { - containerStack.stackTagCompound.setInteger("tickCounter", this.tickCounter); - } - - @Override - public boolean isUseableByPlayer(EntityPlayer player) - { - return true; - } - - @Override - public void openInventory() - { - loadFromNBT(containerStack.stackTagCompound); + getWearableCompound().setTag(TAG_FUEL_TANK, fuelTank.writeToNBT(new NBTTagCompound())); } - @Override - public void closeInventory() - { - saveToNBT(containerStack.stackTagCompound); - } - - public void closeInventoryNoStatus() - { - containerStack.stackTagCompound.setTag("fuelTank", this.fuelTank.writeToNBT(new NBTTagCompound())); - containerStack.stackTagCompound.setInteger("tickCounter", this.tickCounter); - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack stack) + public void dirtyStatus() { - return false; + getWearableCompound().setByte(TAG_STATUS, status); } - public void onInventoryChanged() + public boolean canConsumeFuel(int quantity) { - - ItemStack container = getStackInSlot(0); - - closeInventory(); + return fuelTank.drain(quantity, false) != null && fuelTank.drain(quantity, false).amount > 0; } - @Override - public void setInventorySlotContentsNoSave(int slot, ItemStack stack) + public void consumeFuel(int quantity) { - if (slot > inventory.length) return; - inventory[slot] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) - { - stack.stackSize = this.getInventoryStackLimit(); - } + fuelTank.drain(quantity, true); + dirtyTanks(); } - @Override - public ItemStack decrStackSizeNoSave(int slot, int amount) + public byte getStatus() { - if (slot < inventory.length && inventory[slot] != null) - { - if (inventory[slot].stackSize > amount) - { - ItemStack result = inventory[slot].splitStack(amount); - return result; - } - ItemStack stack = inventory[slot]; - setInventorySlotContentsNoSave(slot, null); - return stack; - } - return null; + return status; } - public ItemStack getParentItemStack() + public void setStatus(byte status) { - return this.containerStack; + this.status = status; } - public int getTickCounter() { return tickCounter; @@ -234,52 +130,22 @@ public void setTickCounter(int ticks) this.tickCounter = ticks; } - public byte getStatus() + private void detectAndConvertFromOldNBTFormat(NBTTagCompound compound) // backwards compatibility { - return status; - } + if (compound == null || compound.hasKey(TAG_WEARABLE_COMPOUND)) + return; - @Override - public boolean updateTankSlots() - { - return false; - } + if (compound.hasKey("status")) + compound.removeTag("status"); + if (compound.hasKey("tickCounter")) + compound.removeTag("tickCounter"); - @Override - public void loadFromNBT(NBTTagCompound compound) - { fuelTank.readFromNBT(compound.getCompoundTag("fuelTank")); - status = compound.getByte("status"); - tickCounter = compound.getInteger("tickCounter"); - } - - @Override - public void saveToNBT(NBTTagCompound compound) - { - compound.setTag("fuelTank", fuelTank.writeToNBT(new NBTTagCompound())); - compound.setByte("status", status); - compound.setInteger("tickCounter", this.tickCounter); - } - - @Override - public FluidTank[] getTanksArray() - { - FluidTank[] tanks = {fuelTank}; - return tanks; - } - public void setStatus(byte status) - { - this.status = status; - } - - public void dirtyStatus() - { - containerStack.stackTagCompound.setByte("status", status); - } + NBTTagCompound newCopterTag = new NBTTagCompound(); + newCopterTag.setTag(TAG_FUEL_TANK, fuelTank.writeToNBT(new NBTTagCompound())); - public void setContainerStack(ItemStack containerStack) - { - this.containerStack = containerStack; + compound.setTag(TAG_WEARABLE_COMPOUND, newCopterTag); + compound.removeTag("fuelTank"); } } diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCraftingBackpack.java b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCraftingBackpack.java new file mode 100644 index 00000000..32c7c236 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/InventoryCraftingBackpack.java @@ -0,0 +1,25 @@ +package com.darkona.adventurebackpack.inventory; + +import javax.annotation.Nullable; + +import net.minecraft.inventory.Container; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; + +/** + * Created on 04.02.2018 + * + * @author Ugachaga + */ +public class InventoryCraftingBackpack extends InventoryCrafting +{ + public InventoryCraftingBackpack(Container eventHandler, int columns, int rows) + { + super(eventHandler, columns, rows); + } + + public void setInventorySlotContentsNoUpdate(int slotID, @Nullable ItemStack stack) + { + this.stackList[slotID] = stack; + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/InventorySteamJetpack.java b/src/main/java/com/darkona/adventurebackpack/inventory/InventorySteamJetpack.java deleted file mode 100644 index ee07d6dd..00000000 --- a/src/main/java/com/darkona/adventurebackpack/inventory/InventorySteamJetpack.java +++ /dev/null @@ -1,492 +0,0 @@ -package com.darkona.adventurebackpack.inventory; - -import com.darkona.adventurebackpack.util.FluidUtils; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntityFurnace; -import net.minecraftforge.fluids.FluidContainerRegistry; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidTank; - -/** - * Created on 15/01/2015 - * - * @author Darkona - */ -public class InventorySteamJetpack implements IInventoryTanks -{ - public static final boolean OFF = false; - public static final boolean ON = true; - private FluidTank waterTank = new FluidTank(6000); - private FluidTank steamTank = new FluidTank(12000); - private ItemStack[] inventory = new ItemStack[3]; - private int temperature = 25; - private boolean status = OFF; - private int burnTicks = 0; - private ItemStack containerStack; - private long systemTime = 0; - private boolean boiling = false; - private boolean leaking = false; - private boolean inUse = false; - public int currentItemBurnTime = 0; - - - public static final int MAX_TEMPERATURE = 200; - public static final int BUCKET_IN_SLOT = 0; - public static final int BUCKET_OUT_SLOT = 1; - public static final int FUEL_SLOT = 2; - private int coolTicks = 5000; - - public InventorySteamJetpack(final ItemStack jetpack) - { - this.containerStack = jetpack; - if (!containerStack.hasTagCompound()) - { - containerStack.stackTagCompound = new NBTTagCompound(); - closeInventory(); - } - openInventory(); - } - - public int getBurnTimeRemainingScaled(int scale) - { - if (this.currentItemBurnTime == 0) - { - this.currentItemBurnTime = 200; - } - - return this.burnTicks * scale / this.currentItemBurnTime; - } - - @Override - public boolean updateTankSlots() - { - return false; - } - - @Override - public void loadFromNBT(NBTTagCompound compound) - { - if(compound.hasKey("jetpackData")) - { - NBTTagCompound jetpackData = compound.getCompoundTag("jetpackData"); - waterTank.readFromNBT(jetpackData.getCompoundTag("waterTank")); - steamTank.readFromNBT(jetpackData.getCompoundTag("steamTank")); - temperature = jetpackData.getInteger("temperature"); - status = jetpackData.getBoolean("status"); - burnTicks = jetpackData.getInteger("burnTicks"); - coolTicks = jetpackData.getInteger("coolTicks"); - systemTime = jetpackData.getLong("systemTime"); - inUse = jetpackData.getBoolean("inUse"); - boiling = jetpackData.getBoolean("boiling"); - leaking = jetpackData.getBoolean("leaking"); - currentItemBurnTime = jetpackData.getInteger("currentBurn"); - NBTTagList items = jetpackData.getTagList("inventory", net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND); - for (int i = 0; i < items.tagCount(); i++) - { - NBTTagCompound item = items.getCompoundTagAt(i); - byte slot = item.getByte("Slot"); - if (slot >= 0 && slot < inventory.length) - { - inventory[slot] = ItemStack.loadItemStackFromNBT(item); - } - } - } - } - - @Override - public void saveToNBT(NBTTagCompound compound) - { - NBTTagCompound jetpackData; - if(compound.hasKey("jetpackData")) - { - jetpackData = compound.getCompoundTag("jetpackData"); - }else - { - jetpackData = new NBTTagCompound(); - } - - jetpackData.setTag("waterTank",waterTank.writeToNBT(new NBTTagCompound())); - jetpackData.setTag("steamTank",steamTank.writeToNBT(new NBTTagCompound())); - jetpackData.setInteger("temperature", temperature); - jetpackData.setBoolean("status", status); - jetpackData.setInteger("burnTicks", burnTicks); - jetpackData.setInteger("coolTicks", coolTicks); - jetpackData.setLong("systemTime",systemTime); - jetpackData.setBoolean("inUse", inUse); - jetpackData.setBoolean("boiling",boiling); - jetpackData.setBoolean("leaking",leaking); - jetpackData.setInteger("currentBurn",currentItemBurnTime); - NBTTagList items = new NBTTagList(); - for (int i = 0; i < inventory.length; i++) - { - ItemStack stack = inventory[i]; - if (stack != null) - { - NBTTagCompound item = new NBTTagCompound(); - item.setByte("Slot", (byte) i); - stack.writeToNBT(item); - items.appendTag(item); - } - } - jetpackData.setTag("inventory", items); - compound.setTag("jetpackData",jetpackData); - } - - @Override - public FluidTank[] getTanksArray() - { - FluidTank[] tanks = {waterTank,steamTank}; - return tanks; - } - - @Override - public void dirtyInventory() - { - NBTTagList items = new NBTTagList(); - for (int i = 0; i < inventory.length; i++) - { - ItemStack stack = inventory[i]; - if (stack != null) - { - NBTTagCompound item = new NBTTagCompound(); - item.setByte("Slot", (byte) i); - stack.writeToNBT(item); - items.appendTag(item); - } - } - containerStack.stackTagCompound.getCompoundTag("jetpackData").setTag("inventory", items); - } - - @Override - public void dirtyTanks() - { - containerStack.stackTagCompound.getCompoundTag("jetPackData").setTag("waterTank",waterTank.writeToNBT(new NBTTagCompound())); - containerStack.stackTagCompound.getCompoundTag("jetPackData").setTag("steamTank",steamTank.writeToNBT(new NBTTagCompound())); - } - - public void dirtyBoiler() - { - NBTTagCompound jetpackData = containerStack.stackTagCompound.getCompoundTag("jetPackData"); - jetpackData.setBoolean("boiling", boiling); - jetpackData.setBoolean("leaking", leaking); - jetpackData.setInteger("temperature", temperature); - jetpackData.setInteger("burnTicks", burnTicks); - jetpackData.setInteger("coolTicks", coolTicks); - jetpackData.setInteger("currentBurn",currentItemBurnTime); - } - - public int consumeFuel() - { - int result = 0; - if(isFuel(inventory[FUEL_SLOT])) - { - result = TileEntityFurnace.getItemBurnTime(inventory[FUEL_SLOT]); - --inventory[FUEL_SLOT].stackSize; - if(inventory[FUEL_SLOT].stackSize == 0) - { - inventory[FUEL_SLOT] = inventory[FUEL_SLOT].getItem().getContainerItem(inventory[FUEL_SLOT]); - } - dirtyInventory(); - } - return result; - } - - public boolean isFuel(ItemStack stack) - { - return TileEntityFurnace.isItemFuel(stack); - } - - - - @Override - public void setInventorySlotContentsNoSave(int slot, ItemStack stack) - { - if (slot > inventory.length) return; - inventory[slot] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) - { - stack.stackSize = this.getInventoryStackLimit(); - } - } - - @Override - public ItemStack decrStackSizeNoSave(int slot, int amount) - { - if (slot < inventory.length && inventory[slot] != null) - { - if (inventory[slot].stackSize > amount) - { - ItemStack result = inventory[slot].splitStack(amount); - return result; - } - ItemStack stack = inventory[slot]; - setInventorySlotContentsNoSave(slot, null); - return stack; - } - return null; - } - - @Override - public int getSizeInventory() - { - return inventory.length; - } - - @Override - public ItemStack getStackInSlot(int slot) - { - return inventory[slot]; - } - - @Override - public ItemStack decrStackSize(int slot, int quantity) - { - ItemStack itemstack = getStackInSlot(slot); - - if (itemstack != null) - { - if (itemstack.stackSize <= quantity) - { - if(slot == FUEL_SLOT) - { - setInventorySlotContents(slot, itemstack.getItem().getContainerItem(itemstack)); - } - else - { - setInventorySlotContents(slot, null); - } - } else - { - itemstack = itemstack.splitStack(quantity); - } - } - return itemstack; - } - - @Override - public ItemStack getStackInSlotOnClosing(int i) - { - return (i == 0 || i== 1) ? inventory[i] : null; - } - - @Override - public void setInventorySlotContents(int slot, ItemStack stack) - { - inventory[slot] = stack; - if (stack != null && stack.stackSize > getInventoryStackLimit()) - { - stack.stackSize = getInventoryStackLimit(); - } - if(slot < FUEL_SLOT)onInventoryChanged(); - dirtyInventory(); - -} - - public void onInventoryChanged() - { - for (int i = 0; i < inventory.length; i++) - { - if (i == 0) - { - ItemStack container = getStackInSlot(i); - if(FluidContainerRegistry.isFilledContainer(container) && FluidUtils.isContainerForFluid(container, FluidRegistry.WATER)) - { - InventoryActions.transferContainerTank(this, waterTank, i); - }else - if(FluidContainerRegistry.isEmptyContainer(container) && waterTank.getFluid()!=null && FluidUtils.isContainerForFluid(container, FluidRegistry.WATER)) - { - InventoryActions.transferContainerTank(this, waterTank, i); - } - } - } - markDirty(); - } - @Override - public String getInventoryName() - { - return "Steam Jetpack"; - } - - @Override - public boolean hasCustomInventoryName() - { - return true; - } - - @Override - public int getInventoryStackLimit() - { - return 64; - } - - @Override - public void markDirty() - { - saveToNBT(containerStack.stackTagCompound); - } - - @Override - public boolean isUseableByPlayer(EntityPlayer p_70300_1_) - { - return true; - } - - @Override - public void openInventory() - { - loadFromNBT(containerStack.stackTagCompound); - } - - @Override - public void closeInventory() - { - saveToNBT(containerStack.stackTagCompound); - } - - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) - { - if(slot == BUCKET_IN_SLOT)return SlotFluid.valid(stack) && FluidUtils.isContainerForFluid(stack, FluidRegistry.WATER); - if(slot == FUEL_SLOT)return TileEntityFurnace.isItemFuel(stack); - return false; - } - - public ItemStack getParentItemStack() - { - return containerStack; - } - - public FluidTank getWaterTank() - { - return waterTank; - } - - public FluidTank getSteamTank() - { - return steamTank; - } - - public boolean getStatus() - { - return status; - } - - public void setStatus(boolean status) - { - this.status = status; - } - - public int getTemperature() - { - return temperature; - } - - public void setTemperature(int temperature) - { - this.temperature = temperature; - } - - public boolean isInUse() - { - return inUse; - } - - public void setInUse(boolean inUse) - { - this.inUse = inUse; - } - - public boolean isBoiling() - { - return boiling; - } - - public void setBoiling(boolean boiling) - { - this.boiling = boiling; - } - - public boolean isLeaking() - { - return leaking; - } - - public void setLeaking(boolean leaking) - { - this.leaking = leaking; - } - - public long getSystemTime() - { - return systemTime; - } - - public void setSystemTime(long systemTime) - { - this.systemTime = systemTime; - } - - public int getBurnTicks() - { - return burnTicks; - } - - public void setBurnTicks(int burnTicks) - { - this.burnTicks = burnTicks; - } - - public ItemStack[] getInventory() - { - return inventory; - } - - public void setInventory(ItemStack[] inventory) - { - this.inventory = inventory; - } - - public int getIncreasingFactor() - { - if(temperature < 50)return 20; - if(temperature < 100)return 15; - if(temperature < 150)return 10; - return 5; - } - - public int getDecreasingFactor() - { - if(temperature > 150)return 40; - if(temperature > 100)return 80; - if(temperature > 50)return 120; - return 5; - } - public int getCoolTicks() - { - return coolTicks; - } - - public void setCoolTicks(int coolTicks) - { - this.coolTicks = coolTicks; - } - - public void setContainerStack(ItemStack containerStack) - { - this.containerStack = containerStack; - } - - public ItemStack getContainerStack() - { - return containerStack; - } - - public void calculateLostTime() - { - long elapsedTimesince = System.currentTimeMillis() - systemTime; - - } -} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotAdventure.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotAdventure.java new file mode 100644 index 00000000..ef37fbcb --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/SlotAdventure.java @@ -0,0 +1,17 @@ +package com.darkona.adventurebackpack.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; + +/** + * Created on 17/01/2015 + * + * @author Darkona + */ +abstract class SlotAdventure extends Slot +{ + SlotAdventure(IInventory inventory, int slotIndex, int posX, int posY) + { + super(inventory, slotIndex, posX, posY); + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotAdventureBackpack.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotAdventureBackpack.java deleted file mode 100644 index dfc48f5d..00000000 --- a/src/main/java/com/darkona/adventurebackpack/inventory/SlotAdventureBackpack.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.darkona.adventurebackpack.inventory; - -import com.darkona.adventurebackpack.util.Utils; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Slot; - -/** - * Created on 17/01/2015 - * - * @author Darkona - */ -public abstract class SlotAdventureBackpack extends Slot -{ - public SlotAdventureBackpack(IInventory p_i1824_1_, int p_i1824_2_, int p_i1824_3_, int p_i1824_4_) - { - super(p_i1824_1_, p_i1824_2_, p_i1824_3_, p_i1824_4_); - } - - @Override - public void onSlotChanged() - { - if(Utils.inServer()) - { - if (inventory instanceof IInventoryTanks) - ((IInventoryTanks) this.inventory).dirtyInventory(); - } - } -} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotBackpack.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotBackpack.java index bcf50b24..d9629809 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/SlotBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/SlotBackpack.java @@ -1,34 +1,75 @@ package com.darkona.adventurebackpack.inventory; -import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; -import com.darkona.adventurebackpack.init.ModBlocks; -import com.darkona.adventurebackpack.item.ItemAdventureBackpack; -import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import com.darkona.adventurebackpack.config.ConfigHandler; + /** * Created by Darkona on 12/10/2014. */ -public class SlotBackpack extends SlotAdventureBackpack +public class SlotBackpack extends SlotAdventure { + private static final String[] FORBIDDEN_CLASSES = { + // Adventure Backpack 2 + "com.darkona.adventurebackpack.item.ItemAdventureBackpack", + // Backpack Mod + "de.eydamos.backpack.item.ItemBackpack", + "de.eydamos.backpack.item.ItemWorkbenchBackpack", + // Blue Power Canvas Bags + "com.bluepowermod.item.ItemCanvasBag", + // Extra Utilities Golden Bag of Holding + "com.rwtema.extrautils.item.ItemGoldenBag", + // Forestry Backpacks +addons + "forestry.storage.items.ItemBackpack", + "forestry.storage.items.ItemBackpackNaturalist", + // Jabba Dolly + "mcp.mobius.betterbarrels.common.items.dolly.ItemBarrelMover", + "mcp.mobius.betterbarrels.common.items.dolly.ItemDiamondMover", + // Project Red Exploration Backpacks + "mrtjp.projectred.exploration.ItemBackpack",}; - public SlotBackpack(IInventoryAdventureBackpack inventory, int id, int x, int y) + SlotBackpack(IInventory inventory, int slotIndex, int posX, int posY) { - super(inventory, id, x, y); + super(inventory, slotIndex, posX, posY); } - @Override - public boolean isItemValid(ItemStack stack) + public static boolean isValidItem(ItemStack stack) { - return (!(stack.getItem() instanceof ItemAdventureBackpack) && !(stack.getItem() == Item.getItemFromBlock(ModBlocks.blockBackpack))); + if (stack == null) return false; + Item itemCurrent = stack.getItem(); + + for (String classDisallowed : FORBIDDEN_CLASSES) + { + if (itemCurrent.getClass().getName().equals(classDisallowed)) return false; + } + + if (ConfigHandler.enableItemFilters) + { + for (String itemDisallowed : ConfigHandler.nameLocalized) + { + if (stack.getDisplayName().equalsIgnoreCase(itemDisallowed)) return false; + } + for (String itemDisallowed : ConfigHandler.nameInternalID) + { + if (Item.itemRegistry.getNameForObject(itemCurrent).equals(itemDisallowed)) return false; + } + for (String itemDisallowed : ConfigHandler.nameInternalIDs) + { + if (Item.itemRegistry.getNameForObject(itemCurrent).contains(itemDisallowed)) return false; + } + for (String itemDisallowed : ConfigHandler.nameUnlocalized) + { + if (itemCurrent.getUnlocalizedName().equalsIgnoreCase(itemDisallowed)) return false; + } + } + return true; } @Override - public void onPickupFromSlot(EntityPlayer p_82870_1_, ItemStack p_82870_2_) + public boolean isItemValid(ItemStack stack) { - super.onPickupFromSlot(p_82870_1_, p_82870_2_); + return isValidItem(stack); } - - } diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotCraftMatrix.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotCraftMatrix.java new file mode 100644 index 00000000..6fa01d8a --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/SlotCraftMatrix.java @@ -0,0 +1,30 @@ +package com.darkona.adventurebackpack.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +/** + * Created on 04.02.2018 + * + * @author Ugachaga + */ +public class SlotCraftMatrix extends SlotAdventure +{ + SlotCraftMatrix(IInventory craftMatrix, int slotIndex, int posX, int posY) + { + super(craftMatrix, slotIndex, posX, posY); + } + + @Override + public boolean isItemValid(ItemStack stack) + { + return false; + } + + @Override + public boolean canTakeStack(EntityPlayer player) + { + return false; + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotCraftResult.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotCraftResult.java new file mode 100644 index 00000000..dfb1352f --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/SlotCraftResult.java @@ -0,0 +1,30 @@ +package com.darkona.adventurebackpack.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.SlotCrafting; +import net.minecraft.item.ItemStack; + +/** + * Created on 04.02.2018 + * + * @author Ugachaga + */ +public class SlotCraftResult extends SlotCrafting +{ + private ContainerBackpack eventHandler; + + public SlotCraftResult(ContainerBackpack container, EntityPlayer player, IInventory craftMatrix, IInventory inventory, int slotIndex, int posX, int posY) + { + super(player, craftMatrix, inventory, slotIndex, posX, posY); + this.eventHandler = container; + } + + @Override + public void onPickupFromSlot(EntityPlayer player, ItemStack stack) + { + eventHandler.syncCraftMatrixWithInventory(true); // pre craft sync + super.onPickupFromSlot(player, stack); + eventHandler.syncCraftMatrixWithInventory(false); // post craft sync + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluid.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluid.java index c8b6c397..08d0d439 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluid.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluid.java @@ -1,39 +1,102 @@ package com.darkona.adventurebackpack.inventory; -import com.darkona.adventurebackpack.util.Utils; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidTank; + +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.item.ItemHose; +import com.darkona.adventurebackpack.util.Utils; /** * Created on 12/10/2014 - * @author Darkona - * * + * @author Darkona */ -public class SlotFluid extends SlotAdventureBackpack +public class SlotFluid extends SlotAdventure { + SlotFluid(IInventory inventory, int slotIndex, int posX, int posY) + { + super(inventory, slotIndex, posX, posY); + } + + static boolean isContainer(ItemStack stack) + { + return FluidContainerRegistry.isContainer(stack); + } + + static boolean isEmpty(ItemStack stack) + { + return FluidContainerRegistry.isEmptyContainer(stack); + } + + static boolean isEmpty(FluidTank tank) + { + return tank.getFluidAmount() == 0; + } + + static boolean isFilled(ItemStack stack) + { + return FluidContainerRegistry.isFilledContainer(stack); + } - public SlotFluid(IInventory inventory, int id, int x, int y) + static boolean isEqualFluid(ItemStack container, FluidTank tank) { - super(inventory, id, x, y); + return getFluidID(container) == getFluidID(tank); } - public static boolean valid(ItemStack stack) + static int getFluidID(ItemStack stack) { - return ((stack != null) && (FluidContainerRegistry.isContainer(stack))); + if (stack == null || isEmpty(stack)) + return -1; + return FluidContainerRegistry.getFluidForFilledItem(stack).getFluid().getID(); + } + + static int getFluidID(FluidTank tank) + { + if (tank == null || tank.getFluidAmount() <= 0) + return -1; + return tank.getFluid().getFluid().getID(); + } + + static Fluid getFluid(ItemStack stack) + { + if (stack == null || isEmpty(stack)) + return null; + return FluidContainerRegistry.getFluidForFilledItem(stack).getFluid(); + } + + static int getCapacity(ItemStack stack) + { + return FluidContainerRegistry.getContainerCapacity(stack); + } + + static boolean canFitToTank(ItemStack container, FluidTank tank) + { + return tank.getFluidAmount() + getCapacity(container) <= tank.getCapacity(); + } + + static boolean isEqualAndCanFit(ItemStack container, FluidTank tank) + { + return isEqualFluid(container, tank) && canFitToTank(container, tank); + } + + static ItemStack getEmptyContainer(ItemStack container) + { + return FluidContainerRegistry.drainFluidContainer(container); } @Override public boolean isItemValid(ItemStack stack) { - return ((stack != null) && (FluidContainerRegistry.isContainer(stack))); + return stack != null && (isContainer(stack) || stack.getItem() instanceof ItemHose); } @Override public void onSlotChanged() { - if (Utils.inServer()) { if (inventory instanceof IInventoryTanks) @@ -45,8 +108,8 @@ public void onSlotChanged() } @Override - public void putStack(ItemStack par1ItemStack) + public int getSlotStackLimit() { - super.putStack(par1ItemStack); + return Constants.BASIC_TANK_CAPACITY / Constants.BUCKET; } } diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluidFuel.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluidFuel.java new file mode 100644 index 00000000..16fadd48 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluidFuel.java @@ -0,0 +1,43 @@ +package com.darkona.adventurebackpack.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.item.ItemHose; +import com.darkona.adventurebackpack.reference.GeneralReference; + +/** + * Created on 10.04.2017 + * + * @author Ugachaga + */ +public class SlotFluidFuel extends SlotFluid +{ + SlotFluidFuel(IInventory inventory, int slotIndex, int posX, int posY) + { + super(inventory, slotIndex, posX, posY); + } + + private static boolean isValidContainer(ItemStack stack) + { + return isEmpty(stack) || (isFilled(stack) && GeneralReference.isValidFuel(getFluid(stack).getName())); + } + + static boolean isValidItem(ItemStack stack) + { + return isContainer(stack) && isValidContainer(stack); + } + + @Override + public boolean isItemValid(ItemStack stack) + { + return stack != null && (isValidItem(stack) || stack.getItem() instanceof ItemHose); + } + + @Override + public int getSlotStackLimit() + { + return Constants.Copter.FUEL_CAPACITY / Constants.BUCKET; + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluidWater.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluidWater.java new file mode 100644 index 00000000..302c1b73 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/inventory/SlotFluidWater.java @@ -0,0 +1,55 @@ +package com.darkona.adventurebackpack.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidRegistry; + +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.item.ItemHose; +import com.darkona.adventurebackpack.util.FluidUtils; + +/** + * Created on 10.04.2017 + * + * @author Ugachaga + */ +public class SlotFluidWater extends SlotFluid +{ + SlotFluidWater(IInventory inventory, int slotIndex, int posX, int posY) + { + super(inventory, slotIndex, posX, posY); + } + + private static boolean isContainerForWater(ItemStack stack) + { + return FluidUtils.isContainerForFluid(stack, FluidRegistry.WATER); + } + + private static boolean isContainerWithWater(ItemStack stack) + { + return isFilled(stack) && FluidContainerRegistry.getFluidForFilledItem(stack).getFluid().getName().contains("water"); + } + + private static boolean isValidContainer(ItemStack stack) + { + return isContainerForWater(stack) && (isEmpty(stack) || isContainerWithWater(stack)); + } + + static boolean isValidItem(ItemStack stack) + { + return isContainer(stack) && isValidContainer(stack); + } + + @Override + public boolean isItemValid(ItemStack stack) + { + return stack != null && (isValidItem(stack) || stack.getItem() instanceof ItemHose); + } + + @Override + public int getSlotStackLimit() + { + return Constants.Jetpack.WATER_CAPACITY / Constants.BUCKET; + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotFuel.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotFuel.java index 622d41d6..7c6a2a8a 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/SlotFuel.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/SlotFuel.java @@ -1,19 +1,29 @@ package com.darkona.adventurebackpack.inventory; import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntityFurnace; /** * Created on 17/01/2015 * * @author Darkona */ -public class SlotFuel extends SlotAdventureBackpack +public class SlotFuel extends SlotAdventure { - public SlotFuel(IInventory p_i1824_1_, int p_i1824_2_, int p_i1824_3_, int p_i1824_4_) + SlotFuel(IInventory inventory, int slotIndex, int posX, int posY) { - super(p_i1824_1_, p_i1824_2_, p_i1824_3_, p_i1824_4_); + super(inventory, slotIndex, posX, posY); } + static boolean isValidItem(ItemStack stack) + { + return TileEntityFurnace.isItemFuel(stack) && !SlotFluid.isContainer(stack); // fuel slot accepts only solid fuel + } - + @Override + public boolean isItemValid(ItemStack stack) + { + return stack != null && isValidItem(stack); + } } diff --git a/src/main/java/com/darkona/adventurebackpack/inventory/SlotTool.java b/src/main/java/com/darkona/adventurebackpack/inventory/SlotTool.java index 1f93e9c6..7772541c 100644 --- a/src/main/java/com/darkona/adventurebackpack/inventory/SlotTool.java +++ b/src/main/java/com/darkona/adventurebackpack/inventory/SlotTool.java @@ -1,21 +1,34 @@ package com.darkona.adventurebackpack.inventory; -import com.darkona.adventurebackpack.item.ItemAdventureBackpack; -import com.darkona.adventurebackpack.item.ItemHose; import net.minecraft.inventory.IInventory; -import net.minecraft.item.*; +import net.minecraft.item.Item; +import net.minecraft.item.ItemFishingRod; +import net.minecraft.item.ItemFlintAndSteel; +import net.minecraft.item.ItemHoe; +import net.minecraft.item.ItemShears; +import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemTool; + +import com.darkona.adventurebackpack.util.GregtechUtils; +import com.darkona.adventurebackpack.util.ThaumcraftUtils; +import com.darkona.adventurebackpack.util.TinkersUtils; /** * Created on 12/10/2014 * * @author Darkona */ -public class SlotTool extends SlotAdventureBackpack +public class SlotTool extends SlotAdventure { + private static final String[] VALID_TOOL_NAMES = {"axe", "crowbar", "drill", "grafter", "hammer", "scoop", "shovel", + "wrench",}; + private static final String[] INVALID_TOOL_NAMES = {"bow", "bucket", "shield", "sword",}; + private static final String[] INVALID_TINKER_NAMES = {"battleaxe", "bow", "cleaver", "cutlass", "dagger", "rapier", + "sabre", "shield", "sign", "sword",}; - public SlotTool(IInventory inventory, int id, int x, int y) + SlotTool(IInventory inventory, int slotIndex, int posX, int posY) { - super(inventory, id, x, y); + super(inventory, slotIndex, posX, posY); } @Override @@ -26,87 +39,85 @@ public boolean isItemValid(ItemStack stack) public static boolean isValidTool(ItemStack stack) { + if (stack == null || stack.getMaxStackSize() != 1) + return false; - boolean valid = false; + Item item = stack.getItem(); + String clazzName = item.getClass().getName(); + String objectName = Item.itemRegistry.getNameForObject(item); + String itemName = item.getUnlocalizedName().toLowerCase(); - String[] validToolNames = { - "wrench", "hammer", "axe", "shovel", "grafter", "scoop", "crowbar", "mattock", "drill",/*"hatchet","excavator","chisel"*/ - }; - - String[] invalidToolNames = { - "bucket", "sword", "dagger", "sabre", "rapier", "shield", "cutlass", "bow", "whip" - }; + // Vanilla + if (item instanceof ItemTool || item instanceof ItemHoe || item instanceof ItemShears + || item instanceof ItemFishingRod || item instanceof ItemFlintAndSteel) + { + return true; + } - if (stack != null && stack.getMaxStackSize() == 1) + // GregTech + if (GregtechUtils.isTool(itemName)) { - Item item = stack.getItem(); - String name = item.getUnlocalizedName().toLowerCase(); - - // Vanilla - if (item instanceof ItemTool || item instanceof ItemHoe || item instanceof ItemShears || item instanceof ItemFishingRod || item instanceof ItemFlintAndSteel) - { - return true; - } - - //Adventure Backpack duh! - if (item instanceof ItemHose || item instanceof ItemAdventureBackpack) - { - return false; - } - - // Just for extra compatibility and/or security and/or less annoyance - for (String toolName : validToolNames) - { - String a = toolName; - if (name.contains(toolName)) return true; - } - - for (String toolName : invalidToolNames) - { - String a = toolName; - if (name.contains(toolName)) return false; - } - - //And also this because I'm a badass - try - { - // Tinker's Construct - if (item.getClass().getName().contains("tconstruct.items.tools")) return true; - } catch (Exception oops) - { - // oops.printStackTrace(); - } - try - { - //Buildcraft - if (java.lang.Class.forName("buildcraft.api.tools.IToolWrench").isInstance(item)) return true; - } catch (Exception oops) - { - // oops.printStackTrace(); - } - try - { - //IndustrialCraft - if (java.lang.Class.forName("ic2.api.item.IElectricItem").isInstance(item)) return true; - } catch (Exception oops) - { - // oops.printStackTrace(); - } - //Thaumcraft - try - { - //Thermal Expansion - if (java.lang.Class.forName("cofh.core.item.tool").isInstance(item)) return true; - if (java.lang.Class.forName("thermalexpansion.item.tool").isInstance(item)) return true; - } catch (Exception oops) - { - // oops.printStackTrace(); - } + int meta = stack.getItemDamage(); + return !(meta == 0 || meta == 24 || meta > 169); // 0 = sword, 24 = mortar, 170+ = turbines + } + if (itemName.startsWith("gt.metaitem")) return false; // charged baterries and such + // Tinkers Construct + if (TinkersUtils.isTool(clazzName)) + { + for (String toolName : INVALID_TINKER_NAMES) + if (itemName.contains(toolName)) return false; + return true; } - return valid; - } + // Thaumcraft + if (ThaumcraftUtils.isTool(stack)) return true; + + // Ender IO + // Yeta Wrench uses Shift+Scroll for switch own modes + if (objectName.equals("EnderIO:itemYetaWrench")) return false; + + // Extra Utilities + if (clazzName.equals("com.rwtema.extrautils.item.ItemBuildersWand")) return true; + + // Better builders Wands + if (objectName.startsWith("betterbuilderswands:wand")) return true; + + // Just for extra compatibility and/or security and/or less annoyance + for (String toolName : INVALID_TOOL_NAMES) + if (itemName.contains(toolName)) return false; + for (String toolName : VALID_TOOL_NAMES) + if (itemName.contains(toolName)) return true; + // Mekanism + if (clazzName.startsWith("mekanism.common.item")) + return !itemName.contains("disassembler") && !itemName.contains("robit"); + + // And also this because I'm a badass + try + { + // Buildcraft + if (java.lang.Class.forName("buildcraft.api.tools.IToolWrench").isInstance(item)) return true; + } + catch (ClassNotFoundException e) + { /* */ } + try + { + // IndustrialCraft + if (java.lang.Class.forName("ic2.api.item.IElectricItem").isInstance(item)) return true; + } + catch (ClassNotFoundException e) + { /* */ } + try + { + // Thermal Expansion + if (java.lang.Class.forName("cofh.core.item.tool").isInstance(item)) return true; + if (java.lang.Class.forName("thermalexpansion.item.tool").isInstance(item)) return true; + } + catch (ClassNotFoundException e) + { /* */ } + + return false; + } } diff --git a/src/main/java/com/darkona/adventurebackpack/item/ArmorAB.java b/src/main/java/com/darkona/adventurebackpack/item/ArmorAB.java index 7e29bb0f..4cc45f8a 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ArmorAB.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ArmorAB.java @@ -1,40 +1,39 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.CreativeTabAB; -import com.darkona.adventurebackpack.init.ModMaterials; -import com.darkona.adventurebackpack.reference.ModInfo; -import com.darkona.adventurebackpack.util.Resources; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import com.darkona.adventurebackpack.CreativeTabAB; +import com.darkona.adventurebackpack.init.ModMaterials; +import com.darkona.adventurebackpack.reference.ModInfo; +import com.darkona.adventurebackpack.util.Resources; /** * Created on 11/10/2014. + * * @author Javier Darkona */ public class ArmorAB extends ItemArmor { - /** * @param type 2 Chain * @param renderIndex 0 Helmet, 1 Plate, 2 Pants, 3 Boots */ - public ArmorAB(int renderIndex, int type) + ArmorAB(int renderIndex, int type) { super(ModMaterials.ruggedLeather, renderIndex, type); - setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB); + setCreativeTab(CreativeTabAB.TAB_AB); } - - protected String getUnwrappedUnlocalizedName(String unlocalizedName) + private String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } - @Override public String getUnlocalizedName(ItemStack stack) { @@ -44,7 +43,7 @@ public String getUnlocalizedName(ItemStack stack) @Override public String getUnlocalizedName() { - return String.format("item.%s%s", ModInfo.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); + return String.format("item.%s%s", ModInfo.MOD_ID + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override diff --git a/src/main/java/com/darkona/adventurebackpack/item/IBackWearableItem.java b/src/main/java/com/darkona/adventurebackpack/item/IBackWearableItem.java index c9467e3b..9243a95c 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/IBackWearableItem.java +++ b/src/main/java/com/darkona/adventurebackpack/item/IBackWearableItem.java @@ -1,12 +1,12 @@ package com.darkona.adventurebackpack.item; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.model.ModelBiped; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; /** * Created on 08/01/2015 @@ -15,18 +15,17 @@ */ public interface IBackWearableItem { - public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack); + void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack); - public void onPlayerDeath(World world, EntityPlayer player, ItemStack stack); + void onPlayerDeath(World world, EntityPlayer player, ItemStack stack); - public void onEquipped(World world, EntityPlayer player, ItemStack stack); + void onEquipped(World world, EntityPlayer player, ItemStack stack); - public void onUnequipped(World world, EntityPlayer player, ItemStack stack); + void onUnequipped(World world, EntityPlayer player, ItemStack stack); @SideOnly(Side.CLIENT) - public ModelBiped getWearableModel(ItemStack wearable); + ModelBiped getWearableModel(ItemStack wearable); @SideOnly(Side.CLIENT) - public ResourceLocation getWearableTexture(ItemStack wearable); - + ResourceLocation getWearableTexture(ItemStack wearable); } diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemAB.java b/src/main/java/com/darkona/adventurebackpack/item/ItemAB.java index 3bcf1a16..65cbcdc9 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemAB.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemAB.java @@ -1,40 +1,40 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.CreativeTabAB; -import com.darkona.adventurebackpack.reference.ModInfo; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import com.darkona.adventurebackpack.CreativeTabAB; +import com.darkona.adventurebackpack.reference.ModInfo; /** * Created by Darkona on 10/10/2014. */ public class ItemAB extends Item { - - public ItemAB() + ItemAB() { super(); - setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB); + setCreativeTab(CreativeTabAB.TAB_AB); } @Override public String getUnlocalizedName(ItemStack stack) { - return String.format("item.%s%s", ModInfo.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); + return String.format("item.%s%s", ModInfo.MOD_ID + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override public String getUnlocalizedName() { - return String.format("item.%s%s", ModInfo.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); + return String.format("item.%s%s", ModInfo.MOD_ID + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } public String getUnlocalizedName(String name) { - return String.format("item.%s%s", ModInfo.MOD_ID.toLowerCase() + ":", name); + return String.format("item.%s%s", ModInfo.MOD_ID + ":", name); } @Override @@ -44,8 +44,7 @@ public void registerIcons(IIconRegister iconRegister) itemIcon = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1)); } - - protected String getUnwrappedUnlocalizedName(String unlocalizedName) + private String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventure.java b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventure.java new file mode 100644 index 00000000..3fcfd28e --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventure.java @@ -0,0 +1,52 @@ +package com.darkona.adventurebackpack.item; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; + +import com.darkona.adventurebackpack.inventory.ContainerAdventure; +import com.darkona.adventurebackpack.util.EnchUtils; + +/** + * Created on 01.03.2018 + * + * @author Ugachaga + */ +@SuppressWarnings("WeakerAccess") +public abstract class ItemAdventure extends ItemAB implements IBackWearableItem +{ + public ItemAdventure() + { + super(); + setFull3D(); + setMaxStackSize(1); + } + + @Override + public boolean isDamageable() + { + return false; + } + + @Override + public int getItemEnchantability() + { + return 0; + } + + @Override + public boolean onDroppedByPlayer(ItemStack stack, EntityPlayer player) + { + if (stack != null && player instanceof EntityPlayerMP && player.openContainer instanceof ContainerAdventure) + player.closeScreen(); + + return super.onDroppedByPlayer(stack, player); + } + + @Override + public boolean isBookEnchantable(ItemStack stack, ItemStack book) + { + return EnchUtils.isSoulBook(book); + } + +} diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureBackpack.java b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureBackpack.java index f9e0f9cb..06475cca 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureBackpack.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureBackpack.java @@ -1,134 +1,204 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.AdventureBackpack; +import java.util.List; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.model.ModelBiped; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.Constants.NBT; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.FluidTank; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + import com.darkona.adventurebackpack.block.BlockAdventureBackpack; import com.darkona.adventurebackpack.block.TileAdventureBackpack; -import com.darkona.adventurebackpack.client.models.ModelBackpackArmor; import com.darkona.adventurebackpack.common.BackpackAbilities; +import com.darkona.adventurebackpack.common.Constants; import com.darkona.adventurebackpack.config.ConfigHandler; import com.darkona.adventurebackpack.events.WearableEvent; +import com.darkona.adventurebackpack.util.TipUtils; import com.darkona.adventurebackpack.init.ModBlocks; -import com.darkona.adventurebackpack.init.ModItems; import com.darkona.adventurebackpack.init.ModNetwork; import com.darkona.adventurebackpack.network.GUIPacket; import com.darkona.adventurebackpack.playerProperties.BackpackProperty; import com.darkona.adventurebackpack.proxy.ClientProxy; -import com.darkona.adventurebackpack.reference.BackpackNames; +import com.darkona.adventurebackpack.reference.BackpackTypes; import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.CoordsUtils; +import com.darkona.adventurebackpack.util.EnchUtils; import com.darkona.adventurebackpack.util.Resources; import com.darkona.adventurebackpack.util.Utils; -import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.block.Block; -import net.minecraft.client.model.ModelBiped; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.World; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; +import static com.darkona.adventurebackpack.common.Constants.BASIC_TANK_CAPACITY; +import static com.darkona.adventurebackpack.common.Constants.TAG_DISABLE_CYCLING; +import static com.darkona.adventurebackpack.common.Constants.TAG_DISABLE_NVISION; +import static com.darkona.adventurebackpack.common.Constants.TAG_INVENTORY; +import static com.darkona.adventurebackpack.common.Constants.TAG_LEFT_TANK; +import static com.darkona.adventurebackpack.common.Constants.TAG_RIGHT_TANK; +import static com.darkona.adventurebackpack.common.Constants.TAG_TYPE; +import static com.darkona.adventurebackpack.util.TipUtils.l10n; /** * Created on 12/10/2014 * * @author Darkona */ -public class ItemAdventureBackpack extends ItemAB implements IBackWearableItem +public class ItemAdventureBackpack extends ItemAdventure { - - public ItemAdventureBackpack() { super(); setUnlocalizedName("adventureBackpack"); - setFull3D(); - setMaxStackSize(1); } - - public static Item getItemFromBlock(Block block) + @Override + @SuppressWarnings({"unchecked"}) + @SideOnly(Side.CLIENT) + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List subItems) { - return block instanceof BlockAdventureBackpack ? ModItems.adventureBackpack : null; + for (BackpackTypes type : BackpackTypes.values()) + { + if (type == BackpackTypes.UNKNOWN) + continue; + + subItems.add(BackpackUtils.createBackpackStack(type)); + } } - /** - * Return the enchantability factor of the item, most of the timeInSeconds is based on material. - */ @Override - public int getItemEnchantability() + @SuppressWarnings({"unchecked"}) + @SideOnly(Side.CLIENT) + public void addInformation(ItemStack stack, EntityPlayer player, List tooltips, boolean advanced) { - return 0; + NBTTagCompound backpackTag = BackpackUtils.getWearableCompound(stack); + + BackpackTypes type = BackpackTypes.getType(backpackTag.getByte(TAG_TYPE)); + tooltips.add(Utils.getColoredSkinName(type)); + + FluidTank tank = new FluidTank(BASIC_TANK_CAPACITY); + + if (GuiScreen.isShiftKeyDown()) + { + NBTTagList itemList = backpackTag.getTagList(TAG_INVENTORY, NBT.TAG_COMPOUND); + tooltips.add(l10n("backpack.slots.used") + ": " + TipUtils.inventoryTooltip(itemList)); + + tank.readFromNBT(backpackTag.getCompoundTag(TAG_LEFT_TANK)); + tooltips.add(l10n("backpack.tank.left") + ": " + TipUtils.tankTooltip(tank)); + + tank.readFromNBT(backpackTag.getCompoundTag(TAG_RIGHT_TANK)); + tooltips.add(l10n("backpack.tank.right") + ": " + TipUtils.tankTooltip(tank)); + + TipUtils.shiftFooter(tooltips); + } + else if (!GuiScreen.isCtrlKeyDown()) + { + tooltips.add(TipUtils.holdShift()); + } + + if (GuiScreen.isCtrlKeyDown()) + { + boolean cycling = !backpackTag.getBoolean(TAG_DISABLE_CYCLING); + tooltips.add(l10n("backpack.cycling") + ": " + TipUtils.switchTooltip(cycling, true)); + tooltips.add(TipUtils.pressKeyFormat(TipUtils.actionKeyFormat()) + l10n("backpack.cycling.key1")); + tooltips.add(l10n("backpack.cycling.key2") + " " + TipUtils.switchTooltip(!cycling, false)); + + if (BackpackTypes.isNightVision(type)) + { + boolean vision = !backpackTag.getBoolean(TAG_DISABLE_NVISION); + tooltips.add(l10n("backpack.vision") + ": " + TipUtils.switchTooltip(vision, true)); + tooltips.add(TipUtils.pressShiftKeyFormat(TipUtils.actionKeyFormat()) + l10n("backpack.vision.key1")); + tooltips.add(l10n("backpack.vision.key2") + " " + TipUtils.switchTooltip(!vision, false)); + } + } } - /** - * Return whether this item is repairable in an anvil. - * - * @param p_82789_1_ - * @param p_82789_2_ - */ @Override - public boolean getIsRepairable(ItemStack p_82789_1_, ItemStack p_82789_2_) + public void onCreated(ItemStack stack, World world, EntityPlayer player) { - return false; + super.onCreated(stack, world, player); + BackpackUtils.setBackpackType(stack, BackpackTypes.getType(stack.getItemDamage())); } - /** - * Determines if the durability bar should be rendered for this item. - * Defaults to vanilla stack.isDamaged behavior. - * But modders can use this for any data they wish. - * - * @param stack The current Item Stack - * @return True if it should render the 'durability' bar. - */ @Override - public boolean showDurabilityBar(ItemStack stack) + public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { - return false; + return player.canPlayerEdit(x, y, z, side, stack) && placeBackpack(stack, player, world, x, y, z, side, true); } - /** - * Queries the percentage of the 'Durability' bar that should be drawn. - * - * @param stack The current ItemStack - * @return 1.0 for 100% 0 for 0% - */ @Override - public double getDurabilityForDisplay(ItemStack stack) + public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { - return 1; + MovingObjectPosition mop = getMovingObjectPositionFromPlayer(world, player, true); + if (mop == null || mop.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) + { + if (world.isRemote) + { + ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.BACKPACK_GUI, GUIPacket.FROM_HOLDING)); + } + } + return stack; } @Override - public String getItemStackDisplayName(ItemStack stack) + public void onPlayerDeath(World world, EntityPlayer player, ItemStack stack) { - return "Adventure Backpack";// + stack.getTagCompound().getString("colorName"); + if (world.isRemote || !ConfigHandler.backpackDeathPlace || EnchUtils.isSoulBounded(stack) + || player.getEntityWorld().getGameRules().getGameRuleBooleanValue("keepInventory")) + { + return; + } + + if (!tryPlace(world, player, stack)) + { + player.dropPlayerItemWithRandomChoice(stack, false); + } + + BackpackProperty.get(player).setWearable(null); } - @Override - public void onCreated(ItemStack stack, World par2World, EntityPlayer par3EntityPlayer) + private boolean tryPlace(World world, EntityPlayer player, ItemStack backpack) //TODO extract behavior to CoordsUtils { + int X = (int) player.posX; + if (player.posX < 0) X--; + int Z = (int) player.posZ; + if (player.posZ < 0) Z--; + int Y = (int) player.posY; + if (Y < 1) Y = 1; + + int positions[] = {0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6}; - super.onCreated(stack, par2World, par3EntityPlayer); - BackpackNames.setBackpackColorNameFromDamage(stack, stack.getItemDamage()); + for (int shiftY : positions) + { + if (Y + shiftY >= 1) + { + ChunkCoordinates spawn = CoordsUtils.getNearestEmptyChunkCoordinatesSpiral(world, X, Z, X, Y + shiftY, Z, 6, true, 1, (byte) 0, false); + if (spawn != null) + { + return placeBackpack(backpack, player, world, spawn.posX, spawn.posY, spawn.posZ, ForgeDirection.UP.ordinal(), false); + } + } + } + return false; } - public boolean placeBackpack(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, boolean from) + private boolean placeBackpack(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, boolean from) { + if (stack.stackSize == 0 || !player.canPlayerEdit(x, y, z, side, stack)) return false; if (!stack.hasTagCompound()) stack.setTagCompound(new NBTTagCompound()); - if (!player.canPlayerEdit(x, y, z, side, stack)) return false; - if (!stack.stackTagCompound.hasKey("colorName") || stack.stackTagCompound.getString("colorName").isEmpty()) + if (!stack.stackTagCompound.hasKey(TAG_TYPE)) { - stack.stackTagCompound.setString("colorName", "Standard"); + stack.stackTagCompound.setByte(TAG_TYPE, BackpackTypes.getMeta(BackpackTypes.STANDARD)); } // world.spawnEntityInWorld(new EntityLightningBolt(world, x, y, z)); @@ -177,8 +247,9 @@ public boolean placeBackpack(ItemStack stack, EntityPlayer player, World world, ((TileAdventureBackpack) world.getTileEntity(x, y, z)).loadFromNBT(stack.stackTagCompound); if (from) { - player.inventory.decrStackSize(player.inventory.currentItem, 1); - } else + stack.stackSize--; + } + else { BackpackProperty.get(player).setWearable(null); } @@ -192,159 +263,56 @@ public boolean placeBackpack(ItemStack stack, EntityPlayer player, World world, } @Override - public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) - { - return player.canPlayerEdit(x, y, z, side, stack) && placeBackpack(stack, player, world, x, y, z, side, true); - } - - @Override - public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) - { - MovingObjectPosition mop = getMovingObjectPositionFromPlayer(world, player, true); - if (mop == null || mop.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) - { - if (world.isRemote) - { - ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.BACKPACK_GUI, GUIPacket.FROM_HOLDING)); - } - } - return stack; - } - - - @Override - public boolean isDamageable() - { - return false; - } - - @Override - public boolean onDroppedByPlayer(ItemStack stack, EntityPlayer player) + public void onEquipped(World world, EntityPlayer player, ItemStack stack) { - return true; - } - @SideOnly(Side.CLIENT) - @Override - public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack stack, int armorSlot) - { - return new ModelBackpackArmor(); } - @SideOnly(Side.CLIENT) @Override - public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) - { - String modelTexture; - if (BackpackNames.getBackpackColorName(stack).equals("Standard")) - { - modelTexture = Resources.backpackTextureFromString(AdventureBackpack.instance.Holiday).toString(); - } else - { - modelTexture = Resources.backpackTexturesStringFromColor(stack); - } - return modelTexture; - } - - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - @SideOnly(Side.CLIENT) - public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean par4) + public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) { - NBTTagCompound backpackData = BackpackUtils.getBackpackData(stack); - if (backpackData != null) - { - if (backpackData.hasKey("colorName")) - { - list.add(backpackData.getString("colorName")); - } - } - } - + if (!ConfigHandler.backpackAbilities || world == null || player == null || stack == null) + return; - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - @SideOnly(Side.CLIENT) - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List subItems) - { - for (int i = 0; i < BackpackNames.backpackNames.length; i++) + if (BackpackTypes.isSpecial(BackpackTypes.getType(stack))) { - ItemStack bp = new ItemStack(this, 1, 0); - bp.setItemDamage(i); - NBTTagCompound c = new NBTTagCompound(); - c.setString("colorName", BackpackNames.backpackNames[i]); - BackpackUtils.setBackpackData(bp, c); - subItems.add(bp); + BackpackAbilities.backpackAbilities.executeAbility(player, world, stack); } } @Override - public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) + public void onUnequipped(World world, EntityPlayer player, ItemStack stack) { - - if (!ConfigHandler.BACKPACK_ABILITIES) return; - if (world == null || player == null || stack == null) return; - - if (BackpackAbilities.hasAbility(BackpackNames.getBackpackColorName(stack))) + if (BackpackTypes.hasProperty(BackpackTypes.getType(stack), BackpackTypes.Props.REMOVAL)) { - BackpackAbilities.backpackAbilities.executeAbility(player, world, stack); + BackpackAbilities.backpackAbilities.executeRemoval(player, world, stack); } } @Override - public void onPlayerDeath(World world, EntityPlayer player, ItemStack stack) + public double getDurabilityForDisplay(ItemStack stack) { - if(world.isRemote)return; - - if (Wearing.isWearingTheRightBackpack(player, "Creeper")) - { - player.worldObj.createExplosion(player, player.posX, player.posY, player.posZ, 4.0F, false); - } - - if(ConfigHandler.BACKPACK_DEATH_PLACE) - { - if (!tryPlace(world, player, stack)) - { - player.dropPlayerItemWithRandomChoice(stack, false); - BackpackProperty.get(player).setWearable(null); - } - }else{ - player.dropPlayerItemWithRandomChoice(stack, false); - BackpackProperty.get(player).setWearable(null); - } + return (double) getItemCount(stack) / Constants.INVENTORY_MAIN_SIZE; } - private boolean tryPlace(World world, EntityPlayer player, ItemStack backpack) + private int getItemCount(ItemStack backpack) { - int X = (int) player.posX; - int Z = (int) player.posZ; - int positions[] = {0,-1,1,-2,2,-3,3,-4,4,-5,5,-6,6}; - - for (int Y: positions) + NBTTagList itemList = BackpackUtils.getWearableInventory(backpack); + int itemCount = itemList.tagCount(); + for (int i = itemCount - 1; i >= 0; i--) { - ChunkCoordinates spawn = - Utils.getNearestEmptyChunkCoordinatesSpiral(world, X, Z, X, (int)player.posY + Y, Z, 12, true, 1, (byte) 0, false); - if (spawn != null) - { - return placeBackpack(backpack, player, world, spawn.posX, spawn.posY, spawn.posZ, ForgeDirection.UP.ordinal(), false); - } + int slotAtI = itemList.getCompoundTagAt(i).getInteger(Constants.TAG_SLOT); + if (slotAtI < Constants.INVENTORY_MAIN_SIZE) + break; + itemCount--; } - return false; + return itemCount; } @Override - public void onEquipped(World world, EntityPlayer player, ItemStack stack) + public boolean showDurabilityBar(ItemStack stack) { - - } - - @Override - public void onUnequipped(World world, EntityPlayer player, ItemStack stack) - { - if(BackpackAbilities.hasRemoval(BackpackNames.getBackpackColorName(stack))) - { - BackpackAbilities.backpackAbilities.executeRemoval(player, world, stack); - } + return ConfigHandler.enableFullnessBar && getItemCount(stack) > 0; } @Override @@ -356,19 +324,8 @@ public ModelBiped getWearableModel(ItemStack wearable) @Override @SideOnly(Side.CLIENT) - public ResourceLocation getWearableTexture(ItemStack wearable){ - - ResourceLocation modelTexture; - - if (BackpackNames.getBackpackColorName(wearable).equals("Standard")) - { - modelTexture = Resources.backpackTextureFromString(AdventureBackpack.instance.Holiday); - } else - { - modelTexture = Resources.backpackTextureFromString(BackpackNames.getBackpackColorName(wearable)); - } - return modelTexture; + public ResourceLocation getWearableTexture(ItemStack wearable) + { + return Resources.getBackpackTexture(BackpackTypes.getType(wearable)); } - - } diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureHat.java b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureHat.java index 9e89dbe9..d3652d28 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureHat.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureHat.java @@ -1,23 +1,23 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.client.models.ModelAdventureHat; -import com.darkona.adventurebackpack.util.Resources; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.model.ModelBiped; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import com.darkona.adventurebackpack.client.models.ModelAdventureHat; /** * Created by Darkona on 11/10/2014. */ public class ItemAdventureHat extends ArmorAB { - public ItemAdventureHat() { super(2, 0); + setMaxDamage(Items.leather_helmet.getMaxDamage() + 45); setUnlocalizedName("adventureHat"); } @@ -28,15 +28,9 @@ public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemSta return new ModelAdventureHat(); } - - @SideOnly(Side.CLIENT) @Override - public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) + public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) { - String modelTexture; - modelTexture = Resources.modelTextures("adventureHat").toString(); - - return modelTexture; + return repair.isItemEqual(new ItemStack(Items.leather)); } } - diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureJacket.java b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureJacket.java deleted file mode 100644 index eaeddc93..00000000 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureJacket.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.darkona.adventurebackpack.item; - -import com.darkona.adventurebackpack.client.models.ModelFullArmor; -import com.darkona.adventurebackpack.util.Resources; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.client.model.ModelBiped; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -/** - * Created on 11/10/2014 - * - * @author Darkona - */ -public class ItemAdventureJacket extends ArmorAB -{ - - public ItemAdventureJacket() - { - super(2, 2); - setUnlocalizedName("adventureSuit"); - } - - @Override - public boolean isValidArmor(ItemStack stack, int armorType, Entity entity) - { - return armorType == 1; - } - - @Override - public IIcon getIcon(ItemStack stack, int pass) - { - return itemIcon; - } - - @Override - @SideOnly(Side.CLIENT) - public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) - { - return Resources.modelTextureResourceString("adventureSuit_texture.png"); - } - - @Override - @SideOnly(Side.CLIENT) - public ModelBiped getArmorModel(EntityLivingBase entity, ItemStack itemStack, int armorSlot) - { - return new ModelFullArmor(); - } - -} diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventurePantaloon.java b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventurePantaloon.java deleted file mode 100644 index aa84754a..00000000 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventurePantaloon.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.darkona.adventurebackpack.item; - -import com.darkona.adventurebackpack.client.models.ModelFullArmor; -import com.darkona.adventurebackpack.util.Resources; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.client.model.ModelBiped; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -/** - * Created on 11/10/2014 - * - * @author Darkona - */ -public class ItemAdventurePantaloon extends ArmorAB -{ - - public ItemAdventurePantaloon() - { - super(2, 2); - setUnlocalizedName("adventureSuit"); - } - - @Override - public boolean isValidArmor(ItemStack stack, int armorType, Entity entity) - { - return armorType == 2; - } - - @Override - public IIcon getIcon(ItemStack stack, int pass) - { - return itemIcon; - } - - @Override - @SideOnly(Side.CLIENT) - public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) - { - return Resources.modelTextureResourceString("adventureSuit_texture.png"); - } - - @Override - @SideOnly(Side.CLIENT) - public ModelBiped getArmorModel(EntityLivingBase entity, ItemStack itemStack, int armorSlot) - { - return new ModelFullArmor(); - } - -} diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventurePants.java b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventurePants.java new file mode 100644 index 00000000..63c066d4 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventurePants.java @@ -0,0 +1,25 @@ +package com.darkona.adventurebackpack.item; + +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; + +/** + * Created on 11/10/2014 + * + * @author Darkona + */ +public class ItemAdventurePants extends ArmorAB +{ + public ItemAdventurePants() + { + super(2, 2); + setMaxDamage(Items.leather_leggings.getMaxDamage() + 75); + setUnlocalizedName("adventurePants"); + } + + @Override + public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) + { + return repair.isItemEqual(new ItemStack(Items.leather)); + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureSuit.java b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureSuit.java new file mode 100644 index 00000000..9aaca149 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemAdventureSuit.java @@ -0,0 +1,25 @@ +package com.darkona.adventurebackpack.item; + +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; + +/** + * Created on 11/10/2014 + * + * @author Darkona + */ +public class ItemAdventureSuit extends ArmorAB +{ + public ItemAdventureSuit() + { + super(1, 1); + setMaxDamage(Items.leather_chestplate.getMaxDamage() + 70); + setUnlocalizedName("adventureSuit"); + } + + @Override + public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) + { + return repair.isItemEqual(new ItemStack(Items.leather)); + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemSteamJetpack.java b/src/main/java/com/darkona/adventurebackpack/item/ItemCoalJetpack.java similarity index 57% rename from src/main/java/com/darkona/adventurebackpack/item/ItemSteamJetpack.java rename to src/main/java/com/darkona/adventurebackpack/item/ItemCoalJetpack.java index 350665b1..7597cddb 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemSteamJetpack.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemCoalJetpack.java @@ -1,125 +1,125 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.init.ModNetwork; -import com.darkona.adventurebackpack.inventory.InventorySteamJetpack; -import com.darkona.adventurebackpack.network.GUIPacket; -import com.darkona.adventurebackpack.network.PlayerActionPacket; -import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; -import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; -import com.darkona.adventurebackpack.playerProperties.BackpackProperty; -import com.darkona.adventurebackpack.proxy.ClientProxy; -import com.darkona.adventurebackpack.util.Resources; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; + import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.model.ModelBiped; +import net.minecraft.creativetab.CreativeTabs; 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.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.BiomeDictionary; +import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; +import com.darkona.adventurebackpack.network.GUIPacket; +import com.darkona.adventurebackpack.network.PlayerActionPacket; +import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; +import com.darkona.adventurebackpack.network.messages.EntitySoundPacket; +import com.darkona.adventurebackpack.proxy.ClientProxy; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.Resources; +import com.darkona.adventurebackpack.util.TipUtils; + +import static com.darkona.adventurebackpack.util.TipUtils.l10n; /** * Created on 15/01/2015 * * @author Darkona */ -public class ItemSteamJetpack extends ItemAB implements IBackWearableItem +public class ItemCoalJetpack extends ItemAdventure { - - public static byte OFF_MODE = 0; - public static byte NORMAL_MODE = 1; - - public ItemSteamJetpack() + public ItemCoalJetpack() { super(); - setUnlocalizedName("steamJetpack"); - setFull3D(); - setMaxStackSize(1); + setUnlocalizedName("coalJetpack"); } @Override - public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) + @SuppressWarnings("unchecked") + public void getSubItems(Item item, CreativeTabs tab, List list) { - if (world.isRemote) - { - ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.JETPACK_GUI, GUIPacket.FROM_HOLDING)); - } - return stack; + list.add(BackpackUtils.createJetpackStack()); } - private void runFirebox(InventorySteamJetpack inv) + @Override + @SuppressWarnings({"unchecked"}) + @SideOnly(Side.CLIENT) + public void addInformation(ItemStack stack, EntityPlayer player, List tooltips, boolean advanced) { - if (inv.getBurnTicks() <= 0) + FluidTank waterTank = new FluidTank(Constants.Jetpack.WATER_CAPACITY); + FluidTank steamTank = new FluidTank(Constants.Jetpack.STEAM_CAPACITY); + NBTTagCompound jetpackTag = BackpackUtils.getWearableCompound(stack); + + if (GuiScreen.isShiftKeyDown()) { - inv.setBurnTicks(inv.consumeFuel()); - inv.currentItemBurnTime = inv.getBurnTicks(); - } - inv.dirtyInventory(); - } + NBTTagList itemList = jetpackTag.getTagList(Constants.TAG_INVENTORY, NBT.TAG_COMPOUND); + tooltips.add(l10n("jetpack.fuel") + ": " + TipUtils.slotStackTooltip(itemList, Constants.Jetpack.FUEL_SLOT)); - private void runHeater(InventorySteamJetpack inv, World world, EntityPlayer player) - { - int temperature = inv.getTemperature(); - int burnTicks = inv.getBurnTicks() - 1; - int coolTicks = inv.getCoolTicks() - 1; - //Run the boiler: increase/maintain heat if there's burn ticks, or decrease temperature if there aren't + waterTank.readFromNBT(jetpackTag.getCompoundTag(Constants.Jetpack.TAG_WATER_TANK)); + tooltips.add(l10n("jetpack.tank.water") + ": " + TipUtils.tankTooltip(waterTank)); - if (burnTicks > 0) + steamTank.readFromNBT(jetpackTag.getCompoundTag(Constants.Jetpack.TAG_STEAM_TANK)); + // special case for steam, have to set displayed fluid name manually, cuz technically it's water + String theSteam = steamTank.getFluidAmount() > 0 ? EnumChatFormatting.AQUA + l10n("steam") : ""; + tooltips.add(l10n("jetpack.tank.steam") + ": " + TipUtils.tankTooltip(steamTank, false) + theSteam); + + TipUtils.shiftFooter(tooltips); + } + else if (!GuiScreen.isCtrlKeyDown()) { - if (temperature < InventorySteamJetpack.MAX_TEMPERATURE) - { - if (burnTicks % inv.getIncreasingFactor() == 0) - { - ++temperature; - coolTicks = coolTicks < 5000 ? coolTicks + 100 : coolTicks; - } - } - } else if (burnTicks <= 0) + tooltips.add(TipUtils.holdShift()); + } + + if (GuiScreen.isCtrlKeyDown()) { - inv.currentItemBurnTime = 0; - if (coolTicks % inv.getDecreasingFactor() == 0) - { - temperature = (temperature - 1 >= getBiomeMinTemp(player, world)) ? temperature - 1 : 0; - } + tooltips.add(l10n("max.altitude") + ": " + TipUtils.whiteFormat("185 ") + l10n("meters")); + tooltips.add(TipUtils.pressShiftKeyFormat(TipUtils.actionKeyFormat()) + l10n("jetpack.key.onoff1")); + tooltips.add(l10n("jetpack.key.onoff2") + " " + l10n("on")); } - inv.setTemperature(temperature); - inv.setCoolTicks(coolTicks); - inv.setBurnTicks(burnTicks <= 0 ? 0 : burnTicks); } - private int getBiomeMinTemp(EntityPlayer player, World world) + @Override + public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { - BiomeDictionary.Type[] thisBiomeTypes = BiomeDictionary.getTypesForBiome(world.getBiomeGenForCoords((int) player.posX, (int) player.posZ)); - for (BiomeDictionary.Type type : thisBiomeTypes) + if (world.isRemote) { - if (type == BiomeDictionary.Type.COLD || type == BiomeDictionary.Type.SNOWY) - { - return 0; - } - if (type == BiomeDictionary.Type.HOT || type == BiomeDictionary.Type.BEACH) - { - return 30; - } - if (type == BiomeDictionary.Type.NETHER) - { - return 40; - } + ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.JETPACK_GUI, GUIPacket.FROM_HOLDING)); } - return 25; + return stack; + } + + @Override + public void onEquipped(World world, EntityPlayer player, ItemStack stack) + { + InventoryCoalJetpack inv = new InventoryCoalJetpack(stack); + if (inv.getTemperature() == 0) inv.setTemperature(getBiomeMinTemp(player, world)); } @Override - public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) + public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) //TODO extract behavior to separate class { - InventorySteamJetpack inv = new InventorySteamJetpack(stack); + InventoryCoalJetpack inv = new InventoryCoalJetpack(stack); inv.openInventory(); boolean mustFizzz = !inv.isInUse(); - int steamConsumed = 13; - boolean canUse = inv.getSteamTank().drain(steamConsumed,false) != null; + int CoalConsumed = 13; + boolean canUse = inv.getSteamTank().drain(CoalConsumed, false) != null; if (inv.getStatus()) { @@ -130,9 +130,9 @@ public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) inv.dirtyBoiler(); //Suction - if(player.isInWater()) + if (player.isInWater()) { - inv.getWaterTank().fill(new FluidStack(FluidRegistry.WATER,2),true); + inv.getWaterTank().fill(new FluidStack(FluidRegistry.WATER, 2), true); } //Elevation @@ -146,7 +146,8 @@ public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) { ModNetwork.net.sendToServer(new EntitySoundPacket.Message(EntitySoundPacket.JETPACK_FIZZ, player)); } - } else + } + else { inv.setInUse(false); ModNetwork.net.sendToServer(new PlayerActionPacket.ActionMessage(PlayerActionPacket.JETPACK_NOT_IN_USE)); @@ -155,30 +156,41 @@ public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) if (inv.isInUse() && canUse) { - elevate(player); - inv.getSteamTank().drain(steamConsumed, true); + inv.getSteamTank().drain(CoalConsumed, true); if (inv.getSteamTank().getFluidAmount() == 0) { inv.setInUse(false); } player.moveFlying(player.moveStrafing, player.moveForward, 0.02f); - if(player.fallDistance > 1) + if (player.fallDistance > 1) { player.fallDistance -= 1; } - if(player.motionY >= 0) + if (player.motionY >= 0) { player.fallDistance = 0; } - if(!world.isRemote) - ModNetwork.sendToNearby(new EntityParticlePacket.Message(EntityParticlePacket.JETPACK_PARTICLE, player), player); - + if (!world.isRemote) + ModNetwork.sendToNearby(new EntityParticlePacket.Message(EntityParticlePacket.JETPACK_PARTICLE, player), player); } inv.closeInventory(); } - private void runBoiler(InventorySteamJetpack inv, World world, EntityPlayer player) + private static void elevate(EntityPlayer player) + { + if (player.posY < 135) + if (player.motionY <= 0.32) + player.motionY += 0.1; + else + player.motionY = Math.max(player.motionY, 0.32); + else if (player.posY < 185) + player.motionY = 0.32 - (player.posY - 135) / 160; + else if (player.posY >= 185) + player.motionY += 0; + } + + private void runBoiler(InventoryCoalJetpack inv, World world, EntityPlayer player) { int temperature = inv.getTemperature(); boolean mustSSSSS = !inv.isLeaking(); @@ -188,13 +200,14 @@ private void runBoiler(InventorySteamJetpack inv, World world, EntityPlayer play if (temperature >= 100 && inv.getWaterTank().getFluidAmount() > 0) { - if(!boiling)boiling = true; + if (!boiling) boiling = true; if (!world.isRemote && mustBlublub) { ModNetwork.net.sendTo(new EntitySoundPacket.Message(EntitySoundPacket.BOILING_BUBBLES, player), (EntityPlayerMP) player); } - } else + } + else { if (boiling) { @@ -208,8 +221,8 @@ private void runBoiler(InventorySteamJetpack inv, World world, EntityPlayer play { if (inv.getWaterTank().getFluid() != null) { - int steam = inv.getWaterTank().drain((temperature / 100), true).amount; - inv.getSteamTank().fill(new FluidStack(FluidRegistry.getFluid("steam"), steam * 4), true); + int water = inv.getWaterTank().drain((temperature / 100), true).amount; + inv.getSteamTank().fill(new FluidStack(FluidRegistry.getFluid("water"), water * 4), true); inv.dirtyTanks(); } } @@ -221,7 +234,8 @@ private void runBoiler(InventorySteamJetpack inv, World world, EntityPlayer play { leaking = false; } - } else + } + else { if (!leaking) { @@ -237,57 +251,113 @@ private void runBoiler(InventorySteamJetpack inv, World world, EntityPlayer play inv.setTemperature(temperature); } - public static void elevate(EntityPlayer player) + private void runFirebox(InventoryCoalJetpack inv) { - if (player.motionY <= 0.32 && player.posY < 100) + if (inv.getBurnTicks() <= 0) { - player.motionY += 0.1; - } else + inv.setBurnTicks(inv.consumeFuel()); + inv.setCurrentItemBurnTime(inv.getBurnTicks()); + } + inv.dirtyInventory(); + } + + private void runHeater(InventoryCoalJetpack inv, World world, EntityPlayer player) + { + int temperature = inv.getTemperature(); + int burnTicks = inv.getBurnTicks() - 1; + int coolTicks = inv.getCoolTicks() - 1; + + if (burnTicks > 0) + { + if (temperature < Constants.Jetpack.MAX_TEMPERATURE) + { + if (burnTicks % inv.getIncreasingFactor() == 0) + { + ++temperature; + coolTicks = coolTicks < 5000 ? coolTicks + 100 : coolTicks; + } + } + } + else { - if (player.posY < 100) player.motionY = Math.max(player.motionY, 0.32); - if (player.posY > 100) player.motionY = 0.32 - ((player.posY % 100) / 100); + inv.setCurrentItemBurnTime(0); + if (coolTicks % inv.getDecreasingFactor() == 0) + { + temperature = (temperature - 1 >= getBiomeMinTemp(player, world)) ? temperature - 1 : 0; + } } + inv.setTemperature(temperature); + inv.setCoolTicks(coolTicks); + inv.setBurnTicks(burnTicks <= 0 ? 0 : burnTicks); + } + + @Override + public void onUnequipped(World world, EntityPlayer player, ItemStack stack) + { + InventoryCoalJetpack inv = new InventoryCoalJetpack(stack); + inv.setBoiling(false); + inv.setInUse(false); + inv.setLeaking(false); + inv.setStatus(false); + inv.markDirty(); } @Override public void onPlayerDeath(World world, EntityPlayer player, ItemStack stack) { onUnequipped(world, player, stack); - player.dropPlayerItemWithRandomChoice(stack.copy(), false); - BackpackProperty.get(player).setWearable(null); } @Override - public void onEquipped(World world, EntityPlayer player, ItemStack stack) + public double getDurabilityForDisplay(ItemStack stack) { - InventorySteamJetpack inv = new InventorySteamJetpack(stack); - inv.calculateLostTime(); - if(inv.getTemperature() == 0)inv.setTemperature(getBiomeMinTemp(player, world)); + return (float) getTemperature(stack) / Constants.Jetpack.MAX_TEMPERATURE + 50; + } + + private int getTemperature(ItemStack jetpack) + { + return BackpackUtils.getWearableCompound(jetpack).getInteger("temperature"); } @Override - public void onUnequipped(World world, EntityPlayer player, ItemStack stack) + public boolean showDurabilityBar(ItemStack stack) { - InventorySteamJetpack inv = new InventorySteamJetpack(stack); - inv.setBoiling(false); - inv.setInUse(false); - inv.setLeaking(false); - inv.setStatus(false); - inv.setSystemTime(System.currentTimeMillis()); - inv.markDirty(); + return ConfigHandler.enableTemperatureBar && getTemperature(stack) > 50; + } + + private int getBiomeMinTemp(EntityPlayer player, World world) + { + BiomeDictionary.Type[] thisBiomeTypes = BiomeDictionary.getTypesForBiome(world.getBiomeGenForCoords((int) player.posX, (int) player.posZ)); + for (BiomeDictionary.Type type : thisBiomeTypes) + { + if (type == BiomeDictionary.Type.COLD || type == BiomeDictionary.Type.SNOWY) + { + return 0; + } + if (type == BiomeDictionary.Type.HOT || type == BiomeDictionary.Type.BEACH) + { + return 30; + } + if (type == BiomeDictionary.Type.NETHER) + { + return 40; + } + } + return 25; } @Override @SideOnly(Side.CLIENT) public ModelBiped getWearableModel(ItemStack wearable) { - return ClientProxy.modelSteamJetpack.setWearable(wearable); + return ClientProxy.modelCoalJetpack.setWearable(wearable); } @Override @SideOnly(Side.CLIENT) public ResourceLocation getWearableTexture(ItemStack wearable) { - return Resources.modelTextures("steamJetpack"); + return Resources.modelTextures("coalJetpack"); } -} + +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemComponent.java b/src/main/java/com/darkona/adventurebackpack/item/ItemComponent.java index ae36b2b7..df8dc4c6 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemComponent.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemComponent.java @@ -1,9 +1,8 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.entity.EntityInflatableBoat; -import com.darkona.adventurebackpack.util.LogHelper; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.HashMap; +import java.util.List; + import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; @@ -11,20 +10,25 @@ import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.util.*; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.IIcon; +import net.minecraft.util.MathHelper; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; import net.minecraft.world.World; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; -import java.util.HashMap; -import java.util.List; +import com.darkona.adventurebackpack.entity.EntityInflatableBoat; /** * Created on 11/10/2014 - * @author Darkona * + * @author Darkona */ public class ItemComponent extends ItemAB { - private HashMap componentIcons = new HashMap(); + private HashMap componentIcons = new HashMap<>(); private String[] names = { "sleepingBag", "backpackTank", @@ -35,10 +39,8 @@ public class ItemComponent extends ItemAB "inflatableBoat", "inflatableBoatMotorized", "hydroBlades", - }; - public ItemComponent() { setNoRepair(); @@ -51,13 +53,11 @@ public ItemComponent() @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) { - - for(String name : names){ + for (String name : names) + { IIcon temporalIcon = iconRegister.registerIcon(super.getUnlocalizedName(name).substring(this.getUnlocalizedName().indexOf(".") + 1)); componentIcons.put(name, temporalIcon); } - - itemIcon = iconRegister.registerIcon(super.getUnlocalizedName("sleepingBag").substring(this.getUnlocalizedName().indexOf(".") + 1)); } @@ -67,25 +67,22 @@ public IIcon getIcon(ItemStack stack, int renderPass, EntityPlayer player, ItemS return super.getIcon(stack, renderPass, player, usingItem, useRemaining); } - @Override @SideOnly(Side.CLIENT) public IIcon getIconFromDamage(int damage) { - return componentIcons.get(names[damage-1]); - + return componentIcons.get(names[damage - 1]); } @Override public String getUnlocalizedName(ItemStack stack) { - return super.getUnlocalizedName(names[getDamage(stack)-1]); - + return super.getUnlocalizedName(names[getDamage(stack) - 1]); } @Override - @SideOnly(Side.CLIENT) @SuppressWarnings("unchecked") + @SideOnly(Side.CLIENT) public void getSubItems(Item item, CreativeTabs creativeTabs, List list) { for (int i = 1; i <= names.length; i++) @@ -95,69 +92,15 @@ public void getSubItems(Item item, CreativeTabs creativeTabs, List list) } @Override - public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int meta, float f1, float f2, float f3) + public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { - return false; - /*if (itemStack.getItemDamage() != 1) return true; - if (world.isRemote) - { - return true; - } else if (meta != 1) - { - return false; - } else - { - /* ++y; - BlockSleepingBag blockbed = ModBlocks.blockSleepingBag; - int i1 = MathHelper.floor_double((double) (player.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3; - byte b0 = 0; - byte b1 = 0; - - if (i1 == 0) - { - b1 = 1; - } - - if (i1 == 1) - { - b0 = -1; - } - - if (i1 == 2) - { - b1 = -1; - } - - if (i1 == 3) - { - b0 = 1; - } - - if (player.canPlayerEdit(x, y, z, meta, itemStack) && player.canPlayerEdit(x + b0, y, z + b1, meta, itemStack)) - { - if (world.isAirBlock(x, y, z) && world.isAirBlock(x + b0, y, z + b1) && World.doesBlockHaveSolidTopSurface(world, x, y - 1, z) && World.doesBlockHaveSolidTopSurface(world, x + b0, y - 1, z + b1)) - { - world.setBlock(x, y, z, blockbed, i1, 3); - - if (world.getBlock(x, y, z) == blockbed) - { - world.setBlock(x + b0, y, z + b1, blockbed, i1 + 8, 3); - } - - --itemStack.stackSize; - return true; - } else - { - return false; - } - } else - { - return false; - } - }*/ + if (stack.getItemDamage() == 7) + return placeBoat(stack, world, player, false); + if (stack.getItemDamage() == 8) + return placeBoat(stack, world, player, true); + return stack; } - private ItemStack placeBoat(ItemStack stack, World world, EntityPlayer player, boolean motorized) { float f = 1.0F; @@ -180,7 +123,8 @@ private ItemStack placeBoat(ItemStack stack, World world, EntityPlayer player, b if (movingobjectposition == null) { return stack; - } else + } + else { Vec3 vec32 = player.getLook(f); boolean flag = false; @@ -207,7 +151,8 @@ private ItemStack placeBoat(ItemStack stack, World world, EntityPlayer player, b if (flag) { return stack; - } else + } + else { if (movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { @@ -242,22 +187,4 @@ private ItemStack placeBoat(ItemStack stack, World world, EntityPlayer player, b } } } - - - - /** - * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer - * - * @param stack - * @param world - * @param player - */ - @Override - public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) - { - LogHelper.info("Damage: " + stack.getItemDamage()); - if(stack.getItemDamage() == 7)return placeBoat(stack,world,player,false); - if(stack.getItemDamage() == 8)return placeBoat(stack,world,player,true); - return stack; - } -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemCopterPack.java b/src/main/java/com/darkona/adventurebackpack/item/ItemCopterPack.java index a36ae594..7b227cd1 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemCopterPack.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemCopterPack.java @@ -1,152 +1,141 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.client.models.ModelCopterPack; -import com.darkona.adventurebackpack.init.ModNetwork; -import com.darkona.adventurebackpack.inventory.InventoryCopterPack; -import com.darkona.adventurebackpack.network.GUIPacket; -import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; -import com.darkona.adventurebackpack.playerProperties.BackpackProperty; -import com.darkona.adventurebackpack.proxy.ClientProxy; -import com.darkona.adventurebackpack.reference.GeneralReference; -import com.darkona.adventurebackpack.util.Resources; -import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; + import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.model.ModelBiped; +import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import net.minecraftforge.fluids.FluidTank; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; -import java.util.List; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.inventory.InventoryCopterPack; +import com.darkona.adventurebackpack.network.GUIPacket; +import com.darkona.adventurebackpack.network.messages.EntityParticlePacket; +import com.darkona.adventurebackpack.proxy.ClientProxy; +import com.darkona.adventurebackpack.reference.GeneralReference; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.Resources; +import com.darkona.adventurebackpack.util.TipUtils; +import com.darkona.adventurebackpack.util.Wearing; + +import static com.darkona.adventurebackpack.common.Constants.Copter.FUEL_CAPACITY; +import static com.darkona.adventurebackpack.common.Constants.Copter.TAG_FUEL_TANK; +import static com.darkona.adventurebackpack.common.Constants.Copter.TAG_STATUS; +import static com.darkona.adventurebackpack.util.TipUtils.l10n; /** * Created on 31/12/2014 * * @author Darkona */ -public class ItemCopterPack extends ItemAB implements IBackWearableItem +public class ItemCopterPack extends ItemAdventure { + public static byte OFF_MODE = 0; + public static byte NORMAL_MODE = 1; + public static byte HOVER_MODE = 2; + + private float fuelSpent; public ItemCopterPack() { super(); setUnlocalizedName("copterPack"); - setFull3D(); - setMaxStackSize(1); } - public static byte OFF_MODE = 0; - public static byte NORMAL_MODE = 1; - public static byte HOVER_MODE = 2; - @Override - public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) + @SuppressWarnings("unchecked") + public void getSubItems(Item item, CreativeTabs tab, List list) { - if (world.isRemote) - { - ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.COPTER_GUI, GUIPacket.FROM_HOLDING)); - } - return stack; + list.add(BackpackUtils.createCopterStack()); } @Override - public void onUpdate(ItemStack stack, World world, Entity entity, int slot, boolean isCurrent) + @SuppressWarnings({"unchecked"}) + @SideOnly(Side.CLIENT) + public void addInformation(ItemStack stack, EntityPlayer player, List tooltips, boolean advanced) { - } - + FluidTank fuelTank = new FluidTank(FUEL_CAPACITY); + NBTTagCompound copterTag = BackpackUtils.getWearableCompound(stack); - @SuppressWarnings(value = "unchecked") - public void pushEntities(World world, EntityPlayer player, float speed) - { - double posX = player.posX; - double posY = player.posY; - double posZ = player.posZ; - List groundItems = world.getEntitiesWithinAABB( - EntityItem.class, - AxisAlignedBB.getBoundingBox(posX, posY, posZ, - posX + 1.0D, posY + 1.0D, - posZ + 1.0D).expand(4.0D, 4.0D, 4.0D)); + if (GuiScreen.isShiftKeyDown()) + { + fuelTank.readFromNBT(copterTag.getCompoundTag(TAG_FUEL_TANK)); + tooltips.add(l10n("copter.tank.fuel") + ": " + TipUtils.tankTooltip(fuelTank)); + tooltips.add(l10n("copter.rate.fuel") + ": " + TipUtils.fuelConsumptionTooltip(fuelTank)); - for (EntityItem groundItem : groundItems) + TipUtils.shiftFooter(tooltips); + } + else if (!GuiScreen.isCtrlKeyDown()) { - if (!groundItem.isInWater()) - { - if (groundItem.posX > posX) - { - groundItem.motionX = speed; - } - if (groundItem.posX < posX) - { - groundItem.motionX = -speed; - } + tooltips.add(TipUtils.holdShift()); + } - if (groundItem.posZ > posZ) - { - groundItem.motionZ = speed; - } - if (groundItem.posZ < posZ) - { - groundItem.motionZ = -speed; - } + if (GuiScreen.isCtrlKeyDown()) + { + tooltips.add(l10n("max.altitude") + ": " + TipUtils.whiteFormat("250 ") + l10n("meters")); + tooltips.add(TipUtils.pressShiftKeyFormat(TipUtils.actionKeyFormat()) + l10n("copter.key.onoff1")); + tooltips.add(l10n("copter.key.onoff2") + " " + l10n("on")); - if (groundItem.posY < posY) - { - groundItem.motionY -= speed; - } - } + tooltips.add(TipUtils.pressKeyFormat(TipUtils.actionKeyFormat()) + l10n("copter.key.hover1")); + tooltips.add(l10n("copter.key.hover2")); } } - - @SideOnly(Side.CLIENT) - public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack stack, int armorSlot) + @Override + public void onUpdate(ItemStack stack, World world, Entity entity, int slot, boolean isCurrent) { - return ModelCopterPack.instance.setWearable(stack); - } + } - @SideOnly(Side.CLIENT) - public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) + @Override + public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { - String modelTexture; - modelTexture = Resources.modelTextures("copterPack").toString(); - - return modelTexture; + if (world.isRemote) + { + ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.COPTER_GUI, GUIPacket.FROM_HOLDING)); + } + return stack; } - public static void elevate(EntityPlayer player, ItemStack copter) + @Override + public void onEquipped(World world, EntityPlayer player, ItemStack stack) { - if (player.posY < 100) player.motionY = Math.max(player.motionY, 0.18); - if (player.posY > 100) player.motionY = 0.18 - ((player.posY % 100) / 100); + BackpackUtils.getWearableCompound(stack).setByte(TAG_STATUS, OFF_MODE); } @Override - public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) + public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) //TODO extract behavior to separate class { InventoryCopterPack inv = new InventoryCopterPack(Wearing.getWearingCopter(player)); inv.openInventory(); boolean canElevate = true; - int fuelConsumption = 0; + float fuelConsumption = 0.0f; if (inv.getStatus() != OFF_MODE) { if (player.isInWater()) { inv.setStatus(OFF_MODE); inv.dirtyStatus(); - if (!world.isRemote){ + if (!world.isRemote) + { player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.copterpack.cantwater")); } return; } - if (inv.fuelTank.getFluidAmount() == 0) + if (inv.getFuelTank().getFluidAmount() == 0) { canElevate = false; if (player.onGround) @@ -162,7 +151,6 @@ public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) } if (inv.getStatus() == HOVER_MODE) { - inv.setStatus(NORMAL_MODE); inv.dirtyStatus(); if (!world.isRemote) @@ -195,8 +183,10 @@ public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) if (player.isSneaking()) { player.motionY = -0.3; - }else{ - fuelConsumption+=2; + } + else + { + fuelConsumption *= 2; player.motionY = 0.0f; } } @@ -209,15 +199,15 @@ public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) } //Sound - float factor = 0.05f; if (!player.onGround) { //Airwave pushEntities(world, player, 0.2f); //movement boost - player.moveFlying(player.moveStrafing,player.moveForward,factor); - } else + player.moveFlying(player.moveStrafing, player.moveForward, factor); + } + else { pushEntities(world, player, factor + 0.4f); } @@ -227,7 +217,7 @@ public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) { if (Minecraft.getMinecraft().gameSettings.keyBindJump.getIsKeyPressed()) { - if (inv.canConsumeFuel(fuelConsumption + 2) && canElevate) + if (inv.canConsumeFuel((int) Math.ceil(fuelConsumption * 2)) && canElevate) { elevate(player, stack); } @@ -237,49 +227,95 @@ public void onEquippedUpdate(World world, EntityPlayer player, ItemStack stack) //Elevation serverside if (!player.onGround && player.motionY > 0) { - fuelConsumption += 2; + fuelConsumption *= 2; } - int ticks = inv.tickCounter - 1; - if (inv.fuelTank.getFluid() != null) + int ticks = inv.getTickCounter() - 1; + FluidTank tank = inv.getFuelTank(); + if (tank.getFluid() != null && GeneralReference.isValidFuel(tank.getFluid().getFluid().getName())) { - if(GeneralReference.isValidFuel(inv.getFuelTank().getFluid().getFluid())) - { - fuelConsumption = (int)Math.floor(fuelConsumption * GeneralReference.liquidFuels.get(inv.getFuelTank().getFluid().getFluid().getName())); - } + fuelConsumption = fuelConsumption * GeneralReference.getFuelRate(tank.getFluid().getFluid().getName()); } if (ticks <= 0) { - inv.tickCounter = 3; - inv.consumeFuel(fuelConsumption); + inv.setTickCounter(3); + inv.consumeFuel(getFuelSpent(fuelConsumption)); inv.dirtyTanks(); - } else + } + else { - inv.tickCounter = ticks; + inv.setTickCounter(ticks); } } - // if(!world.isRemote)inv.closeInventory(); inv.closeInventory(); } - @Override - public void onPlayerDeath(World world, EntityPlayer player, ItemStack stack) + private int getFuelSpent(float f) { - onUnequipped(world,player,stack); - player.dropPlayerItemWithRandomChoice(stack.copy(),false); - BackpackProperty.get(player).setWearable(null); + f += fuelSpent; + fuelSpent = f % 1; + return (int) (f - fuelSpent); } - @Override - public void onEquipped(World world, EntityPlayer player, ItemStack stack) + private static void elevate(EntityPlayer player, ItemStack copter) { - if(!stack.hasTagCompound())stack.setTagCompound(new NBTTagCompound()); - stack.stackTagCompound.setByte("status",OFF_MODE); + if (player.posY < 100) + player.motionY = Math.max(player.motionY, 0.18); + else if (player.posY < 250) + player.motionY = 0.18 - (player.posY - 100) / 1000; + else if (player.posY >= 250) + player.motionY += 0; + } + + @SuppressWarnings("unchecked") + private void pushEntities(World world, EntityPlayer player, float speed) + { + double posX = player.posX; + double posY = player.posY; + double posZ = player.posZ; + List groundItems = world.getEntitiesWithinAABB( + EntityItem.class, AxisAlignedBB.getBoundingBox( + posX, posY, posZ, posX + 1.0D, posY + 1.0D, posZ + 1.0D).expand(4.0D, 4.0D, 4.0D)); + + for (EntityItem groundItem : groundItems) + { + if (!groundItem.isInWater()) + { + if (groundItem.posX > posX) + { + groundItem.motionX = speed; + } + if (groundItem.posX < posX) + { + groundItem.motionX = -speed; + } + + if (groundItem.posZ > posZ) + { + groundItem.motionZ = speed; + } + if (groundItem.posZ < posZ) + { + groundItem.motionZ = -speed; + } + + if (groundItem.posY < posY) + { + groundItem.motionY -= speed; + } + } + } } @Override public void onUnequipped(World world, EntityPlayer player, ItemStack stack) { - stack.stackTagCompound.setByte("status",OFF_MODE); + BackpackUtils.getWearableCompound(stack).setByte(TAG_STATUS, OFF_MODE); + } + + @Override + public void onPlayerDeath(World world, EntityPlayer player, ItemStack stack) + { + onUnequipped(world, player, stack); } @Override @@ -296,5 +332,4 @@ public ResourceLocation getWearableTexture(ItemStack wearable) return Resources.modelTextures("copterPack"); } - -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemCrossbow.java b/src/main/java/com/darkona/adventurebackpack/item/ItemCrossbow.java index fcb50a10..6ab66d12 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemCrossbow.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemCrossbow.java @@ -18,7 +18,6 @@ */ public class ItemCrossbow extends ItemAB { - public ItemCrossbow() { super(); @@ -27,7 +26,6 @@ public ItemCrossbow() setMaxStackSize(1); } - /** * Returns true if players can use this item to affect the world (e.g. placing blocks, placing ender eyes in portal) * when not in creative @@ -44,18 +42,6 @@ public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, return false; } - @Override - public boolean isRepairable() - { - return super.isRepairable(); - } - - @Override - public String getItemStackDisplayName(ItemStack stack) - { - return super.getItemStackDisplayName(stack); - } - @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { @@ -70,10 +56,6 @@ public EnumAction getItemUseAction(ItemStack p_77661_1_) /** * Called when item is crafted/smelted. Used only by maps so far. - * - * @param stack - * @param world - * @param player */ @Override public void onCreated(ItemStack stack, World world, EntityPlayer player) @@ -96,42 +78,38 @@ public void onUsingTick(ItemStack stack, EntityPlayer player, int count) @Override public void onUpdate(ItemStack stack, World world, Entity entity, int slot, boolean current) { - if(!stack.hasTagCompound()){ + if (!stack.hasTagCompound()) + { stack.stackTagCompound = new NBTTagCompound(); - stack.stackTagCompound.setByte("Shot",(byte)0); - stack.stackTagCompound.setInteger("Reloading",0); + stack.stackTagCompound.setByte("Shot", (byte) 0); + stack.stackTagCompound.setInteger("Reloading", 0); } - if(current) + if (current) { byte shot = stack.stackTagCompound.getByte("Shot"); int reloading = stack.stackTagCompound.getInteger("Reloading"); - if(shot > 0)stack.stackTagCompound.setByte("Shot", (byte)(shot-1)); - if(reloading > 0)stack.stackTagCompound.setInteger("Reloading",reloading-1); - if(entity instanceof EntityPlayer) - { - //((EntityPlayer)entity).setItemInUse(stack,2); - } + if (shot > 0) stack.stackTagCompound.setByte("Shot", (byte) (shot - 1)); + if (reloading > 0) stack.stackTagCompound.setInteger("Reloading", reloading - 1); } } @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { - if(!stack.hasTagCompound())stack.setTagCompound(new NBTTagCompound()); - if(!stack.stackTagCompound.hasKey("Reloading"))stack.stackTagCompound.setInteger("Reloading",0); + if (!stack.hasTagCompound()) stack.setTagCompound(new NBTTagCompound()); + if (!stack.stackTagCompound.hasKey("Reloading")) stack.stackTagCompound.setInteger("Reloading", 0); int reloading = stack.stackTagCompound.getInteger("Reloading"); - if(reloading <= 0){ - shootArrow(stack,player.worldObj,player, 1000); - stack.stackTagCompound.setByte("Shot",(byte)4); + if (reloading <= 0) + { + shootArrow(stack, player.worldObj, player, 1000); + stack.stackTagCompound.setByte("Shot", (byte) 4); int reloadTime = 20; stack.stackTagCompound.setInteger("Reloading", reloadTime); - } return stack; } - @Override public int getMaxItemUseDuration(ItemStack stack) { @@ -141,17 +119,17 @@ public int getMaxItemUseDuration(ItemStack stack) @Override public void onPlayerStoppedUsing(ItemStack stack, World world, EntityPlayer player, int counter) { + } - public void shootArrow(ItemStack stack, World world, EntityPlayer player, int count) + private void shootArrow(ItemStack stack, World world, EntityPlayer player, int count) { - int j = count; - - boolean flag = player.capabilities.isCreativeMode || EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0; + boolean flag = EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0 + || player.capabilities.isCreativeMode; if (flag || player.inventory.hasItem(Items.arrow)) { - float f = j / 20.0F; + float f = count / 20.0F; f = (f * f + f * 2.0F) / 3.0F; if (f < 0.1D) @@ -191,7 +169,8 @@ public void shootArrow(ItemStack stack, World world, EntityPlayer player, int co if (flag) { entityarrow.canBePickedUp = 2; - } else + } + else { player.inventory.consumeInventoryItem(Items.arrow); } diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemCrossbowMagazine.java b/src/main/java/com/darkona/adventurebackpack/item/ItemCrossbowMagazine.java index d5e58560..dad675c2 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemCrossbowMagazine.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemCrossbowMagazine.java @@ -7,4 +7,5 @@ */ public class ItemCrossbowMagazine { + } diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemHose.java b/src/main/java/com/darkona/adventurebackpack/item/ItemHose.java index 1ea437d6..b3fffa29 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemHose.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemHose.java @@ -1,18 +1,12 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.CreativeTabAB; -import com.darkona.adventurebackpack.common.Constants; -import com.darkona.adventurebackpack.common.ServerActions; -import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; -import com.darkona.adventurebackpack.init.ModFluids; -import com.darkona.adventurebackpack.inventory.InventoryBackpack; -import com.darkona.adventurebackpack.util.Resources; -import com.darkona.adventurebackpack.util.Utils; -import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; + +import org.apache.commons.lang3.text.WordUtils; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; +import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -24,53 +18,89 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IIcon; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.*; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; +import net.minecraftforge.fluids.IFluidHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import com.darkona.adventurebackpack.CreativeTabAB; +import com.darkona.adventurebackpack.common.ServerActions; +import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; +import com.darkona.adventurebackpack.init.ModFluids; +import com.darkona.adventurebackpack.inventory.InventoryBackpack; +import com.darkona.adventurebackpack.util.Resources; +import com.darkona.adventurebackpack.util.TipUtils; +import com.darkona.adventurebackpack.util.Wearing; + +import static com.darkona.adventurebackpack.common.Constants.BUCKET; +import static com.darkona.adventurebackpack.util.TipUtils.l10n; /** * Created by Darkona on 12/10/2014. */ public class ItemHose extends ItemAB { - - IIcon drinkIcon; - IIcon spillIcon; - IIcon suckIcon; - final byte HOSE_SUCK_MODE = 0; - final byte HOSE_SPILL_MODE = 1; - final byte HOSE_DRINK_MODE = 2; + private IIcon drinkIcon; + private IIcon spillIcon; + private IIcon suckIcon; + private static final byte HOSE_SUCK_MODE = 0; + private static final byte HOSE_SPILL_MODE = 1; + private static final byte HOSE_DRINK_MODE = 2; public ItemHose() { super(); setMaxStackSize(1); setFull3D(); - //.setCreativeTab(CreativeTabs.tabTools) setNoRepair(); setUnlocalizedName("backpackHose"); - setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB); + setCreativeTab(CreativeTabAB.TAB_AB); } + @Override + @SuppressWarnings({"unchecked"}) + @SideOnly(Side.CLIENT) + public void addInformation(ItemStack stack, EntityPlayer player, List tooltips, boolean advanced) + { + if (GuiScreen.isCtrlKeyDown()) + { + tooltips.add(l10n("hose.key.header")); + tooltips.add("- " + TipUtils.pressKeyFormat(TipUtils.actionKeyFormat()) + l10n("hose.key.tank")); + tooltips.add("- " + TipUtils.pressShiftKeyFormat(TipUtils.whiteFormat(l10n("mouse.wheel"))) + l10n("hose.key.mode")); + tooltips.add(""); + tooltips.add(l10n("hose.dump1")); + tooltips.add(l10n("hose.dump2")); + tooltips.add(EnumChatFormatting.RED.toString() + l10n("hose.dump.warn")); + } + else + { + tooltips.add(TipUtils.holdCtrl()); + } + } - // ================================================ GETTERS =====================================================// @Override @SideOnly(Side.CLIENT) public IIcon getIcon(ItemStack stack, int pass) { - switch(getHoseMode(stack)) - { - case HOSE_SUCK_MODE: - return suckIcon; - case HOSE_SPILL_MODE: - return spillIcon; - case HOSE_DRINK_MODE: - return drinkIcon; - default: - return itemIcon; - } + switch (getHoseMode(stack)) + { + case HOSE_SUCK_MODE: + return suckIcon; + case HOSE_SPILL_MODE: + return spillIcon; + case HOSE_DRINK_MODE: + return drinkIcon; + default: + return itemIcon; + } } @Override @@ -135,8 +165,6 @@ public int getMaxDamage(ItemStack stack) return 0; } - // ================================================ SETTERS =====================================================// - // ================================================= ICONS ======================================================// @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) @@ -146,7 +174,6 @@ public void registerIcons(IIconRegister iconRegister) suckIcon = iconRegister.registerIcon(Resources.getIconString("hoseSuck")); itemIcon = iconRegister.registerIcon(Resources.getIconString("hoseLeft")); } - // ================================================ ACTIONS =====================================================// @Override public void onUpdate(ItemStack stack, World world, Entity entity, int inv_slot, boolean isCurrent) @@ -156,7 +183,6 @@ public void onUpdate(ItemStack stack, World world, Entity entity, int inv_slot, EntityPlayer player = (EntityPlayer) entity; if (world.isRemote && player.getItemInUse() != null && player.getItemInUse().getItem().equals(this)) return; - NBTTagCompound nbt = stack.hasTagCompound() ? stack.getTagCompound() : new NBTTagCompound(); ItemStack backpack = Wearing.getWearingBackpack(player); if (backpack != null) @@ -167,14 +193,16 @@ public void onUpdate(ItemStack stack, World world, Entity entity, int inv_slot, FluidTank tank = nbt.getInteger("tank") == 0 ? inv.getLeftTank() : inv.getRightTank(); if (tank != null && tank.getFluid() != null) { - nbt.setString("fluid", Utils.capitalize(tank.getFluid().getFluid().getName())); + nbt.setString("fluid", WordUtils.capitalize(tank.getFluid().getFluid().getName())); nbt.setInteger("amount", tank.getFluidAmount()); - } else + } + else { nbt.setInteger("amount", 0); nbt.setString("fluid", "Empty"); } - } else + } + else { nbt.setInteger("amount", 0); nbt.setString("fluid", "None"); @@ -187,7 +215,7 @@ public void onUpdate(ItemStack stack, World world, Entity entity, int inv_slot, @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { - if(!Wearing.isWearingBackpack(player))return true; + if (!Wearing.isWearingBackpack(player)) return true; InventoryBackpack inv = new InventoryBackpack(Wearing.getWearingBackpack(player)); inv.openInventory(); @@ -196,12 +224,12 @@ public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int if (te != null && te instanceof IFluidHandler) { IFluidHandler exTank = (IFluidHandler) te; - int accepted = 0; + int accepted; switch (getHoseMode(stack)) { case HOSE_SUCK_MODE: - accepted = tank.fill(exTank.drain(ForgeDirection.UNKNOWN, Constants.bucket, false), false); + accepted = tank.fill(exTank.drain(ForgeDirection.UNKNOWN, BUCKET, false), false); if (accepted > 0) { tank.fill(exTank.drain(ForgeDirection.UNKNOWN, accepted, true), true); @@ -213,7 +241,7 @@ public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int case HOSE_SPILL_MODE: - accepted = exTank.fill(ForgeDirection.UNKNOWN, tank.drain(Constants.bucket, false), false); + accepted = exTank.fill(ForgeDirection.UNKNOWN, tank.drain(BUCKET, false), false); if (accepted > 0) { exTank.fill(ForgeDirection.UNKNOWN, tank.drain(accepted, true), true); @@ -228,23 +256,10 @@ public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int } - @Override - public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity entity) - { - return false; - } - - /** - * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer - * - * @param stack - * @param world - * @param player - */ @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { - if(!Wearing.isWearingBackpack(player))return stack; + if (!Wearing.isWearingBackpack(player)) return stack; InventoryBackpack inv = new InventoryBackpack(Wearing.getWearingBackpack(player)); inv.openInventory(); MovingObjectPosition mop = getMovingObjectPositionFromPlayer(world, player, true); @@ -257,11 +272,6 @@ public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer pla if (mop != null && mop.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - /* if (!world.canMineBlock(player, mop.blockX, mop.blockY, mop.blockZ)) - { - return stack; - }*/ - if (!player.canPlayerEdit(mop.blockX, mop.blockY, mop.blockZ, mop.sideHit, null)) { return stack; @@ -270,7 +280,7 @@ public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer pla Fluid fluidBlock = FluidRegistry.lookupFluidForBlock(world.getBlock(mop.blockX, mop.blockY, mop.blockZ)); if (fluidBlock != null) { - FluidStack fluid = new FluidStack(fluidBlock, Constants.bucket); + FluidStack fluid = new FluidStack(fluidBlock, BUCKET); if (tank.getFluid() == null || tank.getFluid().containsFluid(fluid)) { int accepted = tank.fill(fluid, false); @@ -329,21 +339,21 @@ public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer pla { return stack; } - /* IN HELL DIMENSION No, I won't let you put water in the nether. You freak*/ + /* IN HELL DIMENSION No, I won't let you put water in the nether. You freak*/ if (world.provider.isHellWorld && fluid.getFluid() == FluidRegistry.WATER) { - tank.drain(Constants.bucket, true); - world.playSoundEffect(x + 0.5F, y + 0.5F, z + 0.5F, "random.fizz", 0.5F, - 2.6F + (world.rand.nextFloat() - world.rand.nextFloat()) * 0.8F); + tank.drain(BUCKET, true); + world.playSoundEffect(x + 0.5F, y + 0.5F, z + 0.5F, "random.fizz", 0.5F, 2.6F + (world.rand.nextFloat() - world.rand.nextFloat()) * 0.8F); for (int l = 0; l < 12; ++l) { world.spawnParticle("largesmoke", x + Math.random(), y + Math.random(), z + Math.random(), 0.0D, 0.0D, 0.0D); } - } else + } + else { - /* NOT IN HELL DIMENSION. */ - FluidStack drainedFluid = tank.drain(Constants.bucket, false); - if (drainedFluid != null && drainedFluid.amount >= Constants.bucket) + /* NOT IN HELL DIMENSION. */ + FluidStack drainedFluid = tank.drain(BUCKET, false); + if (drainedFluid != null && drainedFluid.amount >= BUCKET) { if (!world.isRemote && flag && !material.isLiquid()) { @@ -354,17 +364,19 @@ public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer pla { if (world.setBlock(x, y, z, Blocks.flowing_water, 0, 3)) { - tank.drain(Constants.bucket, true); + tank.drain(BUCKET, true); } - } else if (fluid.getFluid().getBlock() == Blocks.lava) + } + else if (fluid.getFluid().getBlock() == Blocks.lava) { if (world.setBlock(x, y, z, Blocks.flowing_lava, 0, 3)) { - tank.drain(Constants.bucket, true); + tank.drain(BUCKET, true); } - } else if (world.setBlock(x, y, z, fluid.getFluid().getBlock(), 0, 3)) + } + else if (world.setBlock(x, y, z, fluid.getFluid().getBlock(), 0, 3)) { - tank.drain(Constants.bucket, true); + tank.drain(BUCKET, true); } } } @@ -375,7 +387,7 @@ public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer pla } break; case HOSE_DRINK_MODE: - if (tank.getFluid() != null && tank.getFluidAmount() >= Constants.bucket) + if (tank.getFluid() != null && tank.getFluidAmount() >= BUCKET) { if (FluidEffectRegistry.hasFluidEffect(tank.getFluid().getFluid())) { @@ -390,22 +402,10 @@ public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer pla return stack; } - @Override - public boolean onBlockStartBreak(ItemStack itemstack, int X, int Y, int Z, EntityPlayer player) - { - return false; - } - - @Override - public boolean onEntitySwing(EntityLivingBase entityLiving, ItemStack stack) - { - return false; - } - @Override public ItemStack onEaten(ItemStack hose, World world, EntityPlayer player) { - if(!Wearing.isWearingBackpack(player))return hose; + if (!Wearing.isWearingBackpack(player)) return hose; int mode = -1; int tank = -1; if (hose.stackTagCompound != null) @@ -422,7 +422,7 @@ public ItemStack onEaten(ItemStack hose, World world, EntityPlayer player) { if (ServerActions.setFluidEffect(world, player, backpackTank)) { - backpackTank.drain(Constants.bucket, true); + backpackTank.drain(BUCKET, true); inv.dirtyTanks(); } } @@ -430,24 +430,17 @@ public ItemStack onEaten(ItemStack hose, World world, EntityPlayer player) return hose; } - @Override - public boolean onDroppedByPlayer(ItemStack item, EntityPlayer player) - { - return true; - } - - // ================================================ BOOLEANS =====================================================// @Override public boolean itemInteractionForEntity(ItemStack stack, EntityPlayer player, EntityLivingBase entity) { - if(!Wearing.isWearingBackpack(player))return false; + if (!Wearing.isWearingBackpack(player)) return false; InventoryBackpack inventory = new InventoryBackpack(Wearing.getWearingBackpack(player)); inventory.openInventory(); if (entity instanceof EntityCow && !(entity instanceof EntityMooshroom)) { FluidTank tank = getHoseTank(stack) == 0 ? inventory.getLeftTank() : inventory.getRightTank(); - tank.fill(new FluidStack(ModFluids.milk, Constants.bucket), true); + tank.fill(new FluidStack(ModFluids.milk, BUCKET), true); inventory.dirtyTanks(); ((EntityCow) entity).faceEntity(player, 0.1f, 0.1f); @@ -456,7 +449,7 @@ public boolean itemInteractionForEntity(ItemStack stack, EntityPlayer player, En if (entity instanceof EntityMooshroom) { FluidTank tank = getHoseTank(stack) == 0 ? inventory.getLeftTank() : inventory.getRightTank(); - tank.fill(new FluidStack(ModFluids.mushroomStew, Constants.bucket), true); + tank.fill(new FluidStack(ModFluids.mushroomStew, BUCKET), true); inventory.dirtyTanks(); ((EntityMooshroom) entity).faceEntity(player, 0.1f, 0.1f); diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemJuiceBottle.java b/src/main/java/com/darkona/adventurebackpack/item/ItemJuiceBottle.java index a8bf3d90..25ac9bb6 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemJuiceBottle.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemJuiceBottle.java @@ -1,9 +1,5 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.CreativeTabAB; -import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; -import com.darkona.adventurebackpack.init.ModFluids; -import com.darkona.adventurebackpack.util.Resources; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; @@ -11,6 +7,11 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; +import com.darkona.adventurebackpack.CreativeTabAB; +import com.darkona.adventurebackpack.fluids.FluidEffectRegistry; +import com.darkona.adventurebackpack.init.ModFluids; +import com.darkona.adventurebackpack.util.Resources; + /** * Created on 19/10/2014 * @@ -18,17 +19,15 @@ */ public class ItemJuiceBottle extends ItemAB { - public ItemJuiceBottle() { super(); - setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB); + setCreativeTab(CreativeTabAB.TAB_AB); setFull3D(); setUnlocalizedName("melonJuiceBottle"); setMaxStackSize(1); } - @Override public ItemStack onEaten(ItemStack stack, World world, EntityPlayer player) { @@ -43,20 +42,12 @@ public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer pla return stack; } - @Override - public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int meta, float hitX, float hitY, float hitZ) - { - return false; - } - - @Override public EnumAction getItemUseAction(ItemStack p_77661_1_) { return EnumAction.drink; } - @Override public int getMaxItemUseDuration(ItemStack p_77626_1_) { diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemMachete.java b/src/main/java/com/darkona/adventurebackpack/item/ItemMachete.java index 417d93c0..b1378f65 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemMachete.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemMachete.java @@ -1,8 +1,9 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.CreativeTabAB; -import com.darkona.adventurebackpack.init.ModMaterials; +import java.util.Set; + import com.google.common.collect.Sets; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.EntityLivingBase; @@ -16,7 +17,8 @@ import net.minecraftforge.common.IShearable; import net.minecraftforge.oredict.OreDictionary; -import java.util.Set; +import com.darkona.adventurebackpack.CreativeTabAB; +import com.darkona.adventurebackpack.init.ModMaterials; /** * Created on 10/10/2014 @@ -25,7 +27,8 @@ */ public class ItemMachete extends ToolAB { - private static final Set breakableBlocks = Sets.newHashSet(Blocks.pumpkin, + private static final Set BREAKABLE_BLOCKS = Sets.newHashSet( + Blocks.pumpkin, Blocks.web, Blocks.leaves, Blocks.leaves2, @@ -48,13 +51,15 @@ public class ItemMachete extends ToolAB Blocks.waterlily, Blocks.wheat, Blocks.wool); + + @SuppressWarnings("FieldCanBeLocal") private float field_150934_a; public ItemMachete() { - super(ModMaterials.ruggedIron, breakableBlocks); - setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB); + super(ModMaterials.ruggedIron, BREAKABLE_BLOCKS); + setCreativeTab(CreativeTabAB.TAB_AB); setMaxDamage(Items.iron_sword.getMaxDamage() + 250); this.field_150934_a = ModMaterials.ruggedIron.getDamageVsEntity(); this.setUnlocalizedName("machete"); @@ -72,13 +77,8 @@ public float func_150893_a(ItemStack stack, Block block) if (stacky.getItem() == Item.getItemFromBlock(block)) return 15F; } return material == Material.plants || material == Material.vine || material == Material.coral || material == Material.gourd || material == Material.leaves || material == Material.cloth ? 12.0F : 0.5F; - } - /** - * Current implementations of this method in child classes do not use the entry argument beside ev. They just raise - * the damage on the stack. - */ @Override public boolean hitEntity(ItemStack p_77644_1_, EntityLivingBase p_77644_2_, EntityLivingBase p_77644_3_) { @@ -89,55 +89,13 @@ public boolean hitEntity(ItemStack p_77644_1_, EntityLivingBase p_77644_2_, Enti @Override public boolean onBlockDestroyed(ItemStack stack, World world, Block block, int x, int y, int z, EntityLivingBase entityLivingBase) { - if (block != Blocks.vine && !(block instanceof IShearable)) - { - return super.onBlockDestroyed(stack, world, block, x, y, z, entityLivingBase); - } else - { - return true; - } + return block == Blocks.vine || block instanceof IShearable + || super.onBlockDestroyed(stack, world, block, x, y, z, entityLivingBase); } @Override public boolean onBlockStartBreak(ItemStack itemstack, int x, int y, int z, EntityPlayer player) { - /* - if (player.worldObj.isRemote) - { - return false; - } - int id = player.worldObj.getBlockId(x, y, z); - for(ItemStack stacky : OreDictionary.getOres("treeLeaves")){ - if (stacky.itemID == id) return false; - } - - if (Block.blocksList[id] instanceof IShearable ) - { - IShearable target = (IShearable)Block.blocksList[id]; - if (target.isShearable(itemstack, player.worldObj, x, y, z)) - { - ArrayList drops = target.onSheared(itemstack, player.worldObj, x, y, z, - EnchantmentHelper.getEnchantmentLevel(Enchantment.fortune.effectId, itemstack)); - Random rand = new Random(); - - for(ItemStack stack : drops) - { - float f = 0.7F; - double d = (double)(rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D; - double d1 = (double)(rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D; - double d2 = (double)(rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D; - EntityItem entityitem = new EntityItem(player.worldObj, (double)x + d, (double)y + d1, (double)z + d2, stack); - entityitem.delayBeforeCanPickup = 10; - player.worldObj.spawnEntityInWorld(entityitem); - } - - itemstack.damageItem(1, player); - player.addStat(StatList.mineBlockStatArray[id], 1); - } - } - return false; - */ return new ItemStack(new ItemShears()).getItem().onBlockStartBreak(itemstack, x, y, z, player); } - } diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemPistonBoots.java b/src/main/java/com/darkona/adventurebackpack/item/ItemPistonBoots.java index e742b912..7f8dfe82 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemPistonBoots.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemPistonBoots.java @@ -1,34 +1,38 @@ package com.darkona.adventurebackpack.item; - import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; +import com.darkona.adventurebackpack.config.ConfigHandler; + /** * Created by Darkona on 11/10/2014. */ public class ItemPistonBoots extends ArmorAB { - public ItemPistonBoots() { super(2, 3); + setMaxDamage(Items.iron_boots.getMaxDamage() + 55); setUnlocalizedName("pistonBoots"); } + @Override public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { - if (player.isSprinting()) - { + if (ConfigHandler.pistonBootsAutoStep) player.stepHeight = 1.001F; - player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 1)); - } else - { - player.stepHeight = 0.5001F; - } + if (ConfigHandler.pistonBootsSprintBoost != 0 && player.isSprinting()) + player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 1, ConfigHandler.pistonBootsSprintBoost - 1)); } + @Override + public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) + { + return repair.isItemEqual(new ItemStack(Items.leather)); + } } diff --git a/src/main/java/com/darkona/adventurebackpack/item/ItemTelescope.java b/src/main/java/com/darkona/adventurebackpack/item/ItemTelescope.java index f391f974..2f495ba4 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ItemTelescope.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ItemTelescope.java @@ -7,5 +7,5 @@ */ public class ItemTelescope extends ItemAB { - + //Make Telescope item doto list } diff --git a/src/main/java/com/darkona/adventurebackpack/item/ToolAB.java b/src/main/java/com/darkona/adventurebackpack/item/ToolAB.java index f9422351..aea4b004 100644 --- a/src/main/java/com/darkona/adventurebackpack/item/ToolAB.java +++ b/src/main/java/com/darkona/adventurebackpack/item/ToolAB.java @@ -1,26 +1,26 @@ package com.darkona.adventurebackpack.item; -import com.darkona.adventurebackpack.reference.ModInfo; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.Set; + import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; -import java.util.Set; +import com.darkona.adventurebackpack.reference.ModInfo; /** * Created by Darkona on 11/10/2014. */ public class ToolAB extends ItemTool { - - public ToolAB(ToolMaterial material, Set breakableBlocks) + ToolAB(ToolMaterial material, Set breakableBlocks) { super(1f, material, breakableBlocks); - //setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB); + //setCreativeTab(CreativeTabAB.TAB_AB); } @Override @@ -32,13 +32,13 @@ public Item setCreativeTab(CreativeTabs tab) @Override public String getUnlocalizedName(ItemStack stack) { - return String.format("item.%s%s", ModInfo.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); + return String.format("item.%s%s", ModInfo.MOD_ID + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override public String getUnlocalizedName() { - return String.format("item.%s%s", ModInfo.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); + return String.format("item.%s%s", ModInfo.MOD_ID + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override @@ -48,7 +48,6 @@ public void registerIcons(IIconRegister iconRegister) itemIcon = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1)); } - protected String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); diff --git a/src/main/java/com/darkona/adventurebackpack/network/CowAbilityPacket.java b/src/main/java/com/darkona/adventurebackpack/network/CowAbilityPacket.java index 1f4a8b12..8f88832b 100644 --- a/src/main/java/com/darkona/adventurebackpack/network/CowAbilityPacket.java +++ b/src/main/java/com/darkona/adventurebackpack/network/CowAbilityPacket.java @@ -1,17 +1,19 @@ package com.darkona.adventurebackpack.network; -import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; -import com.darkona.adventurebackpack.inventory.ContainerBackpack; -import cpw.mods.fml.common.network.ByteBufUtils; -import cpw.mods.fml.common.network.simpleimpl.IMessage; -import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; -import cpw.mods.fml.common.network.simpleimpl.MessageContext; +import java.util.UUID; + import io.netty.buffer.ByteBuf; + import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; +import cpw.mods.fml.common.network.ByteBufUtils; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; -import java.util.UUID; +import com.darkona.adventurebackpack.inventory.ContainerBackpack; +import com.darkona.adventurebackpack.inventory.IInventoryBackpack; /** * Created on 16/10/2014 @@ -20,7 +22,6 @@ */ public class CowAbilityPacket implements IMessageHandler { - public static final byte CONSUME_WHEAT = 0; @Override @@ -34,7 +35,7 @@ public IMessage onMessage(CowAbilityMessage message, MessageContext ctx) { ContainerBackpack cont = ((ContainerBackpack) player.openContainer); cont.detectAndSendChanges(); - IInventoryAdventureBackpack inv = cont.inventory; + IInventoryBackpack inv = cont.getInventoryBackpack(); switch (message.action) { case CONSUME_WHEAT: @@ -47,13 +48,10 @@ public IMessage onMessage(CowAbilityMessage message, MessageContext ctx) public static class CowAbilityMessage implements IMessage { - private byte action; private String playerID; - public CowAbilityMessage() - { - } + public CowAbilityMessage() {} public CowAbilityMessage(String playerID, byte action) { @@ -64,7 +62,6 @@ public CowAbilityMessage(String playerID, byte action) @Override public void fromBytes(ByteBuf buf) { - playerID = ByteBufUtils.readUTF8String(buf); action = buf.readByte(); } @@ -76,5 +73,4 @@ public void toBytes(ByteBuf buf) buf.writeByte(action); } } - } diff --git a/src/main/java/com/darkona/adventurebackpack/network/CycleToolPacket.java b/src/main/java/com/darkona/adventurebackpack/network/CycleToolPacket.java index 1e402280..25e95a21 100644 --- a/src/main/java/com/darkona/adventurebackpack/network/CycleToolPacket.java +++ b/src/main/java/com/darkona/adventurebackpack/network/CycleToolPacket.java @@ -1,11 +1,13 @@ package com.darkona.adventurebackpack.network; -import com.darkona.adventurebackpack.common.ServerActions; +import io.netty.buffer.ByteBuf; + +import net.minecraft.entity.player.EntityPlayerMP; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; -import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayerMP; + +import com.darkona.adventurebackpack.common.ServerActions; /** * Created by Darkona on 12/10/2014. @@ -14,7 +16,6 @@ */ public class CycleToolPacket implements IMessageHandler { - public static final byte TOGGLE_HOSE_TANK = 0; public static final byte SWITCH_HOSE_ACTION = 1; public static final byte CYCLE_TOOL_ACTION = 2; @@ -24,18 +25,21 @@ public IMessage onMessage(CycleToolMessage message, MessageContext ctx) { if (ctx.side.isServer()) { - //LogHelper.info("Received CycleToolMessage with values: " + message.directionOfCycle + " " + message.typeOfAction + " " + message.slot); EntityPlayerMP player = ctx.getServerHandler().playerEntity; + + if (player == null || player.isDead) + return null; + switch (message.typeOfAction) { case CYCLE_TOOL_ACTION: - ServerActions.cycleTool(player, message.directionOfCycle, message.slot); + ServerActions.cycleTool(player, message.isWheelUp); break; case TOGGLE_HOSE_TANK: - ServerActions.switchHose(player, ServerActions.HOSE_TOGGLE, message.directionOfCycle, message.slot); + ServerActions.switchHose(player, message.isWheelUp, ServerActions.HOSE_TOGGLE); break; case SWITCH_HOSE_ACTION: - ServerActions.switchHose(player, ServerActions.HOSE_SWITCH, message.directionOfCycle, message.slot); + ServerActions.switchHose(player, message.isWheelUp, ServerActions.HOSE_SWITCH); break; } } @@ -44,38 +48,29 @@ public IMessage onMessage(CycleToolMessage message, MessageContext ctx) public static class CycleToolMessage implements IMessage { - - private int directionOfCycle; - private int slot; private byte typeOfAction; + private boolean isWheelUp; - public CycleToolMessage() - { - } + public CycleToolMessage() {} - public CycleToolMessage(int directionOfCycle, int slot, byte typeOfAction) + public CycleToolMessage(boolean isWheelUp, byte typeOfAction) { this.typeOfAction = typeOfAction; - this.directionOfCycle = directionOfCycle; - this.slot = slot; - + this.isWheelUp = isWheelUp; } @Override public void fromBytes(ByteBuf buf) { this.typeOfAction = buf.readByte(); - this.directionOfCycle = buf.readInt(); - this.slot = buf.readInt(); + this.isWheelUp = buf.readBoolean(); } @Override public void toBytes(ByteBuf buf) { buf.writeByte(typeOfAction); - buf.writeInt(directionOfCycle); - buf.writeInt(slot); + buf.writeBoolean(isWheelUp); } } - } diff --git a/src/main/java/com/darkona/adventurebackpack/network/EquipUnequipBackWearablePacket.java b/src/main/java/com/darkona/adventurebackpack/network/EquipUnequipBackWearablePacket.java index 190a1874..27d02e50 100644 --- a/src/main/java/com/darkona/adventurebackpack/network/EquipUnequipBackWearablePacket.java +++ b/src/main/java/com/darkona/adventurebackpack/network/EquipUnequipBackWearablePacket.java @@ -1,51 +1,51 @@ package com.darkona.adventurebackpack.network; -import com.darkona.adventurebackpack.util.BackpackUtils; -import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.common.network.simpleimpl.IMessage; -import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; -import cpw.mods.fml.common.network.simpleimpl.MessageContext; import io.netty.buffer.ByteBuf; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ChatComponentTranslation; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; + +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.Wearing; /** * Created on 08/01/2015 * * @author Darkona */ -public class EquipUnequipBackWearablePacket implements IMessageHandler +public class EquipUnequipBackWearablePacket implements IMessageHandler { - public static final byte EQUIP_WEARABLE = 0; public static final byte UNEQUIP_WEARABLE = 1; - @Override public Message onMessage(Message message, MessageContext ctx) { - - if(ctx.side.isServer()) + if (ctx.side.isServer()) { EntityPlayer player = ctx.getServerHandler().playerEntity; - if(message.action == EQUIP_WEARABLE) + + if (player == null || player.isDead) + return null; + + if (message.action == EQUIP_WEARABLE && Wearing.isHoldingWearable(player)) { - if(message.force) + if (Wearing.isWearingWearable(player)) { - BackpackUtils.unequipWearable(player); + Wearing.WearableType wtype = Wearing.getWearingWearableType(player); + if (wtype != Wearing.WearableType.UNKNOWN) + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.already.equipped." + wtype.name().toLowerCase())); } - if(Wearing.isHoldingWearable(player)) - { - if(BackpackUtils.equipWearable(player.getCurrentEquippedItem(), player) == BackpackUtils.reasons.SUCCESFUL){ - player.inventory.setInventorySlotContents(player.inventory.currentItem,null); - player.inventoryContainer.detectAndSendChanges(); - } - }else + else if (BackpackUtils.equipWearable(player.getCurrentEquippedItem(), player) == BackpackUtils.Reasons.SUCCESSFUL) { - player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:already.equipped")); + player.inventory.setInventorySlotContents(player.inventory.currentItem, null); + player.inventoryContainer.detectAndSendChanges(); } } - if(message.action == UNEQUIP_WEARABLE) + else if (message.action == UNEQUIP_WEARABLE) { BackpackUtils.unequipWearable(player); } @@ -55,33 +55,25 @@ public Message onMessage(Message message, MessageContext ctx) public static class Message implements IMessage { - private byte action; - private boolean force; - public Message(){} + public Message() {} - public Message(byte action, boolean force){ + public Message(byte action) + { this.action = action; - this.force = force; } + @Override public void fromBytes(ByteBuf buf) { action = buf.readByte(); - force = buf.readBoolean(); } - /** - * Deconstruct your message into the supplied byte buffer - * - * @param buf - */ @Override public void toBytes(ByteBuf buf) { buf.writeByte(action); - buf.writeBoolean(force); } } } diff --git a/src/main/java/com/darkona/adventurebackpack/network/GUIPacket.java b/src/main/java/com/darkona/adventurebackpack/network/GUIPacket.java index 797212d7..30d01154 100644 --- a/src/main/java/com/darkona/adventurebackpack/network/GUIPacket.java +++ b/src/main/java/com/darkona/adventurebackpack/network/GUIPacket.java @@ -1,26 +1,27 @@ package com.darkona.adventurebackpack.network; +import io.netty.buffer.ByteBuf; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.world.World; +import cpw.mods.fml.common.network.internal.FMLNetworkHandler; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; + import com.darkona.adventurebackpack.AdventureBackpack; import com.darkona.adventurebackpack.block.TileAdventureBackpack; import com.darkona.adventurebackpack.handlers.GuiHandler; import com.darkona.adventurebackpack.inventory.ContainerBackpack; +import com.darkona.adventurebackpack.reference.GeneralReference; import com.darkona.adventurebackpack.util.Wearing; -import cpw.mods.fml.common.network.internal.FMLNetworkHandler; -import cpw.mods.fml.common.network.simpleimpl.IMessage; -import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; -import cpw.mods.fml.common.network.simpleimpl.MessageContext; -import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.world.World; /** * Created by Darkona on 12/10/2014. */ public class GUIPacket implements IMessageHandler { - - - public static final byte FROM_KEYBIND = 0; + public static final byte FROM_WEARING = 0; public static final byte FROM_HOLDING = 1; public static final byte FROM_TILE = 2; @@ -35,94 +36,74 @@ public IMessage onMessage(GUImessage message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().playerEntity; - if (player != null) + if (player == null || player.isDead) + return null; + + World world = player.worldObj; + int playerX = (int) player.posX; + int playerY = (int) player.posY; + int playerZ = (int) player.posZ; + + if (message.type == COPTER_GUI) + { + if (message.from == FROM_WEARING) + { + if (Wearing.isWearingCopter(player)) + FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.COPTER_WEARING, world, playerX, playerY, playerZ); + } + else if (message.from == FROM_HOLDING) + { + if (Wearing.isHoldingCopter(player)) + FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.COPTER_HOLDING, world, playerX, playerY, playerZ); + } + } + else if (message.type == JETPACK_GUI) + { + if (message.from == FROM_WEARING) + { + if (Wearing.isWearingJetpack(player)) + FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.JETPACK_WEARING, world, playerX, playerY, playerZ); + } + else if (message.from == FROM_HOLDING) + { + if (Wearing.isHoldingJetpack(player)) + FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.JETPACK_HOLDING, world, playerX, playerY, playerZ); + } + } + else if (message.type == BACKPACK_GUI) { - int playerX = (int) player.posX; - int playerY = (int) player.posY; - int playerZ = (int) player.posZ; - World world = player.worldObj; + if (!GeneralReference.isDimensionAllowed(player)) + return null; - if (message.type == COPTER_GUI) + if (message.from == FROM_WEARING) { - if(message.from == FROM_KEYBIND) - { - if (Wearing.isWearingCopter(player)) - { - FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.COPTER_WEARING, world, playerX, playerY, playerZ); - return null; - } - } - if(message.from == FROM_HOLDING) - { - if (Wearing.isHoldingCopter(player)) - { - FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.COPTER_HOLDING, world, playerX, playerY, playerZ); - return null; - } - } + if (Wearing.isWearingBackpack(player)) + FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.BACKPACK_WEARING, world, playerX, playerY, playerZ); } - if (message.type == JETPACK_GUI) + else if (message.from == FROM_HOLDING) { - if(message.from == FROM_KEYBIND) - { - if (Wearing.isWearingSteam(player)) - { - FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.JETPACK_WEARING, world, playerX, playerY, playerZ); - return null; - } - } - if(message.from == FROM_HOLDING) - { - if (Wearing.isHoldingSteam(player)) - { - FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.JETPACK_HOLDING, world, playerX, playerY, playerZ); - return null; - } - } + if (Wearing.isHoldingBackpack(player)) + FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.BACKPACK_HOLDING, world, playerX, playerY, playerZ); } - if (message.type == BACKPACK_GUI) + else if (message.from == FROM_TILE) { - if (message.from == FROM_KEYBIND) - { - if (Wearing.isWearingBackpack(player)) - { - FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.BACKPACK_WEARING, world, playerX, playerY, playerZ); - return null; - } - } - if (message.from == FROM_HOLDING) + if (player.openContainer instanceof ContainerBackpack) { - if (Wearing.isHoldingBackpack(player)) - { - FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.BACKPACK_HOLDING, world, playerX, playerY, playerZ); - return null; - } - } - if (message.from == FROM_TILE) - { - if (player.openContainer instanceof ContainerBackpack) - { - TileAdventureBackpack te = (TileAdventureBackpack) ((ContainerBackpack) player.openContainer).inventory; - FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.BACKPACK_TILE, world, te.xCoord, te.yCoord, te.zCoord); - return null; - } + TileAdventureBackpack te = (TileAdventureBackpack) ((ContainerBackpack) player.openContainer).getInventoryBackpack(); + FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.BACKPACK_TILE, world, te.xCoord, te.yCoord, te.zCoord); } } } - } return null; } public static class GUImessage implements IMessage { - private byte type; private byte from; - public GUImessage() - { - } + public GUImessage() {} public GUImessage(byte type, byte from) { diff --git a/src/main/java/com/darkona/adventurebackpack/network/MessageConstants.java b/src/main/java/com/darkona/adventurebackpack/network/MessageConstants.java deleted file mode 100644 index 60c049c3..00000000 --- a/src/main/java/com/darkona/adventurebackpack/network/MessageConstants.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.darkona.adventurebackpack.network; - -/** - * Created on 14/10/2014 - * - * @author Darkona - */ -public class MessageConstants -{ - -} diff --git a/src/main/java/com/darkona/adventurebackpack/network/PlayerActionPacket.java b/src/main/java/com/darkona/adventurebackpack/network/PlayerActionPacket.java index fced6343..cf1422b1 100644 --- a/src/main/java/com/darkona/adventurebackpack/network/PlayerActionPacket.java +++ b/src/main/java/com/darkona/adventurebackpack/network/PlayerActionPacket.java @@ -1,61 +1,80 @@ package com.darkona.adventurebackpack.network; -import com.darkona.adventurebackpack.entity.EntityFriendlySpider; -import com.darkona.adventurebackpack.inventory.InventorySteamJetpack; -import com.darkona.adventurebackpack.util.Wearing; +import io.netty.buffer.ByteBuf; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; -import io.netty.buffer.ByteBuf; + +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.entity.EntityFriendlySpider; +import com.darkona.adventurebackpack.inventory.ContainerBackpack; +import com.darkona.adventurebackpack.inventory.IInventoryBackpack; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; +import com.darkona.adventurebackpack.util.Wearing; /** * Created by Darkona on 12/10/2014. */ public class PlayerActionPacket implements IMessageHandler { - public static final byte spiderJump = 0; + public static final byte SPIDER_JUMP = 0; public static final byte JETPACK_IN_USE = 1; public static final byte JETPACK_NOT_IN_USE = 2; + public static final byte GUI_HOLDING_SPACE = 3; + public static final byte GUI_NOT_HOLDING_SPACE = 4; @Override public IMessage onMessage(ActionMessage message, MessageContext ctx) { if (ctx.side.isServer()) { - if(message.type == spiderJump){ - if(ctx.getServerHandler().playerEntity.ridingEntity != null && ctx.getServerHandler().playerEntity.ridingEntity instanceof EntityFriendlySpider) - { - ((EntityFriendlySpider)ctx.getServerHandler().playerEntity.ridingEntity).setJumping(true); - } - } + EntityPlayerMP player = ctx.getServerHandler().playerEntity; + + if (player == null || player.isDead) + return null; - if(message.type == JETPACK_IN_USE || message.type == JETPACK_NOT_IN_USE) + if (message.type == SPIDER_JUMP) { - if(Wearing.isWearingSteam(ctx.getServerHandler().playerEntity)) + if (player.ridingEntity instanceof EntityFriendlySpider) + ((EntityFriendlySpider) player.ridingEntity).setJumping(true); + } + else if (message.type == JETPACK_IN_USE || message.type == JETPACK_NOT_IN_USE) + { + ItemStack jetpack = Wearing.getWearingJetpack(player); + if (jetpack != null) { - InventorySteamJetpack inv = new InventorySteamJetpack(Wearing.getWearingSteam(ctx.getServerHandler().playerEntity)); + InventoryCoalJetpack inv = new InventoryCoalJetpack(jetpack); inv.setInUse(message.type == JETPACK_IN_USE); inv.markDirty(); } } - + else if (message.type == GUI_HOLDING_SPACE || message.type == GUI_NOT_HOLDING_SPACE) + { + if (player.openContainer instanceof ContainerBackpack) + { + IInventoryBackpack inv = ((ContainerBackpack) player.openContainer).getInventoryBackpack(); + if (message.type == GUI_HOLDING_SPACE) + inv.getExtendedProperties().setBoolean(Constants.TAG_HOLDING_SPACE, true); + else if (message.type == GUI_NOT_HOLDING_SPACE) + inv.getExtendedProperties().removeTag(Constants.TAG_HOLDING_SPACE); + } + } } return null; } public static class ActionMessage implements IMessage { - private byte type; - public ActionMessage() - { - } + public ActionMessage() {} public ActionMessage(byte type) { this.type = type; - } @Override diff --git a/src/main/java/com/darkona/adventurebackpack/network/SleepingBagPacket.java b/src/main/java/com/darkona/adventurebackpack/network/SleepingBagPacket.java index 70e7ccee..59267e6c 100644 --- a/src/main/java/com/darkona/adventurebackpack/network/SleepingBagPacket.java +++ b/src/main/java/com/darkona/adventurebackpack/network/SleepingBagPacket.java @@ -1,10 +1,14 @@ package com.darkona.adventurebackpack.network; -import com.darkona.adventurebackpack.common.ServerActions; +import io.netty.buffer.ByteBuf; + +import net.minecraft.entity.player.EntityPlayerMP; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; -import io.netty.buffer.ByteBuf; + +import com.darkona.adventurebackpack.common.ServerActions; +import com.darkona.adventurebackpack.config.ConfigHandler; /** * Created on 19/10/2014 @@ -13,51 +17,57 @@ */ public class SleepingBagPacket implements IMessageHandler { - @Override public IMessage onMessage(SleepingBagMessage message, MessageContext ctx) { if (ctx.side.isServer()) { - ServerActions.toggleSleepingBag(ctx.getServerHandler().playerEntity, message.x, message.y, message.z); + EntityPlayerMP player = ctx.getServerHandler().playerEntity; + + if (player == null || player.isDead) + return null; + + if (message.isTile || ConfigHandler.portableSleepingBag) // serverside check + { + ServerActions.toggleSleepingBag(player, message.isTile, message.cX, message.cY, message.cZ); + } } return null; } - public static class SleepingBagMessage implements IMessage { + private boolean isTile; + private int cX; + private int cY; + private int cZ; - public int x; - public int y; - public int z; + public SleepingBagMessage() {} - public SleepingBagMessage() + public SleepingBagMessage(boolean isTile, int cX, int cY, int cZ) { - } - - public SleepingBagMessage(int X, int Y, int Z) - { - this.x = X; - this.y = Y; - this.z = Z; + this.isTile = isTile; + this.cX = cX; + this.cY = cY; + this.cZ = cZ; } @Override public void fromBytes(ByteBuf buf) { - x = buf.readInt(); - y = buf.readInt(); - z = buf.readInt(); + isTile = buf.readBoolean(); + cX = buf.readInt(); + cY = buf.readInt(); + cZ = buf.readInt(); } @Override public void toBytes(ByteBuf buf) { - buf.writeInt(x); - buf.writeInt(y); - buf.writeInt(z); + buf.writeBoolean(isTile); + buf.writeInt(cX); + buf.writeInt(cY); + buf.writeInt(cZ); } - } } diff --git a/src/main/java/com/darkona/adventurebackpack/network/SyncPropertiesPacket.java b/src/main/java/com/darkona/adventurebackpack/network/SyncPropertiesPacket.java index 781d742a..7d06fbf5 100644 --- a/src/main/java/com/darkona/adventurebackpack/network/SyncPropertiesPacket.java +++ b/src/main/java/com/darkona/adventurebackpack/network/SyncPropertiesPacket.java @@ -1,13 +1,17 @@ package com.darkona.adventurebackpack.network; -import com.darkona.adventurebackpack.AdventureBackpack; -import com.darkona.adventurebackpack.playerProperties.BackpackProperty; +import io.netty.buffer.ByteBuf; + +import net.minecraft.client.Minecraft; +import net.minecraft.nbt.NBTTagCompound; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; -import io.netty.buffer.ByteBuf; -import net.minecraft.nbt.NBTTagCompound; + +import com.darkona.adventurebackpack.AdventureBackpack; +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.playerProperties.BackpackProperty; /** * Created on 08/01/2015 @@ -24,10 +28,16 @@ public class SyncPropertiesPacket implements IMessageHandler { - public static byte COPTER_ON_OFF = 0; - public static byte COPTER_TOGGLE = 1; - public static byte JETPACK_ON_OFF = 2; + public static final byte COPTER_ON_OFF = 0; + public static final byte COPTER_TOGGLE = 1; + public static final byte JETPACK_ON_OFF = 2; + public static final byte CYCLING_ON_OFF = 3; + public static final byte NIGHTVISION_ON_OFF = 4; + @Override public Message onMessage(Message message, MessageContext ctx) { if (ctx.side.isServer()) { EntityPlayerMP player = ctx.getServerHandler().playerEntity; + // we don't want to process any packets from a player who's already considered dead on the server. + // in the current tick, at the time the packets are processed, the entity data must already be updated + // and isDead flag will be set, see: MinecraftServer#updateTimeLightAndEntities (func_71190_q) + if (player == null || player.isDead) + return null; - if (player != null) + if (message.type == COPTER_ON_OFF || message.type == COPTER_TOGGLE) { - if((message.type == COPTER_ON_OFF || message.type == COPTER_TOGGLE)) - ServerActions.toggleCopterPack(player, Wearing.getWearingCopter(player), message.type); - - if(message.type == JETPACK_ON_OFF) - ServerActions.toggleSteamJetpack(player,Wearing.getWearingSteam(player),message.type); + ItemStack copter = Wearing.getWearingCopter(player); + // for concurrency reasons, at the time of death with OpenBlocks mod, the copter may already be + // in the grave, and Wearing#getWearingCopter will return null (c) Relvl + if (copter != null) + ServerActions.toggleCopterPack(player, copter, message.type); + } + else if (message.type == JETPACK_ON_OFF) + { + ItemStack jetpack = Wearing.getWearingJetpack(player); + if (jetpack != null) // so now we are well-defended + ServerActions.toggleCoalJetpack(player, jetpack); + } + else if (message.type == CYCLING_ON_OFF || message.type == NIGHTVISION_ON_OFF) + { + ItemStack backpack = Wearing.getWearingBackpack(player); + if (backpack != null) // null shall not pass! + { + if (message.type == CYCLING_ON_OFF) + ServerActions.toggleToolCycling(player, backpack); + else if (message.type == NIGHTVISION_ON_OFF) + ServerActions.toggleNightVision(player, backpack); + } } - - } - if (ctx.side.isClient()) - { - } return null; } public static class Message implements IMessage { - private byte type; - private String playerID; - public Message() - { - } + public Message() {} - public Message(byte type, String playerID) + public Message(byte type) { this.type = type; - this.playerID = playerID; } @Override public void fromBytes(ByteBuf buf) { this.type = buf.readByte(); - playerID = ByteBufUtils.readUTF8String(buf); } @Override public void toBytes(ByteBuf buf) { buf.writeByte(type); - ByteBufUtils.writeUTF8String(buf, playerID); } } } \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/network/messages/EntityParticlePacket.java b/src/main/java/com/darkona/adventurebackpack/network/messages/EntityParticlePacket.java index 213df08c..0e3f95a8 100644 --- a/src/main/java/com/darkona/adventurebackpack/network/messages/EntityParticlePacket.java +++ b/src/main/java/com/darkona/adventurebackpack/network/messages/EntityParticlePacket.java @@ -1,13 +1,15 @@ package com.darkona.adventurebackpack.network.messages; -import com.darkona.adventurebackpack.client.ClientActions; -import com.darkona.adventurebackpack.init.ModNetwork; -import cpw.mods.fml.common.network.simpleimpl.IMessage; -import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; -import cpw.mods.fml.common.network.simpleimpl.MessageContext; import io.netty.buffer.ByteBuf; + import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; + +import com.darkona.adventurebackpack.client.ClientActions; +import com.darkona.adventurebackpack.init.ModNetwork; /** * Created on 06/01/2015 @@ -21,8 +23,6 @@ public class EntityParticlePacket implements IMessageHandler { - public static final boolean play = true; public static final byte NYAN_SOUND = 0; @@ -32,7 +33,8 @@ public Message onMessage(Message message, MessageContext ctx) if (ctx.side.isClient()) { ClientActions.playSoundAtEntity(Minecraft.getMinecraft().theWorld.getEntityByID(message.entityID), message.soundCode); - } else + } + else { EntityPlayer player = ctx.getServerHandler().playerEntity; ModNetwork.sendToNearby(message, player); @@ -42,8 +44,6 @@ public Message onMessage(Message message, MessageContext ctx) public static class Message implements IMessage { - - private byte soundCode; private int entityID; @@ -55,6 +55,7 @@ public Message(byte soundCode, Entity entity) public Message() { + } @Override diff --git a/src/main/java/com/darkona/adventurebackpack/playerProperties/BackpackProperty.java b/src/main/java/com/darkona/adventurebackpack/playerProperties/BackpackProperty.java index bab96da4..2312645f 100644 --- a/src/main/java/com/darkona/adventurebackpack/playerProperties/BackpackProperty.java +++ b/src/main/java/com/darkona/adventurebackpack/playerProperties/BackpackProperty.java @@ -1,225 +1,180 @@ -package com.darkona.adventurebackpack.playerProperties; - -import com.darkona.adventurebackpack.init.ModNetwork; -import com.darkona.adventurebackpack.item.IBackWearableItem; -import com.darkona.adventurebackpack.network.SyncPropertiesPacket; -import com.darkona.adventurebackpack.util.Utils; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; -import net.minecraftforge.common.IExtendedEntityProperties; - -/** - * Created on 24/10/2014 - * - * @author Darkona - */ -public class BackpackProperty implements IExtendedEntityProperties -{ - - public static final String PROPERTY_NAME = "abp.property"; - protected EntityPlayer player = null; - private ItemStack wearable = null; - private ChunkCoordinates campFire = null; - private NBTTagCompound wearableData = new NBTTagCompound(); - private boolean forceCampFire = false; - private int dimension = 0; - - public NBTTagCompound getWearableData() - { - return wearableData; - } - - - public static void sync(EntityPlayer player) - { - if(player instanceof EntityPlayerMP) - { - syncToNear(player); - } - } - - public static void syncToNear(EntityPlayer player) - { - //Thanks diesieben07!!! - if(player != null && player instanceof EntityPlayerMP) - { - try - { - ((EntityPlayerMP) player) - .getServerForPlayer() - .getEntityTracker() - .func_151248_b(player, ModNetwork.net.getPacketFrom(new SyncPropertiesPacket.Message(player.getEntityId(), get(player).getData()))); - }catch(Exception ex){ - ex.printStackTrace(); - } - } - } - - public BackpackProperty(EntityPlayer player) - { - this.player = player; - } - - public NBTTagCompound getData() - { - NBTTagCompound data = new NBTTagCompound(); - saveNBTData(data); - - return data; - } - - public static void register(EntityPlayer player) - { - player.registerExtendedProperties(PROPERTY_NAME, new BackpackProperty(player)); - } - - public static BackpackProperty get(EntityPlayer player) - { - return (BackpackProperty) player.getExtendedProperties(PROPERTY_NAME); - } - - /** - * Called when the entity that this class is attached to is saved. - * Any custom entity data that needs saving should be saved here. - * - * @param compound The compound to save to. - */ - @Override - public void saveNBTData(NBTTagCompound compound) - { - if(wearable != null) compound.setTag("wearable", wearable.writeToNBT(new NBTTagCompound())); - if (campFire != null) - { - compound.setInteger("campFireX", campFire.posX); - compound.setInteger("campFireY", campFire.posY); - compound.setInteger("campFireZ", campFire.posZ); - compound.setInteger("campFireDim", dimension); - - } - compound.setBoolean("forceCampFire",forceCampFire); - } - - /** - * Called when the entity that this class is attached to is loaded. - * In order to hook into this, you will need to subscribe to the EntityConstructing event. - * Otherwise, you will need to initialize manually. - * - * @param compound The compound to load from. - */ - @Override - public void loadNBTData(NBTTagCompound compound) - { - if(compound!=null) - { - setWearable( compound.hasKey("wearable") ? ItemStack.loadItemStackFromNBT(compound.getCompoundTag("wearable")) : null); - setCampFire( new ChunkCoordinates(compound.getInteger("campFireX"), compound.getInteger("campFireY"), compound.getInteger("campFireZ"))); - dimension = compound.getInteger("compFireDim"); - forceCampFire = compound.getBoolean("forceCampfire"); - } - } - - /** - * Used to initialize the extended properties with the entity that this is attached to, as well - * as the world object. - * Called automatically if you register with the EntityConstructing event. - * May be called multiple times if the extended properties is moved over to a new entity. - * Such as when a player switches dimension {Minecraft re-creates the player entity} - * - * @param entity The entity that this extended properties is attached to - * @param world The world in which the entity exists - */ - @Override - public void init(Entity entity, World world) - { - this.player = (EntityPlayer)entity; - } - - public void setWearable(ItemStack bp) - { - wearable = bp; - } - - - public ItemStack getWearable() - { - return wearable != null ? wearable : null ; - } - - public void setCampFire(ChunkCoordinates cf) - { - campFire = cf; - } - - public boolean hasWearable() - { - return wearable != null; - } - - public ChunkCoordinates getCampFire() - { - return campFire; - } - - public EntityPlayer getPlayer() - { - return player; - } - - public void setDimension(int dimension) - { - this.dimension = dimension; - } - - public int getDimension() - { - return dimension; - } - - public boolean isForcedCampFire() - { - return forceCampFire; - } - - public void setForceCampFire(boolean forceCampFire) - { - this.forceCampFire = forceCampFire; - } - - //Scary names for methods because why not - public void executeWearableUpdateProtocol() - { - if(Utils.notNullAndInstanceOf(wearable.getItem(), IBackWearableItem.class)) - { - ((IBackWearableItem)wearable.getItem()).onEquippedUpdate(player.getEntityWorld(), player, wearable); - } - } - - public void executeWearableDeathProtocol() - { - if (Utils.notNullAndInstanceOf(wearable.getItem(), IBackWearableItem.class)) - { - ((IBackWearableItem) wearable.getItem()).onPlayerDeath(player.getEntityWorld(), player, wearable); - } - } - - public void executeWearableEquipProtocol() - { - if (Utils.notNullAndInstanceOf(wearable.getItem(), IBackWearableItem.class)) - { - ((IBackWearableItem) wearable.getItem()).onEquipped(player.getEntityWorld(), player, wearable); - } - } - - public void executeWearableUnequipProtocol() - { - if (Utils.notNullAndInstanceOf(wearable.getItem() , IBackWearableItem.class)) - { - ((IBackWearableItem) wearable.getItem()).onUnequipped(player.getEntityWorld(), player, wearable); - } - } -} +package com.darkona.adventurebackpack.playerProperties; + +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; +import net.minecraftforge.common.IExtendedEntityProperties; + +import com.darkona.adventurebackpack.init.ModNetwork; +import com.darkona.adventurebackpack.item.IBackWearableItem; +import com.darkona.adventurebackpack.network.SyncPropertiesPacket; + +/** + * Created on 24/10/2014 + * + * @author Darkona + */ +public class BackpackProperty implements IExtendedEntityProperties +{ + private static final String PROPERTY_NAME = "abp.property"; + + private EntityPlayer player; + private ItemStack wearable = null; + private ChunkCoordinates campFire = null; + private boolean forceCampFire = false; + private int dimension = 0; + + private boolean isWakingUpInPortableBag = false; + + public void setWakingUpInPortableBag(boolean b) + { + this.isWakingUpInPortableBag = b; + } + + public boolean isWakingUpInPortableBag() + { + return this.isWakingUpInPortableBag; + } + + public static void sync(EntityPlayer player) + { + if (player instanceof EntityPlayerMP) + { + syncToNear((EntityPlayerMP) player); + } + } + + private static void syncToNear(EntityPlayerMP player) + { + //Thanks diesieben07!!! + try + { + player.getServerForPlayer().getEntityTracker() + .func_151248_b(player, ModNetwork.net.getPacketFrom(new SyncPropertiesPacket + .Message(player.getEntityId(), get(player).getData()))); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + + public BackpackProperty(EntityPlayer player) + { + this.player = player; + } + + public NBTTagCompound getData() + { + NBTTagCompound data = new NBTTagCompound(); + saveNBTData(data); + + return data; + } + + public static void register(EntityPlayer player) + { + player.registerExtendedProperties(PROPERTY_NAME, new BackpackProperty(player)); + } + + public static BackpackProperty get(EntityPlayer player) + { + return (BackpackProperty) player.getExtendedProperties(PROPERTY_NAME); + } + + @Override + public void saveNBTData(NBTTagCompound compound) + { + if (wearable != null) compound.setTag("wearable", wearable.writeToNBT(new NBTTagCompound())); + if (campFire != null) + { + compound.setInteger("campFireX", campFire.posX); + compound.setInteger("campFireY", campFire.posY); + compound.setInteger("campFireZ", campFire.posZ); + compound.setInteger("campFireDim", dimension); //TODO use it for check dim + } + compound.setBoolean("forceCampFire", forceCampFire); + } + + @Override + public void loadNBTData(NBTTagCompound compound) + { + if (compound != null) + { + setWearable(compound.hasKey("wearable") ? ItemStack.loadItemStackFromNBT(compound.getCompoundTag("wearable")) : null); + setCampFire(new ChunkCoordinates(compound.getInteger("campFireX"), compound.getInteger("campFireY"), compound.getInteger("campFireZ"))); + dimension = compound.getInteger("campFireDim"); + forceCampFire = compound.getBoolean("forceCampFire"); + } + } + + @Override + public void init(Entity entity, World world) + { + this.player = (EntityPlayer) entity; + } + + public void setWearable(ItemStack bp) + { + wearable = bp; + } + + public ItemStack getWearable() + { + return wearable; + } + + public void setCampFire(ChunkCoordinates cf) + { + campFire = cf; + } + + public ChunkCoordinates getCampFire() + { + return campFire; + } + + public EntityPlayer getPlayer() + { + return player; + } + + public boolean isForcedCampFire() + { + return forceCampFire; + } + + public void setForceCampFire(boolean forceCampFire) + { + this.forceCampFire = forceCampFire; + } + + //Scary names for methods because why not + public void executeWearableUpdateProtocol() + { + if (wearable.getItem() instanceof IBackWearableItem) + { + ((IBackWearableItem) wearable.getItem()).onEquippedUpdate(player.getEntityWorld(), player, wearable); + } + } + + public void executeWearableEquipProtocol() + { + if (wearable.getItem() instanceof IBackWearableItem) + { + ((IBackWearableItem) wearable.getItem()).onEquipped(player.getEntityWorld(), player, wearable); + } + } + + public void executeWearableUnequipProtocol() + { + if (wearable.getItem() instanceof IBackWearableItem) + { + ((IBackWearableItem) wearable.getItem()).onUnequipped(player.getEntityWorld(), player, wearable); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/proxy/ClientProxy.java b/src/main/java/com/darkona/adventurebackpack/proxy/ClientProxy.java index 2e20a8a1..e23a6f48 100644 --- a/src/main/java/com/darkona/adventurebackpack/proxy/ClientProxy.java +++ b/src/main/java/com/darkona/adventurebackpack/proxy/ClientProxy.java @@ -1,33 +1,43 @@ package com.darkona.adventurebackpack.proxy; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.client.MinecraftForgeClient; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.oredict.OreDictionary; +import cpw.mods.fml.client.registry.ClientRegistry; +import cpw.mods.fml.client.registry.RenderingRegistry; +import cpw.mods.fml.common.FMLCommonHandler; + import com.darkona.adventurebackpack.block.TileAdventureBackpack; import com.darkona.adventurebackpack.block.TileCampfire; import com.darkona.adventurebackpack.client.gui.GuiOverlay; import com.darkona.adventurebackpack.client.models.ModelBackpackArmor; +import com.darkona.adventurebackpack.client.models.ModelCoalJetpack; import com.darkona.adventurebackpack.client.models.ModelCopterPack; -import com.darkona.adventurebackpack.client.models.ModelSteamJetpack; -import com.darkona.adventurebackpack.client.render.*; +import com.darkona.adventurebackpack.client.render.RenderRideableSpider; +import com.darkona.adventurebackpack.client.render.RendererAdventureBackpackBlock; +import com.darkona.adventurebackpack.client.render.RendererCampFire; +import com.darkona.adventurebackpack.client.render.RendererHose; +import com.darkona.adventurebackpack.client.render.RendererInflatableBoat; +import com.darkona.adventurebackpack.client.render.RendererItemAdventureBackpack; +import com.darkona.adventurebackpack.client.render.RendererItemAdventureHat; +import com.darkona.adventurebackpack.client.render.RendererItemClockworkCrossbow; +import com.darkona.adventurebackpack.client.render.RendererWearableEquipped; import com.darkona.adventurebackpack.config.ConfigHandler; import com.darkona.adventurebackpack.config.Keybindings; import com.darkona.adventurebackpack.entity.EntityFriendlySpider; import com.darkona.adventurebackpack.entity.EntityInflatableBoat; -import com.darkona.adventurebackpack.handlers.KeybindHandler; +import com.darkona.adventurebackpack.handlers.KeyInputEventHandler; import com.darkona.adventurebackpack.handlers.RenderHandler; import com.darkona.adventurebackpack.init.ModBlocks; import com.darkona.adventurebackpack.init.ModItems; import com.darkona.adventurebackpack.playerProperties.BackpackProperty; -import com.darkona.adventurebackpack.util.LogHelper; -import com.darkona.adventurebackpack.util.Utils; -import cpw.mods.fml.client.registry.ClientRegistry; -import cpw.mods.fml.client.registry.RenderingRegistry; -import cpw.mods.fml.common.FMLCommonHandler; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.client.MinecraftForgeClient; -import net.minecraftforge.common.MinecraftForge; +import com.darkona.adventurebackpack.reference.LoadedMods; /** * Created on 10/10/2014 @@ -36,86 +46,69 @@ */ public class ClientProxy implements IProxy { - - public static RendererItemAdventureBackpack rendererItemAdventureBackpack; - public static RendererItemAdventureHat rendererItemAdventureHat; - public static RendererHose rendererHose; - public static RendererWearableEquipped rendererWearableEquipped; - public static RenderHandler renderHandler; - public static RendererInflatableBoat renderInflatableBoat; - public static RenderRideableSpider renderRideableSpider; - public static RendererItemClockworkCrossbow renderCrossbow; - public static ModelSteamJetpack modelSteamJetpack = new ModelSteamJetpack(); + public static RendererWearableEquipped rendererWearableEquipped = new RendererWearableEquipped(); public static ModelBackpackArmor modelAdventureBackpack = new ModelBackpackArmor(); + public static ModelCoalJetpack modelCoalJetpack = new ModelCoalJetpack(); public static ModelCopterPack modelCopterPack = new ModelCopterPack(); - + @Override public void init() { initRenderers(); registerKeybindings(); MinecraftForge.EVENT_BUS.register(new GuiOverlay(Minecraft.getMinecraft())); - } - - public void initNetwork() - { - - } - @Override - public void joinPlayer(EntityPlayer player) - { - LogHelper.info("Joined Player in client"); + if (LoadedMods.NEI) + { + codechicken.nei.api.API.hideItem(new ItemStack(ModBlocks.blockBackpack, 1, OreDictionary.WILDCARD_VALUE)); + codechicken.nei.api.API.hideItem(new ItemStack(ModBlocks.blockSleepingBag, 1, OreDictionary.WILDCARD_VALUE)); + } } @Override public void synchronizePlayer(int id, NBTTagCompound properties) { Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(id); - if(Utils.notNullAndInstanceOf(entity, EntityPlayer.class)&& properties != null) + + if (entity instanceof EntityPlayer && properties != null) { - EntityPlayer player = (EntityPlayer)entity; - if(BackpackProperty.get(player) == null) BackpackProperty.register(player); + EntityPlayer player = (EntityPlayer) entity; + + if (BackpackProperty.get(player) == null) + BackpackProperty.register(player); + BackpackProperty.get(player).loadNBTData(properties); } } - public void initRenderers() + private void initRenderers() { - renderHandler = new RenderHandler(); - MinecraftForge.EVENT_BUS.register(renderHandler); - rendererWearableEquipped = new RendererWearableEquipped(); + MinecraftForge.EVENT_BUS.register(new RenderHandler()); - rendererItemAdventureBackpack = new RendererItemAdventureBackpack(); - MinecraftForgeClient.registerItemRenderer(ModItems.adventureBackpack, rendererItemAdventureBackpack); - MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(ModBlocks.blockBackpack), rendererItemAdventureBackpack); + MinecraftForgeClient.registerItemRenderer(ModItems.adventureBackpack, new RendererItemAdventureBackpack()); + MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(ModBlocks.blockBackpack), new RendererItemAdventureBackpack()); ClientRegistry.bindTileEntitySpecialRenderer(TileAdventureBackpack.class, new RendererAdventureBackpackBlock()); - rendererItemAdventureHat = new RendererItemAdventureHat(); - MinecraftForgeClient.registerItemRenderer(ModItems.adventureHat, rendererItemAdventureHat); + MinecraftForgeClient.registerItemRenderer(ModItems.adventureHat, new RendererItemAdventureHat()); - if(!ConfigHandler.TANKS_OVERLAY) + if (!ConfigHandler.tanksOverlay) { - rendererHose = new RendererHose(); - MinecraftForgeClient.registerItemRenderer(ModItems.hose, rendererHose); + MinecraftForgeClient.registerItemRenderer(ModItems.hose, new RendererHose()); } ClientRegistry.bindTileEntitySpecialRenderer(TileCampfire.class, new RendererCampFire()); - renderInflatableBoat = new RendererInflatableBoat(); - RenderingRegistry.registerEntityRenderingHandler(EntityInflatableBoat.class, renderInflatableBoat); - renderRideableSpider = new RenderRideableSpider(); - RenderingRegistry.registerEntityRenderingHandler(EntityFriendlySpider.class, renderRideableSpider); + RenderingRegistry.registerEntityRenderingHandler(EntityInflatableBoat.class, new RendererInflatableBoat()); + RenderingRegistry.registerEntityRenderingHandler(EntityFriendlySpider.class, new RenderRideableSpider()); - renderCrossbow = new RendererItemClockworkCrossbow(); - MinecraftForgeClient.registerItemRenderer(ModItems.cwxbow, renderCrossbow); + MinecraftForgeClient.registerItemRenderer(ModItems.cwxbow, new RendererItemClockworkCrossbow()); } + @Override public void registerKeybindings() { - ClientRegistry.registerKeyBinding(Keybindings.openBackpack); - ClientRegistry.registerKeyBinding(Keybindings.toggleHose); - FMLCommonHandler.instance().bus().register(new KeybindHandler()); + ClientRegistry.registerKeyBinding(Keybindings.openInventory); + ClientRegistry.registerKeyBinding(Keybindings.toggleActions); + FMLCommonHandler.instance().bus().register(new KeyInputEventHandler()); } - } diff --git a/src/main/java/com/darkona/adventurebackpack/proxy/IProxy.java b/src/main/java/com/darkona/adventurebackpack/proxy/IProxy.java index ecff3d0b..a5ecbaf2 100644 --- a/src/main/java/com/darkona/adventurebackpack/proxy/IProxy.java +++ b/src/main/java/com/darkona/adventurebackpack/proxy/IProxy.java @@ -1,6 +1,5 @@ package com.darkona.adventurebackpack.proxy; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; /** @@ -10,15 +9,9 @@ */ public interface IProxy { + void init(); - public void init(); - - public void registerKeybindings(); - - void initNetwork(); - - public void joinPlayer(EntityPlayer player); - - public void synchronizePlayer(int id, NBTTagCompound compound); + void registerKeybindings(); + void synchronizePlayer(int id, NBTTagCompound compound); } diff --git a/src/main/java/com/darkona/adventurebackpack/proxy/ServerProxy.java b/src/main/java/com/darkona/adventurebackpack/proxy/ServerProxy.java index 388118df..00d20cef 100644 --- a/src/main/java/com/darkona/adventurebackpack/proxy/ServerProxy.java +++ b/src/main/java/com/darkona/adventurebackpack/proxy/ServerProxy.java @@ -1,85 +1,64 @@ -package com.darkona.adventurebackpack.proxy; - -import com.darkona.adventurebackpack.playerProperties.BackpackProperty; -import com.darkona.adventurebackpack.util.LogHelper; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -/** - * Created on 22/12/2014 - * - * @author Darkona - */ -public class ServerProxy implements IProxy -{ - private static final Map extendedEntityData = new HashMap(); - - @Override - public void init() - { - - } - - @Override - public void registerKeybindings() - { - - } - - @Override - public void initNetwork() - { - - } - - @Override - public void joinPlayer(EntityPlayer player) - { - NBTTagCompound playerData = extractPlayerProps(player.getUniqueID()); - - if (playerData != null) - { - LogHelper.info("Stored properties retrieved"); - BackpackProperty.get(player).loadNBTData(playerData); - BackpackProperty.syncToNear(player); - }else{ - LogHelper.info("Data is null! WTF!"); - } - } - - @Override - public void synchronizePlayer(int id, NBTTagCompound compound) - { - - } - - public static void storePlayerProps(EntityPlayer player) - { - try - { - NBTTagCompound data = BackpackProperty.get(player).getData(); - if(data.hasKey("wearable")) - { - LogHelper.info("Storing wearable: " + ItemStack.loadItemStackFromNBT(data.getCompoundTag("wearable")).getDisplayName()); - } - extendedEntityData.put(player.getUniqueID(), data); - LogHelper.info("Stored player properties for dead player"); - } - catch(Exception ex) - { - LogHelper.error("Something went wrong while saving player properties: " + ex.getMessage()); - ex.printStackTrace(); - } - } - - - public static NBTTagCompound extractPlayerProps(UUID playerID) - { - return extendedEntityData.remove(playerID); - } -} +package com.darkona.adventurebackpack.proxy; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +import com.darkona.adventurebackpack.playerProperties.BackpackProperty; +import com.darkona.adventurebackpack.util.LogHelper; + +/** + * Created on 22/12/2014 + * + * @author Darkona + */ +public class ServerProxy implements IProxy +{ + private static final Map extendedEntityData = new HashMap<>(); + + @Override + public void init() + { + + } + + @Override + public void registerKeybindings() + { + + } + + @Override + public void synchronizePlayer(int id, NBTTagCompound compound) + { + + } + + public static void storePlayerProps(EntityPlayer player) + { + try + { + NBTTagCompound data = BackpackProperty.get(player).getData(); + if (data.hasKey("wearable")) + { + LogHelper.info("Storing wearable: " + ItemStack.loadItemStackFromNBT(data.getCompoundTag("wearable")).getDisplayName()); + } + extendedEntityData.put(player.getUniqueID(), data); + LogHelper.info("Stored player properties for dead player"); + } + catch (Exception ex) + { + LogHelper.error("Something went wrong while saving player properties: " + ex.getMessage()); + ex.printStackTrace(); + } + } + + public static NBTTagCompound extractPlayerProps(UUID playerID) + { + return extendedEntityData.remove(playerID); + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/reference/BackpackNames.java b/src/main/java/com/darkona/adventurebackpack/reference/BackpackNames.java deleted file mode 100644 index 04fbd2fa..00000000 --- a/src/main/java/com/darkona/adventurebackpack/reference/BackpackNames.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.darkona.adventurebackpack.reference; - -import com.darkona.adventurebackpack.block.TileAdventureBackpack; -import com.darkona.adventurebackpack.item.ItemAdventureBackpack; -import com.darkona.adventurebackpack.util.BackpackUtils; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -/** - * Created on 15/10/2014 - * - * @author Darkona - */ -public class BackpackNames -{ - - public static String[] backpackNames = { - "Standard", - "Cow", - "Bat", - "Black", - "Blaze", - "Carrot", - "Coal", - "Diamond", - "Emerald", - "Gold", - "Iron", - "IronGolem", - "Lapis", - "Redstone", - "Blue", - "Bookshelf", - "Brown", - "Cactus", - "Cake", - "Chest", - "Cookie", - "Cyan", - "Dragon", - "Egg", - "Electric", - "Deluxe", - "Enderman", - "End", - "Chicken", - "Ocelot", - "Ghast", - "Gray", - "Green", - "Haybale", - "Horse", - "Leather", - "LightBlue", - "Glowstone", - "LightGray", - "Lime", - "Magenta", - "MagmaCube", - "Melon", - "BrownMushroom", - "RedMushroom", - "Mooshroom", - "Nether", - "Wither", - "Obsidian", - "Orange", - "Overworld", - "Pigman", - "Pink", - "Pig", - "Pumpkin", - "Purple", - "Quartz", - "Rainbow", - "Red", - "Sandstone", - "Sheep", - "Silverfish", - "Squid", - "Sunflower", - "Creeper", - "Skeleton", - "WitherSkeleton", - "Slime", - "Snow", - "Spider", - "Sponge", - "Villager", - "White", - "Wolf", - "Yellow", - "Zombie" - }; - - public static ItemStack setBackpackColorNameFromDamage(ItemStack backpack, int damage) - { - - if (backpack == null) return null; - if (!(backpack.getItem() instanceof ItemAdventureBackpack)) return null; - NBTTagCompound backpackData = BackpackUtils.getBackpackData(backpack) != null ? BackpackUtils.getBackpackData(backpack) : new NBTTagCompound() ; - backpack.setItemDamage(damage); - assert backpackData != null; - backpackData.setString("colorName", backpackNames[damage]); - BackpackUtils.setBackpackData(backpack,backpackData); - return backpack; - } - - public static int getBackpackDamageFromName(String name) - { - for (int i = 0; i < backpackNames.length; i++) - { - if (backpackNames[i].equals(name)) return i; - } - return 0; - } - - public static String getBackpackColorName(TileAdventureBackpack te) - { - return te.getColorName(); - } - - public static String getBackpackColorName(ItemStack backpack) - { - if (backpack == null) return ""; - NBTTagCompound backpackData = BackpackUtils.getBackpackData(backpack) != null ? BackpackUtils.getBackpackData(backpack) : new NBTTagCompound() ; - assert backpackData != null; - if (backpackData.getString("colorName").isEmpty()) - { - backpackData.setString("colorName", "Standard"); - } - return backpackData.getString("colorName"); - } - - public static void setBackpackColorName(ItemStack backpack, String newName) - { - if (backpack != null) - { - NBTTagCompound backpackData = BackpackUtils.getBackpackData(backpack) != null ? BackpackUtils.getBackpackData(backpack) : new NBTTagCompound() ; - assert backpackData != null; - backpackData.setString("colorName", newName); - BackpackUtils.setBackpackData(backpack, backpackData); - } - } -} diff --git a/src/main/java/com/darkona/adventurebackpack/reference/BackpackTypes.java b/src/main/java/com/darkona/adventurebackpack/reference/BackpackTypes.java new file mode 100644 index 00000000..7e7bab26 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/reference/BackpackTypes.java @@ -0,0 +1,261 @@ +package com.darkona.adventurebackpack.reference; + +import java.util.Arrays; + +import com.google.common.collect.BiMap; +import com.google.common.collect.EnumHashBiMap; +import com.google.common.collect.ImmutableBiMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.Validate; +import org.apache.commons.lang3.text.WordUtils; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; + +import com.darkona.adventurebackpack.util.BackpackUtils; + +import static com.darkona.adventurebackpack.common.Constants.TAG_TYPE; +import static com.darkona.adventurebackpack.reference.BackpackTypes.Props.NIGHT_VISION; +import static com.darkona.adventurebackpack.reference.BackpackTypes.Props.REMOVAL; +import static com.darkona.adventurebackpack.reference.BackpackTypes.Props.SPECIAL; +import static com.darkona.adventurebackpack.reference.BackpackTypes.Props.TILE; + +/** + * Created on 15.08.2017 + * + * @author Ugachaga + */ +@SuppressWarnings("unused") +public enum BackpackTypes +{ + // @formatter:off + STANDARD ( 0), + + BAT ( 2, SPECIAL, REMOVAL, NIGHT_VISION), + BLACK ( 3), + BLAZE ( 4), + BLUE ( 14), + BOOKSHELF ( 15), + BROWN ( 16), + BROWN_MUSHROOM ( 43), + CACTUS ( 17, SPECIAL, TILE), + CAKE ( 18), + CARROT ( 5), + CHEST ( 19), + CHICKEN ( 28, SPECIAL), + COAL ( 6), + COOKIE ( 20), + COW ( 1, SPECIAL), + CREEPER ( 64, SPECIAL), + CYAN ( 21), + DELUXE ( 25), + DIAMOND ( 7), + DRAGON ( 22, SPECIAL, REMOVAL, NIGHT_VISION), + EGG ( 23), + ELECTRIC ( 24), + EMERALD ( 8), + END ( 27), + ENDERMAN ( 26), + GHAST ( 30), + GLOWSTONE ( 37), + GOLD ( 9), + GRAY ( 31), + GREEN ( 32), + HAYBALE ( 33), + HORSE ( 34), + IRON ( 10), + IRON_GOLEM ( 11), //TODO has other ability, need some prop + LAPIS ( 12), + LEATHER ( 35), + LIGHT_BLUE ( 36), + LIGHT_GRAY ( 38), + LIME ( 39), + MAGENTA ( 40), + MAGMA_CUBE ( 41), + MELON ( 42, SPECIAL, TILE), + MODDED_NETWORK ( 76), + MOOSHROOM ( 45, SPECIAL), + NETHER ( 46), + OBSIDIAN ( 48), + OCELOT ( 29, SPECIAL), + ORANGE ( 49), + OVERWORLD ( 50), + PIG ( 53, SPECIAL), + PIGMAN ( 51, SPECIAL, REMOVAL), + PINK ( 52), + PUMPKIN ( 54), + PURPLE ( 55), + QUARTZ ( 56), + RAINBOW ( 57, SPECIAL, REMOVAL), + RED ( 58), + RED_MUSHROOM ( 44), + REDSTONE ( 13), + SANDSTONE ( 59), + SHEEP ( 60), + SILVERFISH ( 61), + SKELETON ( 65), + SLIME ( 67, SPECIAL), + SNOW ( 68), + SPIDER ( 69), + SPONGE ( 70), + SQUID ( 62, SPECIAL, REMOVAL, NIGHT_VISION), + SUNFLOWER ( 63, SPECIAL), + VILLAGER ( 71), + WHITE ( 72), + WITHER ( 47), + WITHER_SKELETON ( 66), + WOLF ( 73, SPECIAL), + YELLOW ( 74), + ZOMBIE ( 75), + + UNKNOWN (127, "UNKNOWN"), // null object + ; + // @formatter:on + + public static final ImmutableBiMap BY_META; + + private final byte meta; + private final String skinName; + private final ImmutableSet props; + + BackpackTypes(int meta, String skin, Props... props) + { + Validate.inclusiveBetween(0, (int) Byte.MAX_VALUE, meta, "wrong meta value: %s (%s)", meta, this); + + this.meta = (byte) meta; + this.skinName = skin.isEmpty() ? generateSkinName() : skin; + this.props = Sets.immutableEnumSet(Arrays.asList(props)); + } + + BackpackTypes(int meta, Props... props) + { + this(meta, StringUtils.EMPTY, props); + } + + private String generateSkinName() + { + return WordUtils + .capitalize(this.name().toLowerCase(), '_') + .replaceAll("_", ""); + } + + static + { + BiMap byMeta = EnumHashBiMap.create(BackpackTypes.class); + + for (BackpackTypes type : BackpackTypes.values()) + if (byMeta.put(type, type.meta) != null) + throw new IllegalArgumentException("duplicate meta: " + type.meta); + + BY_META = ImmutableBiMap.copyOf(byMeta.inverse()); + } + + public static String getSkinName(BackpackTypes type) + { + return type.skinName; + } + + public static String getSkinName(int meta) + { + return getType(meta).skinName; + } + + public static String getSkinName(ItemStack backpack) + { + return getSkinName(getType(backpack)); + } + + public static String getLocalizedName(BackpackTypes type) + { + return StatCollector.translateToLocal("adventurebackpack:skin.name." + type.name().toLowerCase()); + } + + public static byte getMeta(BackpackTypes type) + { + return type.meta; + } + + public static BackpackTypes getType(int meta) + { + Validate.inclusiveBetween(0, (int) Byte.MAX_VALUE, meta, "wrong meta value: %s", meta); + BackpackTypes type = BY_META.get((byte) meta); + return type != null ? type : UNKNOWN; + } + + public static BackpackTypes getType(byte meta) + { + Validate.inclusiveBetween((byte) 0, Byte.MAX_VALUE, meta, "wrong meta value: %s", meta); + BackpackTypes type = BY_META.get(meta); + return type != null ? type : UNKNOWN; + } + + public static BackpackTypes getType(String skinName) + { + for (BackpackTypes type : BackpackTypes.values()) + { + if (type.skinName.equals(skinName)) + return type; + } + return UNKNOWN; + } + + public static BackpackTypes getType(ItemStack backpack) + { + if (backpack == null) // well... Wearing.getWearingBackpack() may return null... //TODO solve this damn null + return null; + + NBTTagCompound backpackTag = BackpackUtils.getWearableCompound(backpack); + if (backpackTag.getByte(TAG_TYPE) == UNKNOWN.meta) //TODO remove? are we rly need to normalize it? + { + backpackTag.setByte(TAG_TYPE, STANDARD.meta); + } + return getType(backpackTag.getByte(TAG_TYPE)); + } + + public static int getLowestUnusedMeta() + { + for (byte b = 0; b < Byte.MAX_VALUE; b++) + { + if (BY_META.get(b) == null) + return b; + } + return -1; + } + + public static boolean isNightVision(BackpackTypes type) + { + return hasProperty(type, NIGHT_VISION); + } + + public static boolean isSpecial(BackpackTypes type) + { + return hasProperty(type, SPECIAL); + } + + public static boolean hasProperty(BackpackTypes type, Props prop) + { + return type.props.contains(prop); + } + + public static boolean hasProperties(BackpackTypes type, ImmutableSet props) + { + return type.props.containsAll(props); + } + + public enum Props + { + SPECIAL, + REMOVAL, + TILE, + NIGHT_VISION, + //HOLIDAY, + //OTHER_ABILITY, // creeper or skeleton etc + ; + + public static final ImmutableSet POTION_EFFECT = Sets.immutableEnumSet(SPECIAL, REMOVAL); + } + +} diff --git a/src/main/java/com/darkona/adventurebackpack/reference/GeneralReference.java b/src/main/java/com/darkona/adventurebackpack/reference/GeneralReference.java index e5aafbd2..5daeb751 100644 --- a/src/main/java/com/darkona/adventurebackpack/reference/GeneralReference.java +++ b/src/main/java/com/darkona/adventurebackpack/reference/GeneralReference.java @@ -1,8 +1,17 @@ package com.darkona.adventurebackpack.reference; -import net.minecraftforge.fluids.Fluid; - +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.fluids.FluidRegistry; + +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.util.LogHelper; /** * Created on 16/01/2015 @@ -11,32 +20,117 @@ */ public class GeneralReference { - public static HashMap liquidFuels = new HashMap(); + private static HashMap liquidFuels = new HashMap<>(); + private static Set dimensionBlacklist = new HashSet<>(); + private static final float MAX_RATE = 20.0f; + private static final float MIN_RATE = 0.05f; public static void init() { - liquidFuels.put("fuel", 1.0f); - liquidFuels.put("oil", 1.5f); - liquidFuels.put("bioethanol", 1.2f); - liquidFuels.put("biofuel", 1.0f); - liquidFuels.put("creosote", 1.8f); - liquidFuels.put("coal", 0.8f); + parseLiquidFuelsConfig(); + parseDimensionBlacklistConfig(); + + if (LoadedMods.DEV_ENV) + liquidFuels.put("holywater", 0.0f); // shhh.. you did not see anything. hallelujah! + } + + private static void parseDimensionBlacklistConfig() + { + for (String dim : ConfigHandler.forbiddenDimensions) + { + int dimID; + try + { + dimID = Integer.parseInt(dim); + } + catch (NumberFormatException nfe) + { + LogHelper.error("Cannot parse Forbidden Dimension ID for " + dim + ". Ignored"); + continue; + } + if (DimensionManager.isDimensionRegistered(dimID)) + { + dimensionBlacklist.add(dimID); + LogHelper.info("Dimension " + dimID + " is registered as Forbidden for Adventure Backpack"); + } + else + { + LogHelper.info("Not found dimension " + dimID + ". Skipped"); + } + } } - public static boolean isValidFuel(Fluid fluid) + private static void parseLiquidFuelsConfig() { - if(fluid != null) + int wrongCount = 0; + int unregCount = 0; + + for (String fuel : ConfigHandler.copterFuels) { - for(String fuel : liquidFuels.keySet()) + String[] arrFuel = fuel + .replaceAll(" ", "") + .split(","); + + if (arrFuel.length != 2) { - if(fuel.equals(fluid.getName())) + wrongCount++; + continue; + } + + String fluid = arrFuel[0]; + float rate; + + if (FluidRegistry.isFluidRegistered(fluid)) + { + try + { + rate = Float.parseFloat(arrFuel[1]); + } + catch (NumberFormatException nfe) { - return true; + rate = MAX_RATE; + LogHelper.error("Cannot parse consumption rate for " + fluid + ". Setting MAX rate"); } + rate = rate < MIN_RATE ? MIN_RATE : (rate > MAX_RATE ? MAX_RATE : rate); + liquidFuels.put(fluid, rate); + LogHelper.info("Registered " + fluid + " as Copter fuel with consumption rate " + rate); + } + else + { + unregCount++; } } - return false; + + if (wrongCount > 0 || unregCount > 0) + { + LogHelper.info("Skipped " + + (wrongCount > 0 ? (wrongCount + " incorrect entr" + (wrongCount > 1 ? "ies" : "y")) : "") + + (wrongCount > 0 && unregCount > 0 ? " and " : "") + + (unregCount > 0 ? (unregCount + " unregistered fluid" + (unregCount > 1 ? "s" : "")) : "")); + } + } + + public static boolean isDimensionAllowed(@Nonnull EntityPlayer player) + { + return isDimensionAllowed(player.worldObj.provider.dimensionId); } + + public static boolean isDimensionAllowed(int dimID) + { + return !dimensionBlacklist.contains(dimID); + } + + public static boolean isValidFuel(String fluidName) + { + return liquidFuels.containsKey(fluidName); + } + + @Nullable + public static Float getFuelRate(String fluidName) + { + return liquidFuels.get(fluidName); + } + } diff --git a/src/main/java/com/darkona/adventurebackpack/reference/Key.java b/src/main/java/com/darkona/adventurebackpack/reference/Key.java deleted file mode 100644 index 2491ab63..00000000 --- a/src/main/java/com/darkona/adventurebackpack/reference/Key.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.darkona.adventurebackpack.reference; - -/** - * Created on 14/10/2014 - * - * @author Darkona - */ -public enum Key -{ - - UNKNOWN, INVENTORY_KEY, TOGGLE_KEY, JUMP -} diff --git a/src/main/java/com/darkona/adventurebackpack/reference/LoadedMods.java b/src/main/java/com/darkona/adventurebackpack/reference/LoadedMods.java new file mode 100644 index 00000000..04b1153f --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/reference/LoadedMods.java @@ -0,0 +1,50 @@ +package com.darkona.adventurebackpack.reference; + +import net.minecraft.launchwrapper.Launch; +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.ModContainer; + +import com.darkona.adventurebackpack.util.LogHelper; + +/** + * Created on 24.02.2018 + * + * @author Ugachaga + */ +public final class LoadedMods +{ + public static final boolean DEV_ENV = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment"); + + public static final boolean BUILDCRAFT = registerMod("BuildCraft|Core"); + public static final boolean ENDERIO = registerMod("EnderIO"); + public static final boolean GREGTECH = registerMod("gregtech"); + public static final boolean NEI = registerMod("NotEnoughItems"); + public static final boolean TCONSTRUCT = registerMod("TConstruct"); + public static final boolean THAUMCRAFT = registerMod("Thaumcraft"); + public static final boolean WAILA = registerMod("waila"); + + private LoadedMods() {} + + public static void init() + { + if (DEV_ENV) + { + LogHelper.info("Dev environment detected. All hail the creator"); + } + } + + private static boolean registerMod(String modID) + { + if (!Loader.isModLoaded(modID)) + return false; + + String modName = modID; + for (ModContainer mod : Loader.instance().getModList()) + { + if (mod.getModId().equals(modID)) + modName = mod.getName(); + } + LogHelper.info(modName + " is present. Acting accordingly"); + return true; + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java b/src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java index 0ed9e354..5970249d 100644 --- a/src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java +++ b/src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java @@ -5,11 +5,11 @@ */ public class ModInfo { + public static final String MOD_ID = "adventurebackpack"; // must be lowercase public static final String MOD_NAME = "Adventure Backpack"; - public static final String MOD_VERSION = "1.7.10-0.8d"; - public static final String MOD_ID = "adventurebackpack"; - public static final String MOD_CHANNEL = "advBackpackChan"; + public static final String MOD_VERSION = "@VERSION@"; + public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory"; public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy"; public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy"; - public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory"; + public static final String MOD_CHANNEL = "advBackpackChan"; } diff --git a/src/main/java/com/darkona/adventurebackpack/reference/Names.java b/src/main/java/com/darkona/adventurebackpack/reference/Names.java deleted file mode 100644 index 6e561147..00000000 --- a/src/main/java/com/darkona/adventurebackpack/reference/Names.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.darkona.adventurebackpack.reference; - -/** - * Created on 14/10/2014 - * - * @author Darkona - */ -public final class Names -{ - - public static final class keys - { - - public static final String CATEGORY = "keys.adventureBackpack.category"; - public static String OPEN_BACKPACK_INVENTORY = "keys.adventureBackpack.openBackpackInventory"; - public static String TOGGLE_HOSE_TANK = "keys.adventureBackpack.switchHoseTank"; - } - -} diff --git a/src/main/java/com/darkona/adventurebackpack/reference/ToolHandler.java b/src/main/java/com/darkona/adventurebackpack/reference/ToolHandler.java new file mode 100644 index 00000000..dc1e635b --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/reference/ToolHandler.java @@ -0,0 +1,35 @@ +package com.darkona.adventurebackpack.reference; + +import net.minecraft.item.ItemStack; + +import com.darkona.adventurebackpack.util.GregtechUtils; +import com.darkona.adventurebackpack.util.ThaumcraftUtils; +import com.darkona.adventurebackpack.util.TinkersUtils; + +/** + * Created on 06.02.2018 + * + * @author Ugachaga + */ +public enum ToolHandler +{ + VANILLA, + GREGTECH, + TCONSTRUCT, + THAUMCRAFT, + ; + + public static ToolHandler getToolHandler(ItemStack stack) + { + if (stack == null) + return VANILLA; + + if (GregtechUtils.isTool(stack)) + return GREGTECH; + if (TinkersUtils.isTool(stack)) + return TCONSTRUCT; + if (ThaumcraftUtils.isTool(stack)) + return THAUMCRAFT; + return VANILLA; + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/reference/WailaTileAdventureBackpack.java b/src/main/java/com/darkona/adventurebackpack/reference/WailaTileAdventureBackpack.java new file mode 100644 index 00000000..3147bf57 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/reference/WailaTileAdventureBackpack.java @@ -0,0 +1,142 @@ +package com.darkona.adventurebackpack.reference; + +import javax.annotation.Nullable; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.world.World; +import net.minecraftforge.common.util.Constants.NBT; +import net.minecraftforge.fluids.FluidTank; +import cpw.mods.fml.common.event.FMLInterModComms; + +import com.darkona.adventurebackpack.block.TileAdventureBackpack; +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.util.TipUtils; +import com.darkona.adventurebackpack.util.BackpackUtils; +import com.darkona.adventurebackpack.util.Utils; + +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaDataProvider; +import mcp.mobius.waila.api.IWailaRegistrar; + +import static com.darkona.adventurebackpack.common.Constants.TAG_INVENTORY; +import static com.darkona.adventurebackpack.common.Constants.TAG_LEFT_TANK; +import static com.darkona.adventurebackpack.common.Constants.TAG_RIGHT_TANK; +import static com.darkona.adventurebackpack.common.Constants.TAG_TYPE; +import static com.darkona.adventurebackpack.common.Constants.TAG_WEARABLE_COMPOUND; + +/** + * Created on 03.02.2018 + * + * @author Ugachaga + */ +public class WailaTileAdventureBackpack implements IWailaDataProvider +{ + public static void init() + { + FMLInterModComms.sendMessage("Waila", "register", "com.darkona.adventurebackpack.reference.WailaTileAdventureBackpack.callbackRegister"); + } + + @SuppressWarnings("unused") + public static void callbackRegister(IWailaRegistrar registrar) + { + registrar.registerStackProvider(new WailaTileAdventureBackpack(), TileAdventureBackpack.class); + registrar.registerHeadProvider(new WailaTileAdventureBackpack(), TileAdventureBackpack.class); + registrar.registerBodyProvider(new WailaTileAdventureBackpack(), TileAdventureBackpack.class); + } + + @Override + public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) + { + return addTypeToStack(accessor); + } + + private ItemStack addTypeToStack(IWailaDataAccessor accessor) + { + if (accessor.getNBTData().hasKey(TAG_WEARABLE_COMPOUND)) + { + NBTTagCompound backpackTag = accessor.getNBTData().getCompoundTag(TAG_WEARABLE_COMPOUND); + BackpackTypes type = BackpackTypes.getType(backpackTag.getByte(TAG_TYPE)); + return BackpackUtils.createBackpackStack(type); + } + return BackpackUtils.createBackpackStack(BackpackTypes.STANDARD); + } + + @Override + public List getWailaHead(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) + { + addHeadToBackpack(currenttip, accessor); + return currenttip; + } + + private static void addHeadToBackpack(List currenttip, IWailaDataAccessor accessor) + { + if (accessor.getNBTData().hasKey(TAG_WEARABLE_COMPOUND)) + { + NBTTagCompound backpackTag = accessor.getNBTData().getCompoundTag(TAG_WEARABLE_COMPOUND); + addHeadToBackpack(currenttip, backpackTag); + } + } + + private static void addHeadToBackpack(List currenttip, NBTTagCompound backpackTag) + { + currenttip.remove(0); + BackpackTypes type = BackpackTypes.getType(backpackTag.getByte(TAG_TYPE)); + String skin = ""; + if (type != BackpackTypes.STANDARD) + skin = EnumChatFormatting.GRAY + " \"" + Utils.getColoredSkinName(type) + EnumChatFormatting.GRAY + "\""; + currenttip.add(EnumChatFormatting.WHITE + "Adventure Backpack" + skin); + } + + @Override + public List getWailaBody(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) + { + addTipToBackpack(currenttip, accessor); + return currenttip; + } + + private static void addTipToBackpack(List currenttip, IWailaDataAccessor accessor) + { + if (accessor.getNBTData().hasKey(TAG_WEARABLE_COMPOUND)) + { + NBTTagCompound backpackTag = accessor.getNBTData().getCompoundTag(TAG_WEARABLE_COMPOUND); + addTipToBackpack(currenttip, backpackTag); + } + } + + private static void addTipToBackpack(List currenttip, NBTTagCompound backpackTag) + { + NBTTagList itemList = backpackTag.getTagList(TAG_INVENTORY, NBT.TAG_COMPOUND); + currenttip.add(TipUtils.l10n("backpack.slots.used") + ": " + TipUtils.inventoryTooltip(itemList)); + + FluidTank tank = new FluidTank(Constants.BASIC_TANK_CAPACITY); + + tank.readFromNBT(backpackTag.getCompoundTag(TAG_LEFT_TANK)); + currenttip.add(EnumChatFormatting.RESET + TipUtils.l10n("backpack.tank.left") + + ": " + TipUtils.tankTooltip(tank)); + + tank.readFromNBT(backpackTag.getCompoundTag(TAG_RIGHT_TANK)); + currenttip.add(EnumChatFormatting.RESET + TipUtils.l10n("backpack.tank.right") + + ": " + TipUtils.tankTooltip(tank)); + } + + @Nullable + @Override + public List getWailaTail(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) + { + return null; + } + + @Nullable + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z) + { + return null; + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/util/BackpackUtils.java b/src/main/java/com/darkona/adventurebackpack/util/BackpackUtils.java index 4ac04ab7..b8d48d41 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/BackpackUtils.java +++ b/src/main/java/com/darkona/adventurebackpack/util/BackpackUtils.java @@ -1,12 +1,24 @@ package com.darkona.adventurebackpack.util; -import com.darkona.adventurebackpack.events.WearableEvent; -import com.darkona.adventurebackpack.playerProperties.BackpackProperty; +import java.util.Timer; +import java.util.TimerTask; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import net.minecraft.util.ChatComponentTranslation; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.Constants; + +import com.darkona.adventurebackpack.events.WearableEvent; +import com.darkona.adventurebackpack.init.ModItems; +import com.darkona.adventurebackpack.playerProperties.BackpackProperty; +import com.darkona.adventurebackpack.reference.BackpackTypes; + +import static com.darkona.adventurebackpack.common.Constants.TAG_INVENTORY; +import static com.darkona.adventurebackpack.common.Constants.TAG_TYPE; +import static com.darkona.adventurebackpack.common.Constants.TAG_WEARABLE_COMPOUND; /** * Created on 08/01/2015 @@ -15,14 +27,17 @@ */ public class BackpackUtils { + private static Timer timer = new Timer(); //TODO remove timer, find the dupe, fix the dupe - public enum reasons{ - SUCCESFUL,ALREADY_EQUIPPED + public enum Reasons + { + SUCCESSFUL, ALREADY_EQUIPPED } - public static reasons equipWearable(ItemStack backpack, EntityPlayer player) + + public static Reasons equipWearable(ItemStack backpack, EntityPlayer player) { BackpackProperty prop = BackpackProperty.get(player); - if(prop.getWearable() == null) + if (prop.getWearable() == null) { player.openContainer.onContainerClosed(player); prop.setWearable(backpack.copy()); @@ -31,48 +46,109 @@ public static reasons equipWearable(ItemStack backpack, EntityPlayer player) WearableEvent event = new WearableEvent.EquipWearableEvent(player, prop.getWearable()); MinecraftForge.EVENT_BUS.post(event); BackpackProperty.sync(player); - return reasons.SUCCESFUL; - }else + return Reasons.SUCCESSFUL; + } + else { - return reasons.ALREADY_EQUIPPED; + return Reasons.ALREADY_EQUIPPED; } } public static void unequipWearable(EntityPlayer player) { - BackpackProperty prop = BackpackProperty.get(player); - if(prop.getWearable() != null) + TimerTask unequipTask = new DelayUnequipTask(player); + timer.schedule(unequipTask, 200); + } + + private static class DelayUnequipTask extends TimerTask + { + private EntityPlayer player; + + DelayUnequipTask(EntityPlayer player) { - player.openContainer.onContainerClosed(player); - ItemStack gimme = prop.getWearable().copy(); - BackpackProperty.get(player).executeWearableUnequipProtocol(); - prop.setWearable(null); - if(!player.inventory.addItemStackToInventory(gimme)) + this.player = player; + } + + @Override + public void run() + { + BackpackProperty prop = BackpackProperty.get(player); + if (prop.getWearable() != null) { - player.dropPlayerItemWithRandomChoice(gimme,false); + player.openContainer.onContainerClosed(player); + ItemStack gimme = prop.getWearable().copy(); + BackpackProperty.get(player).executeWearableUnequipProtocol(); + prop.setWearable(null); + if (!player.inventory.addItemStackToInventory(gimme)) + { + player.dropPlayerItemWithRandomChoice(gimme, false); + } + WearableEvent event = new WearableEvent.UnequipWearableEvent(player, gimme); + MinecraftForge.EVENT_BUS.post(event); + BackpackProperty.sync(player); + } + else + { + player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.already.impossibru")); } - WearableEvent event = new WearableEvent.UnequipWearableEvent(player, gimme); - MinecraftForge.EVENT_BUS.post(event); - BackpackProperty.sync(player); - }else - { - player.addChatComponentMessage(new ChatComponentTranslation("adventurebackpack:messages.already.impossibru")); } } - public static NBTTagCompound getBackpackData(ItemStack backpack) + public static NBTTagCompound getWearableCompound(ItemStack stack) { - if(backpack.hasTagCompound() && backpack.stackTagCompound.hasKey("backpackData")) - { - return backpack.stackTagCompound.getCompoundTag("backpackData"); - } - return null; + // it also creates wearable compound if stack has no own, so maybe worth to rename the method + if (!stack.hasTagCompound() || !stack.stackTagCompound.hasKey(TAG_WEARABLE_COMPOUND)) + createWearableCompound(stack); + + return stack.stackTagCompound.getCompoundTag(TAG_WEARABLE_COMPOUND); + } + + private static void createWearableCompound(ItemStack stack) + { + if (!stack.hasTagCompound()) + stack.stackTagCompound = new NBTTagCompound(); + + stack.stackTagCompound.setTag(TAG_WEARABLE_COMPOUND, new NBTTagCompound()); + } + + public static NBTTagList getWearableInventory(ItemStack stack) + { + // it also creates TagList if stack has no own, so maybe worth to rename the method + if (!getWearableCompound(stack).hasKey(TAG_INVENTORY)) + createWearableInventory(stack); + + return getWearableCompound(stack).getTagList(TAG_INVENTORY, Constants.NBT.TAG_COMPOUND); + } + + private static void createWearableInventory(ItemStack stack) + { + getWearableCompound(stack).setTag(TAG_INVENTORY, new NBTTagList()); + } + + public static ItemStack createBackpackStack(BackpackTypes type) + { + ItemStack backpackStack = new ItemStack(ModItems.adventureBackpack, 1, BackpackTypes.getMeta(type)); + setBackpackType(backpackStack, type); + return backpackStack; + } + + public static void setBackpackType(ItemStack stack, BackpackTypes type) + { + getWearableCompound(stack).setByte(TAG_TYPE, BackpackTypes.getMeta(type)); + } + + public static ItemStack createCopterStack() + { + ItemStack copterStack = new ItemStack(ModItems.copterPack, 1, 0); + createWearableCompound(copterStack); + return copterStack; } - public static void setBackpackData(ItemStack stack, NBTTagCompound compound) + public static ItemStack createJetpackStack() { - if(!stack.hasTagCompound())stack.stackTagCompound = new NBTTagCompound(); - stack.stackTagCompound.setTag("backpackData",compound); + ItemStack jetpackStack = new ItemStack(ModItems.coalJetpack, 1, 0); + createWearableCompound(jetpackStack); + return jetpackStack; } -} +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/util/ColorReplacer.java b/src/main/java/com/darkona/adventurebackpack/util/ColorReplacer.java index 8b44ab0b..d0f2cc9a 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/ColorReplacer.java +++ b/src/main/java/com/darkona/adventurebackpack/util/ColorReplacer.java @@ -11,7 +11,6 @@ public class ColorReplacer { - public static BufferedImage colorImage(int colour, BufferedImage image) { int width = image.getWidth(); diff --git a/src/main/java/com/darkona/adventurebackpack/util/CoordsUtils.java b/src/main/java/com/darkona/adventurebackpack/util/CoordsUtils.java new file mode 100644 index 00000000..4183149d --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/util/CoordsUtils.java @@ -0,0 +1,285 @@ +package com.darkona.adventurebackpack.util; + +import javax.annotation.Nullable; + +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.MathHelper; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.darkona.adventurebackpack.block.TileAdventureBackpack; +import com.darkona.adventurebackpack.init.ModBlocks; + +/** + * Created on 31.01.2018 + * + * @author Ugachaga + */ +public class CoordsUtils +{ + private CoordsUtils() {} + + public static ChunkCoordinates findBlock2D(World world, int cX, int cY, int cZ, Block block, int range) + { + for (int i = cX - range; i <= cX + range; i++) + { + for (int j = cZ - range; j <= cZ + range; j++) + { + if (world.getBlock(i, cY, j) == block) + { + return new ChunkCoordinates(i, cY, j); + } + } + } + return null; + } + + public static ChunkCoordinates findBlock3D(World world, int cX, int cY, int cZ, Block block, int hRange, int vRange) + { + for (int i = (cY - vRange); i <= (cY + vRange); i++) + { + for (int j = (cX - hRange); j <= (cX + hRange); j++) + { + for (int k = (cZ - hRange); k <= (cZ + hRange); k++) + { + if (world.getBlock(j, i, k) == block) + { + return new ChunkCoordinates(j, i, k); + } + } + } + } + return null; + } + + @Nullable + private static ChunkCoordinates checkCoordsForBackpack(IBlockAccess world, int cX, int cY, int cZ) + { + return isAirOrReplaceable(world, cX, cY, cZ) ? new ChunkCoordinates(cX, cY, cZ) : null; + } + + private static boolean isAirOrReplaceable(IBlockAccess world, int cX, int cY, int cZ) + { + return world.isAirBlock(cX, cY, cZ) || world.getBlock(cX, cY, cZ).isReplaceable(world, cX, cY, cZ); + } + + private static ChunkCoordinates checkCoordsForPlayer(IBlockAccess world, int origX, int origZ, int cX, int cY, int cZ, boolean except) + { + LogHelper.info("Checking coordinates in X=" + cX + ", Y=" + cY + ", Z=" + cZ); + if (except && world.isSideSolid(cX, cY - 1, cZ, ForgeDirection.UP, true) && world.isAirBlock(cX, cY, cZ) && world.isAirBlock(cX, cY + 1, cZ) && !areCoordinatesTheSame2D(origX, origZ, cX, cZ)) + { + LogHelper.info("Found spot with the exception of the origin point"); + return new ChunkCoordinates(cX, cY, cZ); + } + if (!except && world.isSideSolid(cX, cY - 1, cZ, ForgeDirection.UP, true) && world.isAirBlock(cX, cY, cZ) && world.isAirBlock(cX, cY + 1, cZ)) + { + LogHelper.info("Found spot without exceptions"); + return new ChunkCoordinates(cX, cY, cZ); + } + return null; + } + + /** + * Gets you the nearest Empty Chunk Coordinates, free of charge! Looks in two dimensions and finds a block + * that a: can have stuff placed on it and b: has space above it. + * This is a spiral search, will begin at close range and move out. + * + * @param world The world object. + * @param origX Original cX coordinate + * @param origZ Original cZ coordinate + * @param cX Moving cX coordinate, should be the same as origX when called. + * @param cY cY coordinate, does not move. + * @param cZ Moving cZ coordinate, should be the same as origZ when called. + * @param radius The radius of the search. If set to high numbers, will create a ton of lag + * @param except Wether to include the origin of the search as a valid block. + * @param steps Number of steps of the recursive recursiveness that recurses through the recursion. It is the first size of the spiral, should be one (1) always at the first call. + * @param pass Pass switch for the witchcraft I can't quite explain. Set to 0 always at the beggining. + * @param type True = for player, False = for backpack + * @return The coordinates of the block in the chunk of the world of the game of the server of the owner of the computer, where you can place something above it. + */ + public static ChunkCoordinates getNearestEmptyChunkCoordinatesSpiral(IBlockAccess world, int origX, int origZ, int cX, int cY, int cZ, int radius, boolean except, int steps, byte pass, boolean type) + { + //Spiral search, because I'm awesome :) + //This is so the backpack tries to get placed near the death point first + //And then goes looking farther away at each step + //Steps mod 2 == 0 => cX++, cZ-- + //Steps mod 2 == 1 => cX--, cZ++ + + if (steps >= radius) return null; + int i = cX, j = cZ; + if (steps % 2 == 0) + { + if (pass == 0) + { + for (; i <= cX + steps; i++) + { + ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, cX, cY, cZ, except) : checkCoordsForBackpack(world, cX, cY, cZ); + if (coords != null) + { + return coords; + } + } + pass++; + return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, cY, j, radius, except, steps, pass, type); + } + if (pass == 1) + { + for (; j >= cZ - steps; j--) + { + ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, cX, cY, cZ, except) : checkCoordsForBackpack(world, cX, cY, cZ); + if (coords != null) + { + return coords; + } + } + pass--; + steps++; + return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, cY, j, radius, except, steps, pass, type); + } + } + + if (steps % 2 == 1) + { + if (pass == 0) + { + for (; i >= cX - steps; i--) + { + ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, cX, cY, cZ, except) : checkCoordsForBackpack(world, cX, cY, cZ); + if (coords != null) + { + return coords; + } + } + pass++; + return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, cY, j, radius, except, steps, pass, type); + } + if (pass == 1) + { + for (; j <= cZ + steps; j++) + { + ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, cX, cY, cZ, except) : checkCoordsForBackpack(world, cX, cY, cZ); + if (coords != null) + { + return coords; + } + } + pass--; + steps++; + return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, cY, j, radius, except, steps, pass, type); + } + } + + return null; + } + + public static int[] canDeploySleepingBag(World world, EntityPlayer player, int cX, int cY, int cZ, boolean isTile) + { + int switchBy = -1; + if (isTile) + { + TileAdventureBackpack te = (TileAdventureBackpack) world.getTileEntity(cX, cY, cZ); + if (!te.isSleepingBagDeployed()) + switchBy = world.getBlockMetadata(cX, cY, cZ) & 3; + } + else + { + int playerDirection = MathHelper.floor_double((double) ((player.rotationYaw * 4F) / 360F) + 0.5D) & 3; + int[] tileSequence = {2, 3, 0, 1}; + for (int i = 0; i < tileSequence.length; i++) // converts to use isTile format + { + if (playerDirection == i) + { + switchBy = tileSequence[i]; + break; + } + } + } + return getDirectionAndCoordsForSleepingBag(switchBy, world, cX, cY, cZ); + } + + private static int[] getDirectionAndCoordsForSleepingBag(int switchBy, World world, int cX, int cY, int cZ) + { + int direction = -1; + switch (switchBy) + { + case 0: + --cZ; + if (isAirAboveSolid(world, cX, cY, cZ) && isAirAboveSolid(world, cX, cY, cZ - 1)) + direction = 2; + break; + case 1: + ++cX; + if (isAirAboveSolid(world, cX, cY, cZ) && isAirAboveSolid(world, cX + 1, cY, cZ)) + direction = 3; + break; + case 2: + ++cZ; + if (isAirAboveSolid(world, cX, cY, cZ) && isAirAboveSolid(world, cX, cY, cZ + 1)) + direction = 0; + break; + case 3: + --cX; + if (isAirAboveSolid(world, cX, cY, cZ) && isAirAboveSolid(world, cX - 1, cY, cZ)) + direction = 1; + break; + default: + break; + } + return new int[]{direction, cX, cY, cZ}; + } + + private static boolean isAirAboveSolid(World world, int cX, int cY, int cZ) + { + return world.isAirBlock(cX, cY, cZ) && world.getBlock(cX, cY - 1, cZ).getMaterial().isSolid(); + } + + public static boolean spawnSleepingBag(EntityPlayer player, World world, int meta, int cX, int cY, int cZ) + { + Block sleepingBag = ModBlocks.blockSleepingBag; + if (world.setBlock(cX, cY, cZ, sleepingBag, meta, 3)) + { + world.playSoundAtEntity(player, Block.soundTypeCloth.func_150496_b(), 0.5f, 1.0f); + switch (meta & 3) + { + case 0: + ++cZ; + break; + case 1: + --cX; + break; + case 2: + --cZ; + break; + case 3: + ++cX; + break; + } + return world.setBlock(cX, cY, cZ, sleepingBag, meta + 8, 3); + } + return false; + } + + /** + * Compares two coordinates. Heh. + * + * @param cX1 First coordinate X. + * @param cY1 First coordinate Y. + * @param cZ1 First coordinate Z. + * @param cX2 Second coordinate X. + * @param cY2 Second coordinate Y. + * @param cZ2 Second coordinate Z. I really didn't need to type all that, its obvious. + * @return If both coordinates are the same, returns true. This is the least helpful javadoc ever. + */ + private static boolean areCoordinatesTheSame(int cX1, int cY1, int cZ1, int cX2, int cY2, int cZ2) + { + return (cX1 == cX2 && cY1 == cY2 && cZ1 == cZ2); + } + + private static boolean areCoordinatesTheSame2D(int cX1, int cZ1, int cX2, int cZ2) + { + return (cX1 == cX2 && cZ1 == cZ2); + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/util/EnchUtils.java b/src/main/java/com/darkona/adventurebackpack/util/EnchUtils.java new file mode 100644 index 00000000..fff885d0 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/util/EnchUtils.java @@ -0,0 +1,73 @@ +package com.darkona.adventurebackpack.util; + +import net.minecraft.enchantment.Enchantment; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.Constants.NBT; + +import com.darkona.adventurebackpack.config.ConfigHandler; +import com.darkona.adventurebackpack.reference.LoadedMods; + +/** + * Created on 24.03.2017 + * + * @author Ugachaga + */ +public final class EnchUtils +{ + // -3 - disabled by config + // -2 - EnderIO not found + // -1 - enchantment not found + private static final int SOUL_BOUND_ID = setSoulBoundID(); + + private EnchUtils() {} + + private static int setSoulBoundID() + { + if (!ConfigHandler.allowSoulBound) + return -3; + + if (!LoadedMods.ENDERIO) + return -2; + + for (Enchantment ench : Enchantment.enchantmentsList) + if (ench != null && ench.getName().equals("enchantment.enderio.soulBound")) + return ench.effectId; + + return -1; + } + + public static boolean isSoulBounded(ItemStack stack) + { + NBTTagList stackEnch = stack.getEnchantmentTagList(); + if (SOUL_BOUND_ID >= 0 && stackEnch != null) + { + for (int i = 0; i < stackEnch.tagCount(); i++) + { + int id = stackEnch.getCompoundTagAt(i).getInteger("id"); + if (id == SOUL_BOUND_ID) + return true; + } + } + return false; + } + + public static boolean isSoulBook(ItemStack book) + { + if (SOUL_BOUND_ID >= 0 && book.hasTagCompound()) + { + NBTTagCompound bookData = book.stackTagCompound; + if (bookData.hasKey("StoredEnchantments")) + { + NBTTagList bookEnch = bookData.getTagList("StoredEnchantments", NBT.TAG_COMPOUND); + if (!bookEnch.getCompoundTagAt(1).getBoolean("id")) // only pure soulbook allowed + { + int id = bookEnch.getCompoundTagAt(0).getInteger("id"); + return id == SOUL_BOUND_ID; + } + } + } + return false; + } +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/util/FluidUtils.java b/src/main/java/com/darkona/adventurebackpack/util/FluidUtils.java index 6de761e7..d0c79d01 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/FluidUtils.java +++ b/src/main/java/com/darkona/adventurebackpack/util/FluidUtils.java @@ -11,17 +11,16 @@ */ public class FluidUtils { - public static boolean isContainerForFluid(ItemStack container, Fluid fluid) { - if(container != null && fluid != null) + if (container != null && fluid != null) { for (FluidContainerRegistry.FluidContainerData data : FluidContainerRegistry.getRegisteredFluidContainerData()) { - if ( - (data.fluid.getFluid().getID() == fluid.getID()) && - (data.emptyContainer.getItem().equals(container.getItem()) || data.filledContainer.getItem().equals(container.getItem())) - ) + if (data.fluid != null && data.fluid.getFluid() != null + && data.fluid.getFluid().getID() == fluid.getID() + && (data.emptyContainer.getItem().equals(container.getItem()) + || data.filledContainer.getItem().equals(container.getItem()))) { return true; } @@ -36,10 +35,9 @@ public static boolean isEmptyContainerForFluid(ItemStack container, Fluid fluid) { for (FluidContainerRegistry.FluidContainerData data : FluidContainerRegistry.getRegisteredFluidContainerData()) { - if ( - (data.fluid.getFluid().getID() == fluid.getID()) && - (data.emptyContainer.getItem().equals(container.getItem())) - ) + if (data.fluid != null && data.fluid.getFluid() != null + && data.fluid.getFluid().getID() == fluid.getID() + && data.emptyContainer.getItem().equals(container.getItem())) { return true; } diff --git a/src/main/java/com/darkona/adventurebackpack/util/GregtechUtils.java b/src/main/java/com/darkona/adventurebackpack/util/GregtechUtils.java new file mode 100644 index 00000000..79dae2e6 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/util/GregtechUtils.java @@ -0,0 +1,81 @@ +package com.darkona.adventurebackpack.util; + +import javax.annotation.Nonnull; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.client.IItemRenderer; + +import com.darkona.adventurebackpack.reference.LoadedMods; + +/** + * Created on 30.01.2018 + * + * @author Ugachaga + */ +public final class GregtechUtils +{ + private static final String CLASS_RENDERER = "gregtech.common.render.GT_MetaGenerated_Tool_Renderer"; + + private static final String TOOLS_NAME = "gt.metatool.01"; + private static final int[] ROTATED_45_TOOLS = {16, 26, 30, 130}; + private static final int[] ROTATED_90_TOOLS = {10, 14, 18, 22, 34, 150, 160}; + + private static Class toolRenderer; + private static Object toolRendererInstance; + + private GregtechUtils() {} + + static + { + if (LoadedMods.GREGTECH) + { + createToolRendererInstance(); + } + } + + private static void createToolRendererInstance() + { + if (Utils.inClient()) + { + try + { + toolRenderer = Class.forName(CLASS_RENDERER); + toolRendererInstance = toolRenderer.newInstance(); + } + catch (Exception e) + { + LogHelper.error("Error getting instance of Gregtech Tools Renderer: " + e); + } + } + } + + public static boolean isTool(@Nonnull ItemStack stack) + { + return LoadedMods.GREGTECH && stack.getItem().getUnlocalizedName().equals(TOOLS_NAME); + } + + public static boolean isTool(String itemName) + { + return LoadedMods.GREGTECH && itemName.equals(TOOLS_NAME); + } + + public static float getToolRotationAngle(ItemStack stack, boolean isLowerSlot) + { + int meta = stack.getItemDamage(); + + for (int rotated45 : ROTATED_45_TOOLS) + if (meta == rotated45) + return isLowerSlot ? 0F : 90F; + + for (int rotated90 : ROTATED_90_TOOLS) + if (meta == rotated90) + return isLowerSlot ? 45F : 135F; + + return isLowerSlot ? -45F : 45F; + } + + public static void renderTool(ItemStack stack, IItemRenderer.ItemRenderType renderType) + { + ToolRenderHelper.render(stack, renderType, toolRenderer, toolRendererInstance); + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/util/LogHelper.java b/src/main/java/com/darkona/adventurebackpack/util/LogHelper.java index 68821071..a8590dfc 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/LogHelper.java +++ b/src/main/java/com/darkona/adventurebackpack/util/LogHelper.java @@ -1,38 +1,21 @@ package com.darkona.adventurebackpack.util; -import com.darkona.adventurebackpack.reference.ModInfo; -import cpw.mods.fml.common.FMLLog; -import net.minecraft.util.ChunkCoordinates; import org.apache.logging.log4j.Level; +import cpw.mods.fml.common.FMLLog; + +import com.darkona.adventurebackpack.reference.ModInfo; /** * Created by Darkona on 12/10/2014. */ public class LogHelper { - - public static void log(Level logLevel, Object object) { FMLLog.log(ModInfo.MOD_NAME, logLevel, String.valueOf(object)); } - public static String print3DCoords(int x, int y, int z) - { - return "Coords: X= " + x + ", Y= " + y + ", Z=" + z; - } - - public static String print3DCoords(ChunkCoordinates coords) - { - return print3DCoords(coords.posX, coords.posY, coords.posZ); - } - - public static void all(Object object) - { - log(Level.ALL, object); - } - public static void debug(Object object) { log(Level.DEBUG, object); @@ -43,28 +26,13 @@ public static void error(Object object) log(Level.ERROR, object); } - public static void fatal(Object object) + public static void warn(Object object) { - log(Level.FATAL, object); + log(Level.WARN, object); } public static void info(Object object) { log(Level.INFO, object); } - - public static void off(Object object) - { - log(Level.OFF, object); - } - - public static void trace(Object object) - { - log(Level.TRACE, object); - } - - public static void warn(Object object) - { - log(Level.WARN, object); - } } diff --git a/src/main/java/com/darkona/adventurebackpack/util/Resources.java b/src/main/java/com/darkona/adventurebackpack/util/Resources.java index 8fac4850..13cf533c 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/Resources.java +++ b/src/main/java/com/darkona/adventurebackpack/util/Resources.java @@ -1,11 +1,11 @@ package com.darkona.adventurebackpack.util; -import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; -import com.darkona.adventurebackpack.reference.BackpackNames; -import com.darkona.adventurebackpack.reference.ModInfo; -import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; +import com.darkona.adventurebackpack.init.ModDates; +import com.darkona.adventurebackpack.reference.BackpackTypes; +import com.darkona.adventurebackpack.reference.ModInfo; + /** * Created on 10/10/2014 * @@ -13,27 +13,28 @@ */ public class Resources { + private static final String TEXTURE_LOCATION = ModInfo.MOD_ID; - public static final String TEXTURE_LOCATION = ModInfo.MOD_ID.toLowerCase(); - - public static String modelTextureResourceString(String name) + public static ResourceLocation getBackpackTexture(BackpackTypes type) { - return new ResourceLocation(TEXTURE_LOCATION, "textures/models/" + name).toString(); + return type == BackpackTypes.STANDARD + ? backpackTextureFromString(ModDates.getHoliday()) + : backpackTextureFromType(type); } - public static String backpackTexturesStringFromColor(ItemStack backpack) + private static ResourceLocation backpackTextureFromString(String color) { - return new ResourceLocation(TEXTURE_LOCATION, "textures/backpack/" + BackpackNames.getBackpackColorName(backpack) + ".png").toString(); + return new ResourceLocation(TEXTURE_LOCATION, "textures/backpack/" + color + ".png"); } - public static ResourceLocation backpackTextureFromString(String color) + private static ResourceLocation backpackTextureFromType(BackpackTypes type) { - return new ResourceLocation(TEXTURE_LOCATION, "textures/backpack/" + color + ".png"); + return new ResourceLocation(TEXTURE_LOCATION, "textures/backpack/" + BackpackTypes.getSkinName(type) + ".png"); } - public static ResourceLocation backpackTextureFromColor(IInventoryAdventureBackpack adventureBackpack) + public static String modelTextureResourceString(String name) { - return new ResourceLocation(TEXTURE_LOCATION, "textures/backpack/" + adventureBackpack.getColorName() + ".png"); + return new ResourceLocation(TEXTURE_LOCATION, "textures/models/" + name).toString(); } public static ResourceLocation guiTextures(String name) @@ -66,5 +67,4 @@ public static String getIconString(String name) return TEXTURE_LOCATION + ":" + name; } - } diff --git a/src/main/java/com/darkona/adventurebackpack/util/ThaumcraftUtils.java b/src/main/java/com/darkona/adventurebackpack/util/ThaumcraftUtils.java new file mode 100644 index 00000000..f6d49d5a --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/util/ThaumcraftUtils.java @@ -0,0 +1,90 @@ +package com.darkona.adventurebackpack.util; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.client.IItemRenderer; + +import com.darkona.adventurebackpack.reference.LoadedMods; + +/** + * Created on 06.02.2018 + * + * @author Ugachaga + */ +public final class ThaumcraftUtils +{ + public static final boolean DIAL_BOTTOM = setDialBottom(); + + private static final String CLASS_RENDERER = "thaumcraft.client.renderers.item.ItemWandRenderer"; + private static final String CLASS_CONFIG = "thaumcraft.common.config.Config"; + private static final String CLASS_WANDS = "thaumcraft.common.items.wands.ItemWandCasting"; + private static final String FIELD_DIAL_BOTTOM = "dialBottom"; + + private static Class toolRenderer; + private static Object toolRendererInstance; + + private ThaumcraftUtils() {} + + static + { + if (LoadedMods.THAUMCRAFT) + { + createToolRendererInstance(); + } + } + + private static void createToolRendererInstance() + { + if (Utils.inClient()) + { + try + { + toolRenderer = Class.forName(CLASS_RENDERER); + toolRendererInstance = toolRenderer.newInstance(); + } + catch (Exception e) + { + LogHelper.error("Error getting instance of Thaumcraft Wands Renderer: " + e); + } + } + } + + private static boolean setDialBottom() + { + if (!LoadedMods.THAUMCRAFT || Utils.inServer()) + return false; + + try + { + return Class.forName(CLASS_CONFIG).getField(FIELD_DIAL_BOTTOM).getBoolean(null); + } + catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) + { + return false; + } + } + + public static boolean isTool(ItemStack stack) + { + if (!LoadedMods.THAUMCRAFT || stack == null) + return false; + + try + { + return Class.forName(CLASS_WANDS).isInstance(stack.getItem()); + } + catch (ClassNotFoundException e) + { + return false; + } + } + + public static float getToolRotationAngle(ItemStack stack, boolean isLowerSlot) + { + return isLowerSlot ? 0F : 90F; + } + + public static void renderTool(ItemStack stack, IItemRenderer.ItemRenderType renderType) + { + ToolRenderHelper.render(stack, renderType, toolRenderer, toolRendererInstance); + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/util/TinkersUtils.java b/src/main/java/com/darkona/adventurebackpack/util/TinkersUtils.java new file mode 100644 index 00000000..405513ee --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/util/TinkersUtils.java @@ -0,0 +1,169 @@ +package com.darkona.adventurebackpack.util; + +import java.util.UUID; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.WorldServer; +import net.minecraftforge.client.IItemRenderer; +import net.minecraftforge.common.util.FakePlayer; +import com.mojang.authlib.GameProfile; +import cpw.mods.fml.common.FMLCommonHandler; + +import com.darkona.adventurebackpack.reference.LoadedMods; + +/** + * Created on 03.02.2018 + * + * @author Ugachaga + */ +public final class TinkersUtils +{ + public static final ResourceLocation GUI_ICONS = new ResourceLocation("tinker", "textures/gui/icons.png"); + + private static final String CLASS_CRAFTING_LOGIC = "tconstruct.tools.logic.CraftingStationLogic"; + private static final String CLASS_CRAFTING_STATION = "tconstruct.tools.inventory.CraftingStationContainer"; + private static final String METHOD_ON_CRAFT_CHANGED = LoadedMods.DEV_ENV ? "onCraftMatrixChanged" : "func_75130_a"; + private static final String FIELD_CRAFT_MATRIX = "craftMatrix"; + private static final String FIELD_CRAFT_RESULT = "craftResult"; + + private static final String CLASS_RENDERER = "tconstruct.client.FlexibleToolRenderer"; + + private static final String PACKAGE_TCONSTRUCT = "tconstruct"; + private static final String PACKAGE_TOOLS = "tconstruct.items.tools"; + private static final String PACKAGE_AMMO = "tconstruct.weaponry.ammo"; // arrows and bolts + private static final String PACKAGE_WEAPONS = "tconstruct.weaponry.weapons"; // bows, crossbows, throwing weapons + + private static Class craftingStation; + private static Object craftingStationInstance; + + private static Class toolRenderer; + private static Object toolRendererInstance; + + private TinkersUtils() {} + + static + { + if (LoadedMods.TCONSTRUCT) + { + createCraftingStationInstance(); + createToolRendererInstance(); + } + } + + private static void createCraftingStationInstance() + { + try + { + Class craftingLogic = Class.forName(CLASS_CRAFTING_LOGIC); + Object craftingLogicInstance = craftingLogic.newInstance(); + InventoryPlayer invPlayer = getInventoryPlayer(); + + craftingStation = Class.forName(CLASS_CRAFTING_STATION); + craftingStationInstance = craftingStation + .getConstructor(InventoryPlayer.class, craftingLogic, int.class, int.class, int.class) + .newInstance(invPlayer, craftingLogicInstance, 0, 0, 0); + } + catch (Exception e) + { + LogHelper.error("Error getting instance of Tinkers Crafting Station: " + e); + } + } + + private static InventoryPlayer getInventoryPlayer() + { + InventoryPlayer invPlayer; + if (Utils.inServer()) + { + WorldServer world = FMLCommonHandler.instance().getMinecraftServerInstance().worldServers[0]; + UUID fakeUuid = UUID.fromString("521e749d-2ac0-3459-af7a-160b4be5c62b"); + GameProfile fakeProfile = new GameProfile(fakeUuid, "[Adventurer]"); + invPlayer = new InventoryPlayer(new FakePlayer(world, fakeProfile)); + } + else + { + invPlayer = Minecraft.getMinecraft().thePlayer.inventory; + } + return invPlayer; + } + + private static void createToolRendererInstance() + { + if (Utils.inClient()) + { + try + { + toolRenderer = Class.forName(CLASS_RENDERER); + toolRendererInstance = toolRenderer.newInstance(); + } + catch (Exception e) + { + LogHelper.error("Error getting instance of Tinkers Tool Renderer: " + e); + } + } + } + + public static boolean isToolOrWeapon(@Nullable ItemStack stack) + { + if (stack == null) + return false; + + String cn = stack.getItem().getClass().getName(); + return cn.startsWith(PACKAGE_TCONSTRUCT) + && (cn.startsWith(PACKAGE_TOOLS) || cn.startsWith(PACKAGE_WEAPONS) || cn.startsWith(PACKAGE_AMMO)); + } + + public static boolean isTool(@Nonnull ItemStack stack) + { + return LoadedMods.TCONSTRUCT && stack.getItem().getClass().getName().startsWith(PACKAGE_TOOLS); + } + + public static boolean isTool(String clazzName) + { + return LoadedMods.TCONSTRUCT && clazzName.startsWith(PACKAGE_TOOLS); + } + + @Nullable + public synchronized static ItemStack getTinkersRecipe(InventoryCrafting craftMatrix) + { + if (craftingStationInstance == null) + return null; + + try + { + craftingStation + .getField(FIELD_CRAFT_MATRIX) + .set(craftingStationInstance, craftMatrix); + + craftingStation + .getMethod(METHOD_ON_CRAFT_CHANGED, IInventory.class) + .invoke(craftingStationInstance, craftMatrix); + + return ((IInventory) craftingStation + .getField(FIELD_CRAFT_RESULT) + .get(craftingStationInstance)) + .getStackInSlot(0); + } + catch (Exception e) + { + LogHelper.error("Error during reflection in getTinkersRecipe: " + e); + return null; + } + } + + public static float getToolRotationAngle(ItemStack stack, boolean isLowerSlot) + { + return isLowerSlot ? -45F : 45F; + } + + public static void renderTool(ItemStack stack, IItemRenderer.ItemRenderType renderType) + { + ToolRenderHelper.render(stack, renderType, toolRenderer, toolRendererInstance); + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/util/TipUtils.java b/src/main/java/com/darkona/adventurebackpack/util/TipUtils.java new file mode 100644 index 00000000..6c941fd6 --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/util/TipUtils.java @@ -0,0 +1,221 @@ +package com.darkona.adventurebackpack.util; + +import java.util.List; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; +import cpw.mods.fml.common.registry.GameData; + +import com.darkona.adventurebackpack.common.Constants; +import com.darkona.adventurebackpack.config.Keybindings; +import com.darkona.adventurebackpack.reference.GeneralReference; + +/** + * Created on 24.03.2017 + * + * @author Ugachaga + */ +public final class TipUtils +{ + private TipUtils() {} + + public static String l10n(String tip) + { + return StatCollector.translateToLocal("adventurebackpack:tooltips." + tip); + } + + public static void shiftFooter(List eventTips) + { + if (GuiScreen.isCtrlKeyDown()) + eventTips.add(""); + else + eventTips.add(holdCtrl()); + } + + public static String holdShift() + { + return holdThe(true); + } + + public static String holdCtrl() + { + return holdThe(false); + } + + private static String holdThe(boolean button) + { + return whiteFormat(EnumChatFormatting.ITALIC + "<" + (button ? l10n("hold.shift") + : l10n("hold.ctrl")) + ">"); + } + + public static String whiteFormat(String stringIn) + { + return EnumChatFormatting.WHITE + stringIn + EnumChatFormatting.GRAY; + } + + public static String actionKeyFormat() + { + return whiteFormat(Keybindings.getActionKeyName()); + } + + public static String pressKeyFormat(String button) + { + return l10n("press") + " '" + button + "' "; + } + + public static String pressShiftKeyFormat(String button) + { + return l10n("press") + " Shift+'" + button + "' "; + } + + public static String inventoryTooltip(NBTTagList itemList) + { + int itemCount = itemList.tagCount(); + boolean toolSlotU = false; + boolean toolSlotL = false; + for (int i = itemCount - 1; i >= 0; i--) + { + int slotAtI = itemList.getCompoundTagAt(i).getInteger(Constants.TAG_SLOT); + if (slotAtI < Constants.TOOL_UPPER) + break; + else if (slotAtI == Constants.TOOL_UPPER) + toolSlotU = true; + else if (slotAtI == Constants.TOOL_LOWER) + toolSlotL = true; + else + itemCount--; // this need for correct count while GUI is open and bucket slots may be occupied + } + itemCount -= (toolSlotU ? 1 : 0) + (toolSlotL ? 1 : 0); + return toolSlotFormat(toolSlotU) + toolSlotFormat(toolSlotL) + " " + mainSlotsFormat(itemCount); + } + + private static String toolSlotFormat(boolean isTool) + { + return (isTool ? EnumChatFormatting.WHITE : EnumChatFormatting.DARK_GRAY) + "[]"; + } + + private static String mainSlotsFormat(int slotsUsed) + { + String slotsFormatted = Integer.toString(slotsUsed); + if (slotsUsed == 0) + slotsFormatted = EnumChatFormatting.DARK_GRAY + slotsFormatted; + else if (slotsUsed == Constants.INVENTORY_MAIN_SIZE) + slotsFormatted = EnumChatFormatting.WHITE + slotsFormatted; + else + slotsFormatted = EnumChatFormatting.GRAY + slotsFormatted; + return slotsFormatted + "/" + Constants.INVENTORY_MAIN_SIZE; + } + + public static String tankTooltip(FluidTank tank) + { + return tankTooltip(tank, true); + } + + public static String tankTooltip(FluidTank tank, boolean attachName) + { + String fluidAmount = fluidAmountFormat(tank.getFluidAmount(), tank.getCapacity()); + String fluidName = tank.getFluid() == null ? "" : attachName ? fluidNameFormat(tank.getFluid()) : " "; + return fluidAmount + (tank.getFluidAmount() > 0 ? "/" + tank.getCapacity() : "") + fluidName; + } + + private static String fluidAmountFormat(int fluidAmount, int tankCapacity) + { + String amountFormatted = Integer.toString(fluidAmount); + if (fluidAmount == tankCapacity) + amountFormatted = EnumChatFormatting.WHITE + amountFormatted; + else if (fluidAmount == 0) + amountFormatted = emptyFormat(); + return amountFormatted; + } + + private static String fluidNameFormat(FluidStack fluid) + { + String nameUnlocalized = fluid.getUnlocalizedName().toLowerCase(); + String nameFormatted = " "; + if (nameUnlocalized.contains("lava") || nameUnlocalized.contains("fire")) + nameFormatted += EnumChatFormatting.RED; + else if (nameUnlocalized.contains("water")) + nameFormatted += EnumChatFormatting.BLUE; + else if (nameUnlocalized.contains("oil")) + nameFormatted += EnumChatFormatting.DARK_GRAY; + else if (nameUnlocalized.contains("fuel") || nameUnlocalized.contains("creosote")) + nameFormatted += EnumChatFormatting.YELLOW; + else if (nameUnlocalized.contains("milk")) + nameFormatted += EnumChatFormatting.WHITE; + else if (nameUnlocalized.contains("xpjuice")) + nameFormatted += EnumChatFormatting.GREEN; + else + nameFormatted += EnumChatFormatting.GRAY; + return nameFormatted + fluid.getLocalizedName(); + } + + public static String switchTooltip(boolean status, boolean doFormat) + { + return doFormat ? switchFormat(status) : status ? l10n("on") : l10n("off"); + } + + private static String switchFormat(boolean status) + { + String switchFormatted = status ? EnumChatFormatting.WHITE + l10n("on") + : EnumChatFormatting.DARK_GRAY + l10n("off"); + return "[" + switchFormatted + EnumChatFormatting.GRAY + "]"; + } + + public static String slotStackTooltip(NBTTagList itemList, int slot) + { + int slotID, slotMeta, slotCount = slotID = slotMeta = 0; + for (int i = 0; i <= slot; i++) + { + int slotAtI = itemList.getCompoundTagAt(i).getInteger(Constants.TAG_SLOT); + if (slotAtI == slot) + { + slotID = itemList.getCompoundTagAt(i).getInteger("id"); + slotMeta = itemList.getCompoundTagAt(i).getInteger("Damage"); + slotCount = itemList.getCompoundTagAt(i).getInteger("Count"); + break; + } + } + return stackDataFormat(slotID, slotMeta, slotCount); + } + + private static String stackDataFormat(int id, int meta, int count) + { + if (count == 0) + return emptyFormat(); + + String dataFormatted; + try + { + ItemStack iStack = new ItemStack(GameData.getItemRegistry().getObjectById(id), 0, meta); + dataFormatted = iStack.getDisplayName() + " (" + stackSizeFormat(iStack, count) + ")"; + } + catch (Exception e) + { + dataFormatted = EnumChatFormatting.RED + l10n("error"); + } + return dataFormatted; + } + + private static String stackSizeFormat(ItemStack stack, int count) + { + return stack.getMaxStackSize() == count ? whiteFormat(Integer.toString(count)) : Integer.toString(count); + } + + public static String fuelConsumptionTooltip(FluidTank tank) + { + return (tank.getFluid() != null) + ? String.format("x%.2f", GeneralReference.getFuelRate(tank.getFluid().getFluid().getName())) + : EnumChatFormatting.DARK_GRAY + "-" ; + } + + private static String emptyFormat() + { + return EnumChatFormatting.DARK_GRAY.toString() + EnumChatFormatting.ITALIC + l10n("empty"); + } + +} \ No newline at end of file diff --git a/src/main/java/com/darkona/adventurebackpack/util/ToolRenderHelper.java b/src/main/java/com/darkona/adventurebackpack/util/ToolRenderHelper.java new file mode 100644 index 00000000..4bcc22ee --- /dev/null +++ b/src/main/java/com/darkona/adventurebackpack/util/ToolRenderHelper.java @@ -0,0 +1,32 @@ +package com.darkona.adventurebackpack.util; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.client.IItemRenderer.ItemRenderType; + +/** + * Created on 25.02.2018 + * + * @author Ugachaga + */ +public final class ToolRenderHelper +{ + private static final String METHOD_RENDERER = "renderItem"; + private static final Object[] EMPTY_OBJECT = {}; + + private ToolRenderHelper() {} + + public static void render(ItemStack stack, ItemRenderType type, Class renderer, Object rendererInstance) + { + if (rendererInstance == null) + return; + + try + { + renderer + .getMethod(METHOD_RENDERER, ItemRenderType.class, ItemStack.class, Object[].class) + .invoke(rendererInstance, type, stack, EMPTY_OBJECT); + } + catch (Exception e) + { /* */ } + } +} diff --git a/src/main/java/com/darkona/adventurebackpack/util/Utils.java b/src/main/java/com/darkona/adventurebackpack/util/Utils.java index 7c2a1834..27efcdd8 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/Utils.java +++ b/src/main/java/com/darkona/adventurebackpack/util/Utils.java @@ -1,459 +1,151 @@ package com.darkona.adventurebackpack.util; -import com.darkona.adventurebackpack.AdventureBackpack; +import net.minecraft.client.Minecraft; +import net.minecraft.util.EnumChatFormatting; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.Vec3; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import java.util.Calendar; +import com.darkona.adventurebackpack.reference.BackpackTypes; /** * Created on 12/10/2014 - * @author Darkona * + * @author Darkona */ public class Utils { - - public static float degreesToRadians(float degrees) + public static boolean inServer() { - return degrees / 57.2957795f; + return FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER; } - public static float radiansToDegrees(float radians) + public static boolean inClient() { - return radians * 57.2957795f; + return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT; } - public static int[] calculateEaster(int year) + public static float degreesToRadians(float degrees) { - - - int a = year % 19, - b = year / 100, - c = year % 100, - d = b / 4, - e = b % 4, - g = (8 * b + 13) / 25, - h = (19 * a + b - d - g + 15) % 30, - j = c / 4, - k = c % 4, - m = (a + 11 * h) / 319, - r = (2 * e + 2 * j - k - h + m + 32) % 7, - n = (h - m + r + 90) / 25, - p = (h - m + r + n + 19) % 32; - - return new int[]{n, p}; + return degrees / 57.2957795f; } - public static String getHoliday() + public static float radiansToDegrees(float radians) { - - Calendar calendar = Calendar.getInstance(); - int year = calendar.get(Calendar.YEAR), - month = calendar.get(Calendar.MONTH) + 1, - day = calendar.get(Calendar.DAY_OF_MONTH); - - if (AdventureBackpack.instance.chineseNewYear) return "ChinaNewYear"; - if (AdventureBackpack.instance.hannukah) return "Hannukah"; - if (month == Utils.calculateEaster(year)[0] && day == Utils.calculateEaster(year)[1]) return "Easter"; - String dia = "Standard"; - if (month == 1) - { - if (day == 1) dia = "NewYear"; - if (day == 28) dia = "Shuttle";//Challenger - } - if (month == 2) - { - if (day == 1) dia = "Shuttle";//Columbia - if (day == 14) dia = "Valentines"; - if (day == 23) dia = "Fatherland"; - } - if (month == 3) - { - if (day == 17) dia = "Patrick"; - } - if (month == 4) - { - if (day == 1) dia = "Fools"; - if (day == 25) dia = "Italy"; - } - if (month == 5) - { - if (day == 8 || day == 9 || day == 10) dia = "Liberation"; - } - if (month == 6) - { - } - if (month == 7) - { - if (day == 4) dia = "USA"; - if (day == 24) dia = "Bolivar"; - if (day == 14) dia = "Bastille"; - } - if (month == 8) - { - } - if (month == 9) - { - if (day == 19) dia = "Pirate"; - } - if (month == 10) - { - if (day == 3) dia = "Germany"; - if (day == 12) dia = "Columbus"; - if (day == 31) dia = "Halloween"; - } - if (month == 11) - { - if (day == 2) dia = "Muertos"; - } - if (month == 12) - { - if (day >= 22 && day <= 26) dia = "Christmas"; - if (day == 31) dia = "NewYear"; - } - //LogHelper.info("Today is: " + day + "/" + month + "/" + year + ". Which means today is: " + dia); - return dia; - + return radians * 57.2957795f; } - public static int isBlockRegisteredAsFluid(Block block) + public static int secondsToTicks(int seconds) { - /* - * for (Map.Entry fluid : - * getRegisteredFluids().entrySet()) { int ID = - * (fluid.getValue().getBlockID() == BlockID) ? fluid.getValue().getID() - * : -1; if (ID > 0) return ID; } - */ - int fluidID = -1; - for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) - { - fluidID = (fluid.getBlock() == block) ? fluid.getID() : -1; - if (fluidID > 0) - { - return fluidID; - } - } - return fluidID; + return seconds * 20; } - public static boolean shouldGiveEmpty(ItemStack cont) + public static int[] createSlotArray(int first, int count) { - boolean valid = true; - // System.out.println("Item class name is: "+cont.getItem().getClass().getName()); - - try + int[] slots = new int[count]; + for (int i = first; i < first + count; i++) { - // Industrialcraft cells - // if (apis.ic2.api.item.Items.getItem("cell").getClass().isInstance(cont.getItem())) - // { - // valid = false; - // } - // Forestry capsules - if (java.lang.Class.forName("forestry.core.items.ItemLiquidContainer").isInstance(cont.getItem())) - { - valid = false; - } - } catch (Exception oops) - { - + slots[i - first] = i; } - // Others - - return valid; + return slots; } - public static ChunkCoordinates findBlock2D(World world, int x, int y, int z, Block block, int range) - { - for (int i = x - range; i <= x + range; i++) - { - for (int j = z - range; j <= z + range; j++) - { - if (world.getBlock(i, y, j) == block) - { - return new ChunkCoordinates(i, y, j); - } - } - } - return null; - } + private static final EnumChatFormatting[] RAINBOW_SEQUENCE = {EnumChatFormatting.RED, EnumChatFormatting.GOLD, + EnumChatFormatting.YELLOW, EnumChatFormatting.GREEN, EnumChatFormatting.AQUA, EnumChatFormatting.BLUE, + EnumChatFormatting.DARK_PURPLE}; - public static ChunkCoordinates findBlock3D(World world, int x, int y, int z, Block block, int hRange, int vRange) + public static String makeItRainbow(String stringIn) { - for (int i = (y - vRange); i <= (y + vRange); i++) + StringBuilder rainbowed = new StringBuilder(stringIn.length() * 3); // special characters = length * 2 + for (int i = 0; i < stringIn.length(); i++) { - for (int j = (x - hRange); j <= (x + hRange); j++) - { - for (int k = (z - hRange); k <= (z + hRange); k++) - { - if (world.getBlock(j, i, k) == block) - { - return new ChunkCoordinates(j, i, k); - } - } - } + rainbowed.append(RAINBOW_SEQUENCE[i % RAINBOW_SEQUENCE.length]).append(stringIn.charAt(i)); } - return null; - } - - public static String capitalize(String s) - { - // Character.toUpperCase(itemName.charAt(0)) + itemName.substring(1); - return s.substring(0, 1).toUpperCase().concat(s.substring(1)); - } - - public static int getOppositeCardinalFromMeta(int meta) - { - return (meta % 2 == 0) ? (meta == 0) ? 2 : 0 : ((meta + 1) % 4) + 1; - } - - //This is some black magic that returns a block or entity as far as the argument reach goes. - public static MovingObjectPosition getMovingObjectPositionFromPlayersHat(World world, EntityPlayer player, boolean flag, double reach) - { - float f = 1.0F; - float playerPitch = player.prevRotationPitch - + (player.rotationPitch - player.prevRotationPitch) * f; - float playerYaw = player.prevRotationYaw - + (player.rotationYaw - player.prevRotationYaw) * f; - double playerPosX = player.prevPosX + (player.posX - player.prevPosX) - * f; - double playerPosY = (player.prevPosY + (player.posY - player.prevPosY) - * f + 1.6200000000000001D) - - player.yOffset; - double playerPosZ = player.prevPosZ + (player.posZ - player.prevPosZ) - * f; - Vec3 vecPlayer = Vec3.createVectorHelper(playerPosX, playerPosY, - playerPosZ); - float cosYaw = (float) Math.cos(-playerYaw * 0.01745329F - 3.141593F); - float sinYaw = (float) Math.sin(-playerYaw * 0.01745329F - 3.141593F); - float cosPitch = (float) -Math.cos(-playerPitch * 0.01745329F); - float sinPitch = (float) Math.sin(-playerPitch * 0.01745329F); - float pointX = sinYaw * cosPitch; - float pointY = sinPitch; - float pointZ = cosYaw * cosPitch; - Vec3 vecPoint = vecPlayer.addVector(pointX * reach, pointY * reach, - pointZ * reach); - return world.func_147447_a/*rayTraceBlocks_do_do*/( - vecPlayer, vecPoint, flag, !flag, flag); + return rainbowed.toString(); } - public static String printCoordinates(int x, int y, int z) + public static String getColoredSkinName(BackpackTypes type) { - return "X= " + x + ", Y= " + y + ", Z= " + z; - } - - - public static int secondsToTicks(int seconds) - { - return seconds * 20; - } - - public static int secondsToTicks(float seconds) - { - return (int) seconds * 20; - } - - public static boolean inServer() - { - Side side = FMLCommonHandler.instance().getEffectiveSide(); - return side == Side.SERVER; - } - - private static ChunkCoordinates checkCoordsForBackpack(IBlockAccess world, int origX, int origZ, int X, int Y, int Z, boolean except) - { - //LogHelper.info("Checking coordinates in X="+X+", Y="+Y+", Z="+Z); - if (except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z) && !areCoordinatesTheSame(origX, Y, origZ, X, Y, Z)) - { - //LogHelper.info("Found spot with the exception of the death point"); - return new ChunkCoordinates(X, Y, Z); - } - if (!except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z)) + String result; + String name = BackpackTypes.getLocalizedName(type); + switch (type) { - //LogHelper.info("Found spot without exceptions"); - return new ChunkCoordinates(X, Y, Z); + case BAT: + result = EnumChatFormatting.DARK_PURPLE + name; + break; + case EMERALD: + result = animateString(name, EnumChatFormatting.GREEN); + break; + case DIAMOND: + result = animateString(name, EnumChatFormatting.AQUA); + break; + case DRAGON: + result = EnumChatFormatting.LIGHT_PURPLE + name; + break; + case GOLD: + result = animateString(name, EnumChatFormatting.YELLOW); + break; + case IRON_GOLEM: + result = EnumChatFormatting.WHITE + name; + break; + case OBSIDIAN: + result = animateString(name, EnumChatFormatting.DARK_PURPLE); + break; + case PIGMAN: + result = EnumChatFormatting.RED + name; + break; + case QUARTZ: + result = animateString(name, EnumChatFormatting.WHITE); + break; + case RAINBOW: + result = makeItRainbow(name); + break; + case SQUID: + result = EnumChatFormatting.DARK_AQUA + name; + break; + default: + result = name; + break; } - return null; + return result; } - private static ChunkCoordinates checkCoordsForPlayer(IBlockAccess world, int origX, int origZ, int X, int Y, int Z, boolean except) + private static String animateString(String stringIn, EnumChatFormatting bold) { - LogHelper.info("Checking coordinates in X="+X+", Y="+Y+", Z="+Z); - if (except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z) && world.isAirBlock(X,Y+1,Z) && !areCoordinatesTheSame2D(origX, origZ, X, Z)) - { - LogHelper.info("Found spot with the exception of the origin point"); - return new ChunkCoordinates(X, Y, Z); - } - if (!except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z)&& world.isAirBlock(X,Y+1,Z)) - { - LogHelper.info("Found spot without exceptions"); - return new ChunkCoordinates(X, Y, Z); - } - return null; + return animateString(stringIn, EnumChatFormatting.GRAY, bold); } - /** - * Gets you the nearest Empty Chunk Coordinates, free of charge! Looks in two dimensions and finds a block - * that a: can have stuff placed on it and b: has space above it. - * This is a spiral search, will begin at close range and move out. - * @param world The world object. - * @param origX Original X coordinate - * @param origZ Original Z coordinate - * @param X Moving X coordinate, should be the same as origX when called. - * @param Y Y coordinate, does not move. - * @param Z Moving Z coordinate, should be the same as origZ when called. - * @param radius The radius of the search. If set to high numbers, will create a ton of lag - * @param except Wether to include the origin of the search as a valid block. - * @param steps Number of steps of the recursive recursiveness that recurses through the recursion. It is the first size of the spiral, should be one (1) always at the first call. - * @param pass Pass switch for the witchcraft I can't quite explain. Set to 0 always at the beggining. - * @param type True = for player, False = for backpack - * @return The coordinates of the block in the chunk of the world of the game of the server of the owner of the computer, where you can place something above it. - */ - public static ChunkCoordinates getNearestEmptyChunkCoordinatesSpiral(IBlockAccess world, int origX, int origZ, int X, int Y, int Z, int radius, boolean except, int steps, byte pass, boolean type) + private static String animateString(String stringIn, EnumChatFormatting regular, EnumChatFormatting bold) { - //Spiral search, because I'm awesome :) - //This is so the backpack tries to get placed near the death point first - //And then goes looking farther away at each step - //Steps mod 2 == 0 => X++, Z-- - //Steps mod 2 == 1 => X--, Z++ + int len = stringIn.length(); + int time = Math.abs((int) Minecraft.getMinecraft().theWorld.getWorldTime()); - // - if (steps >= radius) return null; - int i = X, j = Z; - if (steps % 2 == 0) - { - if (pass == 0) - { - for (; i <= X + steps; i++) - { + int k = 1; // animation slowness coefficient, changes charID every k ticks, k = 1 for max speed + int charID = (time / k) % len ; - ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except); - if (coords != null) - { - return coords; - } - } - pass++; - return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type); - } - if (pass == 1) - { - for (; j >= Z - steps; j--) - { - ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except); - if (coords != null) - { - return coords; - } - } - pass--; - steps++; - return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type); - } - } + int n = 100 / len; // makes n phases with len length + int phaseFactor = (time / k) % (len * n); + int phase = 1 + phaseFactor / len; - if (steps % 2 == 1) + if (phase == 1) { - if (pass == 0) - { - for (; i >= X - steps; i--) - { - ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except); - if (coords != null) - { - return coords; - } - } - pass++; - return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type); - } - if (pass == 1) - { - for (; j <= Z + steps; j++) - { - ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except); - if (coords != null) - { - return coords; - } - } - pass--; - steps++; - return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type); - } + return decorateCharInString(stringIn, charID, regular, bold, phase % 2 != 0); } - - /* Old code. Still works, though. - for (int i = x - radius; i <= x + radius; i++) - { - for (int j = y - (radius / 2); j <= y + (radius / 2); j++) - { - for (int k = z + radius; k <= z + (radius); k++) - { - if (except && world.isSideSolid(i, j - 1, k, ForgeDirection.UP) && world.isAirBlock(i, j, k) && !areCoordinatesTheSame(x, y, z, i, j, k)) - { - return new ChunkCoordinates(i, j, k); - } - if (!except && world.isSideSolid(i, j - 1, k, ForgeDirection.UP) && world.isAirBlock(i, j, k)) - { - return new ChunkCoordinates(i, j, k); - } - } - } - }*/ - return null; - } - - /** - * Compares two coordinates. Heh. - * - * @param X1 First coordinate X. - * @param Y1 First coordinate Y. - * @param Z1 First coordinate Z. - * @param X2 Second coordinate X. - * @param Y2 Second coordinate Y. - * @param Z2 Second coordinate Z. I really didn't need to type all that, its obvious. - * @return If both coordinates are the same, returns true. This is the least helpful javadoc ever. - */ - private static boolean areCoordinatesTheSame(int X1, int Y1, int Z1, int X2, int Y2, int Z2) - { - return (X1 == X2 && Y1 == Y2 && Z1 == Z2); - } - - private static boolean areCoordinatesTheSame2D(int X1, int Z1, int X2, int Z2) - { - return (X1 == X2 && Z1 == Z2); - } - - /** - * Seriously why doesn't Java's instanceof check for null? - * @return true if the object is not null and is an instance of the supplied class. - */ - public static boolean notNullAndInstanceOf(Object object, Class clazz) - { - return object != null && clazz.isInstance(object); + return stringIn; } - public static String getFirstWord(String text) + private static String decorateCharInString(String stringIn, int charID, EnumChatFormatting regular, EnumChatFormatting bold, boolean dir) { - if (text.indexOf(' ') > -1) - { // Check if there is more than one word. - String firstWord = text.substring(0, text.indexOf(' ')); - String secondWord = text.substring(text.indexOf(' ') + 1); - return firstWord.equals("Molten") ? secondWord : firstWord;// Extract first word. - } else + int len = stringIn.length(); + StringBuilder decorated = new StringBuilder(); + for (int i = dir ? 0 : len - 1; dir ? i < len : i >= 0; i = dir ? ++i : --i) { - return text; // Text is the first word itself. + if (i == charID) + decorated.append(bold); + else if (i == (dir ? charID + 1 : charID - 1) && regular != null) + decorated.append(regular); + decorated.append(stringIn.charAt(dir ? i : len - 1 - i)); } + return decorated.toString(); } + } diff --git a/src/main/java/com/darkona/adventurebackpack/util/Wearing.java b/src/main/java/com/darkona/adventurebackpack/util/Wearing.java index 2fe09829..13ddb639 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/Wearing.java +++ b/src/main/java/com/darkona/adventurebackpack/util/Wearing.java @@ -1,154 +1,198 @@ package com.darkona.adventurebackpack.util; +import javax.annotation.Nonnull; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +import com.darkona.adventurebackpack.init.ModItems; import com.darkona.adventurebackpack.inventory.IInventoryTanks; import com.darkona.adventurebackpack.inventory.InventoryBackpack; +import com.darkona.adventurebackpack.inventory.InventoryCoalJetpack; import com.darkona.adventurebackpack.inventory.InventoryCopterPack; -import com.darkona.adventurebackpack.inventory.InventorySteamJetpack; -import com.darkona.adventurebackpack.item.*; +import com.darkona.adventurebackpack.item.IBackWearableItem; +import com.darkona.adventurebackpack.item.ItemAdventureBackpack; +import com.darkona.adventurebackpack.item.ItemAdventureHat; +import com.darkona.adventurebackpack.item.ItemCoalJetpack; +import com.darkona.adventurebackpack.item.ItemCopterPack; +import com.darkona.adventurebackpack.item.ItemHose; +import com.darkona.adventurebackpack.item.ItemPistonBoots; import com.darkona.adventurebackpack.playerProperties.BackpackProperty; -import com.darkona.adventurebackpack.reference.BackpackNames; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; +import com.darkona.adventurebackpack.reference.BackpackTypes; /** * Created on 11/10/2014 - * @author Darkona * + * @author Darkona */ public class Wearing { - public static boolean isWearingWearable(EntityPlayer player){ + public enum WearableType + { + BACKPACK, COPTERPACK, JETPACK, UNKNOWN; + + public static WearableType get(@Nonnull ItemStack stack) + { + Item item = stack.getItem(); + if (item == ModItems.adventureBackpack) + return BACKPACK; + if (item == ModItems.copterPack) + return COPTERPACK; + if (item == ModItems.coalJetpack) + return JETPACK; + return UNKNOWN; + } + } + + // Wearable + public static boolean isWearingWearable(EntityPlayer player) + { return BackpackProperty.get(player).getWearable() != null && BackpackProperty.get(player).getWearable().getItem() instanceof IBackWearableItem; } public static ItemStack getWearingWearable(EntityPlayer player) { - return isWearingWearable(player) ? BackpackProperty.get(player).getWearable() : null; + return isWearingWearable(player) ? BackpackProperty.get(player).getWearable() : null; } - public static boolean isHoldingWearable(EntityPlayer player){ - return player.inventory.getCurrentItem()!= null && player.inventory.getCurrentItem().getItem() instanceof IBackWearableItem; + public static WearableType getWearingWearableType(EntityPlayer player) + { + return isWearingWearable(player) ? WearableType.get(BackpackProperty.get(player).getWearable()) : WearableType.UNKNOWN; } - public static boolean isWearingCopter(EntityPlayer player) + public static IInventoryTanks getWearingWearableInv(EntityPlayer player) { - return BackpackProperty.get(player).getWearable() != null && BackpackProperty.get(player).getWearable().getItem() instanceof ItemCopterPack; + ItemStack wearable = Wearing.getWearingWearable(player); + if (wearable.getItem() instanceof ItemAdventureBackpack) + return new InventoryBackpack(wearable); + if (wearable.getItem() instanceof ItemCoalJetpack) + return new InventoryCoalJetpack(wearable); + if (wearable.getItem() instanceof ItemCopterPack) + return new InventoryCopterPack(wearable); + return null; } - public static ItemStack getWearingCopter(EntityPlayer player) + public static boolean isHoldingWearable(EntityPlayer player) { - return isWearingCopter(player) ? BackpackProperty.get(player).getWearable() : null; + return player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() instanceof IBackWearableItem; } - public static boolean isHoldingSteam(EntityPlayer player) + // Backpack + public static boolean isWearingBackpack(EntityPlayer player) { - return player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() instanceof ItemSteamJetpack; + return BackpackProperty.get(player).getWearable() != null && BackpackProperty.get(player).getWearable().getItem() instanceof ItemAdventureBackpack; } - public static ItemStack getHoldingSteam(EntityPlayer player) + public static boolean isWearingTheRightBackpack(EntityPlayer player, BackpackTypes... backpacks) { - return isHoldingSteam(player) ? player.inventory.getCurrentItem() : null; + if (Wearing.isWearingBackpack(player)) + { + for (BackpackTypes type : backpacks) + { + if (BackpackTypes.getType(Wearing.getWearingBackpack(player)) == type) + return true; + } + } + return false; } - public static boolean isWearingSteam(EntityPlayer player) + public static ItemStack getWearingBackpack(EntityPlayer player) { - return BackpackProperty.get(player).getWearable() != null && BackpackProperty.get(player).getWearable().getItem() instanceof ItemSteamJetpack; + return isWearingBackpack(player) ? BackpackProperty.get(player).getWearable() : null; } - public static ItemStack getWearingSteam(EntityPlayer player) + public static InventoryBackpack getWearingBackpackInv(EntityPlayer player) { - return isWearingSteam(player) ? BackpackProperty.get(player).getWearable() : null; + return new InventoryBackpack(BackpackProperty.get(player).getWearable()); } - public static boolean isHoldingCopter(EntityPlayer player) + public static boolean isHoldingBackpack(EntityPlayer player) { - return player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() instanceof ItemCopterPack; + return player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() instanceof ItemAdventureBackpack; } - public static ItemStack getHoldingCopter(EntityPlayer player) + public static ItemStack getHoldingBackpack(EntityPlayer player) { - return isHoldingCopter(player) ? player.inventory.getCurrentItem() : null; + return isHoldingBackpack(player) ? player.inventory.getCurrentItem() : null; } + public static InventoryBackpack getHoldingBackpackInv(EntityPlayer player) + { + return new InventoryBackpack(player.getCurrentEquippedItem()); + } - public static boolean isWearingBoots(EntityPlayer player) + // Copter + public static boolean isWearingCopter(EntityPlayer player) { - return player.inventory.armorInventory[0] != null && player.inventory.armorInventory[0].getItem() instanceof ItemPistonBoots; + return BackpackProperty.get(player).getWearable() != null && BackpackProperty.get(player).getWearable().getItem() instanceof ItemCopterPack; } - public static boolean isWearingHat(EntityPlayer player) + public static ItemStack getWearingCopter(EntityPlayer player) { - return player.inventory.armorInventory[3] != null && player.inventory.armorInventory[3].getItem() instanceof ItemAdventureHat; + return isWearingCopter(player) ? BackpackProperty.get(player).getWearable() : null; } - public static boolean isWearingBackpack(EntityPlayer player) + public static boolean isHoldingCopter(EntityPlayer player) { - return BackpackProperty.get(player).getWearable() != null && BackpackProperty.get(player).getWearable().getItem() instanceof ItemAdventureBackpack; + return player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() instanceof ItemCopterPack; } - public static boolean isHoldingBackpack(EntityPlayer player) + public static ItemStack getHoldingCopter(EntityPlayer player) { - return player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() instanceof ItemAdventureBackpack; + return isHoldingCopter(player) ? player.inventory.getCurrentItem() : null; } - public static ItemStack getWearingHat(EntityPlayer player) + // Jetpack + public static boolean isWearingJetpack(EntityPlayer player) { - if (isWearingHat(player)) return player.inventory.armorInventory[3]; - return null; + return BackpackProperty.get(player).getWearable() != null && BackpackProperty.get(player).getWearable().getItem() instanceof ItemCoalJetpack; } - public static ItemStack getWearingBackpack(EntityPlayer player) + public static ItemStack getWearingJetpack(EntityPlayer player) { - return isWearingBackpack(player) ? BackpackProperty.get(player).getWearable() : null; + return isWearingJetpack(player) ? BackpackProperty.get(player).getWearable() : null; } - public static ItemStack getHoldingBackpack(EntityPlayer player) + public static boolean isHoldingJetpack(EntityPlayer player) { - if (isHoldingBackpack(player)) - { - return player.inventory.getCurrentItem(); - } - return null; + return player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() instanceof ItemCoalJetpack; } - public static ItemStack getWearingBoots(EntityPlayer player) + public static ItemStack getHoldingJetpack(EntityPlayer player) { - return isWearingBoots(player) ? player.inventory.armorInventory[0] : null; + return isHoldingJetpack(player) ? player.inventory.getCurrentItem() : null; } - /** - * Will return a backpack inventory from a backpack in the slot if true, or in the hand if false. - * - * @param player the player - * @param wearing boolean flag - * @return - */ - public static InventoryBackpack getBackpackInv(EntityPlayer player, boolean wearing) + // Hose + public static boolean isHoldingHose(EntityPlayer player) { - return new InventoryBackpack((wearing) ? BackpackProperty.get(player).getWearable() : player.getCurrentEquippedItem()); + return player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() instanceof ItemHose; } - public static boolean isWearingTheRightBackpack(EntityPlayer player, String... backpacks) + public static ItemStack getHoldingHose(EntityPlayer player) { - if(Wearing.isWearingBackpack(player)) - { - for(String name : backpacks) - { - if(BackpackNames.getBackpackColorName(Wearing.getWearingBackpack(player)).equals(name)) - { - return true; - } - } - } - return false; + return isHoldingHose(player) ? player.inventory.getCurrentItem() : null; } - public static IInventoryTanks getWearableInv(EntityPlayer player) + // Armor + public static boolean isWearingHat(EntityPlayer player) { - ItemStack wearable = Wearing.getWearingWearable(player); - if(wearable.getItem() instanceof ItemAdventureBackpack)return new InventoryBackpack(wearable); - if (wearable.getItem() instanceof ItemSteamJetpack) return new InventorySteamJetpack(wearable); - if (wearable.getItem() instanceof ItemCopterPack) return new InventoryCopterPack(wearable); - return null; + return player.inventory.armorInventory[3] != null && player.inventory.armorInventory[3].getItem() instanceof ItemAdventureHat; + } + + public static ItemStack getWearingHat(EntityPlayer player) + { + return isWearingHat(player) ? player.inventory.armorInventory[3] : null; + } + + public static boolean isWearingBoots(EntityPlayer player) + { + return player.inventory.armorInventory[0] != null && player.inventory.armorInventory[0].getItem() instanceof ItemPistonBoots; + } + + public static ItemStack getWearingBoots(EntityPlayer player) + { + return isWearingBoots(player) ? player.inventory.armorInventory[0] : null; } } diff --git a/src/main/java/com/darkona/adventurebackpack/util/calendar/CalendarDate.java b/src/main/java/com/darkona/adventurebackpack/util/calendar/CalendarDate.java index 7d79ec4c..3ab33215 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/calendar/CalendarDate.java +++ b/src/main/java/com/darkona/adventurebackpack/util/calendar/CalendarDate.java @@ -59,7 +59,8 @@ public boolean areDatesEqual(CalendarDate date) (year == date.getYear())) { return true; - } else + } + else { return false; } diff --git a/src/main/java/com/darkona/adventurebackpack/util/calendar/CalendarImpl.java b/src/main/java/com/darkona/adventurebackpack/util/calendar/CalendarImpl.java index 2da8b656..9ce2ffe6 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/calendar/CalendarImpl.java +++ b/src/main/java/com/darkona/adventurebackpack/util/calendar/CalendarImpl.java @@ -37,7 +37,8 @@ public int getLastDayOfGregorianMonth(int month, int year) ((year % 400) != 300)) { return 29; - } else + } + else { return month_list[month - 1]; } @@ -108,7 +109,8 @@ public boolean hebrewLeapYear(int year) if ((((year * 7) + 1) % 19) < 7) { return true; - } else + } + else { return false; } @@ -119,7 +121,8 @@ public int getLastMonthOfJewishYear(int year) if (hebrewLeapYear(year)) { return 13; - } else + } + else { return 12; } @@ -199,7 +202,8 @@ private int hebrewCalendarElapsedDays(int year) /* Then postpone Rosh HaShanah one day */ { alternativeDay = day + 1; - } else + } + else { alternativeDay = day; } @@ -228,7 +232,8 @@ private boolean longHeshvan(int year) if ((daysInHebrewYear(year) % 10) == 5) { return true; - } else + } + else { return false; } @@ -239,7 +244,8 @@ private boolean shortKislev(int year) if ((daysInHebrewYear(year) % 10) == 3) { return true; - } else + } + else { return false; } @@ -268,7 +274,8 @@ public int absoluteFromJewishDate(CalendarDate date) value = getLastDayOfJewishMonth(m, date.getYear()); returnValue += value; } - } else + } + else { for (m = 7; m < date.getMonth(); m++) { @@ -310,7 +317,8 @@ public CalendarDate jewishDateFromAbsolute(int absDate) if (absDate < temp) { start = 7; - } else + } + else { start = 1; } diff --git a/src/main/java/com/darkona/adventurebackpack/util/calendar/ChineseCalendar.java b/src/main/java/com/darkona/adventurebackpack/util/calendar/ChineseCalendar.java index 79b1220f..ffe0cae8 100644 --- a/src/main/java/com/darkona/adventurebackpack/util/calendar/ChineseCalendar.java +++ b/src/main/java/com/darkona/adventurebackpack/util/calendar/ChineseCalendar.java @@ -48,11 +48,13 @@ public static void generateChineseCalendar(String[] arg) { String[] t = c.getYearTable(); for (int i = 0; i < t.length; i++) System.out.println(t[i]); - } else if (cmd.equalsIgnoreCase("month")) + } + else if (cmd.equalsIgnoreCase("month")) { String[] t = c.getMonthTable(); for (int i = 0; i < t.length; i++) System.out.println(t[i]); - } else + } + else { System.out.println(c.toString()); } @@ -248,19 +250,22 @@ public static int daysInChineseMonth(int y, int m) v = chineseMonths[2 * index]; l = m - 1; if (((v >> l) & 0x01) == 1) d = 29; - } else if (9 <= m && m <= 12) + } + else if (9 <= m && m <= 12) { v = chineseMonths[2 * index + 1]; l = m - 9; if (((v >> l) & 0x01) == 1) d = 29; - } else + } + else { // leap month v = chineseMonths[2 * index + 1]; v = (v >> 4) & 0x0F; if (v != Math.abs(m)) { d = 0; // wrong m specified - } else + } + else { d = 29; for (int i = 0; i < bigLeapMonthYears.length; i++) @@ -511,16 +516,20 @@ public String getDateString() if (gregorianDate == sectionalTerm) { str = " ST" + gm; - } else if (gregorianDate == principleTerm) + } + else if (gregorianDate == principleTerm) { str = " PT" + gm; - } else if (chineseDate == 1 && chineseMonth > 0) + } + else if (chineseDate == 1 && chineseMonth > 0) { str = " CM" + cm; - } else if (chineseDate == 1 && chineseMonth < 0) + } + else if (chineseDate == 1 && chineseMonth < 0) { str = "*CM" + cm; - } else + } + else { str = gd + '/' + cd; } diff --git a/src/main/java/copy/betterstorage/utils/ReflectionUtils.java b/src/main/java/copy/betterstorage/utils/ReflectionUtils.java deleted file mode 100644 index 56b76473..00000000 --- a/src/main/java/copy/betterstorage/utils/ReflectionUtils.java +++ /dev/null @@ -1,193 +0,0 @@ -package copy.betterstorage.utils; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * Created on 26/12/2014 - * - * @author copygirl - */ -public class ReflectionUtils -{ - - private static Map cachedFields = new HashMap(); - - - private static Map cachedMethods = new HashMap(); - - private ReflectionUtils() - { - } - - - public static Field findField(Class clazz, String srgName, String mcpName) - { - try - { - for (String name : new String[]{srgName, mcpName}) - { - Cache fieldCache = new Cache(clazz, name); - Field field = cachedFields.get(fieldCache); - if (field == null) - { - try - { - field = clazz.getDeclaredField(name); - } catch (NoSuchFieldException ex) - { - continue; - } - if (field == null) continue; - field.setAccessible(true); - cachedFields.put(fieldCache, field); - } - return field; - } - } catch (SecurityException ex) - { - throw new RuntimeException(ex); - } - throw new RuntimeException(String.format("Could not find field '%s' for class %s", mcpName, clazz.getName())); - } - - public static void set(Class clazz, U instance, String srgName, String mcpName, V value) - { - try - { - findField(clazz, srgName, mcpName).set(instance, value); - } catch (IllegalArgumentException ex) - { - throw new RuntimeException(ex); - } catch (IllegalAccessException ex) - { - throw new RuntimeException(ex); - } - } - - public static V get(Class clazz, U instance, String srgName, String mcpName) - { - try - { - return (V) findField(clazz, srgName, mcpName).get(instance); - } catch (IllegalArgumentException ex) - { - throw new RuntimeException(ex); - } catch (IllegalAccessException ex) - { - throw new RuntimeException(ex); - } - } - - - public static Method findMethod(Class clazz, String srgName, String mcpName, Class... parameterTypes) - { - try - { - for (String name : new String[]{srgName, mcpName}) - { - MethodCache methodCache = new MethodCache(clazz, name, parameterTypes); - Method method = cachedMethods.get(methodCache); - if (method == null) - { - try - { - method = clazz.getDeclaredMethod(name, parameterTypes); - } catch (NoSuchMethodException ex) - { - continue; - } - if (method == null) continue; - method.setAccessible(true); - cachedMethods.put(methodCache, method); - } - return method; - } - } catch (SecurityException ex) - { - throw new RuntimeException(ex); - } - throw new RuntimeException(String.format("Could not find method '%s' for class %s", mcpName, clazz.getName())); - } - - public static V invoke(Class clazz, U instance, String srgName, String mcpName, Object... args) - { - Class[] parameterTypes = new Class[args.length / 2]; - Object[] parameters = new Object[args.length / 2]; - for (int i = 0; i < args.length / 2; i++) - { - parameterTypes[i] = (Class) args[i]; - parameters[i] = args[args.length / 2 + i]; - } - try - { - return (V) findMethod(clazz, srgName, mcpName, parameterTypes).invoke(instance, parameters); - } catch (IllegalAccessException ex) - { - throw new RuntimeException(ex); - } catch (IllegalArgumentException ex) - { - throw new RuntimeException(ex); - } catch (InvocationTargetException ex) - { - throw new RuntimeException(ex); - } - } - - - private static class Cache - { - public final Class clazz; - public final String name; - - public Cache(Class clazz, String name) - { - this.clazz = clazz; - this.name = name; - } - - @Override - public boolean equals(Object obj) - { - if (!(obj instanceof Cache)) return false; - Cache cache = (Cache) obj; - return ((cache.clazz == clazz) && (cache.name.equals(name))); - } - - @Override - public int hashCode() - { - return (clazz.hashCode() ^ name.hashCode()); - } - } - - private static class MethodCache extends Cache - { - public final Class[] types; - - public MethodCache(Class clazz, String name, Class... parameterTypes) - { - super(clazz, name); - this.types = parameterTypes; - } - - @Override - public boolean equals(Object obj) - { - if (!(obj instanceof MethodCache)) return false; - MethodCache cache = (MethodCache) obj; - return (super.equals(cache) && Arrays.equals(cache.types, types)); - } - - @Override - public int hashCode() - { - return (super.hashCode() ^ Arrays.hashCode(types)); - } - } - -} diff --git a/src/main/resources/META-INF/adventurebackpack_at.cfg b/src/main/resources/META-INF/adventurebackpack_at.cfg new file mode 100644 index 00000000..a9371e12 --- /dev/null +++ b/src/main/resources/META-INF/adventurebackpack_at.cfg @@ -0,0 +1 @@ +protected net.minecraft.inventory.InventoryCrafting field_70466_a # stackList \ No newline at end of file diff --git a/src/main/resources/assets/adventurebackpack/lang/en_US.lang b/src/main/resources/assets/adventurebackpack/lang/en_US.lang index 3449ee99..24e40d74 100644 --- a/src/main/resources/assets/adventurebackpack/lang/en_US.lang +++ b/src/main/resources/assets/adventurebackpack/lang/en_US.lang @@ -1,4 +1,4 @@ -# Items +# Items THIS IS ALL UPDATED ALL OF THE OTHER LANGUAGE IS NOT ## Component Items For Crafting item.adventurebackpack:backpackComponent.name=Backpack Component Item @@ -12,6 +12,9 @@ item.adventurebackpack:hydroBlades.name=Hydro Blades item.adventurebackpack:inflatableBoat.name=Inflatable Boat item.adventurebackpack:inflatableBoatMotorized.name=Inflatable Boat (Motorized) +## Entity +entity.adventurebackpack.inflatableBoat.name=Inflatable Boat + ## Tools and consumables item.adventurebackpack:clockworkCrossbow.name=Clockwork Crossbow item.adventurebackpack:melonJuiceBottle.name=Melon Juice Bottle @@ -30,25 +33,26 @@ item.adventurebackpack:hoseUseless.name=Hose: Useless / No Backpack ## Wearables item.adventurebackpack:adventureBackpack.name=Adventure Backpack item.adventurebackpack:copterPack.name=Copter Pack -item.adventurebackpack:steamJetpack.name=Steam Jetpack +item.adventurebackpack:coalJetpack.name=Coal Jetpack ## Armor -item.adventurebackpack:adventureSuit.name=Adventurer's Suit item.adventurebackpack:adventureHat.name=Adventurer's Fedora +item.adventurebackpack:adventureSuit.name=Adventurer's Suit +item.adventurebackpack:adventurePants.name=Adventurer's Pants item.adventurebackpack:pistonBoots.name=Piston Boots ## Blocks -block.adventurebackpack:AdventureBackpack.name=Adventure Backpack Block -block.adventurebackpack:CampFire.name=Campfire -block.adventurebackpack:SleepingBag.name=Sleeping Bag +blockAdventureBackpack.name=Adventure Backpacks +blockCampFire.name=CampFire +blockSleepingBag.name=Sleeping Bag ## CreativeTab -itemGroup.adventurebackpack=Adventure Backpack +itemGroup.adventurebackpack=Adventure Backpack Mod ## Keybindings keys.adventureBackpack.category=Adventure Backpack -keys.adventureBackpack.openBackpackInventory=Open Inventory Key -keys.adventureBackpack.switchHoseTank=Toggle Action Key +keys.adventureBackpack.openInventory=Open Inventory +keys.adventureBackpack.toggleActions=Toggle Actions ## Fluids fluid.melonJuice=Melon Juice @@ -56,13 +60,144 @@ fluid.milk=Milk fluid.mushrromstew=Mushroom Stew ## Messages -adventurebackpack:messages.already.equipped=You are already equipping a backpack. +adventurebackpack:messages.already.equipped.backpack=You are already equipping an Adventure Backpack. +adventurebackpack:messages.already.equipped.copterpack=You are already equipping a Copter Pack. +adventurebackpack:messages.already.equipped.jetpack=You are already equipping a Coal Jetpack. adventurebackpack:messages.already.impossibru=You aren't wearing any backpacks. +adventurebackpack:messages.backpack.cant.bag=Can't deploy the sleeping bag! Check the surrounding area. +adventurebackpack:messages.cant.sleep.here=Ancient forces do not welcome sleep here. adventurebackpack:messages.copterpack.hover=CopterPack: Hover Mode. adventurebackpack:messages.copterpack.normal=CopterPack: Normal Mode. adventurebackpack:messages.copterpack.outoffuel=CopterPack: Out of fuel. adventurebackpack:messages.copterpack.cantwater=CopterPack: Can't function in water. adventurebackpack:messages.copterpack.off=CopterPack: Off. -adventurebackpack:messages.jetpack.on=Steam Jetpack: On. -adventurebackpack:messages.jetpack.off=Steam Jetpack: Off. +adventurebackpack:messages.jetpack.on=Coal Jetpack: On. +adventurebackpack:messages.jetpack.off=Coal Jetpack: Off. +adventurebackpack:messages.nightvision.on=Night Vision: On. +adventurebackpack:messages.nightvision.off=Night Vision: Off. +adventurebackpack:messages.cycling.on=Tool Cycling: On. +adventurebackpack:messages.cycling.off=Tool Cycling: Off. adventurebackpack:messages.crossbow.outofammo=Clockwork Crossbow: Out of ammo. + +## Tooltips +adventurebackpack:tooltips.on=ON +adventurebackpack:tooltips.off=OFF +adventurebackpack:tooltips.empty=Empty +adventurebackpack:tooltips.meters=meters +adventurebackpack:tooltips.error=Error +adventurebackpack:tooltips.steam=Steam +adventurebackpack:tooltips.press=Press +adventurebackpack:tooltips.hold.shift=Hold Shift +adventurebackpack:tooltips.hold.ctrl=Hold Ctrl +adventurebackpack:tooltips.mouse.wheel=Wheel +adventurebackpack:tooltips.max.altitude=Maximum altitude + +adventurebackpack:tooltips.backpack.slots.used=Slots used +adventurebackpack:tooltips.backpack.tank.left=Left Tank +adventurebackpack:tooltips.backpack.tank.right=Right Tank +adventurebackpack:tooltips.backpack.cycling=Tool Cycling +adventurebackpack:tooltips.backpack.cycling.key1=while wearing +adventurebackpack:tooltips.backpack.cycling.key2=backpack, for turn cycling +adventurebackpack:tooltips.backpack.vision=Night Vision +adventurebackpack:tooltips.backpack.vision.key1=while wearing +adventurebackpack:tooltips.backpack.vision.key2=backpack, for turn nightvision + +adventurebackpack:tooltips.jetpack.fuel=Fuel +adventurebackpack:tooltips.jetpack.tank.water=Left Tank +adventurebackpack:tooltips.jetpack.tank.steam=Right Tank +adventurebackpack:tooltips.jetpack.key.onoff1=while wearing +adventurebackpack:tooltips.jetpack.key.onoff2=jetpack, for turn it + +adventurebackpack:tooltips.copter.tank.fuel=Fuel Tank +adventurebackpack:tooltips.copter.rate.fuel=Fuel consumption rate +adventurebackpack:tooltips.copter.key.onoff1=while wearing +adventurebackpack:tooltips.copter.key.onoff2=copterpack, for turn it +adventurebackpack:tooltips.copter.key.hover1=during flight to +adventurebackpack:tooltips.copter.key.hover2=switch hover mode + +adventurebackpack:tooltips.hose.key.header=While holding Hose: +adventurebackpack:tooltips.hose.key.tank=to change active tank +adventurebackpack:tooltips.hose.key.mode=to change mode +adventurebackpack:tooltips.hose.dump1=Put Hose into bucketOut slot of wearable pack +adventurebackpack:tooltips.hose.dump2=to empty corresponded tank +adventurebackpack:tooltips.hose.dump.warn=WARNING! Fluid will be dumped and lost. Forever. + +## Skins +adventurebackpack:skin.name.standard=Standard +adventurebackpack:skin.name.bat=Bat +adventurebackpack:skin.name.black=Black +adventurebackpack:skin.name.blaze=Blaze +adventurebackpack:skin.name.blue=Blue +adventurebackpack:skin.name.bookshelf=Bookshelf +adventurebackpack:skin.name.brown=Brown +adventurebackpack:skin.name.brown_mushroom=Brown Mushroom +adventurebackpack:skin.name.cactus=Cactus +adventurebackpack:skin.name.cake=Cake +adventurebackpack:skin.name.carrot=Carrot +adventurebackpack:skin.name.chest=Chest +adventurebackpack:skin.name.chicken=Chicken +adventurebackpack:skin.name.coal=Coal +adventurebackpack:skin.name.cookie=Cookie +adventurebackpack:skin.name.cow=Cow +adventurebackpack:skin.name.creeper=Creeper +adventurebackpack:skin.name.cyan=Cyan +adventurebackpack:skin.name.deluxe=Deluxe +adventurebackpack:skin.name.diamond=Diamond +adventurebackpack:skin.name.dragon=Dragon +adventurebackpack:skin.name.egg=Egg +adventurebackpack:skin.name.electric=Electric +adventurebackpack:skin.name.emerald=Emerald +adventurebackpack:skin.name.end=End +adventurebackpack:skin.name.enderman=Enderman +adventurebackpack:skin.name.ghast=Ghast +adventurebackpack:skin.name.glowstone=Glowstone +adventurebackpack:skin.name.gold=Gold +adventurebackpack:skin.name.gray=Gray +adventurebackpack:skin.name.green=Green +adventurebackpack:skin.name.haybale=Haybale +adventurebackpack:skin.name.horse=Horse +adventurebackpack:skin.name.iron=Iron +adventurebackpack:skin.name.iron_golem=Iron Golem +adventurebackpack:skin.name.lapis=Lapis +adventurebackpack:skin.name.leather=Leather +adventurebackpack:skin.name.light_blue=Light Blue +adventurebackpack:skin.name.light_gray=Light Gray +adventurebackpack:skin.name.lime=Lime +adventurebackpack:skin.name.magenta=Magenta +adventurebackpack:skin.name.magma_cube=Magma Cube +adventurebackpack:skin.name.melon=Melon +adventurebackpack:skin.name.modded_network=Modded Network +adventurebackpack:skin.name.mooshroom=Mooshroom +adventurebackpack:skin.name.nether=Nether +adventurebackpack:skin.name.obsidian=Obsidian +adventurebackpack:skin.name.ocelot=Ocelot +adventurebackpack:skin.name.orange=Orange +adventurebackpack:skin.name.overworld=Overworld +adventurebackpack:skin.name.pig=Pig +adventurebackpack:skin.name.pigman=Pigman +adventurebackpack:skin.name.pink=Pink +adventurebackpack:skin.name.pumpkin=Pumpkin +adventurebackpack:skin.name.purple=Purple +adventurebackpack:skin.name.quartz=Quartz +adventurebackpack:skin.name.rainbow=Rainbow +adventurebackpack:skin.name.red=Red +adventurebackpack:skin.name.red_mushroom=Red Mushroom +adventurebackpack:skin.name.redstone=Redstone +adventurebackpack:skin.name.sandstone=Sandstone +adventurebackpack:skin.name.sheep=Sheep +adventurebackpack:skin.name.silverfish=Silverfish +adventurebackpack:skin.name.skeleton=Skeleton +adventurebackpack:skin.name.slime=Slime +adventurebackpack:skin.name.snow=Snow +adventurebackpack:skin.name.spider=Spider +adventurebackpack:skin.name.sponge=Sponge +adventurebackpack:skin.name.squid=Squid +adventurebackpack:skin.name.sunflower=Sunflower +adventurebackpack:skin.name.villager=Villager +adventurebackpack:skin.name.white=White +adventurebackpack:skin.name.wither=Wither +adventurebackpack:skin.name.wither_skeleton=Wither Skeleton +adventurebackpack:skin.name.wolf=Wolf +adventurebackpack:skin.name.yellow=Yellow +adventurebackpack:skin.name.zombie=Zombie +adventurebackpack:skin.name.unknown=UNKNOWN \ No newline at end of file diff --git a/src/main/resources/assets/adventurebackpack/lang/pt_BR.lang b/src/main/resources/assets/adventurebackpack/lang/pt_BR.lang index 369449ef..058c4aff 100644 --- a/src/main/resources/assets/adventurebackpack/lang/pt_BR.lang +++ b/src/main/resources/assets/adventurebackpack/lang/pt_BR.lang @@ -22,12 +22,12 @@ item.adventurebackpack:hose_rightTank_spill.name=Mangueira: Tanque Direito / Mod item.adventurebackpack:hose_rightTank_drink.name=Mangueira: Tanque Direito / Modo Beber item.adventurebackpack:hoseUseless.name=Mangueira: Inútil / Sem Mochila -item.adventurebackpack:copterPack.name= +item.adventurebackpack:copterPack.name=MochiloCóptero #Blocks -block.adventurebackpack:blockAdventureBackpack.name=Base Para Mochila do Aventureiro +block.adventurebackpack:blockAdventureBackpack.name=Mochila do Aventureiro #CreativeTab -itemGroup.adventurebackpack=Mochila do Aventureiro +itemGroup.adventurebackpack=Mochilas dos Aventureiros #Keybindings keys.adventureBackpack.category=Mochila do Aventureiro @@ -37,4 +37,4 @@ keys.adventureBackpack.switchHoseTank=Trocar a Mangueira do Tanque #Fluids fluid.melonJuice=Suco de Melancia fluid.milk=Leite -fluid.mushroomstew= \ No newline at end of file +fluid.mushroomstew=Ensopado de Cogumelos diff --git a/src/main/resources/assets/adventurebackpack/lang/ru_RU.lang b/src/main/resources/assets/adventurebackpack/lang/ru_RU.lang index c40db1ca..dcb791a4 100644 --- a/src/main/resources/assets/adventurebackpack/lang/ru_RU.lang +++ b/src/main/resources/assets/adventurebackpack/lang/ru_RU.lang @@ -1,54 +1,58 @@ -# Items +#Перевод сделан pingvikin ## Component Items For Crafting item.adventurebackpack:backpackComponent.name=Компонент рюкзака item.adventurebackpack:sleepingBag.name=Спальный мешок -item.adventurebackpack:backpackTank.name=Резервуар для жидкости рюкзака -item.adventurebackpack:macheteHandle=Ручка от мачете -item.adventurebackpack:hoseHead.name=Наконечник для трубки +item.adventurebackpack:backpackTank.name=Бак для жидкости +item.adventurebackpack:macheteHandle.name=Ручка от мачете +item.adventurebackpack:hoseHead.name=Наконечник шланга item.adventurebackpack:copterEngine.name=Двухцилиндровый дизельный двигатель item.adventurebackpack:copterBlades.name=Вертолётные лопасти item.adventurebackpack:hydroBlades.name=Водяные лопасти item.adventurebackpack:inflatableBoat.name=Надувная лодка item.adventurebackpack:inflatableBoatMotorized.name=Надувная лодка с мотором +## Entity +entity.adventurebackpack.inflatableBoat.name=Надувная лодка + ## Tools and consumables item.adventurebackpack:clockworkCrossbow.name=Арбалет с часовым механизмом item.adventurebackpack:melonJuiceBottle.name=Бутылка с арбузным соком item.adventurebackpack:machete.name=Мачете -item.adventurebackpack:backpackHose.name=Трубка для жидкостей рюкзака -item.adventurebackpack:hose_leftTank_suck.name=Трубка для жидкостей: Левая ёмкость / Режим закачивания -item.adventurebackpack:hose_leftTank_spill.name=Трубка для жидкостей: Левая ёмкость / Режим откачивания -item.adventurebackpack:hose_leftTank_drink.name=Трубка для жидкостей: Левая ёмкость / Режим питья +item.adventurebackpack:backpackHose.name=Шланг для рюкзака +item.adventurebackpack:hose_leftTank_suck.name=Шланг: Левый бак / Режим закачивания +item.adventurebackpack:hose_leftTank_spill.name=Шланг: Левый бак / Режим откачивания +item.adventurebackpack:hose_leftTank_drink.name=Шланг: Левый бак / Режим питья -item.adventurebackpack:hose_rightTank_suck.name=Трубка для жидкостей: Правая ёмкость / Режим закачивания -item.adventurebackpack:hose_rightTank_spill.name=Трубка для жидкостей: Правая ёмкость / Режим откачивания -item.adventurebackpack:hose_rightTank_drink.name=Трубка для жидкостей: Правая ёмкость / Режим питья -item.adventurebackpack:hoseUseless.name=Трубка для жидкостей: Не используется / Нет рюкзака +item.adventurebackpack:hose_rightTank_suck.name=Шланг: Правый бак / Режим закачивания +item.adventurebackpack:hose_rightTank_spill.name=Шланг: Правый бак / Режим откачивания +item.adventurebackpack:hose_rightTank_drink.name=Шланг: Правый бак / Режим питья +item.adventurebackpack:hoseUseless.name=Шланг: Не используется / Нет рюкзака ## Wearables -item.adventurebackpack:adventureBackpack.name=Рюкзак искателя приключений +item.adventurebackpack:adventureBackpack.name=Рюкзак путешественника item.adventurebackpack:copterPack.name=Вертолётный ранец -item.adventurebackpack:steamJetpack.name=Паровой ранец +item.adventurebackpack:coalJetpack.name=Паровой ранец ## Armor -item.adventurebackpack:adventureSuit.name=Костюм искателя приключений -item.adventurebackpack:adventureHat.name=Фетровая шляпа искателя приключений +item.adventurebackpack:adventureSuit.name=Дублёнка +item.adventurebackpack:adventureHat.name=Фетровая шляпа +item.adventurebackpack:adventurePants.name=Дублёные штаны item.adventurebackpack:pistonBoots.name=Поршневые ботинки ## Blocks -block.adventurebackpack:blockAdventureBackpack.name=Основа рюкзака искателя приключений -block.adventurebackpack:blockCampFire.name=Костёр -block.adventurebackpack:blockSleepingBag.name=Спальный мешок +blockAdventureBackpack.name=Рюкзак путешественника +blockCampFire.name=Костёр +blockSleepingBag.name=Спальный мешок ## CreativeTab -itemGroup.adventurebackpack=Рюкзак искателя приключений +itemGroup.adventurebackpack=Рюкзак путешественника ## Keybindings -keys.adventureBackpack.category=Рюкзак искателя приключений -keys.adventureBackpack.openBackpackInventory=Открыть инвентарь рюкзака -keys.adventureBackpack.switchHoseTank=Сменить используемый резервуар +keys.adventureBackpack.category=Рюкзак путешественника +keys.adventureBackpack.openInventory=Открыть инвентарь +keys.adventureBackpack.toggleActions=Toggle Actions ## Fluids fluid.melonJuice=Арбузный сок @@ -56,13 +60,144 @@ fluid.milk=Молоко fluid.mushrromstew=Тушеные грибы ## Messages -adventurebackpack:already.equipped=Рюкзак уже надет на вас. +adventurebackpack:messages.already.equipped.backpack=Рюкзак уже надет на вас. +adventurebackpack:messages.already.equipped.copterpack=Вертолётный ранец уже надет. +adventurebackpack:messages.already.equipped.jetpack=Паровой ранец уже надет. adventurebackpack:messages.already.impossibru=Вы не можете надеть больше рюкзаков. -adventurebackpack:messages.copterpack.hover=Вертолётный ранец: Режим зависания. +adventurebackpack:messages.backpack.cant.bag=Недостаточно места, для установки спального мешка. +adventurebackpack:messages.cant.sleep.here=Древние силы не дают вам уснуть. +adventurebackpack:messages.copterpack.hover=Вертолётный ранец: Режим парения. adventurebackpack:messages.copterpack.normal=Вертолётный ранец: Обычный режим. adventurebackpack:messages.copterpack.outoffuel=Вертолётный ранец: Нет топлива. adventurebackpack:messages.copterpack.cantwater=Вертолётный ранец: Невозможно работать в воде. adventurebackpack:messages.copterpack.off=Вертолётный ранец: Выключен. adventurebackpack:messages.jetpack.on=Паровой ранец: Включен. adventurebackpack:messages.jetpack.off=Паровой ранец: Выключен. +adventurebackpack:messages.nightvision.on=Ночное зрение: Включено. +adventurebackpack:messages.nightvision.off=Ночное зрение: Выключено. +adventurebackpack:messages.cycling.on=Карманы для инструментов: Включены. +adventurebackpack:messages.cycling.off=Карманы для инструментов: Выключены. adventurebackpack:messages.crossbow.outofammo=Арбалет с часовым механизмом: Нет боеприпасов. + +## Tooltips +adventurebackpack:tooltips.on=ВКЛ +adventurebackpack:tooltips.off=ВЫКЛ +adventurebackpack:tooltips.empty=Пусто +adventurebackpack:tooltips.meters=метров +adventurebackpack:tooltips.error=Ошибка +adventurebackpack:tooltips.steam=Пар +adventurebackpack:tooltips.press=Нажмите +adventurebackpack:tooltips.hold.shift=Удерживайте Shift +adventurebackpack:tooltips.hold.ctrl=Удерживайте Ctrl +adventurebackpack:tooltips.mouse.wheel=Wheel +adventurebackpack:tooltips.max.altitude=Максмальная высота + +adventurebackpack:tooltips.backpack.slots.used=Доступные слоты +adventurebackpack:tooltips.backpack.tank.left=Левый бак +adventurebackpack:tooltips.backpack.tank.right=Правый бак +adventurebackpack:tooltips.backpack.cycling=Карманы для инструментов +adventurebackpack:tooltips.backpack.cycling.key1=во время ношения +adventurebackpack:tooltips.backpack.cycling.key2=рюкзака чтобы +adventurebackpack:tooltips.backpack.vision=Ночное зрение +adventurebackpack:tooltips.backpack.vision.key1=во время ношения +adventurebackpack:tooltips.backpack.vision.key2=рюкзака чтобы + +adventurebackpack:tooltips.jetpack.fuel=Топливо +adventurebackpack:tooltips.jetpack.tank.water=Левый бак +adventurebackpack:tooltips.jetpack.tank.steam=Правый бак +adventurebackpack:tooltips.jetpack.key.onoff1=во время ношения +adventurebackpack:tooltips.jetpack.key.onoff2=ранца чтобы + +adventurebackpack:tooltips.copter.tank.fuel=Бак топлива +adventurebackpack:tooltips.copter.rate.fuel=Потребления топлива +adventurebackpack:tooltips.copter.key.onoff1=во время ношения +adventurebackpack:tooltips.copter.key.onoff2=ранца чтобы +adventurebackpack:tooltips.copter.key.hover1=во время полета +adventurebackpack:tooltips.copter.key.hover2=переключить режим парения + +adventurebackpack:tooltips.hose.key.header=Когда держите Шланг: +adventurebackpack:tooltips.hose.key.tank=чтобы изменить активный бак +adventurebackpack:tooltips.hose.key.mode=чтобы изменить режим +adventurebackpack:tooltips.hose.dump1=Поместите Шланг в выходящий слот Ранца +adventurebackpack:tooltips.hose.dump2=чтобы опустошить соответствующий бак +adventurebackpack:tooltips.hose.dump.warn=ВНИМАНИЕ! Жидкость будет слита и потеряна. Навсегда. + +## Skins +adventurebackpack:skin.name.standard=Обычный +adventurebackpack:skin.name.bat=Летучие мыши ^-^ +adventurebackpack:skin.name.black=Чёрный +adventurebackpack:skin.name.blaze=Ифрита +adventurebackpack:skin.name.blue=Синий +adventurebackpack:skin.name.bookshelf=Книжный +adventurebackpack:skin.name.brown=Серый +adventurebackpack:skin.name.brown_mushroom=Серый Гриб +adventurebackpack:skin.name.cactus=Кактус +adventurebackpack:skin.name.cake=Торт +adventurebackpack:skin.name.carrot=Морковь +adventurebackpack:skin.name.chest=Сундук +adventurebackpack:skin.name.chicken=Курица +adventurebackpack:skin.name.coal=Уголь +adventurebackpack:skin.name.cookie=Печенька +adventurebackpack:skin.name.cow=Бык +adventurebackpack:skin.name.creeper=Крипер +adventurebackpack:skin.name.cyan=Бирюзовый +adventurebackpack:skin.name.deluxe=Делюкс +adventurebackpack:skin.name.diamond=Алмазный +adventurebackpack:skin.name.dragon=Дракон +adventurebackpack:skin.name.egg=Яйцо +adventurebackpack:skin.name.electric=Электрический +adventurebackpack:skin.name.emerald=Изумруд +adventurebackpack:skin.name.end=Край +adventurebackpack:skin.name.enderman=Эндермен +adventurebackpack:skin.name.ghast=Гаст +adventurebackpack:skin.name.glowstone=Свето-каменный +adventurebackpack:skin.name.gold=Золотой +adventurebackpack:skin.name.gray=Серый +adventurebackpack:skin.name.green=Зелёный +adventurebackpack:skin.name.haybale=СЕНО +adventurebackpack:skin.name.horse=Пони +adventurebackpack:skin.name.iron=Железный +adventurebackpack:skin.name.iron_golem=Железный Голем +adventurebackpack:skin.name.lapis=Лазурит +adventurebackpack:skin.name.leather=Кожанный +adventurebackpack:skin.name.light_blue=Голубой +adventurebackpack:skin.name.light_gray=Светло-Серый +adventurebackpack:skin.name.lime=Лаймовый +adventurebackpack:skin.name.magenta=Пурпурный +adventurebackpack:skin.name.magma_cube=Магмовый Куб +adventurebackpack:skin.name.melon=Арбузный +adventurebackpack:skin.name.modded_network=Молодёжный +adventurebackpack:skin.name.mooshroom=Грибной +adventurebackpack:skin.name.nether=Адский +adventurebackpack:skin.name.obsidian=Обсидиановый +adventurebackpack:skin.name.ocelot=Кошачий +adventurebackpack:skin.name.orange=Оранжевый +adventurebackpack:skin.name.overworld=Земной +adventurebackpack:skin.name.pig=Поросёнок +adventurebackpack:skin.name.pigman=Свино-Зомби +adventurebackpack:skin.name.pink=Розовый +adventurebackpack:skin.name.pumpkin=Тыква +adventurebackpack:skin.name.purple=Фиолетовый +adventurebackpack:skin.name.quartz=Кварцевый +adventurebackpack:skin.name.rainbow=Нян-Кет +adventurebackpack:skin.name.red=Красный +adventurebackpack:skin.name.red_mushroom=Красный Гриб +adventurebackpack:skin.name.redstone=Красный камень +adventurebackpack:skin.name.sandstone=Песчанник +adventurebackpack:skin.name.sheep=Овечка +adventurebackpack:skin.name.silverfish=Чешуйница +adventurebackpack:skin.name.skeleton=Скелет +adventurebackpack:skin.name.slime=Слизень +adventurebackpack:skin.name.snow=Зимний +adventurebackpack:skin.name.spider=Паук +adventurebackpack:skin.name.sponge=Губка +adventurebackpack:skin.name.squid=Спрут +adventurebackpack:skin.name.sunflower=Подсолнух +adventurebackpack:skin.name.villager=Житель +adventurebackpack:skin.name.white=Белый +adventurebackpack:skin.name.wither=Иссушитель +adventurebackpack:skin.name.wither_skeleton=Скелет-Иссушитель +adventurebackpack:skin.name.wolf=Волк +adventurebackpack:skin.name.yellow=Жёлтый +adventurebackpack:skin.name.zombie=Зомби +adventurebackpack:skin.name.unknown=Неизвестный \ No newline at end of file diff --git a/src/main/resources/assets/adventurebackpack/lang/uk_UA.lang b/src/main/resources/assets/adventurebackpack/lang/uk_UA.lang new file mode 100644 index 00000000..ba7b3d03 --- /dev/null +++ b/src/main/resources/assets/adventurebackpack/lang/uk_UA.lang @@ -0,0 +1,68 @@ +# Items + +## Component Items For Crafting +item.adventurebackpack:backpackComponent.name=Компонент рюкзака +item.adventurebackpack:sleepingBag.name=Спальний мішок +item.adventurebackpack:backpackTank.name=Резервуар для рідини в рюкзаку +item.adventurebackpack:macheteHandle=Ручка від мачете +item.adventurebackpack:hoseHead.name=Накінечник для трубки +item.adventurebackpack:copterEngine.name=Двоциліндровий дизельний двигун +item.adventurebackpack:copterBlades.name=Гелікоптерні лопаті +item.adventurebackpack:hydroBlades.name=Водяні лопаті +item.adventurebackpack:inflatableBoat.name=Надувний човен +item.adventurebackpack:inflatableBoatMotorized.name=Моторний надувний човен + +## Tools and consumables +item.adventurebackpack:clockworkCrossbow.name=Арбалет з часовим механізмом +item.adventurebackpack:melonJuiceBottle.name=Пляшка кавунного соку +item.adventurebackpack:machete.name=Мачете + +item.adventurebackpack:backpackHose.name=Трубка для рідин з рюкзаку +item.adventurebackpack:hose_leftTank_suck.name=Трубка для рідин: Ліва ємність / Режим закачування +item.adventurebackpack:hose_leftTank_spill.name=Трубка для рідин: Ліва ємність / Режим відкачування +item.adventurebackpack:hose_leftTank_drink.name=Трубка для рідин: Ліва ємність / Режим пиття + +item.adventurebackpack:hose_rightTank_suck.name=Трубка для рідин: Права ємність / Режим закачування +item.adventurebackpack:hose_rightTank_spill.name=Трубка для рідин: Права ємність / Режим відкачування +item.adventurebackpack:hose_rightTank_drink.name=Трубка для рідин: Права ємність / Режим пиття +item.adventurebackpack:hoseUseless.name=Трубка для рідин: Не використовується / Нема рюкзака + +## Wearables +item.adventurebackpack:adventureBackpack.name=Ранець шукача пригод +item.adventurebackpack:copterPack.name=Ранець-гелікоптер +item.adventurebackpack:steamJetpack.name=Паровий ранець + +## Armor +item.adventurebackpack:adventureSuit.name=Костюм шукача пригод +item.adventurebackpack:adventureHat.name=Фетровий капелюх шукача пригод +item.adventurebackpack:pistonBoots.name=Поршньові черевики + +## Blocks +block.adventurebackpack:blockAdventureBackpack.name=Основа рюкзака шукача пригод +block.adventurebackpack:blockCampFire.name=Вогнище +block.adventurebackpack:blockSleepingBag.name=Спальний мішок + +## CreativeTab +itemGroup.adventurebackpack=Adventure Backpack + +## Keybindings +keys.adventureBackpack.category=Рюкзак шукача пригод +keys.adventureBackpack.openBackpackInventory=Відкрити інвентар рюкзака +keys.adventureBackpack.switchHoseTank=Змінити використовуваний резервуар + +## Fluids +fluid.melonJuice=Кавунний сік +fluid.milk=Молоко +fluid.mushrromstew=Суп з грибів + +## Messages +adventurebackpack:already.equipped=Ви вже надягнули рюкзак. +adventurebackpack:messages.already.impossibru=Ви не можете надягнути більше рюкзаків. +adventurebackpack:messages.copterpack.hover=Рюкзак-гелікоптер: режим зависання. +adventurebackpack:messages.copterpack.normal=Рюкзак-гелікоптер: звичайний режим. +adventurebackpack:messages.copterpack.outoffuel=Рюкзак-гелікоптер: нема пального. +adventurebackpack:messages.copterpack.cantwater=Рюкзак-гелікоптер: праця під водою неможлива. +adventurebackpack:messages.copterpack.off=Рюкзак-гелікоптер: вимкнений. +adventurebackpack:messages.jetpack.on=Паровий рюкзак: увімкнений. +adventurebackpack:messages.jetpack.off=Паровий рюкзак: вимкнений. +adventurebackpack:messages.crossbow.outofammo=Арбалет з часовим механізмом: немає набоїв. diff --git a/src/main/resources/assets/adventurebackpack/sounds.json b/src/main/resources/assets/adventurebackpack/sounds.json index e9855cfb..b1e6bd0b 100644 --- a/src/main/resources/assets/adventurebackpack/sounds.json +++ b/src/main/resources/assets/adventurebackpack/sounds.json @@ -1,8 +1,8 @@ { "nyan":{"category":"player","sounds":[{"name":"nyan","stream":"true"}]}, - "helicopter":{"category":"player","sounds":[{"name":"helicopter","stream":"false"}]}, - "crossbowshot":{"category":"master","sounds":[{"name":"crossbowShot","stream":"false"}]}, - "s_jetpackon":{"category":"player","sounds":[{"name":"s_jetpackon","stream":"false"}]}, - "s_boiling":{"category":"player","sounds":[{"name":"s_boiling","stream":"false"}]}, - "s_background2":{"category":"player","sounds":[{"name":"s_background2","stream":"false"}]} + "helicopter3":{"category":"player","sounds":[{"name":"helicopter3","stream":"false"}]}, + "crossbowshot":{"category":"master","sounds":[{"name":"crossbowShot","stream":"false"}]}, + "s_jetpackon":{"category":"player","sounds":[{"name":"s_jetpackon","stream":"false"}]}, + "s_boiling":{"category":"player","sounds":[{"name":"s_boiling","stream":"false"}]}, + "s_background2":{"category":"player","sounds":[{"name":"s_background2","stream":"false"}]} } \ No newline at end of file diff --git a/src/main/resources/assets/adventurebackpack/sounds/helicopter3.ogg b/src/main/resources/assets/adventurebackpack/sounds/helicopter3.ogg new file mode 100644 index 00000000..e0c5e75e Binary files /dev/null and b/src/main/resources/assets/adventurebackpack/sounds/helicopter3.ogg differ diff --git a/src/main/resources/assets/adventurebackpack/textures/backpack/Fools.png b/src/main/resources/assets/adventurebackpack/textures/backpack/Fools.png new file mode 100644 index 00000000..4ecd5de1 Binary files /dev/null and b/src/main/resources/assets/adventurebackpack/textures/backpack/Fools.png differ diff --git a/src/main/resources/assets/adventurebackpack/textures/backpack/ModdedNetwork.png b/src/main/resources/assets/adventurebackpack/textures/backpack/ModdedNetwork.png new file mode 100644 index 00000000..80b3684f Binary files /dev/null and b/src/main/resources/assets/adventurebackpack/textures/backpack/ModdedNetwork.png differ diff --git a/src/main/resources/assets/adventurebackpack/textures/backpack/USA.png b/src/main/resources/assets/adventurebackpack/textures/backpack/USA.png new file mode 100644 index 00000000..7c788f6a Binary files /dev/null and b/src/main/resources/assets/adventurebackpack/textures/backpack/USA.png differ diff --git a/src/main/resources/assets/adventurebackpack/textures/gui/guiSteamJetpack.png b/src/main/resources/assets/adventurebackpack/textures/gui/guiCoalJetpack.png similarity index 100% rename from src/main/resources/assets/adventurebackpack/textures/gui/guiSteamJetpack.png rename to src/main/resources/assets/adventurebackpack/textures/gui/guiCoalJetpack.png diff --git a/src/main/resources/assets/adventurebackpack/textures/items/adventurePants.png b/src/main/resources/assets/adventurebackpack/textures/items/adventurePants.png new file mode 100644 index 00000000..051ac386 Binary files /dev/null and b/src/main/resources/assets/adventurebackpack/textures/items/adventurePants.png differ diff --git a/src/main/resources/assets/adventurebackpack/textures/items/steamJetpack.png b/src/main/resources/assets/adventurebackpack/textures/items/coalJetpack.png similarity index 100% rename from src/main/resources/assets/adventurebackpack/textures/items/steamJetpack.png rename to src/main/resources/assets/adventurebackpack/textures/items/coalJetpack.png diff --git a/src/main/resources/assets/adventurebackpack/textures/models/adventureHat.png b/src/main/resources/assets/adventurebackpack/textures/models/adventureHat_texture.png similarity index 100% rename from src/main/resources/assets/adventurebackpack/textures/models/adventureHat.png rename to src/main/resources/assets/adventurebackpack/textures/models/adventureHat_texture.png diff --git a/src/main/resources/assets/adventurebackpack/textures/models/adventurePants_texture.png b/src/main/resources/assets/adventurebackpack/textures/models/adventurePants_texture.png new file mode 100644 index 00000000..9d6c6bd1 Binary files /dev/null and b/src/main/resources/assets/adventurebackpack/textures/models/adventurePants_texture.png differ diff --git a/src/main/resources/assets/adventurebackpack/textures/models/steamJetpack.png b/src/main/resources/assets/adventurebackpack/textures/models/coalJetpack.png similarity index 100% rename from src/main/resources/assets/adventurebackpack/textures/models/steamJetpack.png rename to src/main/resources/assets/adventurebackpack/textures/models/coalJetpack.png diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index 9ca9193a..d83c7f07 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -2,15 +2,15 @@ { "modid": "adventurebackpack", "name": "Adventure Backpack", - "dependencies": ["Buildcraft|Core","Railcraft"], - "useDependencyInformation" : true, "description": "Useful and pretty backpacks for Minecraft", - "version": "1.7.10-0.8d", - "mcversion": "1.7.10", - "url": "http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/wip-mods/2252109-wip-adventure-backpack-mod-beta-0-7-3-updated-26", + "version": "${version}", + "mcversion": "${mcversion}", + "url": "https://github.com/runescapejon/AdventureBackpack2/releases", "updateUrl": "", "authorList": [ - "Darkona" + "Darkona", + "runescapejon", + "Ugachaga" ], "credits": "", "logoFile": "", @@ -18,6 +18,7 @@ ], "parent": "", "dependencies": [ + "CodeChickenLib" ] } ] \ No newline at end of file