diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a8e787c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,26 @@ +# default +* text eol=auto + +# git +.gitattributes text eol=lf +.gitignore text eol=lf + +# sources +*.java text eol=lf + +# resources +*.lang text eol=lf +*.cfg text eol=lf +*.info text eol=lf +*.mcmeta text eol=lf +*.md text eol=lf +*.xml text eol=lf + +# scripts +*.bat text eol=crlf +*.gradle text eol=lf +*.properties text eol=lf + +# binaries +*.png binary +*.jar binary diff --git a/.gitignore b/.gitignore index b9e8d82..6cb683a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,24 @@ -/.settings/ -/bin/ -/release/ -/build/ -/.gradle/ -/run/ -.project -.classpath -build.properties.old \ No newline at end of file +## gradle +/.gradle +/build + +## ForgeGradle +/run + +## eclipse +/.settings +/.metadata +/.classpath +/.project +/*.launch +/bin + +## intellij +/out +/.idea +/*.iml +/*.ipr +/*.iws + +## custom +/release diff --git a/build.gradle b/build.gradle index bee783c..629ebc3 100644 --- a/build.gradle +++ b/build.gradle @@ -1,47 +1,48 @@ buildscript { repositories { mavenCentral() + jcenter() maven { - name = "forge" - url = "http://files.minecraftforge.net/maven" + name = 'forge' + url = 'http://files.minecraftforge.net/maven' } maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" + name = 'sonatype' + url = 'https://oss.sonatype.org/content/repositories/snapshots/' } } dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + classpath 'net.minecraftforge.gradle:ForgeGradle:2.2-SNAPSHOT' + classpath 'com.matthewprenger:CurseGradle:1.0-SNAPSHOT' } } -apply plugin: "forge" +apply plugin: 'net.minecraftforge.gradle.forge' +apply plugin: 'com.matthewprenger.cursegradle' compileJava.options.encoding = 'UTF-8' -// define the properties file -ext.configFile = file "build.properties" - -configFile.withReader { - // read config. it shall from now on be referenced as simply config or as project.config - def prop = new Properties() - prop.load(it) - project.ext.config = new ConfigSlurper().parse prop -} - -group = config.group_name -version = config.mod_version -archivesBaseName = "[${config.minecraft_version}]${config.mod_id}" +group = project.group_name +version = project.mod_version +archivesBaseName = "${project.mod_id}_mc${project.minecraft_version}-${project.minecraft_maxversion}_v" minecraft { - version = config.minecraft_version + "-" + config.forge_version // grab latest forge - mappings = config.mappings_version - runDir = "run" - replace '@MOD_VERSION@', config.mod_version - replace '@MINECRAFT_VERSION@', config.minecraft_version + version = project.minecraft_version + '-' + project.forge_version // + "-" + project.minecraft_version // grab latest forge + mappings = project.mappings_version + runDir = 'run' + replace '@MOD_VERSION@', project.mod_version + replace '@MIN_MC_VERSION@', project.minecraft_version + replace '@MAX_MC_VERSION@', project.minecraft_maxversion } processResources { + // force replacements if input changes + inputs.property 'mod_version', version + inputs.property 'forge_version', project.forge_version + inputs.property 'forge_versionlimit', project.forge_versionlimit + inputs.property 'minecraft_version', project.minecraft_version + inputs.property 'minecraft_maxversion', project.minecraft_maxversion + // replace stuff in the files we want. from(sourceSets.main.resources.srcDirs) { include '**/*.info' @@ -49,13 +50,15 @@ processResources { // replaces expand ([ - 'mod_version': config.mod_version, - 'forge_version': config.forge_version, - 'minecraft_version': config.minecraft_version, + 'mod_version': project.mod_version, + 'forge_version': project.forge_version, + 'forge_versionlimit': project.forge_versionlimit, + 'minecraft_version': project.minecraft_version, + 'minecraft_maxversion': project.minecraft_maxversion ]) } - // copy everything else that we didnt do before + // copy everything else that we didn't do before from(sourceSets.main.resources.srcDirs) { exclude '**/*.info' exclude '**/*.properties' @@ -64,22 +67,29 @@ processResources { // change the name of my obfuscated jar jar { - appendix = config.appendix + appendix = project.appendix } -// add a source jar -task sourceJar(type: Jar) { - from sourceSets.main.allSource +sourceJar { appendix = 'src' -} - -// because the normal output has been made to be obfuscated -task deobfJar(type: Jar) { - from sourceSets.main.output - appendix = 'deobf' + classifier = '' } artifacts { archives sourceJar - archives deobfJar -} \ No newline at end of file +} + +if (project.hasProperty('api_key_curse') && project.hasProperty('extra_curse_id')) { + tasks.curseforge.dependsOn signJars + curseforge { + apiKey = project.api_key_curse + + project { + id = project.extra_curse_id + changelog = '' + releaseType = project.hasProperty('extra_curse_releasetype') ? project.extra_curse_releasetype : 'release' + + addArtifact sourceJar + } + } +} diff --git a/build.properties b/build.properties deleted file mode 100644 index 5d78ac2..0000000 --- a/build.properties +++ /dev/null @@ -1,7 +0,0 @@ -minecraft_version=1.8 -forge_version=11.14.1.1334 -mappings_version=stable_16 -mod_version=7.01 -mod_id=bspkrsCore -group_name=bspkrscore -appendix=universal \ No newline at end of file diff --git a/change.log b/change.log index c457a44..e471ddf 100644 --- a/change.log +++ b/change.log @@ -1,3 +1,5 @@ +7.1 - 02-Apr-2016 +- 1.9 update 7.01 - 06-Mar-2015 - 1.8 update - removed main menu mobs (will be released as a separate mod) diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..95ace7c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,9 @@ +minecraft_version=1.9 +minecraft_maxversion=1.10.2 +forge_version=12.16.1.1887 +forge_versionlimit=12.18.2 +mappings_version=stable_24 +mod_version=7.1.1 +mod_id=bspkrsCore +group_name=bspkrscore +appendix=client diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index b761216..9411448 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 678d9d8..baf5d7e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Wed Jul 02 15:54:47 CDT 2014 +#Tue Feb 02 17:03:16 CET 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.9-bin.zip diff --git a/gradlew b/gradlew index 91a7e26..9d82f78 100644 --- a/gradlew +++ b/gradlew @@ -42,11 +42,6 @@ case "`uname`" in ;; 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" @@ -61,9 +56,9 @@ while [ -h "$PRG" ] ; do fi done SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- +cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" -cd "$SAVED" >&- +cd "$SAVED" >/dev/null CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -114,6 +109,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` diff --git a/src/main/java/bspkrs/bspkrscore/fml/BSCClientTicker.java b/src/main/java/bspkrs/bspkrscore/fml/BSCClientTicker.java deleted file mode 100644 index 3e7dc46..0000000 --- a/src/main/java/bspkrs/bspkrscore/fml/BSCClientTicker.java +++ /dev/null @@ -1,61 +0,0 @@ -package bspkrs.bspkrscore.fml; - -import net.minecraft.client.Minecraft; -import net.minecraft.util.ChatComponentText; -import net.minecraftforge.fml.client.FMLClientHandler; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class BSCClientTicker -{ - public static boolean allowUpdateCheck = bspkrsCoreMod.instance.allowUpdateCheck; - private Minecraft mcClient; - public static boolean isRegistered = false; - - public BSCClientTicker() - { - if (!isRegistered) - { - mcClient = FMLClientHandler.instance().getClient(); - FMLCommonHandler.instance().bus().register(this); - isRegistered = true; - } - } - - @SubscribeEvent - public void onTick(ClientTickEvent event) - { - if (!event.phase.equals(Phase.START)) - { - boolean keepTicking = !(mcClient != null && mcClient.thePlayer != null && mcClient.theWorld != null); - - if (!keepTicking && isRegistered) - { - if (bspkrsCoreMod.instance.allowUpdateCheck && bspkrsCoreMod.instance.versionChecker != null) - if (!bspkrsCoreMod.instance.versionChecker.isCurrentVersion()) - for (String msg : bspkrsCoreMod.instance.versionChecker.getInGameMessage()) - mcClient.thePlayer.addChatMessage(new ChatComponentText(msg)); - - allowUpdateCheck = false; - - if (bspkrsCoreMod.instance.allowDebugOutput && !keepTicking && mcClient.theWorld.isRemote) - { - //EntityPlayerHelper.addChatMessage(mcClient.thePlayer, new ChatComponentText("\2470\2470\2471\2472\2473\2474\2475\2476\2477\247e\247f")); - } - - FMLCommonHandler.instance().bus().unregister(this); - isRegistered = false; - } - } - } - - public static boolean isRegistered() - { - return isRegistered; - } -} diff --git a/src/main/java/bspkrs/bspkrscore/fml/ClientProxy.java b/src/main/java/bspkrs/bspkrscore/fml/ClientProxy.java index 498b65f..1c8f479 100644 --- a/src/main/java/bspkrs/bspkrscore/fml/ClientProxy.java +++ b/src/main/java/bspkrs/bspkrscore/fml/ClientProxy.java @@ -8,8 +8,5 @@ public class ClientProxy extends CommonProxy { @Override protected void registerGameTickHandler() - { - if (BSCClientTicker.allowUpdateCheck) - new BSCClientTicker(); - } + {} } diff --git a/src/main/java/bspkrs/bspkrscore/fml/CommandBS.java b/src/main/java/bspkrs/bspkrscore/fml/CommandBS.java deleted file mode 100644 index 0d31993..0000000 --- a/src/main/java/bspkrs/bspkrscore/fml/CommandBS.java +++ /dev/null @@ -1,81 +0,0 @@ -package bspkrs.bspkrscore.fml; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.command.CommandBase; -import net.minecraft.command.ICommandSender; -import net.minecraft.command.WrongUsageException; -import net.minecraft.util.BlockPos; -import net.minecraft.util.ChatComponentText; -import bspkrs.util.ModVersionChecker; - -@SuppressWarnings("unchecked") -public class CommandBS extends CommandBase -{ - @SuppressWarnings("rawtypes") - private static List version = new ArrayList(); - - static - { - version.add("version"); - } - - @Override - public String getCommandName() - { - return "bs"; - } - - @Override - public String getCommandUsage(ICommandSender sender) - { - return "commands.bs.usage"; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) - { - return true; - } - - @Override - public int getRequiredPermissionLevel() - { - return 1; - } - - @Override - public void processCommand(ICommandSender sender, String[] args) throws WrongUsageException - { - if (!bspkrsCoreMod.instance.allowUpdateCheck) - throw new WrongUsageException("commands.bs.disabled"); - - if (args.length != 2) - throw new WrongUsageException("commands.bs.usage"); - - if (!args[0].equalsIgnoreCase("version")) - throw new WrongUsageException("commands.bs.usage"); - - String[] message = ModVersionChecker.checkVersionForMod(args[1]); - - for (String s : message) - sender.addChatMessage(new ChatComponentText(s)); - } - - @SuppressWarnings("rawtypes") - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) - { - return args.length == 2 ? getListOfStringsMatchingLastWord(args, ModVersionChecker.getVersionCheckerMap().keySet().toArray(new String[] {})) : args.length == 1 ? version : null; - } - - @Override - public int compareTo(Object object) - { - if (object instanceof CommandBase) - return this.getCommandName().compareTo(((CommandBase) object).getCommandName()); - - return 0; - } -} diff --git a/src/main/java/bspkrs/bspkrscore/fml/bspkrsCoreMod.java b/src/main/java/bspkrs/bspkrscore/fml/bspkrsCoreMod.java index cc19559..69d27ae 100644 --- a/src/main/java/bspkrs/bspkrscore/fml/bspkrsCoreMod.java +++ b/src/main/java/bspkrs/bspkrscore/fml/bspkrsCoreMod.java @@ -4,10 +4,9 @@ import java.util.ArrayList; import java.util.List; -import net.minecraftforge.client.ClientCommandHandler; +import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; -import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; @@ -19,14 +18,14 @@ import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; import bspkrs.util.CommonUtils; import bspkrs.util.Const; -import bspkrs.util.ModVersionChecker; import bspkrs.util.UniqueNameListGenerator; -@Mod(modid = Reference.MODID, name = Reference.NAME, version = "@MOD_VERSION@", useMetadata = true, guiFactory = Reference.GUI_FACTORY) +@Mod(modid = Reference.MODID, name = Reference.NAME, version = "@MOD_VERSION@", + useMetadata = true, guiFactory = Reference.GUI_FACTORY, + updateJSON = Const.VERSION_URL_BASE + Reference.MODID + Const.VERSION_URL_EXT, + acceptedMinecraftVersions = "[@MIN_MC_VERSION@,@MAX_MC_VERSION@]") public class bspkrsCoreMod { // config stuff @@ -48,19 +47,9 @@ public class bspkrsCoreMod @SidedProxy(clientSide = Reference.PROXY_CLIENT, serverSide = Reference.PROXY_COMMON) public static CommonProxy proxy; - protected ModVersionChecker versionChecker; - protected final String versionURL = Const.VERSION_URL + "/Minecraft/" + Const.MCVERSION + "/bspkrsCore.version"; - protected final String mcfTopic = "http://www.minecraftforum.net/topic/1114612-"; - - @SideOnly(Side.CLIENT) - protected BSCClientTicker ticker; - private boolean isCommandRegistered; - @EventHandler public void preInit(FMLPreInitializationEvent event) { - metadata = event.getModMetadata(); - File file = event.getSuggestedConfigurationFile(); if (!CommonUtils.isObfuscatedEnv()) @@ -108,27 +97,12 @@ public void syncConfig() @EventHandler public void init(FMLInitializationEvent event) { - if (allowUpdateCheck) - { - versionChecker = new ModVersionChecker(Reference.MODID, metadata.version, versionURL, mcfTopic); - versionChecker.checkVersionWithLogging(); - } - if (event.getSide().isClient()) { - FMLCommonHandler.instance().bus().register(new NetworkHandler()); - try - { - ClientCommandHandler.instance.registerCommand(new CommandBS()); - isCommandRegistered = true; - } - catch (Throwable e) - { - isCommandRegistered = false; - } + MinecraftForge.EVENT_BUS.register(new NetworkHandler()); } - FMLCommonHandler.instance().bus().register(instance); + MinecraftForge.EVENT_BUS.register(instance); } @EventHandler @@ -141,14 +115,12 @@ public void postInit(FMLPostInitializationEvent event) @EventHandler public void serverStarting(FMLServerStartingEvent event) { - if (!isCommandRegistered) - event.registerServerCommand(new CommandBS()); } @SubscribeEvent public void onConfigChanged(OnConfigChangedEvent event) { - if (event.modID.equals(Reference.MODID)) + if (event.getModID().equals(Reference.MODID)) { Reference.config.save(); syncConfig(); diff --git a/src/main/java/bspkrs/client/util/EntityUtils.java b/src/main/java/bspkrs/client/util/EntityUtils.java index 9ace3e2..899a59c 100644 --- a/src/main/java/bspkrs/client/util/EntityUtils.java +++ b/src/main/java/bspkrs/client/util/EntityUtils.java @@ -15,8 +15,8 @@ import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.Render; +import net.minecraft.client.renderer.entity.RenderLivingBase; import net.minecraft.client.renderer.entity.RenderManager; -import net.minecraft.client.renderer.entity.RendererLivingEntity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.world.World; @@ -76,9 +76,9 @@ public class EntityUtils public static float getModelSize(EntityLivingBase ent) { Render render = Minecraft.getMinecraft().getRenderManager().getEntityRenderObject(ent); - if (render instanceof RendererLivingEntity) + if (render instanceof RenderLivingBase) { - RendererLivingEntity entRender = (RendererLivingEntity) render; + RenderLivingBase entRender = (RenderLivingBase) render; ModelBase mainModel; ModelBase renderPassModel; try @@ -180,7 +180,7 @@ public static void drawEntityOnScreen(int posX, int posY, float scale, float mou RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager(); rendermanager.setPlayerViewY(180.0F); rendermanager.setRenderShadow(false); - rendermanager.renderEntityWithPosYaw(ent, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F); + rendermanager.doRenderEntity(ent, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F, false); rendermanager.setRenderShadow(true); } finally @@ -217,7 +217,7 @@ public static EntityLivingBase getRandomLivingEntity(World world, { Random random = new Random(); // Get a COPY dumbass! - Set entities = new TreeSet(EntityList.stringToClassMapping.keySet()); + Set entities = new TreeSet(EntityList.NAME_TO_CLASS.keySet()); if (blacklist != null) entities.removeAll(blacklist); @@ -230,7 +230,7 @@ public static EntityLivingBase getRandomLivingEntity(World world, do { id = random.nextInt(entStrings.length); - clazz = (Class) EntityList.stringToClassMapping.get(entStrings[id]); + clazz = (Class) EntityList.NAME_TO_CLASS.get(entStrings[id]); } while (!EntityLivingBase.class.isAssignableFrom(clazz) && (++tries <= numberOfAttempts)); diff --git a/src/main/java/bspkrs/client/util/HUDUtils.java b/src/main/java/bspkrs/client/util/HUDUtils.java index a7cc89e..47adcc7 100644 --- a/src/main/java/bspkrs/client/util/HUDUtils.java +++ b/src/main/java/bspkrs/client/util/HUDUtils.java @@ -5,7 +5,8 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.WorldRenderer; +import net.minecraft.client.renderer.VertexBuffer; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; @@ -169,12 +170,12 @@ public static void drawTexturedModalRect(int x, int y, int u, int v, int width, float var7 = 0.00390625F; float var8 = 0.00390625F; Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldRenderer = tessellator.getWorldRenderer(); - worldRenderer.startDrawingQuads(); - worldRenderer.addVertexWithUV((x + 0), (y + height), zLevel, ((u + 0) * var7), ((v + height) * var8)); - worldRenderer.addVertexWithUV((x + width), (y + height), zLevel, ((u + width) * var7), ((v + height) * var8)); - worldRenderer.addVertexWithUV((x + width), (y + 0), zLevel, ((u + width) * var7), ((v + 0) * var8)); - worldRenderer.addVertexWithUV((x + 0), (y + 0), zLevel, ((u + 0) * var7), ((v + 0) * var8)); + VertexBuffer worldRenderer = tessellator.getBuffer(); + worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX); + worldRenderer.pos((x + 0), (y + height), zLevel).tex(((u + 0) * var7), ((v + height) * var8)).endVertex(); + worldRenderer.pos((x + width), (y + height), zLevel).tex(((u + width) * var7), ((v + height) * var8)).endVertex(); + worldRenderer.pos((x + width), (y + 0), zLevel).tex(((u + width) * var7), ((v + 0) * var8)).endVertex(); + worldRenderer.pos((x + 0), (y + 0), zLevel).tex(((u + 0) * var7), ((v + 0) * var8)).endVertex(); tessellator.draw(); } @@ -221,8 +222,8 @@ public static void renderItemOverlayIntoGUI(FontRenderer fontRenderer, ItemStack if (itemStack.getMaxStackSize() > 1) count = HUDUtils.countInInventory(Minecraft.getMinecraft().thePlayer, itemStack.getItem(), itemStack.getItemDamage()); - else if (itemStack.getItem().equals(Items.bow)) - count = HUDUtils.countInInventory(Minecraft.getMinecraft().thePlayer, Items.arrow); + else if (itemStack.getItem().equals(Items.BOW)) + count = HUDUtils.countInInventory(Minecraft.getMinecraft().thePlayer, Items.ARROW); if (count > 1) { @@ -244,13 +245,16 @@ else if (itemStack.getItem().equals(Items.bow)) */ public static void renderQuad(Tessellator tessellator, int x, int y, int width, int height, int color) { - WorldRenderer worldRenderer = tessellator.getWorldRenderer(); - worldRenderer.startDrawingQuads(); - worldRenderer.setColorOpaque_I(color); - worldRenderer.addVertex((x + 0), (y + 0), 0.0D); - worldRenderer.addVertex((x + 0), (y + height), 0.0D); - worldRenderer.addVertex((x + width), (y + height), 0.0D); - worldRenderer.addVertex((x + width), (y + 0), 0.0D); + VertexBuffer worldRenderer = tessellator.getBuffer(); + worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); + int a = (color >> 24) & 0xFF; + int r = (color >> 16) & 0xFF; + int g = (color >> 8) & 0xFF; + int b = (color >> 0) & 0xFF; + worldRenderer.pos(x + 0, y + 0, 0.0D).color(r, g, b, a).endVertex(); + worldRenderer.pos(x + 0, y + height, 0.0D).color(r, g, b, a).endVertex(); + worldRenderer.pos(x + width, y + height, 0.0D).color(r, g, b, a).endVertex(); + worldRenderer.pos(x + width, y + 0, 0.0D).color(r, g, b, a).endVertex(); tessellator.draw(); } diff --git a/src/main/java/bspkrs/fml/util/DelayedGuiDisplayTicker.java b/src/main/java/bspkrs/fml/util/DelayedGuiDisplayTicker.java index b8e2e76..fde6574 100644 --- a/src/main/java/bspkrs/fml/util/DelayedGuiDisplayTicker.java +++ b/src/main/java/bspkrs/fml/util/DelayedGuiDisplayTicker.java @@ -2,8 +2,8 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.FMLClientHandler; -import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; @@ -19,7 +19,7 @@ public DelayedGuiDisplayTicker(int delayTicks, GuiScreen screen) this.delayTicks = delayTicks; this.mcClient = FMLClientHandler.instance().getClient(); this.screen = screen; - FMLCommonHandler.instance().bus().register(this); + MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent @@ -31,7 +31,7 @@ public void onTick(ClientTickEvent event) if (--delayTicks <= 0) { mcClient.displayGuiScreen(screen); - FMLCommonHandler.instance().bus().unregister(this); + MinecraftForge.EVENT_BUS.unregister(this); } } } diff --git a/src/main/java/bspkrs/fml/util/InputEventListener.java b/src/main/java/bspkrs/fml/util/InputEventListener.java index 1545ff5..8696082 100644 --- a/src/main/java/bspkrs/fml/util/InputEventListener.java +++ b/src/main/java/bspkrs/fml/util/InputEventListener.java @@ -4,11 +4,11 @@ import net.minecraft.client.settings.KeyBinding; +import net.minecraftforge.common.MinecraftForge; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import net.minecraftforge.fml.client.registry.ClientRegistry; -import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import net.minecraftforge.fml.common.gameevent.InputEvent.KeyInputEvent; @@ -79,7 +79,7 @@ public static void unRegister(KeyBinding kb) { if (isRegistered(kb)) { - FMLCommonHandler.instance().bus().unregister(instances.get(kb)); + MinecraftForge.EVENT_BUS.unregister(instances.get(kb)); instances.remove(kb); } } diff --git a/src/main/java/bspkrs/util/BSConfiguration.java b/src/main/java/bspkrs/util/BSConfiguration.java deleted file mode 100644 index 96a8ea8..0000000 --- a/src/main/java/bspkrs/util/BSConfiguration.java +++ /dev/null @@ -1,227 +0,0 @@ -package bspkrs.util; - -import java.io.File; - -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; - -/** - * This class offers advanced configurations capabilities, allowing to provide various categories for configuration variables. - */ -@Deprecated -public class BSConfiguration extends Configuration -{ - private final File fileRef; - - public BSConfiguration(File file) - { - super(file); - fileRef = file; - } - - @Override - public File getConfigFile() - { - return fileRef; - } - - /** - * Renames a property in a given category. - * - * @param category the category in which the property resides - * @param oldPropName the existing property name - * @param newPropName the - * @return true if the category and property exist, false otherwise - */ - @Override - public boolean renameProperty(String category, String oldPropName, String newPropName) - { - if (hasCategory(category)) - { - if (getCategory(category).containsKey(oldPropName) && !oldPropName.equalsIgnoreCase(newPropName)) - { - get(category, newPropName, getCategory(category).get(oldPropName).getString()); - getCategory(category).remove(oldPropName); - return true; - } - } - return false; - } - - /** - * Moves a property from one category to another. - * - * @param oldCategory the category the property currently resides in - * @param propName the name of the property to move - * @param newCategory the category the property should be moved to - * @return true if the old category and property exist, false otherwise - */ - @Override - public boolean moveProperty(String oldCategory, String propName, String newCategory) - { - if (hasCategory(oldCategory)) - { - if (getCategory(oldCategory).containsKey(propName)) - { - getCategory(newCategory).put(propName, getCategory(oldCategory).get(propName)); - return true; - } - } - return false; - } - - // public static void renameCtgy(Configuration config, String oldCtgy, String newCtgy) - // { - // if (!oldCtgy.equalsIgnoreCase(newCtgy)) - // { - // for (String prop : config.getCategory(oldCtgy).keySet()) - // config.get(newCtgy, prop, config.getCategory(oldCtgy).get(prop).getString()); - // - // Map> toAdd = new HashMap>(); - // - // for (String key : config.getCategoryNames()) - // if (key.contains(oldCtgy + ".")) - // { - // HashMap props = new HashMap(); - // for (String prop : config.getCategory(key).keySet()) - // props.put(prop, config.getCategory(key).get(prop).getString()); - // - // toAdd.put(newCtgy + key.substring(key.indexOf(".")), props); - // } - // - // for (String newName : toAdd.keySet()) - // for (String newProp : toAdd.get(newName).keySet()) - // config.get(newName, newProp, toAdd.get(newName).get(newProp)); - // - // //config.categories.remove(oldCtgy); - // } - // } - - /** - * Creates a string property. - * - * @param name Name of the property. - * @param category Category of the property. - * @param defaultValue Default value of the property. - * @param comment A brief description what the property does. - * @return The value of the new string property. - */ - @Override - public String getString(String name, String category, String defaultValue, String comment) - { - return getString(name, category, defaultValue, comment, new String[0]); - } - - /** - * Creates a string property. - * - * @param name Name of the property. - * @param category Category of the property. - * @param defaultValue Default value of the property. - * @param comment A brief description what the property does. - * @param validValues A list of valid values that this property can be set to. - * @return The value of the new string property. - */ - @Override - public String getString(String name, String category, String defaultValue, String comment, String[] validValues) - { - Property prop = this.get(category, name, defaultValue); - prop.comment = comment + " [default: " + defaultValue + "]"; - return prop.getString(); - } - - /** - * Creates a string list property. - * - * @param name Name of the property. - * @param category Category of the property. - * @param defaultValue Default value of the property. - * @param comment A brief description what the property does. - * @return The value of the new string property. - */ - @Override - public String[] getStringList(String name, String category, String[] defaultValues, String comment) - { - return getStringList(name, category, defaultValues, comment, new String[0]); - } - - /** - * Creates a string list property. - * - * @param name Name of the property. - * @param category Category of the property. - * @param defaultValue Default value of the property. - * @param comment A brief description what the property does. - * @return The value of the new string property. - */ - @Override - public String[] getStringList(String name, String category, String[] defaultValue, String comment, String[] validValues) - { - Property prop = this.get(category, name, defaultValue); - prop.comment = comment + " [default: " + defaultValue + "]"; - return prop.getStringList(); - } - - /** - * Creates a boolean property. - * - * @param name Name of the property. - * @param category Category of the property. - * @param defaultValue Default value of the property. - * @param comment A brief description what the property does. - * @return The value of the new boolean property. - */ - @Override - public boolean getBoolean(String name, String category, boolean defaultValue, String comment) - { - Property prop = this.get(category, name, defaultValue); - prop.comment = comment + " [default: " + defaultValue + "]"; - return prop.getBoolean(defaultValue); - } - - /** - * Creates a integer property. - * - * @param name Name of the property. - * @param category Category of the property. - * @param defaultValue Default value of the property. - * @param minValue Minimum value of the property. - * @param maxValue Maximum value of the property. - * @param comment A brief description what the property does. - * @return The value of the new integer property. - */ - @Override - public int getInt(String name, String category, int defaultValue, int minValue, int maxValue, String comment) - { - Property prop = this.get(category, name, defaultValue); - prop.comment = comment + " [range: " + minValue + " ~ " + maxValue + ", default: " + defaultValue + "]"; - return prop.getInt(defaultValue) < minValue ? minValue : (prop.getInt(defaultValue) > maxValue ? maxValue : prop.getInt(defaultValue)); - } - - /** - * Creates a float property. - * - * @param name Name of the property. - * @param category Category of the property. - * @param defaultValue Default value of the property. - * @param minValue Minimum value of the property. - * @param maxValue Maximum value of the property. - * @param comment A brief description what the property does. - * @return The value of the new float property. - */ - @Override - public float getFloat(String name, String category, float defaultValue, float minValue, float maxValue, String comment) - { - Property prop = this.get(category, name, Float.toString(defaultValue)); - prop.comment = comment + " [range: " + minValue + " ~ " + maxValue + ", default: " + defaultValue + "]"; - try - { - return Float.parseFloat(prop.getString()) < minValue ? minValue : (Float.parseFloat(prop.getString()) > maxValue ? maxValue : Float.parseFloat(prop.getString())); - } - catch (Exception e) - { - e.printStackTrace(); - } - return defaultValue; - } -} diff --git a/src/main/java/bspkrs/util/BlockID.java b/src/main/java/bspkrs/util/BlockID.java index 2983a05..f614536 100644 --- a/src/main/java/bspkrs/util/BlockID.java +++ b/src/main/java/bspkrs/util/BlockID.java @@ -1,148 +1,150 @@ -package bspkrs.util; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.fml.common.registry.GameData; - -public class BlockID -{ - public final String id; - public final int metadata; - - public BlockID(String id, int metadata) - { - this.id = id; - this.metadata = metadata; - } - - public BlockID(String block) - { - this(block, -1); - } - - public BlockID(Block block, int metadata) - { - this(GameData.getBlockRegistry().getNameForObject(block).toString(), metadata); - } - - public BlockID(Block block) - { - this(GameData.getBlockRegistry().getNameForObject(block).toString(), -1); - } - - public BlockID(Block block, IBlockState state) - { - this(block, block.getMetaFromState(state)); - } - - public BlockID(IBlockState state) - { - this(state.getBlock(), state); - } - - public BlockID(World world, BlockPos pos) - { - this(world.getBlockState(pos)); - } - - public BlockID(World world, BlockPos pos, int metadata) - { - this(world.getBlockState(pos).getBlock(), metadata); - } - - public boolean isValid() - { - return getBlock() != null; - } - - public Block getBlock() - { - return GameData.getBlockRegistry().getObject(id); - } - - public static BlockID parse(String format) - { - String id; - int metadata; - int metadataModulus = 0; - format = format.trim(); - int comma = format.indexOf(","); - int tilde = format.indexOf("~"); - if (tilde == -1) - tilde = format.indexOf("%"); - - if ((comma == -1) && (tilde != -1)) - throw new RuntimeException(String.format("ModulusBlockID format error: a \"~\" or \"%1$s\" was found, but no \",\" in format \"%2$s\". " + - "Expected format is \", %1$s \". EG: \"minecraft:log, 0 %1$s 4\".", "%", format)); - - if ((tilde != -1) && (comma > tilde)) - throw new RuntimeException(String.format("ModulusBlockID format error: a \"~\" or \"%1$s\" was found before a \",\" in format \"%2$s\". " + - "Expected format is \", %1$s \". EG: \"minecraft:log, 0 %1$s 4\".", "%", format)); - - if (tilde == -1) - tilde = format.length(); - - if (comma != -1) - id = format.substring(0, comma).trim(); - else - id = format.trim(); - - metadata = CommonUtils.parseInt(format.substring(comma + 1, tilde).trim(), -1); - if (tilde != format.length()) - metadataModulus = CommonUtils.parseInt(format.substring(tilde + 1, format.length()).trim(), 0); - - if ((metadata != -1) && (metadataModulus > 0)) - return new ModulusBlockID(id, metadata, metadataModulus); - else - return new BlockID(id, metadata); - } - - @Override - public BlockID clone() - { - return new BlockID(id, metadata); - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - - if (!(obj instanceof BlockID)) - return false; - - if ((((BlockID) obj).id != null) && !((BlockID) obj).id.equals(id)) - return false; - else if ((((BlockID) obj).id == null) && (id != null)) - return false; - - if (obj instanceof ModulusBlockID) - { - ModulusBlockID o = (ModulusBlockID) obj; - return (metadata % o.metadataModulus) == (o.metadata % o.metadataModulus); - } - else - { - BlockID o = (BlockID) obj; - if ((o.metadata == -1) || (metadata == -1)) - return true; - else - return metadata == o.metadata; - } - } - - @Override - public int hashCode() - { - return id.hashCode() * 37; - } - - @Override - public String toString() - { - return (metadata == -1 ? id : id + ", " + metadata); - } -} +package bspkrs.util; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; +import net.minecraftforge.fml.common.registry.GameData; + +@Deprecated // TODO: replace with a IBlockState implementation +public class BlockID +{ + public final String id; + public final int metadata; + + public BlockID(String id, int metadata) + { + this.id = id; + this.metadata = metadata; + } + + public BlockID(String block) + { + this(block, -1); + } + + public BlockID(Block block, int metadata) + { + this(GameData.getBlockRegistry().getNameForObject(block).toString(), metadata); + } + + public BlockID(Block block) + { + this(GameData.getBlockRegistry().getNameForObject(block).toString(), -1); + } + + public BlockID(Block block, IBlockState state) + { + this(block, block.getMetaFromState(state)); + } + + public BlockID(IBlockState state) + { + this(state.getBlock(), state); + } + + public BlockID(World world, BlockPos pos) + { + this(world.getBlockState(pos)); + } + + public BlockID(World world, BlockPos pos, int metadata) + { + this(world.getBlockState(pos).getBlock(), metadata); + } + + public boolean isValid() + { + return getBlock() != null; + } + + public Block getBlock() + { + return GameData.getBlockRegistry().getObject(new ResourceLocation(id)); + } + + public static BlockID parse(String format) + { + String id; + int metadata; + int metadataModulus = 0; + format = format.trim(); + int comma = format.indexOf(","); + int tilde = format.indexOf("~"); + if (tilde == -1) + tilde = format.indexOf("%"); + + if ((comma == -1) && (tilde != -1)) + throw new RuntimeException(String.format("ModulusBlockID format error: a \"~\" or \"%1$s\" was found, but no \",\" in format \"%2$s\". " + + "Expected format is \", %1$s \". EG: \"minecraft:log, 0 %1$s 4\".", "%", format)); + + if ((tilde != -1) && (comma > tilde)) + throw new RuntimeException(String.format("ModulusBlockID format error: a \"~\" or \"%1$s\" was found before a \",\" in format \"%2$s\". " + + "Expected format is \", %1$s \". EG: \"minecraft:log, 0 %1$s 4\".", "%", format)); + + if (tilde == -1) + tilde = format.length(); + + if (comma != -1) + id = format.substring(0, comma).trim(); + else + id = format.trim(); + + metadata = CommonUtils.parseInt(format.substring(comma + 1, tilde).trim(), -1); + if (tilde != format.length()) + metadataModulus = CommonUtils.parseInt(format.substring(tilde + 1, format.length()).trim(), 0); + + if ((metadata != -1) && (metadataModulus > 0)) + return new ModulusBlockID(id, metadata, metadataModulus); + else + return new BlockID(id, metadata); + } + + @Override + public BlockID clone() + { + return new BlockID(id, metadata); + } + + @Override + public boolean equals(Object obj) + { + if (this == obj) + return true; + + if (!(obj instanceof BlockID)) + return false; + + if ((((BlockID) obj).id != null) && !((BlockID) obj).id.equals(id)) + return false; + else if ((((BlockID) obj).id == null) && (id != null)) + return false; + + if (obj instanceof ModulusBlockID) + { + ModulusBlockID o = (ModulusBlockID) obj; + return (metadata % o.metadataModulus) == (o.metadata % o.metadataModulus); + } + else + { + BlockID o = (BlockID) obj; + if ((o.metadata == -1) || (metadata == -1)) + return true; + else + return metadata == o.metadata; + } + } + + @Override + public int hashCode() + { + return id.hashCode() * 37; + } + + @Override + public String toString() + { + return (metadata == -1 ? id : id + ", " + metadata); + } +} diff --git a/src/main/java/bspkrs/util/CommonUtils.java b/src/main/java/bspkrs/util/CommonUtils.java index 70cc69b..8aa9c63 100644 --- a/src/main/java/bspkrs/util/CommonUtils.java +++ b/src/main/java/bspkrs/util/CommonUtils.java @@ -1,593 +1,597 @@ -package bspkrs.util; - -import java.io.File; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.Scanner; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiMainMenu; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.server.MinecraftServer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.BlockPos; -import net.minecraft.util.EnumParticleTypes; -import net.minecraft.util.MathHelper; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Logger; - -import bspkrs.bspkrscore.fml.bspkrsCoreMod; - -/* - * @Authors: DaftPVF, bspkrs - * @Desc: Helpers from original Treecapitator, ConnectedDestruction, and FloatingRuins mod code and new utility methods - */ - -public final class CommonUtils -{ - public static boolean isStringAllLettersOrDigits(CharSequence s) - { - for (int i = 0; i < s.length(); i++) - if (!Character.isLetterOrDigit(s.charAt(i))) - return false; - return true; - } - - public static boolean isStringAllLettersOrDigitsOr(CharSequence s, String chrs) - { - for (int i = 0; i < s.length(); i++) - if (!Character.isLetterOrDigit(s.charAt(i)) && !chrs.contains(s.subSequence(i, i + 1))) - return false; - return true; - } - - /* - * List parser helpers - */ - - public static boolean isItemInList(int id, int md, String list) - { - if (list.trim().length() != 0) - { - String[] items = list.split(";"); - for (String item : items) - { - String[] values = item.split(","); - if (parseInt(values[0]) == id) - { - if (values.length == 1) - return true; - else if ((values.length == 2) && (parseInt(values[1]) == md)) - return true; - } - } - } - return false; - } - - public static boolean isIDInList(String id, int md, String list) - { - String[] itemArray = list.split(";"); - for (int i = 0; i < itemArray.length; i++) - { - String[] values = itemArray[i].split(","); - - if ((values.length > 1) && values[0].trim().equals(id) && (parseInt(values[1], -1) == md)) - return true; - else if (values[0].trim().equals(id)) - return true; - } - return false; - } - - public static boolean isIDInList(int id, int md, String list) - { - String[] itemArray = list.split(";"); - for (int i = 0; i < itemArray.length; i++) - { - String[] values = itemArray[i].split(","); - int tempID = parseInt(values[0], Integer.MAX_VALUE); - - if (tempID == Integer.MAX_VALUE) - continue; - - if ((values.length > 1) && (tempID == id) && (parseInt(values[1], -1) == md)) - return true; - else if (tempID == id) - return true; - } - return false; - } - - public static boolean isIDInList(int id, String list) - { - return isIDInList(id, -1, list); - } - - public static int[][][] stringToGroups(String string) - { - List groupList = new ArrayList(); - String[] groups = string.split(";"); - for (String group : groups) - { - groupList.add(stringToGroup(group)); - } - int[][][] res = new int[groupList.size()][][]; - for (int i = 0; i < groupList.size(); i++) - { - res[i] = groupList.get(i); - } - return res; - } - - public static int[][] stringToGroup(String string) - { - List blockList = new ArrayList(); - String[] blocks = string.split(">"); - for (String block : blocks) - { - blockList.add(stringToBlock(block)); - } - int[][] res = new int[blockList.size()][]; - for (int i = 0; i < blockList.size(); i++) - { - res[i] = blockList.get(i); - } - return res; - } - - public static int[] stringToBlock(String string) - { - int[] values = new int[] { 0, -1 }; - String[] src = string.split(","); - if (src.length < 1) - return values; - values[0] = parseInt(src[0]); - if (src.length < 2) - return values; - values[1] = parseInt(src[1]); - return values; - } - - public static boolean isBlockInGroups(int[] block, int[][][] groups) - { - for (int[][] group : groups) - { - if (indexOfBlock(block, group) > -1) - return true; - } - return false; - } - - public static int indexOfBlock(int[] block, int[][] group) - { - for (int i = 0; i < group.length; i++) - { - if (block[0] == group[i][0]) - { - if ((group[i][1] == -1) || (block[1] == group[i][1])) - return i; - } - } - return -1; - } - - public static int[][] getRelatedBlocks(int[] block, int[][][] groups) - { - List blockList = new ArrayList(); - for (int[][] group : groups) - { - if (indexOfBlock(block, group) > -1) - { - for (int i = 0; i < groups.length; i++) - { - if (blockList.contains(group[i])) - continue; - blockList.add(i, group[i]); - } - } - } - int[][] secondary = new int[blockList.size()][]; - for (int i = 0; i < blockList.size(); i++) - { - secondary[i] = blockList.get(i); - } - return secondary; - } - - public static int smallerBlockIndex(int[] block, int[][][] groups) - { - int min = Integer.MAX_VALUE; - for (int[][] group : groups) - { - int i = indexOfBlock(block, group); - if ((i > -1) && (i < min)) - min = i; - } - if (min == Integer.MAX_VALUE) - min = -1; - return min; - } - - public static boolean isMetadataNull(int id, int[][][] groups) - { - for (int[][] group : groups) - { - for (int[] block : group) - { - if ((block[0] == id) && (block[1] == -1)) - return true; - } - } - return false; - } - - /* - * Math helpers - */ - - public static int sqr(int value) - { - return value * value; - } - - public static float sqr(float value) - { - return value * value; - } - - public static int parseInt(String string) - { - return parseInt(string, 0); - } - - public static int parseInt(String string, int defaultValue) - { - try - { - return Integer.parseInt(string.trim()); - } - catch (NumberFormatException ex) - { - return defaultValue; - } - } - - /* - * General Minecraft methods - */ - - public void playAtPitch(int i, World world, EntityPlayer entityplayer) - { - float f = (float) Math.pow(2D, (i - 12) / 12D); - world.playSoundAtEntity(entityplayer, "note.pling", 0.5F, f); - } - - public static boolean moveBlock(World world, BlockPos src, BlockPos tgt, boolean allowBlockReplacement) - { - return moveBlock(world, src, tgt, allowBlockReplacement, BlockNotifyType.ALL); - } - - public static boolean moveBlock(World world, BlockPos src, BlockPos tgt, boolean allowBlockReplacement, int notifyFlag) - { - if (!world.isRemote && !world.isAirBlock(src) && (world.isAirBlock(tgt) || allowBlockReplacement)) - { - IBlockState state = world.getBlockState(src); - - world.setBlockState(tgt, state, notifyFlag); - - TileEntity te = world.getTileEntity(src); - if (te != null) - { - NBTTagCompound nbt = new NBTTagCompound(); - te.writeToNBT(nbt); - - nbt.setInteger("x", tgt.getX()); - nbt.setInteger("y", tgt.getY()); - nbt.setInteger("z", tgt.getZ()); - - te = world.getTileEntity(tgt); - if (te != null) - te.readFromNBT(nbt); - - world.removeTileEntity(src); - } - - world.setBlockToAir(src); - return true; - } - return false; - } - - public static int getHighestGroundBlock(World world, BlockPos pos) - { - while ((pos.getY() > 0) && (world.isAirBlock(pos) || !world.isBlockNormalCube(pos, true) - || world.getBlockState(pos).getBlock().isWood(world, pos))) - { - pos = pos.down(); - } - return pos.getY(); - } - - public static int getFirstNonAirBlockFromTop(World world, BlockPos pos) - { - int y; - int x = pos.getX(); - int z = pos.getZ(); - for (y = world.getActualHeight(); world.isAirBlock(new BlockPos(x, y - 1, z)) && (y > 0); y--) - {} - return y; - } - - public static int getSphericalDistance(BlockPos startPos, BlockPos endPos) - { - return (int) Math.round(Math.sqrt(CommonUtils.sqr(endPos.getX() - startPos.getX()) - + CommonUtils.sqr(endPos.getZ() - startPos.getZ()) + CommonUtils.sqr(endPos.getY() - startPos.getY()))); - } - - public static int getCubicDistance(BlockPos startPos, BlockPos endPos) - { - return Math.abs(endPos.getX() - startPos.getX()) + Math.abs(endPos.getY() - startPos.getY()) + Math.abs(endPos.getZ() - startPos.getZ()); - } - - public static int getHorSquaredDistance(BlockPos pos, BlockPos pos2) - { - return Math.abs(pos2.getX() - pos.getX()) + Math.abs(pos2.getZ() - pos.getZ()); - } - - public static int getVerDistance(BlockPos startPos, BlockPos endPos) - { - return Math.abs(endPos.getY() - startPos.getY()); - } - - public static double getDistanceRatioToCenter(int point1, int point2, int pos) - { - double radius = Math.abs(point2 - point1) / 2D; - double dar = Math.abs(Math.abs(pos - point1) - radius); - return radius != 0.0D ? dar / radius : 0.0D; - } - - public static void setHugeMushroom(World world, Random random, BlockPos pos, IBlockState state) - { - int x = pos.getX(); - int y = pos.getY(); - int z = pos.getZ(); - byte w = 3; - byte cw = 4; - byte h = 4; - fillWithBlocks(world, new BlockPos((x - w) + 1, y, z - w), new BlockPos((x + w) - 1, (y + h) - 1, z - w), state.getBlock().getStateFromMeta(10)); - fillWithBlocks(world, new BlockPos((x - w) + 1, y, z + w), new BlockPos((x + w) - 1, (y + h) - 1, z + w), state.getBlock().getStateFromMeta(10)); - fillWithBlocks(world, new BlockPos(x - w, y, (z - w) + 1), new BlockPos(x - w, (y + h) - 1, (z + w) - 1), state.getBlock().getStateFromMeta(10)); - fillWithBlocks(world, new BlockPos(x + w, y, (z - w) + 1), new BlockPos(x + w, (y + h) - 1, (z + w) - 1), state.getBlock().getStateFromMeta(10)); - fillWithBlocksRounded(world, new BlockPos(x - cw, y + h, z - cw), new BlockPos(x + cw, y + h, z + cw), state.getBlock().getStateFromMeta(14)); - } - - public static void fillWithBlocks(World world, BlockPos pos1, BlockPos pos2, IBlockState state) - { - for (int x = pos1.getX(); x <= pos2.getX(); x++) - for (int y = pos1.getY(); y <= pos2.getY(); y++) - for (int z = pos1.getZ(); z <= pos2.getZ(); z++) - world.setBlockState(new BlockPos(x, y, z), state, 3); - } - - public static void fillWithBlocksRounded(World world, BlockPos pos1, BlockPos pos2, IBlockState state) - { - for (int x = pos1.getX(); x <= pos2.getX(); x++) - for (int y = pos1.getY(); y <= pos2.getY(); y++) - for (int z = pos1.getZ(); z <= pos2.getZ(); z++) - { - double xd = getDistanceRatioToCenter(pos1.getX(), pos2.getX(), x); - double yd = getDistanceRatioToCenter(pos1.getY(), pos2.getY(), y); - double zd = getDistanceRatioToCenter(pos1.getZ(), pos2.getZ(), z); - if (((xd * xd) + (yd * yd) + (zd * zd)) <= 1.5D) - world.setBlockState(new BlockPos(x, y, z), state, 3); - } - } - - public static boolean isGamePaused(Minecraft mc) - { - return (mc.currentScreen != null) && (mc.currentScreen.doesGuiPauseGame() || (mc.currentScreen instanceof GuiMainMenu)); - } - - public static String getMCTimeString(long worldTime, long fmt) - { - long HH = (int) (((worldTime / 1000L) + 6) % 24L); - int MM = (int) (((worldTime % 1000L) / 1000.0D) * 60.0D); - boolean am = HH < 12; - HH = HH % fmt; - String hour = ""; - - if (fmt == 24L) - hour = (HH < 10 ? "0" : "") + String.valueOf(HH); - else - hour = String.valueOf(HH == 0 ? 12 : HH); - - String min = (MM < 10 ? "0" : "") + String.valueOf(MM); - return hour + ":" + min + (fmt == 12L ? (am ? "AM" : "PM") : ""); - } - - public static String ticksToTimeString(long ticks) - { - long secs = ticks / 20L; - long mins = secs / 60L; - long hrs = mins / 60L; - long days = hrs / 24L; - - String time = ""; - - if (days > 0L) - time = days + ":"; - - if (hrs > 0L) - time = time + (((hrs % 24L) < 10L) && (days > 0L) ? "0" : "") + (hrs % 24L) + ":"; - - if (mins > 0L) - time = time + (((mins % 60L) < 10L) && (hrs > 0L) ? "0" : "") + (mins % 60L) + ":"; - else - time = time + "0:"; - - time = time + ((secs % 60L) < 10L ? "0" : "") + (secs % 60L); - return time; - } - - public static String stringArrayToString(String[] sa) - { - return stringArrayToString(sa, "#"); - } - - public static String stringArrayToString(String[] sa, String separator) - { - String ret = ""; - for (String s : sa) - ret += separator + " " + s; - - return ret.replaceFirst(separator + " ", ""); - } - - public static String[] loadTextFromURL(URL url, Logger logger) - { - return loadTextFromURL(url, logger, new String[] { "" }, 0); - } - - public static String[] loadTextFromURL(URL url, Logger logger, int timeoutMS) - { - return loadTextFromURL(url, logger, new String[] { "" }, timeoutMS); - } - - public static String[] loadTextFromURL(URL url, Logger logger, String defaultValue) - { - return loadTextFromURL(url, logger, new String[] { defaultValue }, 0); - } - - public static String[] loadTextFromURL(URL url, Logger logger, String defaultValue, int timeoutMS) - { - return loadTextFromURL(url, logger, new String[] { defaultValue }, timeoutMS); - } - - public static String[] loadTextFromURL(URL url, Logger logger, String[] defaultValue) - { - return loadTextFromURL(url, logger, defaultValue, 0); - } - - public static String[] loadTextFromURL(URL url, Logger logger, String[] defaultValue, int timeoutMS) - { - List arraylist = new ArrayList(); - Scanner scanner = null; - try - { - URLConnection uc = url.openConnection(); - uc.setReadTimeout(timeoutMS); - uc.setConnectTimeout(timeoutMS); - uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)"); - scanner = new Scanner(uc.getInputStream(), "UTF-8"); - } - catch (Throwable e) - { - logger.log(Level.WARN, String.format("Error retrieving remote string value at URL %s! Defaulting to %s", url.toString(), stringArrayToString(defaultValue))); - if (bspkrsCoreMod.instance.allowDebugOutput) - e.printStackTrace(); - if (scanner != null) - scanner.close(); - return defaultValue; - } - - while (scanner.hasNextLine()) - { - arraylist.add(scanner.nextLine()); - } - scanner.close(); - return arraylist.toArray(new String[arraylist.size()]); - } - - public static String getLogFileName() - { - try - { - Minecraft.getMinecraft(); - return "ForgeModLoader-client-0.log"; - } - catch (Throwable e) - { - return "ForgeModLoader-server-0.log"; - } - } - - public static String getMinecraftDir() - { - try - { - return Minecraft.getMinecraft().mcDataDir.getAbsolutePath(); - } - catch (NoClassDefFoundError e) - { - return MinecraftServer.getServer().getFile("").getAbsolutePath(); - } - } - - public static String getConfigDir() - { - File configDir = new File(getMinecraftDir(), "config"); - return configDir.getAbsolutePath(); - } - - public static boolean isObfuscatedEnv() - { - try - { - Blocks.class.getField("air"); - return false; - } - catch (Throwable e) - { - return true; - } - } - - public static MovingObjectPosition getPlayerLookingSpot(EntityPlayer player, boolean restrict) - { - float scale = 1.0F; - float pitch = player.prevRotationPitch + ((player.rotationPitch - player.prevRotationPitch) * scale); - float yaw = player.prevRotationYaw + ((player.rotationYaw - player.prevRotationYaw) * scale); - double x = player.prevPosX + ((player.posX - player.prevPosX) * scale); - double y = (player.prevPosY + ((player.posY - player.prevPosY) * scale) + 1.62D); - double z = player.prevPosZ + ((player.posZ - player.prevPosZ) * scale); - Vec3 vector1 = new Vec3(x, y, z); - float cosYaw = MathHelper.cos((-yaw * 0.017453292F) - (float) Math.PI); - float sinYaw = MathHelper.sin((-yaw * 0.017453292F) - (float) Math.PI); - float cosPitch = -MathHelper.cos(-pitch * 0.017453292F); - float sinPitch = MathHelper.sin(-pitch * 0.017453292F); - float pitchAdjustedSinYaw = sinYaw * cosPitch; - float pitchAdjustedCosYaw = cosYaw * cosPitch; - double distance = 500D; - if ((player instanceof EntityPlayerMP) && restrict) - { - distance = ((EntityPlayerMP) player).theItemInWorldManager.getBlockReachDistance(); - } - Vec3 vector2 = vector1.addVector(pitchAdjustedSinYaw * distance, sinPitch * distance, pitchAdjustedCosYaw * distance); - return player.worldObj.rayTraceBlocks(vector1, vector2); - } - - public static void spawnExplosionParticleAtEntity(Entity entity) - { - for (int i = 0; i < 20; ++i) - { - double d0 = entity.worldObj.rand.nextGaussian() * 0.02D; - double d1 = entity.worldObj.rand.nextGaussian() * 0.02D; - double d2 = entity.worldObj.rand.nextGaussian() * 0.02D; - double d3 = 10.0D; - entity.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, (entity.posX + (entity.worldObj.rand.nextFloat() * entity.width * 2.0F)) - entity.width - (d0 * d3), (entity.posY + (entity.worldObj.rand.nextFloat() * entity.height)) - (d1 * d3), (entity.posZ + (entity.worldObj.rand.nextFloat() * entity.width * 2.0F)) - entity.width - (d2 * d3), d0, d1, d2); - } - } -} +package bspkrs.util; + +import java.io.File; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.Scanner; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiMainMenu; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.SoundEvents; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.EnumParticleTypes; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; +import net.minecraft.util.SoundCategory; +import net.minecraft.world.World; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.Logger; + +import bspkrs.bspkrscore.fml.bspkrsCoreMod; + +/* + * @Authors: DaftPVF, bspkrs + * @Desc: Helpers from original Treecapitator, ConnectedDestruction, and FloatingRuins mod code and new utility methods + */ + +public final class CommonUtils +{ + public static boolean isStringAllLettersOrDigits(CharSequence s) + { + for (int i = 0; i < s.length(); i++) + if (!Character.isLetterOrDigit(s.charAt(i))) + return false; + return true; + } + + public static boolean isStringAllLettersOrDigitsOr(CharSequence s, String chrs) + { + for (int i = 0; i < s.length(); i++) + if (!Character.isLetterOrDigit(s.charAt(i)) && !chrs.contains(s.subSequence(i, i + 1))) + return false; + return true; + } + + /* + * List parser helpers + */ + + public static boolean isItemInList(int id, int md, String list) + { + if (list.trim().length() != 0) + { + String[] items = list.split(";"); + for (String item : items) + { + String[] values = item.split(","); + if (parseInt(values[0]) == id) + { + if (values.length == 1) + return true; + else if ((values.length == 2) && (parseInt(values[1]) == md)) + return true; + } + } + } + return false; + } + + public static boolean isIDInList(String id, int md, String list) + { + String[] itemArray = list.split(";"); + for (int i = 0; i < itemArray.length; i++) + { + String[] values = itemArray[i].split(","); + + if ((values.length > 1) && values[0].trim().equals(id) && (parseInt(values[1], -1) == md)) + return true; + else if (values[0].trim().equals(id)) + return true; + } + return false; + } + + public static boolean isIDInList(int id, int md, String list) + { + String[] itemArray = list.split(";"); + for (int i = 0; i < itemArray.length; i++) + { + String[] values = itemArray[i].split(","); + int tempID = parseInt(values[0], Integer.MAX_VALUE); + + if (tempID == Integer.MAX_VALUE) + continue; + + if ((values.length > 1) && (tempID == id) && (parseInt(values[1], -1) == md)) + return true; + else if (tempID == id) + return true; + } + return false; + } + + public static boolean isIDInList(int id, String list) + { + return isIDInList(id, -1, list); + } + + public static int[][][] stringToGroups(String string) + { + List groupList = new ArrayList(); + String[] groups = string.split(";"); + for (String group : groups) + { + groupList.add(stringToGroup(group)); + } + int[][][] res = new int[groupList.size()][][]; + for (int i = 0; i < groupList.size(); i++) + { + res[i] = groupList.get(i); + } + return res; + } + + public static int[][] stringToGroup(String string) + { + List blockList = new ArrayList(); + String[] blocks = string.split(">"); + for (String block : blocks) + { + blockList.add(stringToBlock(block)); + } + int[][] res = new int[blockList.size()][]; + for (int i = 0; i < blockList.size(); i++) + { + res[i] = blockList.get(i); + } + return res; + } + + public static int[] stringToBlock(String string) + { + int[] values = new int[] { 0, -1 }; + String[] src = string.split(","); + if (src.length < 1) + return values; + values[0] = parseInt(src[0]); + if (src.length < 2) + return values; + values[1] = parseInt(src[1]); + return values; + } + + public static boolean isBlockInGroups(int[] block, int[][][] groups) + { + for (int[][] group : groups) + { + if (indexOfBlock(block, group) > -1) + return true; + } + return false; + } + + public static int indexOfBlock(int[] block, int[][] group) + { + for (int i = 0; i < group.length; i++) + { + if (block[0] == group[i][0]) + { + if ((group[i][1] == -1) || (block[1] == group[i][1])) + return i; + } + } + return -1; + } + + public static int[][] getRelatedBlocks(int[] block, int[][][] groups) + { + List blockList = new ArrayList(); + for (int[][] group : groups) + { + if (indexOfBlock(block, group) > -1) + { + for (int i = 0; i < groups.length; i++) + { + if (blockList.contains(group[i])) + continue; + blockList.add(i, group[i]); + } + } + } + int[][] secondary = new int[blockList.size()][]; + for (int i = 0; i < blockList.size(); i++) + { + secondary[i] = blockList.get(i); + } + return secondary; + } + + public static int smallerBlockIndex(int[] block, int[][][] groups) + { + int min = Integer.MAX_VALUE; + for (int[][] group : groups) + { + int i = indexOfBlock(block, group); + if ((i > -1) && (i < min)) + min = i; + } + if (min == Integer.MAX_VALUE) + min = -1; + return min; + } + + public static boolean isMetadataNull(int id, int[][][] groups) + { + for (int[][] group : groups) + { + for (int[] block : group) + { + if ((block[0] == id) && (block[1] == -1)) + return true; + } + } + return false; + } + + /* + * Math helpers + */ + + public static int sqr(int value) + { + return value * value; + } + + public static float sqr(float value) + { + return value * value; + } + + public static int parseInt(String string) + { + return parseInt(string, 0); + } + + public static int parseInt(String string, int defaultValue) + { + try + { + return Integer.parseInt(string.trim()); + } + catch (NumberFormatException ex) + { + return defaultValue; + } + } + + /* + * General Minecraft methods + */ + + public void playAtPitch(int i, World world, EntityPlayer entityplayer) + { + float f = (float) Math.pow(2D, (i - 12) / 12D); + world.playSound(entityplayer, entityplayer.getPosition(), SoundEvents.BLOCK_NOTE_PLING, SoundCategory.getByName("block"), 0.5F, f); + } + + public static boolean moveBlock(World world, BlockPos src, BlockPos tgt, boolean allowBlockReplacement) + { + return moveBlock(world, src, tgt, allowBlockReplacement, BlockNotifyType.ALL); + } + + public static boolean moveBlock(World world, BlockPos src, BlockPos tgt, boolean allowBlockReplacement, int notifyFlag) + { + if (!world.isRemote && !world.isAirBlock(src) && (world.isAirBlock(tgt) || allowBlockReplacement)) + { + IBlockState state = world.getBlockState(src); + + world.setBlockState(tgt, state, notifyFlag); + + TileEntity te = world.getTileEntity(src); + if (te != null) + { + NBTTagCompound nbt = new NBTTagCompound(); + te.writeToNBT(nbt); + + nbt.setInteger("x", tgt.getX()); + nbt.setInteger("y", tgt.getY()); + nbt.setInteger("z", tgt.getZ()); + + te = world.getTileEntity(tgt); + if (te != null) + te.readFromNBT(nbt); + + world.removeTileEntity(src); + } + + world.setBlockToAir(src); + return true; + } + return false; + } + + public static int getHighestGroundBlock(World world, BlockPos pos) + { + while ((pos.getY() > 0) && (world.isAirBlock(pos) || !world.isBlockNormalCube(pos, true) + || world.getBlockState(pos).getBlock().isWood(world, pos))) + { + pos = pos.down(); + } + return pos.getY(); + } + + public static int getFirstNonAirBlockFromTop(World world, BlockPos pos) + { + int y; + int x = pos.getX(); + int z = pos.getZ(); + for (y = world.getActualHeight(); world.isAirBlock(new BlockPos(x, y - 1, z)) && (y > 0); y--) + {} + return y; + } + + public static int getSphericalDistance(BlockPos startPos, BlockPos endPos) + { + return (int) Math.round(Math.sqrt(CommonUtils.sqr(endPos.getX() - startPos.getX()) + + CommonUtils.sqr(endPos.getZ() - startPos.getZ()) + CommonUtils.sqr(endPos.getY() - startPos.getY()))); + } + + public static int getCubicDistance(BlockPos startPos, BlockPos endPos) + { + return Math.abs(endPos.getX() - startPos.getX()) + Math.abs(endPos.getY() - startPos.getY()) + Math.abs(endPos.getZ() - startPos.getZ()); + } + + public static int getHorSquaredDistance(BlockPos pos, BlockPos pos2) + { + return Math.abs(pos2.getX() - pos.getX()) + Math.abs(pos2.getZ() - pos.getZ()); + } + + public static int getVerDistance(BlockPos startPos, BlockPos endPos) + { + return Math.abs(endPos.getY() - startPos.getY()); + } + + public static double getDistanceRatioToCenter(int point1, int point2, int pos) + { + double radius = Math.abs(point2 - point1) / 2D; + double dar = Math.abs(Math.abs(pos - point1) - radius); + return radius != 0.0D ? dar / radius : 0.0D; + } + + public static void setHugeMushroom(World world, Random random, BlockPos pos, IBlockState state) + { + int x = pos.getX(); + int y = pos.getY(); + int z = pos.getZ(); + byte w = 3; + byte cw = 4; + byte h = 4; + fillWithBlocks(world, new BlockPos((x - w) + 1, y, z - w), new BlockPos((x + w) - 1, (y + h) - 1, z - w), state.getBlock().getStateFromMeta(10)); + fillWithBlocks(world, new BlockPos((x - w) + 1, y, z + w), new BlockPos((x + w) - 1, (y + h) - 1, z + w), state.getBlock().getStateFromMeta(10)); + fillWithBlocks(world, new BlockPos(x - w, y, (z - w) + 1), new BlockPos(x - w, (y + h) - 1, (z + w) - 1), state.getBlock().getStateFromMeta(10)); + fillWithBlocks(world, new BlockPos(x + w, y, (z - w) + 1), new BlockPos(x + w, (y + h) - 1, (z + w) - 1), state.getBlock().getStateFromMeta(10)); + fillWithBlocksRounded(world, new BlockPos(x - cw, y + h, z - cw), new BlockPos(x + cw, y + h, z + cw), state.getBlock().getStateFromMeta(14)); + } + + public static void fillWithBlocks(World world, BlockPos pos1, BlockPos pos2, IBlockState state) + { + for (int x = pos1.getX(); x <= pos2.getX(); x++) + for (int y = pos1.getY(); y <= pos2.getY(); y++) + for (int z = pos1.getZ(); z <= pos2.getZ(); z++) + world.setBlockState(new BlockPos(x, y, z), state, 3); + } + + public static void fillWithBlocksRounded(World world, BlockPos pos1, BlockPos pos2, IBlockState state) + { + for (int x = pos1.getX(); x <= pos2.getX(); x++) + for (int y = pos1.getY(); y <= pos2.getY(); y++) + for (int z = pos1.getZ(); z <= pos2.getZ(); z++) + { + double xd = getDistanceRatioToCenter(pos1.getX(), pos2.getX(), x); + double yd = getDistanceRatioToCenter(pos1.getY(), pos2.getY(), y); + double zd = getDistanceRatioToCenter(pos1.getZ(), pos2.getZ(), z); + if (((xd * xd) + (yd * yd) + (zd * zd)) <= 1.5D) + world.setBlockState(new BlockPos(x, y, z), state, 3); + } + } + + public static boolean isGamePaused(Minecraft mc) + { + return (mc.currentScreen != null) && (mc.currentScreen.doesGuiPauseGame() || (mc.currentScreen instanceof GuiMainMenu)); + } + + public static String getMCTimeString(long worldTime, long fmt) + { + long HH = (int) (((worldTime / 1000L) + 6) % 24L); + int MM = (int) (((worldTime % 1000L) / 1000.0D) * 60.0D); + boolean am = HH < 12; + HH = HH % fmt; + String hour = ""; + + if (fmt == 24L) + hour = (HH < 10 ? "0" : "") + String.valueOf(HH); + else + hour = String.valueOf(HH == 0 ? 12 : HH); + + String min = (MM < 10 ? "0" : "") + String.valueOf(MM); + return hour + ":" + min + (fmt == 12L ? (am ? "AM" : "PM") : ""); + } + + public static String ticksToTimeString(long ticks) + { + long secs = ticks / 20L; + long mins = secs / 60L; + long hrs = mins / 60L; + long days = hrs / 24L; + + String time = ""; + + if (days > 0L) + time = days + ":"; + + if (hrs > 0L) + time = time + (((hrs % 24L) < 10L) && (days > 0L) ? "0" : "") + (hrs % 24L) + ":"; + + if (mins > 0L) + time = time + (((mins % 60L) < 10L) && (hrs > 0L) ? "0" : "") + (mins % 60L) + ":"; + else + time = time + "0:"; + + time = time + ((secs % 60L) < 10L ? "0" : "") + (secs % 60L); + return time; + } + + public static String stringArrayToString(String[] sa) + { + return stringArrayToString(sa, "#"); + } + + public static String stringArrayToString(String[] sa, String separator) + { + String ret = ""; + for (String s : sa) + ret += separator + " " + s; + + return ret.replaceFirst(separator + " ", ""); + } + + public static String[] loadTextFromURL(URL url, Logger logger) + { + return loadTextFromURL(url, logger, new String[] { "" }, 0); + } + + public static String[] loadTextFromURL(URL url, Logger logger, int timeoutMS) + { + return loadTextFromURL(url, logger, new String[] { "" }, timeoutMS); + } + + public static String[] loadTextFromURL(URL url, Logger logger, String defaultValue) + { + return loadTextFromURL(url, logger, new String[] { defaultValue }, 0); + } + + public static String[] loadTextFromURL(URL url, Logger logger, String defaultValue, int timeoutMS) + { + return loadTextFromURL(url, logger, new String[] { defaultValue }, timeoutMS); + } + + public static String[] loadTextFromURL(URL url, Logger logger, String[] defaultValue) + { + return loadTextFromURL(url, logger, defaultValue, 0); + } + + public static String[] loadTextFromURL(URL url, Logger logger, String[] defaultValue, int timeoutMS) + { + List arraylist = new ArrayList(); + Scanner scanner = null; + try + { + URLConnection uc = url.openConnection(); + uc.setReadTimeout(timeoutMS); + uc.setConnectTimeout(timeoutMS); + uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)"); + scanner = new Scanner(uc.getInputStream(), "UTF-8"); + } + catch (Throwable e) + { + logger.log(Level.WARN, String.format("Error retrieving remote string value at URL %s! Defaulting to %s", url.toString(), stringArrayToString(defaultValue))); + if (bspkrsCoreMod.instance.allowDebugOutput) + e.printStackTrace(); + if (scanner != null) + scanner.close(); + return defaultValue; + } + + while (scanner.hasNextLine()) + { + arraylist.add(scanner.nextLine()); + } + scanner.close(); + return arraylist.toArray(new String[arraylist.size()]); + } + + public static String getLogFileName() + { + try + { + Minecraft.getMinecraft(); + return "ForgeModLoader-client-0.log"; + } + catch (Throwable e) + { + return "ForgeModLoader-server-0.log"; + } + } + + public static String getMinecraftDir() + { + try + { + return Minecraft.getMinecraft().mcDataDir.getAbsolutePath(); + } + catch (NoClassDefFoundError e) + { +//TODO: find an alternative static way to get a handle on MinecraftServer +// this is not a static reference anymore +// return MinecraftServer.getServer().getFile("").getAbsolutePath(); +// just throw it + throw e; + } + } + + public static String getConfigDir() + { + File configDir = new File(getMinecraftDir(), "config"); + return configDir.getAbsolutePath(); + } + + public static boolean isObfuscatedEnv() + { + try + { + Blocks.class.getField("air"); + return false; + } + catch (Throwable e) + { + return true; + } + } + + public static RayTraceResult getPlayerLookingSpot(EntityPlayer player, boolean restrict) + { + float scale = 1.0F; + float pitch = player.prevRotationPitch + ((player.rotationPitch - player.prevRotationPitch) * scale); + float yaw = player.prevRotationYaw + ((player.rotationYaw - player.prevRotationYaw) * scale); + double x = player.prevPosX + ((player.posX - player.prevPosX) * scale); + double y = (player.prevPosY + ((player.posY - player.prevPosY) * scale) + 1.62D); + double z = player.prevPosZ + ((player.posZ - player.prevPosZ) * scale); + Vec3d vector1 = new Vec3d(x, y, z); + float cosYaw = MathHelper.cos((-yaw * 0.017453292F) - (float) Math.PI); + float sinYaw = MathHelper.sin((-yaw * 0.017453292F) - (float) Math.PI); + float cosPitch = -MathHelper.cos(-pitch * 0.017453292F); + float sinPitch = MathHelper.sin(-pitch * 0.017453292F); + float pitchAdjustedSinYaw = sinYaw * cosPitch; + float pitchAdjustedCosYaw = cosYaw * cosPitch; + double distance = 500D; + if ((player instanceof EntityPlayerMP) && restrict) + { + distance = ((EntityPlayerMP) player).interactionManager.getBlockReachDistance(); + } + Vec3d vector2 = vector1.addVector(pitchAdjustedSinYaw * distance, sinPitch * distance, pitchAdjustedCosYaw * distance); + return player.worldObj.rayTraceBlocks(vector1, vector2); + } + + public static void spawnExplosionParticleAtEntity(Entity entity) + { + for (int i = 0; i < 20; ++i) + { + double d0 = entity.worldObj.rand.nextGaussian() * 0.02D; + double d1 = entity.worldObj.rand.nextGaussian() * 0.02D; + double d2 = entity.worldObj.rand.nextGaussian() * 0.02D; + double d3 = 10.0D; + entity.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, (entity.posX + (entity.worldObj.rand.nextFloat() * entity.width * 2.0F)) - entity.width - (d0 * d3), (entity.posY + (entity.worldObj.rand.nextFloat() * entity.height)) - (d1 * d3), (entity.posZ + (entity.worldObj.rand.nextFloat() * entity.width * 2.0F)) - entity.width - (d2 * d3), d0, d1, d2); + } + } +} diff --git a/src/main/java/bspkrs/util/Const.java b/src/main/java/bspkrs/util/Const.java index ec70f0a..010bdd5 100644 --- a/src/main/java/bspkrs/util/Const.java +++ b/src/main/java/bspkrs/util/Const.java @@ -2,6 +2,7 @@ public class Const { - public static String MCVERSION = "@MINECRAFT_VERSION@"; - public static String VERSION_URL = "http://bspk.rs"; + public static final String MCVERSION = "@MINECRAFT_VERSION@"; + public static final String VERSION_URL_BASE = "http://bspk.rs/Minecraft/"; + public static final String VERSION_URL_EXT = ".json"; } diff --git a/src/main/java/bspkrs/util/ModVersionChecker.java b/src/main/java/bspkrs/util/ModVersionChecker.java deleted file mode 100644 index a4b603c..0000000 --- a/src/main/java/bspkrs/util/ModVersionChecker.java +++ /dev/null @@ -1,232 +0,0 @@ -package bspkrs.util; - -import java.io.File; -import java.net.URL; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.prefs.Preferences; - -import net.minecraft.util.StatCollector; -import bspkrs.bspkrscore.fml.bspkrsCoreMod; - -import com.google.common.collect.Ordering; - -/** - * This class retrieves a version string from a text file at a given URL and compares it against the locally provided version string. It - * uses a natural order comparator to determine if the remote version is newer than our local version. - * - * @author bspkrs - */ - -public class ModVersionChecker -{ - private static final Map versionCheckerMap = new HashMap(); - private URL versionURL; - private final String modID; - private String newVersion; - private final String currentVersion; - private String updateURL; - private String[] loadMsg; - private String[] inGameMsg; - private File trackerFile; - private File trackerDir; - private static Preferences versionCheckTracker; - private String lastNewVersionFound; - private final String CHECK_ERROR = "check_error"; - private final boolean errorDetected; - private int runsSinceLastMessage; - - public ModVersionChecker(String modID, String curVer, String versionURL, String updateURL, String[] loadMsg, String[] inGameMsg) - { - this(modID, curVer, versionURL, updateURL, loadMsg, inGameMsg, bspkrsCoreMod.instance.updateTimeoutMilliseconds); - } - - public ModVersionChecker(String modID, String curVer, String versionURL, String updateURL, String[] loadMsg, String[] inGameMsg, int timeoutMS) - { - this.modID = modID; - this.currentVersion = curVer; - this.updateURL = updateURL; - this.loadMsg = loadMsg; - this.inGameMsg = inGameMsg; - - try - { - if (versionURL.startsWith("http://dl.dropboxusercontent.com")) - versionURL = versionURL.replaceFirst("http", "https"); - - this.versionURL = new URL(versionURL); - BSLog.info("Initializing ModVersionChecker for mod %s", modID); - } - catch (Throwable e) - { - BSLog.warning("Error initializing ModVersionChecker for mod %s: %s", modID, e.getMessage()); - } - - String[] versionLines = CommonUtils.loadTextFromURL(this.versionURL, BSLog.INSTANCE.getLogger(), new String[] { CHECK_ERROR }, timeoutMS); - - if (versionLines.length == 0 || versionLines[0].trim().equals("")) - newVersion = CHECK_ERROR; - else - newVersion = versionLines[0].trim(); - - errorDetected = newVersion.equals(CHECK_ERROR); - - // Keep track of the versions we've seen to keep from nagging players with new version notifications beyond the first one - if (trackerDir == null) - { - trackerDir = new File(CommonUtils.getConfigDir() + "/bspkrsCore/"); - if (trackerDir.exists()) - { - trackerFile = new File(trackerDir, "ModVersionCheckerTracking.txt"); - trackerFile.delete(); - trackerDir.delete(); - } - - trackerDir = new File(CommonUtils.getConfigDir()); - trackerFile = new File(trackerDir, "bspkrs_ModVersionCheckerTracking.txt"); - if ((trackerFile.exists())) - trackerFile.delete(); - } - - if (versionCheckTracker == null) - versionCheckTracker = Preferences.userNodeForPackage(this.getClass()).node("modversiontracker" + Const.MCVERSION); - - if (!(new StringBuilder("@").append("MOD_VERSION@")).toString().equals(currentVersion) && !"${mod_version}".equals(currentVersion)) - { - lastNewVersionFound = versionCheckTracker.get(modID, currentVersion); - - if (lastNewVersionFound.equals("")) - lastNewVersionFound = currentVersion; - - runsSinceLastMessage = versionCheckTracker.node("runs_since_last_message").getInt(modID, 0); - - if (errorDetected) - newVersion = lastNewVersionFound; - - if (!errorDetected && !isCurrentVersion(lastNewVersionFound, newVersion)) - { - runsSinceLastMessage = 0; - lastNewVersionFound = newVersion; - } - else - runsSinceLastMessage = runsSinceLastMessage % 10; - - versionCheckTracker.node("runs_since_last_message").putInt(modID, runsSinceLastMessage + 1); - versionCheckTracker.put(modID, lastNewVersionFound); - } - - // Override instantiated updateURL with second line of version file if it exists and is non-blank - if (versionLines.length > 1 && versionLines[1].trim().length() != 0) - this.updateURL = versionLines[1]; - - setLoadMessage(loadMsg); - setInGameMessage(inGameMsg); - - versionCheckerMap.put(modID.toLowerCase(Locale.US), this); - } - - public ModVersionChecker(String modName, String oldVer, String versionURL, String updateURL) - { - this(modName, oldVer, versionURL, updateURL, - new String[] { "{modID} {oldVer} is out of date! Visit {updateURL} to download the latest release ({newVer})." }, - new String[] { "\247c{modID} {newVer} \247ris out! Download the latest from \247a{updateURL}\247r" }); - } - - public void checkVersionWithLogging() - { - if (!isCurrentVersion(currentVersion, newVersion)) - for (String msg : loadMsg) - BSLog.info(msg); - } - - public void setLoadMessage(String[] loadMsg) - { - this.loadMsg = loadMsg; - - for (int i = 0; i < this.loadMsg.length; i++) - this.loadMsg[i] = replaceAllTags(this.loadMsg[i]); - } - - public void setInGameMessage(String[] inGameMsg) - { - this.inGameMsg = inGameMsg; - - for (int i = 0; i < this.inGameMsg.length; i++) - this.inGameMsg[i] = replaceAllTags(this.inGameMsg[i]); - - } - - public String[] getLoadMessage() - { - return loadMsg; - } - - public String[] getInGameMessage() - { - return inGameMsg; - } - - public URL getVersionURL() - { - return versionURL; - } - - public String getNewVersion() - { - return newVersion; - } - - public String getCurrentVersion() - { - return currentVersion; - } - - public String getUpdateURL() - { - return updateURL; - } - - public static Map getVersionCheckerMap() - { - return versionCheckerMap; - } - - public boolean isCurrentVersion() - { - return errorDetected || isCurrentVersion(runsSinceLastMessage == 0 ? currentVersion : lastNewVersionFound, newVersion); - } - - public static boolean isCurrentVersion(String oldVer, String newVer) - { - return Ordering.natural().compare(oldVer, newVer) >= 0; - } - - private String replaceAllTags(String s) - { - return s.replace("{oldVer}", currentVersion).replace("{newVer}", newVersion).replace("{modID}", modID).replace("{updateURL}", updateURL); - } - - public static String[] checkVersionForMod(String modID) - { - String[] r = { "" }; - - if (versionCheckerMap.containsKey(modID.toLowerCase(Locale.US))) - { - ModVersionChecker versionChecker = versionCheckerMap.get(modID.toLowerCase(Locale.US)); - if (!versionChecker.errorDetected) - { - if (!isCurrentVersion(versionChecker.currentVersion, versionChecker.newVersion)) - r = versionChecker.getInGameMessage(); - else - r = new String[] { StatCollector.translateToLocalFormatted("bspkrs.modversionchecker.uptodate", versionChecker.modID) }; - } - else - r = new String[] { StatCollector.translateToLocalFormatted("bspkrs.modversionchecker.error", versionChecker.modID) }; - } - else - r = new String[] { StatCollector.translateToLocal("bspkrs.modversionchecker.invalidmodid") }; - - return r; - } -} diff --git a/src/main/java/bspkrs/util/ModulusBlockID.java b/src/main/java/bspkrs/util/ModulusBlockID.java index 187d4b6..ea866f8 100644 --- a/src/main/java/bspkrs/util/ModulusBlockID.java +++ b/src/main/java/bspkrs/util/ModulusBlockID.java @@ -2,9 +2,10 @@ import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; -import net.minecraft.util.BlockPos; +import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +@Deprecated // TODO: replace with a IBlockState implementation public class ModulusBlockID extends BlockID { public final int metadataModulus; diff --git a/src/main/java/bspkrs/util/UniqueNameListGenerator.java b/src/main/java/bspkrs/util/UniqueNameListGenerator.java index 3c43426..38e4e75 100644 --- a/src/main/java/bspkrs/util/UniqueNameListGenerator.java +++ b/src/main/java/bspkrs/util/UniqueNameListGenerator.java @@ -1,7 +1,6 @@ package bspkrs.util; import java.io.File; -import java.io.FileWriter; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -45,7 +44,7 @@ public void run() listFile.createNewFile(); - PrintWriter out = new PrintWriter(new FileWriter(listFile)); + PrintWriter out = new PrintWriter(listFile, "UTF-8"); out.println("# generated by bspkrsCore " + new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date())); out.println(); diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index ee6ecb4..d6ee3a7 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -5,7 +5,7 @@ "name": "bspkrsCore", "description": "Shared classes used in the mods maintained by bspkrs.", "version": "${mod_version}", - "mcversion": "${minecraft_version}", + "mcversion": "${minecraft_maxversion}", "url": "http://www.minecraftforum.net/topic/1114612-/", "updateUrl": "", "authorList": [ "DaftPVF", "bspkrs" ], @@ -13,8 +13,8 @@ "logoFile": "", "screenshots": [], "parent": "", - "requiredMods": ["Forge@[${forge_version},)"], - "dependencies": ["Forge@[${forge_version},)"], + "requiredMods": ["Forge@[${forge_version},${forge_versionlimit})"], + "dependencies": ["Forge@[${forge_version},${forge_versionlimit})"], "dependants": [], "useDependencyInformation": "true" }] diff --git a/src/test/java/bspkrs/testmod/ClientProxy.java b/src/test/java/bspkrs/testmod/ClientProxy.java new file mode 100644 index 0000000..c42bdd1 --- /dev/null +++ b/src/test/java/bspkrs/testmod/ClientProxy.java @@ -0,0 +1,9 @@ +package bspkrs.testmod; + +public class ClientProxy extends CommonProxy +{ + @Override + protected void registerTickHandler() + { + } +} diff --git a/testmod/bspkrs/testmod/CommonProxy.java b/src/test/java/bspkrs/testmod/CommonProxy.java similarity index 100% rename from testmod/bspkrs/testmod/CommonProxy.java rename to src/test/java/bspkrs/testmod/CommonProxy.java diff --git a/testmod/bspkrs/testmod/GuiTestModConfig.java b/src/test/java/bspkrs/testmod/GuiTestModConfig.java similarity index 100% rename from testmod/bspkrs/testmod/GuiTestModConfig.java rename to src/test/java/bspkrs/testmod/GuiTestModConfig.java diff --git a/testmod/bspkrs/testmod/ModGuiFactoryHandler.java b/src/test/java/bspkrs/testmod/ModGuiFactoryHandler.java similarity index 100% rename from testmod/bspkrs/testmod/ModGuiFactoryHandler.java rename to src/test/java/bspkrs/testmod/ModGuiFactoryHandler.java diff --git a/src/test/java/bspkrs/testmod/TMTicker.java b/src/test/java/bspkrs/testmod/TMTicker.java new file mode 100644 index 0000000..b9bf2ef --- /dev/null +++ b/src/test/java/bspkrs/testmod/TMTicker.java @@ -0,0 +1,32 @@ +package bspkrs.testmod; + +import net.minecraft.client.Minecraft; +import net.minecraftforge.fml.client.FMLClientHandler; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class TMTicker +{ + private Minecraft mcClient; + private static boolean isRegistered = false; + + public TMTicker() + { + mcClient = FMLClientHandler.instance().getClient(); + isRegistered = true; + } + + @SubscribeEvent + public void onTick(ClientTickEvent event) + { + + } + + public static boolean isRegistered() + { + return isRegistered; + } +} diff --git a/testmod/bspkrs/testmod/TestMod.java b/src/test/java/bspkrs/testmod/TestMod.java similarity index 62% rename from testmod/bspkrs/testmod/TestMod.java rename to src/test/java/bspkrs/testmod/TestMod.java index ae28180..8debe1b 100644 --- a/testmod/bspkrs/testmod/TestMod.java +++ b/src/test/java/bspkrs/testmod/TestMod.java @@ -1,8 +1,6 @@ package bspkrs.testmod; -import bspkrs.bspkrscore.fml.bspkrsCoreMod; import bspkrs.util.Const; -import bspkrs.util.ModVersionChecker; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; @@ -13,39 +11,27 @@ import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = "TestMod", name = "TestMod", version = "2.0", dependencies = "required-after:bspkrsCore", - guiFactory = "bspkrs.testmod.ModGuiFactoryHandler") + guiFactory = "bspkrs.testmod.ModGuiFactoryHandler", updateJSON = Const.VERSION_URL_BASE + "TestMod" + Const.VERSION_URL_EXT) public class TestMod { @Metadata(value = "TestMod") public static ModMetadata metadata; - + @Instance(value = "TestMod") public static TestMod instance; - + @SidedProxy(clientSide = "bspkrs.testmod.ClientProxy", serverSide = "bspkrs.testmod.CommonProxy") public static CommonProxy proxy; - - protected ModVersionChecker versionChecker; - private final String versionURL = Const.VERSION_URL + "/Minecraft/TestMod/testMod.version"; - private final String mcfTopic = "http://www.minecraftforum.net/topic/1114612-"; - + @EventHandler public void preInit(FMLPreInitializationEvent event) { - metadata = event.getModMetadata(); - TestModSimpleConfig.initConfig(event.getSuggestedConfigurationFile()); } - + @EventHandler public void init(FMLInitializationEvent event) { - if (bspkrsCoreMod.instance.allowUpdateCheck) - { - versionChecker = new ModVersionChecker(metadata.name, metadata.version, versionURL, mcfTopic); - versionChecker.checkVersionWithLogging(); - } - proxy.registerTickHandler(); } } diff --git a/testmod/bspkrs/testmod/TestModSimpleConfig.java b/src/test/java/bspkrs/testmod/TestModSimpleConfig.java similarity index 100% rename from testmod/bspkrs/testmod/TestModSimpleConfig.java rename to src/test/java/bspkrs/testmod/TestModSimpleConfig.java diff --git a/testmod/bspkrs/testmod/ClientProxy.java b/testmod/bspkrs/testmod/ClientProxy.java deleted file mode 100644 index 68ca03f..0000000 --- a/testmod/bspkrs/testmod/ClientProxy.java +++ /dev/null @@ -1,13 +0,0 @@ -package bspkrs.testmod; - -import net.minecraftforge.fml.common.FMLCommonHandler; - -public class ClientProxy extends CommonProxy -{ - @Override - protected void registerTickHandler() - { - if (!TMTicker.isRegistered()) - FMLCommonHandler.instance().bus().register(new TMTicker()); - } -} diff --git a/testmod/bspkrs/testmod/TMTicker.java b/testmod/bspkrs/testmod/TMTicker.java deleted file mode 100644 index 1f63a8f..0000000 --- a/testmod/bspkrs/testmod/TMTicker.java +++ /dev/null @@ -1,51 +0,0 @@ -package bspkrs.testmod; - -import net.minecraft.client.Minecraft; -import net.minecraft.util.ChatComponentText; -import bspkrs.bspkrscore.fml.bspkrsCoreMod; -import net.minecraftforge.fml.client.FMLClientHandler; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class TMTicker -{ - private Minecraft mcClient; - private static boolean isRegistered = false; - - public TMTicker() - { - mcClient = FMLClientHandler.instance().getClient(); - isRegistered = true; - } - - @SubscribeEvent - public void onTick(ClientTickEvent event) - { - boolean keepTicking = !(mcClient != null && mcClient.thePlayer != null && mcClient.theWorld != null); - - if (!event.phase.equals(Phase.START)) - { - if (bspkrsCoreMod.instance.allowUpdateCheck && !keepTicking) - if (TestMod.instance.versionChecker != null) - if (!TestMod.instance.versionChecker.isCurrentVersion()) - for (String msg : TestMod.instance.versionChecker.getInGameMessage()) - mcClient.thePlayer.addChatMessage(new ChatComponentText(msg)); - - if (!keepTicking) - { - FMLCommonHandler.instance().bus().unregister(this); - isRegistered = false; - } - } - } - - public static boolean isRegistered() - { - return isRegistered; - } -}