From bda260b10feeb352a6253a9c1397c3fb15fd11c2 Mon Sep 17 00:00:00 2001 From: tterrag1098 Date: Tue, 8 Sep 2015 23:45:49 -0400 Subject: [PATCH] Format everything consistently --- src/main/java/com/enderio/core/EnderCore.java | 2 +- src/main/java/com/enderio/core/IEnderMod.java | 16 +- .../core/api/client/gui/IGuiOverlay.java | 1 - .../core/api/client/model/IEnderModel.java | 35 +- .../render/IConnectedTextureRenderer.java | 2 +- .../core/api/client/render/IWidgetIcon.java | 1 - .../core/api/client/render/IWidgetMap.java | 2 +- .../api/common/enchant/IAdvancedEnchant.java | 17 +- .../com/enderio/core/api/common/imc/IMC.java | 26 +- .../com/enderio/core/client/ClientProxy.java | 1 - .../client/EnderCoreModConflictException.java | 4 +- .../core/client/config/BaseConfigGui.java | 234 ++-- .../core/client/gui/GuiContainerBase.java | 149 +- .../core/client/gui/GuiScreenBase.java | 33 +- .../core/client/gui/ToolTipManager.java | 12 +- .../gui/bettermodlist/EventHandlerGui.java | 59 +- .../core/client/gui/button/ColorButton.java | 18 +- .../core/client/gui/button/IIconButton.java | 7 +- .../core/client/gui/button/IconButton.java | 4 +- .../client/gui/button/IconToggleButton.java | 4 +- .../core/client/gui/button/ItemButton.java | 9 +- .../core/client/gui/widget/GhostSlot.java | 2 +- .../client/gui/widget/GuiScrollableList.java | 60 +- .../core/client/gui/widget/GuiToolTip.java | 22 +- .../core/client/gui/widget/TemplateSlot.java | 2 +- .../client/gui/widget/TextFieldEnder.java | 4 +- .../core/client/handlers/ClientHandler.java | 19 +- .../handlers/EnchantTooltipHandler.java | 46 +- .../handlers/OreDictTooltipHandler.java | 48 +- .../handlers/SpecialTooltipHandler.java | 43 +- .../core/client/render/BoundingBox.java | 43 +- .../render/ConnectedTextureRenderer.java | 76 +- .../core/client/render/CubeRenderer.java | 64 +- .../client/render/CustomCubeRenderer.java | 6 +- .../client/render/CustomRenderBlocks.java | 125 +- .../core/client/render/CustomWidgetIcon.java | 2 +- .../render/DirectionalModelRenderer.java | 242 ++-- .../core/client/render/EnderWidget.java | 2 +- .../enderio/core/client/render/IconUtil.java | 4 +- .../client/render/TechneModelRenderer.java | 8 +- .../core/client/render/TechneUtil.java | 27 +- .../core/client/render/VertexRotation.java | 2 +- .../client/render/VertexRotationFacing.java | 12 +- .../enderio/core/client/sound/BlockSound.java | 65 +- .../com/enderio/core/common/CommonProxy.java | 6 +- .../java/com/enderio/core/common/OreDict.java | 120 +- .../enderio/core/common/TileEntityEnder.java | 2 +- .../common/command/CommandReloadConfigs.java | 170 +-- .../common/command/CommandScoreboardInfo.java | 139 +- .../core/common/compat/CompatRegistry.java | 157 +-- .../enderio/core/common/compat/ICompat.java | 9 +- .../common/config/AbstractConfigHandler.java | 1231 ++++++++--------- .../core/common/config/BaseConfigFactory.java | 39 +- .../core/common/config/ConfigProcessor.java | 687 +++++---- .../common/config/ITweakConfigHandler.java | 5 +- .../core/common/config/TypeAdapterBase.java | 57 +- .../core/common/config/annot/Comment.java | 15 +- .../core/common/config/annot/Config.java | 22 +- .../core/common/config/annot/NoSync.java | 9 +- .../core/common/config/annot/Range.java | 43 +- .../core/common/config/annot/RestartReq.java | 22 +- .../core/common/enchant/EnchantAutoSmelt.java | 102 +- .../core/common/enchant/EnchantXPBoost.java | 93 +- .../core/common/event/ArrowUpdateEvent.java | 10 +- .../common/event/ConfigFileChangedEvent.java | 21 +- .../core/common/event/ItemStackEvent.java | 78 +- .../core/common/handlers/FireworkHandler.java | 95 +- .../handlers/RightClickCropHandler.java | 155 +-- .../core/common/handlers/XPBoostHandler.java | 207 ++- .../enderio/core/common/imc/IMCRegistry.java | 89 +- .../imc/handlers/IMCRightClickCrop.java | 39 +- .../common/network/CompressedDataInput.java | 2 +- .../common/network/CompressedDataOutput.java | 2 +- .../common/network/EnderPacketHandler.java | 2 +- .../common/network/MessageTileEntity.java | 2 +- .../core/common/network/MessageTileNBT.java | 8 +- .../core/common/network/NetworkUtil.java | 6 +- .../core/common/network/PacketProgress.java | 2 +- .../common/transform/EnderCoreMethods.java | 355 ++--- .../common/transform/EnderCorePlugin.java | 56 +- .../transform/EnderCoreTransformer.java | 475 +++---- .../transform/EnderCoreTransformerClient.java | 132 +- .../core/common/tweaks/SlabRecipes.java | 53 +- .../com/enderio/core/common/tweaks/Tweak.java | 21 +- .../enderio/core/common/tweaks/Tweaks.java | 16 +- .../enderio/core/common/util/BlockCoord.java | 14 +- .../core/common/util/CreativeTabsCustom.java | 79 +- .../enderio/core/common/util/DyeColor.java | 48 +- .../core/common/util/EnderFileUtils.java | 600 ++++---- .../core/common/util/EnderRegistryUtils.java | 199 ++- .../core/common/util/EnderStringUtils.java | 224 ++- .../enderio/core/common/util/FluidUtil.java | 100 +- .../common/util/ForgeDirectionOffsets.java | 4 +- .../core/common/util/InventoryWrapper.java | 8 +- .../enderio/core/common/util/ItemUtil.java | 3 +- .../com/enderio/core/common/util/Log.java | 1 - .../core/common/util/MetadataUtil.java | 6 +- .../core/common/util/PermanentCache.java | 4 +- .../enderio/core/common/util/PlayerUtil.java | 4 +- .../core/common/util/RegisterTime.java | 26 +- .../common/util/ResourcePackAssembler.java | 399 +++--- .../core/common/util/RoundRobinIterator.java | 10 +- .../enderio/core/common/util/Scheduler.java | 191 ++- .../enderio/core/common/util/SoundUtil.java | 7 +- .../core/common/util/TextureErrorRemover.java | 85 +- .../com/enderio/core/common/util/Util.java | 165 ++- .../enderio/core/common/util/WorldCache.java | 4 +- .../blockiterators/AbstractBlockIterator.java | 30 +- .../blockiterators/CubicBlockIterator.java | 58 +- .../blockiterators/PlanarBlockIterator.java | 96 +- .../enderio/core/common/vecmath/Camera.java | 20 +- .../enderio/core/common/vecmath/Matrix4d.java | 41 +- .../enderio/core/common/vecmath/Quat4d.java | 2 +- .../core/common/vecmath/VecmathUtil.java | 76 +- .../enderio/core/common/vecmath/Vector3f.java | 6 +- .../enderio/core/common/vecmath/Vertex.java | 12 +- .../core/common/vecmath/ViewFrustum.java | 2 +- 117 files changed, 4014 insertions(+), 4824 deletions(-) diff --git a/src/main/java/com/enderio/core/EnderCore.java b/src/main/java/com/enderio/core/EnderCore.java index efcbc0e..37f002b 100644 --- a/src/main/java/com/enderio/core/EnderCore.java +++ b/src/main/java/com/enderio/core/EnderCore.java @@ -93,7 +93,7 @@ public class EnderCore implements IEnderMod { @EventHandler public void init(FMLInitializationEvent event) { EnderPacketHandler.init(); - + for (IConfigHandler c : configs) { c.initHook(); } diff --git a/src/main/java/com/enderio/core/IEnderMod.java b/src/main/java/com/enderio/core/IEnderMod.java index 78486f8..49fa005 100644 --- a/src/main/java/com/enderio/core/IEnderMod.java +++ b/src/main/java/com/enderio/core/IEnderMod.java @@ -1,15 +1,15 @@ package com.enderio.core; /** - * By implementing this interface, your mod package will automatically be added to the handler search and other package based functionality. + * By implementing this interface, your mod package will automatically be added + * to the handler search and other package based functionality. * * It also provides convenience functions for later use. */ -public interface IEnderMod -{ - String modid(); - - String name(); - - String version(); +public interface IEnderMod { + String modid(); + + String name(); + + String version(); } diff --git a/src/main/java/com/enderio/core/api/client/gui/IGuiOverlay.java b/src/main/java/com/enderio/core/api/client/gui/IGuiOverlay.java index 1c9f42c..b5d35f6 100644 --- a/src/main/java/com/enderio/core/api/client/gui/IGuiOverlay.java +++ b/src/main/java/com/enderio/core/api/client/gui/IGuiOverlay.java @@ -6,7 +6,6 @@ public interface IGuiOverlay { void init(IGuiScreen screen); - Rectangle getBounds(); void draw(int mouseX, int mouseY, float partialTick); diff --git a/src/main/java/com/enderio/core/api/client/model/IEnderModel.java b/src/main/java/com/enderio/core/api/client/model/IEnderModel.java index 93f2035..e1c6f3e 100644 --- a/src/main/java/com/enderio/core/api/client/model/IEnderModel.java +++ b/src/main/java/com/enderio/core/api/client/model/IEnderModel.java @@ -5,22 +5,23 @@ import net.minecraft.client.model.ModelRenderer; /** * To be used on techne-style box models */ -public interface IEnderModel -{ - /** - * Renders all parts of the model - * - * @param size - Size of the model (usually 0.0625f) - */ - public void render(float size); +public interface IEnderModel { + /** + * Renders all parts of the model + * + * @param size + * - Size of the model (usually 0.0625f) + */ + public void render(float size); - /** - * Rotates the model part in the given directions - * - * @param model - part of the model to rotate - * @param x - * @param y - * @param z - */ - public void setRotation(ModelRenderer model, float x, float y, float z); + /** + * Rotates the model part in the given directions + * + * @param model + * - part of the model to rotate + * @param x + * @param y + * @param z + */ + public void setRotation(ModelRenderer model, float x, float y, float z); } diff --git a/src/main/java/com/enderio/core/api/client/render/IConnectedTextureRenderer.java b/src/main/java/com/enderio/core/api/client/render/IConnectedTextureRenderer.java index f781246..7ba4e6c 100644 --- a/src/main/java/com/enderio/core/api/client/render/IConnectedTextureRenderer.java +++ b/src/main/java/com/enderio/core/api/client/render/IConnectedTextureRenderer.java @@ -1,7 +1,7 @@ package com.enderio.core.api.client.render; public interface IConnectedTextureRenderer { - + boolean matchesMetadata(int meta1, int meta2); } diff --git a/src/main/java/com/enderio/core/api/client/render/IWidgetIcon.java b/src/main/java/com/enderio/core/api/client/render/IWidgetIcon.java index efdc5bd..bd3beae 100644 --- a/src/main/java/com/enderio/core/api/client/render/IWidgetIcon.java +++ b/src/main/java/com/enderio/core/api/client/render/IWidgetIcon.java @@ -2,7 +2,6 @@ package com.enderio.core.api.client.render; import javax.annotation.Nullable; - public interface IWidgetIcon { int getX(); diff --git a/src/main/java/com/enderio/core/api/client/render/IWidgetMap.java b/src/main/java/com/enderio/core/api/client/render/IWidgetMap.java index c0c97a6..a753a0b 100644 --- a/src/main/java/com/enderio/core/api/client/render/IWidgetMap.java +++ b/src/main/java/com/enderio/core/api/client/render/IWidgetMap.java @@ -53,7 +53,7 @@ public interface IWidgetMap { @Override public void render(IWidgetIcon widget, double x, double y, double width, double height, double zLevel, boolean doDraw, boolean flipY) { - + Tessellator tessellator = Tessellator.instance; if (doDraw) { RenderUtil.bindTexture(getTexture()); diff --git a/src/main/java/com/enderio/core/api/common/enchant/IAdvancedEnchant.java b/src/main/java/com/enderio/core/api/common/enchant/IAdvancedEnchant.java index 5e830d7..89d636a 100644 --- a/src/main/java/com/enderio/core/api/common/enchant/IAdvancedEnchant.java +++ b/src/main/java/com/enderio/core/api/common/enchant/IAdvancedEnchant.java @@ -5,13 +5,12 @@ import net.minecraft.item.ItemStack; /** * Allows your enchants to have some flavor or descrtiption text underneath them */ -public interface IAdvancedEnchant -{ - /** - * Get the detail for this itemstack - * - * @param stack - * @return a list of Strings to be bulleted under the enchantment - */ - public String[] getTooltipDetails(ItemStack stack); +public interface IAdvancedEnchant { + /** + * Get the detail for this itemstack + * + * @param stack + * @return a list of Strings to be bulleted under the enchantment + */ + public String[] getTooltipDetails(ItemStack stack); } diff --git a/src/main/java/com/enderio/core/api/common/imc/IMC.java b/src/main/java/com/enderio/core/api/common/imc/IMC.java index 93bd36a..7ce9a11 100644 --- a/src/main/java/com/enderio/core/api/common/imc/IMC.java +++ b/src/main/java/com/enderio/core/api/common/imc/IMC.java @@ -1,16 +1,16 @@ package com.enderio.core.api.common.imc; -public class IMC -{ - /** - * Use an IMC event with this string to add a right click crop as compatible. Syntax is a single - * string, with '|' separating the values, in the order seed, block, meta, resetMeta. A valid - * entry would look like this: - *

- * {@literal "minecraft:wheat_seeds|minecraft:wheat|7|0"} - *

- * The "reset meta" is the metadata that the plant will be reset to when it is harvested. - * Regular meta is the meta that must match the plant in world for the harvest to occur. - */ - public static final String ADD_RIGHT_CLICK_CROP = "addRightClickCrop"; +public class IMC { + /** + * Use an IMC event with this string to add a right click crop as compatible. + * Syntax is a single string, with '|' separating the values, in the order + * seed, block, meta, resetMeta. A valid entry would look like this: + *

+ * {@literal "minecraft:wheat_seeds|minecraft:wheat|7|0"} + *

+ * The "reset meta" is the metadata that the plant will be reset to when it is + * harvested. Regular meta is the meta that must match the plant in world for + * the harvest to occur. + */ + public static final String ADD_RIGHT_CLICK_CROP = "addRightClickCrop"; } diff --git a/src/main/java/com/enderio/core/client/ClientProxy.java b/src/main/java/com/enderio/core/client/ClientProxy.java index 0ee18f9..5783f9e 100644 --- a/src/main/java/com/enderio/core/client/ClientProxy.java +++ b/src/main/java/com/enderio/core/client/ClientProxy.java @@ -24,5 +24,4 @@ public class ClientProxy extends CommonProxy { throw new EnderCoreModConflictException(msgs); } - } diff --git a/src/main/java/com/enderio/core/client/EnderCoreModConflictException.java b/src/main/java/com/enderio/core/client/EnderCoreModConflictException.java index 5e077d7..21b23fe 100644 --- a/src/main/java/com/enderio/core/client/EnderCoreModConflictException.java +++ b/src/main/java/com/enderio/core/client/EnderCoreModConflictException.java @@ -3,7 +3,6 @@ package com.enderio.core.client; import cpw.mods.fml.client.CustomModLoadingErrorDisplayException; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiErrorScreen; @@ -13,6 +12,7 @@ public class EnderCoreModConflictException extends CustomModLoadingErrorDisplayE private final String[] msgs; public EnderCoreModConflictException(String[] msgs) { + super(msgs[0], new RuntimeException()); this.msgs = msgs; } @@ -23,7 +23,7 @@ public class EnderCoreModConflictException extends CustomModLoadingErrorDisplayE @Override public void drawScreen(GuiErrorScreen errorScreen, FontRenderer fontRenderer, int mouseRelX, int mouseRelY, float tickTime) { int y = errorScreen.height / 2 - msgs.length * 5; - for(String msg : msgs) { + for (String msg : msgs) { errorScreen.drawCenteredString(fontRenderer, msg, errorScreen.width / 2, y, 0xFFFFFF); y += 10; } diff --git a/src/main/java/com/enderio/core/client/config/BaseConfigGui.java b/src/main/java/com/enderio/core/client/config/BaseConfigGui.java index 078cd08..6497f18 100644 --- a/src/main/java/com/enderio/core/client/config/BaseConfigGui.java +++ b/src/main/java/com/enderio/core/client/config/BaseConfigGui.java @@ -17,151 +17,123 @@ import net.minecraftforge.common.config.Property; import cpw.mods.fml.client.config.GuiConfig; import cpw.mods.fml.client.config.IConfigElement; -public class BaseConfigGui extends GuiConfig -{ - @SuppressWarnings("rawtypes") - public BaseConfigGui(GuiScreen parentScreen) - { - // dummy super so we can call instance methods - super(parentScreen, new ArrayList(), null, false, false, null); +public class BaseConfigGui extends GuiConfig { + @SuppressWarnings("rawtypes") + public BaseConfigGui(GuiScreen parentScreen) { + // dummy super so we can call instance methods + super(parentScreen, new ArrayList(), null, false, false, null); - try - { - // pffft final, what a wimpy modifier - Field modID = GuiConfig.class.getDeclaredField("modID"); - Field configElements = GuiConfig.class.getDeclaredField("configElements"); + try { + // pffft final, what a wimpy modifier + Field modID = GuiConfig.class.getDeclaredField("modID"); + Field configElements = GuiConfig.class.getDeclaredField("configElements"); - modID.setAccessible(true); - configElements.setAccessible(true); + modID.setAccessible(true); + configElements.setAccessible(true); - modID.set(this, getConfigHandler().getModID()); - configElements.set(this, getConfigElements()); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - - this.title = getTitle(); + modID.set(this, getConfigHandler().getModID()); + configElements.set(this, getConfigElements()); + } catch (Exception e) { + throw new RuntimeException(e); } - /** - * The localized title of this config screen - */ - protected String getTitle() - { - return EnderCore.lang.localize("config.title"); + this.title = getTitle(); + } + + /** + * The localized title of this config screen + */ + protected String getTitle() { + return EnderCore.lang.localize("config.title"); + } + + /** + * The {@link IConfigHandler} to refer to when generating this config screen + */ + protected IConfigHandler getConfigHandler() { + return ConfigHandler.instance(); + } + + /** + * The lang prefix to use before your section lang keys. Default is "config.". + */ + protected String getLangPrefix() { + return "config."; + } + + @SuppressWarnings("rawtypes") + private List getConfigElements() { + List list = new ArrayList(); + String prefix = getLangPrefix(); + IConfigHandler config = getConfigHandler(); + + prefix = prefix.endsWith(".") ? prefix : prefix + "."; + + for (Section s : config.getSections()) { + list.add(new ConfigSection(s, prefix)); } - /** - * The {@link IConfigHandler} to refer to when generating this config screen - */ - protected IConfigHandler getConfigHandler() - { - return ConfigHandler.instance(); + return list; + } + + @SuppressWarnings("rawtypes") + private class ConfigSection extends ConfigElement { + private Section section; + private String prefix; + + private ConfigSection(Section s, String prefix) { + super(BaseConfigGui.this.getConfigHandler().getCategory(s.lc()).setLanguageKey(prefix + s.lang)); + this.section = s; + this.prefix = prefix; } - /** - * The lang prefix to use before your section lang keys. Default is "config.". - */ - protected String getLangPrefix() - { - return "config."; + @Override + public List getChildElements() { + List temp = super.getChildElements(); + List ret = new ArrayList(temp.size()); + for (IConfigElement e : temp) { + if (e.isProperty()) { + ret.add(new ConfigElementExtended(e)); + } else { + ret.add(new ConfigSection(section, prefix)); + } + } + return ret; + } + } + + @SuppressWarnings("rawtypes") + private static class ConfigElementExtended extends ConfigElement { + private static final Field _prop; + static { + try { + _prop = ConfigElement.class.getDeclaredField("prop"); + _prop.setAccessible(true); + } catch (Exception e) { + throw new RuntimeException(e); + } } - @SuppressWarnings("rawtypes") - private List getConfigElements() - { - List list = new ArrayList(); - String prefix = getLangPrefix(); - IConfigHandler config = getConfigHandler(); - - prefix = prefix.endsWith(".") ? prefix : prefix + "."; - - for (Section s : config.getSections()) - { - list.add(new ConfigSection(s, prefix)); - } - - return list; + private ConfigElementExtended(IConfigElement other) { + super(getProp(other)); } - @SuppressWarnings("rawtypes") - private class ConfigSection extends ConfigElement - { - private Section section; - private String prefix; - - private ConfigSection(Section s, String prefix) - { - super(BaseConfigGui.this.getConfigHandler().getCategory(s.lc()).setLanguageKey(prefix + s.lang)); - this.section = s; - this.prefix = prefix; - } - - @Override - public List getChildElements() - { - List temp = super.getChildElements(); - List ret = new ArrayList(temp.size()); - for (IConfigElement e : temp) - { - if (e.isProperty()) - { - ret.add(new ConfigElementExtended(e)); - } - else - { - ret.add(new ConfigSection(section, prefix)); - } - } - return ret; - } + @SneakyThrows + private static Property getProp(IConfigElement other) { + return (Property) _prop.get(other); } - @SuppressWarnings("rawtypes") - private static class ConfigElementExtended extends ConfigElement - { - private static final Field _prop; - static - { - try - { - _prop = ConfigElement.class.getDeclaredField("prop"); - _prop.setAccessible(true); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - - private ConfigElementExtended(IConfigElement other) - { - super(getProp(other)); - } - - @SneakyThrows - private static Property getProp(IConfigElement other) - { - return (Property) _prop.get(other); - } - - @Override - public String getComment() - { - String comment = super.getComment(); - String range = "[range:"; - String def = "[default:"; - if (comment.contains(range)) - { - comment = comment.substring(0, comment.indexOf(range) - 1); - } - else if (comment.contains(def)) - { - comment = comment.substring(0, comment.indexOf(def) - 1); - } - return comment; - } + @Override + public String getComment() { + String comment = super.getComment(); + String range = "[range:"; + String def = "[default:"; + if (comment.contains(range)) { + comment = comment.substring(0, comment.indexOf(range) - 1); + } else if (comment.contains(def)) { + comment = comment.substring(0, comment.indexOf(def) - 1); + } + return comment; } + } } diff --git a/src/main/java/com/enderio/core/client/gui/GuiContainerBase.java b/src/main/java/com/enderio/core/client/gui/GuiContainerBase.java index 18cdf41..0fbafe4 100644 --- a/src/main/java/com/enderio/core/client/gui/GuiContainerBase.java +++ b/src/main/java/com/enderio/core/client/gui/GuiContainerBase.java @@ -35,9 +35,7 @@ import com.google.common.collect.Lists; import cpw.mods.fml.common.Optional; -@Optional.InterfaceList({ - @Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems") -}) +@Optional.InterfaceList({ @Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems") }) public abstract class GuiContainerBase extends GuiContainer implements ToolTipRenderer, IGuiScreen, INEIGuiHandler { protected ToolTipManager ttMan = new ToolTipManager(); @@ -76,22 +74,22 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe focused = f; } } - + // If esc is pressed - if(key == 1) { + if (key == 1) { // If there is a focused text field unfocus it - if(focused != null && key == 1) { + if (focused != null && key == 1) { focused.setFocused(false); focused = null; return; - } else if(!hideOverlays()) { // Otherwise close overlays/GUI + } else if (!hideOverlays()) { // Otherwise close overlays/GUI this.mc.thePlayer.closeScreen(); return; } } - + // If the user pressed tab, switch to the next text field, or unfocus if there are none - if(c == '\t') { + if (c == '\t') { for (int i = 0; i < textFields.size(); i++) { TextFieldEnder f = textFields.get(i); if (f.isFocused()) { @@ -103,23 +101,23 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe } // If there is a focused text field, attempt to type into it - if(focused != null) { + if (focused != null) { String old = focused.getText(); - if(focused.textboxKeyTyped(c, key)) { + if (focused.textboxKeyTyped(c, key)) { onTextFieldChanged(focused, old); return; } } - + // More NEI behavior, f key focuses first text field - if(c == 'f' && focused == null && !textFields.isEmpty()) { + if (c == 'f' && focused == null && !textFields.isEmpty()) { focused = textFields.get(0); focused.setFocused(true); } // Finally if 'e' was pressed but not captured by a text field, close the overlays/GUI - if(key == this.mc.gameSettings.keyBindInventory.getKeyCode()) { - if(!hideOverlays()) { + if (key == this.mc.gameSettings.keyBindInventory.getKeyCode()) { + if (!hideOverlays()) { this.mc.thePlayer.closeScreen(); } return; @@ -141,7 +139,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe public boolean hideOverlays() { for (IGuiOverlay overlay : overlays) { - if(overlay.isVisible()) { + if (overlay.isVisible()) { overlay.setVisible(false); return true; } @@ -153,15 +151,15 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe public void addToolTip(GuiToolTip toolTip) { ttMan.addToolTip(toolTip); } - + @Override public void updateScreen() { super.updateScreen(); - + if (!inventorySlots.canInteractWith(mc.thePlayer)) { mc.thePlayer.closeScreen(); } - + for (GuiTextField f : textFields) { f.updateCursorCounter(); } @@ -173,12 +171,12 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; int b = Mouse.getEventButton(); for (IGuiOverlay overlay : overlays) { - if(overlay != null && overlay.isVisible() && overlay.handleMouseInput(x, y, b)) { + if (overlay != null && overlay.isVisible() && overlay.handleMouseInput(x, y, b)) { return; } } int delta = Mouse.getEventDWheel(); - if(delta != 0) { + if (delta != 0) { mouseWheel(x, y, delta); } super.handleMouseInput(); @@ -189,7 +187,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe int x = Mouse.getEventX() * this.width / this.mc.displayWidth; int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; for (IGuiOverlay overlay : overlays) { - if(overlay != null && overlay.isVisible() && overlay.isMouseInBounds(x, y)) { + if (overlay != null && overlay.isVisible() && overlay.isMouseInBounds(x, y)) { return false; } } @@ -211,39 +209,39 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe for (GuiTextField f : textFields) { f.mouseClicked(x, y, button); } - if(!scrollbars.isEmpty()) { - if(draggingScrollbar != null) { + if (!scrollbars.isEmpty()) { + if (draggingScrollbar != null) { draggingScrollbar.mouseClicked(x, y, button); return; } - for(VScrollbar vs : scrollbars) { - if(vs.mouseClicked(x, y, button)) { + for (VScrollbar vs : scrollbars) { + if (vs.mouseClicked(x, y, button)) { draggingScrollbar = vs; return; } } } - if(!ghostSlots.isEmpty()) { + if (!ghostSlots.isEmpty()) { GhostSlot slot = getGhostSlot(x, y); - if(slot != null) { + if (slot != null) { ghostSlotClicked(slot, x, y, button); return; } } // Right click field clearing - if(button == 1) { + if (button == 1) { for (TextFieldEnder tf : textFields) { - if(tf.contains(x, y)) { + if (tf.contains(x, y)) { setText(tf, ""); } } } // Button events for non-left-clicks - if(button >= 1) { - for(Object obj : buttonList) { - if(obj instanceof IconButton) { + if (button >= 1) { + for (Object obj : buttonList) { + if (obj instanceof IconButton) { IconButton btn = (IconButton) obj; - if(btn.mousePressedButton(mc, x, y, button)) { + if (btn.mousePressedButton(mc, x, y, button)) { btn.func_146113_a(this.mc.getSoundHandler()); actionPerformedButton(btn, button); } @@ -255,7 +253,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe @Override protected void mouseMovedOrUp(int x, int y, int button) { - if(draggingScrollbar != null) { + if (draggingScrollbar != null) { draggingScrollbar.mouseMovedOrUp(x, y, button); draggingScrollbar = null; } @@ -264,7 +262,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe @Override protected void mouseClickMove(int x, int y, int button, long time) { - if(draggingScrollbar != null) { + if (draggingScrollbar != null) { draggingScrollbar.mouseClickMove(x, y, button, time); return; } @@ -272,8 +270,8 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe } protected void mouseWheel(int x, int y, int delta) { - if(!scrollbars.isEmpty()) { - for(VScrollbar vs : scrollbars) { + if (!scrollbars.isEmpty()) { + for (VScrollbar vs : scrollbars) { vs.mouseWheel(x, y, delta); } } @@ -298,7 +296,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe public void removeScrollbar(VScrollbar vs) { scrollbars.remove(vs); - if(draggingScrollbar == vs) { + if (draggingScrollbar == vs) { draggingScrollbar = null; } } @@ -310,13 +308,13 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe drawForegroundImpl(mouseX, mouseY); Timer t = RenderUtil.getTimer(); - - if(t != null) { + + if (t != null) { GL11.glPushMatrix(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_DEPTH_TEST); for (IGuiOverlay overlay : overlays) { - if(overlay != null && overlay.isVisible()) { + if (overlay != null && overlay.isVisible()) { overlay.draw(realMx, realMy, t.renderPartialTicks); } } @@ -324,14 +322,14 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe GL11.glPopMatrix(); } } - + @Override protected void drawGuiContainerBackgroundLayer(float par1, int mouseX, int mouseY) { for (GuiTextField f : textFields) { f.drawTextBox(); } - if(!scrollbars.isEmpty()) { - for(VScrollbar vs : scrollbars) { + if (!scrollbars.isEmpty()) { + for (VScrollbar vs : scrollbars) { vs.drawScrollbar(mouseX, mouseY); } } @@ -344,7 +342,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe int mx = realMx = par1; int my = realMy = par2; for (IGuiOverlay overlay : overlays) { - if(overlay != null && overlay.isVisible() && isMouseInOverlay(par1, par2, overlay)) { + if (overlay != null && overlay.isVisible() && isMouseInOverlay(par1, par2, overlay)) { mx = -5000; my = -5000; this.drawItemStack(this.mc.thePlayer.inventory.getItemStack(), par1 - this.guiLeft - 8, par2 - this.guiTop - 8, null); @@ -353,8 +351,8 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe super.drawScreen(mx, my, par3); - if(draggingScrollbar == null) { - if(hoverGhostSlot != null && mc.thePlayer.inventory.getItemStack() == null) { + if (draggingScrollbar == null) { + if (hoverGhostSlot != null && mc.thePlayer.inventory.getItemStack() == null) { drawGhostSlotTooltip(hoverGhostSlot, par1, par2); } @@ -363,16 +361,15 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe } // copied from super with hate - protected void drawItemStack(ItemStack stack, int mouseX, int mouseY, String str) - { + protected void drawItemStack(ItemStack stack, int mouseX, int mouseY, String str) { GL11.glTranslatef(0.0F, 0.0F, 32.0F); this.zLevel = 200.0F; itemRender.zLevel = 200.0F; FontRenderer font = null; - if(stack != null) { + if (stack != null) { font = stack.getItem().getFontRenderer(stack); } - if(font == null) { + if (font == null) { font = fontRendererObj; } itemRender.renderItemAndEffectIntoGUI(font, this.mc.getTextureManager(), stack, mouseX, mouseY); @@ -413,13 +410,13 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe protected void drawGhostSlotTooltip(GhostSlot slot, int mouseX, int mouseY) { ItemStack stack = slot.getStack(); - if(stack != null) { + if (stack != null) { renderToolTip(stack, mouseX, mouseY); } } protected void drawGhostSlots(int mouseX, int mouseY) { - if(ghostSlots.isEmpty()) { + if (ghostSlots.isEmpty()) { return; } int sx = getGuiLeft(); @@ -427,18 +424,18 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe drawFakeItemsStart(); try { hoverGhostSlot = null; - for(GhostSlot slot : ghostSlots) { + for (GhostSlot slot : ghostSlots) { ItemStack stack = slot.getStack(); - if(slot.isVisible()) { - if(stack != null) { + if (slot.isVisible()) { + if (stack != null) { drawFakeItemStack(slot.x + sx, slot.y + sy, stack); } - if(slot.isMouseOver(mouseX - sx, mouseY - sy)) { + if (slot.isMouseOver(mouseX - sx, mouseY - sy)) { hoverGhostSlot = slot; } } } - if(hoverGhostSlot != null) { + if (hoverGhostSlot != null) { // draw hover last to prevent it from affecting rendering of other slots ... drawFakeItemHover(hoverGhostSlot.x + sx, hoverGhostSlot.y + sy); } @@ -450,8 +447,8 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe protected GhostSlot getGhostSlot(int mouseX, int mouseY) { mouseX -= getGuiLeft(); mouseY -= getGuiTop(); - for(GhostSlot slot : ghostSlots) { - if(slot.isVisible() && slot.isMouseOver(mouseX, mouseY)) { + for (GhostSlot slot : ghostSlots) { + if (slot.isVisible() && slot.isMouseOver(mouseX, mouseY)) { return slot; } } @@ -486,8 +483,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe //This is a copy of the super class method due to 'Method not found' errors // reported with some mods installed. protected void copyOfdrawHoveringText(List par1List, int par2, int par3, FontRenderer font) { - if(!par1List.isEmpty()) - { + if (!par1List.isEmpty()) { GL11.glDisable(GL12.GL_RESCALE_NORMAL); RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); @@ -495,13 +491,11 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe int k = 0; Iterator iterator = par1List.iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { String s = (String) iterator.next(); int l = font.getStringWidth(s); - if(l > k) - { + if (l > k) { k = l; } } @@ -510,18 +504,15 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe int j1 = par3 - 12; int k1 = 8; - if(par1List.size() > 1) - { + if (par1List.size() > 1) { k1 += 2 + (par1List.size() - 1) * 10; } - if(i1 + k > this.width) - { + if (i1 + k > this.width) { i1 -= 28 + k; } - if(j1 + k1 + 6 > this.height) - { + if (j1 + k1 + 6 > this.height) { j1 = this.height - k1 - 6; } @@ -540,13 +531,11 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2); this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2); - for (int k2 = 0; k2 < par1List.size(); ++k2) - { + for (int k2 = 0; k2 < par1List.size(); ++k2) { String s1 = (String) par1List.get(k2); font.drawStringWithShadow(s1, i1, j1, -1); - if(k2 == 0) - { + if (k2 == 0) { j1 += 2; } @@ -581,7 +570,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe public int getYSize() { return ySize; } - + public void setGuiLeft(int i) { guiLeft = i; } @@ -606,7 +595,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe @SuppressWarnings("unchecked") @Override public void addButton(GuiButton button) { - if(!buttonList.contains(button)) { + if (!buttonList.contains(button)) { buttonList.add(button); } } @@ -641,7 +630,7 @@ public abstract class GuiContainerBase extends GuiContainer implements ToolTipRe @Override @Optional.Method(modid = "NotEnoughItems") public List getInventoryAreas(GuiContainer gc) { - return Collections.emptyList(); + return Collections. emptyList(); } @Override diff --git a/src/main/java/com/enderio/core/client/gui/GuiScreenBase.java b/src/main/java/com/enderio/core/client/gui/GuiScreenBase.java index 60e1c47..d16bb86 100644 --- a/src/main/java/com/enderio/core/client/gui/GuiScreenBase.java +++ b/src/main/java/com/enderio/core/client/gui/GuiScreenBase.java @@ -38,7 +38,7 @@ public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer protected int guiTop; protected boolean drawButtons = true; - + protected GuiScreenBase() { } @@ -74,7 +74,7 @@ public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDisable(GL12.GL_RESCALE_NORMAL); - if(drawButtons) { + if (drawButtons) { RenderHelper.enableGUIStandardItemLighting(); super.drawScreen(par1, par2, par3); } @@ -108,7 +108,7 @@ public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer @Override public void drawHoveringText(List par1List, int par2, int par3, FontRenderer font) { - if(!par1List.isEmpty()) { + if (!par1List.isEmpty()) { GL11.glPushAttrib(GL11.GL_ENABLE_BIT); GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); @@ -120,13 +120,11 @@ public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer int k = 0; Iterator iterator = par1List.iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { String s = (String) iterator.next(); int l = font.getStringWidth(s); - if(l > k) - { + if (l > k) { k = l; } } @@ -135,18 +133,15 @@ public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer int j1 = par3 - 12; int k1 = 8; - if(par1List.size() > 1) - { + if (par1List.size() > 1) { k1 += 2 + (par1List.size() - 1) * 10; } - if(i1 + k > this.width) - { + if (i1 + k > this.width) { i1 -= 28 + k; } - if(j1 + k1 + 6 > this.height) - { + if (j1 + k1 + 6 > this.height) { j1 = this.height - k1 - 6; } @@ -165,13 +160,11 @@ public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2); this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2); - for (int k2 = 0; k2 < par1List.size(); ++k2) - { + for (int k2 = 0; k2 < par1List.size(); ++k2) { String s1 = (String) par1List.get(k2); font.drawStringWithShadow(s1, i1, j1, -1); - if(k2 == 0) - { + if (k2 == 0) { j1 += 2; } @@ -218,7 +211,7 @@ public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer @Override public void addButton(GuiButton button) { - if(!buttonList.contains(button)) { + if (!buttonList.contains(button)) { buttonList.add(button); } } @@ -227,10 +220,10 @@ public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer public void removeButton(GuiButton button) { buttonList.remove(button); } - + @Override public void doActionPerformed(GuiButton guiButton) { - actionPerformed(guiButton); + actionPerformed(guiButton); } @Override diff --git a/src/main/java/com/enderio/core/client/gui/ToolTipManager.java b/src/main/java/com/enderio/core/client/gui/ToolTipManager.java index e12901d..a9935d2 100644 --- a/src/main/java/com/enderio/core/client/gui/ToolTipManager.java +++ b/src/main/java/com/enderio/core/client/gui/ToolTipManager.java @@ -25,7 +25,7 @@ public class ToolTipManager { private List toolTips = new ArrayList(); public void addToolTip(GuiToolTip toolTip) { - if(!toolTips.contains(toolTip)) { + if (!toolTips.contains(toolTip)) { toolTips.add(toolTip); } } @@ -37,7 +37,7 @@ public class ToolTipManager { protected final void drawTooltips(ToolTipRenderer renderer, int mouseX, int mouseY) { for (GuiToolTip toolTip : toolTips) { toolTip.onTick(mouseX - renderer.getGuiLeft(), mouseY - renderer.getGuiTop()); - if(toolTip.shouldDraw()) { + if (toolTip.shouldDraw()) { drawTooltip(toolTip, mouseX, mouseY, renderer); } } @@ -45,26 +45,26 @@ public class ToolTipManager { protected void drawTooltip(GuiToolTip toolTip, int mouseX, int mouseY, ToolTipRenderer renderer) { List list = toolTip.getToolTipText(); - if(list == null) { + if (list == null) { return; } List formatted = new ArrayList(list.size()); for (int i = 0; i < list.size(); i++) { - if(i == 0) { + if (i == 0) { formatted.add("\u00a7f" + list.get(i)); } else { formatted.add("\u00a77" + list.get(i)); } } - if(mouseX > renderer.getGuiLeft() + renderer.getXSize() / 2) { + if (mouseX > renderer.getGuiLeft() + renderer.getXSize() / 2) { int maxWidth = 0; Iterator iterator = formatted.iterator(); while (iterator.hasNext()) { String s = (String) iterator.next(); int w = renderer.getFontRenderer().getStringWidth(s); - if(w > maxWidth) { + if (w > maxWidth) { maxWidth = w; } } diff --git a/src/main/java/com/enderio/core/client/gui/bettermodlist/EventHandlerGui.java b/src/main/java/com/enderio/core/client/gui/bettermodlist/EventHandlerGui.java index 2fdcf68..a665893 100644 --- a/src/main/java/com/enderio/core/client/gui/bettermodlist/EventHandlerGui.java +++ b/src/main/java/com/enderio/core/client/gui/bettermodlist/EventHandlerGui.java @@ -14,42 +14,33 @@ import cpw.mods.fml.client.GuiModList; import cpw.mods.fml.common.eventhandler.SubscribeEvent; @Handler -public class EventHandlerGui -{ - private static Field _mainMenu, _parentScreen; +public class EventHandlerGui { + private static Field _mainMenu, _parentScreen; - static - { - try - { - _mainMenu = GuiModList.class.getDeclaredField("mainMenu"); - _mainMenu.setAccessible(true); - _parentScreen = GuiIngameModOptions.class.getDeclaredField("parentScreen"); - _parentScreen.setAccessible(true); - } - catch (Exception e) - { - throw new RuntimeException(e); - } + static { + try { + _mainMenu = GuiModList.class.getDeclaredField("mainMenu"); + _mainMenu.setAccessible(true); + _parentScreen = GuiIngameModOptions.class.getDeclaredField("parentScreen"); + _parentScreen.setAccessible(true); + } catch (Exception e) { + throw new RuntimeException(e); } + } - @SubscribeEvent - @SneakyThrows - public void onGuiOpen(GuiOpenEvent event) - { - if (event.gui == null) - { - return; - } - if (event.gui.getClass() == GuiModList.class) - { - event.setCanceled(true); - Minecraft.getMinecraft().displayGuiScreen(new GuiEnhancedModList((GuiScreen) _mainMenu.get(event.gui))); - } - if (event.gui.getClass() == GuiIngameModOptions.class) - { - event.setCanceled(true); - Minecraft.getMinecraft().displayGuiScreen(new GuiEnhancedModList((GuiScreen) _parentScreen.get(event.gui))); - } + @SubscribeEvent + @SneakyThrows + public void onGuiOpen(GuiOpenEvent event) { + if (event.gui == null) { + return; } + if (event.gui.getClass() == GuiModList.class) { + event.setCanceled(true); + Minecraft.getMinecraft().displayGuiScreen(new GuiEnhancedModList((GuiScreen) _mainMenu.get(event.gui))); + } + if (event.gui.getClass() == GuiIngameModOptions.class) { + event.setCanceled(true); + Minecraft.getMinecraft().displayGuiScreen(new GuiEnhancedModList((GuiScreen) _parentScreen.get(event.gui))); + } + } } diff --git a/src/main/java/com/enderio/core/client/gui/button/ColorButton.java b/src/main/java/com/enderio/core/client/gui/button/ColorButton.java index 2d2edaa..339323f 100644 --- a/src/main/java/com/enderio/core/client/gui/button/ColorButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/ColorButton.java @@ -23,7 +23,7 @@ public class ColorButton extends IconButton { @Override public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) { boolean result = super.mousePressed(par1Minecraft, par2, par3); - if(result) { + if (result) { nextColor(); } return result; @@ -32,7 +32,7 @@ public class ColorButton extends IconButton { @Override public boolean mousePressedButton(Minecraft mc, int x, int y, int button) { boolean result = button == 1 && super.checkMousePress(mc, x, y); - if(result) { + if (result) { prevColor(); } return result; @@ -43,7 +43,7 @@ public class ColorButton extends IconButton { } public void setToolTipHeading(String tooltipPrefix) { - if(tooltipPrefix == null) { + if (tooltipPrefix == null) { this.tooltipPrefix = ""; } else { this.tooltipPrefix = tooltipPrefix; @@ -52,18 +52,18 @@ public class ColorButton extends IconButton { private void nextColor() { colorIndex++; - if(colorIndex >= ItemDye.field_150923_a.length) { + if (colorIndex >= ItemDye.field_150923_a.length) { colorIndex = 0; } setColorIndex(colorIndex); } - + private void prevColor() { colorIndex--; - if(colorIndex < 0) { + if (colorIndex < 0) { colorIndex = ItemDye.field_150923_a.length - 1; } - setColorIndex(colorIndex); + setColorIndex(colorIndex); } public int getColorIndex() { @@ -73,7 +73,7 @@ public class ColorButton extends IconButton { public void setColorIndex(int colorIndex) { this.colorIndex = MathHelper.clamp_int(colorIndex, 0, ItemDye.field_150923_a.length - 1); String colStr = DyeColor.values()[colorIndex].getLocalisedName(); - if(tooltipPrefix != null && tooltipPrefix.length() > 0) { + if (tooltipPrefix != null && tooltipPrefix.length() > 0) { setToolTip(tooltipPrefix, colStr); } else { setToolTip(colStr); @@ -83,7 +83,7 @@ public class ColorButton extends IconButton { @Override public void drawButton(Minecraft mc, int mouseX, int mouseY) { super.drawButton(mc, mouseX, mouseY); - if(visible) { + if (visible) { Tessellator tes = Tessellator.instance; tes.startDrawingQuads(); diff --git a/src/main/java/com/enderio/core/client/gui/button/IIconButton.java b/src/main/java/com/enderio/core/client/gui/button/IIconButton.java index 95b467f..00bec23 100644 --- a/src/main/java/com/enderio/core/client/gui/button/IIconButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/IIconButton.java @@ -60,12 +60,11 @@ public class IIconButton extends GuiButton { @SuppressWarnings("synthetic-access") @Override public void drawButton(Minecraft par1Minecraft, int par2, int par3) { - if(visible) { + if (visible) { RenderUtil.bindTexture("textures/gui/widgets.png"); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + width - && par3 < this.yPosition + height; + this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + width && par3 < this.yPosition + height; int hoverState = getHoverState(this.field_146123_n); // x, y, u, v, width, height @@ -80,7 +79,7 @@ public class IIconButton extends GuiButton { mouseDragged(par1Minecraft, par2, par3); - if(icon != null && texture != null) { + if (icon != null && texture != null) { GL11.glPushAttrib(GL11.GL_ENABLE_BIT); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); diff --git a/src/main/java/com/enderio/core/client/gui/button/IconButton.java b/src/main/java/com/enderio/core/client/gui/button/IconButton.java index f29499a..8894292 100644 --- a/src/main/java/com/enderio/core/client/gui/button/IconButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/IconButton.java @@ -23,7 +23,7 @@ public class IconButton extends GuiButton { protected IGuiScreen gui; protected String[] toolTipText; - + private GuiToolTip toolTip; private int marginY = 0; private int marginX = 0; @@ -45,7 +45,7 @@ public class IconButton extends GuiButton { } this.toolTipText = tooltipText; } - + protected void setToolTip(GuiToolTip newToolTip) { boolean addTooltip = false; if (toolTip != null) { diff --git a/src/main/java/com/enderio/core/client/gui/button/IconToggleButton.java b/src/main/java/com/enderio/core/client/gui/button/IconToggleButton.java index 25ef793..7825c06 100644 --- a/src/main/java/com/enderio/core/client/gui/button/IconToggleButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/IconToggleButton.java @@ -23,9 +23,9 @@ public class IconToggleButton extends IIconButton { @Override public int getHoverState(boolean par1) { int result = 1; - if(!enabled || selected) { + if (!enabled || selected) { result = 0; - } else if(par1) { + } else if (par1) { result = 2; } return result; diff --git a/src/main/java/com/enderio/core/client/gui/button/ItemButton.java b/src/main/java/com/enderio/core/client/gui/button/ItemButton.java index 91891ca..6820ce4 100644 --- a/src/main/java/com/enderio/core/client/gui/button/ItemButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/ItemButton.java @@ -48,12 +48,11 @@ public class ItemButton extends GuiButton { @SuppressWarnings("synthetic-access") @Override public void drawButton(Minecraft par1Minecraft, int par2, int par3) { - if(visible) { + if (visible) { RenderUtil.bindTexture("textures/gui/widgets.png"); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + width - && par3 < this.yPosition + height; + this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + width && par3 < this.yPosition + height; int hoverState = this.getHoverState(this.field_146123_n); // x, y, u, v, width, height @@ -70,9 +69,9 @@ public class ItemButton extends GuiButton { int l = 14737632; - if(!this.enabled) { + if (!this.enabled) { l = -6250336; - } else if(this.field_146123_n) { + } else if (this.field_146123_n) { l = 16777120; } diff --git a/src/main/java/com/enderio/core/client/gui/widget/GhostSlot.java b/src/main/java/com/enderio/core/client/gui/widget/GhostSlot.java index e509f55..fe8bef2 100644 --- a/src/main/java/com/enderio/core/client/gui/widget/GhostSlot.java +++ b/src/main/java/com/enderio/core/client/gui/widget/GhostSlot.java @@ -10,7 +10,7 @@ public class GhostSlot { public ItemStack stack; public boolean isMouseOver(int mx, int my) { - return mx >= x && mx < (x+16) && my >= y && my < (y+16); + return mx >= x && mx < (x + 16) && my >= y && my < (y + 16); } public boolean isVisible() { diff --git a/src/main/java/com/enderio/core/client/gui/widget/GuiScrollableList.java b/src/main/java/com/enderio/core/client/gui/widget/GuiScrollableList.java index 3faac1e..5fea025 100644 --- a/src/main/java/com/enderio/core/client/gui/widget/GuiScrollableList.java +++ b/src/main/java/com/enderio/core/client/gui/widget/GuiScrollableList.java @@ -90,7 +90,7 @@ public abstract class GuiScrollableList { } public void setSelection(int index) { - if(index == selectedIndex) { + if (index == selectedIndex) { return; } selectedIndex = index; @@ -100,11 +100,11 @@ public abstract class GuiScrollableList { } public int getIndexOf(T element) { - if(element == null) { + if (element == null) { return -1; } for (int i = 0; i < getNumElements(); i++) { - if(element.equals(getElementAt(i))) { + if (element.equals(getElementAt(i))) { return i; } } @@ -136,13 +136,13 @@ public abstract class GuiScrollableList { private void clampScrollToBounds() { int i = getContentOverhang(); - if(i < 0) { + if (i < 0) { i *= -1; } - if(amountScrolled < 0.0F) { + if (amountScrolled < 0.0F) { amountScrolled = 0.0F; } - if(amountScrolled > i) { + if (amountScrolled > i) { amountScrolled = i; } } @@ -152,12 +152,12 @@ public abstract class GuiScrollableList { } public void actionPerformed(GuiButton b) { - if(b.enabled) { - if(b.id == scrollUpButtonID) { + if (b.enabled) { + if (b.id == scrollUpButtonID) { amountScrolled -= slotHeight * 2 / 3; initialClickY = -2.0F; clampScrollToBounds(); - } else if(b.id == scrollDownButtonID) { + } else if (b.id == scrollDownButtonID) { amountScrolled += slotHeight * 2 / 3; initialClickY = -2.0F; clampScrollToBounds(); @@ -198,9 +198,9 @@ public abstract class GuiScrollableList { int elementY = contentYOffset + i * this.slotHeight; int slotHeight = this.slotHeight - margin; - if(elementY <= maxY && elementY + slotHeight >= minY) { + if (elementY <= maxY && elementY + slotHeight >= minY) { - if(showSelectionBox && i == selectedIndex) { + if (showSelectionBox && i == selectedIndex) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_TEXTURE_2D); tessellator.startDrawingQuads(); @@ -259,20 +259,20 @@ public abstract class GuiScrollableList { protected void renderScrollBar(Tessellator tessellator) { int contentHeightOverBounds = getContentOverhang(); - if(contentHeightOverBounds > 0) { + if (contentHeightOverBounds > 0) { int clear = (maxY - minY) * (maxY - minY) / getContentHeight(); - if(clear < 32) { + if (clear < 32) { clear = 32; } - if(clear > maxY - minY - 8) { + if (clear > maxY - minY - 8) { clear = maxY - minY - 8; } int y = (int) this.amountScrolled * (maxY - minY - clear) / contentHeightOverBounds + minY; - if(y < minY) { + if (y < minY) { y = minY; } @@ -305,17 +305,17 @@ public abstract class GuiScrollableList { } private void processMouseEvents() { - if(Mouse.isButtonDown(0)) { + if (Mouse.isButtonDown(0)) { processMouseBown(); } else { while (!mc.gameSettings.touchscreen && Mouse.next()) { int mouseWheelDelta = Mouse.getEventDWheel(); - if(mouseWheelDelta != 0) { - if(mouseWheelDelta > 0) { + if (mouseWheelDelta != 0) { + if (mouseWheelDelta > 0) { mouseWheelDelta = -1; - } else if(mouseWheelDelta < 0) { + } else if (mouseWheelDelta < 0) { mouseWheelDelta = 1; } amountScrolled += mouseWheelDelta * slotHeight / 2; @@ -327,42 +327,42 @@ public abstract class GuiScrollableList { private void processMouseBown() { int contentHeightOverBounds; - if(initialClickY == -1.0F) { + if (initialClickY == -1.0F) { - if(mouseY >= minY && mouseY <= maxY && mouseX >= minX && mouseX <= maxX + 6) { + if (mouseY >= minY && mouseY <= maxY && mouseX >= minX && mouseX <= maxX + 6) { boolean clickInBounds = true; int y = mouseY - minY + (int) amountScrolled - margin; int mouseOverElement = y / slotHeight; - if(mouseX >= minX && mouseX <= maxX && mouseOverElement >= 0 && y >= 0 && mouseOverElement < getNumElements()) { + if (mouseX >= minX && mouseX <= maxX && mouseOverElement >= 0 && y >= 0 && mouseOverElement < getNumElements()) { boolean doubleClick = mouseOverElement == selectedIndex && Minecraft.getSystemTime() - lastClickedTime < 250L; - if(elementClicked(mouseOverElement, doubleClick)) { + if (elementClicked(mouseOverElement, doubleClick)) { setSelection(mouseOverElement); } lastClickedTime = Minecraft.getSystemTime(); - } else if(mouseX >= minX && mouseX <= maxX && y < 0) { + } else if (mouseX >= minX && mouseX <= maxX && y < 0) { clickInBounds = false; } int scrollBarMinX = getScrollBarX(); int scrollBarMaxX = scrollBarMinX + 6; - if(mouseX >= scrollBarMinX && mouseX <= scrollBarMaxX) { + if (mouseX >= scrollBarMinX && mouseX <= scrollBarMaxX) { scrollMultiplier = -1.0F; contentHeightOverBounds = getContentOverhang(); - if(contentHeightOverBounds < 1) { + if (contentHeightOverBounds < 1) { contentHeightOverBounds = 1; } int empty = (int) ((float) ((maxY - minY) * (maxY - minY)) / (float) getContentHeight()); - if(empty < 32) { + if (empty < 32) { empty = 32; } - if(empty > maxY - minY - 8) { + if (empty > maxY - minY - 8) { empty = maxY - minY - 8; } scrollMultiplier /= (float) (maxY - minY - empty) / (float) contentHeightOverBounds; @@ -371,7 +371,7 @@ public abstract class GuiScrollableList { scrollMultiplier = 1.0F; } - if(clickInBounds) { + if (clickInBounds) { initialClickY = mouseY; } else { initialClickY = -2.0F; @@ -381,7 +381,7 @@ public abstract class GuiScrollableList { initialClickY = -2.0F; } - } else if(initialClickY >= 0.0F) { + } else if (initialClickY >= 0.0F) { // Scrolling amountScrolled -= (mouseY - initialClickY) * scrollMultiplier; initialClickY = mouseY; diff --git a/src/main/java/com/enderio/core/client/gui/widget/GuiToolTip.java b/src/main/java/com/enderio/core/client/gui/widget/GuiToolTip.java index 3972736..0dbfbcc 100644 --- a/src/main/java/com/enderio/core/client/gui/widget/GuiToolTip.java +++ b/src/main/java/com/enderio/core/client/gui/widget/GuiToolTip.java @@ -17,12 +17,12 @@ public class GuiToolTip { private int lastMouseX = -1; private int lastMouseY = -1; - + private boolean visible = true; public GuiToolTip(Rectangle bounds, String... lines) { this.bounds = bounds; - if(lines != null) { + if (lines != null) { text = new ArrayList(lines.length); for (String line : lines) { text.add(line); @@ -34,7 +34,7 @@ public class GuiToolTip { public GuiToolTip(Rectangle bounds, List lines) { this.bounds = bounds; - if(lines == null) { + if (lines == null) { text = new ArrayList(); } else { text = new ArrayList(lines); @@ -58,13 +58,13 @@ public class GuiToolTip { } public void onTick(int mouseX, int mouseY) { - if(lastMouseX != mouseX || lastMouseY != mouseY) { + if (lastMouseX != mouseX || lastMouseY != mouseY) { mouseOverStart = 0; } - if(bounds.contains(mouseX, mouseY)) { + if (bounds.contains(mouseX, mouseY)) { - if(mouseOverStart == 0) { + if (mouseOverStart == 0) { mouseOverStart = System.currentTimeMillis(); } } else { @@ -75,12 +75,12 @@ public class GuiToolTip { lastMouseY = mouseY; } - public boolean shouldDraw() { - if(!visible) { + public boolean shouldDraw() { + if (!visible) { return false; - } + } updateText(); - if(mouseOverStart == 0) { + if (mouseOverStart == 0) { return false; } return System.currentTimeMillis() - mouseOverStart >= DELAY; @@ -91,7 +91,7 @@ public class GuiToolTip { public void setToolTipText(String... txt) { text.clear(); - if(txt != null) { + if (txt != null) { for (String line : txt) { text.add(line); } diff --git a/src/main/java/com/enderio/core/client/gui/widget/TemplateSlot.java b/src/main/java/com/enderio/core/client/gui/widget/TemplateSlot.java index 9611397..98a079b 100644 --- a/src/main/java/com/enderio/core/client/gui/widget/TemplateSlot.java +++ b/src/main/java/com/enderio/core/client/gui/widget/TemplateSlot.java @@ -31,7 +31,7 @@ public class TemplateSlot extends Slot { @Override public void putStack(ItemStack par1ItemStack) { - if(par1ItemStack != null) { + if (par1ItemStack != null) { par1ItemStack.stackSize = 0; } inventory.setInventorySlotContents(slotIndex, par1ItemStack); diff --git a/src/main/java/com/enderio/core/client/gui/widget/TextFieldEnder.java b/src/main/java/com/enderio/core/client/gui/widget/TextFieldEnder.java index 453626a..971750f 100644 --- a/src/main/java/com/enderio/core/client/gui/widget/TextFieldEnder.java +++ b/src/main/java/com/enderio/core/client/gui/widget/TextFieldEnder.java @@ -56,7 +56,7 @@ public class TextFieldEnder extends GuiTextField { public TextFieldEnder(FontRenderer fnt, int x, int y, int width, int height) { this(fnt, x, y, width, height, null); } - + public TextFieldEnder(FontRenderer fnt, int x, int y, int width, int height, ICharFilter charFilter) { super(fnt, x, y, width, height); this.xOrigin = x; @@ -76,7 +76,7 @@ public class TextFieldEnder extends GuiTextField { @Override public boolean textboxKeyTyped(char c, int key) { - if(filter == null || filter.passesFilter(this, c) || isSpecialChar(c, key)) { + if (filter == null || filter.passesFilter(this, c) || isSpecialChar(c, key)) { return super.textboxKeyTyped(c, key); } return false; diff --git a/src/main/java/com/enderio/core/client/handlers/ClientHandler.java b/src/main/java/com/enderio/core/client/handlers/ClientHandler.java index 0fc92d3..a1169ae 100644 --- a/src/main/java/com/enderio/core/client/handlers/ClientHandler.java +++ b/src/main/java/com/enderio/core/client/handlers/ClientHandler.java @@ -9,17 +9,14 @@ import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; @Handler -public class ClientHandler -{ - @Getter - private static int ticksElapsed; +public class ClientHandler { + @Getter + private static int ticksElapsed; - @SubscribeEvent - public void onClientTick(ClientTickEvent event) - { - if (event.phase == Phase.END) - { - ticksElapsed++; - } + @SubscribeEvent + public void onClientTick(ClientTickEvent event) { + if (event.phase == Phase.END) { + ticksElapsed++; } + } } diff --git a/src/main/java/com/enderio/core/client/handlers/EnchantTooltipHandler.java b/src/main/java/com/enderio/core/client/handlers/EnchantTooltipHandler.java index d23545f..b6c5270 100644 --- a/src/main/java/com/enderio/core/client/handlers/EnchantTooltipHandler.java +++ b/src/main/java/com/enderio/core/client/handlers/EnchantTooltipHandler.java @@ -14,35 +14,27 @@ import com.enderio.core.common.Handlers.Handler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; @Handler -public class EnchantTooltipHandler -{ - @SuppressWarnings("unchecked") - @SubscribeEvent - public void handleTooltip(ItemTooltipEvent event) - { - if (event.itemStack.hasTagCompound()) - { - Map enchantments = EnchantmentHelper.getEnchantments(event.itemStack); +public class EnchantTooltipHandler { + @SuppressWarnings("unchecked") + @SubscribeEvent + public void handleTooltip(ItemTooltipEvent event) { + if (event.itemStack.hasTagCompound()) { + Map enchantments = EnchantmentHelper.getEnchantments(event.itemStack); - for (Integer integer : enchantments.keySet()) - { - Enchantment enchant = Enchantment.enchantmentsList[integer]; - - if (enchant instanceof IAdvancedEnchant) - { - for (int i = 0; i < event.toolTip.size(); i++) - { - if (event.toolTip.get(i).contains(StatCollector.translateToLocal(enchant.getName()))) - { - for (String s : ((IAdvancedEnchant) enchant).getTooltipDetails(event.itemStack)) - { - event.toolTip.add(i + 1, EnumChatFormatting.DARK_GRAY.toString() + EnumChatFormatting.ITALIC + " - " + s); - i++; - } - } - } - } + for (Integer integer : enchantments.keySet()) { + Enchantment enchant = Enchantment.enchantmentsList[integer]; + + if (enchant instanceof IAdvancedEnchant) { + for (int i = 0; i < event.toolTip.size(); i++) { + if (event.toolTip.get(i).contains(StatCollector.translateToLocal(enchant.getName()))) { + for (String s : ((IAdvancedEnchant) enchant).getTooltipDetails(event.itemStack)) { + event.toolTip.add(i + 1, EnumChatFormatting.DARK_GRAY.toString() + EnumChatFormatting.ITALIC + " - " + s); + i++; + } } + } } + } } + } } diff --git a/src/main/java/com/enderio/core/client/handlers/OreDictTooltipHandler.java b/src/main/java/com/enderio/core/client/handlers/OreDictTooltipHandler.java index 5b1413f..d694a46 100644 --- a/src/main/java/com/enderio/core/client/handlers/OreDictTooltipHandler.java +++ b/src/main/java/com/enderio/core/client/handlers/OreDictTooltipHandler.java @@ -15,33 +15,27 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import static com.enderio.core.common.config.ConfigHandler.*; @Handler -public class OreDictTooltipHandler -{ - @SubscribeEvent - public void onItemTooltip(ItemTooltipEvent event) - { - boolean shiftDown = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - boolean debugMode = Minecraft.getMinecraft().gameSettings.advancedItemTooltips; - boolean doRegistry = showRegistryNameTooltips == 3 ? debugMode : showRegistryNameTooltips == 2 ? shiftDown : showRegistryNameTooltips == 1; - boolean doOredict = showOredictTooltips == 3 ? debugMode : showOredictTooltips == 2 ? shiftDown : showOredictTooltips == 1; +public class OreDictTooltipHandler { + @SubscribeEvent + public void onItemTooltip(ItemTooltipEvent event) { + boolean shiftDown = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + boolean debugMode = Minecraft.getMinecraft().gameSettings.advancedItemTooltips; + boolean doRegistry = showRegistryNameTooltips == 3 ? debugMode : showRegistryNameTooltips == 2 ? shiftDown : showRegistryNameTooltips == 1; + boolean doOredict = showOredictTooltips == 3 ? debugMode : showOredictTooltips == 2 ? shiftDown : showOredictTooltips == 1; - if (doRegistry) - { - event.toolTip.add(Item.itemRegistry.getNameForObject(event.itemStack.getItem())); - } - - if (doOredict) - { - int[] ids = OreDictionary.getOreIDs(event.itemStack); - - if (ids.length > 0) - { - event.toolTip.add(EnderCore.lang.localize("tooltip.oreDictNames")); - for (int i : ids) - { - event.toolTip.add(" - " + OreDictionary.getOreName(i)); - } - } - } + if (doRegistry) { + event.toolTip.add(Item.itemRegistry.getNameForObject(event.itemStack.getItem())); } + + if (doOredict) { + int[] ids = OreDictionary.getOreIDs(event.itemStack); + + if (ids.length > 0) { + event.toolTip.add(EnderCore.lang.localize("tooltip.oreDictNames")); + for (int i : ids) { + event.toolTip.add(" - " + OreDictionary.getOreName(i)); + } + } + } + } } diff --git a/src/main/java/com/enderio/core/client/handlers/SpecialTooltipHandler.java b/src/main/java/com/enderio/core/client/handlers/SpecialTooltipHandler.java index f8de587..7a799a5 100644 --- a/src/main/java/com/enderio/core/client/handlers/SpecialTooltipHandler.java +++ b/src/main/java/com/enderio/core/client/handlers/SpecialTooltipHandler.java @@ -40,19 +40,19 @@ public class SpecialTooltipHandler { } public static final SpecialTooltipHandler INSTANCE = new SpecialTooltipHandler(); - + private final List callbacks = Lists.newArrayList(); - + public void addCallback(ITooltipCallback callback) { callbacks.add(callback); } @SubscribeEvent public void addTooltip(ItemTooltipEvent evt) { - if(evt.itemStack == null) { + if (evt.itemStack == null) { return; } - + boolean shiftDown = showAdvancedTooltips(); boolean debugMode = Minecraft.getMinecraft().gameSettings.advancedItemTooltips; boolean doDurability = showDurabilityTooltips == 3 ? debugMode : showDurabilityTooltips == 2 ? shiftDown : showDurabilityTooltips == 1; @@ -61,38 +61,37 @@ public class SpecialTooltipHandler { addDurabilityTooltip(evt.toolTip, evt.itemStack); } - if(evt.itemStack.getItem() instanceof IAdvancedTooltipProvider) { + if (evt.itemStack.getItem() instanceof IAdvancedTooltipProvider) { IAdvancedTooltipProvider ttp = (IAdvancedTooltipProvider) evt.itemStack.getItem(); addInformation(ttp, evt.itemStack, evt.entityPlayer, evt.toolTip, false); return; - } else if(evt.itemStack.getItem() instanceof IResourceTooltipProvider) { + } else if (evt.itemStack.getItem() instanceof IResourceTooltipProvider) { addInformation((IResourceTooltipProvider) evt.itemStack.getItem(), evt); return; } Block blk = Block.getBlockFromItem(evt.itemStack.getItem()); - if(blk instanceof IAdvancedTooltipProvider) { + if (blk instanceof IAdvancedTooltipProvider) { addInformation((IAdvancedTooltipProvider) blk, evt.itemStack, evt.entityPlayer, evt.toolTip, false); return; - } else if(blk instanceof IResourceTooltipProvider) { + } else if (blk instanceof IResourceTooltipProvider) { addInformation((IResourceTooltipProvider) blk, evt); return; } - + for (ITooltipCallback callback : callbacks) { if (callback.shouldHandleItem(evt.itemStack)) { addInformation(callback, evt.itemStack, evt.entityPlayer, evt.toolTip, false); } } } - + public void addDurabilityTooltip(List toolTip, ItemStack itemStack) { - if(!itemStack.isItemStackDamageable()) { + if (!itemStack.isItemStackDamageable()) { return; } Item item = itemStack.getItem(); - if(item instanceof ItemTool || item instanceof ItemArmor || - item instanceof ItemSword || item instanceof ItemHoe || item instanceof ItemBow) { + if (item instanceof ItemTool || item instanceof ItemArmor || item instanceof ItemSword || item instanceof ItemHoe || item instanceof ItemBow) { toolTip.add(ItemUtil.getDurabilityString(itemStack)); } } @@ -103,13 +102,13 @@ public class SpecialTooltipHandler { public void addInformation(IResourceTooltipProvider tt, ItemStack itemstack, EntityPlayer entityplayer, List list) { String name = tt.getUnlocalizedNameForTooltip(itemstack); - if(showAdvancedTooltips()) { + if (showAdvancedTooltips()) { addCommonTooltipFromResources(list, name); addDetailedTooltipFromResources(list, name); } else { addBasicTooltipFromResources(list, name); addCommonTooltipFromResources(list, name); - if(hasDetailedTooltip(tt, itemstack)) { + if (hasDetailedTooltip(tt, itemstack)) { addShowDetailsTooltip(list); } } @@ -117,11 +116,11 @@ public class SpecialTooltipHandler { public void addInformation(IAdvancedTooltipProvider tt, ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { tt.addCommonEntries(itemstack, entityplayer, list, flag); - if(showAdvancedTooltips()) { + if (showAdvancedTooltips()) { tt.addDetailedEntries(itemstack, entityplayer, list, flag); } else { tt.addBasicEntries(itemstack, entityplayer, list, flag); - if(hasDetailedTooltip(tt, itemstack, entityplayer, flag)) { + if (hasDetailedTooltip(tt, itemstack, entityplayer, flag)) { addShowDetailsTooltip(list); } } @@ -168,7 +167,7 @@ public class SpecialTooltipHandler { while (!done) { String key = keyBase + line; String val = EnderCore.lang.localizeExact(key); - if(val == null || val.trim().length() < 0 || val.equals(key) || line > 12) { + if (val == null || val.trim().length() < 0 || val.equals(key) || line > 12) { done = true; } else { list.add(val); @@ -180,23 +179,23 @@ public class SpecialTooltipHandler { private static String getUnlocalizedNameForTooltip(ItemStack itemstack) { String unlocalizedNameForTooltip = null; if (itemstack.getItem() instanceof IResourceTooltipProvider) { - unlocalizedNameForTooltip = ((IResourceTooltipProvider)itemstack.getItem()).getUnlocalizedNameForTooltip(itemstack); + unlocalizedNameForTooltip = ((IResourceTooltipProvider) itemstack.getItem()).getUnlocalizedNameForTooltip(itemstack); } - if(unlocalizedNameForTooltip == null) { + if (unlocalizedNameForTooltip == null) { unlocalizedNameForTooltip = itemstack.getItem().getUnlocalizedName(itemstack); } return unlocalizedNameForTooltip; } public static void addCommonTooltipFromResources(List list, ItemStack itemstack) { - if(itemstack.getItem() == null) { + if (itemstack.getItem() == null) { return; } addCommonTooltipFromResources(list, getUnlocalizedNameForTooltip(itemstack)); } public static void addDetailedTooltipFromResources(List list, ItemStack itemstack) { - if(itemstack.getItem() == null) { + if (itemstack.getItem() == null) { return; } addDetailedTooltipFromResources(list, getUnlocalizedNameForTooltip(itemstack)); diff --git a/src/main/java/com/enderio/core/client/render/BoundingBox.java b/src/main/java/com/enderio/core/client/render/BoundingBox.java index c2c16ab..75d0f07 100644 --- a/src/main/java/com/enderio/core/client/render/BoundingBox.java +++ b/src/main/java/com/enderio/core/client/render/BoundingBox.java @@ -28,7 +28,7 @@ public final class BoundingBox { public BoundingBox(AxisAlignedBB bb) { this(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); } - + public BoundingBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { this.minX = minX; this.minY = minY; @@ -60,13 +60,13 @@ public final class BoundingBox { } public BoundingBox(Block block) { - this(block.getBlockBoundsMinX(), block.getBlockBoundsMinY(), block.getBlockBoundsMinZ(), block.getBlockBoundsMaxX(), block.getBlockBoundsMaxY(), block.getBlockBoundsMaxZ()); + this(block.getBlockBoundsMinX(), block.getBlockBoundsMinY(), block.getBlockBoundsMinZ(), block.getBlockBoundsMaxX(), block.getBlockBoundsMaxY(), block + .getBlockBoundsMaxZ()); } public BoundingBox expandBy(BoundingBox other) { - return new BoundingBox( - Math.min(minX, other.minX), Math.min(minY, other.minY), Math.min(minZ, other.minZ), - Math.max(maxX, other.maxX), Math.max(maxY, other.maxY), Math.max(maxZ, other.maxZ)); + return new BoundingBox(Math.min(minX, other.minX), Math.min(minY, other.minY), Math.min(minZ, other.minZ), Math.max(maxX, other.maxX), Math.max(maxY, + other.maxY), Math.max(maxZ, other.maxZ)); } public boolean contains(BoundingBox other) { @@ -115,9 +115,8 @@ public final class BoundingBox { iTransformation.apply(min); iTransformation.apply(max); - return new BoundingBox( - Math.min(min.x, max.x), Math.min(min.y, max.y), Math.min(min.z, max.z), - Math.max(min.x, max.x), Math.max(min.y, max.y), Math.max(min.z, max.z)); + return new BoundingBox(Math.min(min.x, max.x), Math.min(min.y, max.y), Math.min(min.z, max.z), Math.max(min.x, max.x), Math.max(min.y, max.y), Math.max( + min.z, max.z)); } @@ -322,28 +321,28 @@ public final class BoundingBox { float mxY = maxY; float mxZ = maxZ; boolean mod = false; - if(minX > maxX) { + if (minX > maxX) { mnX = maxX; mxX = minX; mod = true; } - if(minY > maxY) { + if (minY > maxY) { mnY = maxY; mxY = minY; mod = true; } - if(minZ > maxZ) { + if (minZ > maxZ) { mnZ = maxZ; mxZ = minZ; mod = true; } - if(!mod) { + if (!mod) { return this; } return new BoundingBox(mnX, mnY, mnZ, mxX, mxY, mxZ); } - public AxisAlignedBB getAxisAlignedBB() { + public AxisAlignedBB getAxisAlignedBB() { return AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); } @@ -362,24 +361,24 @@ public final class BoundingBox { @Override public boolean equals(Object obj) { - if(this == obj) + if (this == obj) return true; - if(obj == null) + if (obj == null) return false; - if(getClass() != obj.getClass()) + if (getClass() != obj.getClass()) return false; BoundingBox other = (BoundingBox) obj; - if(Float.floatToIntBits(maxX) != Float.floatToIntBits(other.maxX)) + if (Float.floatToIntBits(maxX) != Float.floatToIntBits(other.maxX)) return false; - if(Float.floatToIntBits(maxY) != Float.floatToIntBits(other.maxY)) + if (Float.floatToIntBits(maxY) != Float.floatToIntBits(other.maxY)) return false; - if(Float.floatToIntBits(maxZ) != Float.floatToIntBits(other.maxZ)) + if (Float.floatToIntBits(maxZ) != Float.floatToIntBits(other.maxZ)) return false; - if(Float.floatToIntBits(minX) != Float.floatToIntBits(other.minX)) + if (Float.floatToIntBits(minX) != Float.floatToIntBits(other.minX)) return false; - if(Float.floatToIntBits(minY) != Float.floatToIntBits(other.minY)) + if (Float.floatToIntBits(minY) != Float.floatToIntBits(other.minY)) return false; - if(Float.floatToIntBits(minZ) != Float.floatToIntBits(other.minZ)) + if (Float.floatToIntBits(minZ) != Float.floatToIntBits(other.minZ)) return false; return true; } diff --git a/src/main/java/com/enderio/core/client/render/ConnectedTextureRenderer.java b/src/main/java/com/enderio/core/client/render/ConnectedTextureRenderer.java index 33061eb..decd064 100644 --- a/src/main/java/com/enderio/core/client/render/ConnectedTextureRenderer.java +++ b/src/main/java/com/enderio/core/client/render/ConnectedTextureRenderer.java @@ -46,10 +46,10 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR @Override public IIcon getTextureForFace(ForgeDirection dir) { - if(tex != null) { + if (tex != null) { return tex; } - if(block != null) { + if (block != null) { return block.getIcon(dir.ordinal(), meta); } return null; @@ -62,7 +62,7 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR private TextureCallback edgeTexureCallback; private boolean matchMetaData; - + private EnumSet sidesToRender = EnumSet.allOf(ForgeDirection.class); public boolean isForceAllEdges() { @@ -82,21 +82,21 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR } public void setEdgeTexture(IIcon texture) { - if(texture == null) { + if (texture == null) { edgeTexureCallback = null; return; } edgeTexureCallback = new DefaultTextureCallback(texture); } - + public void setMatchMeta(boolean matchMetaData) { - this.matchMetaData = matchMetaData; + this.matchMetaData = matchMetaData; } - + public void setSidesToRender(EnumSet sides) { sidesToRender = sides.clone(); } - + @Override public boolean matchesMetadata(int meta1, int meta2) { return !this.matchMetaData || meta1 == meta2; @@ -105,7 +105,7 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR @Override public void renderFace(CustomRenderBlocks rb, ForgeDirection face, Block par1Block, double x, double y, double z, IIcon texture, List refVertices, boolean translateToXYZ) { - + if (!sidesToRender.contains(face)) { return; } @@ -114,11 +114,11 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR finalVerts.addAll(refVertices); IIcon borderTex = edgeTexureCallback == null ? null : edgeTexureCallback.getTextureForFace(face); - if(borderTex != null) { + if (borderTex != null) { texture = borderTex; List edges; - if(forceAllEdges) { + if (forceAllEdges) { edges = RenderUtil.getEdgesForFace(face); } else { edges = RenderUtil.getNonConectedEdgesForFace(rb.blockAccess, (int) x, (int) y, (int) z, face, this); @@ -140,16 +140,16 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR float xLen = 1 - Math.abs(edge.offsetX) * scaleFactor; float yLen = 1 - Math.abs(edge.offsetY) * scaleFactor; float zLen = 1 - Math.abs(edge.offsetZ) * scaleFactor; - - xLen -= 2* (1 - par1Block.getBlockBoundsMaxX()) - par1Block.getBlockBoundsMinX(); - yLen -= 2* (1 - par1Block.getBlockBoundsMaxY()) - par1Block.getBlockBoundsMinY(); - zLen -= 2* (1 - par1Block.getBlockBoundsMaxZ()) - par1Block.getBlockBoundsMinZ(); + + xLen -= 2 * (1 - par1Block.getBlockBoundsMaxX()) - par1Block.getBlockBoundsMinX(); + yLen -= 2 * (1 - par1Block.getBlockBoundsMaxY()) - par1Block.getBlockBoundsMinY(); + zLen -= 2 * (1 - par1Block.getBlockBoundsMaxZ()) - par1Block.getBlockBoundsMinZ(); BoundingBox bb = BoundingBox.UNIT_CUBE.scale(xLen, yLen, zLen); List corners = bb.getCornersForFaceD(face); for (Vector3d corner : corners) { - if(translateToXYZ) { + if (translateToXYZ) { corner.x += x; corner.y += y; corner.z += z; @@ -162,7 +162,7 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR int[] indices = new int[] { 0, 1, 2, 3 }; for (int index : indices) { Vector3d corner = corners.get(index); - if(translateToXYZ) { + if (translateToXYZ) { RenderUtil.getUvForCorner(uv, corner, (int) x, (int) y, (int) z, face, texture); } else { RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture); @@ -179,7 +179,7 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR for (int i = 0; i < allEdges.size(); i++) { ForgeDirection dir = allEdges.get(i); ForgeDirection dir2 = i + 1 < allEdges.size() ? allEdges.get(i + 1) : allEdges.get(0); - if(needsCorner(dir, dir2, edges, face, par1Block, x, y, z, rb.blockAccess)) { + if (needsCorner(dir, dir2, edges, face, par1Block, x, y, z, rb.blockAccess)) { Vertex v = new Vertex(); v.uv = new Vector2f(); @@ -190,16 +190,16 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR v.xyz.x = Math.max(-0.001, v.xyz.x); v.xyz.y = Math.max(-0.001, v.xyz.y); v.xyz.z = Math.max(-0.001, v.xyz.z); - + v.xyz.x -= (1 - par1Block.getBlockBoundsMaxX()) - par1Block.getBlockBoundsMinX(); v.xyz.y -= (1 - par1Block.getBlockBoundsMaxY()) - par1Block.getBlockBoundsMinY(); v.xyz.z -= (1 - par1Block.getBlockBoundsMaxZ()) - par1Block.getBlockBoundsMinZ(); - - if(ForgeDirectionOffsets.isPositiveOffset(face)) { + + if (ForgeDirectionOffsets.isPositiveOffset(face)) { v.xyz.add(ForgeDirectionOffsets.forDir(face)); } - if(translateToXYZ) { + if (translateToXYZ) { v.xyz.x += x; v.xyz.y += y; v.xyz.z += z; @@ -212,7 +212,7 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR finalVerts.add(v); Vector3d corner = new Vector3d(v.xyz); - if(ForgeDirectionOffsets.isPositiveOffset(face)) { + if (ForgeDirectionOffsets.isPositiveOffset(face)) { addVertexForCorner(face, x, y, z, texture, translateToXYZ, finalVerts, dir2, null, corner); addVertexForCorner(face, x, y, z, texture, translateToXYZ, finalVerts, dir, dir2, corner); addVertexForCorner(face, x, y, z, texture, translateToXYZ, finalVerts, dir, null, corner); @@ -233,7 +233,7 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR double d2 = Double.MAX_VALUE; for (Vertex v : vertices) { double tmp = corner.distanceSquared(v.xyz); - if(tmp <= d2) { + if (tmp <= d2) { result = v; d2 = tmp; } @@ -248,10 +248,10 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR vert.uv = new Vector2f(); vert.xyz.set(corner); vert.xyz.sub(ForgeDirectionOffsets.offsetScaled(dir, scale)); - if(dir2 != null) { + if (dir2 != null) { vert.xyz.sub(ForgeDirectionOffsets.offsetScaled(dir2, scale)); } - if(translateToXYZ) { + if (translateToXYZ) { RenderUtil.getUvForCorner(vert.uv, vert.xyz, (int) x, (int) y, (int) z, face, texture); } else { RenderUtil.getUvForCorner(vert.uv, vert.xyz, 0, 0, 0, face, texture); @@ -262,31 +262,30 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR private void applyLighting(Vertex vert, Vector3d samplePoint, List litVertices) { Vertex closest = getClosestVertex(litVertices, samplePoint); - if(closest == null) { + if (closest == null) { return; } vert.setBrightness(closest.brightness); Vector4f col = closest.getColor(); - if(col != null) { + if (col != null) { vert.setColor(col); } } - private boolean needsCorner(ForgeDirection dir, ForgeDirection dir2, List edges, ForgeDirection face, - Block par1Block, double x, double y, + private boolean needsCorner(ForgeDirection dir, ForgeDirection dir2, List edges, ForgeDirection face, Block par1Block, double x, double y, double z, IBlockAccess blockAccess) { - if(edges.contains(dir) || edges.contains(dir2)) { + if (edges.contains(dir) || edges.contains(dir2)) { return false; } BlockCoord bc = new BlockCoord((int) x, (int) y, (int) z); BlockCoord testLoc = bc.getLocation(dir); - if(RenderUtil.getNonConectedEdgesForFace(blockAccess, testLoc.x, testLoc.y, testLoc.z, face, this).contains(dir2)) { + if (RenderUtil.getNonConectedEdgesForFace(blockAccess, testLoc.x, testLoc.y, testLoc.z, face, this).contains(dir2)) { return true; } testLoc = bc.getLocation(dir2); - if(RenderUtil.getNonConectedEdgesForFace(blockAccess, testLoc.x, testLoc.y, testLoc.z, face, this).contains(dir)) { + if (RenderUtil.getNonConectedEdgesForFace(blockAccess, testLoc.x, testLoc.y, testLoc.z, face, this).contains(dir)) { return true; } return false; @@ -294,7 +293,7 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR private void moveCorners(List vertices, ForgeDirection edge, float scaleFactor) { int[] indices = getClosest(edge, vertices); - if(indices[0] < 0) { + if (indices[0] < 0) { return; } vertices.get(indices[0]).xyz.x -= scaleFactor * edge.offsetX; @@ -312,8 +311,8 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR int index = 0; for (Vertex v : vertices) { double val = get(v.xyz, edge); - if(highest ? val >= minMax : val <= minMax) { - if(val != minMax) { + if (highest ? val >= minMax : val <= minMax) { + if (val != minMax) { res[0] = index; } else { res[1] = index; @@ -326,14 +325,13 @@ public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureR } private double get(Vector3d xyz, ForgeDirection edge) { - if(edge == ForgeDirection.EAST || edge == ForgeDirection.WEST) { + if (edge == ForgeDirection.EAST || edge == ForgeDirection.WEST) { return xyz.x; } - if(edge == ForgeDirection.UP || edge == ForgeDirection.DOWN) { + if (edge == ForgeDirection.UP || edge == ForgeDirection.DOWN) { return xyz.y; } return xyz.z; } - } diff --git a/src/main/java/com/enderio/core/client/render/CubeRenderer.java b/src/main/java/com/enderio/core/client/render/CubeRenderer.java index e20e85a..5e1aebe 100644 --- a/src/main/java/com/enderio/core/client/render/CubeRenderer.java +++ b/src/main/java/com/enderio/core/client/render/CubeRenderer.java @@ -20,15 +20,15 @@ public final class CubeRenderer { public static void render(Block block, int meta) { render(block, meta, null); } - + public static void render(Block block, int meta, VertexTransform xForm) { IIcon[] icons = new IIcon[6]; - for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { icons[dir.ordinal()] = block.getIcon(dir.ordinal(), meta); } render(BoundingBox.UNIT_CUBE.translate(0, -0.1f, 0), icons, xForm, true); } - + public static void render(BoundingBox bb, IIcon tex) { render(bb, tex, null, false); } @@ -40,13 +40,13 @@ public final class CubeRenderer { public static void render(BoundingBox bb, IIcon tex, VertexTransform xForm) { render(bb, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), xForm, false); } - + public static void render(BoundingBox bb, IIcon tex, VertexTransform xForm, float[] brightnessPerSide, boolean tintSides) { float minU = 0; float minV = 0; float maxU = 1; float maxV = 1; - if(tex != null) { + if (tex != null) { minU = tex.getMinU(); minV = tex.getMinV(); maxU = tex.getMaxU(); @@ -60,7 +60,7 @@ public final class CubeRenderer { float minV = 0; float maxU = 1; float maxV = 1; - if(tex != null) { + if (tex != null) { minU = tex.getMinU(); minV = tex.getMinV(); maxU = tex.getMaxU(); @@ -83,7 +83,7 @@ public final class CubeRenderer { public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm, boolean tintSides) { float[] brightnessPerSide = null; - if(tintSides) { + if (tintSides) { brightnessPerSide = new float[6]; for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { brightnessPerSide[dir.ordinal()] = RenderUtil.getColorMultiplierForFace(dir); @@ -94,8 +94,8 @@ public final class CubeRenderer { public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm, float[] brightnessPerSide, boolean tintSides) { - if(tintSides) { - if(brightnessPerSide == null || brightnessPerSide.length != 6) { + if (tintSides) { + if (brightnessPerSide == null || brightnessPerSide.length != 6) { brightnessPerSide = new float[] { 1, 1, 1, 1, 1, 1 }; } for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { @@ -108,7 +108,7 @@ public final class CubeRenderer { public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm, float[] brightnessPerSide) { - if(brightnessPerSide != null && brightnessPerSide.length != 6) { + if (brightnessPerSide != null && brightnessPerSide.length != 6) { brightnessPerSide = null; } @@ -121,7 +121,7 @@ public final class CubeRenderer { Tessellator tessellator = Tessellator.instance; tessellator.setNormal(0, 0, -1); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.NORTH.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -131,7 +131,7 @@ public final class CubeRenderer { addVecWithUV(verts[2], minU, maxV); tessellator.setNormal(0, 0, 1); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.SOUTH.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -141,7 +141,7 @@ public final class CubeRenderer { addVecWithUV(verts[7], minU, maxV); tessellator.setNormal(0, 1, 0); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.UP.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -151,7 +151,7 @@ public final class CubeRenderer { addVecWithUV(verts[7], maxU, minV); tessellator.setNormal(0, -1, 0); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.DOWN.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -161,7 +161,7 @@ public final class CubeRenderer { addVecWithUV(verts[4], maxU, minV); tessellator.setNormal(1, 0, 0); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.EAST.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -171,7 +171,7 @@ public final class CubeRenderer { addVecWithUV(verts[1], minU, minV); tessellator.setNormal(-1, 0, 0); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.WEST.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -183,19 +183,19 @@ public final class CubeRenderer { public static void render(BoundingBox bb, IIcon[] icons, boolean tintSides) { float[] brightnessPerSide = null; - if(tintSides) { + if (tintSides) { brightnessPerSide = new float[6]; for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { brightnessPerSide[dir.ordinal()] = RenderUtil.getColorMultiplierForFace(dir); } - } + } render(bb, icons, null, brightnessPerSide); - + } - + public static void render(BoundingBox bb, IIcon[] icons, VertexTransform xForm, boolean tintSides) { float[] brightnessPerSide = null; - if(tintSides) { + if (tintSides) { brightnessPerSide = new float[6]; for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { brightnessPerSide[dir.ordinal()] = RenderUtil.getColorMultiplierForFace(dir); @@ -203,7 +203,7 @@ public final class CubeRenderer { } render(bb, icons, xForm, brightnessPerSide); } - + public static void render(BoundingBox bb, IIcon[] faceTextures, VertexTransform xForm, float[] brightnessPerSide) { setupVertices(bb, xForm); float minU; @@ -212,10 +212,10 @@ public final class CubeRenderer { float maxV; IIcon tex; - Tessellator tessellator = Tessellator.instance; + Tessellator tessellator = Tessellator.instance; tessellator.setNormal(0, 0, -1); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.NORTH.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -231,7 +231,7 @@ public final class CubeRenderer { addVecWithUV(verts[2], minU, minV); tessellator.setNormal(0, 0, 1); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.SOUTH.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -246,7 +246,7 @@ public final class CubeRenderer { addVecWithUV(verts[7], minU, minV); tessellator.setNormal(0, 1, 0); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.UP.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -261,7 +261,7 @@ public final class CubeRenderer { addVecWithUV(verts[7], maxU, minV); tessellator.setNormal(0, -1, 0); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.DOWN.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -276,7 +276,7 @@ public final class CubeRenderer { addVecWithUV(verts[4], maxU, minV); tessellator.setNormal(1, 0, 0); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.EAST.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -291,7 +291,7 @@ public final class CubeRenderer { addVecWithUV(verts[1], minU, maxV); tessellator.setNormal(-1, 0, 0); - if(brightnessPerSide != null) { + if (brightnessPerSide != null) { float cm = brightnessPerSide[ForgeDirection.WEST.ordinal()]; tessellator.setColorOpaque_F(cm, cm, cm); } @@ -320,7 +320,7 @@ public final class CubeRenderer { verts[6].set(bound.maxX, bound.maxY, bound.maxZ); verts[7].set(bound.minX, bound.maxY, bound.maxZ); - if(xForm != null) { + if (xForm != null) { for (Vector3d vec : verts) { xForm.apply(vec); } @@ -334,8 +334,4 @@ public final class CubeRenderer { private CubeRenderer() { } - - - - } diff --git a/src/main/java/com/enderio/core/client/render/CustomCubeRenderer.java b/src/main/java/com/enderio/core/client/render/CustomCubeRenderer.java index d97db05..de6be92 100644 --- a/src/main/java/com/enderio/core/client/render/CustomCubeRenderer.java +++ b/src/main/java/com/enderio/core/client/render/CustomCubeRenderer.java @@ -21,13 +21,13 @@ public class CustomCubeRenderer { } public void renderBlock(IBlockAccess ba, Block par1Block, int par2, int par3, int par4, IRenderFace renderer) { - if(rb == null) { + if (rb == null) { rb = new CustomRenderBlocks(ba); } rb.blockAccess = ba; rb.setOverrideTexture(getOverrideTexture()); rb.setFaceRenderers(null); - if(renderer != null) { + if (renderer != null) { rb.addFaceRenderer(renderer); } rb.setRenderBoundsFromBlock(par1Block); @@ -35,7 +35,7 @@ public class CustomCubeRenderer { } public void renderBlock(IBlockAccess ba, Block par1Block, int par2, int par3, int par4, Collection renderers) { - if(rb == null) { + if (rb == null) { rb = new CustomRenderBlocks(ba); } rb.blockAccess = ba; diff --git a/src/main/java/com/enderio/core/client/render/CustomRenderBlocks.java b/src/main/java/com/enderio/core/client/render/CustomRenderBlocks.java index 48ad967..ac13ec3 100644 --- a/src/main/java/com/enderio/core/client/render/CustomRenderBlocks.java +++ b/src/main/java/com/enderio/core/client/render/CustomRenderBlocks.java @@ -26,7 +26,7 @@ public class CustomRenderBlocks extends RenderBlocks { public CustomRenderBlocks() { super(); } - + public CustomRenderBlocks(IBlockAccess par1iBlockAccess) { super(par1iBlockAccess); } @@ -37,7 +37,7 @@ public class CustomRenderBlocks extends RenderBlocks { public void setFaceRenderers(Collection renderers) { renderFaceCallbacks.clear(); - if(renderers != null) { + if (renderers != null) { renderFaceCallbacks.addAll(renderers); } } @@ -61,13 +61,13 @@ public class CustomRenderBlocks extends RenderBlocks { public void setOverrideTexture(IIcon overrideTexture) { this.overrideTexture = overrideTexture; } - + public void setShouldRenderBaseTexture(boolean val) { shouldRenderBaseTexture = val; } private void renderFace(ForgeDirection face, Block par1Block, double x, double y, double z, IIcon texture) { - if(renderFaceCallbacks.isEmpty()) { + if (renderFaceCallbacks.isEmpty()) { doDefaultRenderFace(face, par1Block, x, y, z, overrideTexture == null ? texture : overrideTexture); } else { List faceVertices = createVerticesForFace(face, par1Block, x, y, z, overrideTexture == null ? texture : overrideTexture); @@ -156,7 +156,7 @@ public class CustomRenderBlocks extends RenderBlocks { private List calcFaceXNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - if(hasOverrideBlockTexture()) { + if (hasOverrideBlockTexture()) { par8Icon = this.overrideBlockTexture; } @@ -166,18 +166,18 @@ public class CustomRenderBlocks extends RenderBlocks { double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); double d7; - if(this.flipTexture) { + if (this.flipTexture) { d7 = d3; d3 = d4; d4 = d7; } - if(this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { + if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { d3 = par8Icon.getMinU(); d4 = par8Icon.getMaxU(); } - if(this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { + if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { d5 = par8Icon.getMinV(); d6 = par8Icon.getMaxV(); } @@ -187,7 +187,7 @@ public class CustomRenderBlocks extends RenderBlocks { double d9 = d5; double d10 = d6; - if(this.uvRotateNorth == 1) { + if (this.uvRotateNorth == 1) { d3 = par8Icon.getInterpolatedU(this.renderMinY * 16.0D); d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxZ * 16.0D); d4 = par8Icon.getInterpolatedU(this.renderMaxY * 16.0D); @@ -198,7 +198,7 @@ public class CustomRenderBlocks extends RenderBlocks { d8 = d4; d5 = d6; d6 = d9; - } else if(this.uvRotateNorth == 2) { + } else if (this.uvRotateNorth == 2) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMaxY * 16.0D); d5 = par8Icon.getInterpolatedV(this.renderMinZ * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMinY * 16.0D); @@ -209,7 +209,7 @@ public class CustomRenderBlocks extends RenderBlocks { d4 = d8; d9 = d6; d10 = d5; - } else if(this.uvRotateNorth == 3) { + } else if (this.uvRotateNorth == 3) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMinZ * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMaxZ * 16.0D); d5 = par8Icon.getInterpolatedV(this.renderMaxY * 16.0D); @@ -228,7 +228,7 @@ public class CustomRenderBlocks extends RenderBlocks { List result = new ArrayList(4); Vertex v; - if(enableAO) { + if (enableAO) { result.add(new Vertex(d11, d13, d15, d7, d9, brightnessTopLeft, colorRedTopLeft, this.colorGreenTopLeft, this.colorBlueTopLeft, 1)); result.add(new Vertex(d11, d13, d14, d3, d5, brightnessBottomLeft, colorRedBottomLeft, this.colorGreenBottomLeft, this.colorBlueBottomLeft, 1)); result.add(new Vertex(d11, d12, d14, d8, d10, brightnessBottomRight, colorRedBottomRight, this.colorGreenBottomRight, this.colorBlueBottomRight, 1)); @@ -244,7 +244,7 @@ public class CustomRenderBlocks extends RenderBlocks { private List calcFaceYPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - if(this.hasOverrideBlockTexture()) { + if (this.hasOverrideBlockTexture()) { par8Icon = this.overrideBlockTexture; } @@ -253,12 +253,12 @@ public class CustomRenderBlocks extends RenderBlocks { double d5 = par8Icon.getInterpolatedV(this.renderMinZ * 16.0D); double d6 = par8Icon.getInterpolatedV(this.renderMaxZ * 16.0D); - if(this.renderMinX < 0.0D || this.renderMaxX > 1.0D) { + if (this.renderMinX < 0.0D || this.renderMaxX > 1.0D) { d3 = par8Icon.getMinU(); d4 = par8Icon.getMaxU(); } - if(this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { + if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { d5 = par8Icon.getMinV(); d6 = par8Icon.getMaxV(); } @@ -268,7 +268,7 @@ public class CustomRenderBlocks extends RenderBlocks { double d9 = d5; double d10 = d6; - if(this.uvRotateTop == 1) { + if (this.uvRotateTop == 1) { d3 = par8Icon.getInterpolatedU(this.renderMinZ * 16.0D); d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxX * 16.0D); d4 = par8Icon.getInterpolatedU(this.renderMaxZ * 16.0D); @@ -279,7 +279,7 @@ public class CustomRenderBlocks extends RenderBlocks { d8 = d4; d5 = d6; d6 = d9; - } else if(this.uvRotateTop == 2) { + } else if (this.uvRotateTop == 2) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMaxZ * 16.0D); d5 = par8Icon.getInterpolatedV(this.renderMinX * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMinZ * 16.0D); @@ -290,7 +290,7 @@ public class CustomRenderBlocks extends RenderBlocks { d4 = d8; d9 = d6; d10 = d5; - } else if(this.uvRotateTop == 3) { + } else if (this.uvRotateTop == 3) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMinX * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMaxX * 16.0D); d5 = par8Icon.getInterpolatedV(16.0D - this.renderMinZ * 16.0D); @@ -309,7 +309,7 @@ public class CustomRenderBlocks extends RenderBlocks { List result = new ArrayList(4); Vertex v; - if(enableAO) { + if (enableAO) { v = new Vertex(d12, d13, d15, d4, d6, brightnessTopLeft, colorRedTopLeft, this.colorGreenTopLeft, this.colorBlueTopLeft, 1); result.add(v); v = new Vertex(d12, d13, d14, d7, d9, brightnessBottomLeft, colorRedBottomLeft, this.colorGreenBottomLeft, this.colorBlueBottomLeft, 1); @@ -331,12 +331,10 @@ public class CustomRenderBlocks extends RenderBlocks { return result; } - private List calcFaceZPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) - { + private List calcFaceZPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { Tessellator tessellator = Tessellator.instance; - if(this.hasOverrideBlockTexture()) - { + if (this.hasOverrideBlockTexture()) { par8Icon = this.overrideBlockTexture; } @@ -346,21 +344,18 @@ public class CustomRenderBlocks extends RenderBlocks { double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); double d7; - if(this.flipTexture) - { + if (this.flipTexture) { d7 = d3; d3 = d4; d4 = d7; } - if(this.renderMinX < 0.0D || this.renderMaxX > 1.0D) - { + if (this.renderMinX < 0.0D || this.renderMaxX > 1.0D) { d3 = par8Icon.getMinU(); d4 = par8Icon.getMaxU(); } - if(this.renderMinY < 0.0D || this.renderMaxY > 1.0D) - { + if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { d5 = par8Icon.getMinV(); d6 = par8Icon.getMaxV(); } @@ -370,8 +365,7 @@ public class CustomRenderBlocks extends RenderBlocks { double d9 = d5; double d10 = d6; - if(this.uvRotateWest == 1) - { + if (this.uvRotateWest == 1) { d3 = par8Icon.getInterpolatedU(this.renderMinY * 16.0D); d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinX * 16.0D); d4 = par8Icon.getInterpolatedU(this.renderMaxY * 16.0D); @@ -382,9 +376,7 @@ public class CustomRenderBlocks extends RenderBlocks { d8 = d4; d5 = d6; d6 = d9; - } - else if(this.uvRotateWest == 2) - { + } else if (this.uvRotateWest == 2) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMaxY * 16.0D); d5 = par8Icon.getInterpolatedV(this.renderMinX * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMinY * 16.0D); @@ -395,9 +387,7 @@ public class CustomRenderBlocks extends RenderBlocks { d4 = d8; d9 = d6; d10 = d5; - } - else if(this.uvRotateWest == 3) - { + } else if (this.uvRotateWest == 3) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMinX * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMaxX * 16.0D); d5 = par8Icon.getInterpolatedV(this.renderMaxY * 16.0D); @@ -416,7 +406,7 @@ public class CustomRenderBlocks extends RenderBlocks { List result = new ArrayList(); Vertex v; - if(enableAO) { + if (enableAO) { result.add(new Vertex(d11, d14, d15, d3, d5, brightnessTopLeft, colorRedTopLeft, this.colorGreenTopLeft, this.colorBlueTopLeft, 1)); result.add(new Vertex(d11, d13, d15, d8, d10, brightnessBottomLeft, this.colorRedBottomLeft, this.colorGreenBottomLeft, this.colorBlueBottomLeft, 1)); result.add(new Vertex(d12, d13, d15, d4, d6, brightnessBottomRight, colorRedBottomRight, this.colorGreenBottomRight, this.colorBlueBottomRight, 1)); @@ -432,8 +422,7 @@ public class CustomRenderBlocks extends RenderBlocks { private List calcFaceZNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - if(this.hasOverrideBlockTexture()) - { + if (this.hasOverrideBlockTexture()) { par8Icon = this.overrideBlockTexture; } @@ -443,18 +432,18 @@ public class CustomRenderBlocks extends RenderBlocks { double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); double d7; - if(this.flipTexture) { + if (this.flipTexture) { d7 = d3; d3 = d4; d4 = d7; } - if(this.renderMinX < 0.0D || this.renderMaxX > 1.0D) { + if (this.renderMinX < 0.0D || this.renderMaxX > 1.0D) { d3 = par8Icon.getMinU(); d4 = par8Icon.getMaxU(); } - if(this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { + if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { d5 = par8Icon.getMinV(); d6 = par8Icon.getMaxV(); } @@ -464,7 +453,7 @@ public class CustomRenderBlocks extends RenderBlocks { double d9 = d5; double d10 = d6; - if(this.uvRotateEast == 2) { + if (this.uvRotateEast == 2) { d3 = par8Icon.getInterpolatedU(this.renderMinY * 16.0D); d5 = par8Icon.getInterpolatedV(16.0D - this.renderMinX * 16.0D); d4 = par8Icon.getInterpolatedU(this.renderMaxY * 16.0D); @@ -475,7 +464,7 @@ public class CustomRenderBlocks extends RenderBlocks { d8 = d4; d5 = d6; d6 = d9; - } else if(this.uvRotateEast == 1) { + } else if (this.uvRotateEast == 1) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMaxY * 16.0D); d5 = par8Icon.getInterpolatedV(this.renderMaxX * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMinY * 16.0D); @@ -486,7 +475,7 @@ public class CustomRenderBlocks extends RenderBlocks { d4 = d8; d9 = d6; d10 = d5; - } else if(this.uvRotateEast == 3) { + } else if (this.uvRotateEast == 3) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMinX * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMaxX * 16.0D); d5 = par8Icon.getInterpolatedV(this.renderMaxY * 16.0D); @@ -505,7 +494,7 @@ public class CustomRenderBlocks extends RenderBlocks { List result = new ArrayList(); Vertex v; - if(enableAO) { + if (enableAO) { result.add(new Vertex(d11, d14, d15, d7, d9, brightnessTopLeft, colorRedTopLeft, this.colorGreenTopLeft, this.colorBlueTopLeft, 1)); result.add(new Vertex(d12, d14, d15, d3, d5, brightnessBottomLeft, colorRedBottomLeft, this.colorGreenBottomLeft, this.colorBlueBottomLeft, 1)); result.add(new Vertex(d12, d13, d15, d8, d10, brightnessBottomRight, colorRedBottomRight, this.colorGreenBottomRight, this.colorBlueBottomRight, 1)); @@ -519,12 +508,10 @@ public class CustomRenderBlocks extends RenderBlocks { return result; } - private List calcFaceXPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) - { + private List calcFaceXPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { Tessellator tessellator = Tessellator.instance; - if(this.hasOverrideBlockTexture()) - { + if (this.hasOverrideBlockTexture()) { par8Icon = this.overrideBlockTexture; } @@ -534,21 +521,18 @@ public class CustomRenderBlocks extends RenderBlocks { double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); double d7; - if(this.flipTexture) - { + if (this.flipTexture) { d7 = d3; d3 = d4; d4 = d7; } - if(this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) - { + if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { d3 = par8Icon.getMinU(); d4 = par8Icon.getMaxU(); } - if(this.renderMinY < 0.0D || this.renderMaxY > 1.0D) - { + if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { d5 = par8Icon.getMinV(); d6 = par8Icon.getMaxV(); } @@ -558,8 +542,7 @@ public class CustomRenderBlocks extends RenderBlocks { double d9 = d5; double d10 = d6; - if(this.uvRotateSouth == 2) - { + if (this.uvRotateSouth == 2) { d3 = par8Icon.getInterpolatedU(this.renderMinY * 16.0D); d5 = par8Icon.getInterpolatedV(16.0D - this.renderMinZ * 16.0D); d4 = par8Icon.getInterpolatedU(this.renderMaxY * 16.0D); @@ -570,9 +553,7 @@ public class CustomRenderBlocks extends RenderBlocks { d8 = d4; d5 = d6; d6 = d9; - } - else if(this.uvRotateSouth == 1) - { + } else if (this.uvRotateSouth == 1) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMaxY * 16.0D); d5 = par8Icon.getInterpolatedV(this.renderMaxZ * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMinY * 16.0D); @@ -583,9 +564,7 @@ public class CustomRenderBlocks extends RenderBlocks { d4 = d8; d9 = d6; d10 = d5; - } - else if(this.uvRotateSouth == 3) - { + } else if (this.uvRotateSouth == 3) { d3 = par8Icon.getInterpolatedU(16.0D - this.renderMinZ * 16.0D); d4 = par8Icon.getInterpolatedU(16.0D - this.renderMaxZ * 16.0D); d5 = par8Icon.getInterpolatedV(this.renderMaxY * 16.0D); @@ -604,7 +583,7 @@ public class CustomRenderBlocks extends RenderBlocks { List result = new ArrayList(4); Vertex v; - if(enableAO) { + if (enableAO) { result.add(new Vertex(d11, d12, d15, d8, d10, brightnessTopLeft, colorRedTopLeft, this.colorGreenTopLeft, this.colorBlueTopLeft, 1)); result.add(new Vertex(d11, d12, d14, d4, d6, brightnessBottomLeft, colorRedBottomLeft, this.colorGreenBottomLeft, this.colorBlueBottomLeft, 1)); result.add(new Vertex(d11, d13, d14, d7, d9, brightnessBottomRight, colorRedBottomRight, this.colorGreenBottomRight, this.colorBlueBottomRight, 1)); @@ -620,7 +599,7 @@ public class CustomRenderBlocks extends RenderBlocks { private List calcFaceYNeg(Block par1Block, double x, double y, double z, IIcon icon) { - if(hasOverrideBlockTexture()) { + if (hasOverrideBlockTexture()) { icon = this.overrideBlockTexture; } @@ -629,12 +608,12 @@ public class CustomRenderBlocks extends RenderBlocks { double minV = icon.getInterpolatedV(this.renderMinZ * 16.0D); double maxV = icon.getInterpolatedV(this.renderMaxZ * 16.0D); - if(renderMinX < 0.0D || renderMaxX > 1.0D) { + if (renderMinX < 0.0D || renderMaxX > 1.0D) { minU = icon.getMinU(); maxU = icon.getMaxU(); } - if(this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { + if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { minV = icon.getMinV(); maxV = icon.getMaxV(); } @@ -644,7 +623,7 @@ public class CustomRenderBlocks extends RenderBlocks { double d9 = minV; double d10 = maxV; - if(uvRotateBottom == 2) { + if (uvRotateBottom == 2) { minU = icon.getInterpolatedU(this.renderMinZ * 16.0D); minV = icon.getInterpolatedV(16.0D - this.renderMaxX * 16.0D); maxU = icon.getInterpolatedU(this.renderMaxZ * 16.0D); @@ -655,7 +634,7 @@ public class CustomRenderBlocks extends RenderBlocks { d8 = maxU; minV = maxV; maxV = d9; - } else if(uvRotateBottom == 1) { + } else if (uvRotateBottom == 1) { minU = icon.getInterpolatedU(16.0D - this.renderMaxZ * 16.0D); minV = icon.getInterpolatedV(this.renderMinX * 16.0D); @@ -667,7 +646,7 @@ public class CustomRenderBlocks extends RenderBlocks { maxU = d8; d9 = maxV; d10 = minV; - } else if(uvRotateBottom == 3) { + } else if (uvRotateBottom == 3) { minU = icon.getInterpolatedU(16.0D - this.renderMinX * 16.0D); maxU = icon.getInterpolatedU(16.0D - this.renderMaxX * 16.0D); minV = icon.getInterpolatedV(16.0D - this.renderMinZ * 16.0D); @@ -686,7 +665,7 @@ public class CustomRenderBlocks extends RenderBlocks { List result = new ArrayList(4); Vertex v; - if(this.enableAO) { + if (this.enableAO) { v = new Vertex(minX, minY, maxZ, d8, d10, brightnessTopLeft, colorRedTopLeft, colorGreenTopLeft, colorBlueTopLeft, 1f); result.add(v); v = new Vertex(minX, minY, minZ, minU, minV, brightnessBottomLeft, colorRedBottomLeft, colorGreenBottomLeft, colorBlueBottomLeft, 1f); diff --git a/src/main/java/com/enderio/core/client/render/CustomWidgetIcon.java b/src/main/java/com/enderio/core/client/render/CustomWidgetIcon.java index 5071103..36eec09 100644 --- a/src/main/java/com/enderio/core/client/render/CustomWidgetIcon.java +++ b/src/main/java/com/enderio/core/client/render/CustomWidgetIcon.java @@ -14,7 +14,7 @@ public class CustomWidgetIcon implements IWidgetIcon { private final int x, y, width, height; private final IWidgetMap map; - + private IWidgetIcon overlay; } diff --git a/src/main/java/com/enderio/core/client/render/DirectionalModelRenderer.java b/src/main/java/com/enderio/core/client/render/DirectionalModelRenderer.java index e2b7457..2d98999 100644 --- a/src/main/java/com/enderio/core/client/render/DirectionalModelRenderer.java +++ b/src/main/java/com/enderio/core/client/render/DirectionalModelRenderer.java @@ -19,140 +19,122 @@ import com.enderio.core.common.util.ItemUtil; * * @author Garrett Spicer-Davis */ -public class DirectionalModelRenderer extends TileEntitySpecialRenderer implements IItemRenderer -{ - private IModelCustom model; - private ResourceLocation texture; - private IEnderModel modelSMT; +public class DirectionalModelRenderer extends TileEntitySpecialRenderer implements IItemRenderer { + private IModelCustom model; + private ResourceLocation texture; + private IEnderModel modelSMT; - public DirectionalModelRenderer(ResourceLocation model, ResourceLocation texture) - { - this.model = AdvancedModelLoader.loadModel(model); - this.texture = texture; + public DirectionalModelRenderer(ResourceLocation model, ResourceLocation texture) { + this.model = AdvancedModelLoader.loadModel(model); + this.texture = texture; + } + + public DirectionalModelRenderer(IEnderModel model, ResourceLocation texture) { + this.modelSMT = model; + this.texture = texture; + } + + private void renderDirectionalTileEntityAt(T tile, double x, double y, double z, int metaOverride) { + int meta = getMetadata(tile, metaOverride); + setup(x, y, z, metaOverride); + rotate(getRotation(tile, metaOverride)); + renderModel(tile, meta); + } + + protected final int getMetadata(T tile, int metaOverride) { + return metaOverride >= 0 ? metaOverride : tile.getBlockMetadata(); + } + + protected void setup(double x, double y, double z, int metaOverride) { + GL11.glPushMatrix(); + GL11.glTranslatef((float) x + 0.5f, (float) y - (metaOverride >= 0 ? 0.1f : 0), (float) z + 0.5f); + Minecraft.getMinecraft().getTextureManager().bindTexture(texture); + } + + protected int getRotation(T tile, int metaOverride) { + return getMetadata(tile, metaOverride); + } + + protected void rotate(int rotation) { + switch (rotation) { + case 1: + GL11.glRotatef(180f, 0, 0, 1); + GL11.glTranslatef(0, -1f, 0); + break; + case 2: + GL11.glRotatef(90f, 1f, 0, 0); + GL11.glTranslatef(0, -0.5f, -0.5f); + break; + case 3: + GL11.glRotatef(90f, -1f, 0, 0); + GL11.glTranslatef(0, -0.5f, 0.5f); + break; + case 4: + GL11.glRotatef(90f, 0, 0, -1f); + GL11.glTranslatef(-0.5f, -0.5f, 0); + break; + case 5: + GL11.glRotatef(90f, 0, 0, 1f); + GL11.glTranslatef(0.5f, -0.5f, 0); + break; + } + } + + protected void renderModel(T tile, int meta) { + if (model != null) { + GL11.glScalef(0.5f, 0.5f, 0.5f); + model.renderAll(); + } else { + GL11.glTranslated(0, -0.5, 0); + modelSMT.render(0.0625f); } - public DirectionalModelRenderer(IEnderModel model, ResourceLocation texture) - { - this.modelSMT = model; - this.texture = texture; + GL11.glPopMatrix(); + } + + @SuppressWarnings("unchecked") + @Override + public void renderTileEntityAt(TileEntity tile, double x, double y, double z, float yaw) { + renderDirectionalTileEntityAt((T) tile, x, y, z, -1); + } + + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return true; + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return helper == ItemRendererHelper.INVENTORY_BLOCK || helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + GL11.glPushMatrix(); + + switch (type) { + case ENTITY: + GL11.glTranslatef(-0.4f, 0.1f, -0.4f); + GL11.glScalef(0.75f, 0.75f, 0.75f); + break; + case EQUIPPED: + GL11.glScalef(0.75f, 0.75f, 0.75f); + GL11.glTranslatef(-0.1f, 0.2f, 0.5f); + GL11.glRotatef(-40, 1, 0, 0); + GL11.glRotatef(45, 0, 1, 0); + GL11.glRotatef(20, 0, 0, 1); + break; + case EQUIPPED_FIRST_PERSON: + GL11.glScalef(0.75f, 0.75f, 0.75f); + break; + case FIRST_PERSON_MAP: + break; + case INVENTORY: + break; } - private void renderDirectionalTileEntityAt(T tile, double x, double y, double z, int metaOverride) - { - int meta = getMetadata(tile, metaOverride); - setup(x, y, z, metaOverride); - rotate(getRotation(tile, metaOverride)); - renderModel(tile, meta); - } + renderDirectionalTileEntityAt(null, 0, 0, 0, ItemUtil.getNBTTag(item).getInteger("storedMetaData")); - protected final int getMetadata(T tile, int metaOverride) - { - return metaOverride >= 0 ? metaOverride : tile.getBlockMetadata(); - } - - protected void setup(double x, double y, double z, int metaOverride) - { - GL11.glPushMatrix(); - GL11.glTranslatef((float) x + 0.5f, (float) y - (metaOverride >= 0 ? 0.1f : 0), (float) z + 0.5f); - Minecraft.getMinecraft().getTextureManager().bindTexture(texture); - } - - protected int getRotation(T tile, int metaOverride) - { - return getMetadata(tile, metaOverride); - } - - protected void rotate(int rotation) - { - switch (rotation) - { - case 1: - GL11.glRotatef(180f, 0, 0, 1); - GL11.glTranslatef(0, -1f, 0); - break; - case 2: - GL11.glRotatef(90f, 1f, 0, 0); - GL11.glTranslatef(0, -0.5f, -0.5f); - break; - case 3: - GL11.glRotatef(90f, -1f, 0, 0); - GL11.glTranslatef(0, -0.5f, 0.5f); - break; - case 4: - GL11.glRotatef(90f, 0, 0, -1f); - GL11.glTranslatef(-0.5f, -0.5f, 0); - break; - case 5: - GL11.glRotatef(90f, 0, 0, 1f); - GL11.glTranslatef(0.5f, -0.5f, 0); - break; - } - } - - protected void renderModel(T tile, int meta) - { - if (model != null) - { - GL11.glScalef(0.5f, 0.5f, 0.5f); - model.renderAll(); - } - else - { - GL11.glTranslated(0, -0.5, 0); - modelSMT.render(0.0625f); - } - - GL11.glPopMatrix(); - } - - @SuppressWarnings("unchecked") - @Override - public void renderTileEntityAt(TileEntity tile, double x, double y, double z, float yaw) - { - renderDirectionalTileEntityAt((T) tile, x, y, z, -1); - } - - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) - { - return true; - } - - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) - { - return helper == ItemRendererHelper.INVENTORY_BLOCK || helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; - } - - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) - { - GL11.glPushMatrix(); - - switch (type) - { - case ENTITY: - GL11.glTranslatef(-0.4f, 0.1f, -0.4f); - GL11.glScalef(0.75f, 0.75f, 0.75f); - break; - case EQUIPPED: - GL11.glScalef(0.75f, 0.75f, 0.75f); - GL11.glTranslatef(-0.1f, 0.2f, 0.5f); - GL11.glRotatef(-40, 1, 0, 0); - GL11.glRotatef(45, 0, 1, 0); - GL11.glRotatef(20, 0, 0, 1); - break; - case EQUIPPED_FIRST_PERSON: - GL11.glScalef(0.75f, 0.75f, 0.75f); - break; - case FIRST_PERSON_MAP: - break; - case INVENTORY: - break; - } - - renderDirectionalTileEntityAt(null, 0, 0, 0, ItemUtil.getNBTTag(item).getInteger("storedMetaData")); - - GL11.glPopMatrix(); - } + GL11.glPopMatrix(); + } } diff --git a/src/main/java/com/enderio/core/client/render/EnderWidget.java b/src/main/java/com/enderio/core/client/render/EnderWidget.java index b6b4c90..53b6ef7 100644 --- a/src/main/java/com/enderio/core/client/render/EnderWidget.java +++ b/src/main/java/com/enderio/core/client/render/EnderWidget.java @@ -33,7 +33,7 @@ public enum EnderWidget implements IWidgetIcon { BUTTON_DOWN(48, 208), BUTTON_DOWN_HIGHLIGHT(64, 208), BUTTON_CHECKED(112, 208), - + LEFT_ARROW(224, 32, 8, 16), LEFT_ARROW_PRESSED(240, 32, 8, 16), LEFT_ARROW_HOVER(224, 48, 8, 16), diff --git a/src/main/java/com/enderio/core/client/render/IconUtil.java b/src/main/java/com/enderio/core/client/render/IconUtil.java index 906050c..e7a9522 100644 --- a/src/main/java/com/enderio/core/client/render/IconUtil.java +++ b/src/main/java/com/enderio/core/client/render/IconUtil.java @@ -52,7 +52,7 @@ public class IconUtil { @SubscribeEvent public void onIconLoad(TextureStitchEvent.Pre event) { for (IIconProvider reg : iconProviders) { - if(reg.getTextureType() == event.map.getTextureType()) { + if (reg.getTextureType() == event.map.getTextureType()) { reg.registerIcons(event.map); } } @@ -60,7 +60,7 @@ public class IconUtil { public static IIcon getIconForItem(int itemId, int meta) { Item item = Item.getItemById(itemId); - if(item == null) { + if (item == null) { return null; } return item.getIconFromDamage(meta); diff --git a/src/main/java/com/enderio/core/client/render/TechneModelRenderer.java b/src/main/java/com/enderio/core/client/render/TechneModelRenderer.java index 8f2cb4b..8fe69ba 100644 --- a/src/main/java/com/enderio/core/client/render/TechneModelRenderer.java +++ b/src/main/java/com/enderio/core/client/render/TechneModelRenderer.java @@ -19,7 +19,7 @@ public class TechneModelRenderer implements ISimpleBlockRenderingHandler { private int renderId; protected VertexTransform vt; - + public TechneModelRenderer(String modid, String modelPath, int renderId) { this(modid, modelPath, renderId, null); } @@ -27,7 +27,7 @@ public class TechneModelRenderer implements ISimpleBlockRenderingHandler { public TechneModelRenderer(String modid, String modelPath, int renderId, VertexTransform vt) { this(TechneUtil.getModel(modid, modelPath), renderId, vt); } - + public TechneModelRenderer(Map model, int renderId) { this(model, renderId, null); } @@ -57,7 +57,7 @@ public class TechneModelRenderer implements ISimpleBlockRenderingHandler { TechneUtil.vt = this.vt; return TechneUtil.renderWorldBlock(getModel(world, x, y, z), getModelIcon(world, x, y, z, block), world, x, y, z, block, renderer); } - + protected IIcon getModelIcon(Block block, int metadata) { return block.getIcon(0, metadata); } @@ -65,7 +65,7 @@ public class TechneModelRenderer implements ISimpleBlockRenderingHandler { protected IIcon getModelIcon(IBlockAccess world, int x, int y, int z, Block block) { return block.getIcon(world, x, y, z, 0); } - + @Override public boolean shouldRender3DInInventory(int modelId) { return true; diff --git a/src/main/java/com/enderio/core/client/render/TechneUtil.java b/src/main/java/com/enderio/core/client/render/TechneUtil.java index 12651b3..5c28d76 100644 --- a/src/main/java/com/enderio/core/client/render/TechneUtil.java +++ b/src/main/java/com/enderio/core/client/render/TechneUtil.java @@ -112,8 +112,7 @@ public class TechneUtil { * ModelRenderer.render */ @SuppressWarnings("unchecked") - public static List bakeModel(ModelRenderer model, TechneModel supermodel, float scale, Matrix4f matrix, - boolean rotateYFirst) { + public static List bakeModel(ModelRenderer model, TechneModel supermodel, float scale, Matrix4f matrix, boolean rotateYFirst) { // Correction for the fact that TechneModel sets the texture size on the // ModelRenderer after the texture positions have been calculated. It also @@ -129,13 +128,13 @@ public class TechneUtil { m.translate(new Vector3f(model.offsetX + model.rotationPointX * scale, model.offsetY + model.rotationPointY * scale, model.offsetZ + model.rotationPointZ * scale)); - if(!rotateYFirst) { + if (!rotateYFirst) { m.rotate(model.rotateAngleZ, new Vector3f(0, 0, 1)); } m.rotate(model.rotateAngleY, new Vector3f(0, 1, 0)); m.rotate(model.rotateAngleX, new Vector3f(1, 0, 0)); - if(rotateYFirst) { + if (rotateYFirst) { m.rotate(model.rotateAngleZ, new Vector3f(0, 0, 1)); } @@ -235,7 +234,7 @@ public class TechneUtil { TechneModel tm = (TechneModel) modelLoader.loadInstance(new ResourceLocation(modid.toLowerCase(Locale.US), modelPath + ".tcn")); return TechneUtil.bakeModel(tm, 1f / 16, new Matrix4f().scale(new Vector3f(-1, -1, 1))).values(); } - + public static void renderWithIcon(WavefrontObject model, IIcon icon, Tessellator tes) { renderWithIcon(model.groupObjects, icon, null, tes); } @@ -271,12 +270,12 @@ public class TechneUtil { tes.setNormal(n.x, n.y, n.z); ForgeDirection normal = getNormalFor(n); ForgeDirection right = normal.getRotation(ForgeDirection.DOWN); - if(normal == right) { + if (normal == right) { right = ForgeDirection.EAST; } ForgeDirection down = normal.getRotation(right.getOpposite()); - if(isbrh && world != null && world.getBlock(x, y, z).getLightOpacity() > 0) { + if (isbrh && world != null && world.getBlock(x, y, z).getLightOpacity() > 0) { int bx = x + normal.offsetX; int by = y + normal.offsetY; int bz = z + normal.offsetZ; @@ -288,7 +287,7 @@ public class TechneUtil { Vector3d v = new Vector3d(vert); Vector3d tv = new Vector3d(v); tv.add(0.5, 0, 0.5); - if(vt != null) { + if (vt != null) { vt.apply(v); // TODO BLECH if (vt instanceof VertexRotationFacing) { @@ -303,12 +302,12 @@ public class TechneUtil { } } - if(isbrh) { + if (isbrh) { int c = (int) (0xFF * RenderUtil.getColorMultiplierForFace(normal)); tes.setColorOpaque(c, c, c); } - if(override != null) { + if (override != null) { double interpX = Math.abs(tv.x * right.offsetX + tv.y * right.offsetY + tv.z * right.offsetZ); double interpY = Math.abs(tv.x * down.offsetX + tv.y * down.offsetY + tv.z * down.offsetZ); @@ -321,10 +320,10 @@ public class TechneUtil { interpY--; } - if(normal == ForgeDirection.SOUTH || normal == ForgeDirection.WEST) { + if (normal == ForgeDirection.SOUTH || normal == ForgeDirection.WEST) { interpX = 1 - interpX; } - if(normal != ForgeDirection.UP && normal != ForgeDirection.DOWN) { + if (normal != ForgeDirection.UP && normal != ForgeDirection.DOWN) { interpY = 1 - interpY; } tes.addVertexWithUV(v.x, v.y, v.z, override.getInterpolatedU(interpX * 16), override.getInterpolatedV(interpY * 16)); @@ -347,9 +346,9 @@ public class TechneUtil { } private static ForgeDirection getNormalFor(Vertex n) { - if(n.x != 0) { + if (n.x != 0) { return n.x > 0 ? ForgeDirection.EAST : ForgeDirection.WEST; - } else if(n.y != 0) { + } else if (n.y != 0) { return n.y > 0 ? ForgeDirection.UP : ForgeDirection.DOWN; } else { return n.z > 0 ? ForgeDirection.SOUTH : ForgeDirection.NORTH; diff --git a/src/main/java/com/enderio/core/client/render/VertexRotation.java b/src/main/java/com/enderio/core/client/render/VertexRotation.java index 5e5f9bd..e8d35eb 100644 --- a/src/main/java/com/enderio/core/client/render/VertexRotation.java +++ b/src/main/java/com/enderio/core/client/render/VertexRotation.java @@ -36,7 +36,7 @@ public class VertexRotation implements VertexTransform { this.angle = angle; quat = Quat4d.makeRotate(angle, axis); } - + public double getAngle() { return angle; } diff --git a/src/main/java/com/enderio/core/client/render/VertexRotationFacing.java b/src/main/java/com/enderio/core/client/render/VertexRotationFacing.java index f33301e..93b15d9 100644 --- a/src/main/java/com/enderio/core/client/render/VertexRotationFacing.java +++ b/src/main/java/com/enderio/core/client/render/VertexRotationFacing.java @@ -16,27 +16,27 @@ public class VertexRotationFacing extends VertexRotation { } public void setRotation(ForgeDirection dir) { - if(dir == defaultDir) { + if (dir == defaultDir) { setAngle(0); - } else if(dir == defaultDir.getOpposite()) { + } else if (dir == defaultDir.getOpposite()) { setAngle(ROTATION_AMOUNT * 2); - } else if(dir == defaultDir.getRotation(ForgeDirection.DOWN)) { + } else if (dir == defaultDir.getRotation(ForgeDirection.DOWN)) { setAngle(ROTATION_AMOUNT); } else { setAngle(ROTATION_AMOUNT * 3); } } - + public ForgeDirection rotate(ForgeDirection dir) { if (dir.offsetY != 0) { return dir; } if (getAngle() == ROTATION_AMOUNT) { return dir.getRotation(ForgeDirection.DOWN); - } + } if (getAngle() == ROTATION_AMOUNT * 2) { return dir.getOpposite(); - } + } if (getAngle() == ROTATION_AMOUNT * 3) { return dir.getRotation(ForgeDirection.UP); } diff --git a/src/main/java/com/enderio/core/client/sound/BlockSound.java b/src/main/java/com/enderio/core/client/sound/BlockSound.java index 5785005..68a7d60 100644 --- a/src/main/java/com/enderio/core/client/sound/BlockSound.java +++ b/src/main/java/com/enderio/core/client/sound/BlockSound.java @@ -8,46 +8,39 @@ import net.minecraft.client.audio.PositionedSound; import net.minecraft.util.ResourceLocation; @Accessors(chain = true) -public class BlockSound extends PositionedSound implements ITickableSound -{ - @Getter - @Setter - private boolean donePlaying = false; +public class BlockSound extends PositionedSound implements ITickableSound { + @Getter + @Setter + private boolean donePlaying = false; - public BlockSound(ResourceLocation p_i45103_1_) - { - super(p_i45103_1_); - } + public BlockSound(ResourceLocation p_i45103_1_) { + super(p_i45103_1_); + } - public BlockSound setVolume(float vol) - { - this.volume = vol; - return this; - } + public BlockSound setVolume(float vol) { + this.volume = vol; + return this; + } - public BlockSound setPitch(float pitch) - { - this.field_147663_c = pitch; - return this; - } + public BlockSound setPitch(float pitch) { + this.field_147663_c = pitch; + return this; + } - public BlockSound setLocation(float x, float y, float z) - { - this.xPosF = x; - this.yPosF = y; - this.zPosF = z; - return this; - } + public BlockSound setLocation(float x, float y, float z) { + this.xPosF = x; + this.yPosF = y; + this.zPosF = z; + return this; + } - public BlockSound setDoRepeat(boolean bool) - { - this.repeat = bool; - return this; - } + public BlockSound setDoRepeat(boolean bool) { + this.repeat = bool; + return this; + } - @Override - public void update() - { - ; - } + @Override + public void update() { + ; + } } diff --git a/src/main/java/com/enderio/core/common/CommonProxy.java b/src/main/java/com/enderio/core/common/CommonProxy.java index 2bb7241..12124cc 100644 --- a/src/main/java/com/enderio/core/common/CommonProxy.java +++ b/src/main/java/com/enderio/core/common/CommonProxy.java @@ -21,10 +21,10 @@ public class CommonProxy { return null; } - public void throwModCompatibilityError(String ... msgs) { + public void throwModCompatibilityError(String... msgs) { StringBuilder sb = new StringBuilder(); - for(String msg : msgs) { - if(sb.length() > 0) { + for (String msg : msgs) { + if (sb.length() > 0) { sb.append("\n"); } sb.append(msg); diff --git a/src/main/java/com/enderio/core/common/OreDict.java b/src/main/java/com/enderio/core/common/OreDict.java index 84c34be..327deaf 100644 --- a/src/main/java/com/enderio/core/common/OreDict.java +++ b/src/main/java/com/enderio/core/common/OreDict.java @@ -11,72 +11,64 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; @UtilityClass -public class OreDict -{ - public void registerVanilla() - { - safeRegister("barsIron", Blocks.iron_bars); - safeRegister("blockHopper", Blocks.hopper); - safeRegister("blockObsidian", Blocks.obsidian); - safeRegister("itemNetherStar", Items.nether_star); - safeRegister("gravel", Blocks.gravel); - safeRegister("chestWood", Blocks.chest); - safeRegister("craftingTableWood", Blocks.crafting_table); +public class OreDict { + public void registerVanilla() { + safeRegister("barsIron", Blocks.iron_bars); + safeRegister("blockHopper", Blocks.hopper); + safeRegister("blockObsidian", Blocks.obsidian); + safeRegister("itemNetherStar", Items.nether_star); + safeRegister("gravel", Blocks.gravel); + safeRegister("chestWood", Blocks.chest); + safeRegister("craftingTableWood", Blocks.crafting_table); - safeRegister("itemCoal", Items.coal); - safeRegister("itemCharcoal", new ItemStack(Items.coal, 1, 1)); - safeRegister("pearlEnder", Items.ender_pearl); - safeRegister("pearlEnderEye", Items.ender_eye); - safeRegister("itemBlazeRod", Items.blaze_rod); - safeRegister("itemBlazePowder", Items.blaze_powder); - safeRegister("itemClay", Items.clay_ball); - safeRegister("itemFlint", Items.flint); - safeRegister("itemGhastTear", Items.ghast_tear); - safeRegister("dustGunpowder", Items.gunpowder); - safeRegister("itemLeather", Items.leather); + safeRegister("itemCoal", Items.coal); + safeRegister("itemCharcoal", new ItemStack(Items.coal, 1, 1)); + safeRegister("pearlEnder", Items.ender_pearl); + safeRegister("pearlEnderEye", Items.ender_eye); + safeRegister("itemBlazeRod", Items.blaze_rod); + safeRegister("itemBlazePowder", Items.blaze_powder); + safeRegister("itemClay", Items.clay_ball); + safeRegister("itemFlint", Items.flint); + safeRegister("itemGhastTear", Items.ghast_tear); + safeRegister("dustGunpowder", Items.gunpowder); + safeRegister("itemLeather", Items.leather); - safeRegister("slabWoodOak", new ItemStack(Blocks.wooden_slab, 1, 0)); - safeRegister("slabWoodSpruce", new ItemStack(Blocks.wooden_slab, 1, 1)); - safeRegister("slabWoodBirch", new ItemStack(Blocks.wooden_slab, 1, 2)); - safeRegister("slabWoodJungle", new ItemStack(Blocks.wooden_slab, 1, 3)); - safeRegister("slabWoodAcacia", new ItemStack(Blocks.wooden_slab, 1, 4)); - safeRegister("slabWoodDarkOak", new ItemStack(Blocks.wooden_slab, 1, 5)); + safeRegister("slabWoodOak", new ItemStack(Blocks.wooden_slab, 1, 0)); + safeRegister("slabWoodSpruce", new ItemStack(Blocks.wooden_slab, 1, 1)); + safeRegister("slabWoodBirch", new ItemStack(Blocks.wooden_slab, 1, 2)); + safeRegister("slabWoodJungle", new ItemStack(Blocks.wooden_slab, 1, 3)); + safeRegister("slabWoodAcacia", new ItemStack(Blocks.wooden_slab, 1, 4)); + safeRegister("slabWoodDarkOak", new ItemStack(Blocks.wooden_slab, 1, 5)); - safeRegister("slabStone", new ItemStack(Blocks.stone_slab, 1, 0)); - safeRegister("slabSandstone", new ItemStack(Blocks.stone_slab, 1, 1)); - safeRegister("slabCobblestone", new ItemStack(Blocks.stone_slab, 1, 3)); - safeRegister("slabBricks", new ItemStack(Blocks.stone_slab, 1, 4)); - safeRegister("slabStoneBricks", new ItemStack(Blocks.stone_slab, 1, 5)); - safeRegister("slabNetherBrick", new ItemStack(Blocks.stone_slab, 1, 6)); - safeRegister("slabQuartz", new ItemStack(Blocks.stone_slab, 1, 7)); - } - - public void safeRegister(String name, Block block) - { - safeRegister(name, Item.getItemFromBlock(block)); - } - - public void safeRegister(String name, Item item) - { - safeRegister(name, new ItemStack(item)); - } - - public void safeRegister(String name, ItemStack stack) - { - if (!isRegistered(stack, OreDictionary.getOres(name))) - OreDictionary.registerOre(name, stack); - } - - private boolean isRegistered(ItemStack stack, ArrayList toCheck) - { - for (ItemStack check : toCheck) - { - if (stack != null && stack.getItem() == check.getItem() - && (stack.getItemDamage() == check.getItemDamage() || stack.getItemDamage() == OreDictionary.WILDCARD_VALUE)) - { - return true; - } - } - return false; + safeRegister("slabStone", new ItemStack(Blocks.stone_slab, 1, 0)); + safeRegister("slabSandstone", new ItemStack(Blocks.stone_slab, 1, 1)); + safeRegister("slabCobblestone", new ItemStack(Blocks.stone_slab, 1, 3)); + safeRegister("slabBricks", new ItemStack(Blocks.stone_slab, 1, 4)); + safeRegister("slabStoneBricks", new ItemStack(Blocks.stone_slab, 1, 5)); + safeRegister("slabNetherBrick", new ItemStack(Blocks.stone_slab, 1, 6)); + safeRegister("slabQuartz", new ItemStack(Blocks.stone_slab, 1, 7)); + } + + public void safeRegister(String name, Block block) { + safeRegister(name, Item.getItemFromBlock(block)); + } + + public void safeRegister(String name, Item item) { + safeRegister(name, new ItemStack(item)); + } + + public void safeRegister(String name, ItemStack stack) { + if (!isRegistered(stack, OreDictionary.getOres(name))) + OreDictionary.registerOre(name, stack); + } + + private boolean isRegistered(ItemStack stack, ArrayList toCheck) { + for (ItemStack check : toCheck) { + if (stack != null && stack.getItem() == check.getItem() + && (stack.getItemDamage() == check.getItemDamage() || stack.getItemDamage() == OreDictionary.WILDCARD_VALUE)) { + return true; + } } + return false; + } } diff --git a/src/main/java/com/enderio/core/common/TileEntityEnder.java b/src/main/java/com/enderio/core/common/TileEntityEnder.java index e83dab6..3de7629 100644 --- a/src/main/java/com/enderio/core/common/TileEntityEnder.java +++ b/src/main/java/com/enderio/core/common/TileEntityEnder.java @@ -101,7 +101,7 @@ public abstract class TileEntityEnder extends TileEntity { public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { readCustomNBT(pkt.func_148857_g()); } - + public boolean canPlayerAccess(EntityPlayer player) { return !isInvalid() && player.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64D; } diff --git a/src/main/java/com/enderio/core/common/command/CommandReloadConfigs.java b/src/main/java/com/enderio/core/common/command/CommandReloadConfigs.java index 2b7d64d..e5c01f7 100644 --- a/src/main/java/com/enderio/core/common/command/CommandReloadConfigs.java +++ b/src/main/java/com/enderio/core/common/command/CommandReloadConfigs.java @@ -20,112 +20,90 @@ import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.relauncher.Side; @AllArgsConstructor(access = AccessLevel.PRIVATE) -public class CommandReloadConfigs extends CommandBase -{ - public static final CommandReloadConfigs SERVER = new CommandReloadConfigs(Side.SERVER); - public static final CommandReloadConfigs CLIENT = new CommandReloadConfigs(Side.CLIENT); +public class CommandReloadConfigs extends CommandBase { + public static final CommandReloadConfigs SERVER = new CommandReloadConfigs(Side.SERVER); + public static final CommandReloadConfigs CLIENT = new CommandReloadConfigs(Side.CLIENT); - private static List validModIDs = new ArrayList(); - - private final Side side; + private static List validModIDs = new ArrayList(); - static - { - EnderCore.logger.info("Sending dummy event to all mods"); + private final Side side; - for (ModContainer mod : Loader.instance().getActiveModList()) - { - ConfigFileChangedEvent event = new ConfigFileChangedEvent(mod.getModId()); - FMLCommonHandler.instance().bus().post(event); + static { + EnderCore.logger.info("Sending dummy event to all mods"); - if (event.isSuccessful()) - { - validModIDs.add(mod.getModId()); - } - } + for (ModContainer mod : Loader.instance().getActiveModList()) { + ConfigFileChangedEvent event = new ConfigFileChangedEvent(mod.getModId()); + FMLCommonHandler.instance().bus().post(event); + + if (event.isSuccessful()) { + validModIDs.add(mod.getModId()); + } + } + } + + @Override + public String getCommandName() { + return side == Side.SERVER ? "reloadServerConfigs" : "reloadConfigs"; + } + + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/" + getCommandName() + " ( ...)"; + } + + @Override + public int getRequiredPermissionLevel() { + return 2; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender player) { + return player.getEntityWorld().isRemote || super.canCommandSenderUseCommand(player); + } + + @SuppressWarnings("rawtypes") + @Override + public List addTabCompletionOptions(ICommandSender player, String[] args) { + if (args.length >= 1) { + String[] avail = validModIDs.toArray(new String[validModIDs.size()]); + + for (int i = 0; i < args.length - 1; i++) { + avail = ArrayUtils.removeElement(avail, args[i]); + } + + return getListOfStringsMatchingLastWord(args, avail); } - @Override - public String getCommandName() - { - return side == Side.SERVER ? "reloadServerConfigs" : "reloadConfigs"; - } + return null; + } - @Override - public String getCommandUsage(ICommandSender p_71518_1_) - { - return "/" + getCommandName() + " ( ...)"; - } - - @Override - public int getRequiredPermissionLevel() - { - return 2; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender player) - { - return player.getEntityWorld().isRemote || super.canCommandSenderUseCommand(player); - } - - @SuppressWarnings("rawtypes") - @Override - public List addTabCompletionOptions(ICommandSender player, String[] args) - { - if (args.length >= 1) - { - String[] avail = validModIDs.toArray(new String[validModIDs.size()]); - - for (int i = 0; i < args.length - 1; i++) - { - avail = ArrayUtils.removeElement(avail, args[i]); - } - - return getListOfStringsMatchingLastWord(args, avail); + @Override + public void processCommand(ICommandSender player, String[] args) { + if (side == Side.CLIENT == player.getEntityWorld().isRemote) + for (String s : args) { + boolean validModid = false; + for (ModContainer mod : Loader.instance().getModObjectList().keySet()) { + if (mod.getModId().equals(s)) { + validModid = true; + } } - return null; - } + if (validModid) { + ConfigFileChangedEvent event = new ConfigFileChangedEvent(s); + FMLCommonHandler.instance().bus().post(event); - @Override - public void processCommand(ICommandSender player, String[] args) - { - if (side == Side.CLIENT == player.getEntityWorld().isRemote) - for (String s : args) - { - boolean validModid = false; - for (ModContainer mod : Loader.instance().getModObjectList().keySet()) - { - if (mod.getModId().equals(s)) - { - validModid = true; - } - } - - if (validModid) - { - ConfigFileChangedEvent event = new ConfigFileChangedEvent(s); - FMLCommonHandler.instance().bus().post(event); - - if (event.isSuccessful()) - { - sendResult(player, s, "success"); - } - else - { - sendResult(player, s, "fail"); - } - } - else - { - sendResult(player, s, "invalid"); - } + if (event.isSuccessful()) { + sendResult(player, s, "success"); + } else { + sendResult(player, s, "fail"); + } + } else { + sendResult(player, s, "invalid"); } - } + } + } - private void sendResult(ICommandSender player, String modid, String result) - { - player.addChatMessage(new ChatComponentText(EnderCore.lang.localize("command.config.result." + result, modid))); - } + private void sendResult(ICommandSender player, String modid, String result) { + player.addChatMessage(new ChatComponentText(EnderCore.lang.localize("command.config.result." + result, modid))); + } } diff --git a/src/main/java/com/enderio/core/common/command/CommandScoreboardInfo.java b/src/main/java/com/enderio/core/common/command/CommandScoreboardInfo.java index 1a84561..19734e8 100644 --- a/src/main/java/com/enderio/core/common/command/CommandScoreboardInfo.java +++ b/src/main/java/com/enderio/core/common/command/CommandScoreboardInfo.java @@ -13,90 +13,75 @@ import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.scoreboard.Scoreboard; import net.minecraft.util.ChatComponentText; -public class CommandScoreboardInfo extends CommandBase -{ - @Override - public String getCommandName() - { - return "scoreboardinfo"; +public class CommandScoreboardInfo extends CommandBase { + @Override + public String getCommandName() { + return "scoreboardinfo"; + } + + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/scoreboardinfo "; + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender p_71519_1_) { + return true; + } + + @SuppressWarnings("unchecked") + @Override + public void processCommand(ICommandSender player, String[] args) { + if (args.length < 2) { + throw new WrongUsageException("This command requires 2 args: "); } - @Override - public String getCommandUsage(ICommandSender p_71518_1_) - { - return "/scoreboardinfo "; - } - - @Override - public int getRequiredPermissionLevel() - { - return 0; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender p_71519_1_) - { - return true; + Scoreboard board = player.getEntityWorld().getScoreboard(); + + ScoreObjective obj = board.getObjective(args[0]); + + if (obj == null) { + player.addChatMessage(new ChatComponentText("No such board " + args[0])); } - @SuppressWarnings("unchecked") - @Override - public void processCommand(ICommandSender player, String[] args) - { - if (args.length < 2) - { - throw new WrongUsageException("This command requires 2 args: "); - } + Collection collection = board.func_96534_i(obj); - Scoreboard board = player.getEntityWorld().getScoreboard(); - - ScoreObjective obj = board.getObjective(args[0]); - - if (obj == null) - { - player.addChatMessage(new ChatComponentText("No such board " + args[0])); - } - - Collection collection = board.func_96534_i(obj); - - for (Score score : collection) - { - if (score.getPlayerName().equals(args[1])) - { - player.addChatMessage(new ChatComponentText(args[1] + "'s score on board \"" + args[0] + "\": " + score.getScorePoints())); - return; - } - } - - player.addChatMessage(new ChatComponentText("No score for " + args[1] + " on board \"" + args[0] + "\"")); + for (Score score : collection) { + if (score.getPlayerName().equals(args[1])) { + player.addChatMessage(new ChatComponentText(args[1] + "'s score on board \"" + args[0] + "\": " + score.getScorePoints())); + return; + } } - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public List addTabCompletionOptions(ICommandSender player, String[] args) - { - if (args.length == 1) - { - List boards = new ArrayList(); - for (ScoreObjective obj : (Collection) player.getEntityWorld().getScoreboard().getScoreObjectives()) - { - boards.add(obj.getName()); - } - - return getListOfStringsFromIterableMatchingLastWord(args, boards); - } + player.addChatMessage(new ChatComponentText("No score for " + args[1] + " on board \"" + args[0] + "\"")); + } - if (args.length == 2) - { - List players = new ArrayList(); - for (EntityPlayer p : (List) player.getEntityWorld().playerEntities) - { - players.add(p.getCommandSenderName()); - } - - return getListOfStringsFromIterableMatchingLastWord(args, players); - } - - return null; + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public List addTabCompletionOptions(ICommandSender player, String[] args) { + if (args.length == 1) { + List boards = new ArrayList(); + for (ScoreObjective obj : (Collection) player.getEntityWorld().getScoreboard().getScoreObjectives()) { + boards.add(obj.getName()); + } + + return getListOfStringsFromIterableMatchingLastWord(args, boards); } + + if (args.length == 2) { + List players = new ArrayList(); + for (EntityPlayer p : (List) player.getEntityWorld().playerEntities) { + players.add(p.getCommandSenderName()); + } + + return getListOfStringsFromIterableMatchingLastWord(args, players); + } + + return null; + } } diff --git a/src/main/java/com/enderio/core/common/compat/CompatRegistry.java b/src/main/java/com/enderio/core/common/compat/CompatRegistry.java index c13a39b..a071fa6 100644 --- a/src/main/java/com/enderio/core/common/compat/CompatRegistry.java +++ b/src/main/java/com/enderio/core/common/compat/CompatRegistry.java @@ -19,104 +19,81 @@ import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLStateEvent; @NoArgsConstructor(access = AccessLevel.PRIVATE) -public class CompatRegistry -{ - @Value - private static class Registration - { - String[] modids; - RegisterTime[] times; +public class CompatRegistry { + @Value + private static class Registration { + String[] modids; + RegisterTime[] times; - private Registration(RegisterTime time, String... modids) - { - this.modids = modids; - this.times = new RegisterTime[] { time }; - } - - private Registration(RegisterTime[] times, String... modids) - { - this.modids = modids; - this.times = times; - } + private Registration(RegisterTime time, String... modids) { + this.modids = modids; + this.times = new RegisterTime[] { time }; } - public static final CompatRegistry INSTANCE = new CompatRegistry(); - - private Map compatMap = new HashMap(); - - @Getter - private RegisterTime state = null; - - public void registerCompat(RegisterTime time, String clazz, String... modids) - { - compatMap.put(new Registration(time, modids), clazz); + private Registration(RegisterTime[] times, String... modids) { + this.modids = modids; + this.times = times; } + } - public void registerCompat(RegisterTime[] times, String clazz, String... modids) - { - compatMap.put(new Registration(times, modids), clazz); - } + public static final CompatRegistry INSTANCE = new CompatRegistry(); - public void handle(FMLStateEvent event) - { - RegisterTime time = RegisterTime.timeFor(event); - state = time; - for (Registration r : compatMap.keySet()) - { - if (ArrayUtils.contains(r.times, time) && allModsLoaded(r.modids)) - { - doLoad(compatMap.get(r)); - } - } - } + private Map compatMap = new HashMap(); - private boolean allModsLoaded(String[] modids) - { - for (String s : modids) - { - if (!Loader.isModLoaded(s)) - { - return false; - } - } - return true; - } + @Getter + private RegisterTime state = null; - public void forceLoad(String clazz) - { - Iterator iter = compatMap.keySet().iterator(); - while (iter.hasNext()) - { - Registration r = iter.next(); - String s = compatMap.get(r); - if (s.equals(clazz)) - { - doLoad(s); - } - } - } + public void registerCompat(RegisterTime time, String clazz, String... modids) { + compatMap.put(new Registration(time, modids), clazz); + } - private void doLoad(String clazz) - { - try - { - EnderCore.logger.info("[Compat] Loading compatability class " + clazz); - Class compat = Class.forName(clazz); - compat.getDeclaredMethod(ICompat.METHOD_NAME).invoke(null); - } - catch (NoSuchMethodException e) - { - EnderCore.logger.error("[Compat] ICompatability class {} did not contain static method {}!", clazz, ICompat.METHOD_NAME); - e.printStackTrace(); - } - catch (InvocationTargetException e) - { - throw new RuntimeException("Error in compatability class " + clazz, e.getTargetException()); - } - catch (Throwable e) - { - EnderCore.logger.error("[Compat] An unknown error was thrown loading class {}.", clazz); - e.printStackTrace(); - } + public void registerCompat(RegisterTime[] times, String clazz, String... modids) { + compatMap.put(new Registration(times, modids), clazz); + } + + public void handle(FMLStateEvent event) { + RegisterTime time = RegisterTime.timeFor(event); + state = time; + for (Registration r : compatMap.keySet()) { + if (ArrayUtils.contains(r.times, time) && allModsLoaded(r.modids)) { + doLoad(compatMap.get(r)); + } } + } + + private boolean allModsLoaded(String[] modids) { + for (String s : modids) { + if (!Loader.isModLoaded(s)) { + return false; + } + } + return true; + } + + public void forceLoad(String clazz) { + Iterator iter = compatMap.keySet().iterator(); + while (iter.hasNext()) { + Registration r = iter.next(); + String s = compatMap.get(r); + if (s.equals(clazz)) { + doLoad(s); + } + } + } + + private void doLoad(String clazz) { + try { + EnderCore.logger.info("[Compat] Loading compatability class " + clazz); + Class compat = Class.forName(clazz); + compat.getDeclaredMethod(ICompat.METHOD_NAME).invoke(null); + } catch (NoSuchMethodException e) { + EnderCore.logger.error("[Compat] ICompatability class {} did not contain static method {}!", clazz, ICompat.METHOD_NAME); + e.printStackTrace(); + } catch (InvocationTargetException e) { + throw new RuntimeException("Error in compatability class " + clazz, e.getTargetException()); + } catch (Throwable e) { + EnderCore.logger.error("[Compat] An unknown error was thrown loading class {}.", clazz); + e.printStackTrace(); + } + } } diff --git a/src/main/java/com/enderio/core/common/compat/ICompat.java b/src/main/java/com/enderio/core/common/compat/ICompat.java index 6c15597..d6f09df 100644 --- a/src/main/java/com/enderio/core/common/compat/ICompat.java +++ b/src/main/java/com/enderio/core/common/compat/ICompat.java @@ -1,10 +1,9 @@ package com.enderio.core.common.compat; /** - * By implementing this marker interface the class must have a static method by the name of the - * constant contained within this interface + * By implementing this marker interface the class must have a static method by + * the name of the constant contained within this interface */ -public interface ICompat -{ - public static final String METHOD_NAME = "load"; +public interface ICompat { + public static final String METHOD_NAME = "load"; } diff --git a/src/main/java/com/enderio/core/common/config/AbstractConfigHandler.java b/src/main/java/com/enderio/core/common/config/AbstractConfigHandler.java index c013fa0..f9e108f 100644 --- a/src/main/java/com/enderio/core/common/config/AbstractConfigHandler.java +++ b/src/main/java/com/enderio/core/common/config/AbstractConfigHandler.java @@ -23,650 +23,582 @@ import cpw.mods.fml.client.event.ConfigChangedEvent; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; -public abstract class AbstractConfigHandler implements IConfigHandler -{ +public abstract class AbstractConfigHandler implements IConfigHandler { + /** + * Represents a section in a config handler. + */ + public class Section { + public final String name; + public final String lang; + + public Section(String name, String lang) { + this.name = name; + this.lang = "section." + lang; + } + + private Section register() { + sections.add(this); + return this; + } + + public String lc() { + return name.toLowerCase(Locale.US); + } + } + + public enum RestartReqs { /** - * Represents a section in a config handler. + * No restart needed for this config to be applied. Default value. */ - public class Section - { - public final String name; - public final String lang; - - public Section(String name, String lang) - { - this.name = name; - this.lang = "section." + lang; - } - - private Section register() - { - sections.add(this); - return this; - } - - public String lc() - { - return name.toLowerCase(Locale.US); - } - } - - public enum RestartReqs - { - /** - * No restart needed for this config to be applied. Default value. - */ - NONE, - - /** - * This config requires the world to be restarted to take effect. - */ - REQUIRES_WORLD_RESTART, - - /** - * This config requires the game to be restarted to take effect. {@code REQUIRES_WORLD_RESTART} is implied when using this. - */ - REQUIRES_MC_RESTART; - - public Property apply(Property prop) - { - if (this == REQUIRES_MC_RESTART) - { - prop.setRequiresMcRestart(true); - } - else if (this == REQUIRES_WORLD_RESTART) - { - prop.setRequiresWorldRestart(true); - } - return prop; - } - } - - String modid; - Configuration config; - - private List

sections = new ArrayList
(); - private Section activeSection = null; - - protected AbstractConfigHandler(String modid) - { - this.modid = modid; - FMLCommonHandler.instance().bus().register(this); - EnderCore.instance.configs.add(this); - } - - @Override - public final void initialize(File cfg) - { - config = new Configuration(cfg); - init(); - reloadAllConfigs(); - saveConfigFile(); - } - - protected void loadConfigFile() - { - config.load(); - } - - protected void saveConfigFile() - { - config.save(); - } - - @SubscribeEvent - public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) - { - if (event.modID.equals(modid)) - { - EnderCore.logger.info("Reloading all configs for modid: " + modid); - reloadAllConfigs(); - saveConfigFile(); - } - } - - @SubscribeEvent - public void onConfigFileChanged(ConfigFileChangedEvent event) - { - if (event.modID.equals(modid)) - { - EnderCore.logger.info("Reloading ingame configs for modid: " + modid); - loadConfigFile(); - reloadIngameConfigs(); - event.setSuccessful(); - saveConfigFile(); - } - } - - // convenience for reloading all configs - private void reloadAllConfigs() - { - reloadNonIngameConfigs(); - reloadIngameConfigs(); - } + NONE, /** - * Called after config is loaded, but before properties are processed. - *

- * Use this method to add your sections and do other setup. + * This config requires the world to be restarted to take effect. */ - protected abstract void init(); + REQUIRES_WORLD_RESTART, /** - * Refresh all config values that can only be loaded when NOT in-game. - *

- * {@code reloadIngameConfigs()} will be called after this, do not duplicate calls in this method and that one. + * This config requires the game to be restarted to take effect. + * {@code REQUIRES_WORLD_RESTART} is implied when using this. */ - protected abstract void reloadNonIngameConfigs(); + REQUIRES_MC_RESTART; - /** - * Refresh all config values that can only be loaded when in-game. - *

- * This is separated from {@code reloadNonIngameConfigs()} because some values may not be able to be modified at runtime. - */ - protected abstract void reloadIngameConfigs(); + public Property apply(Property prop) { + if (this == REQUIRES_MC_RESTART) { + prop.setRequiresMcRestart(true); + } else if (this == REQUIRES_WORLD_RESTART) { + prop.setRequiresWorldRestart(true); + } + return prop; + } + } - /** - * Adds a section to your config to be used later - * - * @param sectionName - * The name of the section. Will also be used as language key. - * @return A {@link Section} representing your section in the config - */ - protected Section addSection(String sectionName) - { - return addSection(sectionName, sectionName, null); + String modid; + Configuration config; + + private List

sections = new ArrayList
(); + private Section activeSection = null; + + protected AbstractConfigHandler(String modid) { + this.modid = modid; + FMLCommonHandler.instance().bus().register(this); + EnderCore.instance.configs.add(this); + } + + @Override + public final void initialize(File cfg) { + config = new Configuration(cfg); + init(); + reloadAllConfigs(); + saveConfigFile(); + } + + protected void loadConfigFile() { + config.load(); + } + + protected void saveConfigFile() { + config.save(); + } + + @SubscribeEvent + public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { + if (event.modID.equals(modid)) { + EnderCore.logger.info("Reloading all configs for modid: " + modid); + reloadAllConfigs(); + saveConfigFile(); + } + } + + @SubscribeEvent + public void onConfigFileChanged(ConfigFileChangedEvent event) { + if (event.modID.equals(modid)) { + EnderCore.logger.info("Reloading ingame configs for modid: " + modid); + loadConfigFile(); + reloadIngameConfigs(); + event.setSuccessful(); + saveConfigFile(); + } + } + + // convenience for reloading all configs + private void reloadAllConfigs() { + reloadNonIngameConfigs(); + reloadIngameConfigs(); + } + + /** + * Called after config is loaded, but before properties are processed. + *

+ * Use this method to add your sections and do other setup. + */ + protected abstract void init(); + + /** + * Refresh all config values that can only be loaded when NOT in-game. + *

+ * {@code reloadIngameConfigs()} will be called after this, do not duplicate + * calls in this method and that one. + */ + protected abstract void reloadNonIngameConfigs(); + + /** + * Refresh all config values that can only be loaded when in-game. + *

+ * This is separated from {@code reloadNonIngameConfigs()} because some values + * may not be able to be modified at runtime. + */ + protected abstract void reloadIngameConfigs(); + + /** + * Adds a section to your config to be used later + * + * @param sectionName + * The name of the section. Will also be used as language key. + * @return A {@link Section} representing your section in the config + */ + protected Section addSection(String sectionName) { + return addSection(sectionName, sectionName, null); + } + + /** + * Adds a section to your config to be used later + * + * @param sectionName + * The name of the section + * @param langKey + * The language key to use to display your section name in the Config + * GUI + * @return A {@link Section} representing your section in the config + */ + protected Section addSection(String sectionName, String langKey) { + return addSection(sectionName, langKey, null); + } + + /** + * Adds a section to your config to be used later + * + * @param sectionName + * The name of the section + * @param langKey + * The language key to use to display your section name in the Config + * GUI + * @param comment + * The section comment + * @return A {@link Section} representing your section in the config + */ + protected Section addSection(String sectionName, String langKey, String comment) { + Section section = new Section(sectionName, langKey); + + if (activeSection == null && sections.isEmpty()) { + activeSection = section; } - /** - * Adds a section to your config to be used later - * - * @param sectionName - * The name of the section - * @param langKey - * The language key to use to display your section name in the Config GUI - * @return A {@link Section} representing your section in the config - */ - protected Section addSection(String sectionName, String langKey) - { - return addSection(sectionName, langKey, null); + if (comment != null) { + config.addCustomCategoryComment(sectionName, comment); } - /** - * Adds a section to your config to be used later - * - * @param sectionName - * The name of the section - * @param langKey - * The language key to use to display your section name in the Config GUI - * @param comment - * The section comment - * @return A {@link Section} representing your section in the config - */ - protected Section addSection(String sectionName, String langKey, String comment) - { - Section section = new Section(sectionName, langKey); + return section.register(); + } - if (activeSection == null && sections.isEmpty()) - { - activeSection = section; - } + private void checkInitialized() { + if (activeSection == null) { + throw new IllegalStateException("No section is active!"); + } + } - if (comment != null) - { - config.addCustomCategoryComment(sectionName, comment); - } + /** + * Activates a section + * + * @param sectionName + * The name of the section + * + * @throws NullPointerException + * if {@code sectionName} is null + * @throws IllegalArgumentException + * if {@code sectionName} is not valid + */ + protected void activateSection(@NonNull String sectionName) { + Section section = getSectionByName(sectionName); + if (section == null) { + throw new IllegalArgumentException("Section " + sectionName + " does not exist!"); + } + activateSection(section); + } - return section.register(); + /** + * Activates a section + * + * @param section + * The section to activate + * + * @throws NullPointerException + * if {@code section} is null + */ + protected void activateSection(@NonNull Section section) { + activeSection = section; + } + + /** + * Gets a {@link Section} for a name + * + * @param sectionName + * The name of the section + * @return A section object representing the section in your config with this + * name + * + * @throws NullPointerException + * if {@code sectionName} is null + */ + protected Section getSectionByName(@NonNull String sectionName) { + for (Section s : sections) { + if (s.name.equalsIgnoreCase(sectionName)) { + return s; + } + } + return null; + } + + /** + * Gets a value from this config handler + * + * @param key + * Name of the key for this property + * @param defaultVal + * Default value so a new property can be created + * @return The value of the property + * + * @throws IllegalArgumentException + * If defaultVal is not a valid property type + * @throws IllegalStateException + * If there is no active section + */ + protected T getValue(String key, T defaultVal) { + return getValue(key, defaultVal, RestartReqs.NONE); + } + + /** + * Gets a value from this config handler + * + * @param key + * Name of the key for this property + * @param defaultVal + * Default value so a new property can be created + * @param req + * Restart requirement of the property to be created + * @return The value of the property + * + * @throws IllegalArgumentException + * If defaultVal is not a valid property type + * @throws IllegalStateException + * If there is no active section + */ + protected T getValue(String key, T defaultVal, RestartReqs req) { + return getValue(key, null, defaultVal, req); + } + + /** + * Gets a value from this config handler + * + * @param key + * Name of the key for this property + * @param defaultVal + * Default value so a new property can be created + * @param bound + * The bounds to set on this property + * @return The value of the property + * + * @throws IllegalArgumentException + * If defaultVal is not a valid property type + * @throws IllegalStateException + * If there is no active section + */ + protected T getValue(String key, T defaultVal, Bound bound) { + return getValue(key, null, defaultVal, bound); + } + + /** + * Gets a value from this config handler + * + * @param key + * Name of the key for this property + * @param comment + * The comment to put on this property + * @param defaultVal + * Default value so a new property can be created + * @return The value of the property + * + * @throws IllegalArgumentException + * if defaultVal is not a valid property type + * @throws IllegalStateException + * if there is no active section + */ + protected T getValue(String key, String comment, T defaultVal) { + return getValue(key, comment, defaultVal, RestartReqs.NONE); + } + + /** + * Gets a value from this config handler + * + * @param key + * Name of the key for this property + * @param comment + * The comment to put on this property + * @param defaultVal + * Default value so a new property can be created + * @param req + * Restart requirement of the property to be created + * @return The value of the property + * + * @throws IllegalArgumentException + * if defaultVal is not a valid property type + * @throws IllegalStateException + * if there is no active section + */ + protected T getValue(String key, String comment, T defaultVal, RestartReqs req) { + return getValue(key, comment, defaultVal, req, null); + } + + /** + * Gets a value from this config handler + * + * @param key + * Name of the key for this property + * @param comment + * The comment to put on this property + * @param defaultVal + * Default value so a new property can be created + * @param bound + * The bounds to set on this property + * @return The value of the property + * + * @throws IllegalArgumentException + * if defaultVal is not a valid property type + * @throws IllegalStateException + * if there is no active section + */ + protected T getValue(String key, String comment, T defaultVal, Bound bound) { + return getValue(key, comment, defaultVal, RestartReqs.NONE, bound); + } + + /** + * Gets a value from this config handler + * + * @param key + * Name of the key for this property + * @param comment + * The comment to put on this property + * @param defaultVal + * Default value so a new property can be created + * @param req + * Restart requirement of the property to be created + * @param bound + * The bounds to set on this property + * @return The value of the property + * + * @throws IllegalArgumentException + * if defaultVal is not a valid property type + * @throws IllegalStateException + * if there is no active section + */ + protected T getValue(String key, String comment, T defaultVal, RestartReqs req, Bound bound) { + Property prop = getProperty(key, defaultVal, req); + prop.comment = comment; + + return getValue(prop, defaultVal, bound); + } + + /** + * Gets a value from a property + * + * @param prop + * Property to get value from + * @param defaultVal + * Default value so a new property can be created + * + * @throws IllegalArgumentException + * if defaultVal is not a valid property type + * @throws IllegalStateException + * if there is no active section + */ + protected T getValue(Property prop, T defaultVal) { + return getValue(prop, defaultVal, null); + } + + /** + * Gets a value from a property + * + * @param prop + * Property to get value from + * @param defaultVal + * Default value so a new property can be created + * @param bound + * The bounds to set on this property + * + * @throws IllegalArgumentException + * if defaultVal is not a valid property type + * @throws IllegalStateException + * if there is no active section + */ + @SuppressWarnings("unchecked") + // we check type of defaultVal but compiler still complains about a cast to T + protected T getValue(Property prop, T defaultVal, Bound bound) { + checkInitialized(); + + if (bound != null) { + setBounds(prop, bound); + } else { + bound = Bound.MAX_BOUND; } - private void checkInitialized() - { - if (activeSection == null) - { - throw new IllegalStateException("No section is active!"); - } + addCommentDetails(prop, bound); + + if (defaultVal instanceof Integer) { + Bound b = Bound.of(bound.min.intValue(), bound.max.intValue()); + return (T) boundValue(prop, b, (Integer) defaultVal); + } + if (defaultVal instanceof Float) { + Bound b = Bound.of(bound.min.floatValue(), bound.max.floatValue()); + return (T) boundValue(prop, b, (Float) defaultVal); + } + if (defaultVal instanceof Double) { + Bound b = Bound.of(bound.min.doubleValue(), bound.max.doubleValue()); + return (T) boundValue(prop, b, (Double) defaultVal); + } + if (defaultVal instanceof Boolean) { + return (T) Boolean.valueOf(prop.getBoolean()); + } + if (defaultVal instanceof int[]) { + return (T) prop.getIntList(); + } + if (defaultVal instanceof String) { + return (T) prop.getString(); + } + if (defaultVal instanceof String[]) { + return (T) prop.getStringList(); } - /** - * Activates a section - * - * @param sectionName - * The name of the section - * - * @throws NullPointerException - * if {@code sectionName} is null - * @throws IllegalArgumentException - * if {@code sectionName} is not valid - */ - protected void activateSection(@NonNull String sectionName) - { - Section section = getSectionByName(sectionName); - if (section == null) - { - throw new IllegalArgumentException("Section " + sectionName + " does not exist!"); - } - activateSection(section); - } + throw new IllegalArgumentException("default value is not a config value type."); + } - /** - * Activates a section - * - * @param section - * The section to activate - * - * @throws NullPointerException - * if {@code section} is null - */ - protected void activateSection(@NonNull Section section) - { - activeSection = section; + static void setBounds(Property prop, Bound bound) throws IllegalArgumentException { + if (bound.equals(Bound.MAX_BOUND)) { + return; } + if (prop.getType() == Type.INTEGER) { + Bound b = Bound.of(bound.min.intValue(), bound.max.intValue()); + prop.setMinValue(b.min); + prop.setMaxValue(b.max); + } else if (prop.getType() == Type.DOUBLE) { + Bound b = Bound.of(bound.min.doubleValue(), bound.max.doubleValue()); + prop.setMinValue(b.min); + prop.setMaxValue(b.max); + } else { + throw new IllegalArgumentException(String.format("A mod tried to set bounds %s on a property that was not either of Integer of Double type.", bound)); + } + } - /** - * Gets a {@link Section} for a name - * - * @param sectionName - * The name of the section - * @return A section object representing the section in your config with this name - * - * @throws NullPointerException - * if {@code sectionName} is null - */ - protected Section getSectionByName(@NonNull String sectionName) - { - for (Section s : sections) - { - if (s.name.equalsIgnoreCase(sectionName)) - { - return s; - } - } - return null; + static int[] boundIntArr(Property prop, Bound bound) { + int[] prev = prop.getIntList(); + int[] res = new int[prev.length]; + for (int i = 0; i < prev.length; i++) { + res[i] = bound.clamp(prev[i]); } + prop.set(res); + return res; + } - /** - * Gets a value from this config handler - * - * @param key - * Name of the key for this property - * @param defaultVal - * Default value so a new property can be created - * @return The value of the property - * - * @throws IllegalArgumentException - * If defaultVal is not a valid property type - * @throws IllegalStateException - * If there is no active section - */ - protected T getValue(String key, T defaultVal) - { - return getValue(key, defaultVal, RestartReqs.NONE); + static double[] boundDoubleArr(Property prop, Bound bound) { + double[] prev = prop.getDoubleList(); + double[] res = new double[prev.length]; + for (int i = 0; i < prev.length; i++) { + res[i] = bound.clamp(prev[i]); } + prop.set(res); + return res; + } - /** - * Gets a value from this config handler - * - * @param key - * Name of the key for this property - * @param defaultVal - * Default value so a new property can be created - * @param req - * Restart requirement of the property to be created - * @return The value of the property - * - * @throws IllegalArgumentException - * If defaultVal is not a valid property type - * @throws IllegalStateException - * If there is no active section - */ - protected T getValue(String key, T defaultVal, RestartReqs req) - { - return getValue(key, null, defaultVal, req); + @SuppressWarnings("unchecked") + static > T boundValue(Property prop, Bound bound, T defVal) throws IllegalArgumentException { + Object b = (Object) bound; + if (defVal instanceof Integer) { + return (T) boundInt(prop, (Bound) b); } + if (defVal instanceof Double) { + return (T) boundDouble(prop, (Bound) b); + } + if (defVal instanceof Float) { + return (T) boundFloat(prop, (Bound) b); + } + throw new IllegalArgumentException(bound.min.getClass().getName() + " is not a valid config type."); + } - /** - * Gets a value from this config handler - * - * @param key - * Name of the key for this property - * @param defaultVal - * Default value so a new property can be created - * @param bound - * The bounds to set on this property - * @return The value of the property - * - * @throws IllegalArgumentException - * If defaultVal is not a valid property type - * @throws IllegalStateException - * If there is no active section - */ - protected T getValue(String key, T defaultVal, Bound bound) - { - return getValue(key, null, defaultVal, bound); - } + private static Integer boundInt(Property prop, Bound bound) { + prop.set(bound.clamp(prop.getInt())); + return Integer.valueOf(prop.getInt()); + } - /** - * Gets a value from this config handler - * - * @param key - * Name of the key for this property - * @param comment - * The comment to put on this property - * @param defaultVal - * Default value so a new property can be created - * @return The value of the property - * - * @throws IllegalArgumentException - * if defaultVal is not a valid property type - * @throws IllegalStateException - * if there is no active section - */ - protected T getValue(String key, String comment, T defaultVal) - { - return getValue(key, comment, defaultVal, RestartReqs.NONE); - } + private static Double boundDouble(Property prop, Bound bound) { + prop.set(bound.clamp(prop.getDouble())); + return Double.valueOf(prop.getDouble()); + } - /** - * Gets a value from this config handler - * - * @param key - * Name of the key for this property - * @param comment - * The comment to put on this property - * @param defaultVal - * Default value so a new property can be created - * @param req - * Restart requirement of the property to be created - * @return The value of the property - * - * @throws IllegalArgumentException - * if defaultVal is not a valid property type - * @throws IllegalStateException - * if there is no active section - */ - protected T getValue(String key, String comment, T defaultVal, RestartReqs req) - { - return getValue(key, comment, defaultVal, req, null); - } + private static Float boundFloat(Property prop, Bound bound) { + return boundDouble(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue())).floatValue(); + } - /** - * Gets a value from this config handler - * - * @param key - * Name of the key for this property - * @param comment - * The comment to put on this property - * @param defaultVal - * Default value so a new property can be created - * @param bound - * The bounds to set on this property - * @return The value of the property - * - * @throws IllegalArgumentException - * if defaultVal is not a valid property type - * @throws IllegalStateException - * if there is no active section - */ - protected T getValue(String key, String comment, T defaultVal, Bound bound) - { - return getValue(key, comment, defaultVal, RestartReqs.NONE, bound); - } + private static Lang fmlLang = new Lang("fml.configgui.tooltip"); - /** - * Gets a value from this config handler - * - * @param key - * Name of the key for this property - * @param comment - * The comment to put on this property - * @param defaultVal - * Default value so a new property can be created - * @param req - * Restart requirement of the property to be created - * @param bound - * The bounds to set on this property - * @return The value of the property - * - * @throws IllegalArgumentException - * if defaultVal is not a valid property type - * @throws IllegalStateException - * if there is no active section - */ - protected T getValue(String key, String comment, T defaultVal, RestartReqs req, Bound bound) - { - Property prop = getProperty(key, defaultVal, req); - prop.comment = comment; + static void addCommentDetails(Property prop, Bound bound) { + prop.comment += (prop.comment.isEmpty() ? "" : "\n"); + if (bound.equals(Bound.MAX_BOUND)) { + prop.comment += fmlLang.localize("default", prop.isList() ? Arrays.toString(prop.getDefaults()) : prop.getDefault()); + } else { + boolean minIsInt = bound.min.doubleValue() == bound.min.intValue(); + boolean maxIsInt = bound.max.doubleValue() == bound.max.intValue(); + prop.comment += fmlLang.localize("defaultNumeric", minIsInt ? bound.min.intValue() : bound.min, maxIsInt ? bound.max.intValue() : bound.max, + prop.isList() ? Arrays.toString(prop.getDefaults()) : prop.getDefault()); + } + } - return getValue(prop, defaultVal, bound); - } + /** + * Gets a property from this config handler + * + * @param key + * name of the key for this property + * @param defaultVal + * default value so a new property can be created + * @return The property in the config + * + * @throws IllegalArgumentException + * if defaultVal is not a valid property type + * @throws IllegalStateException + * if there is no active section + */ + protected Property getProperty(String key, T defaultVal) { + return getProperty(key, defaultVal, RestartReqs.NONE); + } - /** - * Gets a value from a property - * - * @param prop - * Property to get value from - * @param defaultVal - * Default value so a new property can be created - * - * @throws IllegalArgumentException - * if defaultVal is not a valid property type - * @throws IllegalStateException - * if there is no active section - */ - protected T getValue(Property prop, T defaultVal) - { - return getValue(prop, defaultVal, null); - } + /** + * Gets a property from this config handler + * + * @param key + * name of the key for this property + * @param defaultVal + * default value so a new property can be created + * @return The property in the config + * + * @throws IllegalArgumentException + * if defaultVal is not a valid property type + * @throws IllegalStateException + * if there is no active section + */ + protected Property getProperty(String key, T defaultVal, RestartReqs req) { + checkInitialized(); + Section section = activeSection; + Property prop = null; - /** - * Gets a value from a property - * - * @param prop - * Property to get value from - * @param defaultVal - * Default value so a new property can be created - * @param bound - * The bounds to set on this property - * - * @throws IllegalArgumentException - * if defaultVal is not a valid property type - * @throws IllegalStateException - * if there is no active section - */ - @SuppressWarnings("unchecked") - // we check type of defaultVal but compiler still complains about a cast to T - protected T getValue(Property prop, T defaultVal, Bound bound) - { - checkInitialized(); - - if (bound != null) - { - setBounds(prop, bound); - } - else - { - bound = Bound.MAX_BOUND; - } - - addCommentDetails(prop, bound); - - if (defaultVal instanceof Integer) - { - Bound b = Bound.of(bound.min.intValue(), bound.max.intValue()); - return (T) boundValue(prop, b, (Integer) defaultVal); - } - if (defaultVal instanceof Float) - { - Bound b = Bound.of(bound.min.floatValue(), bound.max.floatValue()); - return (T) boundValue(prop, b, (Float) defaultVal); - } - if (defaultVal instanceof Double) - { - Bound b = Bound.of(bound.min.doubleValue(), bound.max.doubleValue()); - return (T) boundValue(prop, b, (Double) defaultVal); - } - if (defaultVal instanceof Boolean) - { - return (T) Boolean.valueOf(prop.getBoolean()); - } - if (defaultVal instanceof int[]) - { - return (T) prop.getIntList(); - } - if (defaultVal instanceof String) - { - return (T) prop.getString(); - } - if (defaultVal instanceof String[]) - { - return (T) prop.getStringList(); - } - - throw new IllegalArgumentException("default value is not a config value type."); - } - - static void setBounds(Property prop, Bound bound) throws IllegalArgumentException - { - if (bound.equals(Bound.MAX_BOUND)) - { - return; - } - if (prop.getType() == Type.INTEGER) - { - Bound b = Bound.of(bound.min.intValue(), bound.max.intValue()); - prop.setMinValue(b.min); - prop.setMaxValue(b.max); - } - else if (prop.getType() == Type.DOUBLE) - { - Bound b = Bound.of(bound.min.doubleValue(), bound.max.doubleValue()); - prop.setMinValue(b.min); - prop.setMaxValue(b.max); - } - else - { - throw new IllegalArgumentException(String.format("A mod tried to set bounds %s on a property that was not either of Integer of Double type.", bound)); - } - } - - static int[] boundIntArr(Property prop, Bound bound) - { - int[] prev = prop.getIntList(); - int[] res = new int[prev.length]; - for (int i = 0; i < prev.length; i++) - { - res[i] = bound.clamp(prev[i]); - } - prop.set(res); - return res; - } - - static double[] boundDoubleArr(Property prop, Bound bound) - { - double[] prev = prop.getDoubleList(); - double[] res = new double[prev.length]; - for (int i = 0; i < prev.length; i++) - { - res[i] = bound.clamp(prev[i]); - } - prop.set(res); - return res; - } - - @SuppressWarnings("unchecked") - static > T boundValue(Property prop, Bound bound, T defVal) throws IllegalArgumentException - { - Object b = (Object) bound; - if (defVal instanceof Integer) - { - return (T) boundInt(prop, (Bound) b); - } - if (defVal instanceof Double) - { - return (T) boundDouble(prop, (Bound) b); - } - if (defVal instanceof Float) - { - return (T) boundFloat(prop, (Bound) b); - } - throw new IllegalArgumentException(bound.min.getClass().getName() + " is not a valid config type."); - } - - private static Integer boundInt(Property prop, Bound bound) - { - prop.set(bound.clamp(prop.getInt())); - return Integer.valueOf(prop.getInt()); - } - - private static Double boundDouble(Property prop, Bound bound) - { - prop.set(bound.clamp(prop.getDouble())); - return Double.valueOf(prop.getDouble()); - } - - private static Float boundFloat(Property prop, Bound bound) - { - return boundDouble(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue())).floatValue(); - } - - private static Lang fmlLang = new Lang("fml.configgui.tooltip"); - static void addCommentDetails(Property prop, Bound bound) - { - prop.comment += (prop.comment.isEmpty() ? "" : "\n"); - if (bound.equals(Bound.MAX_BOUND)) - { - prop.comment += fmlLang.localize("default", prop.isList() ? Arrays.toString(prop.getDefaults()) : prop.getDefault()); - } - else - { - boolean minIsInt = bound.min.doubleValue() == bound.min.intValue(); - boolean maxIsInt = bound.max.doubleValue() == bound.max.intValue(); - prop.comment += fmlLang.localize("defaultNumeric", minIsInt ? bound.min.intValue() : bound.min, maxIsInt ? bound.max.intValue() - : bound.max, prop.isList() ? Arrays.toString(prop.getDefaults()) : prop.getDefault()); - } - } - - /** - * Gets a property from this config handler - * - * @param key - * name of the key for this property - * @param defaultVal - * default value so a new property can be created - * @return The property in the config - * - * @throws IllegalArgumentException - * if defaultVal is not a valid property type - * @throws IllegalStateException - * if there is no active section - */ - protected Property getProperty(String key, T defaultVal) - { - return getProperty(key, defaultVal, RestartReqs.NONE); - } - - /** - * Gets a property from this config handler - * - * @param key - * name of the key for this property - * @param defaultVal - * default value so a new property can be created - * @return The property in the config - * - * @throws IllegalArgumentException - * if defaultVal is not a valid property type - * @throws IllegalStateException - * if there is no active section - */ - protected Property getProperty(String key, T defaultVal, RestartReqs req) - { - checkInitialized(); - Section section = activeSection; - Property prop = null; - - // @formatter:off + // @formatter:off // same logic as above method, mostly if (defaultVal instanceof Integer) { @@ -690,60 +622,53 @@ public abstract class AbstractConfigHandler implements IConfigHandler } // @formatter:on - if (defaultVal instanceof Float || defaultVal instanceof Double) - { - double val = defaultVal instanceof Float ? ((Float) defaultVal).doubleValue() : ((Double) defaultVal).doubleValue(); - prop = config.get(section.name, key, val); - } - - if (prop != null) - { - return req.apply(prop); - } - - throw new IllegalArgumentException("default value is not a config value type."); + if (defaultVal instanceof Float || defaultVal instanceof Double) { + double val = defaultVal instanceof Float ? ((Float) defaultVal).doubleValue() : ((Double) defaultVal).doubleValue(); + prop = config.get(section.name, key, val); } - /** - * @return If this config handler should recieve {@link #initHook()} and {@link #postInitHook()} during config reload events. If this returns - * false, these methods will only be called on load. - *

- * Defaults to false. - */ - protected boolean shouldHookOnReload() - { - return true; + if (prop != null) { + return req.apply(prop); } - /* IConfigHandler impl */ + throw new IllegalArgumentException("default value is not a config value type."); + } - @Override - public void initHook() - { - } + /** + * @return If this config handler should recieve {@link #initHook()} and + * {@link #postInitHook()} during config reload events. If this + * returns false, these methods will only be called on load. + *

+ * Defaults to false. + */ + protected boolean shouldHookOnReload() { + return true; + } - @Override - public void postInitHook() - { - } + /* IConfigHandler impl */ - // no need to override these, they are merely utilities, and reference private fields anyways + @Override + public void initHook() { + } - @Override - public final List

getSections() - { - return ImmutableList.copyOf(sections); - } + @Override + public void postInitHook() { + } - @Override - public final ConfigCategory getCategory(String name) - { - return config.getCategory(name); - } + // no need to override these, they are merely utilities, and reference private fields anyways - @Override - public final String getModID() - { - return modid; - } + @Override + public final List
getSections() { + return ImmutableList.copyOf(sections); + } + + @Override + public final ConfigCategory getCategory(String name) { + return config.getCategory(name); + } + + @Override + public final String getModID() { + return modid; + } } diff --git a/src/main/java/com/enderio/core/common/config/BaseConfigFactory.java b/src/main/java/com/enderio/core/common/config/BaseConfigFactory.java index bed4c16..ae570b9 100644 --- a/src/main/java/com/enderio/core/common/config/BaseConfigFactory.java +++ b/src/main/java/com/enderio/core/common/config/BaseConfigFactory.java @@ -8,30 +8,25 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import cpw.mods.fml.client.IModGuiFactory; -public class BaseConfigFactory implements IModGuiFactory -{ - @Override - public void initialize(Minecraft minecraftInstance) - { - ; - } +public class BaseConfigFactory implements IModGuiFactory { + @Override + public void initialize(Minecraft minecraftInstance) { + ; + } - @Override - public Class mainConfigGuiClass() - { - return BaseConfigGui.class; - } + @Override + public Class mainConfigGuiClass() { + return BaseConfigGui.class; + } - @Override - public Set runtimeGuiCategories() - { - return null; - } + @Override + public Set runtimeGuiCategories() { + return null; + } - @Override - public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) - { - return null; - } + @Override + public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { + return null; + } } diff --git a/src/main/java/com/enderio/core/common/config/ConfigProcessor.java b/src/main/java/com/enderio/core/common/config/ConfigProcessor.java index 8cdc5d4..be50b04 100644 --- a/src/main/java/com/enderio/core/common/config/ConfigProcessor.java +++ b/src/main/java/com/enderio/core/common/config/ConfigProcessor.java @@ -38,406 +38,359 @@ import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent; /** - * This class can be used to automatically process {@link Config} annotations on fields, and sync the data in those fields to clients. It will also - * automatically respond to all config changed events and handle them appropriately. + * This class can be used to automatically process {@link Config} annotations on + * fields, and sync the data in those fields to clients. It will also + * automatically respond to all config changed events and handle them + * appropriately. * * @see #process(boolean) */ -public class ConfigProcessor -{ - public interface IReloadCallback - { - void callback(ConfigProcessor inst); - } +public class ConfigProcessor { + public interface IReloadCallback { + void callback(ConfigProcessor inst); + } + + /** + * A simple adapter for reading custom config types. + * + * @param + * Must be a possible class that can be used in configs. This + * consists of: + *
    + * + *
  • Boolean
  • + *
  • Integer
  • + *
  • Double
  • + *
  • String
  • + *
  • boolean[]
  • + *
  • int[]
  • + *
  • double[]
  • + *
  • String[]
  • + *
    + *
+ * @param + * The actual type of this adapter. This is what the field type must + * be for this adapter to be applied. + */ + public interface ITypeAdapter { + TypeToken getActualType(); + + Property.Type getType(); /** - * A simple adapter for reading custom config types. - * - * @param - * Must be a possible class that can be used in configs. This consists of: - *
    - * - *
  • Boolean
  • - *
  • Integer
  • - *
  • Double
  • - *
  • String
  • - *
  • boolean[]
  • - *
  • int[]
  • - *
  • double[]
  • - *
  • String[]
  • - *
    - *
- * @param - * The actual type of this adapter. This is what the field type must be for this adapter to be applied. - */ - public interface ITypeAdapter - { - TypeToken getActualType(); - - Property.Type getType(); - - /** - * If this binds to a primitive type, return it here (e.g. int.class). Otherwise, return null. - * - * @return The class for this ITypeAdapter's primitive type. - */ - @Nullable - Class getPrimitiveType(); - - ACTUAL createActualType(BASE base); - - BASE createBaseType(ACTUAL actual); - } - - static final Map processorMap = Maps.newHashMap(); - - private final List> adapters = Lists.newArrayList(); - - final String modid; - - private final Class configs; - private final Configuration configFile; - private final IReloadCallback callback; - - Map configValues = Maps.newHashMap(); - Map defaultValues = Maps.newHashMap(); - Map originalValues = Maps.newHashMap(); - - private Set sections = Sets.newHashSet(); - - /** - * This constructor omits the callback arg. + * If this binds to a primitive type, return it here (e.g. int.class). + * Otherwise, return null. * - * @see #ConfigProcessor(Class, File, String, IReloadCallback) + * @return The class for this ITypeAdapter's primitive type. */ - public ConfigProcessor(Class configs, File configFile, String modid) - { - this(configs, configFile, modid, null); + @Nullable + Class getPrimitiveType(); + + ACTUAL createActualType(BASE base); + + BASE createBaseType(ACTUAL actual); + } + + static final Map processorMap = Maps.newHashMap(); + + private final List> adapters = Lists.newArrayList(); + + final String modid; + + private final Class configs; + private final Configuration configFile; + private final IReloadCallback callback; + + Map configValues = Maps.newHashMap(); + Map defaultValues = Maps.newHashMap(); + Map originalValues = Maps.newHashMap(); + + private Set sections = Sets.newHashSet(); + + /** + * This constructor omits the callback arg. + * + * @see #ConfigProcessor(Class, File, String, IReloadCallback) + */ + public ConfigProcessor(Class configs, File configFile, String modid) { + this(configs, configFile, modid, null); + } + + /** + * Constructs a new ConfigProcessor to read and set {@link Config} values. + * + * @param configs + * The class which contains your {@link Config} annotations + * @param configFile + * The file to use as the configuration file + * @param modid + * The modid of the owner mod + * @param callback + * an {@link IReloadCallback} object which will be called whenever + * config values are edited. + */ + public ConfigProcessor(Class configs, File configFile, String modid, IReloadCallback callback) { + this(configs, new Configuration(configFile), modid, callback); + } + + /** + * Use this constructor if you are using a {@code ConfigProcessor} alongside + * an {@link AbstractConfigHandler}. Do not pass a handler that has not been + * {@link AbstractConfigHandler#initialize(File) initialized}! + * + * @param configs + * The class which contains your {@link Config} annotations + * (typically same class as your {@link AbstractConfigHandler + * handler}) + * @param handler + * Your {@link AbstractConfigHandler} + */ + public ConfigProcessor(Class configs, AbstractConfigHandler handler) { + this(configs, handler, null); + } + + /** + * Use this constructor if you are using a {@code ConfigProcessor} alongside + * an {@link AbstractConfigHandler}. Do not pass a handler that has not been + * {@link AbstractConfigHandler#initialize(File) initialized}! + * + * @param configs + * The class which contains your {@link Config} annotations + * (typically same class as your {@link AbstractConfigHandler + * handler}) + * @param handler + * Your {@link AbstractConfigHandler} + * @param callback + * an {@link IReloadCallback} object which will be called whenever + * config values are edited. + */ + public ConfigProcessor(Class configs, AbstractConfigHandler handler, IReloadCallback callback) { + this(configs, handler.config, handler.modid, callback); + } + + private ConfigProcessor(Class configs, Configuration configFile, String modid, IReloadCallback callback) { + this.configs = configs; + this.configFile = configFile; + this.modid = modid; + this.callback = callback; + processorMap.put(modid, this); + FMLCommonHandler.instance().bus().register(this); + adapters.addAll(TypeAdapterBase.all); + } + + public ConfigProcessor addAdapter(ITypeAdapter adapter) { + adapters.add(adapter); + return this; + } + + public ConfigProcessor addAdapters(ITypeAdapter... adapters) { + for (ITypeAdapter adapter : adapters) { + addAdapter(adapter); + } + return this; + } + + /** + * Processes all the configs in this processors class, optionally loading them + * from file first. + * + * @param load + * If true, the values from the file will be loaded. Otherwise, the + * values existing in memory will be used. + */ + public void process(boolean load) { + if (load) { + configFile.load(); } - /** - * Constructs a new ConfigProcessor to read and set {@link Config} values. - * - * @param configs - * The class which contains your {@link Config} annotations - * @param configFile - * The file to use as the configuration file - * @param modid - * The modid of the owner mod - * @param callback - * an {@link IReloadCallback} object which will be called whenever config values are edited. - */ - public ConfigProcessor(Class configs, File configFile, String modid, IReloadCallback callback) - { - this(configs, new Configuration(configFile), modid, callback); + try { + for (Field f : configs.getDeclaredFields()) { + processField(f); + } + if (callback != null) { + callback.callback(this); + } + } catch (Exception e) { + throw new RuntimeException(e); } - /** - * Use this constructor if you are using a {@code ConfigProcessor} alongside an {@link AbstractConfigHandler}. Do not pass a handler that has not - * been {@link AbstractConfigHandler#initialize(File) initialized}! - * - * @param configs - * The class which contains your {@link Config} annotations (typically same class as your {@link AbstractConfigHandler handler}) - * @param handler - * Your {@link AbstractConfigHandler} - */ - public ConfigProcessor(Class configs, AbstractConfigHandler handler) - { - this(configs, handler, null); + configFile.save(); + } + + // returns true if the config value changed + private boolean processField(Field f) throws Exception { + Config cfg = f.getAnnotation(Config.class); + if (cfg == null) { + return false; + } + String name = f.getName(); + Object value = defaultValues.get(name); + if (value == null) { + value = f.get(null); + defaultValues.put(name, value); } - /** - * Use this constructor if you are using a {@code ConfigProcessor} alongside an {@link AbstractConfigHandler}. Do not pass a handler that has not - * been {@link AbstractConfigHandler#initialize(File) initialized}! - * - * @param configs - * The class which contains your {@link Config} annotations (typically same class as your {@link AbstractConfigHandler handler}) - * @param handler - * Your {@link AbstractConfigHandler} - * @param callback - * an {@link IReloadCallback} object which will be called whenever config values are edited. - */ - public ConfigProcessor(Class configs, AbstractConfigHandler handler, IReloadCallback callback) - { - this(configs, handler.config, handler.modid, callback); - } + Object newValue = getConfigValue(cfg.value(), getComment(f), f, value); - private ConfigProcessor(Class configs, Configuration configFile, String modid, IReloadCallback callback) - { - this.configs = configs; - this.configFile = configFile; - this.modid = modid; - this.callback = callback; - processorMap.put(modid, this); - FMLCommonHandler.instance().bus().register(this); - adapters.addAll(TypeAdapterBase.all); - } + configValues.put(f.getName(), newValue); + originalValues.put(f.getName(), newValue); + f.set(null, newValue); - public ConfigProcessor addAdapter(ITypeAdapter adapter) - { - adapters.add(adapter); - return this; - } + sections.add(cfg.value()); - public ConfigProcessor addAdapters(ITypeAdapter... adapters) - { - for (ITypeAdapter adapter : adapters) - { - addAdapter(adapter); + return !value.equals(newValue); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private Object getConfigValue(String section, String[] commentLines, Field f, Object defVal) { + Property prop = null; + Object res = null; + Bound bound = getBound(f); + ITypeAdapter adapter = getAdapterFor(f); + String comment = StringUtils.join(commentLines, "\n"); + if (adapter != null) { + defVal = adapter.createBaseType(defVal); + switch (adapter.getType()) { + case BOOLEAN: + if (defVal.getClass().isArray()) { + prop = configFile.get(section, f.getName(), (boolean[]) defVal, comment); + res = prop.getBooleanList(); + } else { + prop = configFile.get(section, f.getName(), (Boolean) defVal, comment); + res = prop.getBoolean(); } - return this; - } - - /** - * Processes all the configs in this processors class, optionally loading them from file first. - * - * @param load - * If true, the values from the file will be loaded. Otherwise, the values existing in memory will be used. - */ - public void process(boolean load) - { - if (load) - { - configFile.load(); + break; + case DOUBLE: + if (defVal.getClass().isArray()) { + prop = configFile.get(section, f.getName(), (double[]) defVal, comment); + res = AbstractConfigHandler.boundDoubleArr(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue())); + } else { + prop = configFile.get(section, f.getName(), (Double) defVal, comment); + res = AbstractConfigHandler.boundValue(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue()), (Double) defVal); } - - try - { - for (Field f : configs.getDeclaredFields()) - { - processField(f); - } - if (callback != null) - { - callback.callback(this); - } + break; + case INTEGER: + if (defVal.getClass().isArray()) { + prop = configFile.get(section, f.getName(), (int[]) defVal, comment); + res = AbstractConfigHandler.boundIntArr(prop, Bound.of(bound.min.intValue(), bound.max.intValue())); + } else { + prop = configFile.get(section, f.getName(), (Integer) defVal, comment); + res = AbstractConfigHandler.boundValue(prop, Bound.of(bound.min.intValue(), bound.max.intValue()), (Integer) defVal); } - catch (Exception e) - { - throw new RuntimeException(e); + break; + case STRING: + if (defVal.getClass().isArray()) { + prop = configFile.get(section, f.getName(), (String[]) defVal, comment); + res = prop.getStringList(); + } else { + prop = configFile.get(section, f.getName(), (String) defVal, comment); + res = prop.getString(); } - - configFile.save(); + break; + default: + break; + } + if (res != null) { + AbstractConfigHandler.setBounds(prop, bound); + AbstractConfigHandler.addCommentDetails(prop, bound); + getRestartReq(f).apply(prop); + return adapter.createActualType(res); + } } + throw new IllegalArgumentException(String.format("No adapter for type %s in class %s, field %s", f.getGenericType(), configs, f)); + } - // returns true if the config value changed - private boolean processField(Field f) throws Exception - { - Config cfg = f.getAnnotation(Config.class); - if (cfg == null) - { - return false; + @SuppressWarnings({ "unchecked", "rawtypes" }) + private ITypeAdapter getAdapterFor(Field f) { + TypeToken t = TypeToken.of(f.getGenericType()); + Class c = f.getType(); + for (ITypeAdapter adapter : adapters) { + if ((c.isPrimitive() && c == adapter.getPrimitiveType()) || adapter.getActualType().isAssignableFrom(t)) { + return adapter; + } + } + return null; + } + + public ImmutableSet sections() { + return ImmutableSet.copyOf(sections); + } + + public ConfigCategory getCategory(String category) { + return configFile.getCategory(category); + } + + public void syncTo(Map values) { + this.configValues = values; + for (String s : configValues.keySet()) { + try { + Field f = configs.getDeclaredField(s); + Config annot = f.getAnnotation(Config.class); + if (annot != null && !getNoSync(f)) { + Object newVal = configValues.get(s); + Object oldVal = f.get(null); + boolean changed = false; + if (!oldVal.equals(newVal)) { + EnderCore.logger.debug("Config {}.{} differs from new data. Changing from {} to {}", configs.getName(), f.getName(), oldVal, newVal); + f.set(null, newVal); + changed = true; + } + if (changed && callback != null) { + callback.callback(this); + } + } else if (annot != null) { + EnderCore.logger.debug("Skipping syncing field {}.{} as it was marked NoSync", configs.getName(), f.getName()); } - String name = f.getName(); - Object value = defaultValues.get(name); - if (value == null) - { - value = f.get(null); - defaultValues.put(name, value); - } - - Object newValue = getConfigValue(cfg.value(), getComment(f), f, value); - - configValues.put(f.getName(), newValue); - originalValues.put(f.getName(), newValue); - f.set(null, newValue); - - sections.add(cfg.value()); - - return !value.equals(newValue); + } catch (Exception e) { + throw new RuntimeException(e); + } } + } - @SuppressWarnings({ "rawtypes", "unchecked" }) - private Object getConfigValue(String section, String[] commentLines, Field f, Object defVal) - { - Property prop = null; - Object res = null; - Bound bound = getBound(f); - ITypeAdapter adapter = getAdapterFor(f); - String comment = StringUtils.join(commentLines, "\n"); - if (adapter != null) - { - defVal = adapter.createBaseType(defVal); - switch (adapter.getType()) - { - case BOOLEAN: - if (defVal.getClass().isArray()) - { - prop = configFile.get(section, f.getName(), (boolean[]) defVal, comment); - res = prop.getBooleanList(); - } - else - { - prop = configFile.get(section, f.getName(), (Boolean) defVal, comment); - res = prop.getBoolean(); - } - break; - case DOUBLE: - if (defVal.getClass().isArray()) - { - prop = configFile.get(section, f.getName(), (double[]) defVal, comment); - res = AbstractConfigHandler.boundDoubleArr(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue())); - } - else - { - prop = configFile.get(section, f.getName(), (Double) defVal, comment); - res = AbstractConfigHandler.boundValue(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue()), (Double) defVal); - } - break; - case INTEGER: - if (defVal.getClass().isArray()) - { - prop = configFile.get(section, f.getName(), (int[]) defVal, comment); - res = AbstractConfigHandler.boundIntArr(prop, Bound.of(bound.min.intValue(), bound.max.intValue())); - } - else - { - prop = configFile.get(section, f.getName(), (Integer) defVal, comment); - res = AbstractConfigHandler.boundValue(prop, Bound.of(bound.min.intValue(), bound.max.intValue()), (Integer) defVal); - } - break; - case STRING: - if (defVal.getClass().isArray()) - { - prop = configFile.get(section, f.getName(), (String[]) defVal, comment); - res = prop.getStringList(); - } - else - { - prop = configFile.get(section, f.getName(), (String) defVal, comment); - res = prop.getString(); - } - break; - default: - break; - } - if (res != null) - { - AbstractConfigHandler.setBounds(prop, bound); - AbstractConfigHandler.addCommentDetails(prop, bound); - getRestartReq(f).apply(prop); - return adapter.createActualType(res); - } - } - throw new IllegalArgumentException(String.format("No adapter for type %s in class %s, field %s", f.getGenericType(), configs, f)); - } + private String[] getComment(Field f) { + Comment c = f.getAnnotation(Comment.class); + return c == null ? new String[0] : c.value(); + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - private ITypeAdapter getAdapterFor(Field f) - { - TypeToken t = TypeToken.of(f.getGenericType()); - Class c = f.getType(); - for (ITypeAdapter adapter : adapters) - { - if ((c.isPrimitive() && c == adapter.getPrimitiveType()) || adapter.getActualType().isAssignableFrom(t)) - { - return adapter; - } - } - return null; - } + private Bound getBound(Field f) { + Range r = f.getAnnotation(Range.class); + return r == null ? Bound.MAX_BOUND : Bound.of(r.min(), r.max()); + } - public ImmutableSet sections() - { - return ImmutableSet.copyOf(sections); - } + private boolean getNoSync(Field f) { + return f.getAnnotation(NoSync.class) != null; + } - public ConfigCategory getCategory(String category) - { - return configFile.getCategory(category); - } + private RestartReqs getRestartReq(Field f) { + RestartReq r = f.getAnnotation(RestartReq.class); + return r == null ? RestartReqs.NONE : r.value(); + } - public void syncTo(Map values) - { - this.configValues = values; - for (String s : configValues.keySet()) - { - try - { - Field f = configs.getDeclaredField(s); - Config annot = f.getAnnotation(Config.class); - if (annot != null && !getNoSync(f)) - { - Object newVal = configValues.get(s); - Object oldVal = f.get(null); - boolean changed = false; - if (!oldVal.equals(newVal)) - { - EnderCore.logger.debug("Config {}.{} differs from new data. Changing from {} to {}", configs.getName(), f.getName(), oldVal, newVal); - f.set(null, newVal); - changed = true; - } - if (changed && callback != null) - { - callback.callback(this); - } - } - else if (annot != null) - { - EnderCore.logger.debug("Skipping syncing field {}.{} as it was marked NoSync", configs.getName(), f.getName()); - } - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - } + /* Event Handling */ - private String[] getComment(Field f) - { - Comment c = f.getAnnotation(Comment.class); - return c == null ? new String[0] : c.value(); - } + @SubscribeEvent + public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) { + EnderCore.logger.info("Sending server configs to client for {}", configs.getName()); + EnderPacketHandler.INSTANCE.sendTo(new PacketConfigSync(this), (EntityPlayerMP) event.player); + } - private Bound getBound(Field f) - { - Range r = f.getAnnotation(Range.class); - return r == null ? Bound.MAX_BOUND : Bound.of(r.min(), r.max()); - } + @SubscribeEvent + public void onPlayerLogout(ClientDisconnectionFromServerEvent event) { + syncTo(originalValues); + EnderCore.logger.info("Reset configs to client values for {}", configs.getName()); + } - private boolean getNoSync(Field f) - { - return f.getAnnotation(NoSync.class) != null; + @SubscribeEvent + public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { + if (event.modID.equals(modid)) { + process(false); } + } - private RestartReqs getRestartReq(Field f) - { - RestartReq r = f.getAnnotation(RestartReq.class); - return r == null ? RestartReqs.NONE : r.value(); - } - - /* Event Handling */ - - @SubscribeEvent - public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) - { - EnderCore.logger.info("Sending server configs to client for {}", configs.getName()); - EnderPacketHandler.INSTANCE.sendTo(new PacketConfigSync(this), (EntityPlayerMP) event.player); - } - - @SubscribeEvent - public void onPlayerLogout(ClientDisconnectionFromServerEvent event) - { - syncTo(originalValues); - EnderCore.logger.info("Reset configs to client values for {}", configs.getName()); - } - - @SubscribeEvent - public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) - { - if (event.modID.equals(modid)) - { - process(false); - } - } - - @SubscribeEvent - public void onConfigFileChanged(ConfigFileChangedEvent event) - { - if (event.modID.equals(modid)) - { - process(true); - } + @SubscribeEvent + public void onConfigFileChanged(ConfigFileChangedEvent event) { + if (event.modID.equals(modid)) { + process(true); } + } } diff --git a/src/main/java/com/enderio/core/common/config/ITweakConfigHandler.java b/src/main/java/com/enderio/core/common/config/ITweakConfigHandler.java index d094c89..07e8439 100644 --- a/src/main/java/com/enderio/core/common/config/ITweakConfigHandler.java +++ b/src/main/java/com/enderio/core/common/config/ITweakConfigHandler.java @@ -2,7 +2,6 @@ package com.enderio.core.common.config; import com.enderio.core.common.tweaks.Tweak; -public interface ITweakConfigHandler -{ - public boolean addBooleanFor(Tweak tweak); +public interface ITweakConfigHandler { + public boolean addBooleanFor(Tweak tweak); } diff --git a/src/main/java/com/enderio/core/common/config/TypeAdapterBase.java b/src/main/java/com/enderio/core/common/config/TypeAdapterBase.java index 618b4bb..c1d5902 100644 --- a/src/main/java/com/enderio/core/common/config/TypeAdapterBase.java +++ b/src/main/java/com/enderio/core/common/config/TypeAdapterBase.java @@ -18,43 +18,36 @@ import com.google.common.reflect.TypeToken; @AllArgsConstructor @Getter @SuppressWarnings({ "serial", "unchecked" }) -public abstract class TypeAdapterBase implements ITypeAdapter -{ - private final TypeToken actualType; - private final Property.Type type; - private final Class primitiveType; +public abstract class TypeAdapterBase implements ITypeAdapter { + private final TypeToken actualType; + private final Property.Type type; + private final Class primitiveType; - public TypeAdapterBase(TypeToken actualType, Property.Type baseType) - { - this(actualType, baseType, null); + public TypeAdapterBase(TypeToken actualType, Property.Type baseType) { + this(actualType, baseType, null); + } + + public static final class TypeAdapterSame extends TypeAdapterBase { + public TypeAdapterSame(TypeToken actual, Property.Type base) { + super(actual, base); } - public static final class TypeAdapterSame extends TypeAdapterBase - { - public TypeAdapterSame(TypeToken actual, Property.Type base) - { - super(actual, base); - } - - public TypeAdapterSame(TypeToken actual, Property.Type base, Class primitiveType) - { - super(actual, base, primitiveType); - } - - @Override - public TYPE createActualType(TYPE base) - { - return base; - } - - @Override - public TYPE createBaseType(TYPE actual) - { - return actual; - } + public TypeAdapterSame(TypeToken actual, Property.Type base, Class primitiveType) { + super(actual, base, primitiveType); } - // @formatter:off + @Override + public TYPE createActualType(TYPE base) { + return base; + } + + @Override + public TYPE createBaseType(TYPE actual) { + return actual; + } + } + + // @formatter:off public static final TypeAdapterSame INTEGER = new TypeAdapterSame(TypeToken.of(Integer.class), Type.INTEGER, int.class); public static final TypeAdapterSame INTEGER_ARR = new TypeAdapterSame(TypeToken.of(int[].class), Type.INTEGER); public static final TypeAdapterSame DOUBLE = new TypeAdapterSame(TypeToken.of(Double.class), Type.DOUBLE, double.class); diff --git a/src/main/java/com/enderio/core/common/config/annot/Comment.java b/src/main/java/com/enderio/core/common/config/annot/Comment.java index 8dfe31a..ead370e 100644 --- a/src/main/java/com/enderio/core/common/config/annot/Comment.java +++ b/src/main/java/com/enderio/core/common/config/annot/Comment.java @@ -7,15 +7,16 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Contains the comment for a config option. Has no effect is this field is not also annotated with {@link Config}. + * Contains the comment for a config option. Has no effect is this field is not + * also annotated with {@link Config}. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Documented -public @interface Comment -{ - /** - * The comment for the config option. Multiple strings will be split into lines. - */ - String[] value() default ""; +public @interface Comment { + /** + * The comment for the config option. Multiple strings will be split into + * lines. + */ + String[] value() default ""; } diff --git a/src/main/java/com/enderio/core/common/config/annot/Config.java b/src/main/java/com/enderio/core/common/config/annot/Config.java index 9329f0a..a4f28ae 100644 --- a/src/main/java/com/enderio/core/common/config/annot/Config.java +++ b/src/main/java/com/enderio/core/common/config/annot/Config.java @@ -11,19 +11,19 @@ import com.enderio.core.common.config.ConfigProcessor; import net.minecraftforge.common.config.Configuration; /** - * Used to mark a {@code static} field as a config option. Has no effect if the class is not processed with a {@link ConfigProcessor} + * Used to mark a {@code static} field as a config option. Has no effect if the + * class is not processed with a {@link ConfigProcessor} */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Documented -public @interface Config -{ - /** - * The section of the config option. - * - * (AKA Category) - * - * @return A string section name. - */ - String value() default Configuration.CATEGORY_GENERAL; +public @interface Config { + /** + * The section of the config option. + * + * (AKA Category) + * + * @return A string section name. + */ + String value() default Configuration.CATEGORY_GENERAL; } diff --git a/src/main/java/com/enderio/core/common/config/annot/NoSync.java b/src/main/java/com/enderio/core/common/config/annot/NoSync.java index a3e65d8..9557ccf 100644 --- a/src/main/java/com/enderio/core/common/config/annot/NoSync.java +++ b/src/main/java/com/enderio/core/common/config/annot/NoSync.java @@ -7,15 +7,16 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * If annotation exists, this config will not be synced to the client upon connection to a server. Has no effect is this field is not also annotated + * If annotation exists, this config will not be synced to the client upon + * connection to a server. Has no effect is this field is not also annotated * with {@link Config}. *

- * This is useful for configs that have no need to be the same between client and server (or are purely client-sided). + * This is useful for configs that have no need to be the same between client + * and server (or are purely client-sided). */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Documented -public @interface NoSync -{ +public @interface NoSync { } diff --git a/src/main/java/com/enderio/core/common/config/annot/Range.java b/src/main/java/com/enderio/core/common/config/annot/Range.java index 23a9349..735c667 100644 --- a/src/main/java/com/enderio/core/common/config/annot/Range.java +++ b/src/main/java/com/enderio/core/common/config/annot/Range.java @@ -7,30 +7,33 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Represents the range a config value can be, i.e. a minimum and maximum value. This is applied forcefully, any value past one of the extremes will - * be clamped inside this range. Has no effect is this field is not also annotated with {@link Config}. + * Represents the range a config value can be, i.e. a minimum and maximum value. + * This is applied forcefully, any value past one of the extremes will be + * clamped inside this range. Has no effect is this field is not also annotated + * with {@link Config}. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Documented -public @interface Range -{ +public @interface Range { - /** - * The min value of the config. - *

- * For non-numeric values, or if there is no min value, this should remain unset. - * - * @return A double minimum value for the config. - */ - double min() default Double.MIN_VALUE; + /** + * The min value of the config. + *

+ * For non-numeric values, or if there is no min value, this should remain + * unset. + * + * @return A double minimum value for the config. + */ + double min() default Double.MIN_VALUE; - /** - * The max value of the config. - *

- * For non-numeric values, or if there is no max value, this should remain unset. - * - * @return A double maximum value for the config. - */ - double max() default Double.MAX_VALUE; + /** + * The max value of the config. + *

+ * For non-numeric values, or if there is no max value, this should remain + * unset. + * + * @return A double maximum value for the config. + */ + double max() default Double.MAX_VALUE; } diff --git a/src/main/java/com/enderio/core/common/config/annot/RestartReq.java b/src/main/java/com/enderio/core/common/config/annot/RestartReq.java index d896ae5..02f376e 100644 --- a/src/main/java/com/enderio/core/common/config/annot/RestartReq.java +++ b/src/main/java/com/enderio/core/common/config/annot/RestartReq.java @@ -9,20 +9,20 @@ import java.lang.annotation.Target; import com.enderio.core.common.config.AbstractConfigHandler.RestartReqs; /** - * Represents the restart requirements of a config value. Use this if your config will have no effect if changed while the game is running. Has no + * Represents the restart requirements of a config value. Use this if your + * config will have no effect if changed while the game is running. Has no * effect is this field is not also annotated with {@link Config}. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Documented -public @interface RestartReq -{ - /** - * What requirements this config has for restarting the game. - * - * @see RestartReqs#NONE - * @see RestartReqs#REQUIRES_WORLD_RESTART - * @see RestartReqs#REQUIRES_MC_RESTART - */ - RestartReqs value() default RestartReqs.NONE; +public @interface RestartReq { + /** + * What requirements this config has for restarting the game. + * + * @see RestartReqs#NONE + * @see RestartReqs#REQUIRES_WORLD_RESTART + * @see RestartReqs#REQUIRES_MC_RESTART + */ + RestartReqs value() default RestartReqs.NONE; } diff --git a/src/main/java/com/enderio/core/common/enchant/EnchantAutoSmelt.java b/src/main/java/com/enderio/core/common/enchant/EnchantAutoSmelt.java index d08a31f..a4bde07 100644 --- a/src/main/java/com/enderio/core/common/enchant/EnchantAutoSmelt.java +++ b/src/main/java/com/enderio/core/common/enchant/EnchantAutoSmelt.java @@ -10,74 +10,60 @@ import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; -public class EnchantAutoSmelt extends Enchantment implements IAdvancedEnchant -{ - public static final EnchantAutoSmelt INSTANCE = new EnchantAutoSmelt(ConfigHandler.enchantIDAutoSmelt); +public class EnchantAutoSmelt extends Enchantment implements IAdvancedEnchant { + public static final EnchantAutoSmelt INSTANCE = new EnchantAutoSmelt(ConfigHandler.enchantIDAutoSmelt); - private EnchantAutoSmelt(int id) - { - super(id, 2, EnumEnchantmentType.breakable); - } + private EnchantAutoSmelt(int id) { + super(id, 2, EnumEnchantmentType.breakable); + } - @Override - public int getMaxEnchantability(int level) - { - return super.getMaxEnchantability(level) + 30; - } + @Override + public int getMaxEnchantability(int level) { + return super.getMaxEnchantability(level) + 30; + } - @Override - public int getMinEnchantability(int level) - { - return super.getMinEnchantability(level); - } + @Override + public int getMinEnchantability(int level) { + return super.getMinEnchantability(level); + } - @Override - public int getMaxLevel() - { - return 1; - } + @Override + public int getMaxLevel() { + return 1; + } - @Override - public boolean canApply(ItemStack stack) - { - return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor); - } + @Override + public boolean canApply(ItemStack stack) { + return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor); + } - @Override - public String getName() - { - return "enchantment.autosmelt"; - } + @Override + public String getName() { + return "enchantment.autosmelt"; + } - @Override - public boolean isAllowedOnBooks() - { - return ConfigHandler.allowAutoSmelt; - } + @Override + public boolean isAllowedOnBooks() { + return ConfigHandler.allowAutoSmelt; + } - @Override - public String[] getTooltipDetails(ItemStack stack) - { - return new String[] { EnderCore.lang.localize("enchantment.autosmelt.tooltip", false) }; - } + @Override + public String[] getTooltipDetails(ItemStack stack) { + return new String[] { EnderCore.lang.localize("enchantment.autosmelt.tooltip", false) }; + } - public void register() - { - if (ConfigHandler.allowAutoSmelt) - { - FMLInterModComms.sendMessage("EnderIO", "recipe:enchanter", - "\n\n"); - } - else - { - Enchantment.enchantmentsList[this.effectId] = null; - } + public void register() { + if (ConfigHandler.allowAutoSmelt) { + FMLInterModComms.sendMessage("EnderIO", "recipe:enchanter", + "\n\n"); + } else { + Enchantment.enchantmentsList[this.effectId] = null; } + } - public boolean canApplyTogether(Enchantment ench) - { - return super.canApplyTogether(ench) && ench.effectId != silkTouch.effectId - && ((ench.effectId != fortune.effectId) || ConfigHandler.allowAutoSmeltWithFortune); - } + public boolean canApplyTogether(Enchantment ench) { + return super.canApplyTogether(ench) && ench.effectId != silkTouch.effectId + && ((ench.effectId != fortune.effectId) || ConfigHandler.allowAutoSmeltWithFortune); + } } diff --git a/src/main/java/com/enderio/core/common/enchant/EnchantXPBoost.java b/src/main/java/com/enderio/core/common/enchant/EnchantXPBoost.java index b424eb3..0e7dcbb 100644 --- a/src/main/java/com/enderio/core/common/enchant/EnchantXPBoost.java +++ b/src/main/java/com/enderio/core/common/enchant/EnchantXPBoost.java @@ -10,67 +10,54 @@ import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.event.FMLInterModComms; -public class EnchantXPBoost extends Enchantment implements IAdvancedEnchant -{ - public static final EnchantXPBoost INSTANCE = new EnchantXPBoost(ConfigHandler.enchantIDXPBoost); +public class EnchantXPBoost extends Enchantment implements IAdvancedEnchant { + public static final EnchantXPBoost INSTANCE = new EnchantXPBoost(ConfigHandler.enchantIDXPBoost); - private EnchantXPBoost(int id) - { - super(id, 2, EnumEnchantmentType.breakable); - } + private EnchantXPBoost(int id) { + super(id, 2, EnumEnchantmentType.breakable); + } - @Override - public int getMaxEnchantability(int level) - { - return super.getMaxEnchantability(level) + 30; - } + @Override + public int getMaxEnchantability(int level) { + return super.getMaxEnchantability(level) + 30; + } - @Override - public int getMinEnchantability(int level) - { - return super.getMinEnchantability(level); - } + @Override + public int getMinEnchantability(int level) { + return super.getMinEnchantability(level); + } - @Override - public int getMaxLevel() - { - return 3; - } + @Override + public int getMaxLevel() { + return 3; + } - @Override - public boolean canApply(ItemStack stack) - { - return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor); - } + @Override + public boolean canApply(ItemStack stack) { + return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor); + } - @Override - public String getName() - { - return "enchantment.xpboost"; - } + @Override + public String getName() { + return "enchantment.xpboost"; + } - @Override - public boolean isAllowedOnBooks() - { - return ConfigHandler.allowXPBoost; - } + @Override + public boolean isAllowedOnBooks() { + return ConfigHandler.allowXPBoost; + } - @Override - public String[] getTooltipDetails(ItemStack stack) - { - return new String[] { EnderCore.lang.localize("enchantment.xpboost.tooltip", false) }; - } + @Override + public String[] getTooltipDetails(ItemStack stack) { + return new String[] { EnderCore.lang.localize("enchantment.xpboost.tooltip", false) }; + } - public void register() - { - if (ConfigHandler.allowXPBoost) - { - FMLInterModComms.sendMessage("EnderIO", "recipe:enchanter", - "\n\n"); - } - else - { - Enchantment.enchantmentsList[this.effectId] = null; - } + public void register() { + if (ConfigHandler.allowXPBoost) { + FMLInterModComms.sendMessage("EnderIO", "recipe:enchanter", + "\n\n"); + } else { + Enchantment.enchantmentsList[this.effectId] = null; } + } } diff --git a/src/main/java/com/enderio/core/common/event/ArrowUpdateEvent.java b/src/main/java/com/enderio/core/common/event/ArrowUpdateEvent.java index ae5921d..fd1441a 100644 --- a/src/main/java/com/enderio/core/common/event/ArrowUpdateEvent.java +++ b/src/main/java/com/enderio/core/common/event/ArrowUpdateEvent.java @@ -15,10 +15,8 @@ import cpw.mods.fml.common.eventhandler.Cancelable; *
* This event is fired on the {@link MinecraftForge#EVENT_BUS}.
**/ -public class ArrowUpdateEvent extends EntityEvent -{ - public ArrowUpdateEvent(Entity entity) - { - super(entity); - } +public class ArrowUpdateEvent extends EntityEvent { + public ArrowUpdateEvent(Entity entity) { + super(entity); + } } diff --git a/src/main/java/com/enderio/core/common/event/ConfigFileChangedEvent.java b/src/main/java/com/enderio/core/common/event/ConfigFileChangedEvent.java index 176bc74..91fcd5d 100644 --- a/src/main/java/com/enderio/core/common/event/ConfigFileChangedEvent.java +++ b/src/main/java/com/enderio/core/common/event/ConfigFileChangedEvent.java @@ -19,18 +19,15 @@ import cpw.mods.fml.client.event.ConfigChangedEvent; * If setSuccessful() is not called, the event post will be * considered a failure! */ -public class ConfigFileChangedEvent extends ConfigChangedEvent -{ - @Getter - private boolean successful; +public class ConfigFileChangedEvent extends ConfigChangedEvent { + @Getter + private boolean successful; - public ConfigFileChangedEvent(String modID) - { - super(modID, "null", true, false); - } + public ConfigFileChangedEvent(String modID) { + super(modID, "null", true, false); + } - public void setSuccessful() - { - this.successful = true; - } + public void setSuccessful() { + this.successful = true; + } } diff --git a/src/main/java/com/enderio/core/common/event/ItemStackEvent.java b/src/main/java/com/enderio/core/common/event/ItemStackEvent.java index a23a93f..9b3b0cc 100644 --- a/src/main/java/com/enderio/core/common/event/ItemStackEvent.java +++ b/src/main/java/com/enderio/core/common/event/ItemStackEvent.java @@ -17,52 +17,46 @@ import cpw.mods.fml.common.eventhandler.Event; * All children of this event are fired on the {@link MinecraftForge#EVENT_BUS}.
**/ @RequiredArgsConstructor -public class ItemStackEvent extends Event -{ - public final ItemStack item; +public class ItemStackEvent extends Event { + public final ItemStack item; - /** - * ItemEnchantabilityEvent is fired when calculating an Item's - * enchantability.
- *
- * This event is not {@link Cancelable}.
- *
- * {@link #enchantability} will be the final value returned for these - * calculations, and is provided with the base enchantability when the event - * is first fired.
- * This event is fired on the {@link MinecraftForge#EVENT_BUS}.
- **/ - public static class ItemEnchantabilityEvent extends ItemStackEvent - { - public int enchantability; + /** + * ItemEnchantabilityEvent is fired when calculating an Item's enchantability.
+ *
+ * This event is not {@link Cancelable}.
+ *
+ * {@link #enchantability} will be the final value returned for these + * calculations, and is provided with the base enchantability when the event + * is first fired.
+ * This event is fired on the {@link MinecraftForge#EVENT_BUS}.
+ **/ + public static class ItemEnchantabilityEvent extends ItemStackEvent { + public int enchantability; - public ItemEnchantabilityEvent(ItemStack itemStack, int baseEnchantability) - { - super(itemStack); - enchantability = baseEnchantability; - } + public ItemEnchantabilityEvent(ItemStack itemStack, int baseEnchantability) { + super(itemStack); + enchantability = baseEnchantability; } + } - /** - * ItemRarityEvent is fired when calculating an Item's Rarity. (Text color - * for the item name in tooltips)
- * This event is fired whenever vanilla Minecraft determines that an entity
- *
- * This event is not {@link Cancelable}.
- *
- * {@link #rarity} will be the final value returned for these calculations, - * and is provided with the normal rarity from Item.getRarity() when the - * event is first fired.
- * This event is fired on the {@link MinecraftForge#EVENT_BUS}.
- **/ - public static class ItemRarityEvent extends ItemStackEvent - { - public EnumRarity rarity; + /** + * ItemRarityEvent is fired when calculating an Item's Rarity. (Text color for + * the item name in tooltips)
+ * This event is fired whenever vanilla Minecraft determines that an entity
+ *
+ * This event is not {@link Cancelable}.
+ *
+ * {@link #rarity} will be the final value returned for these calculations, + * and is provided with the normal rarity from Item.getRarity() when the event + * is first fired.
+ * This event is fired on the {@link MinecraftForge#EVENT_BUS}.
+ **/ + public static class ItemRarityEvent extends ItemStackEvent { + public EnumRarity rarity; - public ItemRarityEvent(ItemStack itemStack, EnumRarity baseRarity) - { - super(itemStack); - rarity = baseRarity; - } + public ItemRarityEvent(ItemStack itemStack, EnumRarity baseRarity) { + super(itemStack); + rarity = baseRarity; } + } } diff --git a/src/main/java/com/enderio/core/common/handlers/FireworkHandler.java b/src/main/java/com/enderio/core/common/handlers/FireworkHandler.java index 0693e45..4a0529a 100644 --- a/src/main/java/com/enderio/core/common/handlers/FireworkHandler.java +++ b/src/main/java/com/enderio/core/common/handlers/FireworkHandler.java @@ -23,63 +23,52 @@ import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent; import static java.util.Calendar.*; @Handler -public class FireworkHandler -{ - @SubscribeEvent - public void onAchievement(AchievementEvent event) - { - StatisticsFile file = ((EntityPlayerMP) event.entityPlayer).func_147099_x(); - if (!event.entity.worldObj.isRemote && file.canUnlockAchievement(event.achievement) && !file.hasAchievementUnlocked(event.achievement) - && ConfigHandler.betterAchievements) - { - event.entityPlayer.getEntityData().setInteger("fireworksLeft", 9); - event.entityPlayer.getEntityData().setBoolean("fireworkDelay", false); +public class FireworkHandler { + @SubscribeEvent + public void onAchievement(AchievementEvent event) { + StatisticsFile file = ((EntityPlayerMP) event.entityPlayer).func_147099_x(); + if (!event.entity.worldObj.isRemote && file.canUnlockAchievement(event.achievement) && !file.hasAchievementUnlocked(event.achievement) + && ConfigHandler.betterAchievements) { + event.entityPlayer.getEntityData().setInteger("fireworksLeft", 9); + event.entityPlayer.getEntityData().setBoolean("fireworkDelay", false); + } + } + + @SubscribeEvent + public void onPlayerTick(PlayerTickEvent event) { + EntityPlayer player = event.player; + + if (!player.worldObj.isRemote && event.phase == Phase.END) { + if (player.worldObj.getTotalWorldTime() % 100 == 0) { + Calendar cal = Calendar.getInstance(); + if (cal.get(DAY_OF_MONTH) == 1 && cal.get(MONTH) == JANUARY + && !player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).getBoolean("celebrated")) { + player.getEntityData().setInteger("fireworksLeft", 15); + player.getEntityData().setBoolean("fireworkDelay", false); + NBTTagCompound tag = player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG); + tag.setBoolean("celebrated", true); + player.getEntityData().setTag(EntityPlayer.PERSISTED_NBT_TAG, tag); + player.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + EnderCore.lang.localize("celebrate"))); } - } + } - @SubscribeEvent - public void onPlayerTick(PlayerTickEvent event) - { - EntityPlayer player = event.player; + int fireworksLeft = player.getEntityData().getInteger("fireworksLeft"); + if (fireworksLeft > 0 && (!player.getEntityData().getBoolean("fireworkDelay") || player.worldObj.getTotalWorldTime() % 20 == 0)) { + BlockCoord pos = getBlockCoord(player); + pos = pos.withY(pos.y + 2); + EntityUtil.spawnFirework(pos, player.worldObj.provider.dimensionId, 12); + player.getEntityData().setInteger("fireworksLeft", fireworksLeft - 1); - if (!player.worldObj.isRemote && event.phase == Phase.END) - { - if (player.worldObj.getTotalWorldTime() % 100 == 0) - { - Calendar cal = Calendar.getInstance(); - if (cal.get(DAY_OF_MONTH) == 1 && cal.get(MONTH) == JANUARY && !player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).getBoolean("celebrated")) - { - player.getEntityData().setInteger("fireworksLeft", 15); - player.getEntityData().setBoolean("fireworkDelay", false); - NBTTagCompound tag = player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG); - tag.setBoolean("celebrated", true); - player.getEntityData().setTag(EntityPlayer.PERSISTED_NBT_TAG, tag); - player.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + EnderCore.lang.localize("celebrate"))); - } - } - - int fireworksLeft = player.getEntityData().getInteger("fireworksLeft"); - if (fireworksLeft > 0 && (!player.getEntityData().getBoolean("fireworkDelay") || player.worldObj.getTotalWorldTime() % 20 == 0)) - { - BlockCoord pos = getBlockCoord(player); - pos = pos.withY(pos.y + 2); - EntityUtil.spawnFirework(pos, player.worldObj.provider.dimensionId, 12); - player.getEntityData().setInteger("fireworksLeft", fireworksLeft - 1); - - if (fireworksLeft > 5) - { - player.getEntityData().setBoolean("fireworkDelay", true); - } - else - { - player.getEntityData().setBoolean("fireworkDelay", false); - } - } + if (fireworksLeft > 5) { + player.getEntityData().setBoolean("fireworkDelay", true); + } else { + player.getEntityData().setBoolean("fireworkDelay", false); } + } } + } - private BlockCoord getBlockCoord(EntityPlayer player) - { - return new BlockCoord((int) Math.floor(player.posX), (int) Math.floor(player.posY), (int) Math.floor(player.posZ)); - } + private BlockCoord getBlockCoord(EntityPlayer player) { + return new BlockCoord((int) Math.floor(player.posX), (int) Math.floor(player.posY), (int) Math.floor(player.posZ)); + } } diff --git a/src/main/java/com/enderio/core/common/handlers/RightClickCropHandler.java b/src/main/java/com/enderio/core/common/handlers/RightClickCropHandler.java index f84c2fa..47906e5 100644 --- a/src/main/java/com/enderio/core/common/handlers/RightClickCropHandler.java +++ b/src/main/java/com/enderio/core/common/handlers/RightClickCropHandler.java @@ -19,97 +19,78 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.registry.GameRegistry; @Handler -public class RightClickCropHandler -{ - @NoArgsConstructor - public static class PlantInfo - { - public String seed; - public String block; - public int meta = 7; - public int resetMeta = 0; +public class RightClickCropHandler { + @NoArgsConstructor + public static class PlantInfo { + public String seed; + public String block; + public int meta = 7; + public int resetMeta = 0; - private transient ItemStack seedStack; - private transient Block blockInst; + private transient ItemStack seedStack; + private transient Block blockInst; - public PlantInfo(String seed, String block, int meta, int resetMeta) - { - this.seed = seed; - this.block = block; - this.meta = meta; - this.resetMeta = resetMeta; + public PlantInfo(String seed, String block, int meta, int resetMeta) { + this.seed = seed; + this.block = block; + this.meta = meta; + this.resetMeta = resetMeta; + } + + public void init() { + seedStack = ItemUtil.parseStringIntoItemStack(seed); + String[] blockinfo = block.split(":"); + blockInst = GameRegistry.findBlock(blockinfo[0], blockinfo[1]); + } + } + + private List plants = Lists.newArrayList(); + + private PlantInfo currentPlant = null; + + public static final RightClickCropHandler INSTANCE = new RightClickCropHandler(); + + private RightClickCropHandler() { + } + + public void addCrop(PlantInfo info) { + plants.add(info); + } + + @SubscribeEvent + public void handleCropRightClick(PlayerInteractEvent event) { + int x = event.x, y = event.y, z = event.z; + Block block = event.world.getBlock(x, y, z); + int meta = event.world.getBlockMetadata(x, y, z); + if (ConfigHandler.allowCropRC && event.action == Action.RIGHT_CLICK_BLOCK && (event.entityPlayer.getHeldItem() == null || !event.entityPlayer.isSneaking())) { + for (PlantInfo info : plants) { + if (info.blockInst == block && meta == info.meta) { + if (event.world.isRemote) { + event.entityPlayer.swingItem(); + } else { + currentPlant = info; + block.dropBlockAsItem(event.world, x, y, z, meta, 0); + currentPlant = null; + event.world.setBlockMetadataWithNotify(x, y, z, info.resetMeta, 3); + event.setCanceled(true); + } + break; } + } + } + } - public void init() - { - seedStack = ItemUtil.parseStringIntoItemStack(seed); - String[] blockinfo = block.split(":"); - blockInst = GameRegistry.findBlock(blockinfo[0], blockinfo[1]); - } - } - - private List plants = Lists.newArrayList(); - - private PlantInfo currentPlant = null; - - public static final RightClickCropHandler INSTANCE = new RightClickCropHandler(); - - private RightClickCropHandler() - { - } - - public void addCrop(PlantInfo info) - { - plants.add(info); - } - - @SubscribeEvent - public void handleCropRightClick(PlayerInteractEvent event) - { - int x = event.x, y = event.y, z = event.z; - Block block = event.world.getBlock(x, y, z); - int meta = event.world.getBlockMetadata(x, y, z); - if (ConfigHandler.allowCropRC && event.action == Action.RIGHT_CLICK_BLOCK - && (event.entityPlayer.getHeldItem() == null || !event.entityPlayer.isSneaking())) - { - for (PlantInfo info : plants) - { - if (info.blockInst == block && meta == info.meta) - { - if (event.world.isRemote) - { - event.entityPlayer.swingItem(); - } - else - { - currentPlant = info; - block.dropBlockAsItem(event.world, x, y, z, meta, 0); - currentPlant = null; - event.world.setBlockMetadataWithNotify(x, y, z, info.resetMeta, 3); - event.setCanceled(true); - } - break; - } - } - } - } - - @SubscribeEvent - public void onHarvestDrop(HarvestDropsEvent event) - { - if (currentPlant != null) - { - for (int i = 0; i < event.drops.size(); i++) - { - ItemStack stack = event.drops.get(i); - if (stack.getItem() == currentPlant.seedStack.getItem() - && (currentPlant.seedStack.getItemDamage() == OreDictionary.WILDCARD_VALUE || stack.getItemDamage() == currentPlant.seedStack - .getItemDamage())) - { - event.drops.remove(i); - break; - } - } + @SubscribeEvent + public void onHarvestDrop(HarvestDropsEvent event) { + if (currentPlant != null) { + for (int i = 0; i < event.drops.size(); i++) { + ItemStack stack = event.drops.get(i); + if (stack.getItem() == currentPlant.seedStack.getItem() + && (currentPlant.seedStack.getItemDamage() == OreDictionary.WILDCARD_VALUE || stack.getItemDamage() == currentPlant.seedStack.getItemDamage())) { + event.drops.remove(i); + break; } + } } + } } diff --git a/src/main/java/com/enderio/core/common/handlers/XPBoostHandler.java b/src/main/java/com/enderio/core/common/handlers/XPBoostHandler.java index e222aa6..a346855 100644 --- a/src/main/java/com/enderio/core/common/handlers/XPBoostHandler.java +++ b/src/main/java/com/enderio/core/common/handlers/XPBoostHandler.java @@ -26,132 +26,105 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.ReflectionHelper; @Handler -public class XPBoostHandler -{ - private static final Method getExperiencePoints = ReflectionHelper.findMethod(EntityLivingBase.class, null, - new String[] { "e", "func_70693_a", "getExperiencePoints" }, EntityPlayer.class); - - private static final String NBT_KEY = "ttCore:xpboost"; +public class XPBoostHandler { + private static final Method getExperiencePoints = ReflectionHelper.findMethod(EntityLivingBase.class, null, new String[] { "e", "func_70693_a", + "getExperiencePoints" }, EntityPlayer.class); - @SubscribeEvent - public void handleEntityKill(LivingDeathEvent event) - { - EntityLivingBase entity = event.entityLiving; - Entity killer = event.source.getSourceOfDamage(); + private static final String NBT_KEY = "ttCore:xpboost"; - if (!entity.worldObj.isRemote && killer != null) - { - if (killer instanceof EntityPlayer) - { - scheduleXP(entity, getXPBoost(entity, (EntityPlayer) killer)); - } - else if (killer instanceof EntityArrow && ((EntityArrow) killer).shootingEntity instanceof EntityPlayer) - { - NBTTagCompound tag = killer.getEntityData(); - if (tag.hasKey(NBT_KEY) && tag.getInteger(NBT_KEY) >= 0) - { - int level = tag.getInteger(NBT_KEY); - EntityArrow arrow = (EntityArrow) killer; - scheduleXP(entity, getXPBoost(entity, (EntityPlayer) arrow.shootingEntity, level)); - } - } + @SubscribeEvent + public void handleEntityKill(LivingDeathEvent event) { + EntityLivingBase entity = event.entityLiving; + Entity killer = event.source.getSourceOfDamage(); + + if (!entity.worldObj.isRemote && killer != null) { + if (killer instanceof EntityPlayer) { + scheduleXP(entity, getXPBoost(entity, (EntityPlayer) killer)); + } else if (killer instanceof EntityArrow && ((EntityArrow) killer).shootingEntity instanceof EntityPlayer) { + NBTTagCompound tag = killer.getEntityData(); + if (tag.hasKey(NBT_KEY) && tag.getInteger(NBT_KEY) >= 0) { + int level = tag.getInteger(NBT_KEY); + EntityArrow arrow = (EntityArrow) killer; + scheduleXP(entity, getXPBoost(entity, (EntityPlayer) arrow.shootingEntity, level)); } + } } - - @SubscribeEvent - public void handleArrowFire(EntityJoinWorldEvent event) - { - if (event.entity instanceof EntityArrow) - { - EntityArrow arrow = (EntityArrow) event.entity; - if (arrow.shootingEntity != null && arrow.shootingEntity instanceof EntityPlayer) - { - arrow.getEntityData().setInteger(NBT_KEY, getXPBoostLevel(((EntityPlayer)arrow.shootingEntity).getCurrentEquippedItem())); - } - } - } - - @SubscribeEvent - public void handleBlockBreak(BreakEvent event) - { - ItemStack held = event.getPlayer().getCurrentEquippedItem(); - if (held != null) - { - int level = getXPBoostLevel(held); - int fortune = EnchantmentHelper.getEnchantmentLevel(Enchantment.fortune.effectId, held); + } - if (level >= 0) - { - int xp = event.block.getExpDrop(event.world, event.blockMetadata, fortune); - if (xp > 0) - { - event.world.spawnEntityInWorld(new EntityXPOrb(event.world, event.x + 0.5, event.y + 0.5, event.z + 0.5, getXPBoost(xp, level))); - } - } + @SubscribeEvent + public void handleArrowFire(EntityJoinWorldEvent event) { + if (event.entity instanceof EntityArrow) { + EntityArrow arrow = (EntityArrow) event.entity; + if (arrow.shootingEntity != null && arrow.shootingEntity instanceof EntityPlayer) { + arrow.getEntityData().setInteger(NBT_KEY, getXPBoostLevel(((EntityPlayer) arrow.shootingEntity).getCurrentEquippedItem())); + } + } + } + + @SubscribeEvent + public void handleBlockBreak(BreakEvent event) { + ItemStack held = event.getPlayer().getCurrentEquippedItem(); + if (held != null) { + int level = getXPBoostLevel(held); + int fortune = EnchantmentHelper.getEnchantmentLevel(Enchantment.fortune.effectId, held); + + if (level >= 0) { + int xp = event.block.getExpDrop(event.world, event.blockMetadata, fortune); + if (xp > 0) { + event.world.spawnEntityInWorld(new EntityXPOrb(event.world, event.x + 0.5, event.y + 0.5, event.z + 0.5, getXPBoost(xp, level))); } + } + } + } + + private int getXPBoost(EntityLivingBase killed, EntityPlayer player) { + return getXPBoost(killed, player, getXPBoostLevel(player.getCurrentEquippedItem())); + } + + @SneakyThrows + private int getXPBoost(EntityLivingBase killed, EntityPlayer player, int level) { + if (level >= 0) { + int xp = (Integer) getExperiencePoints.invoke(killed, player); + return getXPBoost(xp, level); + } + return 0; + } + + private int getXPBoost(int xp, int level) { + return Math.round(xp * ((float) Math.log10(level + 1) * 2)); + } + + @SuppressWarnings("unchecked") + private int getXPBoostLevel(ItemStack weapon) { + if (weapon == null) { + return -1; } - private int getXPBoost(EntityLivingBase killed, EntityPlayer player) - { - return getXPBoost(killed, player, getXPBoostLevel(player.getCurrentEquippedItem())); + Map enchants = EnchantmentHelper.getEnchantments(weapon); + for (int i : enchants.keySet()) { + Enchantment enchant = Enchantment.enchantmentsList[i]; + if (enchant == EnchantXPBoost.INSTANCE) { + return enchants.get(i); + } + } + return -1; + } + + private void scheduleXP(Entity entity, int boost) { + scheduleXP(entity.worldObj, entity.posX, entity.posY, entity.posZ, boost); + } + + private void scheduleXP(final World world, final double x, final double y, final double z, final int boost) { + if (boost <= 0) { + return; } - @SneakyThrows - private int getXPBoost(EntityLivingBase killed, EntityPlayer player, int level) - { - if (level >= 0) - { - int xp = (Integer) getExperiencePoints.invoke(killed, player); - return getXPBoost(xp, level); - } - return 0; - } - - private int getXPBoost(int xp, int level) - { - return Math.round(xp * ((float) Math.log10(level + 1) * 2)); - } - - @SuppressWarnings("unchecked") - private int getXPBoostLevel(ItemStack weapon) - { - if (weapon == null) - { - return -1; - } - - Map enchants = EnchantmentHelper.getEnchantments(weapon); - for (int i : enchants.keySet()) - { - Enchantment enchant = Enchantment.enchantmentsList[i]; - if (enchant == EnchantXPBoost.INSTANCE) - { - return enchants.get(i); - } - } - return -1; - } - - private void scheduleXP(Entity entity, int boost) - { - scheduleXP(entity.worldObj, entity.posX, entity.posY, entity.posZ, boost); - } - - private void scheduleXP(final World world, final double x, final double y, final double z, final int boost) - { - if (boost <= 0) - { - return; - } - - Scheduler.instance().schedule(20, new Runnable() - { - @Override - public void run() - { - world.spawnEntityInWorld(new EntityXPOrb(world, x, y, z, boost)); - } - }); - } + Scheduler.instance().schedule(20, new Runnable() { + @Override + public void run() { + world.spawnEntityInWorld(new EntityXPOrb(world, x, y, z, boost)); + } + }); + } } diff --git a/src/main/java/com/enderio/core/common/imc/IMCRegistry.java b/src/main/java/com/enderio/core/common/imc/IMCRegistry.java index aef4955..a72fd1c 100644 --- a/src/main/java/com/enderio/core/common/imc/IMCRegistry.java +++ b/src/main/java/com/enderio/core/common/imc/IMCRegistry.java @@ -8,59 +8,48 @@ import com.google.common.collect.Lists; import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; -public class IMCRegistry -{ - public interface IIMC - { - String getKey(); +public class IMCRegistry { + public interface IIMC { + String getKey(); - void act(IMCMessage msg); + void act(IMCMessage msg); + } + + public static abstract class IMCBase implements IIMC { + private String key; + + public IMCBase(String key) { + this.key = key; } - - public static abstract class IMCBase implements IIMC - { - private String key; - public IMCBase(String key) - { - this.key = key; + @Override + public String getKey() { + return key; + } + } + + public static final IMCRegistry INSTANCE = new IMCRegistry(); + + private List handlers = Lists.newArrayList(); + + private IMCRegistry() { + } + + public void addIMCHandler(IIMC handler) { + handlers.add(handler); + } + + public void handleEvent(IMCEvent event) { + for (IIMC handler : handlers) { + for (IMCMessage msg : event.getMessages()) { + if (msg.key.equals(handler.getKey())) { + handler.act(msg); } + } + } + } - @Override - public String getKey() - { - return key; - } - } - - public static final IMCRegistry INSTANCE = new IMCRegistry(); - - private List handlers = Lists.newArrayList(); - - private IMCRegistry() - {} - - public void addIMCHandler(IIMC handler) - { - handlers.add(handler); - } - - public void handleEvent(IMCEvent event) - { - for (IIMC handler : handlers) - { - for (IMCMessage msg : event.getMessages()) - { - if (msg.key.equals(handler.getKey())) - { - handler.act(msg); - } - } - } - } - - public void init() - { - addIMCHandler(new IMCRightClickCrop()); - } + public void init() { + addIMCHandler(new IMCRightClickCrop()); + } } diff --git a/src/main/java/com/enderio/core/common/imc/handlers/IMCRightClickCrop.java b/src/main/java/com/enderio/core/common/imc/handlers/IMCRightClickCrop.java index 86fd6a3..8b7be53 100644 --- a/src/main/java/com/enderio/core/common/imc/handlers/IMCRightClickCrop.java +++ b/src/main/java/com/enderio/core/common/imc/handlers/IMCRightClickCrop.java @@ -7,30 +7,25 @@ import com.enderio.core.common.imc.IMCRegistry.IMCBase; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; -public class IMCRightClickCrop extends IMCBase -{ - public IMCRightClickCrop() - { - super(IMC.ADD_RIGHT_CLICK_CROP); +public class IMCRightClickCrop extends IMCBase { + public IMCRightClickCrop() { + super(IMC.ADD_RIGHT_CLICK_CROP); + } + + @Override + public void act(IMCMessage msg) { + if (!msg.isStringMessage()) { + return; } - @Override - public void act(IMCMessage msg) - { - if (!msg.isStringMessage()) - { - return; - } + String[] data = msg.getStringValue().split("\\|"); - String[] data = msg.getStringValue().split("\\|"); - - if (data.length != 3) - { - return; - } - - PlantInfo plantinfo = new PlantInfo(data[0], data[1], Integer.parseInt(data[2]), Integer.parseInt(data[3])); - plantinfo.init(); - RightClickCropHandler.INSTANCE.addCrop(plantinfo); + if (data.length != 3) { + return; } + + PlantInfo plantinfo = new PlantInfo(data[0], data[1], Integer.parseInt(data[2]), Integer.parseInt(data[3])); + plantinfo.init(); + RightClickCropHandler.INSTANCE.addCrop(plantinfo); + } } diff --git a/src/main/java/com/enderio/core/common/network/CompressedDataInput.java b/src/main/java/com/enderio/core/common/network/CompressedDataInput.java index be2e448..34d8f10 100644 --- a/src/main/java/com/enderio/core/common/network/CompressedDataInput.java +++ b/src/main/java/com/enderio/core/common/network/CompressedDataInput.java @@ -24,7 +24,7 @@ public class CompressedDataInput extends DataInputStream { b = readUnsignedByte(); res |= (b & 0x7F) << shift; shift += 7; - } while(b >= 0x80); + } while (b >= 0x80); return res; } } diff --git a/src/main/java/com/enderio/core/common/network/CompressedDataOutput.java b/src/main/java/com/enderio/core/common/network/CompressedDataOutput.java index 21a03b3..0cdb442 100644 --- a/src/main/java/com/enderio/core/common/network/CompressedDataOutput.java +++ b/src/main/java/com/enderio/core/common/network/CompressedDataOutput.java @@ -20,7 +20,7 @@ public class CompressedDataOutput extends DataOutputStream { } public void writeVariable(int value) throws IOException { - while((value & ~0x7F) != 0) { + while ((value & ~0x7F) != 0) { writeByte(value | 0x80); value >>= 7; } diff --git a/src/main/java/com/enderio/core/common/network/EnderPacketHandler.java b/src/main/java/com/enderio/core/common/network/EnderPacketHandler.java index 08dddeb..74c53d0 100644 --- a/src/main/java/com/enderio/core/common/network/EnderPacketHandler.java +++ b/src/main/java/com/enderio/core/common/network/EnderPacketHandler.java @@ -13,7 +13,7 @@ import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; public class EnderPacketHandler { - + public static final SimpleNetworkWrapper INSTANCE = new SimpleNetworkWrapper(EnderCore.NAME); public static void init() { diff --git a/src/main/java/com/enderio/core/common/network/MessageTileEntity.java b/src/main/java/com/enderio/core/common/network/MessageTileEntity.java index 57dc7fe..75e72a5 100644 --- a/src/main/java/com/enderio/core/common/network/MessageTileEntity.java +++ b/src/main/java/com/enderio/core/common/network/MessageTileEntity.java @@ -53,6 +53,6 @@ public abstract class MessageTileEntity implements IMessag } protected World getWorld(MessageContext ctx) { - return ctx.getServerHandler().playerEntity.worldObj; + return ctx.getServerHandler().playerEntity.worldObj; } } diff --git a/src/main/java/com/enderio/core/common/network/MessageTileNBT.java b/src/main/java/com/enderio/core/common/network/MessageTileNBT.java index fab2a4d..9500eb5 100644 --- a/src/main/java/com/enderio/core/common/network/MessageTileNBT.java +++ b/src/main/java/com/enderio/core/common/network/MessageTileNBT.java @@ -57,19 +57,19 @@ public class MessageTileNBT implements IMessage, IMessageHandler { } public static class Handler implements IMessageHandler { - + @Override public IMessage onMessage(PacketProgress message, MessageContext ctx) { TileEntity tile = message.getTileEntity(EnderCore.proxy.getClientWorld()); diff --git a/src/main/java/com/enderio/core/common/transform/EnderCoreMethods.java b/src/main/java/com/enderio/core/common/transform/EnderCoreMethods.java index c51272e..6b92bd1 100644 --- a/src/main/java/com/enderio/core/common/transform/EnderCoreMethods.java +++ b/src/main/java/com/enderio/core/common/transform/EnderCoreMethods.java @@ -19,220 +19,165 @@ import com.enderio.core.common.event.ItemStackEvent.ItemEnchantabilityEvent; import com.enderio.core.common.event.ItemStackEvent.ItemRarityEvent; @UtilityClass -public class EnderCoreMethods -{ - public boolean hasVoidParticles(WorldType type, boolean hasSky) - { - if (ConfigHandler.disableVoidFog == 0) - { - return type != WorldType.FLAT && !hasSky; +public class EnderCoreMethods { + public boolean hasVoidParticles(WorldType type, boolean hasSky) { + if (ConfigHandler.disableVoidFog == 0) { + return type != WorldType.FLAT && !hasSky; + } else if (ConfigHandler.disableVoidFog == 1) { + return type != WorldType.FLAT && type != WorldType.DEFAULT && !hasSky; + } else { + return false; + } + } + + public int getMaxAnvilCost() { + return ConfigHandler.anvilMaxLevel; + } + + public int getItemEnchantability(ItemStack stack, int base) { + ItemEnchantabilityEvent event = new ItemEnchantabilityEvent(stack, base); + MinecraftForge.EVENT_BUS.post(event); + return event.enchantability; + } + + public EnumRarity getItemRarity(ItemStack stack) { + ItemRarityEvent event = new ItemRarityEvent(stack, stack.getItem().getRarity(stack)); + MinecraftForge.EVENT_BUS.post(event); + return event.rarity; + } + + public void onArrowUpdate(EntityArrow entity) { + MinecraftForge.EVENT_BUS.post(new ArrowUpdateEvent(entity)); + } + + // mostly copied from ContainerFurnace + public ItemStack transferStackInSlot(ContainerFurnace inv, EntityPlayer p_82846_1_, int p_82846_2_) { + ItemStack itemstack = null; + Slot slot = (Slot) inv.inventorySlots.get(p_82846_2_); + + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (p_82846_2_ == 2) { + if (!mergeItemStack(inv, itemstack1, 3, 39, true)) { + return null; } - else if (ConfigHandler.disableVoidFog == 1) - { - return type != WorldType.FLAT && type != WorldType.DEFAULT && !hasSky; - } - else - { - return false; - } - } - public int getMaxAnvilCost() - { - return ConfigHandler.anvilMaxLevel; - } - - public int getItemEnchantability(ItemStack stack, int base) - { - ItemEnchantabilityEvent event = new ItemEnchantabilityEvent(stack, base); - MinecraftForge.EVENT_BUS.post(event); - return event.enchantability; - } - - public EnumRarity getItemRarity(ItemStack stack) - { - ItemRarityEvent event = new ItemRarityEvent(stack, stack.getItem().getRarity(stack)); - MinecraftForge.EVENT_BUS.post(event); - return event.rarity; - } - - public void onArrowUpdate(EntityArrow entity) - { - MinecraftForge.EVENT_BUS.post(new ArrowUpdateEvent(entity)); - } - - // mostly copied from ContainerFurnace - public ItemStack transferStackInSlot(ContainerFurnace inv, EntityPlayer p_82846_1_, int p_82846_2_) - { - ItemStack itemstack = null; - Slot slot = (Slot) inv.inventorySlots.get(p_82846_2_); - - if (slot != null && slot.getHasStack()) - { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (p_82846_2_ == 2) - { - if (!mergeItemStack(inv, itemstack1, 3, 39, true)) - { - return null; - } - - slot.onSlotChange(itemstack1, itemstack); - } - else if (p_82846_2_ != 1 && p_82846_2_ != 0) - { - // I have moved this check to the beginning - if (TileEntityFurnace.isItemFuel(itemstack1)) - { - if (!mergeItemStack(inv, itemstack1, 1, 2, false)) - { - // Nest this inside so that if the above fails it will - // attempt to do the input slot - if (FurnaceRecipes.smelting().getSmeltingResult(itemstack1) != null) - { - if (!mergeItemStack(inv, itemstack1, 0, 1, false)) - { - return null; - } - } - } - } - else if (FurnaceRecipes.smelting().getSmeltingResult(itemstack1) != null) - { - if (!mergeItemStack(inv, itemstack1, 0, 1, false)) - { - return null; - } - } - else if (p_82846_2_ >= 3 && p_82846_2_ < 30) - { - if (!mergeItemStack(inv, itemstack1, 30, 39, false)) - { - return null; - } - } - else if (p_82846_2_ >= 30 && p_82846_2_ < 39 && !mergeItemStack(inv, itemstack1, 3, 30, false)) - { - return null; - } - } - else if (!mergeItemStack(inv, itemstack1, 3, 39, false)) - { + slot.onSlotChange(itemstack1, itemstack); + } else if (p_82846_2_ != 1 && p_82846_2_ != 0) { + // I have moved this check to the beginning + if (TileEntityFurnace.isItemFuel(itemstack1)) { + if (!mergeItemStack(inv, itemstack1, 1, 2, false)) { + // Nest this inside so that if the above fails it will + // attempt to do the input slot + if (FurnaceRecipes.smelting().getSmeltingResult(itemstack1) != null) { + if (!mergeItemStack(inv, itemstack1, 0, 1, false)) { return null; + } } - - if (itemstack1.stackSize == 0) - { - slot.putStack((ItemStack) null); - } - else - { - slot.onSlotChanged(); - } - - if (itemstack1.stackSize == itemstack.stackSize) - { - return null; - } - - slot.onPickupFromSlot(p_82846_1_, itemstack1); + } + } else if (FurnaceRecipes.smelting().getSmeltingResult(itemstack1) != null) { + if (!mergeItemStack(inv, itemstack1, 0, 1, false)) { + return null; + } + } else if (p_82846_2_ >= 3 && p_82846_2_ < 30) { + if (!mergeItemStack(inv, itemstack1, 30, 39, false)) { + return null; + } + } else if (p_82846_2_ >= 30 && p_82846_2_ < 39 && !mergeItemStack(inv, itemstack1, 3, 30, false)) { + return null; } + } else if (!mergeItemStack(inv, itemstack1, 3, 39, false)) { + return null; + } - return itemstack; + if (itemstack1.stackSize == 0) { + slot.putStack((ItemStack) null); + } else { + slot.onSlotChanged(); + } + + if (itemstack1.stackSize == itemstack.stackSize) { + return null; + } + + slot.onPickupFromSlot(p_82846_1_, itemstack1); } - // copied from Container - private boolean mergeItemStack(Container inv, ItemStack p_75135_1_, int p_75135_2_, int p_75135_3_, boolean p_75135_4_) - { - boolean flag1 = false; - int k = p_75135_2_; + return itemstack; + } - if (p_75135_4_) - { - k = p_75135_3_ - 1; - } + // copied from Container + private boolean mergeItemStack(Container inv, ItemStack p_75135_1_, int p_75135_2_, int p_75135_3_, boolean p_75135_4_) { + boolean flag1 = false; + int k = p_75135_2_; - Slot slot; - ItemStack itemstack1; - - if (p_75135_1_.isStackable()) - { - while (p_75135_1_.stackSize > 0 && (!p_75135_4_ && k < p_75135_3_ || p_75135_4_ && k >= p_75135_2_)) - { - slot = (Slot) inv.inventorySlots.get(k); - itemstack1 = slot.getStack(); - - if (itemstack1 != null && itemstack1.getItem() == p_75135_1_.getItem() - && (!p_75135_1_.getHasSubtypes() || p_75135_1_.getItemDamage() == itemstack1.getItemDamage()) - && ItemStack.areItemStackTagsEqual(p_75135_1_, itemstack1)) - { - int l = itemstack1.stackSize + p_75135_1_.stackSize; - - if (l <= p_75135_1_.getMaxStackSize()) - { - p_75135_1_.stackSize = 0; - itemstack1.stackSize = l; - slot.onSlotChanged(); - flag1 = true; - } - else if (itemstack1.stackSize < p_75135_1_.getMaxStackSize()) - { - p_75135_1_.stackSize -= p_75135_1_.getMaxStackSize() - itemstack1.stackSize; - itemstack1.stackSize = p_75135_1_.getMaxStackSize(); - slot.onSlotChanged(); - flag1 = true; - } - } - - if (p_75135_4_) - { - --k; - } - else - { - ++k; - } - } - } - - if (p_75135_1_.stackSize > 0) - { - if (p_75135_4_) - { - k = p_75135_3_ - 1; - } - else - { - k = p_75135_2_; - } - - while (!p_75135_4_ && k < p_75135_3_ || p_75135_4_ && k >= p_75135_2_) - { - slot = (Slot) inv.inventorySlots.get(k); - itemstack1 = slot.getStack(); - - if (itemstack1 == null) - { - slot.putStack(p_75135_1_.copy()); - slot.onSlotChanged(); - p_75135_1_.stackSize = 0; - flag1 = true; - break; - } - - if (p_75135_4_) - { - --k; - } - else - { - ++k; - } - } - } - - return flag1; + if (p_75135_4_) { + k = p_75135_3_ - 1; } + + Slot slot; + ItemStack itemstack1; + + if (p_75135_1_.isStackable()) { + while (p_75135_1_.stackSize > 0 && (!p_75135_4_ && k < p_75135_3_ || p_75135_4_ && k >= p_75135_2_)) { + slot = (Slot) inv.inventorySlots.get(k); + itemstack1 = slot.getStack(); + + if (itemstack1 != null && itemstack1.getItem() == p_75135_1_.getItem() + && (!p_75135_1_.getHasSubtypes() || p_75135_1_.getItemDamage() == itemstack1.getItemDamage()) + && ItemStack.areItemStackTagsEqual(p_75135_1_, itemstack1)) { + int l = itemstack1.stackSize + p_75135_1_.stackSize; + + if (l <= p_75135_1_.getMaxStackSize()) { + p_75135_1_.stackSize = 0; + itemstack1.stackSize = l; + slot.onSlotChanged(); + flag1 = true; + } else if (itemstack1.stackSize < p_75135_1_.getMaxStackSize()) { + p_75135_1_.stackSize -= p_75135_1_.getMaxStackSize() - itemstack1.stackSize; + itemstack1.stackSize = p_75135_1_.getMaxStackSize(); + slot.onSlotChanged(); + flag1 = true; + } + } + + if (p_75135_4_) { + --k; + } else { + ++k; + } + } + } + + if (p_75135_1_.stackSize > 0) { + if (p_75135_4_) { + k = p_75135_3_ - 1; + } else { + k = p_75135_2_; + } + + while (!p_75135_4_ && k < p_75135_3_ || p_75135_4_ && k >= p_75135_2_) { + slot = (Slot) inv.inventorySlots.get(k); + itemstack1 = slot.getStack(); + + if (itemstack1 == null) { + slot.putStack(p_75135_1_.copy()); + slot.onSlotChanged(); + p_75135_1_.stackSize = 0; + flag1 = true; + break; + } + + if (p_75135_4_) { + --k; + } else { + ++k; + } + } + } + + return flag1; + } } diff --git a/src/main/java/com/enderio/core/common/transform/EnderCorePlugin.java b/src/main/java/com/enderio/core/common/transform/EnderCorePlugin.java index fc0fd79..6fa24db 100644 --- a/src/main/java/com/enderio/core/common/transform/EnderCorePlugin.java +++ b/src/main/java/com/enderio/core/common/transform/EnderCorePlugin.java @@ -7,41 +7,33 @@ import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; @SuppressWarnings("unused") @MCVersion("1.7.10") -@IFMLLoadingPlugin.SortingIndex(Integer.MAX_VALUE) // we want deobf no matter what -public class EnderCorePlugin implements IFMLLoadingPlugin -{ - public static boolean runtimeDeobfEnabled = false; +@IFMLLoadingPlugin.SortingIndex(Integer.MAX_VALUE) +// we want deobf no matter what +public class EnderCorePlugin implements IFMLLoadingPlugin { + public static boolean runtimeDeobfEnabled = false; - @Override - public String[] getASMTransformerClass() - { - return new String[] { - "com.enderio.core.common.transform.EnderCoreTransformer", - "com.enderio.core.common.transform.EnderCoreTransformerClient" - }; - } + @Override + public String[] getASMTransformerClass() { + return new String[] { "com.enderio.core.common.transform.EnderCoreTransformer", "com.enderio.core.common.transform.EnderCoreTransformerClient" }; + } - @Override - public String getModContainerClass() - { - return null; - } + @Override + public String getModContainerClass() { + return null; + } - @Override - public String getSetupClass() - { - return null; - } + @Override + public String getSetupClass() { + return null; + } - @Override - public void injectData(Map data) - { - runtimeDeobfEnabled = (Boolean) data.get("runtimeDeobfuscationEnabled"); - } + @Override + public void injectData(Map data) { + runtimeDeobfEnabled = (Boolean) data.get("runtimeDeobfuscationEnabled"); + } - @Override - public String getAccessTransformerClass() - { - return null; - } + @Override + public String getAccessTransformerClass() { + return null; + } } diff --git a/src/main/java/com/enderio/core/common/transform/EnderCoreTransformer.java b/src/main/java/com/enderio/core/common/transform/EnderCoreTransformer.java index 0d1a05f..9dcf3b2 100644 --- a/src/main/java/com/enderio/core/common/transform/EnderCoreTransformer.java +++ b/src/main/java/com/enderio/core/common/transform/EnderCoreTransformer.java @@ -24,276 +24,229 @@ import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; import static org.objectweb.asm.Opcodes.*; @MCVersion(value = "1.7.10") -public class EnderCoreTransformer implements IClassTransformer -{ - @AllArgsConstructor - protected static class ObfSafeName - { - private String deobf, srg; +public class EnderCoreTransformer implements IClassTransformer { + @AllArgsConstructor + protected static class ObfSafeName { + private String deobf, srg; - public String getName() - { - return EnderCorePlugin.runtimeDeobfEnabled ? srg : deobf; - } - - @Override - public boolean equals(Object obj) - { - if (obj instanceof String) - { - return obj.equals(deobf) || obj.equals(srg); - } - else if (obj instanceof ObfSafeName) - { - return ((ObfSafeName) obj).deobf.equals(deobf) && ((ObfSafeName) obj).srg.equals(srg); - } - return false; - } - - // no hashcode because I'm naughty + public String getName() { + return EnderCorePlugin.runtimeDeobfEnabled ? srg : deobf; } - protected static abstract class Transform - { - abstract void transform(Iterator methods); - } - - private static final String worldTypeClass = "net.minecraft.world.WorldType"; - private static final ObfSafeName voidFogMethod = new ObfSafeName("hasVoidParticles", "func_76564_j"); - private static final String voidFogMethodSig = "(Lnet/minecraft/world/WorldType;Z)Z"; - - private static final String anvilContainerClass = "net.minecraft.inventory.ContainerRepair"; - private static final ObfSafeName anvilContainerMethod = new ObfSafeName("updateRepairOutput", "func_82848_d"); - - private static final String anvilGuiClass = "net.minecraft.client.gui.GuiRepair"; - private static final ObfSafeName anvilGuiMethod = new ObfSafeName("drawGuiContainerForegroundLayer", "func_146979_b"); - - private static final String enchantHelperClass = "net.minecraft.enchantment.EnchantmentHelper"; - private static final String enchantHelperMethodSig = "(Lnet/minecraft/item/ItemStack;I)I"; - private static final ObfSafeName buildEnchantListMethod = new ObfSafeName("buildEnchantmentList", "func_77513_b"); - private static final ObfSafeName calcEnchantabilityMethod = new ObfSafeName("calcItemStackEnchantability", "func_77514_a"); - - private static final String itemStackClass = "net.minecraft.item.ItemStack"; - private static final ObfSafeName itemStackMethod = new ObfSafeName("getRarity", "func_77953_t"); - private static final String itemStackMethodSig = "(Lnet/minecraft/item/ItemStack;)Lnet/minecraft/item/EnumRarity;"; - - private static final String entityArrowClass = "net.minecraft.entity.projectile.EntityArrow"; - private static final ObfSafeName entityArrowMethod = new ObfSafeName("onUpdate", "func_70071_h_"); - private static final String entityArrowMethodSig = "(Lnet/minecraft/entity/projectile/EntityArrow;)V"; - - private static final String containerFurnaceClass = "net.minecraft.inventory.ContainerFurnace"; - private static final ObfSafeName containerFurnaceMethod = new ObfSafeName("transferStackInSlot", "func_82846_b"); - private static final String containerFurnaceMethodSig = "(Lnet/minecraft/inventory/ContainerFurnace;Lnet/minecraft/entity/player/EntityPlayer;I)Lnet/minecraft/item/ItemStack;"; - @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) - { - // Void fog removal - if (transformedName.equals(worldTypeClass)) - { - basicClass = transform(basicClass, worldTypeClass, voidFogMethod, new Transform() - { - @Override - void transform(Iterator methods) - { - while (methods.hasNext()) - { - MethodNode m = methods.next(); - if (voidFogMethod.equals(m.name)) - { - m.instructions.clear(); - - m.instructions.add(new VarInsnNode(ALOAD, 0)); - m.instructions.add(new VarInsnNode(ILOAD, 1)); - m.instructions.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "hasVoidParticles", - voidFogMethodSig, false)); - m.instructions.add(new InsnNode(IRETURN)); - - break; - } - } - } - }); - } - // Anvil max level - else if (transformedName.equals(anvilContainerClass) || transformedName.equals(anvilGuiClass)) - { - basicClass = transform(basicClass, anvilContainerClass, anvilContainerMethod, new Transform() - { - @Override - void transform(Iterator methods) - { - while (methods.hasNext()) - { - MethodNode m = methods.next(); - if (anvilContainerMethod.equals(m.name) || anvilGuiMethod.equals(m.name)) - { - for (int i = 0; i < m.instructions.size(); i++) - { - AbstractInsnNode next = m.instructions.get(i); - - next = m.instructions.get(i); - if (next instanceof IntInsnNode && ((IntInsnNode) next).operand == 40) - { - m.instructions.set(next, new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", - "getMaxAnvilCost", "()I", false)); - } - } - } - } - } - }); - } - // Item Enchantability Event - else if (transformedName.equals(enchantHelperClass)) - { - final Map data = new HashMap(); - data.put(buildEnchantListMethod.getName(), new int[] { 1, 4 }); - data.put(calcEnchantabilityMethod.getName(), new int[] { 3, 5 }); - Transform transformer = new Transform() - { - @Override - void transform(Iterator methods) - { - while (methods.hasNext()) - { - MethodNode m = methods.next(); - if (data.keySet().contains(m.name)) - { - int[] indeces = data.get(m.name); - for (int i = 0; i < m.instructions.size(); i++) - { - AbstractInsnNode next = m.instructions.get(i); - if (next instanceof VarInsnNode) - { - VarInsnNode varNode = (VarInsnNode) next; - if (varNode.getOpcode() == ISTORE && varNode.var == indeces[1]) - { - InsnList toAdd = new InsnList(); - toAdd.add(new VarInsnNode(ALOAD, indeces[0])); - toAdd.add(new VarInsnNode(ILOAD, indeces[1])); - toAdd.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", - "getItemEnchantability", enchantHelperMethodSig, false)); - toAdd.add(new VarInsnNode(ISTORE, indeces[1])); - m.instructions.insert(next, toAdd); - break; - } - } - } - - break; - } - } - } - }; - - basicClass = transform(basicClass, enchantHelperClass, buildEnchantListMethod, transformer); - } - // ItemRarity Event - else if (transformedName.equals(itemStackClass)) - { - basicClass = transform(basicClass, itemStackClass, itemStackMethod, new Transform() - { - @Override - void transform(Iterator methods) - { - while (methods.hasNext()) - { - MethodNode m = methods.next(); - if (itemStackMethod.equals(m.name)) - { - m.instructions.clear(); - - m.instructions.add(new VarInsnNode(ALOAD, 0)); - m.instructions.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "getItemRarity", - itemStackMethodSig, false)); - m.instructions.add(new InsnNode(ARETURN)); - - break; - } - } - } - }); - } - // ArrowUpdate Event - else if (transformedName.equals(entityArrowClass)) - { - basicClass = transform(basicClass, entityArrowClass, entityArrowMethod, new Transform() - { - @Override - void transform(Iterator methods) - { - while (methods.hasNext()) - { - MethodNode m = methods.next(); - if (entityArrowMethod.equals(m.name)) - { - for (int i = 0; i < m.instructions.size(); i++) - { - AbstractInsnNode next = m.instructions.get(i); - if (next instanceof MethodInsnNode) - { - InsnList toAdd = new InsnList(); - toAdd.add(new VarInsnNode(ALOAD, 0)); - toAdd.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "onArrowUpdate", - entityArrowMethodSig, false)); - m.instructions.insert(next, toAdd); - break; - } - } - break; - } - } - } - }); - } - // Furnace Shift Click Fix - else if (transformedName.equals(containerFurnaceClass)) - { - basicClass = transform(basicClass, containerFurnaceClass, containerFurnaceMethod, new Transform() - { - @Override - void transform(Iterator methods) - { - while (methods.hasNext()) - { - MethodNode m = methods.next(); - if (containerFurnaceMethod.equals(m.name)) - { - m.instructions.clear(); - - m.instructions.add(new VarInsnNode(ALOAD, 0)); - m.instructions.add(new VarInsnNode(ALOAD, 1)); - m.instructions.add(new VarInsnNode(ILOAD, 2)); - m.instructions.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "transferStackInSlot", - containerFurnaceMethodSig, false)); - m.instructions.add(new InsnNode(ARETURN)); - - break; - } - } - } - }); - } - - return basicClass; + public boolean equals(Object obj) { + if (obj instanceof String) { + return obj.equals(deobf) || obj.equals(srg); + } else if (obj instanceof ObfSafeName) { + return ((ObfSafeName) obj).deobf.equals(deobf) && ((ObfSafeName) obj).srg.equals(srg); + } + return false; } - protected final byte[] transform(byte[] classBytes, String className, ObfSafeName methodName, Transform transformer) - { - EnderCore.logger.info("Transforming Class [" + className + "], Method [" + methodName.getName() + "]"); + // no hashcode because I'm naughty + } - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(classBytes); - classReader.accept(classNode, 0); + protected static abstract class Transform { + abstract void transform(Iterator methods); + } - Iterator methods = classNode.methods.iterator(); + private static final String worldTypeClass = "net.minecraft.world.WorldType"; + private static final ObfSafeName voidFogMethod = new ObfSafeName("hasVoidParticles", "func_76564_j"); + private static final String voidFogMethodSig = "(Lnet/minecraft/world/WorldType;Z)Z"; - transformer.transform(methods); + private static final String anvilContainerClass = "net.minecraft.inventory.ContainerRepair"; + private static final ObfSafeName anvilContainerMethod = new ObfSafeName("updateRepairOutput", "func_82848_d"); - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - classNode.accept(cw); - EnderCore.logger.info("Transforming " + className + " Finished."); - return cw.toByteArray(); + private static final String anvilGuiClass = "net.minecraft.client.gui.GuiRepair"; + private static final ObfSafeName anvilGuiMethod = new ObfSafeName("drawGuiContainerForegroundLayer", "func_146979_b"); + + private static final String enchantHelperClass = "net.minecraft.enchantment.EnchantmentHelper"; + private static final String enchantHelperMethodSig = "(Lnet/minecraft/item/ItemStack;I)I"; + private static final ObfSafeName buildEnchantListMethod = new ObfSafeName("buildEnchantmentList", "func_77513_b"); + private static final ObfSafeName calcEnchantabilityMethod = new ObfSafeName("calcItemStackEnchantability", "func_77514_a"); + + private static final String itemStackClass = "net.minecraft.item.ItemStack"; + private static final ObfSafeName itemStackMethod = new ObfSafeName("getRarity", "func_77953_t"); + private static final String itemStackMethodSig = "(Lnet/minecraft/item/ItemStack;)Lnet/minecraft/item/EnumRarity;"; + + private static final String entityArrowClass = "net.minecraft.entity.projectile.EntityArrow"; + private static final ObfSafeName entityArrowMethod = new ObfSafeName("onUpdate", "func_70071_h_"); + private static final String entityArrowMethodSig = "(Lnet/minecraft/entity/projectile/EntityArrow;)V"; + + private static final String containerFurnaceClass = "net.minecraft.inventory.ContainerFurnace"; + private static final ObfSafeName containerFurnaceMethod = new ObfSafeName("transferStackInSlot", "func_82846_b"); + private static final String containerFurnaceMethodSig = "(Lnet/minecraft/inventory/ContainerFurnace;Lnet/minecraft/entity/player/EntityPlayer;I)Lnet/minecraft/item/ItemStack;"; + + @Override + public byte[] transform(String name, String transformedName, byte[] basicClass) { + // Void fog removal + if (transformedName.equals(worldTypeClass)) { + basicClass = transform(basicClass, worldTypeClass, voidFogMethod, new Transform() { + @Override + void transform(Iterator methods) { + while (methods.hasNext()) { + MethodNode m = methods.next(); + if (voidFogMethod.equals(m.name)) { + m.instructions.clear(); + + m.instructions.add(new VarInsnNode(ALOAD, 0)); + m.instructions.add(new VarInsnNode(ILOAD, 1)); + m.instructions.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "hasVoidParticles", voidFogMethodSig, + false)); + m.instructions.add(new InsnNode(IRETURN)); + + break; + } + } + } + }); } + // Anvil max level + else if (transformedName.equals(anvilContainerClass) || transformedName.equals(anvilGuiClass)) { + basicClass = transform(basicClass, anvilContainerClass, anvilContainerMethod, new Transform() { + @Override + void transform(Iterator methods) { + while (methods.hasNext()) { + MethodNode m = methods.next(); + if (anvilContainerMethod.equals(m.name) || anvilGuiMethod.equals(m.name)) { + for (int i = 0; i < m.instructions.size(); i++) { + AbstractInsnNode next = m.instructions.get(i); + + next = m.instructions.get(i); + if (next instanceof IntInsnNode && ((IntInsnNode) next).operand == 40) { + m.instructions.set(next, new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "getMaxAnvilCost", "()I", + false)); + } + } + } + } + } + }); + } + // Item Enchantability Event + else if (transformedName.equals(enchantHelperClass)) { + final Map data = new HashMap(); + data.put(buildEnchantListMethod.getName(), new int[] { 1, 4 }); + data.put(calcEnchantabilityMethod.getName(), new int[] { 3, 5 }); + Transform transformer = new Transform() { + @Override + void transform(Iterator methods) { + while (methods.hasNext()) { + MethodNode m = methods.next(); + if (data.keySet().contains(m.name)) { + int[] indeces = data.get(m.name); + for (int i = 0; i < m.instructions.size(); i++) { + AbstractInsnNode next = m.instructions.get(i); + if (next instanceof VarInsnNode) { + VarInsnNode varNode = (VarInsnNode) next; + if (varNode.getOpcode() == ISTORE && varNode.var == indeces[1]) { + InsnList toAdd = new InsnList(); + toAdd.add(new VarInsnNode(ALOAD, indeces[0])); + toAdd.add(new VarInsnNode(ILOAD, indeces[1])); + toAdd.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "getItemEnchantability", + enchantHelperMethodSig, false)); + toAdd.add(new VarInsnNode(ISTORE, indeces[1])); + m.instructions.insert(next, toAdd); + break; + } + } + } + + break; + } + } + } + }; + + basicClass = transform(basicClass, enchantHelperClass, buildEnchantListMethod, transformer); + } + // ItemRarity Event + else if (transformedName.equals(itemStackClass)) { + basicClass = transform(basicClass, itemStackClass, itemStackMethod, new Transform() { + @Override + void transform(Iterator methods) { + while (methods.hasNext()) { + MethodNode m = methods.next(); + if (itemStackMethod.equals(m.name)) { + m.instructions.clear(); + + m.instructions.add(new VarInsnNode(ALOAD, 0)); + m.instructions.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "getItemRarity", itemStackMethodSig, + false)); + m.instructions.add(new InsnNode(ARETURN)); + + break; + } + } + } + }); + } + // ArrowUpdate Event + else if (transformedName.equals(entityArrowClass)) { + basicClass = transform(basicClass, entityArrowClass, entityArrowMethod, new Transform() { + @Override + void transform(Iterator methods) { + while (methods.hasNext()) { + MethodNode m = methods.next(); + if (entityArrowMethod.equals(m.name)) { + for (int i = 0; i < m.instructions.size(); i++) { + AbstractInsnNode next = m.instructions.get(i); + if (next instanceof MethodInsnNode) { + InsnList toAdd = new InsnList(); + toAdd.add(new VarInsnNode(ALOAD, 0)); + toAdd + .add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "onArrowUpdate", entityArrowMethodSig, false)); + m.instructions.insert(next, toAdd); + break; + } + } + break; + } + } + } + }); + } + // Furnace Shift Click Fix + else if (transformedName.equals(containerFurnaceClass)) { + basicClass = transform(basicClass, containerFurnaceClass, containerFurnaceMethod, new Transform() { + @Override + void transform(Iterator methods) { + while (methods.hasNext()) { + MethodNode m = methods.next(); + if (containerFurnaceMethod.equals(m.name)) { + m.instructions.clear(); + + m.instructions.add(new VarInsnNode(ALOAD, 0)); + m.instructions.add(new VarInsnNode(ALOAD, 1)); + m.instructions.add(new VarInsnNode(ILOAD, 2)); + m.instructions.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/EnderCoreMethods", "transferStackInSlot", + containerFurnaceMethodSig, false)); + m.instructions.add(new InsnNode(ARETURN)); + + break; + } + } + } + }); + } + + return basicClass; + } + + protected final byte[] transform(byte[] classBytes, String className, ObfSafeName methodName, Transform transformer) { + EnderCore.logger.info("Transforming Class [" + className + "], Method [" + methodName.getName() + "]"); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(classBytes); + classReader.accept(classNode, 0); + + Iterator methods = classNode.methods.iterator(); + + transformer.transform(methods); + + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + classNode.accept(cw); + EnderCore.logger.info("Transforming " + className + " Finished."); + return cw.toByteArray(); + } } diff --git a/src/main/java/com/enderio/core/common/transform/EnderCoreTransformerClient.java b/src/main/java/com/enderio/core/common/transform/EnderCoreTransformerClient.java index 3691159..de54e20 100644 --- a/src/main/java/com/enderio/core/common/transform/EnderCoreTransformerClient.java +++ b/src/main/java/com/enderio/core/common/transform/EnderCoreTransformerClient.java @@ -12,86 +12,70 @@ import org.objectweb.asm.tree.VarInsnNode; import static org.objectweb.asm.Opcodes.*; -public class EnderCoreTransformerClient extends EnderCoreTransformer -{ - private static final String scrollingListClass = "cpw.mods.fml.client.GuiScrollingList"; - private static final ObfSafeName drawScreen = new ObfSafeName("func_73863_a", "drawScreen"); +public class EnderCoreTransformerClient extends EnderCoreTransformer { + private static final String scrollingListClass = "cpw.mods.fml.client.GuiScrollingList"; + private static final ObfSafeName drawScreen = new ObfSafeName("func_73863_a", "drawScreen"); - private static final String slotModListClass = "cpw.mods.fml.client.GuiSlotModList"; - private static final ObfSafeName drawBackground = new ObfSafeName("drawBackground", "drawBackground"); + private static final String slotModListClass = "cpw.mods.fml.client.GuiSlotModList"; + private static final ObfSafeName drawBackground = new ObfSafeName("drawBackground", "drawBackground"); - @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) - { - if (transformedName.equals(scrollingListClass)) - { - basicClass = transform(basicClass, scrollingListClass, drawScreen, new Transform() - { - @Override - void transform(Iterator methods) - { - while (methods.hasNext()) - { - MethodNode m = methods.next(); - if (drawScreen.equals(m.name)) - { - for (int i = 0; i < m.instructions.size(); i++) - { - AbstractInsnNode n = m.instructions.get(i); - if (n instanceof InsnNode && n.getOpcode() == ICONST_4) - { - AbstractInsnNode next = m.instructions.get(++i); - if (next instanceof VarInsnNode && next.getOpcode() == ISTORE && ((VarInsnNode) next).var == 15) - { - i += 2; - AbstractInsnNode insertPoint = m.instructions.get(i++); - m.instructions.remove(m.instructions.get(i)); - m.instructions.remove(m.instructions.get(i)); - m.instructions.remove(m.instructions.get(i)); - m.instructions.remove(m.instructions.get(i)); - m.instructions.insert(insertPoint, new InsnNode(ICONST_1)); - } - } - } - break; - } - } + @Override + public byte[] transform(String name, String transformedName, byte[] basicClass) { + if (transformedName.equals(scrollingListClass)) { + basicClass = transform(basicClass, scrollingListClass, drawScreen, new Transform() { + @Override + void transform(Iterator methods) { + while (methods.hasNext()) { + MethodNode m = methods.next(); + if (drawScreen.equals(m.name)) { + for (int i = 0; i < m.instructions.size(); i++) { + AbstractInsnNode n = m.instructions.get(i); + if (n instanceof InsnNode && n.getOpcode() == ICONST_4) { + AbstractInsnNode next = m.instructions.get(++i); + if (next instanceof VarInsnNode && next.getOpcode() == ISTORE && ((VarInsnNode) next).var == 15) { + i += 2; + AbstractInsnNode insertPoint = m.instructions.get(i++); + m.instructions.remove(m.instructions.get(i)); + m.instructions.remove(m.instructions.get(i)); + m.instructions.remove(m.instructions.get(i)); + m.instructions.remove(m.instructions.get(i)); + m.instructions.insert(insertPoint, new InsnNode(ICONST_1)); + } } - }); + } + break; + } + } } - else if (transformedName.equals(slotModListClass)) - { - basicClass = transform(basicClass, slotModListClass, drawBackground, new Transform() - { - @SuppressWarnings("deprecation") - @Override - void transform(Iterator methods) - { - while (methods.hasNext()) - { - MethodNode m = methods.next(); - if (drawBackground.equals(m.name)) - { - m.instructions.clear(); - ObfSafeName drawBackground = new ObfSafeName("drawBackground", "func_146278_c"); - String fieldOwner = "cpw/mods/fml/client/GuiSlotModList"; - String fieldName = "parent"; - String fieldType = "Lcpw/mods/fml/client/GuiModList;"; + }); + } else if (transformedName.equals(slotModListClass)) { + basicClass = transform(basicClass, slotModListClass, drawBackground, new Transform() { + @SuppressWarnings("deprecation") + @Override + void transform(Iterator methods) { + while (methods.hasNext()) { + MethodNode m = methods.next(); + if (drawBackground.equals(m.name)) { + m.instructions.clear(); + ObfSafeName drawBackground = new ObfSafeName("drawBackground", "func_146278_c"); + String fieldOwner = "cpw/mods/fml/client/GuiSlotModList"; + String fieldName = "parent"; + String fieldType = "Lcpw/mods/fml/client/GuiModList;"; - InsnList list = new InsnList(); - list.add(new VarInsnNode(ALOAD, 0)); - list.add(new FieldInsnNode(GETFIELD, fieldOwner, fieldName, fieldType)); - list.add(new InsnNode(ICONST_0)); - list.add(new MethodInsnNode(INVOKEVIRTUAL, "cpw/mods/fml/client/GuiModList", drawBackground.getName(), "(I)V")); - list.add(new InsnNode(RETURN)); + InsnList list = new InsnList(); + list.add(new VarInsnNode(ALOAD, 0)); + list.add(new FieldInsnNode(GETFIELD, fieldOwner, fieldName, fieldType)); + list.add(new InsnNode(ICONST_0)); + list.add(new MethodInsnNode(INVOKEVIRTUAL, "cpw/mods/fml/client/GuiModList", drawBackground.getName(), "(I)V")); + list.add(new InsnNode(RETURN)); - m.instructions.insert(list); - break; - } - } - } - }); + m.instructions.insert(list); + break; + } + } } - return basicClass; + }); } + return basicClass; + } } diff --git a/src/main/java/com/enderio/core/common/tweaks/SlabRecipes.java b/src/main/java/com/enderio/core/common/tweaks/SlabRecipes.java index 7f08c02..69c8421 100644 --- a/src/main/java/com/enderio/core/common/tweaks/SlabRecipes.java +++ b/src/main/java/com/enderio/core/common/tweaks/SlabRecipes.java @@ -6,36 +6,31 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.ShapelessOreRecipe; import cpw.mods.fml.common.registry.GameRegistry; -public class SlabRecipes extends Tweak -{ - private static final String[] slabEndingsWood = { "WoodOak", "WoodSpruce", "WoodBirch", "WoodJungle", "WoodAcacia", "WoodDarkOak" }; - private static final String[] slabEndingsStone = { "Stone", "Sandstone", "Cobblestone", "Bricks", "StoneBricks", "NetherBrick", "Quartz" }; - private static final Block[] slabResults = { Blocks.stone, Blocks.sandstone, Blocks.cobblestone, Blocks.brick_block, Blocks.stonebrick, Blocks.nether_brick, - Blocks.quartz_block }; +public class SlabRecipes extends Tweak { + private static final String[] slabEndingsWood = { "WoodOak", "WoodSpruce", "WoodBirch", "WoodJungle", "WoodAcacia", "WoodDarkOak" }; + private static final String[] slabEndingsStone = { "Stone", "Sandstone", "Cobblestone", "Bricks", "StoneBricks", "NetherBrick", "Quartz" }; + private static final Block[] slabResults = { Blocks.stone, Blocks.sandstone, Blocks.cobblestone, Blocks.brick_block, Blocks.stonebrick, Blocks.nether_brick, + Blocks.quartz_block }; - public static final SlabRecipes INSTANCE = new SlabRecipes(); + public static final SlabRecipes INSTANCE = new SlabRecipes(); - SlabRecipes() - { - super("slabToBlockRecipes", "Adds recipes to turn any two slabs back into a full block"); - } - - @Override - public void load() - { - registerSlabToBlock(); - } - - private void registerSlabToBlock() - { - for (int i = 0; i <= 1; i++) - { - String[] arr = i == 0 ? slabEndingsWood : slabEndingsStone; - Block[] results = i == 1 ? slabResults : null; - for (int j = 0; j < arr.length; j++) - { - GameRegistry.addRecipe(new ShapelessOreRecipe(i == 0 ? new ItemStack(Blocks.planks, 1, j) : new ItemStack(results[j]), "slab" + arr[j], "slab" + arr[j])); - } - } + SlabRecipes() { + super("slabToBlockRecipes", "Adds recipes to turn any two slabs back into a full block"); + } + + @Override + public void load() { + registerSlabToBlock(); + } + + private void registerSlabToBlock() { + for (int i = 0; i <= 1; i++) { + String[] arr = i == 0 ? slabEndingsWood : slabEndingsStone; + Block[] results = i == 1 ? slabResults : null; + for (int j = 0; j < arr.length; j++) { + GameRegistry + .addRecipe(new ShapelessOreRecipe(i == 0 ? new ItemStack(Blocks.planks, 1, j) : new ItemStack(results[j]), "slab" + arr[j], "slab" + arr[j])); + } } + } } diff --git a/src/main/java/com/enderio/core/common/tweaks/Tweak.java b/src/main/java/com/enderio/core/common/tweaks/Tweak.java index 4abed54..ff60b0f 100644 --- a/src/main/java/com/enderio/core/common/tweaks/Tweak.java +++ b/src/main/java/com/enderio/core/common/tweaks/Tweak.java @@ -5,19 +5,16 @@ import com.enderio.core.common.config.ConfigHandler; import lombok.Getter; @Getter -public abstract class Tweak -{ - private String name, comment; +public abstract class Tweak { + private String name, comment; - public Tweak(String key, String comment) - { - this.name = key; - this.comment = comment; - if (ConfigHandler.instance().addBooleanFor(this)) - { - load(); - } + public Tweak(String key, String comment) { + this.name = key; + this.comment = comment; + if (ConfigHandler.instance().addBooleanFor(this)) { + load(); } + } - public abstract void load(); + public abstract void load(); } diff --git a/src/main/java/com/enderio/core/common/tweaks/Tweaks.java b/src/main/java/com/enderio/core/common/tweaks/Tweaks.java index 79639a1..a046e80 100644 --- a/src/main/java/com/enderio/core/common/tweaks/Tweaks.java +++ b/src/main/java/com/enderio/core/common/tweaks/Tweaks.java @@ -9,16 +9,14 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.registry.GameRegistry; -public class Tweaks -{ - /** - * As of yet unused, but might be nice in the future to have a list - */ - private static final List tweaks = new ArrayList(); +public class Tweaks { + /** + * As of yet unused, but might be nice in the future to have a list + */ + private static final List tweaks = new ArrayList(); - public static void loadIngameTweaks() - { - // @formatter:off + public static void loadIngameTweaks() { + // @formatter:off tweaks.add(new Tweak("fixBedSound", "Makes the bed stepSound wool instead of stone") { @Override public void load() { Blocks.bed.setStepSound(Block.soundTypeCloth); } diff --git a/src/main/java/com/enderio/core/common/util/BlockCoord.java b/src/main/java/com/enderio/core/common/util/BlockCoord.java index 86206ba..bebcbc5 100644 --- a/src/main/java/com/enderio/core/common/util/BlockCoord.java +++ b/src/main/java/com/enderio/core/common/util/BlockCoord.java @@ -54,7 +54,7 @@ public class BlockCoord { public BlockCoord(MovingObjectPosition mop) { this(mop.blockX, mop.blockY, mop.blockZ); } - + public Block getBlock(IBlockAccess world) { return world.getBlock(x, y, z); } @@ -86,7 +86,7 @@ public class BlockCoord { public int getDist(TileEntity other) { return getDist(new BlockCoord(other)); } - + public void writeToBuf(ByteBuf buf) { buf.writeInt(x); buf.writeInt(y); @@ -112,14 +112,10 @@ public class BlockCoord { } public String chatString(EnumChatFormatting defaultColor) { - return String.format( - "x%s%d%s y%s%d%s z%s%d", - EnumChatFormatting.GREEN, x, defaultColor, - EnumChatFormatting.GREEN, y, defaultColor, - EnumChatFormatting.GREEN, z - ); + return String.format("x%s%d%s y%s%d%s z%s%d", EnumChatFormatting.GREEN, x, defaultColor, EnumChatFormatting.GREEN, y, defaultColor, + EnumChatFormatting.GREEN, z); } - + public boolean equals(int x, int y, int z) { return equals(new BlockCoord(x, y, z)); } diff --git a/src/main/java/com/enderio/core/common/util/CreativeTabsCustom.java b/src/main/java/com/enderio/core/common/util/CreativeTabsCustom.java index 907522c..74813ad 100644 --- a/src/main/java/com/enderio/core/common/util/CreativeTabsCustom.java +++ b/src/main/java/com/enderio/core/common/util/CreativeTabsCustom.java @@ -6,51 +6,48 @@ import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -public class CreativeTabsCustom extends CreativeTabs -{ - @NonNull - private ItemStack displayStack; +public class CreativeTabsCustom extends CreativeTabs { + @NonNull + private ItemStack displayStack; - public CreativeTabsCustom(String unloc) - { - super(unloc); - } + public CreativeTabsCustom(String unloc) { + super(unloc); + } - /** - * @param item Item to display - */ - public CreativeTabsCustom setDisplay(Item item) - { - return setDisplay(item, 0); - } + /** + * @param item + * Item to display + */ + public CreativeTabsCustom setDisplay(Item item) { + return setDisplay(item, 0); + } - /** - * @param item Item to display - * @param damage Damage of item to display - */ - public CreativeTabsCustom setDisplay(Item item, int damage) - { - return setDisplay(new ItemStack(item, 1, damage)); - } + /** + * @param item + * Item to display + * @param damage + * Damage of item to display + */ + public CreativeTabsCustom setDisplay(Item item, int damage) { + return setDisplay(new ItemStack(item, 1, damage)); + } - /** - * @param display ItemStack to display - */ - public CreativeTabsCustom setDisplay(ItemStack display) - { - this.displayStack = display.copy(); - return this; - } + /** + * @param display + * ItemStack to display + */ + public CreativeTabsCustom setDisplay(ItemStack display) { + this.displayStack = display.copy(); + return this; + } - @Override - public ItemStack getIconItemStack() - { - return displayStack == null ? new ItemStack(Items.diamond) : displayStack; - } + @Override + public ItemStack getIconItemStack() { + return displayStack == null ? new ItemStack(Items.diamond) : displayStack; + } - @Override - public Item getTabIconItem() - { - return null; // defaults to getIconItemStack() - } + @Override + public Item getTabIconItem() { + return null; // defaults to getIconItemStack() + } } diff --git a/src/main/java/com/enderio/core/common/util/DyeColor.java b/src/main/java/com/enderio/core/common/util/DyeColor.java index 16ddec4..467ddc6 100644 --- a/src/main/java/com/enderio/core/common/util/DyeColor.java +++ b/src/main/java/com/enderio/core/common/util/DyeColor.java @@ -25,65 +25,37 @@ public enum DyeColor { ORANGE, WHITE; - public static final String[] DYE_ORE_NAMES = { - "dyeBlack", - "dyeRed", - "dyeGreen", - "dyeBrown", - "dyeBlue", - "dyePurple", - "dyeCyan", - "dyeLightGray", - "dyeGray", - "dyePink", - "dyeLime", - "dyeYellow", - "dyeLightBlue", - "dyeMagenta", - "dyeOrange", - "dyeWhite" - }; + public static final String[] DYE_ORE_NAMES = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", + "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite" }; public static final String[] DYE_ORE_UNLOCAL_NAMES = { - "item.fireworksCharge.black", - "item.fireworksCharge.red", - "item.fireworksCharge.green", - "item.fireworksCharge.brown", - "item.fireworksCharge.blue", - "item.fireworksCharge.purple", - "item.fireworksCharge.cyan", - "item.fireworksCharge.silver", - "item.fireworksCharge.gray", - "item.fireworksCharge.pink", - "item.fireworksCharge.lime", - "item.fireworksCharge.yellow", - "item.fireworksCharge.lightBlue", - "item.fireworksCharge.magenta", - "item.fireworksCharge.orange", - "item.fireworksCharge.white" + "item.fireworksCharge.black", "item.fireworksCharge.red", "item.fireworksCharge.green", "item.fireworksCharge.brown", "item.fireworksCharge.blue", + "item.fireworksCharge.purple", "item.fireworksCharge.cyan", "item.fireworksCharge.silver", "item.fireworksCharge.gray", "item.fireworksCharge.pink", + "item.fireworksCharge.lime", "item.fireworksCharge.yellow", "item.fireworksCharge.lightBlue", "item.fireworksCharge.magenta", + "item.fireworksCharge.orange", "item.fireworksCharge.white" }; public static DyeColor getNext(DyeColor col) { int ord = col.ordinal() + 1; - if(ord >= DyeColor.values().length) { + if (ord >= DyeColor.values().length) { ord = 0; } return DyeColor.values()[ord]; } public static DyeColor getColorFromDye(ItemStack dye) { - if(dye == null) { + if (dye == null) { return null; } int oreId = OreDictionary.getOreID(dye); - if(oreId < 0) { + if (oreId < 0) { return null; } for (int i = 0; i < DYE_ORE_NAMES.length; i++) { String dyeName = DYE_ORE_NAMES[i]; - if(OreDictionary.getOreID(dyeName) == oreId) { + if (OreDictionary.getOreID(dyeName) == oreId) { return DyeColor.values()[i]; } } diff --git a/src/main/java/com/enderio/core/common/util/EnderFileUtils.java b/src/main/java/com/enderio/core/common/util/EnderFileUtils.java index cbdbe46..87a8f26 100644 --- a/src/main/java/com/enderio/core/common/util/EnderFileUtils.java +++ b/src/main/java/com/enderio/core/common/util/EnderFileUtils.java @@ -38,347 +38,295 @@ import com.enderio.core.EnderCore; import com.enderio.core.common.config.ConfigHandler; @UtilityClass -public class EnderFileUtils -{ - public final FileFilter pngFilter = FileFilterUtils.suffixFileFilter(".png"); - public final FileFilter langFilter = FileFilterUtils.suffixFileFilter(".lang"); +public class EnderFileUtils { + public final FileFilter pngFilter = FileFilterUtils.suffixFileFilter(".png"); + public final FileFilter langFilter = FileFilterUtils.suffixFileFilter(".lang"); - /** - * @param jarClass - * - A class from the jar in question - * @param filename - * - Name of the file to copy, automatically prepended with "/assets/" - * @param to - * - File to copy to - */ - public void copyFromJar(Class jarClass, String filename, File to) - { - EnderCore.logger.info("Copying file " + filename + " from jar"); - URL url = jarClass.getResource("/assets/" + filename); + /** + * @param jarClass + * - A class from the jar in question + * @param filename + * - Name of the file to copy, automatically prepended with + * "/assets/" + * @param to + * - File to copy to + */ + public void copyFromJar(Class jarClass, String filename, File to) { + EnderCore.logger.info("Copying file " + filename + " from jar"); + URL url = jarClass.getResource("/assets/" + filename); - try - { - FileUtils.copyURLToFile(url, to); + try { + FileUtils.copyURLToFile(url, to); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * @author Ilias Tsagklis + *

+ * From this site. + * + * @param zip + * - The zip file to extract + * + * @return The folder extracted to + */ + @NonNull + public File extractZip(File zip) { + String zipPath = zip.getParent() + "/extracted"; + File temp = new File(zipPath); + temp.mkdir(); + + ZipFile zipFile = null; + + try { + zipFile = new ZipFile(zip); + + // get an enumeration of the ZIP file entries + Enumeration e = zipFile.entries(); + + while (e.hasMoreElements()) { + ZipEntry entry = e.nextElement(); + + File destinationPath = new File(zipPath, entry.getName()); + + // create parent directories + destinationPath.getParentFile().mkdirs(); + + // if the entry is a file extract it + if (entry.isDirectory()) { + continue; + } else { + EnderCore.logger.info("Extracting file: " + destinationPath); + + BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); + + int b; + byte buffer[] = new byte[1024]; + + FileOutputStream fos = new FileOutputStream(destinationPath); + + BufferedOutputStream bos = new BufferedOutputStream(fos, 1024); + + while ((b = bis.read(buffer, 0, 1024)) != -1) { + bos.write(buffer, 0, b); + } + + bos.close(); + bis.close(); } - catch (IOException e) - { - throw new RuntimeException(e); + } + } catch (IOException e) { + EnderCore.logger.error("Error opening zip file" + e); + } finally { + try { + if (zipFile != null) { + zipFile.close(); } + } catch (IOException e) { + EnderCore.logger.error("Error while closing zip file" + e); + } } - /** - * @author Ilias Tsagklis - *

- * From this site. - * - * @param zip - * - The zip file to extract - * - * @return The folder extracted to - */ - @NonNull - public File extractZip(File zip) - { - String zipPath = zip.getParent() + "/extracted"; - File temp = new File(zipPath); - temp.mkdir(); + return temp; + } - ZipFile zipFile = null; - - try - { - zipFile = new ZipFile(zip); - - // get an enumeration of the ZIP file entries - Enumeration e = zipFile.entries(); - - while (e.hasMoreElements()) - { - ZipEntry entry = e.nextElement(); - - File destinationPath = new File(zipPath, entry.getName()); - - // create parent directories - destinationPath.getParentFile().mkdirs(); - - // if the entry is a file extract it - if (entry.isDirectory()) - { - continue; - } - else - { - EnderCore.logger.info("Extracting file: " + destinationPath); - - BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); - - int b; - byte buffer[] = new byte[1024]; - - FileOutputStream fos = new FileOutputStream(destinationPath); - - BufferedOutputStream bos = new BufferedOutputStream(fos, 1024); - - while ((b = bis.read(buffer, 0, 1024)) != -1) - { - bos.write(buffer, 0, b); - } - - bos.close(); - bis.close(); - } - } + /** + * @author McDowell - http://stackoverflow.com/questions/1399126/java-util-zip + * -recreating-directory-structure + * + * @param directory + * The directory to zip the contents of. Content structure will be + * preserved. + * @param zipfile + * The zip file to output to. + * @throws IOException + */ + @SuppressWarnings("resource") + public void zipFolderContents(File directory, File zipfile) throws IOException { + URI base = directory.toURI(); + Deque queue = new LinkedList(); + queue.push(directory); + OutputStream out = new FileOutputStream(zipfile); + Closeable res = out; + try { + ZipOutputStream zout = new ZipOutputStream(out); + res = zout; + while (!queue.isEmpty()) { + directory = queue.pop(); + for (File child : directory.listFiles()) { + String name = base.relativize(child.toURI()).getPath(); + if (child.isDirectory()) { + queue.push(child); + name = name.endsWith("/") ? name : name + "/"; + zout.putNextEntry(new ZipEntry(name)); + } else { + zout.putNextEntry(new ZipEntry(name)); + copy(child, zout); + zout.closeEntry(); + } } - catch (IOException e) - { - EnderCore.logger.error("Error opening zip file" + e); - } - finally - { - try - { - if (zipFile != null) - { - zipFile.close(); - } - } - catch (IOException e) - { - EnderCore.logger.error("Error while closing zip file" + e); - } + } + } finally { + res.close(); + } + } + + /** @see #zipFolderContents(File, File) */ + private void copy(InputStream in, OutputStream out) throws IOException { + byte[] buffer = new byte[1024]; + while (true) { + int readCount = in.read(buffer); + if (readCount < 0) { + break; + } + out.write(buffer, 0, readCount); + } + } + + /** @see #zipFolderContents(File, File) */ + private void copy(File file, OutputStream out) throws IOException { + InputStream in = new FileInputStream(file); + try { + copy(in, out); + } finally { + in.close(); + } + } + + @NonNull + public File writeToFile(String filepath, String json) { + File file = new File(filepath); + + try { + file.createNewFile(); + FileWriter fw = new FileWriter(file); + fw.write(json); + fw.flush(); + fw.close(); + return file; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @NonNull + public void safeDelete(File file) { + try { + file.delete(); + } catch (Exception e) { + EnderCore.logger.error("Deleting file " + file.getAbsolutePath() + " failed."); + } + } + + @NonNull + public void safeDeleteDirectory(File file) { + try { + FileUtils.deleteDirectory(file); + } catch (Exception e) { + EnderCore.logger.error("Deleting directory " + file.getAbsolutePath() + " failed."); + } + } + + @SneakyThrows + @NonNull + public void loadLangFiles(File directory) { + for (File file : directory.listFiles(langFilter)) { + StringTranslate.inject(new FileInputStream(file)); + } + } + + /** + * Same as manuallyChangeConfigValue(String, String, String), but + * with an additional parameter for what config file to edit + * + * @param filePathFromConfigFolder + * - the full path to the files, including extensions, from inside + * config/ + * @param prefix + * - The prefix of the config option (anything before '='), must + * match exactly. + * @param from + * - The setting to change it from + * @param to + * - The setting to change it to + * @return whether anything changed + */ + public boolean manuallyChangeConfigValue(String filePathFromConfigFolder, String prefix, String from, String to) { + File config = new File(ConfigHandler.configFolder.getAbsolutePath() + "/" + filePathFromConfigFolder); + boolean found = false; + + try { + FileReader fr1 = new FileReader(config); + BufferedReader read = new BufferedReader(fr1); + + ArrayList strings = new ArrayList(); + + while (read.ready()) { + strings.add(read.readLine()); + } + + fr1.close(); + read.close(); + + FileWriter fw = new FileWriter(config); + BufferedWriter bw = new BufferedWriter(fw); + + for (String s : strings) { + if (!found && s.contains(prefix + "=" + from) && !s.contains("=" + to)) { + s = s.replace(prefix + "=" + from, prefix + "=" + to); + EnderCore.logger.info("Successfully changed config value " + prefix + " from " + from + " to " + to); + found = true; } - return temp; + fw.write(s + "\n"); + } + + bw.flush(); + bw.close(); + } catch (Throwable t) { + t.printStackTrace(); } - /** - * @author McDowell - http://stackoverflow.com/questions/1399126/java-util-zip -recreating-directory-structure - * - * @param directory - * The directory to zip the contents of. Content structure will be preserved. - * @param zipfile - * The zip file to output to. - * @throws IOException - */ - @SuppressWarnings("resource") - public void zipFolderContents(File directory, File zipfile) throws IOException - { - URI base = directory.toURI(); - Deque queue = new LinkedList(); - queue.push(directory); - OutputStream out = new FileOutputStream(zipfile); - Closeable res = out; - try - { - ZipOutputStream zout = new ZipOutputStream(out); - res = zout; - while (!queue.isEmpty()) - { - directory = queue.pop(); - for (File child : directory.listFiles()) - { - String name = base.relativize(child.toURI()).getPath(); - if (child.isDirectory()) - { - queue.push(child); - name = name.endsWith("/") ? name : name + "/"; - zout.putNextEntry(new ZipEntry(name)); - } - else - { - zout.putNextEntry(new ZipEntry(name)); - copy(child, zout); - zout.closeEntry(); - } - } - } - } - finally - { - res.close(); - } + return found; + } + + /** + * Finds the config value in the file specified (path starting after config/), + * and for the key specified + * + * @param filePathFromConfigFolder + * - The path to the file, everything up to config/ is calculated for + * you + * @param key + * - A key to find the value by, does not need to match exactly + * @return A parseable string that can be transformed into any of the types of + * config values, for instance using + * Boolean.parseBoolean(String) + */ + public String manuallyGetConfigValue(String filePathFromConfigFolder, String key) { + File config = new File(ConfigHandler.configFolder.getAbsolutePath() + "/" + filePathFromConfigFolder); + Scanner scan = null; + + try { + scan = new Scanner(config); + } catch (FileNotFoundException e) { + return ""; } - /** @see #zipFolderContents(File, File) */ - private void copy(InputStream in, OutputStream out) throws IOException - { - byte[] buffer = new byte[1024]; - while (true) - { - int readCount = in.read(buffer); - if (readCount < 0) - { - break; - } - out.write(buffer, 0, readCount); - } - } - - /** @see #zipFolderContents(File, File) */ - private void copy(File file, OutputStream out) throws IOException - { - InputStream in = new FileInputStream(file); - try - { - copy(in, out); - } - finally - { - in.close(); - } - } - - @NonNull - public File writeToFile(String filepath, String json) - { - File file = new File(filepath); - - try - { - file.createNewFile(); - FileWriter fw = new FileWriter(file); - fw.write(json); - fw.flush(); - fw.close(); - return file; - } - catch (IOException e) - { - throw new RuntimeException(e); - } - } - - @NonNull - public void safeDelete(File file) - { - try - { - file.delete(); - } - catch (Exception e) - { - EnderCore.logger.error("Deleting file " + file.getAbsolutePath() + " failed."); - } - } - - @NonNull - public void safeDeleteDirectory(File file) - { - try - { - FileUtils.deleteDirectory(file); - } - catch (Exception e) - { - EnderCore.logger.error("Deleting directory " + file.getAbsolutePath() + " failed."); - } - } - - @SneakyThrows - @NonNull - public void loadLangFiles(File directory) - { - for (File file : directory.listFiles(langFilter)) - { - StringTranslate.inject(new FileInputStream(file)); - } - } - - /** - * Same as manuallyChangeConfigValue(String, String, String), but with an additional parameter for what config file to edit - * - * @param filePathFromConfigFolder - * - the full path to the files, including extensions, from inside config/ - * @param prefix - * - The prefix of the config option (anything before '='), must match exactly. - * @param from - * - The setting to change it from - * @param to - * - The setting to change it to - * @return whether anything changed - */ - public boolean manuallyChangeConfigValue(String filePathFromConfigFolder, String prefix, String from, String to) - { - File config = new File(ConfigHandler.configFolder.getAbsolutePath() + "/" + filePathFromConfigFolder); - boolean found = false; - - try - { - FileReader fr1 = new FileReader(config); - BufferedReader read = new BufferedReader(fr1); - - ArrayList strings = new ArrayList(); - - while (read.ready()) - { - strings.add(read.readLine()); - } - - fr1.close(); - read.close(); - - FileWriter fw = new FileWriter(config); - BufferedWriter bw = new BufferedWriter(fw); - - for (String s : strings) - { - if (!found && s.contains(prefix + "=" + from) && !s.contains("=" + to)) - { - s = s.replace(prefix + "=" + from, prefix + "=" + to); - EnderCore.logger.info("Successfully changed config value " + prefix + " from " + from + " to " + to); - found = true; - } - - fw.write(s + "\n"); - } - - bw.flush(); - bw.close(); - } - catch (Throwable t) - { - t.printStackTrace(); - } - - return found; - } - - /** - * Finds the config value in the file specified (path starting after config/), and for the key specified - * - * @param filePathFromConfigFolder - * - The path to the file, everything up to config/ is calculated for you - * @param key - * - A key to find the value by, does not need to match exactly - * @return A parseable string that can be transformed into any of the types of config values, for instance using - * Boolean.parseBoolean(String) - */ - public String manuallyGetConfigValue(String filePathFromConfigFolder, String key) - { - File config = new File(ConfigHandler.configFolder.getAbsolutePath() + "/" + filePathFromConfigFolder); - Scanner scan = null; - - try - { - scan = new Scanner(config); - } - catch (FileNotFoundException e) - { - return ""; - } - - while (scan.hasNext()) - { - String s = scan.next(); - - if (s.contains(key)) - { - scan.close(); - return s.substring(s.indexOf("=") + 1, s.length()); - } - } + while (scan.hasNext()) { + String s = scan.next(); + if (s.contains(key)) { scan.close(); - return ""; + return s.substring(s.indexOf("=") + 1, s.length()); + } } + + scan.close(); + return ""; + } } diff --git a/src/main/java/com/enderio/core/common/util/EnderRegistryUtils.java b/src/main/java/com/enderio/core/common/util/EnderRegistryUtils.java index 3c5526b..34158f0 100644 --- a/src/main/java/com/enderio/core/common/util/EnderRegistryUtils.java +++ b/src/main/java/com/enderio/core/common/util/EnderRegistryUtils.java @@ -20,116 +20,107 @@ import cpw.mods.fml.common.LoaderState; import cpw.mods.fml.common.registry.GameData; /** - * This class provides a few utility methods to regain the ability to register items/blocks to a modid other than the active mod's. This is useful - * when registering items/blocks inside Compat classes (as the active mod at that time is always ttCore). + * This class provides a few utility methods to regain the ability to register + * items/blocks to a modid other than the active mod's. This is useful when + * registering items/blocks inside Compat classes (as the active mod at that + * time is always ttCore). */ @UtilityClass -public class EnderRegistryUtils -{ - private Method getMain; - private Method registerItem; - private Method registerBlock; +public class EnderRegistryUtils { + private Method getMain; + private Method registerItem; + private Method registerBlock; - static - { - try - { - getMain = GameData.class.getDeclaredMethod("getMain"); - getMain.setAccessible(true); - registerItem = GameData.class.getDeclaredMethod("registerItem", Item.class, String.class, int.class); - registerItem.setAccessible(true); - registerBlock = GameData.class.getDeclaredMethod("registerBlock", Block.class, String.class, int.class); - registerBlock.setAccessible(true); - } - catch (Exception e) - { - throw new RuntimeException(e); - } + static { + try { + getMain = GameData.class.getDeclaredMethod("getMain"); + getMain.setAccessible(true); + registerItem = GameData.class.getDeclaredMethod("registerItem", Item.class, String.class, int.class); + registerItem.setAccessible(true); + registerBlock = GameData.class.getDeclaredMethod("registerBlock", Block.class, String.class, int.class); + registerBlock.setAccessible(true); + } catch (Exception e) { + throw new RuntimeException(e); } + } - /** - * Registers an item with a custom modid prefix. This method exists due to the fact that FML dropped support for registering items to modids other - * than the currently active container. - * - * @param item - * The item to register - * @param modid - * The modid to register the item to - * @param name - * The name of the item - */ - @SneakyThrows - public void registerItem(Item item, String modid, String name) - { - registerItem.invoke(getMain.invoke(null), item, modid + ":" + name, -1); - } + /** + * Registers an item with a custom modid prefix. This method exists due to the + * fact that FML dropped support for registering items to modids other than + * the currently active container. + * + * @param item + * The item to register + * @param modid + * The modid to register the item to + * @param name + * The name of the item + */ + @SneakyThrows + public void registerItem(Item item, String modid, String name) { + registerItem.invoke(getMain.invoke(null), item, modid + ":" + name, -1); + } - /** - * Registers a block with a custom modid prefix. This method exists due to the fact that FML dropped support for registering blocks to modids - * other than the currently active container. - * - * @param block - * The block to register - * @param modid - * The modid to register the block to - * @param name - * The name of the block - */ - public void registerBlock(Block block, String modid, String name) - { - registerBlock(block, null, modid, name); - } + /** + * Registers a block with a custom modid prefix. This method exists due to the + * fact that FML dropped support for registering blocks to modids other than + * the currently active container. + * + * @param block + * The block to register + * @param modid + * The modid to register the block to + * @param name + * The name of the block + */ + public void registerBlock(Block block, String modid, String name) { + registerBlock(block, null, modid, name); + } - /** - * Registers a block with a custom modid prefix. This method exists due to the fact that FML dropped support for registering blocks to modids - * other than the currently active container. - * - * @param block - * The block to register - * @param itemclass - * The class of the ItemBlock to associate with this block - * @param modid - * The modid to register the block to - * @param name - * The name of the block - * @param itemCtorArgs - * Objects to pass as arguments to the ItemBlock. - */ - @SneakyThrows - public void registerBlock(Block block, Class itemclass, String modid, String name, Object... itemCtorArgs) - { - if (Loader.instance().isInState(LoaderState.CONSTRUCTING)) - { - FMLLog.warning( - "The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", - Loader.instance().activeModContainer()); - } - try - { - assert block != null : "registerBlock: block cannot be null"; - ItemBlock i = null; - if (itemclass != null) - { - Class[] ctorArgClasses = new Class[itemCtorArgs.length + 1]; - ctorArgClasses[0] = Block.class; - for (int idx = 1; idx < ctorArgClasses.length; idx++) - { - ctorArgClasses[idx] = itemCtorArgs[idx - 1].getClass(); - } - Constructor itemCtor = itemclass.getConstructor(ctorArgClasses); - i = itemCtor.newInstance(ObjectArrays.concat(block, itemCtorArgs)); - } - // block registration has to happen first - registerBlock.invoke(getMain.invoke(null), block, modid + ":" + name, -1); - if (i != null) - { - registerItem(i, modid, name); - } - } - catch (Exception e) - { - FMLLog.log(Level.ERROR, e, "Caught an exception during block registration"); - throw new LoaderException(e); - } + /** + * Registers a block with a custom modid prefix. This method exists due to the + * fact that FML dropped support for registering blocks to modids other than + * the currently active container. + * + * @param block + * The block to register + * @param itemclass + * The class of the ItemBlock to associate with this block + * @param modid + * The modid to register the block to + * @param name + * The name of the block + * @param itemCtorArgs + * Objects to pass as arguments to the ItemBlock. + */ + @SneakyThrows + public void registerBlock(Block block, Class itemclass, String modid, String name, Object... itemCtorArgs) { + if (Loader.instance().isInState(LoaderState.CONSTRUCTING)) { + FMLLog + .warning( + "The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", + Loader.instance().activeModContainer()); } + try { + assert block != null : "registerBlock: block cannot be null"; + ItemBlock i = null; + if (itemclass != null) { + Class[] ctorArgClasses = new Class[itemCtorArgs.length + 1]; + ctorArgClasses[0] = Block.class; + for (int idx = 1; idx < ctorArgClasses.length; idx++) { + ctorArgClasses[idx] = itemCtorArgs[idx - 1].getClass(); + } + Constructor itemCtor = itemclass.getConstructor(ctorArgClasses); + i = itemCtor.newInstance(ObjectArrays.concat(block, itemCtorArgs)); + } + // block registration has to happen first + registerBlock.invoke(getMain.invoke(null), block, modid + ":" + name, -1); + if (i != null) { + registerItem(i, modid, name); + } + } catch (Exception e) { + FMLLog.log(Level.ERROR, e, "Caught an exception during block registration"); + throw new LoaderException(e); + } + } } diff --git a/src/main/java/com/enderio/core/common/util/EnderStringUtils.java b/src/main/java/com/enderio/core/common/util/EnderStringUtils.java index 2872b16..35a995c 100644 --- a/src/main/java/com/enderio/core/common/util/EnderStringUtils.java +++ b/src/main/java/com/enderio/core/common/util/EnderStringUtils.java @@ -7,125 +7,115 @@ import net.minecraft.util.EnumChatFormatting; import com.enderio.core.EnderCore; @UtilityClass -public class EnderStringUtils -{ - /** - * Formats a string and number for use in GUIs and tooltips - * - * @param prefix - * - The string to put before the formatted number - * @param suffix - * - The string to put after the formatted number - * @param amnt - * - The number to be formatted - * @param useDecimals - * - Whether or not to use decimals in the representation - * @param formatK - * - Whether or not to format the thousands - * @return A string numeric formatted to use SI suffixes - */ - public String formatString(String prefix, String suffix, long amnt, boolean useDecimals, boolean formatK) - { - if (formatK && Long.toString(amnt).length() < 7 && Long.toString(amnt).length() > 3) - { - return formatSmallerNumber(prefix, suffix, amnt, useDecimals); - } - - switch (Long.toString(amnt).length()) - { - case 7: - prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 3) : "") + "M" + suffix; - return prefix; - case 8: - prefix += Long.toString(amnt).substring(0, 2) + (useDecimals ? "." + Long.toString(amnt).substring(2, 4) : "") + "M" + suffix; - return prefix; - case 9: - prefix += Long.toString(amnt).substring(0, 3) + (useDecimals ? "." + Long.toString(amnt).substring(3, 5) : "") + "M" + suffix; - return prefix; - case 10: - prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 3) : "") + "B" + suffix; - return prefix; - case 11: - prefix += Long.toString(amnt).substring(0, 2) + (useDecimals ? "." + Long.toString(amnt).substring(2, 4) : "") + "B" + suffix; - return prefix; - case 12: - prefix += Long.toString(amnt).substring(0, 3) + (useDecimals ? "." + Long.toString(amnt).substring(3, 5) : "") + "B" + suffix; - return prefix; - case 13: - prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 5) : "") + "T" + suffix; - return prefix; - default: - prefix += "" + amnt + suffix; - return prefix; - } +public class EnderStringUtils { + /** + * Formats a string and number for use in GUIs and tooltips + * + * @param prefix + * - The string to put before the formatted number + * @param suffix + * - The string to put after the formatted number + * @param amnt + * - The number to be formatted + * @param useDecimals + * - Whether or not to use decimals in the representation + * @param formatK + * - Whether or not to format the thousands + * @return A string numeric formatted to use SI suffixes + */ + public String formatString(String prefix, String suffix, long amnt, boolean useDecimals, boolean formatK) { + if (formatK && Long.toString(amnt).length() < 7 && Long.toString(amnt).length() > 3) { + return formatSmallerNumber(prefix, suffix, amnt, useDecimals); } - /** - * Formats a string and number for use in GUIs and tooltips - * - * @param prefix - * - The string to put before the formatted number - * @param suffix - * - The string to put after the formatted number - * @param amnt - * - The number to be formatted - * @param useDecimals - * - Whether or not to use decimals in the representation - * @return A string numeric formatted to use SI suffixes - */ - public String formatString(String prefix, String suffix, long amnt, boolean useDecimals) - { - return formatString(prefix, suffix, amnt, useDecimals, false); + switch (Long.toString(amnt).length()) { + case 7: + prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 3) : "") + "M" + suffix; + return prefix; + case 8: + prefix += Long.toString(amnt).substring(0, 2) + (useDecimals ? "." + Long.toString(amnt).substring(2, 4) : "") + "M" + suffix; + return prefix; + case 9: + prefix += Long.toString(amnt).substring(0, 3) + (useDecimals ? "." + Long.toString(amnt).substring(3, 5) : "") + "M" + suffix; + return prefix; + case 10: + prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 3) : "") + "B" + suffix; + return prefix; + case 11: + prefix += Long.toString(amnt).substring(0, 2) + (useDecimals ? "." + Long.toString(amnt).substring(2, 4) : "") + "B" + suffix; + return prefix; + case 12: + prefix += Long.toString(amnt).substring(0, 3) + (useDecimals ? "." + Long.toString(amnt).substring(3, 5) : "") + "B" + suffix; + return prefix; + case 13: + prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 5) : "") + "T" + suffix; + return prefix; + default: + prefix += "" + amnt + suffix; + return prefix; + } + } + + /** + * Formats a string and number for use in GUIs and tooltips + * + * @param prefix + * - The string to put before the formatted number + * @param suffix + * - The string to put after the formatted number + * @param amnt + * - The number to be formatted + * @param useDecimals + * - Whether or not to use decimals in the representation + * @return A string numeric formatted to use SI suffixes + */ + public String formatString(String prefix, String suffix, long amnt, boolean useDecimals) { + return formatString(prefix, suffix, amnt, useDecimals, false); + } + + private String formatSmallerNumber(String prefix, String suffix, long amnt, boolean useDecimals) { + switch (Long.toString(amnt).length()) { + case 4: + prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 3) : "") + "K" + suffix; + return prefix; + case 5: + prefix += Long.toString(amnt).substring(0, 2) + (useDecimals ? "." + Long.toString(amnt).substring(2, 4) : "") + "K" + suffix; + return prefix; + case 6: + prefix += Long.toString(amnt).substring(0, 3) + (useDecimals ? "." + Long.toString(amnt).substring(3, 5) : "") + "K" + suffix; + return prefix; + } + return ""; + } + + /** + * Returns a color for the number passed, based on its percentage of the max + * + * @param num + * The number to compare + * @param max + * The max number + * + * @return if num {@literal <}= 10% of max : RED
+ * if 10% {@literal <} num {@literal <}= 25% of max: GOLD (orange-ish)
+ * if num {@literal >} 25% of max: GREEN + */ + public EnumChatFormatting getColorFor(double num, double max) { + if (num / max <= .1) + return EnumChatFormatting.RED; + else if (num / max <= .25) + return EnumChatFormatting.GOLD; + else + return EnumChatFormatting.GREEN; + } + + public String getEffectNameWithLevel(PotionEffect effect) { + String name = EnderCore.lang.localize(effect.getEffectName(), false); + + if (effect.getAmplifier() > 0) { + name += " " + EnderCore.lang.localize("enchantment.level." + (effect.getAmplifier() + 1), false); } - private String formatSmallerNumber(String prefix, String suffix, long amnt, boolean useDecimals) - { - switch (Long.toString(amnt).length()) - { - case 4: - prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 3) : "") + "K" + suffix; - return prefix; - case 5: - prefix += Long.toString(amnt).substring(0, 2) + (useDecimals ? "." + Long.toString(amnt).substring(2, 4) : "") + "K" + suffix; - return prefix; - case 6: - prefix += Long.toString(amnt).substring(0, 3) + (useDecimals ? "." + Long.toString(amnt).substring(3, 5) : "") + "K" + suffix; - return prefix; - } - return ""; - } - - /** - * Returns a color for the number passed, based on its percentage of the max - * - * @param num - * The number to compare - * @param max - * The max number - * - * @return if num {@literal <}= 10% of max : RED
- * if 10% {@literal <} num {@literal <}= 25% of max: GOLD (orange-ish)
- * if num {@literal >} 25% of max: GREEN - */ - public EnumChatFormatting getColorFor(double num, double max) - { - if (num / max <= .1) - return EnumChatFormatting.RED; - else if (num / max <= .25) - return EnumChatFormatting.GOLD; - else - return EnumChatFormatting.GREEN; - } - - public String getEffectNameWithLevel(PotionEffect effect) - { - String name = EnderCore.lang.localize(effect.getEffectName(), false); - - if (effect.getAmplifier() > 0) - { - name += " " + EnderCore.lang.localize("enchantment.level." + (effect.getAmplifier() + 1), false); - } - - return name; - } + return name; + } } diff --git a/src/main/java/com/enderio/core/common/util/FluidUtil.java b/src/main/java/com/enderio/core/common/util/FluidUtil.java index 252e0d8..da47a20 100644 --- a/src/main/java/com/enderio/core/common/util/FluidUtil.java +++ b/src/main/java/com/enderio/core/common/util/FluidUtil.java @@ -36,7 +36,7 @@ public class FluidUtil { try { Class.forName("crazypants.util.BuildcraftUtil"); } catch (Exception e) { - if(Loader.isModLoaded("BuildCraft|Transport")) { + if (Loader.isModLoaded("BuildCraft|Transport")) { Log.warn("ItemUtil: Could not register Build Craft pipe handler. Fluid conduits will show connections to all Build Craft pipes."); } //Don't log if BC isn't installed, but we still check in case another mod is using their API } @@ -46,7 +46,7 @@ public class FluidUtil { Map res = new HashMap(); for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { IFluidHandler fh = getFluidHandler(world, bc.getLocation(dir)); - if(fh != null) { + if (fh != null) { res.put(dir, fh); } } @@ -63,10 +63,10 @@ public class FluidUtil { } public static IFluidHandler getFluidHandler(TileEntity te) { - if(te instanceof IFluidHandler) { + if (te instanceof IFluidHandler) { IFluidHandler res = (IFluidHandler) te; for (IFluidReceptor rec : fluidReceptors) { - if(!rec.isValidReceptor(res)) { + if (!rec.isValidReceptor(res)) { return null; } } @@ -76,17 +76,17 @@ public class FluidUtil { } public static FluidStack getFluidFromItem(ItemStack stack) { - if(stack != null) { + if (stack != null) { FluidStack fluidStack = null; - if(stack.getItem() instanceof IFluidContainerItem) { + if (stack.getItem() instanceof IFluidContainerItem) { fluidStack = ((IFluidContainerItem) stack.getItem()).getFluid(stack); } - if(fluidStack == null) { + if (fluidStack == null) { fluidStack = FluidContainerRegistry.getFluidForFilledItem(stack); } - if(fluidStack == null && Block.getBlockFromItem(stack.getItem()) instanceof IFluidBlock) { + if (fluidStack == null && Block.getBlockFromItem(stack.getItem()) instanceof IFluidBlock) { Fluid fluid = ((IFluidBlock) Block.getBlockFromItem(stack.getItem())).getFluid(); - if(fluid != null) { + if (fluid != null) { return new FluidStack(fluid, 1000); } } @@ -99,18 +99,18 @@ public class FluidUtil { TileEntity te = (TileEntity) into; BlockCoord loc = new BlockCoord(te).getLocation(fromDir); IFluidHandler target = FluidUtil.getFluidHandler(te.getWorldObj(), loc); - if(target != null) { + if (target != null) { FluidTankInfo[] infos = target.getTankInfo(fromDir.getOpposite()); - if(infos != null) { + if (infos != null) { for (FluidTankInfo info : infos) { - if(info.fluid != null && info.fluid.amount > 0) { - if(into.canFill(fromDir, info.fluid.getFluid())) { + if (info.fluid != null && info.fluid.amount > 0) { + if (into.canFill(fromDir, info.fluid.getFluid())) { FluidStack canPull = info.fluid.copy(); canPull.amount = Math.min(maxVolume, canPull.amount); FluidStack drained = target.drain(fromDir.getOpposite(), canPull, false); - if(drained != null && drained.amount > 0) { + if (drained != null && drained.amount > 0) { int filled = into.fill(fromDir, drained, false); - if(filled > 0) { + if (filled > 0) { drained = target.drain(fromDir.getOpposite(), filled, true); into.fill(fromDir, drained, true); return true; @@ -129,17 +129,17 @@ public class FluidUtil { TileEntity te = (TileEntity) from; BlockCoord loc = new BlockCoord(te).getLocation(fromDir); IFluidHandler target = getFluidHandler(te.getWorldObj(), loc); - if(target == null) { + if (target == null) { return false; } FluidTankInfo[] infos = from.getTankInfo(fromDir); boolean res = false; - if(infos != null) { + if (infos != null) { for (FluidTankInfo info : infos) { - if(info.fluid != null && info.fluid.amount > 0 && from.canDrain(fromDir, info.fluid.getFluid())) { + if (info.fluid != null && info.fluid.amount > 0 && from.canDrain(fromDir, info.fluid.getFluid())) { FluidStack maxDrain = new FluidStack(info.fluid.getFluid(), maxVolume); FluidStack canDrain = from.drain(fromDir, maxDrain, false); - if(canDrain != null && canDrain.amount > 0) { + if (canDrain != null && canDrain.amount > 0) { int filled = target.fill(fromDir.getOpposite(), canDrain, true); from.drain(fromDir, new FluidStack(info.fluid.getFluid(), filled), true); res |= true; @@ -219,14 +219,13 @@ public class FluidUtil { } FluidStack resultFluid = FluidContainerRegistry.getFluidForFilledItem(source); - if (resultFluid != null && resultFluid.amount > 0 && resultFluid.amount <= maxDrain - && (target == null || resultFluid.getFluid() == target.getFluid())) { + if (resultFluid != null && resultFluid.amount > 0 && resultFluid.amount <= maxDrain && (target == null || resultFluid.getFluid() == target.getFluid())) { ItemStack resultStack = source.getItem().getContainerItem(source); // TODO -// if (resultStack == null && Config.enableWaterFromBottles && source.getItem() instanceof ItemPotion -// && source.stackTagCompound == null) { -// resultStack = new ItemStack(Items.glass_bottle); -// } + // if (resultStack == null && Config.enableWaterFromBottles && source.getItem() instanceof ItemPotion + // && source.stackTagCompound == null) { + // resultStack = new ItemStack(Items.glass_bottle); + // } ItemStack remainderStack = source.copy(); remainderStack.stackSize--; if (remainderStack.stackSize <= 0) { @@ -237,7 +236,6 @@ public class FluidUtil { return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); } - } return new FluidAndStackResult(null, null, source, target); } @@ -247,7 +245,7 @@ public class FluidUtil { if (source.getItem() instanceof IFluidContainerItem) { FluidStack fluid = ((IFluidContainerItem) source.getItem()).getFluid(source); - IFluidTank targetTank = fluid != null ? tank.getInputTank(fluid) : null; + IFluidTank targetTank = fluid != null ? tank.getInputTank(fluid) : null; if (targetTank != null) { FluidStack target = targetTank.getFluid(); int maxDrain = targetTank.getCapacity() - (target != null ? target.amount : 0); @@ -276,10 +274,10 @@ public class FluidUtil { int maxDrain = targetTank.getCapacity() - (target != null ? target.amount : 0); if (resultFluid.amount <= maxDrain && (target == null || resultFluid.getFluid() == target.getFluid())) { ItemStack resultStack = source.getItem().getContainerItem(source); -// if (resultStack == null && Config.enableWaterFromBottles && source.getItem() instanceof ItemPotion -// && source.stackTagCompound == null) { -// resultStack = new ItemStack(Items.glass_bottle); -// } + // if (resultStack == null && Config.enableWaterFromBottles && source.getItem() instanceof ItemPotion + // && source.stackTagCompound == null) { + // resultStack = new ItemStack(Items.glass_bottle); + // } ItemStack remainderStack = source.copy(); remainderStack.stackSize--; if (remainderStack.stackSize <= 0) { @@ -323,27 +321,26 @@ public class FluidUtil { * @param tank * @return true if a container was filled, false otherwise */ - public static boolean fillPlayerHandItemFromInternalTank(World world, int x, int y, int z, EntityPlayer entityPlayer, - ITankAccess tank) { + public static boolean fillPlayerHandItemFromInternalTank(World world, int x, int y, int z, EntityPlayer entityPlayer, ITankAccess tank) { for (FluidTank subTank : tank.getOutputTanks()) { FluidAndStackResult fill = tryFillContainer(entityPlayer.inventory.getCurrentItem(), subTank.getFluid()); - if(fill.result.fluidStack != null) { + if (fill.result.fluidStack != null) { subTank.setFluid(fill.remainder.fluidStack); tank.setTanksDirty(); - if(!entityPlayer.capabilities.isCreativeMode) { - if(fill.remainder.itemStack == null) { + if (!entityPlayer.capabilities.isCreativeMode) { + if (fill.remainder.itemStack == null) { entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, fill.result.itemStack); return true; } else { entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, fill.remainder.itemStack); } - if(fill.result.itemStack.isStackable()) { + if (fill.result.itemStack.isStackable()) { for (int i = 0; i < entityPlayer.inventory.mainInventory.length; i++) { ItemStack inventoryItem = entityPlayer.inventory.mainInventory[i]; - if(ItemUtil.areStackMergable(inventoryItem, fill.result.itemStack) && inventoryItem.stackSize < inventoryItem.getMaxStackSize()) { + if (ItemUtil.areStackMergable(inventoryItem, fill.result.itemStack) && inventoryItem.stackSize < inventoryItem.getMaxStackSize()) { fill.result.itemStack.stackSize += inventoryItem.stackSize; entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); return true; @@ -352,13 +349,13 @@ public class FluidUtil { } for (int i = 0; i < entityPlayer.inventory.mainInventory.length; i++) { - if(entityPlayer.inventory.mainInventory[i] == null) { + if (entityPlayer.inventory.mainInventory[i] == null) { entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); return true; } } - if(!world.isRemote) { + if (!world.isRemote) { double x0 = (x + entityPlayer.posX) / 2.0D; double y0 = (y + entityPlayer.posY) / 2.0D + 0.5D; double z0 = (z + entityPlayer.posZ) / 2.0D; @@ -372,28 +369,27 @@ public class FluidUtil { return false; } - public static boolean fillInternalTankFromPlayerHandItem(World world, int x, int y, int z, EntityPlayer entityPlayer, - ITankAccess tank) { + public static boolean fillInternalTankFromPlayerHandItem(World world, int x, int y, int z, EntityPlayer entityPlayer, ITankAccess tank) { FluidAndStackResult fill = tryDrainContainer(entityPlayer.inventory.getCurrentItem(), tank); - if(fill.result.fluidStack == null) { + if (fill.result.fluidStack == null) { return false; } tank.getInputTank(fill.result.fluidStack).setFluid(fill.remainder.fluidStack); tank.setTanksDirty(); - if(!entityPlayer.capabilities.isCreativeMode) { - if(fill.remainder.itemStack == null) { + if (!entityPlayer.capabilities.isCreativeMode) { + if (fill.remainder.itemStack == null) { entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, fill.result.itemStack); return true; } else { entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, fill.remainder.itemStack); } - if(fill.result.itemStack.isStackable()) { + if (fill.result.itemStack.isStackable()) { for (int i = 0; i < entityPlayer.inventory.mainInventory.length; i++) { ItemStack inventoryItem = entityPlayer.inventory.mainInventory[i]; - if(ItemUtil.areStackMergable(inventoryItem, fill.result.itemStack) && inventoryItem.stackSize < inventoryItem.getMaxStackSize()) { + if (ItemUtil.areStackMergable(inventoryItem, fill.result.itemStack) && inventoryItem.stackSize < inventoryItem.getMaxStackSize()) { fill.result.itemStack.stackSize += inventoryItem.stackSize; entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); return true; @@ -402,13 +398,13 @@ public class FluidUtil { } for (int i = 0; i < entityPlayer.inventory.mainInventory.length; i++) { - if(entityPlayer.inventory.mainInventory[i] == null) { + if (entityPlayer.inventory.mainInventory[i] == null) { entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); return true; } } - if(!world.isRemote) { + if (!world.isRemote) { double x0 = (x + entityPlayer.posX) / 2.0D; double y0 = (y + entityPlayer.posY) / 2.0D + 0.5D; double z0 = (z + entityPlayer.posZ) / 2.0D; @@ -443,14 +439,12 @@ public class FluidUtil { this.remainder = remainder; } - public FluidAndStackResult(FluidStack fluidStackResult, ItemStack itemStackResult, FluidStack fluidStackRemainder, - ItemStack itemStackRemainder) { + public FluidAndStackResult(FluidStack fluidStackResult, ItemStack itemStackResult, FluidStack fluidStackRemainder, ItemStack itemStackRemainder) { this.result = new FluidAndStack(fluidStackResult, itemStackResult); this.remainder = new FluidAndStack(fluidStackRemainder, itemStackRemainder); } - public FluidAndStackResult(ItemStack itemStackResult, FluidStack fluidStackResult, ItemStack itemStackRemainder, - FluidStack fluidStackRemainder) { + public FluidAndStackResult(ItemStack itemStackResult, FluidStack fluidStackResult, ItemStack itemStackRemainder, FluidStack fluidStackRemainder) { this.result = new FluidAndStack(fluidStackResult, itemStackResult); this.remainder = new FluidAndStack(fluidStackRemainder, itemStackRemainder); } diff --git a/src/main/java/com/enderio/core/common/util/ForgeDirectionOffsets.java b/src/main/java/com/enderio/core/common/util/ForgeDirectionOffsets.java index 1dff19f..c621dea 100644 --- a/src/main/java/com/enderio/core/common/util/ForgeDirectionOffsets.java +++ b/src/main/java/com/enderio/core/common/util/ForgeDirectionOffsets.java @@ -41,10 +41,10 @@ public final class ForgeDirectionOffsets { float ay = Math.abs(y); float az = Math.abs(z); - if(ax >= ay && ax >= az) { + if (ax >= ay && ax >= az) { return x > 0 ? ForgeDirection.EAST : ForgeDirection.WEST; } - if(ay >= ax && ay >= az) { + if (ay >= ax && ay >= az) { return y > 0 ? ForgeDirection.UP : ForgeDirection.DOWN; } return z > 0 ? ForgeDirection.SOUTH : ForgeDirection.NORTH; diff --git a/src/main/java/com/enderio/core/common/util/InventoryWrapper.java b/src/main/java/com/enderio/core/common/util/InventoryWrapper.java index 2953d4c..6f7a528 100644 --- a/src/main/java/com/enderio/core/common/util/InventoryWrapper.java +++ b/src/main/java/com/enderio/core/common/util/InventoryWrapper.java @@ -8,10 +8,10 @@ import net.minecraft.item.ItemStack; public class InventoryWrapper implements ISidedInventory { public static ISidedInventory asSidedInventory(IInventory inv) { - if(inv == null) { + if (inv == null) { return null; } - if(inv instanceof ISidedInventory) { + if (inv instanceof ISidedInventory) { return (ISidedInventory) inv; } return new InventoryWrapper(inv); @@ -34,7 +34,7 @@ public class InventoryWrapper implements ISidedInventory { @Override public ItemStack getStackInSlot(int slot) { - if(slot < 0 || slot >= inv.getSizeInventory()) { + if (slot < 0 || slot >= inv.getSizeInventory()) { return null; } return inv.getStackInSlot(slot); @@ -52,7 +52,7 @@ public class InventoryWrapper implements ISidedInventory { @Override public void setInventorySlotContents(int slot, ItemStack itemStack) { - if(slot >= 0 && slot < inv.getSizeInventory()) { + if (slot >= 0 && slot < inv.getSizeInventory()) { inv.setInventorySlotContents(slot, itemStack); } } diff --git a/src/main/java/com/enderio/core/common/util/ItemUtil.java b/src/main/java/com/enderio/core/common/util/ItemUtil.java index 2babd01..26cb102 100644 --- a/src/main/java/com/enderio/core/common/util/ItemUtil.java +++ b/src/main/java/com/enderio/core/common/util/ItemUtil.java @@ -357,7 +357,8 @@ public class ItemUtil { return doInsertItemInv(inv, sidedInv, slots, item, inventorySide, doInsert); } - private static int doInsertItemInv(IInventory inv, ISidedInventory sidedInv, ISlotIterator slots, ItemStack item, ForgeDirection inventorySide, boolean doInsert) { + private static int doInsertItemInv(IInventory inv, ISidedInventory sidedInv, ISlotIterator slots, ItemStack item, ForgeDirection inventorySide, + boolean doInsert) { int numInserted = 0; int numToInsert = item.stackSize; int firstFreeSlot = -1; diff --git a/src/main/java/com/enderio/core/common/util/Log.java b/src/main/java/com/enderio/core/common/util/Log.java index 51e7929..1565517 100644 --- a/src/main/java/com/enderio/core/common/util/Log.java +++ b/src/main/java/com/enderio/core/common/util/Log.java @@ -5,7 +5,6 @@ import org.apache.logging.log4j.Logger; import com.enderio.core.EnderCore; - public final class Log { public static final Logger LOGGER = LogManager.getLogger(EnderCore.MODID); diff --git a/src/main/java/com/enderio/core/common/util/MetadataUtil.java b/src/main/java/com/enderio/core/common/util/MetadataUtil.java index 74eb87c..50ea897 100644 --- a/src/main/java/com/enderio/core/common/util/MetadataUtil.java +++ b/src/main/java/com/enderio/core/common/util/MetadataUtil.java @@ -4,7 +4,7 @@ public class MetadataUtil { public static void printBits(int meta) { for (int k = 0; k < 4; k++) { - if(((meta >> k) & 1) == 1) { + if (((meta >> k) & 1) == 1) { System.out.print(1); } else { System.out.print(0); @@ -16,7 +16,7 @@ public class MetadataUtil { public static String toBitString(int meta) { StringBuilder sb = new StringBuilder(); for (int k = 0; k < 4; k++) { - if(((meta >> k) & 1) == 1) { + if (((meta >> k) & 1) == 1) { sb.append(1); } else { sb.append(0); @@ -30,7 +30,7 @@ public class MetadataUtil { } public static int setBit(int position, boolean value, int meta) { - if(value) { + if (value) { return meta | (1 << position); } return meta & ~(1 << position); diff --git a/src/main/java/com/enderio/core/common/util/PermanentCache.java b/src/main/java/com/enderio/core/common/util/PermanentCache.java index 5ddf300..0e35d29 100644 --- a/src/main/java/com/enderio/core/common/util/PermanentCache.java +++ b/src/main/java/com/enderio/core/common/util/PermanentCache.java @@ -26,14 +26,14 @@ public class PermanentCache extends WorldCache { } return new File("saves", ident + ".dat"); } - + @Override protected void blockOldIDs() { if (!objToName.isEmpty()) { super.blockOldIDs(); } } - + @Override protected void mergeNewIDs() { if (!objToName.isEmpty()) { diff --git a/src/main/java/com/enderio/core/common/util/PlayerUtil.java b/src/main/java/com/enderio/core/common/util/PlayerUtil.java index 1925062..1bbb5f7 100644 --- a/src/main/java/com/enderio/core/common/util/PlayerUtil.java +++ b/src/main/java/com/enderio/core/common/util/PlayerUtil.java @@ -9,7 +9,7 @@ public class PlayerUtil { public static UUID getPlayerUUID(String username) { for (Map.Entry entry : UsernameCache.getMap().entrySet()) { - if(entry.getValue().equalsIgnoreCase(username)) { + if (entry.getValue().equalsIgnoreCase(username)) { return entry.getKey(); } } @@ -17,7 +17,7 @@ public class PlayerUtil { } public static UUID getPlayerUIDUnstable(String possibleUUID) { - if(possibleUUID == null || possibleUUID.isEmpty()) + if (possibleUUID == null || possibleUUID.isEmpty()) return null; UUID uuid = null; try { diff --git a/src/main/java/com/enderio/core/common/util/RegisterTime.java b/src/main/java/com/enderio/core/common/util/RegisterTime.java index 9c6fe40..2a9ee5b 100644 --- a/src/main/java/com/enderio/core/common/util/RegisterTime.java +++ b/src/main/java/com/enderio/core/common/util/RegisterTime.java @@ -7,21 +7,19 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLStateEvent; @AllArgsConstructor -public enum RegisterTime -{ - PREINIT(FMLPreInitializationEvent.class), INIT(FMLInitializationEvent.class), POSTINIT(FMLPostInitializationEvent.class); +public enum RegisterTime { + PREINIT(FMLPreInitializationEvent.class), + INIT(FMLInitializationEvent.class), + POSTINIT(FMLPostInitializationEvent.class); - private Class clazz; + private Class clazz; - public static RegisterTime timeFor(FMLStateEvent event) - { - for (RegisterTime time : values()) - { - if (time.clazz == event.getClass()) - { - return time; - } - } - return null; + public static RegisterTime timeFor(FMLStateEvent event) { + for (RegisterTime time : values()) { + if (time.clazz == event.getClass()) { + return time; + } } + return null; + } } diff --git a/src/main/java/com/enderio/core/common/util/ResourcePackAssembler.java b/src/main/java/com/enderio/core/common/util/ResourcePackAssembler.java index 7304a83..b0e0c22 100644 --- a/src/main/java/com/enderio/core/common/util/ResourcePackAssembler.java +++ b/src/main/java/com/enderio/core/common/util/ResourcePackAssembler.java @@ -35,225 +35,198 @@ import cpw.mods.fml.relauncher.ReflectionHelper; *

* Also, {@link #setHasPackPng(Class)} allows your resource pack to have a logo. */ -public class ResourcePackAssembler -{ - @AllArgsConstructor - private class CustomFile - { - private String ext; - private File file; +public class ResourcePackAssembler { + @AllArgsConstructor + private class CustomFile { + private String ext; + private File file; + } + + private List icons = new ArrayList(); + private List langs = new ArrayList(); + private List customs = new ArrayList(); + + private static List defaultResourcePacks; + + private static final String MC_META_BASE = "{\"pack\":{\"pack_format\":1,\"description\":\"%s\"}}"; + + private File dir; + private File zip; + private String name; + private String mcmeta; + private String modid; + private boolean hasPackPng = false; + private Class jarClass; + + /** + * @param directory + * The directory to assemble the resource pack in. The name of the + * zip created will be the same as this folder, and it will be + * created on the same level as the folder. This folder will be + * WIPED on every call of {@link #assemble()} . + * @param packName + * The name of the resource pack. + * @param modid + * Your mod's mod ID. + */ + public ResourcePackAssembler(File directory, String packName, String modid) { + this.dir = directory; + this.zip = new File(dir.getAbsolutePath() + ".zip"); + this.name = packName; + this.modid = modid.toLowerCase(Locale.US); + this.mcmeta = String.format(MC_META_BASE, this.name); + } + + /** + * Enables the use of a pack.png. + *

+ * Will cause your mod's jar to be searched for a resource pack logo at + * assets/[modid]/pack.png. + * + * @param jarClass + * A class in your jar file. + * @return The {@link ResourcePackAssembler} instance. + */ + public ResourcePackAssembler setHasPackPng(Class jarClass) { + this.jarClass = jarClass; + hasPackPng = true; + return this; + } + + /** + * Adds an icon file. This file will be inserted into both the block and item + * texture folders. + * + * @param icon + * The icon file. + */ + public void addIcon(File icon) { + icons.add(icon); + } + + /** + * Adds a language file. This file will be inserted into the lang dir only. + * + * @param lang + * A language file (e.g. en_US.lang) + */ + public void addLang(File lang) { + langs.add(lang); + } + + /** + * Adds a custom file to the pack. This can be added into any folder in the + * pack you desire. Useful for one-off files such as sounds.json. + * + * @param path + * The path inside the resource pack to this file. + * @param file + * The file to add. + */ + public void addCustomFile(String path, File file) { + customs.add(new CustomFile(path, file)); + } + + /** + * Adds the custom file at the base directory. + * + * @see #addCustomFile(String, File) + * + * @param file + * The file to add. + */ + public void addCustomFile(File file) { + addCustomFile(null, file); + } + + /** + * Assembles the resource pack. This creates a zip file with the name of the + * {@link File directory} that was passed into the constructor on the same + * level as that folder. + * + * @return The {@link ResourcePackAssembler} instance. + */ + public ResourcePackAssembler assemble() { + EnderFileUtils.safeDeleteDirectory(dir); + dir.mkdirs(); + + String pathToDir = dir.getAbsolutePath(); + File metaFile = new File(pathToDir + "/pack.mcmeta"); + + try { + writeNewFile(metaFile, mcmeta); + + if (hasPackPng) { + EnderFileUtils.copyFromJar(jarClass, modid + "/" + "pack.png", new File(dir.getAbsolutePath() + "/pack.png")); + } + + String itemsDir = pathToDir + "/assets/" + modid + "/textures/items"; + String blocksDir = pathToDir + "/assets/" + modid + "/textures/blocks"; + String langDir = pathToDir + "/assets/" + modid + "/lang"; + + for (File icon : icons) { + FileUtils.copyFile(icon, new File(itemsDir + "/" + icon.getName())); + FileUtils.copyFile(icon, new File(blocksDir + "/" + icon.getName())); + } + + for (File lang : langs) { + FileUtils.copyFile(lang, new File(langDir + "/" + lang.getName())); + } + + for (CustomFile custom : customs) { + File directory = new File(pathToDir + (custom.ext != null ? "/" + custom.ext : "")); + directory.mkdirs(); + FileUtils.copyFile(custom.file, new File(directory.getAbsolutePath() + "/" + custom.file.getName())); + } + + EnderFileUtils.zipFolderContents(dir, zip); + EnderFileUtils.safeDeleteDirectory(dir); + } catch (IOException e) { + throw new RuntimeException(e); } - private List icons = new ArrayList(); - private List langs = new ArrayList(); - private List customs = new ArrayList(); + return this; + } - private static List defaultResourcePacks; - - private static final String MC_META_BASE = "{\"pack\":{\"pack_format\":1,\"description\":\"%s\"}}"; - - private File dir; - private File zip; - private String name; - private String mcmeta; - private String modid; - private boolean hasPackPng = false; - private Class jarClass; - - /** - * @param directory - * The directory to assemble the resource pack in. The name of - * the zip created will be the same as this folder, and it will - * be created on the same level as the folder. This folder will - * be WIPED on every call of {@link #assemble()} - * . - * @param packName - * The name of the resource pack. - * @param modid - * Your mod's mod ID. - */ - public ResourcePackAssembler(File directory, String packName, String modid) - { - this.dir = directory; - this.zip = new File(dir.getAbsolutePath() + ".zip"); - this.name = packName; - this.modid = modid.toLowerCase(Locale.US); - this.mcmeta = String.format(MC_META_BASE, this.name); - } - - /** - * Enables the use of a pack.png. - *

- * Will cause your mod's jar to be searched for a resource pack logo at - * assets/[modid]/pack.png. - * - * @param jarClass - * A class in your jar file. - * @return The {@link ResourcePackAssembler} instance. - */ - public ResourcePackAssembler setHasPackPng(Class jarClass) - { - this.jarClass = jarClass; - hasPackPng = true; - return this; - } - - /** - * Adds an icon file. This file will be inserted into both the block and - * item texture folders. - * - * @param icon - * The icon file. - */ - public void addIcon(File icon) - { - icons.add(icon); - } - - /** - * Adds a language file. This file will be inserted into the lang dir only. - * - * @param lang - * A language file (e.g. en_US.lang) - */ - public void addLang(File lang) - { - langs.add(lang); - } - - /** - * Adds a custom file to the pack. This can be added into any folder in the - * pack you desire. Useful for one-off files such as sounds.json. - * - * @param path - * The path inside the resource pack to this file. - * @param file - * The file to add. - */ - public void addCustomFile(String path, File file) - { - customs.add(new CustomFile(path, file)); - } - - /** - * Adds the custom file at the base directory. - * - * @see #addCustomFile(String, File) - * - * @param file - * The file to add. - */ - public void addCustomFile(File file) - { - addCustomFile(null, file); - } - - /** - * Assembles the resource pack. This creates a zip file with the name of the - * {@link File directory} that was passed into the constructor on the same - * level as that folder. - * - * @return The {@link ResourcePackAssembler} instance. - */ - public ResourcePackAssembler assemble() - { - EnderFileUtils.safeDeleteDirectory(dir); - dir.mkdirs(); - - String pathToDir = dir.getAbsolutePath(); - File metaFile = new File(pathToDir + "/pack.mcmeta"); - - try - { - writeNewFile(metaFile, mcmeta); - - if (hasPackPng) - { - EnderFileUtils.copyFromJar(jarClass, modid + "/" + "pack.png", new File(dir.getAbsolutePath() + "/pack.png")); - } - - String itemsDir = pathToDir + "/assets/" + modid + "/textures/items"; - String blocksDir = pathToDir + "/assets/" + modid + "/textures/blocks"; - String langDir = pathToDir + "/assets/" + modid + "/lang"; - - for (File icon : icons) - { - FileUtils.copyFile(icon, new File(itemsDir + "/" + icon.getName())); - FileUtils.copyFile(icon, new File(blocksDir + "/" + icon.getName())); - } - - for (File lang : langs) - { - FileUtils.copyFile(lang, new File(langDir + "/" + lang.getName())); - } - - for (CustomFile custom : customs) - { - File directory = new File(pathToDir + (custom.ext != null ? "/" + custom.ext : "")); - directory.mkdirs(); - FileUtils.copyFile(custom.file, new File(directory.getAbsolutePath() + "/" + custom.file.getName())); - } - - EnderFileUtils.zipFolderContents(dir, zip); - EnderFileUtils.safeDeleteDirectory(dir); - } - catch (IOException e) - { - throw new RuntimeException(e); + /** + * Inserts the resource pack into the game. Enabling the resource pack will + * not be required, it will load automatically. + *

+ * A cache of the pack zip will be kept in "resourcepack/[pack name].zip" + * where "resourcepack" is a folder at the same level as the directory passed + * into the constructor. + */ + public void inject() { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + try { + if (defaultResourcePacks == null) { + defaultResourcePacks = ReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), "defaultResourcePacks", "field_110449_ao", "ap"); } - return this; + File dest = new File(dir.getParent() + "/resourcepack/" + zip.getName()); + EnderFileUtils.safeDelete(dest); + FileUtils.copyFile(zip, dest); + EnderFileUtils.safeDelete(zip); + writeNewFile(new File(dest.getParent() + "/readme.txt"), + EnderCore.lang.localize("resourcepack.readme") + "\n\n" + EnderCore.lang.localize("resourcepack.readme2")); + defaultResourcePacks.add(new FileResourcePack(dest)); + } catch (Exception e) { + EnderCore.logger.error("Failed to inject resource pack for mod {}", modid, e); + } + } else { + EnderCore.logger.info("Skipping resource pack, we are on a dedicated server."); } + } - /** - * Inserts the resource pack into the game. Enabling the resource pack will - * not be required, it will load automatically. - *

- * A cache of the pack zip will be kept in "resourcepack/[pack name].zip" - * where "resourcepack" is a folder at the same level as the directory - * passed into the constructor. - */ - public void inject() - { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) - { - try - { - if (defaultResourcePacks == null) - { - defaultResourcePacks = ReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), "defaultResourcePacks", - "field_110449_ao", "ap"); - } + private void writeNewFile(File file, String defaultText) throws IOException { + EnderFileUtils.safeDelete(file); + file.delete(); + file.getParentFile().mkdirs(); + file.createNewFile(); - File dest = new File(dir.getParent() + "/resourcepack/" + zip.getName()); - EnderFileUtils.safeDelete(dest); - FileUtils.copyFile(zip, dest); - EnderFileUtils.safeDelete(zip); - writeNewFile(new File(dest.getParent() + "/readme.txt"), - EnderCore.lang.localize("resourcepack.readme") + "\n\n" + EnderCore.lang.localize("resourcepack.readme2")); - defaultResourcePacks.add(new FileResourcePack(dest)); - } - catch (Exception e) - { - EnderCore.logger.error("Failed to inject resource pack for mod {}", modid, e); - } - } - else - { - EnderCore.logger.info("Skipping resource pack, we are on a dedicated server."); - } - } - - private void writeNewFile(File file, String defaultText) throws IOException - { - EnderFileUtils.safeDelete(file); - file.delete(); - file.getParentFile().mkdirs(); - file.createNewFile(); - - FileWriter fw = new FileWriter(file); - fw.write(defaultText); - fw.flush(); - fw.close(); - } + FileWriter fw = new FileWriter(file); + fw.write(defaultText); + fw.flush(); + fw.close(); + } } diff --git a/src/main/java/com/enderio/core/common/util/RoundRobinIterator.java b/src/main/java/com/enderio/core/common/util/RoundRobinIterator.java index 67b41bf..9bea26d 100644 --- a/src/main/java/com/enderio/core/common/util/RoundRobinIterator.java +++ b/src/main/java/com/enderio/core/common/util/RoundRobinIterator.java @@ -9,7 +9,7 @@ public class RoundRobinIterator implements Iterable, Iterator { private int currentCount = 0; private final List itOver; - public RoundRobinIterator(List itOver) { + public RoundRobinIterator(List itOver) { this.itOver = itOver; } @@ -26,19 +26,19 @@ public class RoundRobinIterator implements Iterable, Iterator { @Override public T next() { - if(itOver.isEmpty()) { + if (itOver.isEmpty()) { return null; } currentCount++; index++; - if(index >= itOver.size()) { + if (index >= itOver.size()) { index = 0; } return itOver.get(index); } @Override - public void remove() { + public void remove() { } - + } diff --git a/src/main/java/com/enderio/core/common/util/Scheduler.java b/src/main/java/com/enderio/core/common/util/Scheduler.java index 38b1e50..d3bd5c3 100644 --- a/src/main/java/com/enderio/core/common/util/Scheduler.java +++ b/src/main/java/com/enderio/core/common/util/Scheduler.java @@ -22,116 +22,101 @@ import cpw.mods.fml.relauncher.SideOnly; * Convenience helper to schedule events to happen in the future. */ @Handler(getInstFrom = Inst.METHOD) -public class Scheduler -{ - @AllArgsConstructor - private static final class Task - { - private int delay; - private Runnable toRun; - private Side side; +public class Scheduler { + @AllArgsConstructor + private static final class Task { + private int delay; + private Runnable toRun; + private Side side; - private boolean run() - { - if (delay <= 0) - { - toRun.run(); - return true; - } - delay--; - return false; - } + private boolean run() { + if (delay <= 0) { + toRun.run(); + return true; + } + delay--; + return false; } + } - private final List tasks = new ArrayList(); + private final List tasks = new ArrayList(); - /** - * Schedules a task to be called later - * - * @param delay - * The amount of ticks to delay the call - * @param task - * The {@link Runnable} to be run when the delay is up - * - * @see {@link #schedule(int, Runnable, Side)} for more details. - */ - public void schedule(int delay, Runnable task) - { - schedule(delay, task, Side.SERVER); + /** + * Schedules a task to be called later + * + * @param delay + * The amount of ticks to delay the call + * @param task + * The {@link Runnable} to be run when the delay is up + * + * @see {@link #schedule(int, Runnable, Side)} for more details. + */ + public void schedule(int delay, Runnable task) { + schedule(delay, task, Side.SERVER); + } + + /** + * Schedules a task to be called later + * + * @param delay + * The amount of ticks to delay the call + * @param task + * The {@link Runnable} to be run when the delay is up + * @param side + * The side to schedule the task on. + *

+ * You will get a different {@link TickEvent} depending on the side. + *
+ * {@link Side#CLIENT} will be passed a {@link ClientTickEvent}
+ * {@link Side#SERVER} will be passed a {@link ServerTickEvent} + *

+ * Note: passing in {@link Side#CLIENT} on a dedicated server will + * work, but your task will never be called. Please avoid doing this + * to save processing. + */ + public void schedule(int delay, Runnable task, Side side) { + tasks.add(new Task(delay, task, side)); + } + + /** + * Returns the {@link Scheduler} instance for the current side. + * + * @see {@link Scheduler#schedule(int, Runnable)} for scheduling information. + * + * @return The {@link Scheduler} instance. + */ + public static Scheduler instance() { + return EnderCore.proxy.getScheduler(); + } + + /** + * For internal use only. Do not call. + */ + @SubscribeEvent + public void onServerTick(ServerTickEvent event) { + if (event.phase == Phase.END) { + runTasks(Side.SERVER); } + } - /** - * Schedules a task to be called later - * - * @param delay - * The amount of ticks to delay the call - * @param task - * The {@link Runnable} to be run when the delay is up - * @param side - * The side to schedule the task on. - *

- * You will get a different {@link TickEvent} depending on the - * side.
- * {@link Side#CLIENT} will be passed a {@link ClientTickEvent}
- * {@link Side#SERVER} will be passed a {@link ServerTickEvent} - *

- * Note: passing in {@link Side#CLIENT} on a dedicated server - * will work, but your task will never be called. Please avoid - * doing this to save processing. - */ - public void schedule(int delay, Runnable task, Side side) - { - tasks.add(new Task(delay, task, side)); + /** + * For internal use only. Do not call. + */ + @SideOnly(Side.CLIENT) + @SubscribeEvent + public void onClientTick(ClientTickEvent event) { + if (event.phase == Phase.END) { + runTasks(Side.CLIENT); } + } - /** - * Returns the {@link Scheduler} instance for the current side. - * - * @see {@link Scheduler#schedule(int, Runnable)} for scheduling - * information. - * - * @return The {@link Scheduler} instance. - */ - public static Scheduler instance() - { - return EnderCore.proxy.getScheduler(); - } - - /** - * For internal use only. Do not call. - */ - @SubscribeEvent - public void onServerTick(ServerTickEvent event) - { - if (event.phase == Phase.END) - { - runTasks(Side.SERVER); - } - } - - /** - * For internal use only. Do not call. - */ - @SideOnly(Side.CLIENT) - @SubscribeEvent - public void onClientTick(ClientTickEvent event) - { - if (event.phase == Phase.END) - { - runTasks(Side.CLIENT); - } - } - - private void runTasks(Side side) - { - Iterator iter = tasks.iterator(); - while (iter.hasNext()) - { - Task next = iter.next(); - if (next.side == side && next.run()) - { - iter.remove(); - } - } + private void runTasks(Side side) { + Iterator iter = tasks.iterator(); + while (iter.hasNext()) { + Task next = iter.next(); + if (next.side == side && next.run()) { + iter.remove(); + } } + } } diff --git a/src/main/java/com/enderio/core/common/util/SoundUtil.java b/src/main/java/com/enderio/core/common/util/SoundUtil.java index 00a5ea2..e46b046 100644 --- a/src/main/java/com/enderio/core/common/util/SoundUtil.java +++ b/src/main/java/com/enderio/core/common/util/SoundUtil.java @@ -10,8 +10,9 @@ public class SoundUtil { @SideOnly(Side.CLIENT) public static void playClientSoundFX(String name, TileEntity te) { - World world = Minecraft.getMinecraft().thePlayer.worldObj; - Minecraft.getMinecraft().theWorld.playSound(te.xCoord + 0.5, te.yCoord + 0.5, te.zCoord + 0.5, name, 0.1F, 0.5F * ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7F + 1.8F),true); + World world = Minecraft.getMinecraft().thePlayer.worldObj; + Minecraft.getMinecraft().theWorld.playSound(te.xCoord + 0.5, te.yCoord + 0.5, te.zCoord + 0.5, name, 0.1F, + 0.5F * ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7F + 1.8F), true); } - + } diff --git a/src/main/java/com/enderio/core/common/util/TextureErrorRemover.java b/src/main/java/com/enderio/core/common/util/TextureErrorRemover.java index aae47f4..d794ead 100644 --- a/src/main/java/com/enderio/core/common/util/TextureErrorRemover.java +++ b/src/main/java/com/enderio/core/common/util/TextureErrorRemover.java @@ -17,60 +17,47 @@ import com.enderio.core.common.config.ConfigHandler; import cpw.mods.fml.relauncher.ReflectionHelper; -public class TextureErrorRemover extends Logger -{ - private static TextureErrorRemover INSTANCE; - private int removed = 0; +public class TextureErrorRemover extends Logger { + private static TextureErrorRemover INSTANCE; + private int removed = 0; - private TextureErrorRemover(Logger other) - { - super(other.getContext(), other.getName(), other.getMessageFactory()); - } + private TextureErrorRemover(Logger other) { + super(other.getContext(), other.getName(), other.getMessageFactory()); + } - @Override - public void log(Marker marker, String fqcn, Level level, Message data, Throwable t) - { - if (ConfigHandler.textureErrorRemover != 0) - { - if (t instanceof FileNotFoundException) - { - if (ConfigHandler.textureErrorRemover == 1) - { - super.log(marker, fqcn, level, data, null); - } - removed++; - } - else - { - super.log(marker, fqcn, level, data, t); - } - if (data.getFormat().startsWith("Created:")) - { - EnderCore.logger.info(ConfigHandler.textureErrorRemover == 1 ? new FormattedMessage("Removed %d missing texture stacktraces. Tada!", - removed) : new FormattedMessage("There were %d missing texture errors here. They're gone now.", removed)); - removed = 0; - } - return; + @Override + public void log(Marker marker, String fqcn, Level level, Message data, Throwable t) { + if (ConfigHandler.textureErrorRemover != 0) { + if (t instanceof FileNotFoundException) { + if (ConfigHandler.textureErrorRemover == 1) { + super.log(marker, fqcn, level, data, null); } + removed++; + } else { super.log(marker, fqcn, level, data, t); + } + if (data.getFormat().startsWith("Created:")) { + EnderCore.logger.info(ConfigHandler.textureErrorRemover == 1 ? new FormattedMessage("Removed %d missing texture stacktraces. Tada!", removed) + : new FormattedMessage("There were %d missing texture errors here. They're gone now.", removed)); + removed = 0; + } + return; } + super.log(marker, fqcn, level, data, t); + } - public static void beginIntercepting() - { - EnderCore.logger.info("Attempting to initialize texture error message interceptor."); - try - { - Field f = ReflectionHelper.findField(TextureMap.class, "logger", "field_147635_d", "d"); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); - f.setAccessible(true); - INSTANCE = new TextureErrorRemover((Logger) f.get(null)); - f.set(null, INSTANCE); - } - catch (Exception e) - { - EnderCore.logger.error("Failed to initialize texture error interceptor!", e); - } + public static void beginIntercepting() { + EnderCore.logger.info("Attempting to initialize texture error message interceptor."); + try { + Field f = ReflectionHelper.findField(TextureMap.class, "logger", "field_147635_d", "d"); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); + f.setAccessible(true); + INSTANCE = new TextureErrorRemover((Logger) f.get(null)); + f.set(null, INSTANCE); + } catch (Exception e) { + EnderCore.logger.error("Failed to initialize texture error interceptor!", e); } + } } diff --git a/src/main/java/com/enderio/core/common/util/Util.java b/src/main/java/com/enderio/core/common/util/Util.java index 874da0b..19e7d34 100644 --- a/src/main/java/com/enderio/core/common/util/Util.java +++ b/src/main/java/com/enderio/core/common/util/Util.java @@ -34,23 +34,23 @@ public class Util { public static Block getBlockFromItemId(ItemStack itemId) { Item item = itemId.getItem(); - if(item instanceof ItemBlock) { + if (item instanceof ItemBlock) { return ((ItemBlock) item).field_150939_a; } return null; } public static ItemStack consumeItem(ItemStack stack) { - if(stack.getItem() instanceof ItemPotion) { - if(stack.stackSize == 1) { + if (stack.getItem() instanceof ItemPotion) { + if (stack.stackSize == 1) { return new ItemStack(Items.glass_bottle); } else { stack.splitStack(1); return stack; } } - if(stack.stackSize == 1) { - if(stack.getItem().hasContainerItem(stack)) { + if (stack.stackSize == 1) { + if (stack.getItem().hasContainerItem(stack)) { return stack.getItem().getContainerItem(stack); } else { return null; @@ -62,9 +62,9 @@ public class Util { } public static void giveExperience(EntityPlayer thePlayer, float experience) { - if(experience < 1.0F) { + if (experience < 1.0F) { int rndRound = MathHelper.floor_float(experience); - if(rndRound < MathHelper.ceiling_float_int(experience) && (float) Math.random() < experience) { + if (rndRound < MathHelper.ceiling_float_int(experience) && (float) Math.random() < experience) { ++rndRound; } experience = rndRound; @@ -80,39 +80,38 @@ public class Util { // derived from ItemBlock.onItemUse public static BlockCoord canPlaceItem(ItemStack itemUsed, Block blockIdToBePlaced, EntityPlayer player, World world, int x, int y, int z, int side) { - if(blockIdToBePlaced == null) { + if (blockIdToBePlaced == null) { return null; } Block block = world.getBlock(x, y, z); - if(block == Blocks.snow_layer && (world.getBlockMetadata(x, y, z) & 7) < 1) { + if (block == Blocks.snow_layer && (world.getBlockMetadata(x, y, z) & 7) < 1) { side = 1; - } else if(block != Blocks.vine && block != Blocks.tallgrass && block != Blocks.deadbush - && (block == null || !block.isReplaceable(world, x, y, z))) { + } else if (block != Blocks.vine && block != Blocks.tallgrass && block != Blocks.deadbush && (block == null || !block.isReplaceable(world, x, y, z))) { - if(side == 0) { + if (side == 0) { --y; - } else if(side == 1) { + } else if (side == 1) { ++y; - } else if(side == 2) { + } else if (side == 2) { --z; - } else if(side == 3) { + } else if (side == 3) { ++z; - } else if(side == 4) { + } else if (side == 4) { --x; - } else if(side == 5) { + } else if (side == 5) { ++x; } } - if(itemUsed.stackSize == 0) { + if (itemUsed.stackSize == 0) { return null; - } else if(!player.canPlayerEdit(x, y, z, side, itemUsed)) { + } else if (!player.canPlayerEdit(x, y, z, side, itemUsed)) { return null; - } else if(y == 255 && blockIdToBePlaced.getMaterial().isSolid()) { + } else if (y == 255 && blockIdToBePlaced.getMaterial().isSolid()) { return null; - } else if(world.canPlaceEntityOnSide(blockIdToBePlaced, x, y, z, false, side, player, itemUsed)) { + } else if (world.canPlaceEntityOnSide(blockIdToBePlaced, x, y, z, false, side, player, itemUsed)) { return new BlockCoord(x, y, z); } return null; @@ -120,10 +119,10 @@ public class Util { } public static EntityItem createDrop(World world, ItemStack stack, double x, double y, double z, boolean doRandomSpread) { - if(stack == null || stack.stackSize <= 0) { + if (stack == null || stack.stackSize <= 0) { return null; } - if(doRandomSpread) { + if (doRandomSpread) { float f1 = 0.7F; double d = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; double d1 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; @@ -142,7 +141,7 @@ public class Util { } public static void dropItems(World world, ItemStack stack, double x, double y, double z, boolean doRandomSpread) { - if(stack == null || stack.stackSize <= 0) { + if (stack == null || stack.stackSize <= 0) { return; } @@ -157,7 +156,7 @@ public class Util { public static EntityItem createEntityItem(World world, ItemStack stack, double x, double y, double z, boolean doRandomSpread) { EntityItem entityitem; - if(doRandomSpread) { + if (doRandomSpread) { float f1 = 0.7F; double d = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; double d1 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; @@ -175,11 +174,11 @@ public class Util { } public static void dropItems(World world, ItemStack stack, int x, int y, int z, boolean doRandomSpread) { - if(stack == null || stack.stackSize <= 0) { + if (stack == null || stack.stackSize <= 0) { return; } - if(doRandomSpread) { + if (doRandomSpread) { float f1 = 0.7F; double d = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; double d1 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; @@ -199,11 +198,11 @@ public class Util { } public static void dropItems(World world, ItemStack[] inventory, int x, int y, int z, boolean doRandomSpread) { - if(inventory == null) { + if (inventory == null) { return; } for (ItemStack stack : inventory) { - if(stack != null && stack.stackSize > 0) { + if (stack != null && stack.stackSize > 0) { dropItems(world, stack.copy(), x, y, z, doRandomSpread); } } @@ -213,7 +212,7 @@ public class Util { for (int l = 0; l < inventory.getSizeInventory(); ++l) { ItemStack items = inventory.getStackInSlot(l); - if(items != null && items.stackSize > 0) { + if (items != null && items.stackSize > 0) { dropItems(world, inventory.getStackInSlot(l).copy(), x, y, z, doRandomSpread); } } @@ -223,13 +222,13 @@ public class Util { StringBuilder sb = new StringBuilder(); for (Object key : Block.blockRegistry.getKeys()) { - if(key != null) { + if (key != null) { sb.append(key.toString()); sb.append("\n"); } } for (Object key : Item.itemRegistry.getKeys()) { - if(key != null) { + if (key != null) { sb.append(key.toString()); sb.append("\n"); } @@ -260,15 +259,15 @@ public class Util { public static ItemStack decrStackSize(IInventory inventory, int slot, int size) { ItemStack item = inventory.getStackInSlot(slot); - if(item != null) { - if(item.stackSize <= size) { + if (item != null) { + if (item.stackSize <= size) { ItemStack result = item; inventory.setInventorySlotContents(slot, null); inventory.markDirty(); return result; } ItemStack split = item.splitStack(size); - if(item.stackSize == 0) { + if (item.stackSize == 0) { inventory.setInventorySlotContents(slot, null); } inventory.markDirty(); @@ -279,12 +278,12 @@ public class Util { public static Vec3 getEyePosition(EntityPlayer player) { Vec3 v = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); - if(player.worldObj.isRemote) { + if (player.worldObj.isRemote) { //take into account any eye changes done by mods. v.yCoord += player.getEyeHeight() - player.getDefaultEyeHeight(); } else { v.yCoord += player.getEyeHeight(); - if(player instanceof EntityPlayerMP && player.isSneaking()) { + if (player instanceof EntityPlayerMP && player.isSneaking()) { v.yCoord -= 0.08; } } @@ -293,12 +292,12 @@ public class Util { public static Vector3d getEyePositionEio(EntityPlayer player) { Vector3d res = new Vector3d(player.posX, player.posY, player.posZ); - if(player.worldObj.isRemote) { + if (player.worldObj.isRemote) { //take into account any eye changes done by mods. res.y += player.getEyeHeight() - player.getDefaultEyeHeight(); } else { res.y += player.getEyeHeight(); - if(player instanceof EntityPlayerMP && player.isSneaking()) { + if (player instanceof EntityPlayerMP && player.isSneaking()) { res.y -= 0.08; } } @@ -311,7 +310,7 @@ public class Util { } public static boolean isEquipped(EntityPlayer player, Class class1) { - if(player == null || player.inventory == null || player.inventory.getCurrentItem() == null) { + if (player == null || player.inventory == null || player.inventory.getCurrentItem() == null) { return false; } //player.inventory.getCurrentItem().getClass().getItem().isAssignableFrom(class1) @@ -319,7 +318,7 @@ public class Util { } public static boolean isType(ItemStack stack, Class class1) { - if(stack == null || class1 == null) { + if (stack == null || class1 == null) { return false; } return class1.isAssignableFrom(stack.getItem().getClass()); @@ -332,9 +331,9 @@ public class Util { boolean p_147447_4_ = false; boolean p_147447_5_ = false; - if(!Double.isNaN(startVec.xCoord) && !Double.isNaN(startVec.yCoord) && !Double.isNaN(startVec.zCoord)) { - if(!Double.isNaN(endVec.xCoord) && !Double.isNaN(endVec.yCoord) && !Double.isNaN(endVec.zCoord)) { - + if (!Double.isNaN(startVec.xCoord) && !Double.isNaN(startVec.yCoord) && !Double.isNaN(startVec.zCoord)) { + if (!Double.isNaN(endVec.xCoord) && !Double.isNaN(endVec.yCoord) && !Double.isNaN(endVec.zCoord)) { + int i = MathHelper.floor_double(endVec.xCoord); int j = MathHelper.floor_double(endVec.yCoord); int k = MathHelper.floor_double(endVec.zCoord); @@ -344,9 +343,9 @@ public class Util { Block block = world.getBlock(l, i1, j1); int k1 = world.getBlockMetadata(l, i1, j1); - if((!p_147447_4_ || block.getCollisionBoundingBoxFromPool(world, l, i1, j1) != null) && block.canCollideCheck(k1, includeLiquids)) { + if ((!p_147447_4_ || block.getCollisionBoundingBoxFromPool(world, l, i1, j1) != null) && block.canCollideCheck(k1, includeLiquids)) { MovingObjectPosition movingobjectposition = block.collisionRayTrace(world, l, i1, j1, startVec, endVec); - if(movingobjectposition != null) { + if (movingobjectposition != null) { result.add(movingobjectposition); } } @@ -355,12 +354,12 @@ public class Util { k1 = 200; while (k1-- >= 0) { - if(Double.isNaN(startVec.xCoord) || Double.isNaN(startVec.yCoord) || Double.isNaN(startVec.zCoord)) { + if (Double.isNaN(startVec.xCoord) || Double.isNaN(startVec.yCoord) || Double.isNaN(startVec.zCoord)) { return null; } - if(l == i && i1 == j && j1 == k) { - if(p_147447_5_) { + if (l == i && i1 == j && j1 == k) { + if (p_147447_5_) { result.add(movingobjectposition2); } else { return result; @@ -374,25 +373,25 @@ public class Util { double d1 = 999.0D; double d2 = 999.0D; - if(i > l) { + if (i > l) { d0 = l + 1.0D; - } else if(i < l) { + } else if (i < l) { d0 = l + 0.0D; } else { flag6 = false; } - if(j > i1) { + if (j > i1) { d1 = i1 + 1.0D; - } else if(j < i1) { + } else if (j < i1) { d1 = i1 + 0.0D; } else { flag3 = false; } - if(k > j1) { + if (k > j1) { d2 = j1 + 1.0D; - } else if(k < j1) { + } else if (k < j1) { d2 = j1 + 0.0D; } else { flag4 = false; @@ -405,21 +404,21 @@ public class Util { double d7 = endVec.yCoord - startVec.yCoord; double d8 = endVec.zCoord - startVec.zCoord; - if(flag6) { + if (flag6) { d3 = (d0 - startVec.xCoord) / d6; } - if(flag3) { + if (flag3) { d4 = (d1 - startVec.yCoord) / d7; } - if(flag4) { + if (flag4) { d5 = (d2 - startVec.zCoord) / d8; } boolean flag5 = false; byte b0; - if(d3 < d4 && d3 < d5) { - if(i > l) { + if (d3 < d4 && d3 < d5) { + if (i > l) { b0 = 4; } else { b0 = 5; @@ -428,8 +427,8 @@ public class Util { startVec.xCoord = d0; startVec.yCoord += d7 * d3; startVec.zCoord += d8 * d3; - } else if(d4 < d5) { - if(j > i1) { + } else if (d4 < d5) { + if (j > i1) { b0 = 0; } else { b0 = 1; @@ -439,7 +438,7 @@ public class Util { startVec.yCoord = d1; startVec.zCoord += d8 * d4; } else { - if(k > j1) { + if (k > j1) { b0 = 2; } else { b0 = 3; @@ -452,21 +451,21 @@ public class Util { Vec3 vec32 = Vec3.createVectorHelper(startVec.xCoord, startVec.yCoord, startVec.zCoord); l = (int) (vec32.xCoord = MathHelper.floor_double(startVec.xCoord)); - if(b0 == 5) { + if (b0 == 5) { --l; ++vec32.xCoord; } i1 = (int) (vec32.yCoord = MathHelper.floor_double(startVec.yCoord)); - if(b0 == 1) { + if (b0 == 1) { --i1; ++vec32.yCoord; } j1 = (int) (vec32.zCoord = MathHelper.floor_double(startVec.zCoord)); - if(b0 == 3) { + if (b0 == 3) { --j1; ++vec32.zCoord; } @@ -474,10 +473,10 @@ public class Util { Block block1 = world.getBlock(l, i1, j1); int l1 = world.getBlockMetadata(l, i1, j1); - if(!p_147447_4_ || block1.getCollisionBoundingBoxFromPool(world, l, i1, j1) != null) { - if(block1.canCollideCheck(l1, includeLiquids)) { + if (!p_147447_4_ || block1.getCollisionBoundingBoxFromPool(world, l, i1, j1) != null) { + if (block1.canCollideCheck(l1, includeLiquids)) { MovingObjectPosition movingobjectposition1 = block1.collisionRayTrace(world, l, i1, j1, startVec, endVec); - if(movingobjectposition1 != null) { + if (movingobjectposition1 != null) { result.add(movingobjectposition1); } } else { @@ -485,7 +484,7 @@ public class Util { } } } - if(p_147447_5_ ) { + if (p_147447_5_) { result.add(movingobjectposition2); } else { return result; @@ -500,30 +499,30 @@ public class Util { } public static ForgeDirection getDirFromOffset(int xOff, int yOff, int zOff) { - if(xOff != 0 && yOff == 0 && zOff == 0) { + if (xOff != 0 && yOff == 0 && zOff == 0) { return xOff < 0 ? ForgeDirection.WEST : ForgeDirection.EAST; } - if(zOff != 0 && yOff == 0 && xOff == 0) { + if (zOff != 0 && yOff == 0 && xOff == 0) { return zOff < 0 ? ForgeDirection.NORTH : ForgeDirection.SOUTH; } - if(yOff != 0 && xOff == 0 && zOff == 0) { + if (yOff != 0 && xOff == 0 && zOff == 0) { return yOff < 0 ? ForgeDirection.DOWN : ForgeDirection.UP; } return ForgeDirection.UNKNOWN; } - + public static int getProgressScaled(int scale, IProgressTile tile) { return (int) (tile.getProgress() * scale); } - + // copied from WAILA source to avoid API dependency - public static String WailaStyle = "\u00A4"; - public static String WailaIcon = "\u00A5"; - public static String TAB = WailaStyle + WailaStyle +"a"; - public static String ALIGNRIGHT = WailaStyle + WailaStyle +"b"; - public static String ALIGNCENTER = WailaStyle + WailaStyle +"c"; - public static String HEART = WailaStyle + WailaIcon +"a"; - public static String HHEART = WailaStyle + WailaIcon +"b"; - public static String EHEART = WailaStyle + WailaIcon +"c"; + public static String WailaStyle = "\u00A4"; + public static String WailaIcon = "\u00A5"; + public static String TAB = WailaStyle + WailaStyle + "a"; + public static String ALIGNRIGHT = WailaStyle + WailaStyle + "b"; + public static String ALIGNCENTER = WailaStyle + WailaStyle + "c"; + public static String HEART = WailaStyle + WailaIcon + "a"; + public static String HHEART = WailaStyle + WailaIcon + "b"; + public static String EHEART = WailaStyle + WailaIcon + "c"; } diff --git a/src/main/java/com/enderio/core/common/util/WorldCache.java b/src/main/java/com/enderio/core/common/util/WorldCache.java index 3351c1a..5bad3f8 100644 --- a/src/main/java/com/enderio/core/common/util/WorldCache.java +++ b/src/main/java/com/enderio/core/common/util/WorldCache.java @@ -74,7 +74,7 @@ public class WorldCache { @SneakyThrows protected void loadData(File file) { if (!file.createNewFile()) { - NBTTagCompound tag = null; + NBTTagCompound tag = null; try { tag = CompressedStreamTools.read(file); } catch (Exception e) { @@ -169,7 +169,7 @@ public class WorldCache { } return nextID; } - + protected void setID(String name) { setID(name, getNextAvailableID(name)); } diff --git a/src/main/java/com/enderio/core/common/util/blockiterators/AbstractBlockIterator.java b/src/main/java/com/enderio/core/common/util/blockiterators/AbstractBlockIterator.java index f939baa..3a67775 100644 --- a/src/main/java/com/enderio/core/common/util/blockiterators/AbstractBlockIterator.java +++ b/src/main/java/com/enderio/core/common/util/blockiterators/AbstractBlockIterator.java @@ -4,24 +4,20 @@ import java.util.Iterator; import com.enderio.core.common.util.BlockCoord; -public abstract class AbstractBlockIterator implements Iterable, Iterator -{ - protected BlockCoord base; +public abstract class AbstractBlockIterator implements Iterable, Iterator { + protected BlockCoord base; - protected AbstractBlockIterator(BlockCoord base) - { - this.base = base; - } + protected AbstractBlockIterator(BlockCoord base) { + this.base = base; + } - @Override - public void remove() - { - throw new UnsupportedOperationException("You can't remove blocks silly!"); - } + @Override + public void remove() { + throw new UnsupportedOperationException("You can't remove blocks silly!"); + } - @Override - public Iterator iterator() - { - return this; - } + @Override + public Iterator iterator() { + return this; + } } diff --git a/src/main/java/com/enderio/core/common/util/blockiterators/CubicBlockIterator.java b/src/main/java/com/enderio/core/common/util/blockiterators/CubicBlockIterator.java index 2b6c352..6c06b21 100644 --- a/src/main/java/com/enderio/core/common/util/blockiterators/CubicBlockIterator.java +++ b/src/main/java/com/enderio/core/common/util/blockiterators/CubicBlockIterator.java @@ -2,40 +2,36 @@ package com.enderio.core.common.util.blockiterators; import com.enderio.core.common.util.BlockCoord; -public class CubicBlockIterator extends AbstractBlockIterator -{ - protected int radius; - protected int minX, minY, minZ; - protected int curX, curY, curZ; - protected int maxX, maxY, maxZ; +public class CubicBlockIterator extends AbstractBlockIterator { + protected int radius; + protected int minX, minY, minZ; + protected int curX, curY, curZ; + protected int maxX, maxY, maxZ; - public CubicBlockIterator(BlockCoord base, int radius) - { - super(base); - this.radius = radius; + public CubicBlockIterator(BlockCoord base, int radius) { + super(base); + this.radius = radius; - curX = minX = base.x - radius; - curY = minY = base.y - radius; - curZ = minZ = base.z - radius; + curX = minX = base.x - radius; + curY = minY = base.y - radius; + curZ = minZ = base.z - radius; - maxX = base.x + radius; - maxY = base.y + radius; - maxZ = base.z + radius; - } + maxX = base.x + radius; + maxY = base.y + radius; + maxZ = base.z + radius; + } - @Override - public BlockCoord next() - { - BlockCoord ret = new BlockCoord(curX, curY, curZ); - curX = curX == maxX ? minX : curX + 1; - curY = curX == minX ? curY == maxY ? minY : curY + 1 : curY; - curZ = curY == minY && curX == minX ? curZ + 1 : curZ; - return ret; - } + @Override + public BlockCoord next() { + BlockCoord ret = new BlockCoord(curX, curY, curZ); + curX = curX == maxX ? minX : curX + 1; + curY = curX == minX ? curY == maxY ? minY : curY + 1 : curY; + curZ = curY == minY && curX == minX ? curZ + 1 : curZ; + return ret; + } - @Override - public boolean hasNext() - { - return curZ <= maxZ; - } + @Override + public boolean hasNext() { + return curZ <= maxZ; + } } diff --git a/src/main/java/com/enderio/core/common/util/blockiterators/PlanarBlockIterator.java b/src/main/java/com/enderio/core/common/util/blockiterators/PlanarBlockIterator.java index 6106e16..f5779b5 100644 --- a/src/main/java/com/enderio/core/common/util/blockiterators/PlanarBlockIterator.java +++ b/src/main/java/com/enderio/core/common/util/blockiterators/PlanarBlockIterator.java @@ -4,62 +4,56 @@ import com.enderio.core.common.util.BlockCoord; import net.minecraftforge.common.util.ForgeDirection; -public class PlanarBlockIterator extends CubicBlockIterator -{ - public static enum Orientation - { - EAST_WEST, NORTH_SOUTH, HORIZONTAL; +public class PlanarBlockIterator extends CubicBlockIterator { + public static enum Orientation { + EAST_WEST, + NORTH_SOUTH, + HORIZONTAL; - public static Orientation perpendicular(ForgeDirection dir) - { - switch (dir) - { - case DOWN: - case UP: - return HORIZONTAL; - case NORTH: - case SOUTH: - return EAST_WEST; - case EAST: - case WEST: - return NORTH_SOUTH; - default: - return null; - } - } + public static Orientation perpendicular(ForgeDirection dir) { + switch (dir) { + case DOWN: + case UP: + return HORIZONTAL; + case NORTH: + case SOUTH: + return EAST_WEST; + case EAST: + case WEST: + return NORTH_SOUTH; + default: + return null; + } } + } - private Orientation orientation; + private Orientation orientation; - public PlanarBlockIterator(BlockCoord base, Orientation orientation, int radius) - { - super(base, radius); + public PlanarBlockIterator(BlockCoord base, Orientation orientation, int radius) { + super(base, radius); - this.orientation = orientation; + this.orientation = orientation; + } + + @Override + public BlockCoord next() { + BlockCoord coord = new BlockCoord(curX, curY, curZ); + switch (orientation) { + case EAST_WEST: + curY = curY == maxY ? minY : curY + 1; + curX = curY == minY ? curX + 1 : curX; + case NORTH_SOUTH: + curY = curY == maxY ? minY : curY + 1; + curZ = curY == minY ? curZ + 1 : curZ; + case HORIZONTAL: + curX = curX == maxX ? minX : curX + 1; + curZ = curX == minX ? curZ + 1 : curZ; } + return coord; + } - @Override - public BlockCoord next() - { - BlockCoord coord = new BlockCoord(curX, curY, curZ); - switch (orientation) - { - case EAST_WEST: - curY = curY == maxY ? minY : curY + 1; - curX = curY == minY ? curX + 1 : curX; - case NORTH_SOUTH: - curY = curY == maxY ? minY : curY + 1; - curZ = curY == minY ? curZ + 1 : curZ; - case HORIZONTAL: - curX = curX == maxX ? minX : curX + 1; - curZ = curX == minX ? curZ + 1 : curZ; - } - return coord; - } - - @Override - public boolean hasNext() - { - return curX <= maxX && curY <= maxY && curZ <= maxZ; - } + @Override + public boolean hasNext() { + return curX <= maxX && curY <= maxY && curZ <= maxZ; + } } diff --git a/src/main/java/com/enderio/core/common/vecmath/Camera.java b/src/main/java/com/enderio/core/common/vecmath/Camera.java index 405aadc..96f3084 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Camera.java +++ b/src/main/java/com/enderio/core/common/vecmath/Camera.java @@ -29,11 +29,11 @@ public class Camera { public Vector3d getEyePoint() { Matrix4d vpm = new Matrix4d(); Matrix4d ivm = getInverseViewMatrix(); - if(ivm == null) { + if (ivm == null) { return null; } Matrix4d ipm = getInverseProjectionMatrix(); - if(ipm == null) { + if (ipm == null) { return null; } vpm.mul(ivm, ipm); @@ -44,7 +44,7 @@ public class Camera { } public boolean getRayForPixel(int x, int y, Vector3d eyeOut, Vector3d normalOut) { - if(isValid()) { + if (isValid()) { VecmathUtil.computeRayForPixel(viewport, getInverseProjectionMatrix(), getInverseViewMatrix(), x, y, eyeOut, normalOut); return true; } @@ -68,7 +68,7 @@ public class Camera { } public void setViewport(Rectangle viewport) { - if(viewport != null) { + if (viewport != null) { setViewport(viewport.x, viewport.y, viewport.width, viewport.height); } } @@ -90,8 +90,8 @@ public class Camera { } public Matrix4d getInverseProjectionMatrix() { - if(projectionMatrix != null) { - if(projectionInverse == null) { + if (projectionMatrix != null) { + if (projectionInverse == null) { projectionInverse = new Matrix4d(projectionMatrix); projectionInverse.invert(); } @@ -102,7 +102,7 @@ public class Camera { } public void setProjectionMatrix(Matrix4d matrix) { - if(projectionMatrix == null) { + if (projectionMatrix == null) { projectionMatrix = new Matrix4d(); projectionTranspose = new Matrix4d(); } @@ -121,8 +121,8 @@ public class Camera { } public Matrix4d getInverseViewMatrix() { - if(viewMatrix != null) { - if(viewInverse == null) { + if (viewMatrix != null) { + if (viewInverse == null) { viewInverse = new Matrix4d(viewMatrix); viewInverse.invert(); } @@ -133,7 +133,7 @@ public class Camera { } public void setViewMatrix(Matrix4d matrix) { - if(viewMatrix == null) { + if (viewMatrix == null) { viewMatrix = new Matrix4d(); viewTranspose = new Matrix4d(); } diff --git a/src/main/java/com/enderio/core/common/vecmath/Matrix4d.java b/src/main/java/com/enderio/core/common/vecmath/Matrix4d.java index 95c2a2a..52166bb 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Matrix4d.java +++ b/src/main/java/com/enderio/core/common/vecmath/Matrix4d.java @@ -90,10 +90,8 @@ public class Matrix4d { m33 = other.m33; } - public Matrix4d(double m00, double m01, double m02, double m03, - double m10, double m11, double m12, double m13, - double m20, double m21, double m22, double m23, - double m30, double m31, double m32, double m33) { + public Matrix4d(double m00, double m01, double m02, double m03, double m10, double m11, double m12, double m13, double m20, double m21, double m22, + double m23, double m30, double m31, double m32, double m33) { this.m00 = m00; this.m01 = m01; @@ -505,7 +503,7 @@ public class Matrix4d { public void invert() { double det = determinant(); - if(det == 0) { + if (det == 0) { throw new RuntimeException("Cannot invert matrix with a determinat of 0."); } double detInv = 1f / det; @@ -551,27 +549,10 @@ public class Matrix4d { } public double determinant() { - double result = - m00 - * ((m11 * m22 * m33 + m21 * m32 * m13 + m31 * m12 * m23) - - m31 * m22 * m13 - - m11 * m32 * m23 - - m21 * m12 * m33); - result -= m10 - * ((m01 * m22 * m33 + m21 * m32 * m03 + m31 * m02 * m23) - - m31 * m22 * m03 - - m01 * m32 * m23 - - m21 * m02 * m33); - result += m20 - * ((m01 * m12 * m33 + m11 * m32 * m03 + m31 * m02 * m13) - - m31 * m12 * m03 - - m01 * m32 * m13 - - m11 * m02 * m33); - result -= m30 - * ((m01 * m12 * m23 + m11 * m22 * m03 + m21 * m02 * m13) - - m21 * m12 * m03 - - m01 * m22 * m13 - - m11 * m02 * m23); + double result = m00 * ((m11 * m22 * m33 + m21 * m32 * m13 + m31 * m12 * m23) - m31 * m22 * m13 - m11 * m32 * m23 - m21 * m12 * m33); + result -= m10 * ((m01 * m22 * m33 + m21 * m32 * m03 + m31 * m02 * m23) - m31 * m22 * m03 - m01 * m32 * m23 - m21 * m02 * m33); + result += m20 * ((m01 * m12 * m33 + m11 * m32 * m03 + m31 * m02 * m13) - m31 * m12 * m03 - m01 * m32 * m13 - m11 * m02 * m33); + result -= m30 * ((m01 * m12 * m23 + m11 * m22 * m03 + m21 * m02 * m13) - m21 * m12 * m03 - m01 * m22 * m13 - m11 * m02 * m23); return result; } @@ -581,11 +562,7 @@ public class Matrix4d { @Override public String toString() { - return "Matrix4d(\n" + - " " + m00 + ", " + m01 + ", " + m02 + ", " + m03 + "\n" + - " " + m10 + ", " + m11 + ", " + m12 + ", " + m13 + "\n" + - " " + m20 + ", " + m21 + ", " + m22 + ", " + m23 + "\n" + - " " + m30 + ", " + m31 + ", " + m32 + ", " + m33 + "\n" + - ")\n"; + return "Matrix4d(\n" + " " + m00 + ", " + m01 + ", " + m02 + ", " + m03 + "\n" + " " + m10 + ", " + m11 + ", " + m12 + ", " + m13 + "\n" + " " + m20 + + ", " + m21 + ", " + m22 + ", " + m23 + "\n" + " " + m30 + ", " + m31 + ", " + m32 + ", " + m33 + "\n" + ")\n"; } } diff --git a/src/main/java/com/enderio/core/common/vecmath/Quat4d.java b/src/main/java/com/enderio/core/common/vecmath/Quat4d.java index 8fc5b5b..ea6866e 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Quat4d.java +++ b/src/main/java/com/enderio/core/common/vecmath/Quat4d.java @@ -9,7 +9,7 @@ public class Quat4d { double y = axis.y; double z = axis.z; double length = Math.sqrt(x * x + y * y + z * z); - if(length < epsilon) { + if (length < epsilon) { // ~zero length axis, so reset rotation to zero. return new Quat4d(); } diff --git a/src/main/java/com/enderio/core/common/vecmath/VecmathUtil.java b/src/main/java/com/enderio/core/common/vecmath/VecmathUtil.java index 860c7de..093893f 100644 --- a/src/main/java/com/enderio/core/common/vecmath/VecmathUtil.java +++ b/src/main/java/com/enderio/core/common/vecmath/VecmathUtil.java @@ -53,8 +53,7 @@ public class VecmathUtil { * @param result * the result (A,B,C,D) of plane equation. */ - public static void computePlaneEquation(Vector3d a, Vector3d b, - Vector3d c, Vector4d result) { + public static void computePlaneEquation(Vector3d a, Vector3d b, Vector3d c, Vector4d result) { Vector3d i = new Vector3d(); Vector3d j = new Vector3d(); Vector3d k = new Vector3d(); @@ -108,16 +107,15 @@ public class VecmathUtil { * @return the intersection or null if there is no intersection or the line is * on the plane. */ - public static Vector3d computeIntersectionBetweenPlaneAndLine(Vector4d plane, - Vector3d pointInLine, Vector3d lineDirection) { + public static Vector3d computeIntersectionBetweenPlaneAndLine(Vector4d plane, Vector3d pointInLine, Vector3d lineDirection) { // check for no intersection Vector3d planeNormal = new Vector3d(plane.x, plane.y, plane.z); - if(planeNormal.dot(lineDirection) == 0) { + if (planeNormal.dot(lineDirection) == 0) { // line and plane are perpendicular return null; } // check if line is on the plane - if(planeNormal.dot(pointInLine) + plane.w == 0) { + if (planeNormal.dot(pointInLine) + plane.w == 0) { return null; } @@ -145,8 +143,7 @@ public class VecmathUtil { * @param normalOut * the normal description the directional component of the ray. */ - public static void computeRayForPixel(Rectangle vp, Matrix4d ipm, Matrix4d ivm, int x, int y, - Vector3d eyeOut, Vector3d normalOut) { + public static void computeRayForPixel(Rectangle vp, Matrix4d ipm, Matrix4d ivm, int x, int y, Vector3d eyeOut, Vector3d normalOut) { // grab the eye's position ivm.getTranslation(eyeOut); @@ -333,8 +330,7 @@ public class VecmathUtil { * @return the matrix. */ - public static Matrix4d createProjectionMatrixAsPerspective(double fovDegrees, double near, - double far, int viewportWidth, int viewportHeight) { + public static Matrix4d createProjectionMatrixAsPerspective(double fovDegrees, double near, double far, int viewportWidth, int viewportHeight) { Matrix4d matrix = new Matrix4d(); // for impl details see gluPerspective doco in OpenGL reference manual @@ -369,18 +365,15 @@ public class VecmathUtil { * @return the matrix. */ - public static Matrix4d createProjectionMatrixAsPerspective(double left, double right, - double bottom, double top, double zNear, double zFar) { + public static Matrix4d createProjectionMatrixAsPerspective(double left, double right, double bottom, double top, double zNear, double zFar) { double A = (right + left) / (right - left); double B = (top + bottom) / (top - bottom); double C = (Math.abs(zFar) > Double.MAX_VALUE) ? -1. : -(zFar + zNear) / (zFar - zNear); - double D = (Math.abs(zFar) > Double.MAX_VALUE) ? -2. * zNear : -2.0 * zFar * zNear - / (zFar - zNear); + double D = (Math.abs(zFar) > Double.MAX_VALUE) ? -2. * zNear : -2.0 * zFar * zNear / (zFar - zNear); Matrix4d matrix = new Matrix4d(); - matrix.set(new double[] { 2.0 * zNear / (right - left), 0.0, 0.0, 0.0, 0.0, - 2.0 * zNear / (top - bottom), 0.0, 0.0, A, B, C, -1.0, 0.0, 0.0, D, 0.0 + matrix.set(new double[] { 2.0 * zNear / (right - left), 0.0, 0.0, 0.0, 0.0, 2.0 * zNear / (top - bottom), 0.0, 0.0, A, B, C, -1.0, 0.0, 0.0, D, 0.0 }); @@ -406,8 +399,7 @@ public class VecmathUtil { * @return the ortho matrix. */ - public static Matrix4d createProjectionMatrixAsOrtho(double left, double right, double bottom, - double top, double near, double far) { + public static Matrix4d createProjectionMatrixAsOrtho(double left, double right, double bottom, double top, double near, double far) { Matrix4d matrix = new Matrix4d(); // for impl details see glOrtho doco in OpenGL reference manual @@ -415,8 +407,7 @@ public class VecmathUtil { double ty = -((top + bottom) / (top - bottom)); double tz = -((far + near) / (far - near)); - matrix.set(new double[] { 2d / (right - left), 0, 0, tx, 0, 2d / (top - bottom), 0, ty, 0, 0, - -2d / (far - near), tz, 0, 0, 0, 1 }); + matrix.set(new double[] { 2d / (right - left), 0, 0, tx, 0, 2d / (top - bottom), 0, ty, 0, 0, -2d / (far - near), tz, 0, 0, 0, 1 }); return matrix; } @@ -431,15 +422,12 @@ public class VecmathUtil { * @param far * the new far value. */ - public static void setNearFarOnPerspectiveProjectionMatrix(Matrix4d projMat, - double near, double far) { + public static void setNearFarOnPerspectiveProjectionMatrix(Matrix4d projMat, double near, double far) { projMat.transpose(); - double transNearPlane = (-near * projMat.getElement(2, 2) + projMat.getElement(3, 2)) - / (-near * projMat.getElement(2, 3) + projMat.getElement(3, 3)); - double transFarPlane = (-far * projMat.getElement(2, 2) + projMat.getElement(3, 2)) - / (-far * projMat.getElement(2, 3) + projMat.getElement(3, 3)); + double transNearPlane = (-near * projMat.getElement(2, 2) + projMat.getElement(3, 2)) / (-near * projMat.getElement(2, 3) + projMat.getElement(3, 3)); + double transFarPlane = (-far * projMat.getElement(2, 2) + projMat.getElement(3, 2)) / (-far * projMat.getElement(2, 3) + projMat.getElement(3, 3)); double ratio = Math.abs(2.0 / (transNearPlane - transFarPlane)); double center = -(transNearPlane + transFarPlane) / 2.0; @@ -466,8 +454,7 @@ public class VecmathUtil { * @return the look at matrix. */ - public static Matrix4d createMatrixAsLookAt(Vector3d eyePos, - Vector3d lookAtPos, Vector3d upVec) { + public static Matrix4d createMatrixAsLookAt(Vector3d eyePos, Vector3d lookAtPos, Vector3d upVec) { Vector3d eye = new Vector3d(eyePos); Vector3d lookAt = new Vector3d(lookAtPos); @@ -485,8 +472,7 @@ public class VecmathUtil { upVed.cross(sideVec, forwardVec); upVed.normalize(); - Matrix4d mat = new Matrix4d(sideVec.x, sideVec.y, sideVec.z, 0, upVed.x, upVed.y, upVed.z, 0, - -forwardVec.x, -forwardVec.y, -forwardVec.z, 0, 0, 0, 0, 1); + Matrix4d mat = new Matrix4d(sideVec.x, sideVec.y, sideVec.z, 0, upVed.x, upVed.y, upVed.z, 0, -forwardVec.x, -forwardVec.y, -forwardVec.z, 0, 0, 0, 0, 1); eye.negate(); // mat.transform(eye); @@ -509,14 +495,10 @@ public class VecmathUtil { public static Vector3d preMultiply(Vector3d v, Matrix4d mat) { Matrix4d m = new Matrix4d(mat); m.transpose(); - double d = 1.0f / (m.getElement(0, 3) * v.x + m.getElement(1, 3) * v.y + m.getElement(2, 3) - * v.z + m.getElement(3, 3)); - double x = (m.getElement(0, 0) * v.x + m.getElement(1, 0) * v.y + m.getElement(2, 0) * v.z + m - .getElement(3, 0)) * d; - double y = (m.getElement(0, 1) * v.x + m.getElement(1, 1) * v.y + m.getElement(2, 1) * v.z + m - .getElement(3, 1)) * d; - double z = (m.getElement(0, 2) * v.x + m.getElement(1, 2) * v.y + m.getElement(2, 2) * v.z + m - .getElement(3, 2) * d); + double d = 1.0f / (m.getElement(0, 3) * v.x + m.getElement(1, 3) * v.y + m.getElement(2, 3) * v.z + m.getElement(3, 3)); + double x = (m.getElement(0, 0) * v.x + m.getElement(1, 0) * v.y + m.getElement(2, 0) * v.z + m.getElement(3, 0)) * d; + double y = (m.getElement(0, 1) * v.x + m.getElement(1, 1) * v.y + m.getElement(2, 1) * v.z + m.getElement(3, 1)) * d; + double z = (m.getElement(0, 2) * v.x + m.getElement(1, 2) * v.y + m.getElement(2, 2) * v.z + m.getElement(3, 2) * d); return new Vector3d(x, y, z); } @@ -535,17 +517,13 @@ public class VecmathUtil { Vector4d[] res = new Vector4d[4]; // s plane - res[0] = new Vector4d(copy.getElement(0, 0), copy.getElement(1, 0), copy.getElement(2, 0), - copy.getElement(3, 0)); + res[0] = new Vector4d(copy.getElement(0, 0), copy.getElement(1, 0), copy.getElement(2, 0), copy.getElement(3, 0)); // t plane - res[1] = new Vector4d(copy.getElement(0, 1), copy.getElement(1, 1), copy.getElement(2, 1), - copy.getElement(3, 1)); + res[1] = new Vector4d(copy.getElement(0, 1), copy.getElement(1, 1), copy.getElement(2, 1), copy.getElement(3, 1)); // r plane - res[2] = new Vector4d(copy.getElement(0, 2), copy.getElement(1, 2), copy.getElement(2, 2), - copy.getElement(3, 2)); + res[2] = new Vector4d(copy.getElement(0, 2), copy.getElement(1, 2), copy.getElement(2, 2), copy.getElement(3, 2)); // q plane - res[3] = new Vector4d(copy.getElement(0, 3), copy.getElement(1, 3), copy.getElement(2, 3), - copy.getElement(3, 3)); + res[3] = new Vector4d(copy.getElement(0, 3), copy.getElement(1, 3), copy.getElement(2, 3), copy.getElement(3, 3)); return res; } @@ -604,8 +582,7 @@ public class VecmathUtil { * @param lookVecOut * the look vector. */ - public static void getVectorsForMatrix(Matrix4d matrix, Vector3d upVecOut, - Vector3d sideVecOut, Vector3d lookVecOut) { + public static void getVectorsForMatrix(Matrix4d matrix, Vector3d upVecOut, Vector3d sideVecOut, Vector3d lookVecOut) { sideVecOut.set(matrix.getElement(0, 0), matrix.getElement(0, 1), matrix.getElement(0, 2)); sideVecOut.normalize(); @@ -628,8 +605,7 @@ public class VecmathUtil { */ public static Vector3d getUpFromMatrix(Matrix4d matrix) { - Vector3d res = new Vector3d(matrix.getElement(1, 0), matrix.getElement(1, 1), - matrix.getElement(1, 2)); + Vector3d res = new Vector3d(matrix.getElement(1, 0), matrix.getElement(1, 1), matrix.getElement(1, 2)); res.normalize(); return res; } diff --git a/src/main/java/com/enderio/core/common/vecmath/Vector3f.java b/src/main/java/com/enderio/core/common/vecmath/Vector3f.java index fca964f..f8ea4c2 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Vector3f.java +++ b/src/main/java/com/enderio/core/common/vecmath/Vector3f.java @@ -55,11 +55,11 @@ public class Vector3f { y += vec.y; z += vec.z; } - + public void add(int x2, int y2, int z2) { x += x2; y += y2; - z += z2; + z += z2; } public void sub(Vector3f vec) { @@ -114,6 +114,4 @@ public class Vector3f { return new Vector3d(x, y, z); } - - } diff --git a/src/main/java/com/enderio/core/common/vecmath/Vertex.java b/src/main/java/com/enderio/core/common/vecmath/Vertex.java index 5cd88af..1d8a9ff 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Vertex.java +++ b/src/main/java/com/enderio/core/common/vecmath/Vertex.java @@ -14,13 +14,13 @@ public class Vertex { public Vertex(Vertex other) { xyz.set(other.xyz); - if(other.uv != null) { + if (other.uv != null) { uv = new Vector2f(other.uv); } - if(other.normal != null) { + if (other.normal != null) { normal = new Vector3f(other.normal); } - if(other.color != null) { + if (other.color != null) { color = new Vector4f(other.color); } brightness = other.brightness; @@ -49,7 +49,7 @@ public class Vertex { } public void setUV(double u, double v) { - if(uv == null) { + if (uv == null) { uv = new Vector2f(u, v); } else { uv.set(u, v); @@ -57,7 +57,7 @@ public class Vertex { } public void setNormal(double x, double y, double z) { - if(normal == null) { + if (normal == null) { normal = new Vector3f(); } normal.set((float) x, (float) y, (float) z); @@ -65,7 +65,7 @@ public class Vertex { } public void setNormal(Vector3f normal2) { - if(normal2 == null) { + if (normal2 == null) { normal = null; return; } diff --git a/src/main/java/com/enderio/core/common/vecmath/ViewFrustum.java b/src/main/java/com/enderio/core/common/vecmath/ViewFrustum.java index 7640eea..505c18c 100644 --- a/src/main/java/com/enderio/core/common/vecmath/ViewFrustum.java +++ b/src/main/java/com/enderio/core/common/vecmath/ViewFrustum.java @@ -56,7 +56,7 @@ public class ViewFrustum { public boolean containsPoint(Vector3d point) { for (Vector4d plane : planes) { - if(distanceFromPointToPlane(plane, point) < 0) { + if (distanceFromPointToPlane(plane, point) < 0) { return false; } }