From 3852dd21acb3823bf6b293ebfc11e25b5bfcf237 Mon Sep 17 00:00:00 2001 From: Raven Szewczyk Date: Sun, 29 Jan 2023 10:58:53 +0000 Subject: [PATCH] [ci skip] spotlessApply with the new settings --- dependencies.gradle | 2 +- src/main/java/com/enderio/core/EnderCore.java | 178 +- src/main/java/com/enderio/core/IEnderMod.java | 11 +- .../client/gui/IAdvancedTooltipProvider.java | 17 +- .../core/api/client/gui/IGuiOverlay.java | 22 +- .../core/api/client/gui/IGuiScreen.java | 26 +- .../client/gui/IResourceTooltipProvider.java | 2 +- .../core/api/client/gui/ITabPanel.java | 30 +- .../api/client/gui/ListSelectionListener.java | 2 +- .../core/api/client/model/IEnderModel.java | 33 +- .../render/IConnectedTextureRenderer.java | 2 +- .../core/api/client/render/IRenderFace.java | 10 +- .../core/api/client/render/IWidgetIcon.java | 14 +- .../core/api/client/render/IWidgetMap.java | 181 +- .../api/client/render/VertexTransform.java | 6 +- .../api/common/config/IConfigHandler.java | 28 +- .../api/common/enchant/IAdvancedEnchant.java | 15 +- .../com/enderio/core/api/common/imc/IMC.java | 23 +- .../core/api/common/util/IFluidReceptor.java | 2 +- .../core/api/common/util/IItemReceptor.java | 4 +- .../core/api/common/util/IProgressTile.java | 21 +- .../core/api/common/util/ITankAccess.java | 41 +- .../com/enderio/core/client/ClientProxy.java | 28 +- .../client/EnderCoreModConflictException.java | 39 +- .../core/client/config/BaseConfigGui.java | 219 +-- .../core/client/gui/GhostSlotHandler.java | 368 ++-- .../core/client/gui/GuiContainerBase.java | 1266 +++++++------- .../core/client/gui/GuiIconRenderer.java | 130 +- .../core/client/gui/GuiScreenBase.java | 368 ++-- .../core/client/gui/ToolTipManager.java | 105 +- .../gui/bettermodlist/EventHandlerGui.java | 56 +- .../gui/bettermodlist/GuiEnhancedModList.java | 698 ++++---- .../core/client/gui/button/CheckBox.java | 6 +- .../core/client/gui/button/ColorButton.java | 156 +- .../core/client/gui/button/CycleButton.java | 120 +- .../client/gui/button/GuiButtonHideable.java | 4 +- .../core/client/gui/button/IIconButton.java | 164 +- .../core/client/gui/button/IconButton.java | 187 +- .../client/gui/button/IconToggleButton.java | 44 +- .../client/gui/button/InvisibleButton.java | 4 +- .../core/client/gui/button/ItemButton.java | 132 +- .../client/gui/button/MultiIconButton.java | 91 +- .../core/client/gui/button/ToggleButton.java | 118 +- .../core/client/gui/button/TooltipButton.java | 7 +- .../gui/widget/GhostBackgroundItemSlot.java | 91 +- .../core/client/gui/widget/GhostSlot.java | 98 +- .../client/gui/widget/GuiScrollableList.java | 665 ++++---- .../core/client/gui/widget/GuiToolTip.java | 161 +- .../client/gui/widget/TextFieldEnder.java | 184 +- .../core/client/gui/widget/VScrollbar.java | 321 ++-- .../core/client/handlers/ClientHandler.java | 20 +- .../handlers/EnchantTooltipHandler.java | 40 +- .../handlers/OreDictTooltipHandler.java | 44 +- .../handlers/SpecialTooltipHandler.java | 289 ++-- .../core/client/render/BoundingBox.java | 739 ++++---- .../enderio/core/client/render/ColorUtil.java | 125 +- .../render/ConnectedTextureRenderer.java | 593 +++---- .../core/client/render/CubeRenderer.java | 622 +++---- .../client/render/CustomCubeRenderer.java | 85 +- .../client/render/CustomRenderBlocks.java | 1501 ++++++++++------- .../core/client/render/CustomWidgetIcon.java | 76 +- .../render/DirectionalModelRenderer.java | 222 +-- .../core/client/render/EnderWidget.java | 184 +- .../enderio/core/client/render/IconUtil.java | 97 +- .../core/client/render/RenderUtil.java | 1302 +++++++------- .../client/render/SimpleModelRenderer.java | 71 +- .../client/render/TechneModelRenderer.java | 109 +- .../core/client/render/TechneUtil.java | 678 ++++---- .../core/client/render/VertexRotation.java | 76 +- .../client/render/VertexRotationFacing.java | 64 +- .../render/VertexTransformComposite.java | 54 +- .../core/client/render/VertexTranslation.java | 80 +- .../enderio/core/client/sound/BlockSound.java | 66 +- .../com/enderio/core/common/BlockEnder.java | 336 ++-- .../com/enderio/core/common/CommonProxy.java | 50 +- .../enderio/core/common/ContainerEnder.java | 341 ++-- .../com/enderio/core/common/Handlers.java | 593 ++++--- .../java/com/enderio/core/common/Lang.java | 313 ++-- .../java/com/enderio/core/common/OreDict.java | 116 +- .../enderio/core/common/TileEntityEnder.java | 258 ++- .../common/command/CommandReloadConfigs.java | 150 +- .../common/command/CommandScoreboardInfo.java | 120 +- .../core/common/compat/CompatRegistry.java | 205 +-- .../enderio/core/common/compat/ICompat.java | 7 +- .../common/config/AbstractConfigHandler.java | 1080 ++++++------ .../core/common/config/BaseConfigFactory.java | 37 +- .../core/common/config/ConfigHandler.java | 254 +-- .../core/common/config/ConfigProcessor.java | 643 ++++--- .../common/config/ITweakConfigHandler.java | 3 +- .../core/common/config/JsonConfigReader.java | 396 ++--- .../core/common/config/PacketConfigSync.java | 132 +- .../core/common/config/TypeAdapterBase.java | 76 +- .../core/common/config/annot/Comment.java | 13 +- .../core/common/config/annot/Config.java | 25 +- .../core/common/config/annot/NoSync.java | 8 +- .../core/common/config/annot/Range.java | 41 +- .../core/common/config/annot/RestartReq.java | 22 +- .../core/common/enchant/EnchantAutoSmelt.java | 113 +- .../core/common/enchant/EnchantXPBoost.java | 103 +- .../core/common/event/ArrowUpdateEvent.java | 8 +- .../common/event/ConfigFileChangedEvent.java | 40 +- .../core/common/event/ItemStackEvent.java | 83 +- .../common/handlers/AutoSmeltHandler.java | 113 +- .../core/common/handlers/FireworkHandler.java | 98 +- .../handlers/RightClickCropHandler.java | 134 +- .../core/common/handlers/XPBoostHandler.java | 193 ++- .../enderio/core/common/imc/IMCRegistry.java | 70 +- .../imc/handlers/IMCRightClickCrop.java | 32 +- .../common/interfaces/IComparatorOutput.java | 2 +- .../common/network/CompressedDataInput.java | 32 +- .../common/network/CompressedDataOutput.java | 40 +- .../common/network/EnderPacketHandler.java | 40 +- .../common/network/MessageTileEntity.java | 88 +- .../core/common/network/MessageTileNBT.java | 106 +- .../core/common/network/NetworkUtil.java | 76 +- .../core/common/network/PacketGhostSlot.java | 79 +- .../core/common/network/PacketProgress.java | 61 +- .../common/transform/EnderCoreMethods.java | 296 ++-- .../common/transform/EnderCorePlugin.java | 44 +- .../transform/EnderCoreTransformer.java | 462 ++--- .../transform/EnderCoreTransformerClient.java | 157 +- .../enderio/core/common/tweaks/InfiniBow.java | 39 +- .../core/common/tweaks/SlabRecipes.java | 51 +- .../com/enderio/core/common/tweaks/Tweak.java | 29 +- .../enderio/core/common/tweaks/Tweaks.java | 12 +- .../core/common/util/ArrayInventory.java | 114 +- .../enderio/core/common/util/BlockCoord.java | 265 +-- .../com/enderio/core/common/util/Bound.java | 123 +- .../enderio/core/common/util/ChatUtil.java | 377 ++--- .../core/common/util/CreativeTabsCustom.java | 69 +- .../enderio/core/common/util/DyeColor.java | 134 +- .../core/common/util/EnderFileUtils.java | 511 +++--- .../core/common/util/EnderRegistryUtils.java | 179 +- .../core/common/util/EnderStringUtils.java | 229 +-- .../enderio/core/common/util/EntityUtil.java | 228 +-- .../enderio/core/common/util/FluidUtil.java | 805 ++++----- .../common/util/ForgeDirectionOffsets.java | 85 +- .../core/common/util/IBlockAccessWrapper.java | 111 +- .../core/common/util/InventoryWrapper.java | 196 +-- .../enderio/core/common/util/ItemUtil.java | 1004 +++++------ .../com/enderio/core/common/util/Log.java | 29 +- .../core/common/util/MetadataUtil.java | 62 +- .../core/common/util/OreDictionaryHelper.java | 87 +- .../core/common/util/PermanentCache.java | 77 +- .../enderio/core/common/util/PlayerUtil.java | 33 +- .../core/common/util/RegisterTime.java | 29 +- .../common/util/ResourcePackAssembler.java | 382 +++-- .../core/common/util/RoundRobinIterator.java | 63 +- .../enderio/core/common/util/Scheduler.java | 280 ++- .../enderio/core/common/util/SoundUtil.java | 19 +- .../core/common/util/TextureErrorRemover.java | 76 +- .../com/enderio/core/common/util/Util.java | 970 +++++------ .../enderio/core/common/util/WorldCache.java | 326 ++-- .../blockiterators/AbstractBlockIterator.java | 25 +- .../blockiterators/CubicBlockIterator.java | 53 +- .../blockiterators/PlanarBlockIterator.java | 94 +- .../enderio/core/common/vecmath/Camera.java | 249 +-- .../enderio/core/common/vecmath/Matrix4d.java | 1131 +++++++------ .../enderio/core/common/vecmath/Quat4d.java | 89 +- .../core/common/vecmath/VecmathUtil.java | 1075 ++++++------ .../enderio/core/common/vecmath/Vector2d.java | 144 +- .../enderio/core/common/vecmath/Vector2f.java | 142 +- .../enderio/core/common/vecmath/Vector3d.java | 238 +-- .../enderio/core/common/vecmath/Vector3f.java | 182 +- .../enderio/core/common/vecmath/Vector4d.java | 144 +- .../enderio/core/common/vecmath/Vector4f.java | 175 +- .../enderio/core/common/vecmath/Vertex.java | 235 +-- .../core/common/vecmath/ViewFrustum.java | 308 ++-- 168 files changed, 16571 insertions(+), 16033 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index 316837f..ced3e07 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -2,6 +2,6 @@ dependencies { compile("com.github.GTNewHorizons:NotEnoughItems:2.2.15-GTNH:dev") - runtime("com.github.GTNewHorizons:CodeChickenLib:1.1.5.4:dev") + runtimeOnly("com.github.GTNewHorizons:CodeChickenLib:1.1.5.4:dev") compileOnly("curse.maven:cofh-core-69162:2388751") } diff --git a/src/main/java/com/enderio/core/EnderCore.java b/src/main/java/com/enderio/core/EnderCore.java index 2e95dfb..fdae707 100644 --- a/src/main/java/com/enderio/core/EnderCore.java +++ b/src/main/java/com/enderio/core/EnderCore.java @@ -42,109 +42,119 @@ import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; -@Mod(modid = EnderCore.MODID, name = EnderCore.NAME, version = EnderCore.VERSION, dependencies = "after:ttCore", guiFactory = "com.enderio.core.common.config.BaseConfigFactory") +@Mod( + modid = EnderCore.MODID, + name = EnderCore.NAME, + version = EnderCore.VERSION, + dependencies = "after:ttCore", + guiFactory = "com.enderio.core.common.config.BaseConfigFactory") public class EnderCore implements IEnderMod { - public static final String MODID = "endercore"; - public static final String NAME = "EnderCore"; - public static final String BASE_PACKAGE = "com.enderio"; - public static final String VERSION = "GRADLETOKEN_VERSION"; + public static final String MODID = "endercore"; + public static final String NAME = "EnderCore"; + public static final String BASE_PACKAGE = "com.enderio"; + public static final String VERSION = "GRADLETOKEN_VERSION"; - public static final Logger logger = LogManager.getLogger(NAME); - public static final Lang lang = new Lang(MODID); + public static final Logger logger = LogManager.getLogger(NAME); + public static final Lang lang = new Lang(MODID); - @Instance(MODID) - public static EnderCore instance; + @Instance(MODID) + public static EnderCore instance; - @SidedProxy(serverSide = "com.enderio.core.common.CommonProxy", clientSide = "com.enderio.core.client.ClientProxy") - public static CommonProxy proxy; + @SidedProxy(serverSide = "com.enderio.core.common.CommonProxy", clientSide = "com.enderio.core.client.ClientProxy") + public static CommonProxy proxy; - public List configs = Lists.newArrayList(); + public List configs = Lists.newArrayList(); - @EventHandler - public void preInit(FMLPreInitializationEvent event) { - if (Loader.isModLoaded("ttCore")) { - proxy.throwModCompatibilityError(lang.localize("error.ttcore.1"), lang.localize("error.ttcore.2"), lang.localize("error.ttcore.3")); + @EventHandler + public void preInit(FMLPreInitializationEvent event) { + if (Loader.isModLoaded("ttCore")) { + proxy.throwModCompatibilityError( + lang.localize("error.ttcore.1"), + lang.localize("error.ttcore.2"), + lang.localize("error.ttcore.3")); + } + + if (event.getSide().isClient()) { + TextureErrorRemover.beginIntercepting(); + } + + ConfigHandler.configFolder = event.getModConfigurationDirectory(); + ConfigHandler.enderConfigFolder = new File(ConfigHandler.configFolder.getPath() + "/" + MODID); + ConfigHandler.configFile = new File( + ConfigHandler.enderConfigFolder.getPath() + "/" + event.getSuggestedConfigurationFile().getName()); + + if (!ConfigHandler.configFile.exists() && event.getSuggestedConfigurationFile().exists()) { + try { + FileUtils.copyFile(event.getSuggestedConfigurationFile(), ConfigHandler.configFile); + } catch (IOException e) { + Throwables.propagate(e); + } + EnderFileUtils.safeDelete(event.getSuggestedConfigurationFile()); + } + + ConfigHandler.instance().initialize(ConfigHandler.configFile); + Handlers.preInit(event); + + CompatRegistry.INSTANCE.handle(event); + OreDict.registerVanilla(); + + EnchantXPBoost.INSTANCE.register(); + EnchantAutoSmelt.INSTANCE.register(); } - if (event.getSide().isClient()) { - TextureErrorRemover.beginIntercepting(); + @EventHandler + public void init(FMLInitializationEvent event) { + EnderPacketHandler.init(); + + for (IConfigHandler c : configs) { + c.initHook(); + } + + Handlers.register(event); + CompatRegistry.INSTANCE.handle(event); + ClientCommandHandler.instance.registerCommand(CommandReloadConfigs.CLIENT); + if (event.getSide().isServer()) { + ((CommandHandler) MinecraftServer.getServer().getCommandManager()) + .registerCommand(CommandReloadConfigs.SERVER); + } + + IMCRegistry.INSTANCE.init(); } - ConfigHandler.configFolder = event.getModConfigurationDirectory(); - ConfigHandler.enderConfigFolder = new File(ConfigHandler.configFolder.getPath() + "/" + MODID); - ConfigHandler.configFile = new File(ConfigHandler.enderConfigFolder.getPath() + "/" + event.getSuggestedConfigurationFile().getName()); + @EventHandler + public void postInit(FMLPostInitializationEvent event) { + for (IConfigHandler c : configs) { + c.postInitHook(); + } - if (!ConfigHandler.configFile.exists() && event.getSuggestedConfigurationFile().exists()) { - try { - FileUtils.copyFile(event.getSuggestedConfigurationFile(), ConfigHandler.configFile); - } catch (IOException e) { - Throwables.propagate(e); - } - EnderFileUtils.safeDelete(event.getSuggestedConfigurationFile()); + CompatRegistry.INSTANCE.handle(event); + ConfigHandler.instance().loadRightClickCrops(); } - ConfigHandler.instance().initialize(ConfigHandler.configFile); - Handlers.preInit(event); - - CompatRegistry.INSTANCE.handle(event); - OreDict.registerVanilla(); - - EnchantXPBoost.INSTANCE.register(); - EnchantAutoSmelt.INSTANCE.register(); - } - - @EventHandler - public void init(FMLInitializationEvent event) { - EnderPacketHandler.init(); - - for (IConfigHandler c : configs) { - c.initHook(); + @EventHandler + public void onServerStarting(FMLServerStartingEvent event) { + event.registerServerCommand(new CommandScoreboardInfo()); + PermanentCache.saveCaches(); } - Handlers.register(event); - CompatRegistry.INSTANCE.handle(event); - ClientCommandHandler.instance.registerCommand(CommandReloadConfigs.CLIENT); - if (event.getSide().isServer()) { - ((CommandHandler) MinecraftServer.getServer().getCommandManager()).registerCommand(CommandReloadConfigs.SERVER); + @EventHandler + public void onIMCEvent(IMCEvent event) { + IMCRegistry.INSTANCE.handleEvent(event); } - IMCRegistry.INSTANCE.init(); - } - - @EventHandler - public void postInit(FMLPostInitializationEvent event) { - for (IConfigHandler c : configs) { - c.postInitHook(); + @Override + public String modid() { + return MODID; } - CompatRegistry.INSTANCE.handle(event); - ConfigHandler.instance().loadRightClickCrops(); - } + @Override + public String name() { + return NAME; + } - @EventHandler - public void onServerStarting(FMLServerStartingEvent event) { - event.registerServerCommand(new CommandScoreboardInfo()); - PermanentCache.saveCaches(); - } - - @EventHandler - public void onIMCEvent(IMCEvent event) { - IMCRegistry.INSTANCE.handleEvent(event); - } - - @Override - public String modid() { - return MODID; - } - - @Override - public String name() { - return NAME; - } - - @Override - public String version() { - return VERSION; - } + @Override + public String version() { + return VERSION; + } } diff --git a/src/main/java/com/enderio/core/IEnderMod.java b/src/main/java/com/enderio/core/IEnderMod.java index 49fa005..13a5e9b 100644 --- a/src/main/java/com/enderio/core/IEnderMod.java +++ b/src/main/java/com/enderio/core/IEnderMod.java @@ -1,15 +1,16 @@ 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 modid(); - String version(); + String name(); + + String version(); } diff --git a/src/main/java/com/enderio/core/api/client/gui/IAdvancedTooltipProvider.java b/src/main/java/com/enderio/core/api/client/gui/IAdvancedTooltipProvider.java index febfda2..e0f5d7a 100644 --- a/src/main/java/com/enderio/core/api/client/gui/IAdvancedTooltipProvider.java +++ b/src/main/java/com/enderio/core/api/client/gui/IAdvancedTooltipProvider.java @@ -2,20 +2,21 @@ package com.enderio.core.api.client.gui; import java.util.List; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + public interface IAdvancedTooltipProvider { - @SideOnly(Side.CLIENT) - public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag); + @SideOnly(Side.CLIENT) + public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag); - @SideOnly(Side.CLIENT) - public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag); + @SideOnly(Side.CLIENT) + public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag); - @SideOnly(Side.CLIENT) - public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag); + @SideOnly(Side.CLIENT) + public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag); } 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 8b51cb2..2a9b78c 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 @@ -4,21 +4,21 @@ import java.awt.Rectangle; public interface IGuiOverlay extends IHideable { - void init(IGuiScreen screen); + void init(IGuiScreen screen); - Rectangle getBounds(); + Rectangle getBounds(); - void draw(int mouseX, int mouseY, float partialTick); + void draw(int mouseX, int mouseY, float partialTick); - // //consume event? - // boolean mouseClicked(int par1, int par2, int par3); - // - // boolean mouseClickMove(int par1, int par2, int par3, long p_146273_4_); - // - // boolean mouseMovedOrUp(int par1, int par2, int par3); + // //consume event? + // boolean mouseClicked(int par1, int par2, int par3); + // + // boolean mouseClickMove(int par1, int par2, int par3, long p_146273_4_); + // + // boolean mouseMovedOrUp(int par1, int par2, int par3); - boolean handleMouseInput(int x, int y, int b); + boolean handleMouseInput(int x, int y, int b); - boolean isMouseInBounds(int mouseX, int mouseY); + boolean isMouseInBounds(int mouseX, int mouseY); } diff --git a/src/main/java/com/enderio/core/api/client/gui/IGuiScreen.java b/src/main/java/com/enderio/core/api/client/gui/IGuiScreen.java index c0e9458..1444420 100644 --- a/src/main/java/com/enderio/core/api/client/gui/IGuiScreen.java +++ b/src/main/java/com/enderio/core/api/client/gui/IGuiScreen.java @@ -2,33 +2,33 @@ package com.enderio.core.api.client.gui; import java.util.List; +import net.minecraft.client.gui.GuiButton; + import com.enderio.core.client.gui.widget.GhostSlot; import com.enderio.core.client.gui.widget.GuiToolTip; -import net.minecraft.client.gui.GuiButton; - public interface IGuiScreen { - void addToolTip(GuiToolTip toolTip); + void addToolTip(GuiToolTip toolTip); - boolean removeToolTip(GuiToolTip toolTip); + boolean removeToolTip(GuiToolTip toolTip); - int getGuiLeft(); + int getGuiLeft(); - int getGuiTop(); + int getGuiTop(); - int getXSize(); + int getXSize(); - int getYSize(); + int getYSize(); - void addButton(GuiButton button); + void addButton(GuiButton button); - void removeButton(GuiButton button); + void removeButton(GuiButton button); - int getOverlayOffsetX(); + int getOverlayOffsetX(); - void doActionPerformed(GuiButton but); + void doActionPerformed(GuiButton but); - List getGhostSlots(); + List getGhostSlots(); } diff --git a/src/main/java/com/enderio/core/api/client/gui/IResourceTooltipProvider.java b/src/main/java/com/enderio/core/api/client/gui/IResourceTooltipProvider.java index b538c3c..d547e55 100644 --- a/src/main/java/com/enderio/core/api/client/gui/IResourceTooltipProvider.java +++ b/src/main/java/com/enderio/core/api/client/gui/IResourceTooltipProvider.java @@ -4,6 +4,6 @@ import net.minecraft.item.ItemStack; public interface IResourceTooltipProvider { - String getUnlocalizedNameForTooltip(ItemStack itemStack); + String getUnlocalizedNameForTooltip(ItemStack itemStack); } diff --git a/src/main/java/com/enderio/core/api/client/gui/ITabPanel.java b/src/main/java/com/enderio/core/api/client/gui/ITabPanel.java index 8dc4c0e..5009e3a 100644 --- a/src/main/java/com/enderio/core/api/client/gui/ITabPanel.java +++ b/src/main/java/com/enderio/core/api/client/gui/ITabPanel.java @@ -1,33 +1,33 @@ package com.enderio.core.api.client.gui; import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.ResourceLocation; import com.enderio.core.api.client.render.IWidgetIcon; -import net.minecraft.util.ResourceLocation; public interface ITabPanel { - void onGuiInit(int x, int y, int width, int height); + void onGuiInit(int x, int y, int width, int height); - void deactivate(); + void deactivate(); - IWidgetIcon getIcon(); + IWidgetIcon getIcon(); - void render(float par1, int par2, int par3); + void render(float par1, int par2, int par3); - void actionPerformed(GuiButton guiButton); + void actionPerformed(GuiButton guiButton); - void mouseClicked(int x, int y, int par3); + void mouseClicked(int x, int y, int par3); - void keyTyped(char par1, int par2); + void keyTyped(char par1, int par2); - void updateScreen(); + void updateScreen(); - /** - * @return The location of the texture used for slot backgrounds, etc. - */ - default ResourceLocation getTexture() { - return new ResourceLocation("enderio", "textures/gui/23/externalConduitConnection.png"); - } + /** + * @return The location of the texture used for slot backgrounds, etc. + */ + default ResourceLocation getTexture() { + return new ResourceLocation("enderio", "textures/gui/23/externalConduitConnection.png"); + } } diff --git a/src/main/java/com/enderio/core/api/client/gui/ListSelectionListener.java b/src/main/java/com/enderio/core/api/client/gui/ListSelectionListener.java index 0d01846..17ac04a 100644 --- a/src/main/java/com/enderio/core/api/client/gui/ListSelectionListener.java +++ b/src/main/java/com/enderio/core/api/client/gui/ListSelectionListener.java @@ -4,6 +4,6 @@ import com.enderio.core.client.gui.widget.GuiScrollableList; public interface ListSelectionListener { - void selectionChanged(GuiScrollableList list, int selectedIndex); + void selectionChanged(GuiScrollableList list, int selectedIndex); } 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 e1c6f3e..89126a2 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 @@ -6,22 +6,21 @@ 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); - /** - * 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); + /** + * 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); } 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 7ba4e6c..344be7d 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 @@ -2,6 +2,6 @@ package com.enderio.core.api.client.render; public interface IConnectedTextureRenderer { - boolean matchesMetadata(int meta1, int meta2); + boolean matchesMetadata(int meta1, int meta2); } diff --git a/src/main/java/com/enderio/core/api/client/render/IRenderFace.java b/src/main/java/com/enderio/core/api/client/render/IRenderFace.java index 4673e7f..60d4492 100644 --- a/src/main/java/com/enderio/core/api/client/render/IRenderFace.java +++ b/src/main/java/com/enderio/core/api/client/render/IRenderFace.java @@ -2,16 +2,16 @@ package com.enderio.core.api.client.render; import java.util.List; -import com.enderio.core.client.render.CustomRenderBlocks; -import com.enderio.core.common.vecmath.Vertex; - import net.minecraft.block.Block; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; +import com.enderio.core.client.render.CustomRenderBlocks; +import com.enderio.core.common.vecmath.Vertex; + public interface IRenderFace { - void renderFace(CustomRenderBlocks rb, ForgeDirection face, Block par1Block, double x, double y, double z, IIcon texture, List refVertices, - boolean translateToXyz); + void renderFace(CustomRenderBlocks rb, ForgeDirection face, Block par1Block, double x, double y, double z, + IIcon texture, List refVertices, boolean translateToXyz); } 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 bd3beae..d9631a8 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 @@ -4,16 +4,16 @@ import javax.annotation.Nullable; public interface IWidgetIcon { - int getX(); + int getX(); - int getY(); + int getY(); - int getWidth(); + int getWidth(); - int getHeight(); + int getHeight(); - @Nullable - IWidgetIcon getOverlay(); + @Nullable + IWidgetIcon getOverlay(); - IWidgetMap getMap(); + IWidgetMap getMap(); } 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 9272032..fc6cbf7 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 @@ -7,104 +7,107 @@ import com.enderio.core.client.render.RenderUtil; public interface IWidgetMap { - int getSize(); + int getSize(); - ResourceLocation getTexture(); + ResourceLocation getTexture(); - void render(IWidgetIcon widget, double x, double y); + void render(IWidgetIcon widget, double x, double y); - void render(IWidgetIcon widget, double x, double y, boolean doDraw); + void render(IWidgetIcon widget, double x, double y, boolean doDraw); - void render(IWidgetIcon widget, double x, double y, boolean doDraw, boolean flipY); + void render(IWidgetIcon widget, double x, double y, boolean doDraw, boolean flipY); - void render(IWidgetIcon widget, double x, double y, double zLevel, boolean doDraw); + void render(IWidgetIcon widget, double x, double y, double zLevel, boolean doDraw); - void render(IWidgetIcon widget, double x, double y, double zLevel, boolean doDraw, boolean flipY); + void render(IWidgetIcon widget, double x, double y, double zLevel, boolean doDraw, boolean flipY); - void render(IWidgetIcon widget, double x, double y, double width, double height, double zLevel, boolean doDraw); + void render(IWidgetIcon widget, double x, double y, double width, double height, double zLevel, boolean doDraw); - void render(IWidgetIcon widget, double x, double y, double width, double height, double zLevel, boolean doDraw, boolean flipY); + void render(IWidgetIcon widget, double x, double y, double width, double height, double zLevel, boolean doDraw, + boolean flipY); - static class WidgetMapImpl implements IWidgetMap { + static class WidgetMapImpl implements IWidgetMap { - private final int size; - private final ResourceLocation res; - - public WidgetMapImpl(int size, ResourceLocation res) { - this.size = size; - this.res = res; + private final int size; + private final ResourceLocation res; + + public WidgetMapImpl(int size, ResourceLocation res) { + this.size = size; + this.res = res; + } + + @Override + public int getSize() { + return size; + } + + @Override + public ResourceLocation getTexture() { + return res; + } + + @Override + public void render(IWidgetIcon widget, double x, double y) { + render(widget, x, y, false); + } + + @Override + public void render(IWidgetIcon widget, double x, double y, boolean doDraw) { + render(widget, x, y, widget.getWidth(), widget.getHeight(), 0, doDraw); + } + + @Override + public void render(IWidgetIcon widget, double x, double y, boolean doDraw, boolean flipY) { + render(widget, x, y, widget.getWidth(), widget.getHeight(), 0, doDraw, flipY); + } + + @Override + public void render(IWidgetIcon widget, double x, double y, double zLevel, boolean doDraw) { + render(widget, x, y, widget.getWidth(), widget.getHeight(), zLevel, doDraw); + } + + @Override + public void render(IWidgetIcon widget, double x, double y, double zLevel, boolean doDraw, boolean flipY) { + render(widget, x, y, widget.getWidth(), widget.getHeight(), zLevel, doDraw, flipY); + } + + @Override + public void render(IWidgetIcon widget, double x, double y, double width, double height, double zLevel, + boolean doDraw) { + render(widget, x, y, width, height, zLevel, doDraw, false); + } + + @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()); + tessellator.startDrawingQuads(); + } + double minU = (double) widget.getX() / getSize(); + double maxU = (double) (widget.getX() + widget.getWidth()) / getSize(); + double minV = (double) widget.getY() / getSize(); + double maxV = (double) (widget.getY() + widget.getHeight()) / getSize(); + + if (flipY) { + tessellator.addVertexWithUV(x, y + height, zLevel, minU, minV); + tessellator.addVertexWithUV(x + width, y + height, zLevel, maxU, minV); + tessellator.addVertexWithUV(x + width, y + 0, zLevel, maxU, maxV); + tessellator.addVertexWithUV(x, y + 0, zLevel, minU, maxV); + } else { + tessellator.addVertexWithUV(x, y + height, zLevel, minU, maxV); + tessellator.addVertexWithUV(x + width, y + height, zLevel, maxU, maxV); + tessellator.addVertexWithUV(x + width, y + 0, zLevel, maxU, minV); + tessellator.addVertexWithUV(x, y + 0, zLevel, minU, minV); + } + if (widget.getOverlay() != null) { + widget.getOverlay().getMap().render(widget.getOverlay(), x, y, width, height, zLevel, false, flipY); + } + if (doDraw) { + tessellator.draw(); + } + } } - - @Override - public int getSize() { - return size; - } - - @Override - public ResourceLocation getTexture() { - return res; - } - - @Override - public void render(IWidgetIcon widget, double x, double y) { - render(widget, x, y, false); - } - - @Override - public void render(IWidgetIcon widget, double x, double y, boolean doDraw) { - render(widget, x, y, widget.getWidth(), widget.getHeight(), 0, doDraw); - } - - @Override - public void render(IWidgetIcon widget, double x, double y, boolean doDraw, boolean flipY) { - render(widget, x, y, widget.getWidth(), widget.getHeight(), 0, doDraw, flipY); - } - - @Override - public void render(IWidgetIcon widget, double x, double y, double zLevel, boolean doDraw) { - render(widget, x, y, widget.getWidth(), widget.getHeight(), zLevel, doDraw); - } - - @Override - public void render(IWidgetIcon widget, double x, double y, double zLevel, boolean doDraw, boolean flipY) { - render(widget, x, y, widget.getWidth(), widget.getHeight(), zLevel, doDraw, flipY); - } - - @Override - public void render(IWidgetIcon widget, double x, double y, double width, double height, double zLevel, boolean doDraw) { - render(widget, x, y, width, height, zLevel, doDraw, false); - } - - @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()); - tessellator.startDrawingQuads(); - } - double minU = (double) widget.getX() / getSize(); - double maxU = (double) (widget.getX() + widget.getWidth()) / getSize(); - double minV = (double) widget.getY() / getSize(); - double maxV = (double) (widget.getY() + widget.getHeight()) / getSize(); - - if (flipY) { - tessellator.addVertexWithUV(x, y + height, zLevel, minU, minV); - tessellator.addVertexWithUV(x + width, y + height, zLevel, maxU, minV); - tessellator.addVertexWithUV(x + width, y + 0, zLevel, maxU, maxV); - tessellator.addVertexWithUV(x, y + 0, zLevel, minU, maxV); - } else { - tessellator.addVertexWithUV(x, y + height, zLevel, minU, maxV); - tessellator.addVertexWithUV(x + width, y + height, zLevel, maxU, maxV); - tessellator.addVertexWithUV(x + width, y + 0, zLevel, maxU, minV); - tessellator.addVertexWithUV(x, y + 0, zLevel, minU, minV); - } - if (widget.getOverlay() != null) { - widget.getOverlay().getMap().render(widget.getOverlay(), x, y, width, height, zLevel, false, flipY); - } - if (doDraw) { - tessellator.draw(); - } - } - } } diff --git a/src/main/java/com/enderio/core/api/client/render/VertexTransform.java b/src/main/java/com/enderio/core/api/client/render/VertexTransform.java index 6c0dc75..566d508 100644 --- a/src/main/java/com/enderio/core/api/client/render/VertexTransform.java +++ b/src/main/java/com/enderio/core/api/client/render/VertexTransform.java @@ -6,10 +6,10 @@ import com.enderio.core.common.vecmath.Vertex; public interface VertexTransform { - void apply(Vertex vertex); + void apply(Vertex vertex); - void apply(Vector3d vec); + void apply(Vector3d vec); - void applyToNormal(Vector3f vec); + void applyToNormal(Vector3f vec); } diff --git a/src/main/java/com/enderio/core/api/common/config/IConfigHandler.java b/src/main/java/com/enderio/core/api/common/config/IConfigHandler.java index e9ee434..2d92859 100644 --- a/src/main/java/com/enderio/core/api/common/config/IConfigHandler.java +++ b/src/main/java/com/enderio/core/api/common/config/IConfigHandler.java @@ -3,28 +3,30 @@ package com.enderio.core.api.common.config; import java.io.File; import java.util.List; +import net.minecraftforge.common.config.ConfigCategory; + import com.enderio.core.common.config.AbstractConfigHandler.Section; -import net.minecraftforge.common.config.ConfigCategory; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; public interface IConfigHandler { - void initialize(File cfg); - List
getSections(); + void initialize(File cfg); - ConfigCategory getCategory(String name); + List
getSections(); - String getModID(); + ConfigCategory getCategory(String name); - /** - * A hook for the {@link FMLInitializationEvent}. - */ - void initHook(); + String getModID(); - /** - * A hook for the {@link FMLPostInitializationEvent}. - */ - void postInitHook(); + /** + * A hook for the {@link FMLInitializationEvent}. + */ + void initHook(); + + /** + * A hook for the {@link FMLPostInitializationEvent}. + */ + void postInitHook(); } 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 89d636a..32a630a 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 @@ -6,11 +6,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); + + /** + * 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 7ce9a11..6558e66 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,15 @@ 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"; + + /** + * 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/api/common/util/IFluidReceptor.java b/src/main/java/com/enderio/core/api/common/util/IFluidReceptor.java index a654b8c..21c9c76 100644 --- a/src/main/java/com/enderio/core/api/common/util/IFluidReceptor.java +++ b/src/main/java/com/enderio/core/api/common/util/IFluidReceptor.java @@ -4,6 +4,6 @@ import net.minecraftforge.fluids.IFluidHandler; public interface IFluidReceptor { - boolean isValidReceptor(IFluidHandler handler); + boolean isValidReceptor(IFluidHandler handler); } diff --git a/src/main/java/com/enderio/core/api/common/util/IItemReceptor.java b/src/main/java/com/enderio/core/api/common/util/IItemReceptor.java index 76d322f..868fbbf 100644 --- a/src/main/java/com/enderio/core/api/common/util/IItemReceptor.java +++ b/src/main/java/com/enderio/core/api/common/util/IItemReceptor.java @@ -5,8 +5,8 @@ import net.minecraftforge.common.util.ForgeDirection; public interface IItemReceptor { - boolean canInsertIntoObject(Object into, ForgeDirection side); + boolean canInsertIntoObject(Object into, ForgeDirection side); - int doInsertItem(Object into, ItemStack item, ForgeDirection side); + int doInsertItem(Object into, ItemStack item, ForgeDirection side); } diff --git a/src/main/java/com/enderio/core/api/common/util/IProgressTile.java b/src/main/java/com/enderio/core/api/common/util/IProgressTile.java index d93fd11..e0b279e 100644 --- a/src/main/java/com/enderio/core/api/common/util/IProgressTile.java +++ b/src/main/java/com/enderio/core/api/common/util/IProgressTile.java @@ -1,22 +1,21 @@ package com.enderio.core.api.common.util; import net.minecraft.tileentity.TileEntity; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public interface IProgressTile { - float getProgress(); + float getProgress(); - /** - * Client-only. Called to set clientside progress for syncing/rendering - * purposes. - * - * @param progress - * The % progress. - */ - @SideOnly(Side.CLIENT) - void setProgress(float progress); + /** + * Client-only. Called to set clientside progress for syncing/rendering purposes. + * + * @param progress The % progress. + */ + @SideOnly(Side.CLIENT) + void setProgress(float progress); - TileEntity getTileEntity(); + TileEntity getTileEntity(); } diff --git a/src/main/java/com/enderio/core/api/common/util/ITankAccess.java b/src/main/java/com/enderio/core/api/common/util/ITankAccess.java index 69688e5..4fc6306 100644 --- a/src/main/java/com/enderio/core/api/common/util/ITankAccess.java +++ b/src/main/java/com/enderio/core/api/common/util/ITankAccess.java @@ -5,29 +5,26 @@ import net.minecraftforge.fluids.FluidTank; public interface ITankAccess { - /** - * Find tank to insert fluid. - * - * @param forFluidType - * The type of fluid that should be inserted. May be null. - * @return An internal tank that can take the given type of fluid. If multiple - * tanks can take the fluid, the first one that is not full will be - * returned. If no tank can take the fluid, returns null. - */ - FluidTank getInputTank(FluidStack forFluidType); + /** + * Find tank to insert fluid. + * + * @param forFluidType The type of fluid that should be inserted. May be null. + * @return An internal tank that can take the given type of fluid. If multiple tanks can take the fluid, the first + * one that is not full will be returned. If no tank can take the fluid, returns null. + */ + FluidTank getInputTank(FluidStack forFluidType); - /** - * Get tank(s) to remove liquid from. - * - * @return Tank that can be drained. Tanks are returned in order or priority. - * If there's no tank, an empty array is returned. - */ - FluidTank[] getOutputTanks(); + /** + * Get tank(s) to remove liquid from. + * + * @return Tank that can be drained. Tanks are returned in order or priority. If there's no tank, an empty array is + * returned. + */ + FluidTank[] getOutputTanks(); - /** - * Will be called after a tank that was returned by one of the other methods - * was manipulated. - */ - void setTanksDirty(); + /** + * Will be called after a tank that was returned by one of the other methods was manipulated. + */ + void setTanksDirty(); } diff --git a/src/main/java/com/enderio/core/client/ClientProxy.java b/src/main/java/com/enderio/core/client/ClientProxy.java index 033592e..a5e5ad2 100644 --- a/src/main/java/com/enderio/core/client/ClientProxy.java +++ b/src/main/java/com/enderio/core/client/ClientProxy.java @@ -8,22 +8,22 @@ import com.enderio.core.common.util.Scheduler; public class ClientProxy extends CommonProxy { - @Override - public Scheduler getScheduler() { - if (scheduler == null) { - scheduler = new Scheduler(false); + @Override + public Scheduler getScheduler() { + if (scheduler == null) { + scheduler = new Scheduler(false); + } + return scheduler; } - return scheduler; - } - @Override - public World getClientWorld() { - return Minecraft.getMinecraft().theWorld; - } + @Override + public World getClientWorld() { + return Minecraft.getMinecraft().theWorld; + } - @Override - public void throwModCompatibilityError(String... msgs) { - throw new EnderCoreModConflictException(msgs); - } + @Override + public void throwModCompatibilityError(String... msgs) { + 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 21b23fe..28a0bf0 100644 --- a/src/main/java/com/enderio/core/client/EnderCoreModConflictException.java +++ b/src/main/java/com/enderio/core/client/EnderCoreModConflictException.java @@ -1,31 +1,32 @@ package com.enderio.core.client; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiErrorScreen; + 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; @SideOnly(Side.CLIENT) public class EnderCoreModConflictException extends CustomModLoadingErrorDisplayException { - private final String[] msgs; + private final String[] msgs; - public EnderCoreModConflictException(String[] msgs) { - super(msgs[0], new RuntimeException()); - this.msgs = msgs; - } - - @Override - public void initGui(GuiErrorScreen errorScreen, FontRenderer fontRenderer) { - } - - @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) { - errorScreen.drawCenteredString(fontRenderer, msg, errorScreen.width / 2, y, 0xFFFFFF); - y += 10; + public EnderCoreModConflictException(String[] msgs) { + super(msgs[0], new RuntimeException()); + this.msgs = msgs; + } + + @Override + public void initGui(GuiErrorScreen errorScreen, FontRenderer fontRenderer) {} + + @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) { + 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 51f6381..a22e89e 100644 --- a/src/main/java/com/enderio/core/client/config/BaseConfigGui.java +++ b/src/main/java/com/enderio/core/client/config/BaseConfigGui.java @@ -19,125 +19,128 @@ 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); - try { - // pffft final, what a wimpy modifier - Field modID = GuiConfig.class.getDeclaredField("modID"); - Field configElements = GuiConfig.class.getDeclaredField("configElements"); + @SuppressWarnings("rawtypes") + public BaseConfigGui(GuiScreen parentScreen) { + // dummy super so we can call instance methods + super(parentScreen, new ArrayList(), null, false, false, null); - modID.setAccessible(true); - configElements.setAccessible(true); + try { + // pffft final, what a wimpy modifier + Field modID = GuiConfig.class.getDeclaredField("modID"); + Field configElements = GuiConfig.class.getDeclaredField("configElements"); - modID.set(this, getConfigHandler().getModID()); - configElements.set(this, getConfigElements()); - } catch (Exception e) { - throw new RuntimeException(e); - } + modID.setAccessible(true); + configElements.setAccessible(true); - 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)); - } - - 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; - } - - @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)); + modID.set(this, getConfigHandler().getModID()); + configElements.set(this, getConfigElements()); + } catch (Exception e) { + throw new RuntimeException(e); } - } - 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); - } + this.title = getTitle(); } - private ConfigElementExtended(IConfigElement other) { - super(getProp(other)); + /** + * The localized title of this config screen + */ + protected String getTitle() { + return EnderCore.lang.localize("config.title"); } - private static Property getProp(IConfigElement other) { - try { - return (Property) _prop.get(other); - } catch (Exception e) { - throw Throwables.propagate(e); - } + /** + * The {@link IConfigHandler} to refer to when generating this config screen + */ + protected IConfigHandler getConfigHandler() { + return ConfigHandler.instance(); } - @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; + /** + * 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)); + } + + 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; + } + + @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); + } + } + + private ConfigElementExtended(IConfigElement other) { + super(getProp(other)); + } + + private static Property getProp(IConfigElement other) { + try { + return (Property) _prop.get(other); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } + + @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/GhostSlotHandler.java b/src/main/java/com/enderio/core/client/gui/GhostSlotHandler.java index 2e74a19..591e84e 100644 --- a/src/main/java/com/enderio/core/client/gui/GhostSlotHandler.java +++ b/src/main/java/com/enderio/core/client/gui/GhostSlotHandler.java @@ -4,11 +4,11 @@ import static com.enderio.core.client.render.EnderWidget.NEUTRAL_SLOT_BACKGROUND import java.util.List; -import org.lwjgl.opengl.GL11; - import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; +import org.lwjgl.opengl.GL11; + import com.enderio.core.client.gui.widget.GhostSlot; import com.enderio.core.client.render.RenderUtil; import com.enderio.core.common.util.ItemUtil; @@ -16,215 +16,215 @@ import com.google.common.collect.Lists; public class GhostSlotHandler { - protected List ghostSlots = Lists.newArrayList(); - protected GhostSlot hoverGhostSlot; + protected List ghostSlots = Lists.newArrayList(); + protected GhostSlot hoverGhostSlot; - public GhostSlotHandler() { - } + public GhostSlotHandler() {} - // GhostSlot managing + // GhostSlot managing - protected List getGhostSlots() { - return ghostSlots; - } - - protected GhostSlot getGhostSlot(GuiContainerBase guiContainerBase, int mouseX, int mouseY) { - mouseX -= guiContainerBase.getGuiLeft(); - mouseY -= guiContainerBase.getGuiTop(); - for (GhostSlot slot : ghostSlots) { - if (slot.isVisible() && slot.isMouseOver(mouseX, mouseY)) { - return slot; - } + protected List getGhostSlots() { + return ghostSlots; } - return null; - } - // Slot interaction - - /** - * Called when a ghost slot is clicked or mouse wheeled. - * - * @param gui - * The GUI the GhostSlot is in - * @param slot - * The GhostSlot - * @param x - * Mouse position x - * @param y - * Mouse position y - * @param button - * The button used (0=left, 1=right). The mouse wheel is mapped to - * -1=down and -2=up. - */ - protected void ghostSlotClicked(GuiContainerBase gui, GhostSlot slot, int x, int y, int button) { - ItemStack handStack = Minecraft.getMinecraft().thePlayer.inventory.getItemStack(); - ItemStack existingStack = slot.getStack(); - if (button == 0) { // left - ghostSlotClickedPrimaryMouseButton(slot, handStack, existingStack); - } else if (button == 1) { // right - ghostSlotClickedSecondaryMouseButton(slot, handStack, existingStack); - } else if (button == -2) { // wheel up - ghostSlotClickedMouseWheelUp(slot, handStack, existingStack); - } else if (button == -1) { // wheel down - ghostSlotClickedMouseWheelDown(slot, handStack, existingStack); + protected GhostSlot getGhostSlot(GuiContainerBase guiContainerBase, int mouseX, int mouseY) { + mouseX -= guiContainerBase.getGuiLeft(); + mouseY -= guiContainerBase.getGuiTop(); + for (GhostSlot slot : ghostSlots) { + if (slot.isVisible() && slot.isMouseOver(mouseX, mouseY)) { + return slot; + } + } + return null; } - } - protected void ghostSlotClickedPrimaryMouseButton(GhostSlot slot, ItemStack handStack, ItemStack existingStack) { - if (handStack == null || handStack.getItem() == null || handStack.stackSize == 0) { // empty hand - slot.putStack(null); - } else { // item in hand - if (existingStack == null || existingStack.getItem() == null || existingStack.stackSize == 0) { // empty slot - replaceSlot(slot, handStack); - } else { // filled slot - if (ItemUtil.areStackMergable(existingStack, handStack)) { // same item - if (existingStack.stackSize < existingStack.getMaxStackSize() && existingStack.stackSize < slot.getStackSizeLimit()) { + // Slot interaction + + /** + * Called when a ghost slot is clicked or mouse wheeled. + * + * @param gui The GUI the GhostSlot is in + * @param slot The GhostSlot + * @param x Mouse position x + * @param y Mouse position y + * @param button The button used (0=left, 1=right). The mouse wheel is mapped to -1=down and -2=up. + */ + protected void ghostSlotClicked(GuiContainerBase gui, GhostSlot slot, int x, int y, int button) { + ItemStack handStack = Minecraft.getMinecraft().thePlayer.inventory.getItemStack(); + ItemStack existingStack = slot.getStack(); + if (button == 0) { // left + ghostSlotClickedPrimaryMouseButton(slot, handStack, existingStack); + } else if (button == 1) { // right + ghostSlotClickedSecondaryMouseButton(slot, handStack, existingStack); + } else if (button == -2) { // wheel up + ghostSlotClickedMouseWheelUp(slot, handStack, existingStack); + } else if (button == -1) { // wheel down + ghostSlotClickedMouseWheelDown(slot, handStack, existingStack); + } + } + + protected void ghostSlotClickedPrimaryMouseButton(GhostSlot slot, ItemStack handStack, ItemStack existingStack) { + if (handStack == null || handStack.getItem() == null || handStack.stackSize == 0) { // empty hand + slot.putStack(null); + } else { // item in hand + if (existingStack == null || existingStack.getItem() == null || existingStack.stackSize == 0) { // empty + // slot + replaceSlot(slot, handStack); + } else { // filled slot + if (ItemUtil.areStackMergable(existingStack, handStack)) { // same item + if (existingStack.stackSize < existingStack.getMaxStackSize() + && existingStack.stackSize < slot.getStackSizeLimit()) { + increaseSlot(slot, existingStack); + } else { + // NOP + } + } else { // different item + replaceSlot(slot, handStack); + } + } + } + } + + protected void ghostSlotClickedSecondaryMouseButton(GhostSlot slot, ItemStack handStack, ItemStack existingStack) { + if (handStack == null || handStack.getItem() == null || handStack.stackSize == 0) { // empty hand + slot.putStack(null); + } else { // item in hand + if (existingStack == null || existingStack.getItem() == null || existingStack.stackSize == 0) { // empty + // slot + replaceSlot1Item(slot, handStack); + } else { // filled slot + if (ItemUtil.areStackMergable(existingStack, handStack)) { // same item + descreaseSlot(slot, existingStack); + } else { // different item + replaceSlot1Item(slot, handStack); + } + } + } + } + + protected void ghostSlotClickedMouseWheelUp(GhostSlot slot, ItemStack handStack, ItemStack existingStack) { + if (existingStack != null && existingStack.getItem() != null + && existingStack.stackSize > 0 + && existingStack.stackSize < existingStack.getMaxStackSize() + && existingStack.stackSize < slot.getStackSizeLimit()) { increaseSlot(slot, existingStack); - } else { - // NOP - } - } else { // different item - replaceSlot(slot, handStack); } - } } - } - protected void ghostSlotClickedSecondaryMouseButton(GhostSlot slot, ItemStack handStack, ItemStack existingStack) { - if (handStack == null || handStack.getItem() == null || handStack.stackSize == 0) { // empty hand - slot.putStack(null); - } else { // item in hand - if (existingStack == null || existingStack.getItem() == null || existingStack.stackSize == 0) { // empty slot - replaceSlot1Item(slot, handStack); - } else { // filled slot - if (ItemUtil.areStackMergable(existingStack, handStack)) { // same item - descreaseSlot(slot, existingStack); - } else { // different item - replaceSlot1Item(slot, handStack); + protected void ghostSlotClickedMouseWheelDown(GhostSlot slot, ItemStack handStack, ItemStack existingStack) { + if (existingStack != null && existingStack.getItem() != null) { + descreaseSlot(slot, existingStack); } - } } - } - protected void ghostSlotClickedMouseWheelUp(GhostSlot slot, ItemStack handStack, ItemStack existingStack) { - if (existingStack != null && existingStack.getItem() != null && existingStack.stackSize > 0 && existingStack.stackSize < existingStack.getMaxStackSize() - && existingStack.stackSize < slot.getStackSizeLimit()) { - increaseSlot(slot, existingStack); + // Slot interaction tools + + protected void descreaseSlot(GhostSlot slot, ItemStack existingStack) { + if (existingStack.stackSize > 1) { + existingStack.stackSize--; + slot.putStack(existingStack); + } else { + slot.putStack(null); + } } - } - protected void ghostSlotClickedMouseWheelDown(GhostSlot slot, ItemStack handStack, ItemStack existingStack) { - if (existingStack != null && existingStack.getItem() != null) { - descreaseSlot(slot, existingStack); + protected void increaseSlot(GhostSlot slot, ItemStack existingStack) { + existingStack.stackSize++; + slot.putStack(existingStack); } - } - // Slot interaction tools - - protected void descreaseSlot(GhostSlot slot, ItemStack existingStack) { - if (existingStack.stackSize > 1) { - existingStack.stackSize--; - slot.putStack(existingStack); - } else { - slot.putStack(null); + protected void replaceSlot1Item(GhostSlot slot, ItemStack handStack) { + ItemStack oneItem = handStack.copy(); + oneItem.stackSize = 1; + slot.putStack(oneItem); } - } - protected void increaseSlot(GhostSlot slot, ItemStack existingStack) { - existingStack.stackSize++; - slot.putStack(existingStack); - } - - protected void replaceSlot1Item(GhostSlot slot, ItemStack handStack) { - ItemStack oneItem = handStack.copy(); - oneItem.stackSize = 1; - slot.putStack(oneItem); - } - - protected void replaceSlot(GhostSlot slot, ItemStack handStack) { - if (handStack.stackSize <= slot.getStackSizeLimit()) { - slot.putStack(handStack); - } else { - ItemStack tmp = handStack.copy(); - tmp.stackSize = slot.getStackSizeLimit(); - slot.putStack(tmp); + protected void replaceSlot(GhostSlot slot, ItemStack handStack) { + if (handStack.stackSize <= slot.getStackSizeLimit()) { + slot.putStack(handStack); + } else { + ItemStack tmp = handStack.copy(); + tmp.stackSize = slot.getStackSizeLimit(); + slot.putStack(tmp); + } } - } - // Rendering + // Rendering - protected void startDrawing(GuiContainerBase gui) { - gui.hoverGhostSlot = hoverGhostSlot = null; - } + protected void startDrawing(GuiContainerBase gui) { + gui.hoverGhostSlot = hoverGhostSlot = null; + } - protected void drawGhostSlots(GuiContainerBase gui, int mouseX, int mouseY) { - int sx = gui.getGuiLeft(); - int sy = gui.getGuiTop(); - gui.drawFakeItemsStart(); - try { - gui.hoverGhostSlot = hoverGhostSlot = null; - for (GhostSlot slot : ghostSlots) { + protected void drawGhostSlots(GuiContainerBase gui, int mouseX, int mouseY) { + int sx = gui.getGuiLeft(); + int sy = gui.getGuiTop(); + gui.drawFakeItemsStart(); + try { + gui.hoverGhostSlot = hoverGhostSlot = null; + for (GhostSlot slot : ghostSlots) { + ItemStack stack = slot.getStack(); + if (slot.isVisible()) { + if (stack != null) { + gui.drawFakeItemStack(slot.x + sx, slot.y + sy, stack); + if (slot.shouldDisplayStdOverlay()) { + gui.drawFakeItemStackStdOverlay(slot.x + sx, slot.y + sy, stack); + } + if (slot.shouldGrayOut()) { + gui.ghostSlotHandler.drawGhostSlotGrayout(gui, slot); + } + } + if (slot.isMouseOver(mouseX - sx, mouseY - sy)) { + gui.hoverGhostSlot = hoverGhostSlot = slot; + } + } + } + if (hoverGhostSlot != null) { + // draw hover last to prevent it from affecting rendering of other slots ... + gui.drawFakeItemHover(hoverGhostSlot.x + sx, hoverGhostSlot.y + sy); + } + } finally { + gui.drawFakeItemsEnd(); + } + } + + /** + * Gray out the item that was just painted into a GhostSlot by overpainting it with 50% transparent background. This + * gives the illusion that the item was painted with 50% transparency. (100%*a ° 100%*b ° 50%*a == 100%*a ° 50%*b) + */ + protected void drawGhostSlotGrayout(GuiContainerBase gui, GhostSlot slot) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glColor4f(1.0F, 1.0F, 1.0F, slot.getGrayOutLevel()); + String guiTexture = gui.getGuiTexture(); + if (guiTexture == null) { + NEUTRAL_SLOT_BACKGROUND.getMap().render( + NEUTRAL_SLOT_BACKGROUND, + gui.getGuiLeft() + slot.x, + gui.getGuiTop() + slot.y, + gui.getZlevel(), + true); + } else { + RenderUtil.bindTexture(guiTexture); + gui.drawTexturedModalRect(gui.getGuiLeft() + slot.x, gui.getGuiTop() + slot.y, slot.x, slot.y, 16, 16); + } + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_LIGHTING); + } + + protected void drawGhostSlotTooltip(GuiContainerBase guiContainerBase, GhostSlot slot, int mouseX, int mouseY) { ItemStack stack = slot.getStack(); - if (slot.isVisible()) { - if (stack != null) { - gui.drawFakeItemStack(slot.x + sx, slot.y + sy, stack); - if (slot.shouldDisplayStdOverlay()) { - gui.drawFakeItemStackStdOverlay(slot.x + sx, slot.y + sy, stack); - } - if (slot.shouldGrayOut()) { - gui.ghostSlotHandler.drawGhostSlotGrayout(gui, slot); - } - } - if (slot.isMouseOver(mouseX - sx, mouseY - sy)) { - gui.hoverGhostSlot = hoverGhostSlot = slot; - } + if (stack != null) { + guiContainerBase.renderToolTip(stack, mouseX, mouseY); } - } - if (hoverGhostSlot != null) { - // draw hover last to prevent it from affecting rendering of other slots ... - gui.drawFakeItemHover(hoverGhostSlot.x + sx, hoverGhostSlot.y + sy); - } - } finally { - gui.drawFakeItemsEnd(); - } - } - - /** - * Gray out the item that was just painted into a GhostSlot by overpainting it - * with 50% transparent background. This gives the illusion that the item was - * painted with 50% transparency. (100%*a ° 100%*b ° 50%*a == 100%*a ° 50%*b) - */ - protected void drawGhostSlotGrayout(GuiContainerBase gui, GhostSlot slot) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_BLEND); - GL11.glColor4f(1.0F, 1.0F, 1.0F, slot.getGrayOutLevel()); - String guiTexture = gui.getGuiTexture(); - if (guiTexture == null) { - NEUTRAL_SLOT_BACKGROUND.getMap().render(NEUTRAL_SLOT_BACKGROUND, gui.getGuiLeft() + slot.x, gui.getGuiTop() + slot.y, gui.getZlevel(), true); - } else { - RenderUtil.bindTexture(guiTexture); - gui.drawTexturedModalRect(gui.getGuiLeft() + slot.x, gui.getGuiTop() + slot.y, slot.x, slot.y, 16, 16); - } - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_LIGHTING); - } - - - protected void drawGhostSlotTooltip(GuiContainerBase guiContainerBase, GhostSlot slot, int mouseX, int mouseY) { - ItemStack stack = slot.getStack(); - if (stack != null) { - guiContainerBase.renderToolTip(stack, mouseX, mouseY); - } - } - - - protected void drawGhostSlotToolTip(GuiContainerBase gui, int mouseX, int mouseY) { - if (hoverGhostSlot != null && gui.mc.thePlayer.inventory.getItemStack() == null) { - gui.drawGhostSlotTooltip(hoverGhostSlot, mouseX, mouseY); } - } + protected void drawGhostSlotToolTip(GuiContainerBase gui, int mouseX, int mouseY) { + if (hoverGhostSlot != null && gui.mc.thePlayer.inventory.getItemStack() == null) { + gui.drawGhostSlotTooltip(hoverGhostSlot, mouseX, mouseY); + } + + } } 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 2b68797..56e4067 100644 --- a/src/main/java/com/enderio/core/client/gui/GuiContainerBase.java +++ b/src/main/java/com/enderio/core/client/gui/GuiContainerBase.java @@ -19,11 +19,11 @@ import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import codechicken.nei.guihook.GuiContainerManager; -import codechicken.nei.guihook.IContainerObjectHandler; import codechicken.nei.VisiblityData; import codechicken.nei.api.INEIGuiHandler; import codechicken.nei.api.TaggedInventoryArea; +import codechicken.nei.guihook.GuiContainerManager; +import codechicken.nei.guihook.IContainerObjectHandler; import com.enderio.core.api.client.gui.IGuiOverlay; import com.enderio.core.api.client.gui.IGuiScreen; @@ -39,685 +39,685 @@ import com.google.common.collect.Lists; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Optional; -@Optional.InterfaceList({ @Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems"), @Optional.Interface(iface = "codechicken.nei.api.guihook.IContainerObjectHandler", modid = "NotEnoughItems") }) -public abstract class GuiContainerBase extends GuiContainer implements ToolTipRenderer, IGuiScreen, INEIGuiHandler, IContainerObjectHandler { +@Optional.InterfaceList({ @Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems"), + @Optional.Interface(iface = "codechicken.nei.api.guihook.IContainerObjectHandler", modid = "NotEnoughItems") }) +public abstract class GuiContainerBase extends GuiContainer + implements ToolTipRenderer, IGuiScreen, INEIGuiHandler, IContainerObjectHandler { - protected ToolTipManager ttMan = new ToolTipManager(); - protected List overlays = Lists.newArrayList(); - protected List textFields = Lists.newArrayList(); - protected List scrollbars = Lists.newArrayList(); - protected List drawingElements = Lists.newArrayList(); - protected GhostSlotHandler ghostSlotHandler = new GhostSlotHandler(); + protected ToolTipManager ttMan = new ToolTipManager(); + protected List overlays = Lists.newArrayList(); + protected List textFields = Lists.newArrayList(); + protected List scrollbars = Lists.newArrayList(); + protected List drawingElements = Lists.newArrayList(); + protected GhostSlotHandler ghostSlotHandler = new GhostSlotHandler(); - @Deprecated - protected List ghostSlots = ghostSlotHandler.getGhostSlots(); - @Deprecated - protected GhostSlot hoverGhostSlot; + @Deprecated + protected List ghostSlots = ghostSlotHandler.getGhostSlots(); + @Deprecated + protected GhostSlot hoverGhostSlot; - protected VScrollbar draggingScrollbar; + protected VScrollbar draggingScrollbar; - protected static boolean registeredNEIHandler; - protected final boolean isNEILoaded = Loader.isModLoaded("NotEnoughItems"); + protected static boolean registeredNEIHandler; + protected final boolean isNEILoaded = Loader.isModLoaded("NotEnoughItems"); - protected GuiContainerBase(Container par1Container) { - super(par1Container); - } - - @Override - public void initGui() { - super.initGui(); - fixupGuiPosition(); - for (IGuiOverlay overlay : overlays) { - overlay.init(this); - } - for (TextFieldEnder f : textFields) { - f.init(this); + protected GuiContainerBase(Container par1Container) { + super(par1Container); } - if (isNEILoaded && !registeredNEIHandler) { - GuiContainerManager.addObjectHandler(this); - registeredNEIHandler = true; - } - } - - protected void fixupGuiPosition() { - } - - @Override - protected void keyTyped(char c, int key) { - TextFieldEnder focused = null; - for (TextFieldEnder f : textFields) { - if (f.isFocused()) { - focused = f; - } - } - - // If esc is pressed - if (key == 1) { - // If there is a focused text field unfocus it - if (focused != null && key == 1) { - focused.setFocused(false); - focused = null; - return; - } 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') { - for (int i = 0; i < textFields.size(); i++) { - TextFieldEnder f = textFields.get(i); - if (f.isFocused()) { - textFields.get((i + 1) % textFields.size()).setFocused(true); - f.setFocused(false); - return; + @Override + public void initGui() { + super.initGui(); + fixupGuiPosition(); + for (IGuiOverlay overlay : overlays) { + overlay.init(this); + } + for (TextFieldEnder f : textFields) { + f.init(this); + } + + if (isNEILoaded && !registeredNEIHandler) { + GuiContainerManager.addObjectHandler(this); + registeredNEIHandler = true; } - } } - // If there is a focused text field, attempt to type into it - if (focused != null) { - String old = focused.getText(); - if (focused.textboxKeyTyped(c, key)) { - onTextFieldChanged(focused, old); - return; - } + protected void fixupGuiPosition() {} + + @Override + protected void keyTyped(char c, int key) { + TextFieldEnder focused = null; + for (TextFieldEnder f : textFields) { + if (f.isFocused()) { + focused = f; + } + } + + // If esc is pressed + if (key == 1) { + // If there is a focused text field unfocus it + if (focused != null && key == 1) { + focused.setFocused(false); + focused = null; + return; + } 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') { + for (int i = 0; i < textFields.size(); i++) { + TextFieldEnder f = textFields.get(i); + if (f.isFocused()) { + textFields.get((i + 1) % textFields.size()).setFocused(true); + f.setFocused(false); + return; + } + } + } + + // If there is a focused text field, attempt to type into it + if (focused != null) { + String old = focused.getText(); + 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()) { + 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()) { + this.mc.thePlayer.closeScreen(); + } + return; + } + + // If the key was not captured, let NEI do its thing + super.keyTyped(c, key); } - // More NEI behavior, f key focuses first text field - if (c == 'f' && focused == null && !textFields.isEmpty()) { - focused = textFields.get(0); - focused.setFocused(true); + protected final void setText(TextFieldEnder tf, String newText) { + String old = tf.getText(); + tf.setText(newText); + onTextFieldChanged(tf, old); } - // 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()) { - this.mc.thePlayer.closeScreen(); - } - return; + protected void onTextFieldChanged(TextFieldEnder tf, String old) { + } - // If the key was not captured, let NEI do its thing - super.keyTyped(c, key); - } - - protected final void setText(TextFieldEnder tf, String newText) { - String old = tf.getText(); - tf.setText(newText); - onTextFieldChanged(tf, old); - } - - protected void onTextFieldChanged(TextFieldEnder tf, String old) { - - } - - public boolean hideOverlays() { - for (IGuiOverlay overlay : overlays) { - if (overlay.isVisible()) { - overlay.setVisible(false); - return true; - } - } - return false; - } - - @Override - public void addToolTip(GuiToolTip toolTip) { - ttMan.addToolTip(toolTip); - } - - @Override - public void updateScreen() { - super.updateScreen(); - - if (!ForgeHooks.canInteractWith(mc.thePlayer, inventorySlots)) { - mc.thePlayer.closeScreen(); - } - - for (GuiTextField f : textFields) { - f.updateCursorCounter(); - } - } - - @Override - public void handleMouseInput() { - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - 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)) { - return; - } - } - int delta = Mouse.getEventDWheel(); - if (delta != 0) { - mouseWheel(x, y, delta); - } - super.handleMouseInput(); - } - - @Override - protected boolean func_146978_c(int p_146978_1_, int p_146978_2_, int p_146978_3_, int p_146978_4_, int p_146978_5_, int p_146978_6_) { - 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)) { + public boolean hideOverlays() { + for (IGuiOverlay overlay : overlays) { + if (overlay.isVisible()) { + overlay.setVisible(false); + return true; + } + } return false; - } } - return super.func_146978_c(p_146978_1_, p_146978_2_, p_146978_3_, p_146978_4_, p_146978_5_, p_146978_6_); - } - @Override - public List getGhostSlots() { - return ghostSlotHandler.getGhostSlots(); - } - - @Deprecated - protected void ghostSlotClicked(GhostSlot slot, int x, int y, int button) { - ghostSlotHandler.ghostSlotClicked(this, slot, x, y, button); - } - - @Override - protected void mouseClicked(int x, int y, int button) { - for (GuiTextField f : textFields) { - f.mouseClicked(x, y, button); + @Override + public void addToolTip(GuiToolTip toolTip) { + ttMan.addToolTip(toolTip); } - if (!scrollbars.isEmpty()) { - if (draggingScrollbar != null) { - draggingScrollbar.mouseClicked(x, y, button); - return; - } - for (VScrollbar vs : scrollbars) { - if (vs.mouseClicked(x, y, button)) { - draggingScrollbar = vs; - return; + + @Override + public void updateScreen() { + super.updateScreen(); + + if (!ForgeHooks.canInteractWith(mc.thePlayer, inventorySlots)) { + mc.thePlayer.closeScreen(); + } + + for (GuiTextField f : textFields) { + f.updateCursorCounter(); } - } } - if (!ghostSlotHandler.getGhostSlots().isEmpty()) { - GhostSlot slot = getGhostSlot(x, y); - if (slot != null) { - ghostSlotClicked(slot, x, y, button); + + @Override + public void handleMouseInput() { + int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + 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)) { + return; + } + } + int delta = Mouse.getEventDWheel(); + if (delta != 0) { + mouseWheel(x, y, delta); + } + super.handleMouseInput(); + } + + @Override + protected boolean func_146978_c(int p_146978_1_, int p_146978_2_, int p_146978_3_, int p_146978_4_, int p_146978_5_, + int p_146978_6_) { + 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)) { + return false; + } + } + return super.func_146978_c(p_146978_1_, p_146978_2_, p_146978_3_, p_146978_4_, p_146978_5_, p_146978_6_); + } + + @Override + public List getGhostSlots() { + return ghostSlotHandler.getGhostSlots(); + } + + @Deprecated + protected void ghostSlotClicked(GhostSlot slot, int x, int y, int button) { + ghostSlotHandler.ghostSlotClicked(this, slot, x, y, button); + } + + @Override + protected void mouseClicked(int x, int y, int button) { + for (GuiTextField f : textFields) { + f.mouseClicked(x, y, button); + } + if (!scrollbars.isEmpty()) { + if (draggingScrollbar != null) { + draggingScrollbar.mouseClicked(x, y, button); + return; + } + for (VScrollbar vs : scrollbars) { + if (vs.mouseClicked(x, y, button)) { + draggingScrollbar = vs; + return; + } + } + } + if (!ghostSlotHandler.getGhostSlots().isEmpty()) { + GhostSlot slot = getGhostSlot(x, y); + if (slot != null) { + ghostSlotClicked(slot, x, y, button); + super.mouseClicked(x, y, button); + return; + } + } + // Right click field clearing + if (button == 1) { + for (TextFieldEnder tf : textFields) { + if (tf.contains(x, y)) { + setText(tf, ""); + } + } + } + // Button events for non-left-clicks + if (button >= 1) { + for (Object obj : buttonList) { + if (obj instanceof IconButton) { + IconButton btn = (IconButton) obj; + if (btn.mousePressedButton(mc, x, y, button)) { + btn.func_146113_a(this.mc.getSoundHandler()); + actionPerformedButton(btn, button); + } + } + } + } super.mouseClicked(x, y, button); - return; - } } - // Right click field clearing - if (button == 1) { - for (TextFieldEnder tf : textFields) { - if (tf.contains(x, y)) { - setText(tf, ""); + + @Override + protected void mouseMovedOrUp(int x, int y, int button) { + if (draggingScrollbar != null) { + draggingScrollbar.mouseMovedOrUp(x, y, button); + draggingScrollbar = null; } - } + super.mouseMovedOrUp(x, y, button); } - // Button events for non-left-clicks - if (button >= 1) { - for (Object obj : buttonList) { - if (obj instanceof IconButton) { - IconButton btn = (IconButton) obj; - if (btn.mousePressedButton(mc, x, y, button)) { - btn.func_146113_a(this.mc.getSoundHandler()); - actionPerformedButton(btn, button); - } + + @Override + protected void mouseClickMove(int x, int y, int button, long time) { + if (draggingScrollbar != null) { + draggingScrollbar.mouseClickMove(x, y, button, time); + return; } - } + super.mouseClickMove(x, y, button, time); } - super.mouseClicked(x, y, button); - } - @Override - protected void mouseMovedOrUp(int x, int y, int button) { - if (draggingScrollbar != null) { - draggingScrollbar.mouseMovedOrUp(x, y, button); - draggingScrollbar = null; - } - super.mouseMovedOrUp(x, y, button); - } - - @Override - protected void mouseClickMove(int x, int y, int button, long time) { - if (draggingScrollbar != null) { - draggingScrollbar.mouseClickMove(x, y, button, time); - return; - } - super.mouseClickMove(x, y, button, time); - } - - protected void mouseWheel(int x, int y, int delta) { - if (!scrollbars.isEmpty()) { - for (VScrollbar vs : scrollbars) { - vs.mouseWheel(x, y, delta); - } - } - if (!ghostSlotHandler.getGhostSlots().isEmpty()) { - GhostSlot slot = getGhostSlot(x, y); - if (slot != null) { - ghostSlotClicked(slot, x, y, delta < 0 ? -1 : -2); - } - } - } - - protected void actionPerformedButton(IconButton btn, int mouseButton) { - actionPerformed(btn); - } - - public void addOverlay(IGuiOverlay overlay) { - overlays.add(overlay); - } - - public void removeOverlay(IGuiOverlay overlay) { - overlays.remove(overlay); - } - - public void addScrollbar(VScrollbar vs) { - scrollbars.add(vs); - vs.adjustPosition(); - } - - public void removeScrollbar(VScrollbar vs) { - scrollbars.remove(vs); - if (draggingScrollbar == vs) { - draggingScrollbar = null; - } - } - - public void addDrawingElement(IDrawingElement element) { - drawingElements.add(element); - GuiToolTip tooltip = element.getTooltip(); - if (tooltip != null) { - addToolTip(tooltip); - } - } - - public void removeDrawingElement(IDrawingElement element) { - drawingElements.remove(element); - GuiToolTip tooltip = element.getTooltip(); - if (tooltip != null) { - removeToolTip(tooltip); - } - } - - private int realMx, realMy; - - @Override - protected final void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - drawForegroundImpl(mouseX, mouseY); - - Timer t = RenderUtil.getTimer(); - - 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()) { - overlay.draw(realMx, realMy, t.renderPartialTicks); + protected void mouseWheel(int x, int y, int delta) { + if (!scrollbars.isEmpty()) { + for (VScrollbar vs : scrollbars) { + vs.mouseWheel(x, y, delta); + } } - } - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glPopMatrix(); - } - } - - @Override - protected void drawGuiContainerBackgroundLayer(float par1, int mouseX, int mouseY) { - for (IDrawingElement drawingElement : drawingElements) { - drawingElement.drawGuiContainerBackgroundLayer(par1, mouseX, mouseY); - } - for (GuiTextField f : textFields) { - f.drawTextBox(); - } - if (!scrollbars.isEmpty()) { - for (VScrollbar vs : scrollbars) { - vs.drawScrollbar(mouseX, mouseY); - } - } - if (!ghostSlotHandler.getGhostSlots().isEmpty()) { - drawGhostSlots(mouseX, mouseY); - } - } - - @Override - public void drawScreen(int par1, int par2, float par3) { - int mx = realMx = par1; - int my = realMy = par2; - - super.drawScreen(mx, my, par3); - - if (draggingScrollbar == null) { - ghostSlotHandler.drawGhostSlotToolTip(this, par1, par2); - ttMan.drawTooltips(this, par1, par2); - } - } - - // copied from super with hate - 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) { - font = stack.getItem().getFontRenderer(stack); - } - if (font == null) { - font = fontRendererObj; - } - itemRender.renderItemAndEffectIntoGUI(font, this.mc.getTextureManager(), stack, mouseX, mouseY); - itemRender.renderItemOverlayIntoGUI(font, this.mc.getTextureManager(), stack, mouseX, mouseY, str); - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - } - - protected void drawFakeItemsStart() { - zLevel = 0.0F; - itemRender.zLevel = -25.0F; - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableGUIStandardItemLighting(); - } - - protected void drawFakeItemStack(int x, int y, ItemStack stack) { - itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, stack, x, y); - } - - protected void drawFakeItemStackStdOverlay(int x, int y, ItemStack stack) { - itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, stack, x, y, null); - } - - protected void drawFakeItemHover(int x, int y) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glColorMask(true, true, true, false); - drawGradientRect(x, y, x + 16, y + 16, 0x80FFFFFF, 0x80FFFFFF); - GL11.glColorMask(true, true, true, true); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_LIGHTING); - } - - protected void drawFakeItemsEnd() { - GL11.glPopAttrib(); - itemRender.zLevel = 0.0F; - zLevel = 0.0F; - } - - @Override - public void renderToolTip(ItemStack p_146285_1_, int p_146285_2_, int p_146285_3_) { - if (!isNEILoaded) { - super.renderToolTip(p_146285_1_, p_146285_2_, p_146285_3_); - } - } - - @Deprecated - protected void drawGhostSlotTooltip(GhostSlot slot, int mouseX, int mouseY) { - ghostSlotHandler.drawGhostSlotTooltip(this, slot, mouseX, mouseY); - } - - /** - * Override this to allow GhostSlots to gray out with a custom background. Not - * needed if the slot has the default "Minecraft-gray" background---but it may - * be nicer to texture pack creators. - */ - protected String getGuiTexture() { - return null; - } - - @Deprecated - protected void drawGhostSlots(int mouseX, int mouseY) { - ghostSlotHandler.drawGhostSlots(this, mouseX, mouseY); - } - - @Deprecated - protected GhostSlot getGhostSlot(int mouseX, int mouseY) { - return ghostSlotHandler.getGhostSlot(this, mouseX, mouseY); - } - - @Override - public boolean removeToolTip(GuiToolTip toolTip) { - return ttMan.removeToolTip(toolTip); - } - - protected void drawForegroundImpl(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void drawHoveringText(List par1List, int par2, int par3, FontRenderer font) { - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); - copyOfdrawHoveringText(par1List, par2, par3, font); - GL11.glPopAttrib(); - GL11.glPopAttrib(); - } - - //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()) { - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - int k = 0; - Iterator iterator = par1List.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - int l = font.getStringWidth(s); - - if (l > k) { - k = l; + if (!ghostSlotHandler.getGhostSlots().isEmpty()) { + GhostSlot slot = getGhostSlot(x, y); + if (slot != null) { + ghostSlotClicked(slot, x, y, delta < 0 ? -1 : -2); + } } - } + } - int i1 = par2 + 12; - int j1 = par3 - 12; - int k1 = 8; + protected void actionPerformedButton(IconButton btn, int mouseButton) { + actionPerformed(btn); + } - if (par1List.size() > 1) { - k1 += 2 + (par1List.size() - 1) * 10; - } + public void addOverlay(IGuiOverlay overlay) { + overlays.add(overlay); + } - if (i1 + k > this.width) { - i1 -= 28 + k; - } + public void removeOverlay(IGuiOverlay overlay) { + overlays.remove(overlay); + } - if (j1 + k1 + 6 > this.height) { - j1 = this.height - k1 - 6; - } + public void addScrollbar(VScrollbar vs) { + scrollbars.add(vs); + vs.adjustPosition(); + } - this.zLevel = 300.0F; - //itemRenderer.zLevel = 300.0F; - int l1 = -267386864; - this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); - this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1); - this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); - this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1); - int i2 = 1347420415; - int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; - this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2); - this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2); - 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) { - String s1 = (String) par1List.get(k2); - font.drawStringWithShadow(s1, i1, j1, -1); - - if (k2 == 0) { - j1 += 2; + public void removeScrollbar(VScrollbar vs) { + scrollbars.remove(vs); + if (draggingScrollbar == vs) { + draggingScrollbar = null; } - - j1 += 10; - } - - this.zLevel = 0.0F; - //itemRenderer.zLevel = 0.0F; - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableStandardItemLighting(); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); } - } - public float getZlevel() { - return zLevel; - } - - @Override - public int getGuiLeft() { - return guiLeft; - } - - @Override - public int getGuiTop() { - return guiTop; - } - - @Override - public int getXSize() { - return xSize; - } - - @Override - public int getYSize() { - return ySize; - } - - public void setGuiLeft(int i) { - guiLeft = i; - } - - public void setGuiTop(int i) { - guiTop = i; - } - - public void setXSize(int i) { - xSize = i; - } - - public void setYSize(int i) { - ySize = i; - } - - @Override - public FontRenderer getFontRenderer() { - return Minecraft.getMinecraft().fontRenderer; - } - - @SuppressWarnings("unchecked") - @Override - public void addButton(GuiButton button) { - if (!buttonList.contains(button)) { - buttonList.add(button); + public void addDrawingElement(IDrawingElement element) { + drawingElements.add(element); + GuiToolTip tooltip = element.getTooltip(); + if (tooltip != null) { + addToolTip(tooltip); + } } - } - @Override - public void removeButton(GuiButton button) { - buttonList.remove(button); - } - - @Override - public int getOverlayOffsetX() { - return 0; - } - - @Override - public void doActionPerformed(GuiButton guiButton) { - actionPerformed(guiButton); - } - - public ItemStack getHoveredStack(int mouseX, int mouseY) { - GhostSlot slot = getGhostSlot(mouseX, mouseY); - if (slot != null) { - return slot.getStack(); + public void removeDrawingElement(IDrawingElement element) { + drawingElements.remove(element); + GuiToolTip tooltip = element.getTooltip(); + if (tooltip != null) { + removeToolTip(tooltip); + } } - return null; - } - // === NEI methods === + private int realMx, realMy; - // INEIGuiHandler + @Override + protected final void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + drawForegroundImpl(mouseX, mouseY); - @Override - @Optional.Method(modid = "NotEnoughItems") - public VisiblityData modifyVisiblity(GuiContainer gc, VisiblityData vd) { - return vd; - } + Timer t = RenderUtil.getTimer(); - @Override - @Optional.Method(modid = "NotEnoughItems") - public Iterable getItemSpawnSlots(GuiContainer gc, ItemStack is) { - return 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()) { + overlay.draw(realMx, realMy, t.renderPartialTicks); + } + } + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glPopMatrix(); + } + } - @Override - @Optional.Method(modid = "NotEnoughItems") - public List getInventoryAreas(GuiContainer gc) { - return Collections. emptyList(); - } + @Override + protected void drawGuiContainerBackgroundLayer(float par1, int mouseX, int mouseY) { + for (IDrawingElement drawingElement : drawingElements) { + drawingElement.drawGuiContainerBackgroundLayer(par1, mouseX, mouseY); + } + for (GuiTextField f : textFields) { + f.drawTextBox(); + } + if (!scrollbars.isEmpty()) { + for (VScrollbar vs : scrollbars) { + vs.drawScrollbar(mouseX, mouseY); + } + } + if (!ghostSlotHandler.getGhostSlots().isEmpty()) { + drawGhostSlots(mouseX, mouseY); + } + } - @Override - @Optional.Method(modid = "NotEnoughItems") - public boolean handleDragNDrop(GuiContainer gc, int x, int y, ItemStack is, int button) - { - if (gc instanceof GuiContainerBase && button == 0) { - GhostSlot slot = getGhostSlot(x,y); - if (slot != null) { - ghostSlotHandler.ghostSlotClickedPrimaryMouseButton(slot, is, slot.getStack()); - is.stackSize = 0; + @Override + public void drawScreen(int par1, int par2, float par3) { + int mx = realMx = par1; + int my = realMy = par2; + + super.drawScreen(mx, my, par3); + + if (draggingScrollbar == null) { + ghostSlotHandler.drawGhostSlotToolTip(this, par1, par2); + ttMan.drawTooltips(this, par1, par2); + } + } + + // copied from super with hate + 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) { + font = stack.getItem().getFontRenderer(stack); + } + if (font == null) { + font = fontRendererObj; + } + itemRender.renderItemAndEffectIntoGUI(font, this.mc.getTextureManager(), stack, mouseX, mouseY); + itemRender.renderItemOverlayIntoGUI(font, this.mc.getTextureManager(), stack, mouseX, mouseY, str); + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } + + protected void drawFakeItemsStart() { + zLevel = 0.0F; + itemRender.zLevel = -25.0F; + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableGUIStandardItemLighting(); + } + + protected void drawFakeItemStack(int x, int y, ItemStack stack) { + itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, stack, x, y); + } + + protected void drawFakeItemStackStdOverlay(int x, int y, ItemStack stack) { + itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, stack, x, y, null); + } + + protected void drawFakeItemHover(int x, int y) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glColorMask(true, true, true, false); + drawGradientRect(x, y, x + 16, y + 16, 0x80FFFFFF, 0x80FFFFFF); + GL11.glColorMask(true, true, true, true); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_LIGHTING); + } + + protected void drawFakeItemsEnd() { + GL11.glPopAttrib(); + itemRender.zLevel = 0.0F; + zLevel = 0.0F; + } + + @Override + public void renderToolTip(ItemStack p_146285_1_, int p_146285_2_, int p_146285_3_) { + if (!isNEILoaded) { + super.renderToolTip(p_146285_1_, p_146285_2_, p_146285_3_); + } + } + + @Deprecated + protected void drawGhostSlotTooltip(GhostSlot slot, int mouseX, int mouseY) { + ghostSlotHandler.drawGhostSlotTooltip(this, slot, mouseX, mouseY); + } + + /** + * Override this to allow GhostSlots to gray out with a custom background. Not needed if the slot has the default + * "Minecraft-gray" background---but it may be nicer to texture pack creators. + */ + protected String getGuiTexture() { + return null; + } + + @Deprecated + protected void drawGhostSlots(int mouseX, int mouseY) { + ghostSlotHandler.drawGhostSlots(this, mouseX, mouseY); + } + + @Deprecated + protected GhostSlot getGhostSlot(int mouseX, int mouseY) { + return ghostSlotHandler.getGhostSlot(this, mouseX, mouseY); + } + + @Override + public boolean removeToolTip(GuiToolTip toolTip) { + return ttMan.removeToolTip(toolTip); + } + + protected void drawForegroundImpl(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public void drawHoveringText(List par1List, int par2, int par3, FontRenderer font) { + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); + copyOfdrawHoveringText(par1List, par2, par3, font); + GL11.glPopAttrib(); + GL11.glPopAttrib(); + } + + // 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()) { + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + int k = 0; + Iterator iterator = par1List.iterator(); + + while (iterator.hasNext()) { + String s = (String) iterator.next(); + int l = font.getStringWidth(s); + + if (l > k) { + k = l; + } + } + + int i1 = par2 + 12; + int j1 = par3 - 12; + int k1 = 8; + + if (par1List.size() > 1) { + k1 += 2 + (par1List.size() - 1) * 10; + } + + if (i1 + k > this.width) { + i1 -= 28 + k; + } + + if (j1 + k1 + 6 > this.height) { + j1 = this.height - k1 - 6; + } + + this.zLevel = 300.0F; + // itemRenderer.zLevel = 300.0F; + int l1 = -267386864; + this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); + this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1); + int i2 = 1347420415; + int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; + this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2); + 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) { + String s1 = (String) par1List.get(k2); + font.drawStringWithShadow(s1, i1, j1, -1); + + if (k2 == 0) { + j1 += 2; + } + + j1 += 10; + } + + this.zLevel = 0.0F; + // itemRenderer.zLevel = 0.0F; + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } + } + + public float getZlevel() { + return zLevel; + } + + @Override + public int getGuiLeft() { + return guiLeft; + } + + @Override + public int getGuiTop() { + return guiTop; + } + + @Override + public int getXSize() { + return xSize; + } + + @Override + public int getYSize() { + return ySize; + } + + public void setGuiLeft(int i) { + guiLeft = i; + } + + public void setGuiTop(int i) { + guiTop = i; + } + + public void setXSize(int i) { + xSize = i; + } + + public void setYSize(int i) { + ySize = i; + } + + @Override + public FontRenderer getFontRenderer() { + return Minecraft.getMinecraft().fontRenderer; + } + + @SuppressWarnings("unchecked") + @Override + public void addButton(GuiButton button) { + if (!buttonList.contains(button)) { + buttonList.add(button); + } + } + + @Override + public void removeButton(GuiButton button) { + buttonList.remove(button); + } + + @Override + public int getOverlayOffsetX() { + return 0; + } + + @Override + public void doActionPerformed(GuiButton guiButton) { + actionPerformed(guiButton); + } + + public ItemStack getHoveredStack(int mouseX, int mouseY) { + GhostSlot slot = getGhostSlot(mouseX, mouseY); + if (slot != null) { + return slot.getStack(); + } + return null; + } + + // === NEI methods === + + // INEIGuiHandler + + @Override + @Optional.Method(modid = "NotEnoughItems") + public VisiblityData modifyVisiblity(GuiContainer gc, VisiblityData vd) { + return vd; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public Iterable getItemSpawnSlots(GuiContainer gc, ItemStack is) { + return null; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public List getInventoryAreas(GuiContainer gc) { + return Collections.emptyList(); + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public boolean handleDragNDrop(GuiContainer gc, int x, int y, ItemStack is, int button) { + if (gc instanceof GuiContainerBase && button == 0) { + GhostSlot slot = getGhostSlot(x, y); + if (slot != null) { + ghostSlotHandler.ghostSlotClickedPrimaryMouseButton(slot, is, slot.getStack()); + is.stackSize = 0; + return true; + } + } + return false; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public boolean hideItemPanelSlot(GuiContainer gc, int x, int y, int w, int h) { + return false; + } + + // IContainerObjectHandler + + @Override + @Optional.Method(modid = "NotEnoughItems") + public void guiTick(GuiContainer guiContainer) {} + + @Override + @Optional.Method(modid = "NotEnoughItems") + public void refresh(GuiContainer guiContainer) {} + + @Override + @Optional.Method(modid = "NotEnoughItems") + public void load(GuiContainer guiContainer) {} + + @Override + @Optional.Method(modid = "NotEnoughItems") + public ItemStack getStackUnderMouse(GuiContainer guiContainer, int mouseX, int mouseY) { + if (guiContainer instanceof GuiContainerBase) { + return ((GuiContainerBase) guiContainer).getHoveredStack(mouseX, mouseY); + } + return null; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public boolean objectUnderMouse(GuiContainer guiContainer, int mouseX, int mouseY) { + return false; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public boolean shouldShowTooltip(GuiContainer guiContainer) { return true; - } } - return false; - } - - @Override - @Optional.Method(modid = "NotEnoughItems") - public boolean hideItemPanelSlot(GuiContainer gc, int x, int y, int w, int h) { - return false; - } - - // IContainerObjectHandler - - @Override - @Optional.Method(modid = "NotEnoughItems") - public void guiTick(GuiContainer guiContainer) {} - - @Override - @Optional.Method(modid = "NotEnoughItems") - public void refresh(GuiContainer guiContainer) {} - - @Override - @Optional.Method(modid = "NotEnoughItems") - public void load(GuiContainer guiContainer) {} - - @Override - @Optional.Method(modid = "NotEnoughItems") - public ItemStack getStackUnderMouse(GuiContainer guiContainer, int mouseX, int mouseY) { - if (guiContainer instanceof GuiContainerBase) { - return ((GuiContainerBase) guiContainer).getHoveredStack(mouseX, mouseY); - } - return null; - } - - @Override - @Optional.Method(modid = "NotEnoughItems") - public boolean objectUnderMouse(GuiContainer guiContainer, int mouseX, int mouseY) { - return false; - } - - @Override - @Optional.Method(modid = "NotEnoughItems") - public boolean shouldShowTooltip(GuiContainer guiContainer) { - return true; - } } diff --git a/src/main/java/com/enderio/core/client/gui/GuiIconRenderer.java b/src/main/java/com/enderio/core/client/gui/GuiIconRenderer.java index 9d9b5e3..fc7132b 100644 --- a/src/main/java/com/enderio/core/client/gui/GuiIconRenderer.java +++ b/src/main/java/com/enderio/core/client/gui/GuiIconRenderer.java @@ -11,91 +11,91 @@ import com.enderio.core.client.render.RenderUtil; public class GuiIconRenderer extends Gui { - public static final int DEFAULT_WIDTH = 24; - public static final int HWIDTH = DEFAULT_WIDTH / 2; - public static final int DEFAULT_HEIGHT = 24; - public static final int HHEIGHT = DEFAULT_HEIGHT / 2; + public static final int DEFAULT_WIDTH = 24; + public static final int HWIDTH = DEFAULT_WIDTH / 2; + public static final int DEFAULT_HEIGHT = 24; + public static final int HHEIGHT = DEFAULT_HEIGHT / 2; - protected int hwidth = HWIDTH; - protected int hheight = HHEIGHT; - protected int width = DEFAULT_WIDTH; - protected int height = DEFAULT_HEIGHT; + protected int hwidth = HWIDTH; + protected int hheight = HHEIGHT; + protected int width = DEFAULT_WIDTH; + protected int height = DEFAULT_HEIGHT; - protected IIcon icon; - protected ResourceLocation texture; + protected IIcon icon; + protected ResourceLocation texture; - private int yPosition; - private int xPosition; + private int yPosition; + private int xPosition; - private float alpha = 1.0f; + private float alpha = 1.0f; - public GuiIconRenderer(int x, int y, int itemId, int itemMeta) { - xPosition = x; - yPosition = y; - icon = IconUtil.getIconForItem(itemId, itemMeta); - texture = RenderUtil.ITEM_TEX; - } + public GuiIconRenderer(int x, int y, int itemId, int itemMeta) { + xPosition = x; + yPosition = y; + icon = IconUtil.getIconForItem(itemId, itemMeta); + texture = RenderUtil.ITEM_TEX; + } - public GuiIconRenderer(int x, int y, IIcon icon, ResourceLocation texture) { - xPosition = x; - yPosition = y; - this.icon = icon; - this.texture = texture; - } + public GuiIconRenderer(int x, int y, IIcon icon, ResourceLocation texture) { + xPosition = x; + yPosition = y; + this.icon = icon; + this.texture = texture; + } - public void setSize(int width, int height) { - this.width = width; - this.height = height; - hwidth = width / 2; - hheight = height / 2; - } + public void setSize(int width, int height) { + this.width = width; + this.height = height; + hwidth = width / 2; + hheight = height / 2; + } - public int getWidth() { - return width; - } + public int getWidth() { + return width; + } - public int getHeight() { - return height; - } + public int getHeight() { + return height; + } - public IIcon getIcon() { - return icon; - } + public IIcon getIcon() { + return icon; + } - public float getAlpha() { - return alpha; - } + public float getAlpha() { + return alpha; + } - public void setAlpha(float alpha) { - this.alpha = alpha; - } + public void setAlpha(float alpha) { + this.alpha = alpha; + } - public void setIcon(IIcon icon) { - this.icon = icon; - } + public void setIcon(IIcon icon) { + this.icon = icon; + } - public ResourceLocation getTexture() { - return texture; - } + public ResourceLocation getTexture() { + return texture; + } - public void setTexture(ResourceLocation textureName) { - this.texture = textureName; - } + public void setTexture(ResourceLocation textureName) { + this.texture = textureName; + } - public void draw() { + public void draw() { - GL11.glColor4f(1.0F, 1.0F, 1.0F, alpha); + GL11.glColor4f(1.0F, 1.0F, 1.0F, alpha); - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - RenderUtil.bindTexture(texture); - drawTexturedModelRectFromIcon(xPosition, yPosition, icon, width, height); + RenderUtil.bindTexture(texture); + drawTexturedModelRectFromIcon(xPosition, yPosition, icon, width, height); - GL11.glPopAttrib(); + GL11.glPopAttrib(); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - } + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } } 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 d16bb86..df4f044 100644 --- a/src/main/java/com/enderio/core/client/gui/GuiScreenBase.java +++ b/src/main/java/com/enderio/core/client/gui/GuiScreenBase.java @@ -19,220 +19,218 @@ import com.enderio.core.client.gui.widget.GuiToolTip; public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer, IGuiScreen { - protected ToolTipManager ttMan = new ToolTipManager(); + protected ToolTipManager ttMan = new ToolTipManager(); - /** The X size of the inventory window in pixels. */ - protected int xSize = 176; + /** The X size of the inventory window in pixels. */ + protected int xSize = 176; - /** The Y size of the inventory window in pixels. */ - protected int ySize = 166; + /** The Y size of the inventory window in pixels. */ + protected int ySize = 166; - /** - * Starting X position for the Gui. Inconsistent use for Gui backgrounds. - */ - protected int guiLeft; + /** + * Starting X position for the Gui. Inconsistent use for Gui backgrounds. + */ + protected int guiLeft; - /** - * Starting Y position for the Gui. Inconsistent use for Gui backgrounds. - */ - protected int guiTop; + /** + * Starting Y position for the Gui. Inconsistent use for Gui backgrounds. + */ + protected int guiTop; - protected boolean drawButtons = true; + protected boolean drawButtons = true; - protected GuiScreenBase() { - } + protected GuiScreenBase() {} - protected GuiScreenBase(int xSize, int ySize) { - this.xSize = xSize; - this.ySize = ySize; - } - - @Override - public void addToolTip(GuiToolTip toolTip) { - ttMan.addToolTip(toolTip); - } - - @Override - public boolean removeToolTip(GuiToolTip toolTip) { - return ttMan.removeToolTip(toolTip); - } - - @Override - public void initGui() { - super.initGui(); - guiLeft = (this.width - this.xSize) / 2; - guiTop = (this.height - this.ySize) / 2; - } - - @Override - public void drawScreen(int par1, int par2, float par3) { - drawDefaultBackground(); - - drawBackgroundLayer(par3, par1, par2); - - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - if (drawButtons) { - RenderHelper.enableGUIStandardItemLighting(); - super.drawScreen(par1, par2, par3); + protected GuiScreenBase(int xSize, int ySize) { + this.xSize = xSize; + this.ySize = ySize; } - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - GL11.glPushMatrix(); - GL11.glTranslatef(guiLeft, guiTop, 0.0F); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + @Override + public void addToolTip(GuiToolTip toolTip) { + ttMan.addToolTip(toolTip); + } - GL11.glDisable(GL11.GL_LIGHTING); - drawForegroundLayer(par1, par2); - GL11.glEnable(GL11.GL_LIGHTING); + @Override + public boolean removeToolTip(GuiToolTip toolTip) { + return ttMan.removeToolTip(toolTip); + } - GL11.glPopMatrix(); + @Override + public void initGui() { + super.initGui(); + guiLeft = (this.width - this.xSize) / 2; + guiTop = (this.height - this.ySize) / 2; + } - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableStandardItemLighting(); - } + @Override + public void drawScreen(int par1, int par2, float par3) { + drawDefaultBackground(); - protected abstract void drawBackgroundLayer(float par3, int par1, int par2); + drawBackgroundLayer(par3, par1, par2); - protected final void drawForegroundLayer(int mouseX, int mouseY) { - drawForegroundImpl(mouseX, mouseY); - ttMan.drawTooltips(this, mouseX, mouseY); - } - - protected void drawForegroundImpl(int mouseX, int mouseY) { - } - - @Override - public void drawHoveringText(List par1List, int par2, int par3, FontRenderer font) { - - if (!par1List.isEmpty()) { - - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); - - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - int k = 0; - Iterator iterator = par1List.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - int l = font.getStringWidth(s); - - if (l > k) { - k = l; + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + if (drawButtons) { + RenderHelper.enableGUIStandardItemLighting(); + super.drawScreen(par1, par2, par3); } - } + GL11.glEnable(GL12.GL_RESCALE_NORMAL); - int i1 = par2 + 12; - int j1 = par3 - 12; - int k1 = 8; + GL11.glPushMatrix(); + GL11.glTranslatef(guiLeft, guiTop, 0.0F); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - if (par1List.size() > 1) { - k1 += 2 + (par1List.size() - 1) * 10; - } + GL11.glDisable(GL11.GL_LIGHTING); + drawForegroundLayer(par1, par2); + GL11.glEnable(GL11.GL_LIGHTING); - if (i1 + k > this.width) { - i1 -= 28 + k; - } + GL11.glPopMatrix(); - if (j1 + k1 + 6 > this.height) { - j1 = this.height - k1 - 6; - } + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + } - this.zLevel = 300.0F; + protected abstract void drawBackgroundLayer(float par3, int par1, int par2); - int l1 = -267386864; - this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); - this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1); - this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); - this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1); - int i2 = 1347420415; - int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; - this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2); - this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2); - 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); + protected final void drawForegroundLayer(int mouseX, int mouseY) { + drawForegroundImpl(mouseX, mouseY); + ttMan.drawTooltips(this, mouseX, mouseY); + } - for (int k2 = 0; k2 < par1List.size(); ++k2) { - String s1 = (String) par1List.get(k2); - font.drawStringWithShadow(s1, i1, j1, -1); + protected void drawForegroundImpl(int mouseX, int mouseY) {} + + @Override + public void drawHoveringText(List par1List, int par2, int par3, FontRenderer font) { + + if (!par1List.isEmpty()) { + + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); + + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + int k = 0; + Iterator iterator = par1List.iterator(); + + while (iterator.hasNext()) { + String s = (String) iterator.next(); + int l = font.getStringWidth(s); + + if (l > k) { + k = l; + } + } + + int i1 = par2 + 12; + int j1 = par3 - 12; + int k1 = 8; + + if (par1List.size() > 1) { + k1 += 2 + (par1List.size() - 1) * 10; + } + + if (i1 + k > this.width) { + i1 -= 28 + k; + } + + if (j1 + k1 + 6 > this.height) { + j1 = this.height - k1 - 6; + } + + this.zLevel = 300.0F; + + int l1 = -267386864; + this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); + this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1); + int i2 = 1347420415; + int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; + this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2); + 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) { + String s1 = (String) par1List.get(k2); + font.drawStringWithShadow(s1, i1, j1, -1); + + if (k2 == 0) { + j1 += 2; + } + + j1 += 10; + } + + this.zLevel = 0.0F; + + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + + GL11.glPopAttrib(); + GL11.glPopAttrib(); - if (k2 == 0) { - j1 += 2; } - - j1 += 10; - } - - this.zLevel = 0.0F; - - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableStandardItemLighting(); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - - GL11.glPopAttrib(); - GL11.glPopAttrib(); - } - } - @Override - public int getGuiLeft() { - return guiLeft; - } - - @Override - public int getGuiTop() { - return guiTop; - } - - @Override - public int getXSize() { - return xSize; - } - - @Override - public int getYSize() { - return xSize; - } - - @Override - public FontRenderer getFontRenderer() { - return Minecraft.getMinecraft().fontRenderer; - } - - @Override - public void addButton(GuiButton button) { - if (!buttonList.contains(button)) { - buttonList.add(button); + @Override + public int getGuiLeft() { + return guiLeft; } - } - @Override - public void removeButton(GuiButton button) { - buttonList.remove(button); - } + @Override + public int getGuiTop() { + return guiTop; + } - @Override - public void doActionPerformed(GuiButton guiButton) { - actionPerformed(guiButton); - } + @Override + public int getXSize() { + return xSize; + } - @Override - public int getOverlayOffsetX() { - return 0; - } + @Override + public int getYSize() { + return xSize; + } - @Override - public List getGhostSlots() { - return null; - } + @Override + public FontRenderer getFontRenderer() { + return Minecraft.getMinecraft().fontRenderer; + } + + @Override + public void addButton(GuiButton button) { + if (!buttonList.contains(button)) { + buttonList.add(button); + } + } + + @Override + public void removeButton(GuiButton button) { + buttonList.remove(button); + } + + @Override + public void doActionPerformed(GuiButton guiButton) { + actionPerformed(guiButton); + } + + @Override + public int getOverlayOffsetX() { + return 0; + } + + @Override + public List getGhostSlots() { + return null; + } } 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 a9935d2..1226ad2 100644 --- a/src/main/java/com/enderio/core/client/gui/ToolTipManager.java +++ b/src/main/java/com/enderio/core/client/gui/ToolTipManager.java @@ -10,67 +10,68 @@ import com.enderio.core.client.gui.widget.GuiToolTip; public class ToolTipManager { - public static interface ToolTipRenderer { - int getGuiLeft(); + public static interface ToolTipRenderer { - int getGuiTop(); + int getGuiLeft(); - int getXSize(); + int getGuiTop(); - FontRenderer getFontRenderer(); + int getXSize(); - void drawHoveringText(List par1List, int par2, int par3, FontRenderer font); - } + FontRenderer getFontRenderer(); - private List toolTips = new ArrayList(); - - public void addToolTip(GuiToolTip toolTip) { - if (!toolTips.contains(toolTip)) { - toolTips.add(toolTip); - } - } - - public boolean removeToolTip(GuiToolTip toolTip) { - return toolTips.remove(toolTip); - } - - 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()) { - drawTooltip(toolTip, mouseX, mouseY, renderer); - } - } - } - - protected void drawTooltip(GuiToolTip toolTip, int mouseX, int mouseY, ToolTipRenderer renderer) { - List list = toolTip.getToolTipText(); - if (list == null) { - return; + void drawHoveringText(List par1List, int par2, int par3, FontRenderer font); } - List formatted = new ArrayList(list.size()); - for (int i = 0; i < list.size(); i++) { - if (i == 0) { - formatted.add("\u00a7f" + list.get(i)); - } else { - formatted.add("\u00a77" + list.get(i)); - } - } + private List toolTips = new ArrayList(); - 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) { - maxWidth = w; + public void addToolTip(GuiToolTip toolTip) { + if (!toolTips.contains(toolTip)) { + toolTips.add(toolTip); } - } - mouseX -= (maxWidth + 18); } - renderer.drawHoveringText(formatted, mouseX, mouseY, renderer.getFontRenderer()); - } + + public boolean removeToolTip(GuiToolTip toolTip) { + return toolTips.remove(toolTip); + } + + 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()) { + drawTooltip(toolTip, mouseX, mouseY, renderer); + } + } + } + + protected void drawTooltip(GuiToolTip toolTip, int mouseX, int mouseY, ToolTipRenderer renderer) { + List list = toolTip.getToolTipText(); + if (list == null) { + return; + } + + List formatted = new ArrayList(list.size()); + for (int i = 0; i < list.size(); i++) { + if (i == 0) { + formatted.add("\u00a7f" + list.get(i)); + } else { + formatted.add("\u00a77" + list.get(i)); + } + } + + 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) { + maxWidth = w; + } + } + mouseX -= (maxWidth + 18); + } + renderer.drawHoveringText(formatted, mouseX, mouseY, renderer.getFontRenderer()); + } } 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 3f9b8ef..bb9063b 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 @@ -15,35 +15,37 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; @Handler 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); - } - } + private static Field _mainMenu, _parentScreen; - @SubscribeEvent - public void onGuiOpen(GuiOpenEvent event) { - if (event.gui == null) { - return; + 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); + } } - try { - 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))); - } - } catch (Exception e) { - Throwables.propagate(e); + + @SubscribeEvent + public void onGuiOpen(GuiOpenEvent event) { + if (event.gui == null) { + return; + } + try { + 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))); + } + } catch (Exception e) { + Throwables.propagate(e); + } } - } } diff --git a/src/main/java/com/enderio/core/client/gui/bettermodlist/GuiEnhancedModList.java b/src/main/java/com/enderio/core/client/gui/bettermodlist/GuiEnhancedModList.java index 555de0d..a342414 100644 --- a/src/main/java/com/enderio/core/client/gui/bettermodlist/GuiEnhancedModList.java +++ b/src/main/java/com/enderio/core/client/gui/bettermodlist/GuiEnhancedModList.java @@ -24,390 +24,404 @@ import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModContainer; public class GuiEnhancedModList extends GuiModList { - private enum SortType { - NORMAL(24), - A_TO_Z(25), - Z_TO_A(26); - private final int buttonID; - private final ModComparator comparator; + private enum SortType { - private SortType(int buttonID) { - this.buttonID = buttonID; - this.comparator = new ModComparator(this); - } + NORMAL(24), + A_TO_Z(25), + Z_TO_A(26); - public static SortType getTypeForButton(GuiButton button) { - for (SortType t : values()) { - if (t.buttonID == button.id) { - return t; + private final int buttonID; + private final ModComparator comparator; + + private SortType(int buttonID) { + this.buttonID = buttonID; + this.comparator = new ModComparator(this); + } + + public static SortType getTypeForButton(GuiButton button) { + for (SortType t : values()) { + if (t.buttonID == button.id) { + return t; + } + } + return null; } - } - return null; } - } - private static class ModComparator implements Comparator { - private SortType type; + private static class ModComparator implements Comparator { - private ModComparator(SortType type) { - this.type = type; + private SortType type; + + private ModComparator(SortType type) { + this.type = type; + } + + @Override + public int compare(ModContainer o1, ModContainer o2) { + String name1 = StringUtils.stripControlCodes(o1.getName()).toLowerCase(Locale.US); + String name2 = StringUtils.stripControlCodes(o2.getName()).toLowerCase(Locale.US); + switch (type) { + case A_TO_Z: + return name1.compareTo(name2); + case Z_TO_A: + return name2.compareTo(name1); + default: + return 0; + } + } + } + + private class InfoButton extends GuiButton { + + public InfoButton() { + super(30, GuiEnhancedModList.this.width - 22, 2, 20, 20, "?"); + } + + @Override + public void drawButton(Minecraft p_146112_1_, int p_146112_2_, int p_146112_3_) { + if (this.field_146123_n) { + ModContainer sel = GuiEnhancedModList.this.getSelectedMod(); + if (sel != null && sel.getName().equals(EnderCore.NAME)) { + this.displayString = EnderCore.lang.localize("gui.modlistinfo2"); + } else { + this.displayString = EnderCore.lang.localize("gui.modlistinfo1"); + } + + this.width = p_146112_1_.fontRenderer.getStringWidth(this.displayString) + 10; + if (this.width % 2 != 0) // Fixes the button shifting to the left + { + this.width++; + } + + this.xPosition = GuiEnhancedModList.this.width - this.width - 2; + } else { + this.displayString = "?"; + this.width = 20; + this.xPosition = GuiEnhancedModList.this.width - this.width - 2; + } + + super.drawButton(p_146112_1_, p_146112_2_, p_146112_3_); + } + } + + private static Field _mods, _selected, _selectedMod; + private static Field _modList, _modListRight, _modListBottom, _modListMods, _listWidth, _scrollDistance; + static { + try { + _mods = GuiModList.class.getDeclaredField("mods"); + _mods.setAccessible(true); + _selected = GuiModList.class.getDeclaredField("selected"); + _selected.setAccessible(true); + _selectedMod = GuiModList.class.getDeclaredField("selectedMod"); + _selectedMod.setAccessible(true); + _modList = GuiModList.class.getDeclaredField("modList"); + _modList.setAccessible(true); + _modListRight = GuiScrollingList.class.getDeclaredField("right"); + _modListRight.setAccessible(true); + _modListBottom = GuiScrollingList.class.getDeclaredField("bottom"); + _modListBottom.setAccessible(true); + _modListMods = GuiSlotModList.class.getDeclaredField("mods"); + _modListMods.setAccessible(true); + _listWidth = GuiModList.class.getDeclaredField("listWidth"); + _listWidth.setAccessible(true); + _scrollDistance = GuiScrollingList.class.getDeclaredField("scrollDistance"); + _scrollDistance.setAccessible(true); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private int buttonMargin = 1; + private int numButtons = SortType.values().length; + + private String lastFilterText = ""; + + private GuiTextField search; + private boolean sorted = false; + private SortType sortType = SortType.values()[ConfigHandler.defaultModSort]; + + public GuiEnhancedModList(GuiScreen mainMenu) { + super(mainMenu); + } + + @SuppressWarnings("unchecked") + @Override + public void initGui() { + // Super code reinitializes the mod list every time, need to preserve scroll state + float scroll = 0; + if (getGuiModList() != null) { + scroll = getGuiModListScroll(); + } + + super.initGui(); + + // Let's move some buttons + for (GuiButton button : (List) buttonList) { + if (button.id == 6) // Done button + { + int min = getGuiModListRight(); + int max = width; + button.xPosition = ((min + max) / 2) - (button.width / 2); + button.yPosition += 10; + } else if (button.id == 20 || button.id == 21) // Config/Disable + { + button.yPosition += 10; + } + } + + setGuiModListBottom(getGuiModListBottom() - 25); + if (search == null) { + search = new GuiTextField(mc.fontRenderer, 12, getGuiModListBottom() + 17, getListWidth() - 4, 14); + search.setFocused(true); + search.setCanLoseFocus(true); + } + + int width = (getListWidth() / numButtons); + int x = 10, y = 10; + GuiButton normalSort = new GuiButton( + SortType.NORMAL.buttonID, + x, + y, + width - buttonMargin, + 20, + EnderCore.lang.localize("gui.normal")); + normalSort.enabled = false; + buttonList.add(normalSort); + x += width + buttonMargin; + buttonList.add(new GuiButton(SortType.A_TO_Z.buttonID, x, y, width - buttonMargin, 20, "A-Z")); + x += width + buttonMargin; + buttonList.add(new GuiButton(SortType.Z_TO_A.buttonID, x, y, width - buttonMargin, 20, "Z-A")); + + buttonList.add(new InfoButton()); + + reloadMods(); + disableButton(); + + setGuiModListScroll(scroll); } @Override - public int compare(ModContainer o1, ModContainer o2) { - String name1 = StringUtils.stripControlCodes(o1.getName()).toLowerCase(Locale.US); - String name2 = StringUtils.stripControlCodes(o2.getName()).toLowerCase(Locale.US); - switch (type) { - case A_TO_Z: - return name1.compareTo(name2); - case Z_TO_A: - return name2.compareTo(name1); - default: - return 0; - } - } - } - - private class InfoButton extends GuiButton { - public InfoButton() { - super(30, GuiEnhancedModList.this.width - 22, 2, 20, 20, "?"); + @SuppressWarnings("unchecked") + public int drawLine(String line, int offset, int shifty) { + String before = line.substring(0, line.indexOf(':') + 2); + int followingLineOffset = this.fontRendererObj.getStringWidth(before); + String[] manualSplit = line.split("\n"); + List split = Lists.newArrayList(); + for (String s : manualSplit) { + split.addAll(this.fontRendererObj.listFormattedStringToWidth(s, width - offset)); + } + for (int i = 0; i < split.size(); i++) { + this.fontRendererObj.drawString(split.get(i), offset + (i > 0 ? followingLineOffset : 0), shifty, 0xd7edea); + shifty += 10; + } + if (split.size() > 1) { + shifty += 10; + } + return shifty; } @Override - public void drawButton(Minecraft p_146112_1_, int p_146112_2_, int p_146112_3_) { - if (this.field_146123_n) { - ModContainer sel = GuiEnhancedModList.this.getSelectedMod(); - if (sel != null && sel.getName().equals(EnderCore.NAME)) { - this.displayString = EnderCore.lang.localize("gui.modlistinfo2"); + protected void mouseClicked(int x, int y, int button) { + super.mouseClicked(x, y, button); + search.mouseClicked(x, y, button); + if (button == 1 && x >= search.xPosition + && x < search.xPosition + search.width + && y >= search.yPosition + && y < search.yPosition + search.height) { + search.setText(""); + } + } + + @Override + protected void keyTyped(char p_73869_1_, int p_73869_2_) { + super.keyTyped(p_73869_1_, p_73869_2_); + search.textboxKeyTyped(p_73869_1_, p_73869_2_); + } + + @Override + public void updateScreen() { + super.updateScreen(); + search.updateCursorCounter(); + + if (!search.getText().equals(lastFilterText)) { + reloadMods(); + sorted = false; + } + + if (!sorted) { + reloadMods(); + Collections.sort(getMods(), sortType.comparator); + setMods(); + sorted = true; + } + } + + private void reloadMods() { + List mods = getMods(); + mods.clear(); + for (ModContainer m : Loader.instance().getActiveModList()) { + if (m.getName().toLowerCase(Locale.US).contains(search.getText().toLowerCase(Locale.US)) + && m.getMetadata().parentMod == null) { + mods.add(m); + } + } + setMods(); + lastFilterText = search.getText(); + } + + @Override + public void drawScreen(int p_571_1_, int p_571_2_, float p_571_3_) { + super.drawScreen(p_571_1_, p_571_2_, p_571_3_); + + String text = EnderCore.lang.localize("gui.search"); + int x = ((10 + getGuiModListRight()) / 2) - (mc.fontRenderer.getStringWidth(text) / 2); + mc.fontRenderer.drawString(text, x, getGuiModListBottom() + 5, 0xFFFFFF); + search.drawTextBox(); + } + + @Override + protected void actionPerformed(GuiButton button) { + super.actionPerformed(button); + + if (button.id == 30) { + search.setText(""); + reloadMods(); + for (ModContainer m : getMods()) { + if (m.getName().equals(EnderCore.NAME)) { + setSelectedMod(m); + setMods(); + } + } + } + + SortType type = SortType.getTypeForButton(button); + + if (type == null) { + return; } else { - this.displayString = EnderCore.lang.localize("gui.modlistinfo1"); + sorted = false; + sortType = type; + disableButton(); } - this.width = p_146112_1_.fontRenderer.getStringWidth(this.displayString) + 10; - if (this.width % 2 != 0) // Fixes the button shifting to the left - { - this.width++; + setMods(); + } + + @SuppressWarnings("unchecked") + private void disableButton() { + for (GuiButton b : (List) buttonList) { + if (SortType.getTypeForButton(b) != null) { + b.enabled = true; + } + if (b.id == sortType.buttonID) { + b.enabled = false; + } } - - this.xPosition = GuiEnhancedModList.this.width - this.width - 2; - } else { - this.displayString = "?"; - this.width = 20; - this.xPosition = GuiEnhancedModList.this.width - this.width - 2; - } - - super.drawButton(p_146112_1_, p_146112_2_, p_146112_3_); - } - } - - private static Field _mods, _selected, _selectedMod; - private static Field _modList, _modListRight, _modListBottom, _modListMods, _listWidth, _scrollDistance; - static { - try { - _mods = GuiModList.class.getDeclaredField("mods"); - _mods.setAccessible(true); - _selected = GuiModList.class.getDeclaredField("selected"); - _selected.setAccessible(true); - _selectedMod = GuiModList.class.getDeclaredField("selectedMod"); - _selectedMod.setAccessible(true); - _modList = GuiModList.class.getDeclaredField("modList"); - _modList.setAccessible(true); - _modListRight = GuiScrollingList.class.getDeclaredField("right"); - _modListRight.setAccessible(true); - _modListBottom = GuiScrollingList.class.getDeclaredField("bottom"); - _modListBottom.setAccessible(true); - _modListMods = GuiSlotModList.class.getDeclaredField("mods"); - _modListMods.setAccessible(true); - _listWidth = GuiModList.class.getDeclaredField("listWidth"); - _listWidth.setAccessible(true); - _scrollDistance = GuiScrollingList.class.getDeclaredField("scrollDistance"); - _scrollDistance.setAccessible(true); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private int buttonMargin = 1; - private int numButtons = SortType.values().length; - - private String lastFilterText = ""; - - private GuiTextField search; - private boolean sorted = false; - private SortType sortType = SortType.values()[ConfigHandler.defaultModSort]; - - public GuiEnhancedModList(GuiScreen mainMenu) { - super(mainMenu); - } - - @SuppressWarnings("unchecked") - @Override - public void initGui() { - // Super code reinitializes the mod list every time, need to preserve scroll state - float scroll = 0; - if (getGuiModList() != null) { - scroll = getGuiModListScroll(); } - super.initGui(); + private void setMods() { + List mods = getMods(); - // Let's move some buttons - for (GuiButton button : (List) buttonList) { - if (button.id == 6) // Done button - { - int min = getGuiModListRight(); - int max = width; - button.xPosition = ((min + max) / 2) - (button.width / 2); - button.yPosition += 10; - } else if (button.id == 20 || button.id == 21) // Config/Disable - { - button.yPosition += 10; - } - } + ModContainer sel = getSelectedMod(); + boolean found = false; + try { + for (int i = 0; !found && i < mods.size(); i++) { + if (sel == mods.get(i)) { + _selected.setInt(this, i); + found = true; + } + } + if (!found) { + _selected.setInt(this, -1); + _selectedMod.set(this, null); + } - setGuiModListBottom(getGuiModListBottom() - 25); - if (search == null) { - search = new GuiTextField(mc.fontRenderer, 12, getGuiModListBottom() + 17, getListWidth() - 4, 14); - search.setFocused(true); - search.setCanLoseFocus(true); - } - - int width = (getListWidth() / numButtons); - int x = 10, y = 10; - GuiButton normalSort = new GuiButton(SortType.NORMAL.buttonID, x, y, width - buttonMargin, 20, EnderCore.lang.localize("gui.normal")); - normalSort.enabled = false; - buttonList.add(normalSort); - x += width + buttonMargin; - buttonList.add(new GuiButton(SortType.A_TO_Z.buttonID, x, y, width - buttonMargin, 20, "A-Z")); - x += width + buttonMargin; - buttonList.add(new GuiButton(SortType.Z_TO_A.buttonID, x, y, width - buttonMargin, 20, "Z-A")); - - buttonList.add(new InfoButton()); - - reloadMods(); - disableButton(); - - setGuiModListScroll(scroll); - } - - @Override - @SuppressWarnings("unchecked") - public int drawLine(String line, int offset, int shifty) { - String before = line.substring(0, line.indexOf(':') + 2); - int followingLineOffset = this.fontRendererObj.getStringWidth(before); - String[] manualSplit = line.split("\n"); - List split = Lists.newArrayList(); - for (String s : manualSplit) { - split.addAll(this.fontRendererObj.listFormattedStringToWidth(s, width - offset)); - } - for (int i = 0; i < split.size(); i++) { - this.fontRendererObj.drawString(split.get(i), offset + (i > 0 ? followingLineOffset : 0), shifty, 0xd7edea); - shifty += 10; - } - if (split.size() > 1) { - shifty += 10; - } - return shifty; - } - - @Override - protected void mouseClicked(int x, int y, int button) { - super.mouseClicked(x, y, button); - search.mouseClicked(x, y, button); - if (button == 1 && x >= search.xPosition && x < search.xPosition + search.width && y >= search.yPosition && y < search.yPosition + search.height) { - search.setText(""); - } - } - - @Override - protected void keyTyped(char p_73869_1_, int p_73869_2_) { - super.keyTyped(p_73869_1_, p_73869_2_); - search.textboxKeyTyped(p_73869_1_, p_73869_2_); - } - - @Override - public void updateScreen() { - super.updateScreen(); - search.updateCursorCounter(); - - if (!search.getText().equals(lastFilterText)) { - reloadMods(); - sorted = false; - } - - if (!sorted) { - reloadMods(); - Collections.sort(getMods(), sortType.comparator); - setMods(); - sorted = true; - } - } - - private void reloadMods() { - List mods = getMods(); - mods.clear(); - for (ModContainer m : Loader.instance().getActiveModList()) { - if (m.getName().toLowerCase(Locale.US).contains(search.getText().toLowerCase(Locale.US)) && m.getMetadata().parentMod == null) { - mods.add(m); - } - } - setMods(); - lastFilterText = search.getText(); - } - - @Override - public void drawScreen(int p_571_1_, int p_571_2_, float p_571_3_) { - super.drawScreen(p_571_1_, p_571_2_, p_571_3_); - - String text = EnderCore.lang.localize("gui.search"); - int x = ((10 + getGuiModListRight()) / 2) - (mc.fontRenderer.getStringWidth(text) / 2); - mc.fontRenderer.drawString(text, x, getGuiModListBottom() + 5, 0xFFFFFF); - search.drawTextBox(); - } - - @Override - protected void actionPerformed(GuiButton button) { - super.actionPerformed(button); - - if (button.id == 30) { - search.setText(""); - reloadMods(); - for (ModContainer m : getMods()) { - if (m.getName().equals(EnderCore.NAME)) { - setSelectedMod(m); - setMods(); + _mods.set(this, getMods()); + sorted = false; + } catch (Exception e) { + Throwables.propagate(e); } - } } - SortType type = SortType.getTypeForButton(button); - - if (type == null) { - return; - } else { - sorted = false; - sortType = type; - disableButton(); - } - - setMods(); - } - - @SuppressWarnings("unchecked") - private void disableButton() { - for (GuiButton b : (List) buttonList) { - if (SortType.getTypeForButton(b) != null) { - b.enabled = true; - } - if (b.id == sortType.buttonID) { - b.enabled = false; - } - } - } - - private void setMods() { - List mods = getMods(); - - ModContainer sel = getSelectedMod(); - boolean found = false; - try { - for (int i = 0; !found && i < mods.size(); i++) { - if (sel == mods.get(i)) { - _selected.setInt(this, i); - found = true; + private GuiSlotModList getGuiModList() { + try { + return (GuiSlotModList) _modList.get(this); + } catch (Exception e) { + throw Throwables.propagate(e); } - } - if (!found) { - _selected.setInt(this, -1); - _selectedMod.set(this, null); - } - - _mods.set(this, getMods()); - sorted = false; - } catch (Exception e) { - Throwables.propagate(e); } - } - private GuiSlotModList getGuiModList() { - try { - return (GuiSlotModList) _modList.get(this); - } catch (Exception e) { - throw Throwables.propagate(e); + private int getGuiModListRight() { + try { + return _modListRight.getInt(getGuiModList()); + } catch (Exception e) { + throw Throwables.propagate(e); + } } - } - private int getGuiModListRight() { - try { - return _modListRight.getInt(getGuiModList()); - } catch (Exception e) { - throw Throwables.propagate(e); + private void setGuiModListBottom(int bottom) { + try { + _modListBottom.set(getGuiModList(), bottom); + } catch (Exception e) { + Throwables.propagate(e); + } } - } - private void setGuiModListBottom(int bottom) { - try { - _modListBottom.set(getGuiModList(), bottom); - } catch (Exception e) { - Throwables.propagate(e); + private int getGuiModListBottom() { + try { + return _modListBottom.getInt(getGuiModList()); + } catch (Exception e) { + throw Throwables.propagate(e); + } } - } - private int getGuiModListBottom() { - try { - return _modListBottom.getInt(getGuiModList()); - } catch (Exception e) { - throw Throwables.propagate(e); + private float getGuiModListScroll() { + try { + return _scrollDistance.getFloat(getGuiModList()); + } catch (Exception e) { + throw Throwables.propagate(e); + } } - } - private float getGuiModListScroll() { - try { - return _scrollDistance.getFloat(getGuiModList()); - } catch (Exception e) { - throw Throwables.propagate(e); + private void setGuiModListScroll(float scroll) { + try { + _scrollDistance.setFloat(getGuiModList(), scroll); + } catch (Exception e) { + throw Throwables.propagate(e); + } } - } - private void setGuiModListScroll(float scroll) { - try { - _scrollDistance.setFloat(getGuiModList(), scroll); - } catch (Exception e) { - throw Throwables.propagate(e); + @SuppressWarnings("unchecked") + private List getMods() { + try { + return (List) _modListMods.get(_modList.get(this)); + } catch (Exception e) { + throw Throwables.propagate(e); + } } - } - @SuppressWarnings("unchecked") - private List getMods() { - try { - return (List) _modListMods.get(_modList.get(this)); - } catch (Exception e) { - throw Throwables.propagate(e); + private int getListWidth() { + try { + return _listWidth.getInt(this); + } catch (Exception e) { + throw Throwables.propagate(e); + } } - } - private int getListWidth() { - try { - return _listWidth.getInt(this); - } catch (Exception e) { - throw Throwables.propagate(e); + private ModContainer getSelectedMod() { + try { + return (ModContainer) _selectedMod.get(this); + } catch (Exception e) { + throw Throwables.propagate(e); + } } - } - private ModContainer getSelectedMod() { - try { - return (ModContainer) _selectedMod.get(this); - } catch (Exception e) { - throw Throwables.propagate(e); + private void setSelectedMod(ModContainer mod) { + try { + _selectedMod.set(this, mod); + } catch (Exception e) { + Throwables.propagate(e); + } } - } - - private void setSelectedMod(ModContainer mod) { - try { - _selectedMod.set(this, mod); - } catch (Exception e) { - Throwables.propagate(e); - } - } } diff --git a/src/main/java/com/enderio/core/client/gui/button/CheckBox.java b/src/main/java/com/enderio/core/client/gui/button/CheckBox.java index 6ebe153..99039d8 100644 --- a/src/main/java/com/enderio/core/client/gui/button/CheckBox.java +++ b/src/main/java/com/enderio/core/client/gui/button/CheckBox.java @@ -5,8 +5,8 @@ import com.enderio.core.client.render.EnderWidget; public class CheckBox extends ToggleButton { - public CheckBox(IGuiScreen gui, int id, int x, int y) { - super(gui, id, x, y, EnderWidget.BUTTON, EnderWidget.BUTTON_CHECKED); - } + public CheckBox(IGuiScreen gui, int id, int x, int y) { + super(gui, id, x, y, EnderWidget.BUTTON, EnderWidget.BUTTON_CHECKED); + } } 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 339323f..763fdab 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 @@ -12,97 +12,97 @@ import com.enderio.core.common.util.DyeColor; public class ColorButton extends IconButton { - private int colorIndex = 0; + private int colorIndex = 0; - private String tooltipPrefix = ""; + private String tooltipPrefix = ""; - public ColorButton(IGuiScreen gui, int id, int x, int y) { - super(gui, id, x, y, null); - } - - @Override - public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) { - boolean result = super.mousePressed(par1Minecraft, par2, par3); - if (result) { - nextColor(); + public ColorButton(IGuiScreen gui, int id, int x, int y) { + super(gui, id, x, y, null); } - return result; - } - @Override - public boolean mousePressedButton(Minecraft mc, int x, int y, int button) { - boolean result = button == 1 && super.checkMousePress(mc, x, y); - if (result) { - prevColor(); + @Override + public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) { + boolean result = super.mousePressed(par1Minecraft, par2, par3); + if (result) { + nextColor(); + } + return result; } - return result; - } - public String getTooltipPrefix() { - return tooltipPrefix; - } - - public void setToolTipHeading(String tooltipPrefix) { - if (tooltipPrefix == null) { - this.tooltipPrefix = ""; - } else { - this.tooltipPrefix = tooltipPrefix; + @Override + public boolean mousePressedButton(Minecraft mc, int x, int y, int button) { + boolean result = button == 1 && super.checkMousePress(mc, x, y); + if (result) { + prevColor(); + } + return result; } - } - private void nextColor() { - colorIndex++; - if (colorIndex >= ItemDye.field_150923_a.length) { - colorIndex = 0; + public String getTooltipPrefix() { + return tooltipPrefix; } - setColorIndex(colorIndex); - } - private void prevColor() { - colorIndex--; - if (colorIndex < 0) { - colorIndex = ItemDye.field_150923_a.length - 1; + public void setToolTipHeading(String tooltipPrefix) { + if (tooltipPrefix == null) { + this.tooltipPrefix = ""; + } else { + this.tooltipPrefix = tooltipPrefix; + } } - setColorIndex(colorIndex); - } - public int getColorIndex() { - return colorIndex; - } - - 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) { - setToolTip(tooltipPrefix, colStr); - } else { - setToolTip(colStr); + private void nextColor() { + colorIndex++; + if (colorIndex >= ItemDye.field_150923_a.length) { + colorIndex = 0; + } + setColorIndex(colorIndex); } - } - - @Override - public void drawButton(Minecraft mc, int mouseX, int mouseY) { - super.drawButton(mc, mouseX, mouseY); - if (visible) { - Tessellator tes = Tessellator.instance; - tes.startDrawingQuads(); - - int x = xPosition + 2; - int y = yPosition + 2; - - GL11.glDisable(GL11.GL_TEXTURE_2D); - - int col = ItemDye.field_150922_c[colorIndex]; - tes.setColorOpaque_I(col); - tes.addVertex(x, y + height - 4, zLevel); - tes.addVertex(x + width - 4, y + height - 4, zLevel); - tes.addVertex(x + width - 4, y + 0, zLevel); - tes.addVertex(x, y + 0, zLevel); - - tes.draw(); - - GL11.glEnable(GL11.GL_TEXTURE_2D); + private void prevColor() { + colorIndex--; + if (colorIndex < 0) { + colorIndex = ItemDye.field_150923_a.length - 1; + } + setColorIndex(colorIndex); + } + + public int getColorIndex() { + return colorIndex; + } + + 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) { + setToolTip(tooltipPrefix, colStr); + } else { + setToolTip(colStr); + } + } + + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY) { + super.drawButton(mc, mouseX, mouseY); + if (visible) { + Tessellator tes = Tessellator.instance; + tes.startDrawingQuads(); + + int x = xPosition + 2; + int y = yPosition + 2; + + GL11.glDisable(GL11.GL_TEXTURE_2D); + + int col = ItemDye.field_150922_c[colorIndex]; + tes.setColorOpaque_I(col); + tes.addVertex(x, y + height - 4, zLevel); + tes.addVertex(x + width - 4, y + height - 4, zLevel); + tes.addVertex(x + width - 4, y + 0, zLevel); + tes.addVertex(x, y + 0, zLevel); + + tes.draw(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + + } } - } } diff --git a/src/main/java/com/enderio/core/client/gui/button/CycleButton.java b/src/main/java/com/enderio/core/client/gui/button/CycleButton.java index 9009b95..1f6cd27 100644 --- a/src/main/java/com/enderio/core/client/gui/button/CycleButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/CycleButton.java @@ -9,79 +9,77 @@ import com.enderio.core.api.client.render.IWidgetIcon; import com.enderio.core.client.gui.button.CycleButton.ICycleEnum; /** - * A button which automatically parses enum constants and cycles between them - * when clicked. + * A button which automatically parses enum constants and cycles between them when clicked. * - * @param - * The enum type for this button. + * @param The enum type for this button. */ public class CycleButton & ICycleEnum> extends IconButton { - public interface ICycleEnum { + public interface ICycleEnum { - /** - * @return The icon to display when the button has selected this mode. - */ - IWidgetIcon getIcon(); + /** + * @return The icon to display when the button has selected this mode. + */ + IWidgetIcon getIcon(); - /** - * @return Localized tooltip lines. - */ - List getTooltipLines(); - } - - private final T[] modes; - - private T mode; - - public CycleButton(IGuiScreen gui, int id, int x, int y, Class enumClass) { - super(gui, id, x, y, null); - modes = enumClass.getEnumConstants(); - setMode(modes[0]); - } - - @Override - public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) { - boolean result = super.mousePressed(par1Minecraft, par2, par3); - if (result) { - nextMode(); + /** + * @return Localized tooltip lines. + */ + List getTooltipLines(); } - return result; - } - @Override - public boolean mousePressedButton(Minecraft mc, int x, int y, int button) { - boolean result = button == 1 && super.checkMousePress(mc, x, y); - if (result) { - prevMode(); + private final T[] modes; + + private T mode; + + public CycleButton(IGuiScreen gui, int id, int x, int y, Class enumClass) { + super(gui, id, x, y, null); + modes = enumClass.getEnumConstants(); + setMode(modes[0]); } - return result; - } - private void nextMode() { - setMode(modes[(mode.ordinal() + 1) % modes.length]); - } - - private void prevMode() { - int ord = mode.ordinal() - 1; - if (ord < 0) { - ord = modes.length - 1; + @Override + public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) { + boolean result = super.mousePressed(par1Minecraft, par2, par3); + if (result) { + nextMode(); + } + return result; } - setMode(modes[ord]); - } - - public T getMode() { - return mode; - } - public void setMode(T newMode) { - if (mode == newMode) { - return; + @Override + public boolean mousePressedButton(Minecraft mc, int x, int y, int button) { + boolean result = button == 1 && super.checkMousePress(mc, x, y); + if (result) { + prevMode(); + } + return result; } - mode = newMode; - List tooltip = mode.getTooltipLines(); - setToolTip(tooltip.toArray(new String[tooltip.size()])); - this.icon = mode.getIcon(); - } + private void nextMode() { + setMode(modes[(mode.ordinal() + 1) % modes.length]); + } + + private void prevMode() { + int ord = mode.ordinal() - 1; + if (ord < 0) { + ord = modes.length - 1; + } + setMode(modes[ord]); + } + + public T getMode() { + return mode; + } + + public void setMode(T newMode) { + if (mode == newMode) { + return; + } + mode = newMode; + List tooltip = mode.getTooltipLines(); + setToolTip(tooltip.toArray(new String[tooltip.size()])); + + this.icon = mode.getIcon(); + } } diff --git a/src/main/java/com/enderio/core/client/gui/button/GuiButtonHideable.java b/src/main/java/com/enderio/core/client/gui/button/GuiButtonHideable.java index 8539559..2d12606 100644 --- a/src/main/java/com/enderio/core/client/gui/button/GuiButtonHideable.java +++ b/src/main/java/com/enderio/core/client/gui/button/GuiButtonHideable.java @@ -2,11 +2,11 @@ package com.enderio.core.client.gui.button; import javax.annotation.Nonnull; -import com.enderio.core.api.client.gui.IHideable; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; +import com.enderio.core.api.client.gui.IHideable; + public class GuiButtonHideable extends GuiButton implements IHideable { public GuiButtonHideable(int buttonId, int x, int y, @Nonnull String buttonText) { 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 00bec23..f0092cc 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 @@ -12,86 +12,94 @@ import com.enderio.core.client.render.RenderUtil; public class IIconButton extends GuiButton { - public static final int DEFAULT_WIDTH = 24; - public static final int HWIDTH = DEFAULT_WIDTH / 2; - public static final int DEFAULT_HEIGHT = 24; - public static final int HHEIGHT = DEFAULT_HEIGHT / 2; + public static final int DEFAULT_WIDTH = 24; + public static final int HWIDTH = DEFAULT_WIDTH / 2; + public static final int DEFAULT_HEIGHT = 24; + public static final int HHEIGHT = DEFAULT_HEIGHT / 2; - protected int hwidth; - protected int hheight; + protected int hwidth; + protected int hheight; - protected IIcon icon; - protected ResourceLocation texture; - - public IIconButton(FontRenderer fr, int id, int x, int y, IIcon icon, ResourceLocation texture) { - super(id, x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, ""); - hwidth = HWIDTH; - hheight = HHEIGHT; - this.icon = icon; - this.texture = texture; - } - - public void setSize(int width, int height) { - this.width = width; - this.height = height; - hwidth = width / 2; - hheight = height / 2; - } - - public IIcon getIcon() { - return icon; - } - - public void setIcon(IIcon icon) { - this.icon = icon; - } - - public ResourceLocation getTexture() { - return texture; - } - - public void setTexture(ResourceLocation textureName) { - this.texture = textureName; - } - - /** - * Draws this button to the screen. - */ - @SuppressWarnings("synthetic-access") - @Override - public void drawButton(Minecraft par1Minecraft, int par2, int par3) { - 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; - int hoverState = getHoverState(this.field_146123_n); - - // x, y, u, v, width, height - - // top half - drawTexturedModalRect(xPosition, yPosition, 0, 46 + hoverState * 20, hwidth, hheight); - drawTexturedModalRect(xPosition + hwidth, yPosition, 200 - hwidth, 46 + hoverState * 20, hwidth, hheight); - - // bottom half - drawTexturedModalRect(xPosition, yPosition + hheight, 0, 66 - hheight + (hoverState * 20), hwidth, hheight); - drawTexturedModalRect(xPosition + hwidth, yPosition + hheight, 200 - hwidth, 66 - hheight + (hoverState * 20), hwidth, hheight); - - mouseDragged(par1Minecraft, par2, par3); - - 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); - - RenderUtil.bindTexture(texture); - int xLoc = xPosition + 2; - int yLoc = yPosition + 2; - drawTexturedModelRectFromIcon(xLoc, yLoc, icon, width - 4, height - 4); - - GL11.glPopAttrib(); - } + protected IIcon icon; + protected ResourceLocation texture; + public IIconButton(FontRenderer fr, int id, int x, int y, IIcon icon, ResourceLocation texture) { + super(id, x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, ""); + hwidth = HWIDTH; + hheight = HHEIGHT; + this.icon = icon; + this.texture = texture; + } + + public void setSize(int width, int height) { + this.width = width; + this.height = height; + hwidth = width / 2; + hheight = height / 2; + } + + public IIcon getIcon() { + return icon; + } + + public void setIcon(IIcon icon) { + this.icon = icon; + } + + public ResourceLocation getTexture() { + return texture; + } + + public void setTexture(ResourceLocation textureName) { + this.texture = textureName; + } + + /** + * Draws this button to the screen. + */ + @SuppressWarnings("synthetic-access") + @Override + public void drawButton(Minecraft par1Minecraft, int par2, int par3) { + 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; + int hoverState = getHoverState(this.field_146123_n); + + // x, y, u, v, width, height + + // top half + drawTexturedModalRect(xPosition, yPosition, 0, 46 + hoverState * 20, hwidth, hheight); + drawTexturedModalRect(xPosition + hwidth, yPosition, 200 - hwidth, 46 + hoverState * 20, hwidth, hheight); + + // bottom half + drawTexturedModalRect(xPosition, yPosition + hheight, 0, 66 - hheight + (hoverState * 20), hwidth, hheight); + drawTexturedModalRect( + xPosition + hwidth, + yPosition + hheight, + 200 - hwidth, + 66 - hheight + (hoverState * 20), + hwidth, + hheight); + + mouseDragged(par1Minecraft, par2, par3); + + 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); + + RenderUtil.bindTexture(texture); + int xLoc = xPosition + 2; + int yLoc = yPosition + 2; + drawTexturedModelRectFromIcon(xLoc, yLoc, icon, width - 4, height - 4); + + GL11.glPopAttrib(); + } + + } } - } } 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 308387b..44159d0 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 @@ -1,118 +1,113 @@ package com.enderio.core.client.gui.button; -import java.awt.Rectangle; - import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; import org.lwjgl.opengl.GL11; import com.enderio.core.api.client.gui.IGuiScreen; import com.enderio.core.api.client.render.IWidgetIcon; -import com.enderio.core.client.gui.widget.GuiToolTip; import com.enderio.core.client.render.EnderWidget; public class IconButton extends TooltipButton { - public static final int DEFAULT_WIDTH = 16; - public static final int DEFAULT_HEIGHT = 16; + public static final int DEFAULT_WIDTH = 16; + public static final int DEFAULT_HEIGHT = 16; - protected IWidgetIcon icon; - private int xOrigin; - private int yOrigin; + protected IWidgetIcon icon; + private int xOrigin; + private int yOrigin; - protected IGuiScreen gui; + protected IGuiScreen gui; - private int marginY = 0; - private int marginX = 0; - - public IconButton(IGuiScreen gui, int id, int x, int y, IWidgetIcon icon) { - super(gui, id, x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, ""); - this.gui = gui; - this.icon = icon; - this.xOrigin = x; - this.yOrigin = y; - } - - public IconButton setIconMargin(int x, int y) { - marginX = x; - marginY = y; - return this; - } - - public IWidgetIcon getIcon() { - return icon; - } - - public void setIcon(IWidgetIcon icon) { - this.icon = icon; - } - - /** - * Override this to handle mouse clicks with other buttons than the left - * - * @param mc - * The MC instance - * @param x - * X coordinate of mouse click - * @param y - * Y coordinate of mouse click - * @param button - * the mouse button - only called for button {@literal >}= 1 - * @return true if the mouse click is handled - */ - public boolean mousePressedButton(Minecraft mc, int x, int y, int button) { - return false; - } - - protected boolean checkMousePress(Minecraft mc, int x, int y) { - // call super here so that we only get the area check - return super.mousePressed(mc, x, y); - } - - /** - * Draws this button to the screen. - */ - @SuppressWarnings("synthetic-access") - @Override - public void drawButton(Minecraft mc, int mouseX, int mouseY) { - updateTooltip(mc, mouseX, mouseY); - if (isVisible()) { - - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - this.field_146123_n = mouseX >= this.xPosition && mouseY >= this.yPosition && mouseX < this.xPosition + width && mouseY < this.yPosition + height; - int hoverState = getHoverState(this.field_146123_n); - mouseDragged(mc, mouseX, mouseY); - - IWidgetIcon background = getIconForHoverState(hoverState); - - GL11.glColor3f(1, 1, 1); - - int x = xPosition; - int y = yPosition; - - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - - background.getMap().render(background, x, y, width, height, 0, true); - if (icon != null) { - icon.getMap().render(icon, x + marginX, y + marginY, width - (2 * marginX), height - (2 * marginY), 0, true); - } - - GL11.glPopAttrib(); + private int marginY = 0; + private int marginX = 0; + public IconButton(IGuiScreen gui, int id, int x, int y, IWidgetIcon icon) { + super(gui, id, x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, ""); + this.gui = gui; + this.icon = icon; + this.xOrigin = x; + this.yOrigin = y; } - } - protected IWidgetIcon getIconForHoverState(int hoverState) { - if (hoverState == 0) { - return EnderWidget.BUTTON_DISABLED; + public IconButton setIconMargin(int x, int y) { + marginX = x; + marginY = y; + return this; } - if (hoverState == 2) { - return EnderWidget.BUTTON_HIGHLIGHT; + + public IWidgetIcon getIcon() { + return icon; + } + + public void setIcon(IWidgetIcon icon) { + this.icon = icon; + } + + /** + * Override this to handle mouse clicks with other buttons than the left + * + * @param mc The MC instance + * @param x X coordinate of mouse click + * @param y Y coordinate of mouse click + * @param button the mouse button - only called for button {@literal >}= 1 + * @return true if the mouse click is handled + */ + public boolean mousePressedButton(Minecraft mc, int x, int y, int button) { + return false; + } + + protected boolean checkMousePress(Minecraft mc, int x, int y) { + // call super here so that we only get the area check + return super.mousePressed(mc, x, y); + } + + /** + * Draws this button to the screen. + */ + @SuppressWarnings("synthetic-access") + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY) { + updateTooltip(mc, mouseX, mouseY); + if (isVisible()) { + + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.field_146123_n = mouseX >= this.xPosition && mouseY >= this.yPosition + && mouseX < this.xPosition + width + && mouseY < this.yPosition + height; + int hoverState = getHoverState(this.field_146123_n); + mouseDragged(mc, mouseX, mouseY); + + IWidgetIcon background = getIconForHoverState(hoverState); + + GL11.glColor3f(1, 1, 1); + + int x = xPosition; + int y = yPosition; + + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + background.getMap().render(background, x, y, width, height, 0, true); + if (icon != null) { + icon.getMap() + .render(icon, x + marginX, y + marginY, width - (2 * marginX), height - (2 * marginY), 0, true); + } + + GL11.glPopAttrib(); + + } + } + + protected IWidgetIcon getIconForHoverState(int hoverState) { + if (hoverState == 0) { + return EnderWidget.BUTTON_DISABLED; + } + if (hoverState == 2) { + return EnderWidget.BUTTON_HIGHLIGHT; + } + return EnderWidget.BUTTON; } - return EnderWidget.BUTTON; - } } 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 7825c06..52d9862 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 @@ -6,28 +6,28 @@ import net.minecraft.util.ResourceLocation; public class IconToggleButton extends IIconButton { - private boolean selected = false; + private boolean selected = false; - public IconToggleButton(FontRenderer fr, int id, int x, int y, IIcon icon, ResourceLocation texture) { - super(fr, id, x, y, icon, texture); - } - - public boolean isSelected() { - return selected; - } - - public void setSelected(boolean selected) { - this.selected = selected; - } - - @Override - public int getHoverState(boolean par1) { - int result = 1; - if (!enabled || selected) { - result = 0; - } else if (par1) { - result = 2; + public IconToggleButton(FontRenderer fr, int id, int x, int y, IIcon icon, ResourceLocation texture) { + super(fr, id, x, y, icon, texture); + } + + public boolean isSelected() { + return selected; + } + + public void setSelected(boolean selected) { + this.selected = selected; + } + + @Override + public int getHoverState(boolean par1) { + int result = 1; + if (!enabled || selected) { + result = 0; + } else if (par1) { + result = 2; + } + return result; } - return result; - } } diff --git a/src/main/java/com/enderio/core/client/gui/button/InvisibleButton.java b/src/main/java/com/enderio/core/client/gui/button/InvisibleButton.java index 5a7e78b..a408b15 100644 --- a/src/main/java/com/enderio/core/client/gui/button/InvisibleButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/InvisibleButton.java @@ -2,10 +2,10 @@ package com.enderio.core.client.gui.button; import javax.annotation.Nonnull; -import com.enderio.core.api.client.gui.IGuiScreen; - import net.minecraft.client.Minecraft; +import com.enderio.core.api.client.gui.IGuiScreen; + public class InvisibleButton extends TooltipButton { private static final int DEFAULT_WIDTH = 8; 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 6820ce4..86fdb48 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 @@ -13,72 +13,80 @@ import com.enderio.core.client.render.RenderUtil; public class ItemButton extends GuiButton { - public static final RenderItem ITEM_RENDERER = new RenderItem(); + public static final RenderItem ITEM_RENDERER = new RenderItem(); - public static final int DEFAULT_WIDTH = 24; - public static final int HWIDTH = DEFAULT_WIDTH / 2; - public static final int DEFAULT_HEIGHT = 24; - public static final int HHEIGHT = DEFAULT_HEIGHT / 2; + public static final int DEFAULT_WIDTH = 24; + public static final int HWIDTH = DEFAULT_WIDTH / 2; + public static final int DEFAULT_HEIGHT = 24; + public static final int HHEIGHT = DEFAULT_HEIGHT / 2; - private ItemStack item; + private ItemStack item; - private FontRenderer fr; + private FontRenderer fr; - protected int hwidth; - protected int hheight; + protected int hwidth; + protected int hheight; - public ItemButton(FontRenderer fr, int id, int x, int y, Item item) { - super(id, x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, ""); - this.fr = fr; - this.item = new ItemStack(item, 1, 0); - hwidth = HWIDTH; - hheight = HHEIGHT; - } - - public void setSize(int width, int height) { - this.width = width; - this.height = height; - hwidth = width / 2; - hheight = height / 2; - } - - /** - * Draws this button to the screen. - */ - @SuppressWarnings("synthetic-access") - @Override - public void drawButton(Minecraft par1Minecraft, int par2, int par3) { - 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; - int hoverState = this.getHoverState(this.field_146123_n); - - // x, y, u, v, width, height - - // top half - drawTexturedModalRect(xPosition, yPosition, 0, 46 + hoverState * 20, hwidth, hheight); - drawTexturedModalRect(xPosition + hwidth, yPosition, 200 - hwidth, 46 + hoverState * 20, hwidth, hheight); - - // bottom half - drawTexturedModalRect(xPosition, yPosition + hheight, 0, 66 - hheight + (hoverState * 20), hwidth, hheight); - drawTexturedModalRect(xPosition + hwidth, yPosition + hheight, 200 - hwidth, 66 - hheight + (hoverState * 20), hwidth, hheight); - - mouseDragged(par1Minecraft, par2, par3); - - int l = 14737632; - - if (!this.enabled) { - l = -6250336; - } else if (this.field_146123_n) { - l = 16777120; - } - - int xLoc = xPosition + hwidth - 8; - int yLoc = yPosition + hheight - 10; - ITEM_RENDERER.renderItemIntoGUI(fr, par1Minecraft.renderEngine, item, xLoc, yLoc); + public ItemButton(FontRenderer fr, int id, int x, int y, Item item) { + super(id, x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, ""); + this.fr = fr; + this.item = new ItemStack(item, 1, 0); + hwidth = HWIDTH; + hheight = HHEIGHT; } - } -} \ No newline at end of file + public void setSize(int width, int height) { + this.width = width; + this.height = height; + hwidth = width / 2; + hheight = height / 2; + } + + /** + * Draws this button to the screen. + */ + @SuppressWarnings("synthetic-access") + @Override + public void drawButton(Minecraft par1Minecraft, int par2, int par3) { + 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; + int hoverState = this.getHoverState(this.field_146123_n); + + // x, y, u, v, width, height + + // top half + drawTexturedModalRect(xPosition, yPosition, 0, 46 + hoverState * 20, hwidth, hheight); + drawTexturedModalRect(xPosition + hwidth, yPosition, 200 - hwidth, 46 + hoverState * 20, hwidth, hheight); + + // bottom half + drawTexturedModalRect(xPosition, yPosition + hheight, 0, 66 - hheight + (hoverState * 20), hwidth, hheight); + drawTexturedModalRect( + xPosition + hwidth, + yPosition + hheight, + 200 - hwidth, + 66 - hheight + (hoverState * 20), + hwidth, + hheight); + + mouseDragged(par1Minecraft, par2, par3); + + int l = 14737632; + + if (!this.enabled) { + l = -6250336; + } else if (this.field_146123_n) { + l = 16777120; + } + + int xLoc = xPosition + hwidth - 8; + int yLoc = yPosition + hheight - 10; + ITEM_RENDERER.renderItemIntoGUI(fr, par1Minecraft.renderEngine, item, xLoc, yLoc); + } + } + +} diff --git a/src/main/java/com/enderio/core/client/gui/button/MultiIconButton.java b/src/main/java/com/enderio/core/client/gui/button/MultiIconButton.java index c8894bc..6cbc15b 100644 --- a/src/main/java/com/enderio/core/client/gui/button/MultiIconButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/MultiIconButton.java @@ -6,42 +6,71 @@ import com.enderio.core.client.render.EnderWidget; public class MultiIconButton extends IconButton { - private final IWidgetIcon unpressed; - private final IWidgetIcon pressed; - private final IWidgetIcon hover; + private final IWidgetIcon unpressed; + private final IWidgetIcon pressed; + private final IWidgetIcon hover; - public MultiIconButton(IGuiScreen gui, int id, int x, int y, IWidgetIcon unpressed, IWidgetIcon pressed, IWidgetIcon hover) { - super(gui, id, x, y, null); - this.unpressed = unpressed; - this.pressed = pressed; - this.hover = hover; - setSize((int) unpressed.getWidth(), (int) unpressed.getHeight()); - } - - @Override - protected IWidgetIcon getIconForHoverState(int hoverState) { - if (hoverState == 0) { - return pressed; + public MultiIconButton(IGuiScreen gui, int id, int x, int y, IWidgetIcon unpressed, IWidgetIcon pressed, + IWidgetIcon hover) { + super(gui, id, x, y, null); + this.unpressed = unpressed; + this.pressed = pressed; + this.hover = hover; + setSize((int) unpressed.getWidth(), (int) unpressed.getHeight()); } - if (hoverState == 2) { - return hover; + + @Override + protected IWidgetIcon getIconForHoverState(int hoverState) { + if (hoverState == 0) { + return pressed; + } + if (hoverState == 2) { + return hover; + } + return unpressed; } - return unpressed; - } - public static MultiIconButton createRightArrowButton(IGuiScreen gui, int id, int x, int y) { - return new MultiIconButton(gui, id, x, y, EnderWidget.RIGHT_ARROW, EnderWidget.RIGHT_ARROW_PRESSED, EnderWidget.RIGHT_ARROW_HOVER); - } + public static MultiIconButton createRightArrowButton(IGuiScreen gui, int id, int x, int y) { + return new MultiIconButton( + gui, + id, + x, + y, + EnderWidget.RIGHT_ARROW, + EnderWidget.RIGHT_ARROW_PRESSED, + EnderWidget.RIGHT_ARROW_HOVER); + } - public static MultiIconButton createLeftArrowButton(IGuiScreen gui, int id, int x, int y) { - return new MultiIconButton(gui, id, x, y, EnderWidget.LEFT_ARROW, EnderWidget.LEFT_ARROW_PRESSED, EnderWidget.LEFT_ARROW_HOVER); - } + public static MultiIconButton createLeftArrowButton(IGuiScreen gui, int id, int x, int y) { + return new MultiIconButton( + gui, + id, + x, + y, + EnderWidget.LEFT_ARROW, + EnderWidget.LEFT_ARROW_PRESSED, + EnderWidget.LEFT_ARROW_HOVER); + } - public static MultiIconButton createAddButton(IGuiScreen gui, int id, int x, int y) { - return new MultiIconButton(gui, id, x, y, EnderWidget.ADD_BUT, EnderWidget.ADD_BUT_PRESSED, EnderWidget.ADD_BUT_HOVER); - } + public static MultiIconButton createAddButton(IGuiScreen gui, int id, int x, int y) { + return new MultiIconButton( + gui, + id, + x, + y, + EnderWidget.ADD_BUT, + EnderWidget.ADD_BUT_PRESSED, + EnderWidget.ADD_BUT_HOVER); + } - public static MultiIconButton createMinusButton(IGuiScreen gui, int id, int x, int y) { - return new MultiIconButton(gui, id, x, y, EnderWidget.MINUS_BUT, EnderWidget.MINUS_BUT_PRESSED, EnderWidget.MINUS_BUT_HOVER); - } + public static MultiIconButton createMinusButton(IGuiScreen gui, int id, int x, int y) { + return new MultiIconButton( + gui, + id, + x, + y, + EnderWidget.MINUS_BUT, + EnderWidget.MINUS_BUT_PRESSED, + EnderWidget.MINUS_BUT_HOVER); + } } diff --git a/src/main/java/com/enderio/core/client/gui/button/ToggleButton.java b/src/main/java/com/enderio/core/client/gui/button/ToggleButton.java index 6b5dd0a..599e0db 100644 --- a/src/main/java/com/enderio/core/client/gui/button/ToggleButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/ToggleButton.java @@ -12,76 +12,76 @@ import com.google.common.collect.Lists; public class ToggleButton extends IconButton { - private boolean selected; - private final IWidgetIcon unselectedIcon; - private final IWidgetIcon selectedIcon; + private boolean selected; + private final IWidgetIcon unselectedIcon; + private final IWidgetIcon selectedIcon; - private GuiToolTip selectedTooltip, unselectedTooltip; - private boolean paintSelectionBorder; + private GuiToolTip selectedTooltip, unselectedTooltip; + private boolean paintSelectionBorder; - public ToggleButton(IGuiScreen gui, int id, int x, int y, IWidgetIcon unselectedIcon, IWidgetIcon selectedIcon) { - super(gui, id, x, y, unselectedIcon); - this.unselectedIcon = unselectedIcon; - this.selectedIcon = selectedIcon; - selected = false; - paintSelectionBorder = true; - } - - public boolean isSelected() { - return selected; - } - - public ToggleButton setSelected(boolean selected) { - this.selected = selected; - icon = selected ? selectedIcon : unselectedIcon; - if (selected && selectedTooltip != null) { - setToolTip(selectedTooltip); - } else if (!selected && unselectedTooltip != null) { - setToolTip(unselectedTooltip); + public ToggleButton(IGuiScreen gui, int id, int x, int y, IWidgetIcon unselectedIcon, IWidgetIcon selectedIcon) { + super(gui, id, x, y, unselectedIcon); + this.unselectedIcon = unselectedIcon; + this.selectedIcon = selectedIcon; + selected = false; + paintSelectionBorder = true; } - return this; - } - @Override - protected IWidgetIcon getIconForHoverState(int hoverState) { - if (!selected || !paintSelectionBorder) { - return super.getIconForHoverState(hoverState); + public boolean isSelected() { + return selected; } - if (hoverState == 0) { - return EnderWidget.BUTTON_DISABLED; + + public ToggleButton setSelected(boolean selected) { + this.selected = selected; + icon = selected ? selectedIcon : unselectedIcon; + if (selected && selectedTooltip != null) { + setToolTip(selectedTooltip); + } else if (!selected && unselectedTooltip != null) { + setToolTip(unselectedTooltip); + } + return this; } - if (hoverState == 2) { - return EnderWidget.BUTTON_DOWN_HIGHLIGHT; + + @Override + protected IWidgetIcon getIconForHoverState(int hoverState) { + if (!selected || !paintSelectionBorder) { + return super.getIconForHoverState(hoverState); + } + if (hoverState == 0) { + return EnderWidget.BUTTON_DISABLED; + } + if (hoverState == 2) { + return EnderWidget.BUTTON_DOWN_HIGHLIGHT; + } + return EnderWidget.BUTTON_DOWN; } - return EnderWidget.BUTTON_DOWN; - } - @Override - public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) { - if (super.mousePressed(par1Minecraft, par2, par3)) { - return toggleSelected(); + @Override + public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) { + if (super.mousePressed(par1Minecraft, par2, par3)) { + return toggleSelected(); + } + return false; } - return false; - } - protected boolean toggleSelected() { - setSelected(!selected); - return true; - } + protected boolean toggleSelected() { + setSelected(!selected); + return true; + } - public void setSelectedToolTip(String... tt) { - String[] combinedTooltip = ArrayUtils.addAll(toolTipText, tt); - selectedTooltip = new GuiToolTip(getBounds(), Lists.newArrayList(combinedTooltip)); - setSelected(selected); - } + public void setSelectedToolTip(String... tt) { + String[] combinedTooltip = ArrayUtils.addAll(toolTipText, tt); + selectedTooltip = new GuiToolTip(getBounds(), Lists.newArrayList(combinedTooltip)); + setSelected(selected); + } - public void setUnselectedToolTip(String... tt) { - String[] combinedTooltip = ArrayUtils.addAll(toolTipText, tt); - unselectedTooltip = new GuiToolTip(getBounds(), Lists.newArrayList(combinedTooltip)); - setSelected(selected); - } + public void setUnselectedToolTip(String... tt) { + String[] combinedTooltip = ArrayUtils.addAll(toolTipText, tt); + unselectedTooltip = new GuiToolTip(getBounds(), Lists.newArrayList(combinedTooltip)); + setSelected(selected); + } - public void setPaintSelectedBorder(boolean b) { - this.paintSelectionBorder = b; - } + public void setPaintSelectedBorder(boolean b) { + this.paintSelectionBorder = b; + } } diff --git a/src/main/java/com/enderio/core/client/gui/button/TooltipButton.java b/src/main/java/com/enderio/core/client/gui/button/TooltipButton.java index 62f5f7d..c483732 100644 --- a/src/main/java/com/enderio/core/client/gui/button/TooltipButton.java +++ b/src/main/java/com/enderio/core/client/gui/button/TooltipButton.java @@ -5,11 +5,11 @@ import java.awt.Rectangle; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import net.minecraft.client.Minecraft; + import com.enderio.core.api.client.gui.IGuiScreen; import com.enderio.core.client.gui.widget.GuiToolTip; -import net.minecraft.client.Minecraft; - public class TooltipButton extends GuiButtonHideable { protected int xOrigin; @@ -18,7 +18,8 @@ public class TooltipButton extends GuiButtonHideable { protected @Nullable String[] toolTipText; protected @Nullable GuiToolTip toolTip; - public TooltipButton(@Nonnull IGuiScreen gui, int id, int x, int y, int widthIn, int heightIn, @Nonnull String buttonText) { + public TooltipButton(@Nonnull IGuiScreen gui, int id, int x, int y, int widthIn, int heightIn, + @Nonnull String buttonText) { super(id, x, y, widthIn, heightIn, buttonText); this.gui = gui; this.xOrigin = x; diff --git a/src/main/java/com/enderio/core/client/gui/widget/GhostBackgroundItemSlot.java b/src/main/java/com/enderio/core/client/gui/widget/GhostBackgroundItemSlot.java index f55bffe..b4e7c76 100644 --- a/src/main/java/com/enderio/core/client/gui/widget/GhostBackgroundItemSlot.java +++ b/src/main/java/com/enderio/core/client/gui/widget/GhostBackgroundItemSlot.java @@ -7,60 +7,59 @@ import net.minecraft.item.ItemStack; public class GhostBackgroundItemSlot extends GhostSlot { - private final ItemStack stack; - private final Slot parent; + private final ItemStack stack; + private final Slot parent; - public GhostBackgroundItemSlot(ItemStack stack, int x, int y) { - this.stack = stack; - this.parent = null; - this.x = x; - this.y = y; - this.grayOut = true; - this.grayOutLevel = .75f; - } + public GhostBackgroundItemSlot(ItemStack stack, int x, int y) { + this.stack = stack; + this.parent = null; + this.x = x; + this.y = y; + this.grayOut = true; + this.grayOutLevel = .75f; + } - public GhostBackgroundItemSlot(ItemStack stack, Slot parent) { - this.stack = stack; - this.parent = parent; - this.x = parent.xDisplayPosition; - this.y = parent.yDisplayPosition; - this.grayOut = true; - this.grayOutLevel = .75f; - } + public GhostBackgroundItemSlot(ItemStack stack, Slot parent) { + this.stack = stack; + this.parent = parent; + this.x = parent.xDisplayPosition; + this.y = parent.yDisplayPosition; + this.grayOut = true; + this.grayOutLevel = .75f; + } - public GhostBackgroundItemSlot(Item item, int x, int y) { - this(new ItemStack(item), x, y); - } + public GhostBackgroundItemSlot(Item item, int x, int y) { + this(new ItemStack(item), x, y); + } - public GhostBackgroundItemSlot(Block block, int x, int y) { - this(new ItemStack(block), x, y); - } + public GhostBackgroundItemSlot(Block block, int x, int y) { + this(new ItemStack(block), x, y); + } - public GhostBackgroundItemSlot(Item item, Slot parent) { - this(new ItemStack(item), parent); - } + public GhostBackgroundItemSlot(Item item, Slot parent) { + this(new ItemStack(item), parent); + } - public GhostBackgroundItemSlot(Block block, Slot parent) { - this(new ItemStack(block), parent); - } + public GhostBackgroundItemSlot(Block block, Slot parent) { + this(new ItemStack(block), parent); + } - @Override - public boolean isMouseOver(int mx, int my) { - return false; - } + @Override + public boolean isMouseOver(int mx, int my) { + return false; + } - @Override - public ItemStack getStack() { - return stack; - } + @Override + public ItemStack getStack() { + return stack; + } - @Override - public void putStack(ItemStack stack) { - } + @Override + public void putStack(ItemStack stack) {} - @Override - public boolean isVisible() { - return parent != null ? parent.xDisplayPosition >= 0 && parent.yDisplayPosition >= 0 : super.isVisible(); - } + @Override + public boolean isVisible() { + return parent != null ? parent.xDisplayPosition >= 0 && parent.yDisplayPosition >= 0 : super.isVisible(); + } -} \ No newline at end of file +} 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 f3c4d88..83f3054 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 @@ -8,62 +8,62 @@ import com.enderio.core.common.network.PacketGhostSlot; public abstract class GhostSlot { - public TileEntityEnder te = null; - public int slot = -1; - public int x; - public int y; + public TileEntityEnder te = null; + public int slot = -1; + public int x; + public int y; - public boolean visible = true; - public boolean grayOut = true; - public float grayOutLevel = 0.5f; - public boolean displayStdOverlay = false; - public int stackSizeLimit = 1; + public boolean visible = true; + public boolean grayOut = true; + public float grayOutLevel = 0.5f; + public boolean displayStdOverlay = false; + public int stackSizeLimit = 1; - public boolean isMouseOver(int mx, int my) { - return mx >= x && mx < (x + 16) && my >= y && my < (y + 16); - } - - public abstract ItemStack getStack(); - - public void putStack(ItemStack stack) { - if (te != null) { - EnderPacketHandler.sendToServer(PacketGhostSlot.setGhostSlotContents(te, slot, stack)); + public boolean isMouseOver(int mx, int my) { + return mx >= x && mx < (x + 16) && my >= y && my < (y + 16); } - } - /** - * Should the slot be displayed at all? - */ - public boolean isVisible() { - return visible; - } + public abstract ItemStack getStack(); - /** - * Should the slot be grayed out? - */ - public boolean shouldGrayOut() { - return grayOut; - } + public void putStack(ItemStack stack) { + if (te != null) { + EnderPacketHandler.sendToServer(PacketGhostSlot.setGhostSlotContents(te, slot, stack)); + } + } - /** - * If it should be grayed out, how far? (1=no graying, 0=fully invisible) - */ - public float getGrayOutLevel() { - return grayOutLevel; - } + /** + * Should the slot be displayed at all? + */ + public boolean isVisible() { + return visible; + } - /** - * Should the items in the slot have their standard overlay (stacksize)? - */ - public boolean shouldDisplayStdOverlay() { - return displayStdOverlay; - } + /** + * Should the slot be grayed out? + */ + public boolean shouldGrayOut() { + return grayOut; + } - /** - * Limit the stack size? (Enable the standard overlay if this is not 1.) - */ - public int getStackSizeLimit() { - return stackSizeLimit; - } + /** + * If it should be grayed out, how far? (1=no graying, 0=fully invisible) + */ + public float getGrayOutLevel() { + return grayOutLevel; + } + + /** + * Should the items in the slot have their standard overlay (stacksize)? + */ + public boolean shouldDisplayStdOverlay() { + return displayStdOverlay; + } + + /** + * Limit the stack size? (Enable the standard overlay if this is not 1.) + */ + public int getStackSizeLimit() { + return stackSizeLimit; + } } 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 5fea025..9661ae4 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 @@ -16,395 +16,398 @@ import com.enderio.core.api.client.gui.ListSelectionListener; public abstract class GuiScrollableList { - private final Minecraft mc = Minecraft.getMinecraft(); + private final Minecraft mc = Minecraft.getMinecraft(); - protected int originX; - protected int originY; - protected int width; - protected int height; - protected int minY; - protected int maxY; - protected int minX; - protected int maxX; + protected int originX; + protected int originY; + protected int width; + protected int height; + protected int minY; + protected int maxY; + protected int minX; + protected int maxX; - protected final int slotHeight; + protected final int slotHeight; - private int scrollUpButtonID; + private int scrollUpButtonID; - private int scrollDownButtonID; + private int scrollDownButtonID; - protected int mouseX; + protected int mouseX; - protected int mouseY; + protected int mouseY; - private float initialClickY = -2.0F; + private float initialClickY = -2.0F; - private float scrollMultiplier; + private float scrollMultiplier; - private float amountScrolled; + private float amountScrolled; - protected int selectedIndex = -1; + protected int selectedIndex = -1; - private long lastClickedTime; + private long lastClickedTime; - private boolean showSelectionBox = true; + private boolean showSelectionBox = true; - protected int margin = 4; + protected int margin = 4; - protected List> listeners = new CopyOnWriteArrayList>(); + protected List> listeners = new CopyOnWriteArrayList>(); - public GuiScrollableList(int width, int height, int originX, int originY, int slotHeight) { - this.width = width; - this.height = height; - this.originX = originX; - this.originY = originY; - this.slotHeight = slotHeight; + public GuiScrollableList(int width, int height, int originX, int originY, int slotHeight) { + this.width = width; + this.height = height; + this.originX = originX; + this.originY = originY; + this.slotHeight = slotHeight; - minY = originY; - maxY = minY + height; - minX = originX; - maxX = minX + width; - } - - public void onGuiInit(IGuiScreen gui) { - minY = originY + gui.getGuiTop(); - maxY = minY + height; - minX = originX + gui.getGuiLeft(); - maxX = minX + width; - } - - public void addSelectionListener(ListSelectionListener listener) { - listeners.add(listener); - } - - public void removeSelectionListener(ListSelectionListener listener) { - listeners.remove(listener); - } - - public T getSelectedElement() { - return getElementAt(selectedIndex); - } - - public void setSelection(T selection) { - setSelection(getIndexOf(selection)); - } - - public void setSelection(int index) { - if (index == selectedIndex) { - return; + minY = originY; + maxY = minY + height; + minX = originX; + maxX = minX + width; } - selectedIndex = index; - for (ListSelectionListener listener : listeners) { - listener.selectionChanged(this, selectedIndex); + + public void onGuiInit(IGuiScreen gui) { + minY = originY + gui.getGuiTop(); + maxY = minY + height; + minX = originX + gui.getGuiLeft(); + maxX = minX + width; } - } - public int getIndexOf(T element) { - if (element == null) { - return -1; + public void addSelectionListener(ListSelectionListener listener) { + listeners.add(listener); } - for (int i = 0; i < getNumElements(); i++) { - if (element.equals(getElementAt(i))) { - return i; - } + + public void removeSelectionListener(ListSelectionListener listener) { + listeners.remove(listener); } - return -1; - } - public abstract T getElementAt(int index); - - public abstract int getNumElements(); - - protected abstract void drawElement(int elementIndex, int x, int y, int height, Tessellator tessellator); - - protected boolean elementClicked(int elementIndex, boolean doubleClick) { - return true; - } - - public void setShowSelectionBox(boolean val) { - showSelectionBox = val; - } - - protected int getContentHeight() { - return getNumElements() * slotHeight; - } - - public void setScrollButtonIds(int scrollUpButtonID, int scrollDownButtonID) { - this.scrollUpButtonID = scrollUpButtonID; - this.scrollDownButtonID = scrollDownButtonID; - } - - private void clampScrollToBounds() { - int i = getContentOverhang(); - if (i < 0) { - i *= -1; + public T getSelectedElement() { + return getElementAt(selectedIndex); } - if (amountScrolled < 0.0F) { - amountScrolled = 0.0F; - } - if (amountScrolled > i) { - amountScrolled = i; - } - } - public int getContentOverhang() { - return getContentHeight() - (height - margin); - } + public void setSelection(T selection) { + setSelection(getIndexOf(selection)); + } + + public void setSelection(int index) { + if (index == selectedIndex) { + return; + } + selectedIndex = index; + for (ListSelectionListener listener : listeners) { + listener.selectionChanged(this, selectedIndex); + } + } + + public int getIndexOf(T element) { + if (element == null) { + return -1; + } + for (int i = 0; i < getNumElements(); i++) { + if (element.equals(getElementAt(i))) { + return i; + } + } + return -1; + } + + public abstract T getElementAt(int index); + + public abstract int getNumElements(); + + protected abstract void drawElement(int elementIndex, int x, int y, int height, Tessellator tessellator); + + protected boolean elementClicked(int elementIndex, boolean doubleClick) { + return true; + } + + public void setShowSelectionBox(boolean val) { + showSelectionBox = val; + } + + protected int getContentHeight() { + return getNumElements() * slotHeight; + } + + public void setScrollButtonIds(int scrollUpButtonID, int scrollDownButtonID) { + this.scrollUpButtonID = scrollUpButtonID; + this.scrollDownButtonID = scrollDownButtonID; + } + + private void clampScrollToBounds() { + int i = getContentOverhang(); + if (i < 0) { + i *= -1; + } + if (amountScrolled < 0.0F) { + amountScrolled = 0.0F; + } + if (amountScrolled > i) { + amountScrolled = i; + } + } + + public int getContentOverhang() { + return getContentHeight() - (height - margin); + } + + public void actionPerformed(GuiButton b) { + if (b.enabled) { + if (b.id == scrollUpButtonID) { + amountScrolled -= slotHeight * 2 / 3; + initialClickY = -2.0F; + clampScrollToBounds(); + } else if (b.id == scrollDownButtonID) { + amountScrolled += slotHeight * 2 / 3; + initialClickY = -2.0F; + clampScrollToBounds(); + } + } + } + + /** + * draws the slot to the screen, pass in mouse's current x and y and partial ticks + */ + public void drawScreen(int mX, int mY, float partialTick) { + this.mouseX = mX; + this.mouseY = mY; + + processMouseEvents(); - public void actionPerformed(GuiButton b) { - if (b.enabled) { - if (b.id == scrollUpButtonID) { - amountScrolled -= slotHeight * 2 / 3; - initialClickY = -2.0F; clampScrollToBounds(); - } else if (b.id == scrollDownButtonID) { - amountScrolled += slotHeight * 2 / 3; - initialClickY = -2.0F; - clampScrollToBounds(); - } - } - } - /** - * draws the slot to the screen, pass in mouse's current x and y and partial - * ticks - */ - public void drawScreen(int mX, int mY, float partialTick) { - this.mouseX = mX; - this.mouseY = mY; + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_FOG); - processMouseEvents(); + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int sx = minX * sr.getScaleFactor(); + int sw = width * sr.getScaleFactor(); + int sy = mc.displayHeight - (maxY * sr.getScaleFactor()); + int sh = height * sr.getScaleFactor(); + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GL11.glScissor(sx, sy, sw, sh); - clampScrollToBounds(); + Tessellator tessellator = Tessellator.instance; + drawContainerBackground(tessellator); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_FOG); + int contentYOffset = this.minY + margin - (int) this.amountScrolled; - ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - int sx = minX * sr.getScaleFactor(); - int sw = width * sr.getScaleFactor(); - int sy = mc.displayHeight - (maxY * sr.getScaleFactor()); - int sh = height * sr.getScaleFactor(); - GL11.glEnable(GL11.GL_SCISSOR_TEST); - GL11.glScissor(sx, sy, sw, sh); + for (int i = 0; i < getNumElements(); ++i) { - Tessellator tessellator = Tessellator.instance; - drawContainerBackground(tessellator); + int elementY = contentYOffset + i * this.slotHeight; + int slotHeight = this.slotHeight - margin; - int contentYOffset = this.minY + margin - (int) this.amountScrolled; + if (elementY <= maxY && elementY + slotHeight >= minY) { - for (int i = 0; i < getNumElements(); ++i) { + if (showSelectionBox && i == selectedIndex) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glDisable(GL11.GL_TEXTURE_2D); + tessellator.startDrawingQuads(); + tessellator.setColorOpaque_I(8421504); + tessellator.addVertexWithUV(minX, elementY + slotHeight + 2, 0.0D, 0.0D, 1.0D); + tessellator.addVertexWithUV(maxX, elementY + slotHeight + 2, 0.0D, 1.0D, 1.0D); + tessellator.addVertexWithUV(maxX, elementY - 2, 0.0D, 1.0D, 0.0D); + tessellator.addVertexWithUV(minX, elementY - 2, 0.0D, 0.0D, 0.0D); + tessellator.setColorOpaque_I(0); + tessellator.addVertexWithUV(minX + 1, elementY + slotHeight + 1, 0.0D, 0.0D, 1.0D); + tessellator.addVertexWithUV(maxX - 1, elementY + slotHeight + 1, 0.0D, 1.0D, 1.0D); + tessellator.addVertexWithUV(maxX - 1, elementY - 1, 0.0D, 1.0D, 0.0D); + tessellator.addVertexWithUV(minX + 1, elementY - 1, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } - int elementY = contentYOffset + i * this.slotHeight; - int slotHeight = this.slotHeight - margin; - - if (elementY <= maxY && elementY + slotHeight >= minY) { - - if (showSelectionBox && i == selectedIndex) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glDisable(GL11.GL_TEXTURE_2D); - tessellator.startDrawingQuads(); - tessellator.setColorOpaque_I(8421504); - tessellator.addVertexWithUV(minX, elementY + slotHeight + 2, 0.0D, 0.0D, 1.0D); - tessellator.addVertexWithUV(maxX, elementY + slotHeight + 2, 0.0D, 1.0D, 1.0D); - tessellator.addVertexWithUV(maxX, elementY - 2, 0.0D, 1.0D, 0.0D); - tessellator.addVertexWithUV(minX, elementY - 2, 0.0D, 0.0D, 0.0D); - tessellator.setColorOpaque_I(0); - tessellator.addVertexWithUV(minX + 1, elementY + slotHeight + 1, 0.0D, 0.0D, 1.0D); - tessellator.addVertexWithUV(maxX - 1, elementY + slotHeight + 1, 0.0D, 1.0D, 1.0D); - tessellator.addVertexWithUV(maxX - 1, elementY - 1, 0.0D, 1.0D, 0.0D); - tessellator.addVertexWithUV(minX + 1, elementY - 1, 0.0D, 0.0D, 0.0D); - tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); + drawElement(i, minX, elementY, slotHeight, tessellator); + } } - drawElement(i, minX, elementY, slotHeight, tessellator); - } + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glShadeModel(GL11.GL_SMOOTH); + GL11.glDisable(GL11.GL_TEXTURE_2D); + + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_I(0, 0); + tessellator.addVertexWithUV(this.minX, this.minY + margin, 0.0D, 0.0D, 1.0D); + tessellator.addVertexWithUV(this.maxX, this.minY + margin, 0.0D, 1.0D, 1.0D); + tessellator.setColorRGBA_I(0, 255); + tessellator.addVertexWithUV(this.maxX, this.minY, 0.0D, 1.0D, 0.0D); + tessellator.addVertexWithUV(this.minX, this.minY, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_I(0, 255); + tessellator.addVertexWithUV(this.minX, this.maxY, 0.0D, 0.0D, 1.0D); + tessellator.addVertexWithUV(this.maxX, this.maxY, 0.0D, 1.0D, 1.0D); + tessellator.setColorRGBA_I(0, 0); + tessellator.addVertexWithUV(this.maxX, this.maxY - margin, 0.0D, 1.0D, 0.0D); + tessellator.addVertexWithUV(this.minX, this.maxY - margin, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + + renderScrollBar(tessellator); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glShadeModel(GL11.GL_FLAT); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glDisable(GL11.GL_BLEND); } - GL11.glDisable(GL11.GL_SCISSOR_TEST); + protected void renderScrollBar(Tessellator tessellator) { - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glShadeModel(GL11.GL_SMOOTH); - GL11.glDisable(GL11.GL_TEXTURE_2D); + int contentHeightOverBounds = getContentOverhang(); + if (contentHeightOverBounds > 0) { - tessellator.startDrawingQuads(); - tessellator.setColorRGBA_I(0, 0); - tessellator.addVertexWithUV(this.minX, this.minY + margin, 0.0D, 0.0D, 1.0D); - tessellator.addVertexWithUV(this.maxX, this.minY + margin, 0.0D, 1.0D, 1.0D); - tessellator.setColorRGBA_I(0, 255); - tessellator.addVertexWithUV(this.maxX, this.minY, 0.0D, 1.0D, 0.0D); - tessellator.addVertexWithUV(this.minX, this.minY, 0.0D, 0.0D, 0.0D); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setColorRGBA_I(0, 255); - tessellator.addVertexWithUV(this.minX, this.maxY, 0.0D, 0.0D, 1.0D); - tessellator.addVertexWithUV(this.maxX, this.maxY, 0.0D, 1.0D, 1.0D); - tessellator.setColorRGBA_I(0, 0); - tessellator.addVertexWithUV(this.maxX, this.maxY - margin, 0.0D, 1.0D, 0.0D); - tessellator.addVertexWithUV(this.minX, this.maxY - margin, 0.0D, 0.0D, 0.0D); - tessellator.draw(); + int clear = (maxY - minY) * (maxY - minY) / getContentHeight(); - renderScrollBar(tessellator); + if (clear < 32) { + clear = 32; + } - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glShadeModel(GL11.GL_FLAT); - GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glDisable(GL11.GL_BLEND); - } + if (clear > maxY - minY - 8) { + clear = maxY - minY - 8; + } - protected void renderScrollBar(Tessellator tessellator) { + int y = (int) this.amountScrolled * (maxY - minY - clear) / contentHeightOverBounds + minY; + if (y < minY) { + y = minY; + } - int contentHeightOverBounds = getContentOverhang(); - if (contentHeightOverBounds > 0) { + GL11.glDisable(GL11.GL_TEXTURE_2D); + int scrollBarMinX = getScrollBarX(); + int scrollBarMaxX = scrollBarMinX + 6; + tessellator.startDrawingQuads(); - int clear = (maxY - minY) * (maxY - minY) / getContentHeight(); + tessellator.setColorRGBA_I(0, 255); + tessellator.addVertexWithUV(scrollBarMinX, maxY, 0.0D, 0.0D, 1.0D); + tessellator.addVertexWithUV(scrollBarMaxX, maxY, 0.0D, 1.0D, 1.0D); + tessellator.addVertexWithUV(scrollBarMaxX, minY, 0.0D, 1.0D, 0.0D); + tessellator.addVertexWithUV(scrollBarMinX, minY, 0.0D, 0.0D, 0.0D); - if (clear < 32) { - clear = 32; - } + tessellator.setColorRGBA_F(0.3f, 0.3f, 0.3f, 1); + tessellator.addVertexWithUV(scrollBarMinX, (y + clear), 0.0D, 0.0D, 1.0D); + tessellator.addVertexWithUV(scrollBarMaxX, (y + clear), 0.0D, 1.0D, 1.0D); + tessellator.addVertexWithUV(scrollBarMaxX, y, 0.0D, 1.0D, 0.0D); + tessellator.addVertexWithUV(scrollBarMinX, y, 0.0D, 0.0D, 0.0D); - if (clear > maxY - minY - 8) { - clear = maxY - minY - 8; - } + tessellator.setColorRGBA_F(0.7f, 0.7f, 0.7f, 1); + tessellator.addVertexWithUV(scrollBarMinX, (y + clear - 1), 0.0D, 0.0D, 1.0D); + tessellator.addVertexWithUV((scrollBarMaxX - 1), (y + clear - 1), 0.0D, 1.0D, 1.0D); + tessellator.addVertexWithUV((scrollBarMaxX - 1), y, 0.0D, 1.0D, 0.0D); + tessellator.addVertexWithUV(scrollBarMinX, y, 0.0D, 0.0D, 0.0D); - int y = (int) this.amountScrolled * (maxY - minY - clear) / contentHeightOverBounds + minY; - if (y < minY) { - y = minY; - } - - GL11.glDisable(GL11.GL_TEXTURE_2D); - int scrollBarMinX = getScrollBarX(); - int scrollBarMaxX = scrollBarMinX + 6; - tessellator.startDrawingQuads(); - - tessellator.setColorRGBA_I(0, 255); - tessellator.addVertexWithUV(scrollBarMinX, maxY, 0.0D, 0.0D, 1.0D); - tessellator.addVertexWithUV(scrollBarMaxX, maxY, 0.0D, 1.0D, 1.0D); - tessellator.addVertexWithUV(scrollBarMaxX, minY, 0.0D, 1.0D, 0.0D); - tessellator.addVertexWithUV(scrollBarMinX, minY, 0.0D, 0.0D, 0.0D); - - tessellator.setColorRGBA_F(0.3f, 0.3f, 0.3f, 1); - tessellator.addVertexWithUV(scrollBarMinX, (y + clear), 0.0D, 0.0D, 1.0D); - tessellator.addVertexWithUV(scrollBarMaxX, (y + clear), 0.0D, 1.0D, 1.0D); - tessellator.addVertexWithUV(scrollBarMaxX, y, 0.0D, 1.0D, 0.0D); - tessellator.addVertexWithUV(scrollBarMinX, y, 0.0D, 0.0D, 0.0D); - - tessellator.setColorRGBA_F(0.7f, 0.7f, 0.7f, 1); - tessellator.addVertexWithUV(scrollBarMinX, (y + clear - 1), 0.0D, 0.0D, 1.0D); - tessellator.addVertexWithUV((scrollBarMaxX - 1), (y + clear - 1), 0.0D, 1.0D, 1.0D); - tessellator.addVertexWithUV((scrollBarMaxX - 1), y, 0.0D, 1.0D, 0.0D); - tessellator.addVertexWithUV(scrollBarMinX, y, 0.0D, 0.0D, 0.0D); - - tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - } - } - - private void processMouseEvents() { - if (Mouse.isButtonDown(0)) { - processMouseBown(); - } else { - while (!mc.gameSettings.touchscreen && Mouse.next()) { - - int mouseWheelDelta = Mouse.getEventDWheel(); - - if (mouseWheelDelta != 0) { - if (mouseWheelDelta > 0) { - mouseWheelDelta = -1; - } else if (mouseWheelDelta < 0) { - mouseWheelDelta = 1; - } - amountScrolled += mouseWheelDelta * slotHeight / 2; + tessellator.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); } - } - initialClickY = -1.0F; } - } - - private void processMouseBown() { - int contentHeightOverBounds; - if (initialClickY == -1.0F) { - - 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()) { - boolean doubleClick = mouseOverElement == selectedIndex && Minecraft.getSystemTime() - lastClickedTime < 250L; - if (elementClicked(mouseOverElement, doubleClick)) { - setSelection(mouseOverElement); - } - lastClickedTime = Minecraft.getSystemTime(); - - } else if (mouseX >= minX && mouseX <= maxX && y < 0) { - clickInBounds = false; - } - - int scrollBarMinX = getScrollBarX(); - int scrollBarMaxX = scrollBarMinX + 6; - if (mouseX >= scrollBarMinX && mouseX <= scrollBarMaxX) { - - scrollMultiplier = -1.0F; - contentHeightOverBounds = getContentOverhang(); - - if (contentHeightOverBounds < 1) { - contentHeightOverBounds = 1; - } - - int empty = (int) ((float) ((maxY - minY) * (maxY - minY)) / (float) getContentHeight()); - if (empty < 32) { - empty = 32; - } - if (empty > maxY - minY - 8) { - empty = maxY - minY - 8; - } - scrollMultiplier /= (float) (maxY - minY - empty) / (float) contentHeightOverBounds; + private void processMouseEvents() { + if (Mouse.isButtonDown(0)) { + processMouseBown(); } else { - scrollMultiplier = 1.0F; + while (!mc.gameSettings.touchscreen && Mouse.next()) { + + int mouseWheelDelta = Mouse.getEventDWheel(); + + if (mouseWheelDelta != 0) { + if (mouseWheelDelta > 0) { + mouseWheelDelta = -1; + } else if (mouseWheelDelta < 0) { + mouseWheelDelta = 1; + } + amountScrolled += mouseWheelDelta * slotHeight / 2; + } + } + initialClickY = -1.0F; } - - if (clickInBounds) { - initialClickY = mouseY; - } else { - initialClickY = -2.0F; - } - - } else { - initialClickY = -2.0F; - } - - } else if (initialClickY >= 0.0F) { - // Scrolling - amountScrolled -= (mouseY - initialClickY) * scrollMultiplier; - initialClickY = mouseY; } - } - protected int getScrollBarX() { - return minX + width; - } + private void processMouseBown() { + int contentHeightOverBounds; + if (initialClickY == -1.0F) { - protected void drawContainerBackground(Tessellator tess) { + if (mouseY >= minY && mouseY <= maxY && mouseX >= minX && mouseX <= maxX + 6) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glDisable(GL11.GL_TEXTURE_2D); - tess.startDrawingQuads(); - tess.setColorOpaque_I(2105376); - tess.addVertex(minX, maxY, 0.0D); - tess.addVertex(maxX, maxY, 0.0D); - tess.addVertex(maxX, minY, 0.0D); - tess.addVertex(minX, minY, 0.0D); - tess.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); + 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()) { + boolean doubleClick = mouseOverElement == selectedIndex + && Minecraft.getSystemTime() - lastClickedTime < 250L; + if (elementClicked(mouseOverElement, doubleClick)) { + setSelection(mouseOverElement); + } + lastClickedTime = Minecraft.getSystemTime(); + + } else if (mouseX >= minX && mouseX <= maxX && y < 0) { + clickInBounds = false; + } + + int scrollBarMinX = getScrollBarX(); + int scrollBarMaxX = scrollBarMinX + 6; + if (mouseX >= scrollBarMinX && mouseX <= scrollBarMaxX) { + + scrollMultiplier = -1.0F; + contentHeightOverBounds = getContentOverhang(); + + if (contentHeightOverBounds < 1) { + contentHeightOverBounds = 1; + } + + int empty = (int) ((float) ((maxY - minY) * (maxY - minY)) / (float) getContentHeight()); + if (empty < 32) { + empty = 32; + } + if (empty > maxY - minY - 8) { + empty = maxY - minY - 8; + } + scrollMultiplier /= (float) (maxY - minY - empty) / (float) contentHeightOverBounds; + + } else { + scrollMultiplier = 1.0F; + } + + if (clickInBounds) { + initialClickY = mouseY; + } else { + initialClickY = -2.0F; + } + + } else { + initialClickY = -2.0F; + } + + } else if (initialClickY >= 0.0F) { + // Scrolling + amountScrolled -= (mouseY - initialClickY) * scrollMultiplier; + initialClickY = mouseY; + } + } + + protected int getScrollBarX() { + return minX + width; + } + + protected void drawContainerBackground(Tessellator tess) { + + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glDisable(GL11.GL_TEXTURE_2D); + tess.startDrawingQuads(); + tess.setColorOpaque_I(2105376); + tess.addVertex(minX, maxY, 0.0D); + tess.addVertex(maxX, maxY, 0.0D); + tess.addVertex(maxX, minY, 0.0D); + tess.addVertex(minX, minY, 0.0D); + tess.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + + } } 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 c10adf6..c191c52 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 @@ -1,107 +1,106 @@ package com.enderio.core.client.gui.widget; -import com.enderio.core.api.client.gui.IHideable; - import java.awt.Rectangle; import java.util.ArrayList; import java.util.List; +import com.enderio.core.api.client.gui.IHideable; + public class GuiToolTip implements IHideable { - private static final long DELAY = 0; + private static final long DELAY = 0; - protected Rectangle bounds; + protected Rectangle bounds; - private long mouseOverStart; + private long mouseOverStart; - protected final List text; + protected final List text; - private int lastMouseX = -1; + private int lastMouseX = -1; - private int lastMouseY = -1; + private int lastMouseY = -1; - private boolean visible = true; + private boolean visible = true; - public GuiToolTip(Rectangle bounds, String... lines) { - this.bounds = bounds; - if (lines != null) { - text = new ArrayList(lines.length); - for (String line : lines) { - text.add(line); - } - } else { - text = new ArrayList(); - } - } - - public GuiToolTip(Rectangle bounds, List lines) { - this.bounds = bounds; - if (lines == null) { - text = new ArrayList(); - } else { - text = new ArrayList(lines); - } - } - - public boolean isVisible() { - return visible; - } - - public void setVisible(boolean visible) { - this.visible = visible; - } - - public Rectangle getBounds() { - return bounds; - } - - public void setBounds(Rectangle bounds) { - this.bounds = bounds; - } - - public void onTick(int mouseX, int mouseY) { - if (lastMouseX != mouseX || lastMouseY != mouseY) { - mouseOverStart = 0; + public GuiToolTip(Rectangle bounds, String... lines) { + this.bounds = bounds; + if (lines != null) { + text = new ArrayList(lines.length); + for (String line : lines) { + text.add(line); + } + } else { + text = new ArrayList(); + } } - if (bounds.contains(mouseX, mouseY)) { - - if (mouseOverStart == 0) { - mouseOverStart = System.currentTimeMillis(); - } - } else { - mouseOverStart = 0; + public GuiToolTip(Rectangle bounds, List lines) { + this.bounds = bounds; + if (lines == null) { + text = new ArrayList(); + } else { + text = new ArrayList(lines); + } } - lastMouseX = mouseX; - lastMouseY = mouseY; - } - - public boolean shouldDraw() { - if (!visible) { - return false; + public boolean isVisible() { + return visible; } - updateText(); - if (mouseOverStart == 0) { - return false; + + public void setVisible(boolean visible) { + this.visible = visible; } - return System.currentTimeMillis() - mouseOverStart >= DELAY; - } - protected void updateText() { - } - - public void setToolTipText(String... txt) { - text.clear(); - if (txt != null) { - for (String line : txt) { - text.add(line); - } + public Rectangle getBounds() { + return bounds; } - } - public List getToolTipText() { - return text; - } + public void setBounds(Rectangle bounds) { + this.bounds = bounds; + } + + public void onTick(int mouseX, int mouseY) { + if (lastMouseX != mouseX || lastMouseY != mouseY) { + mouseOverStart = 0; + } + + if (bounds.contains(mouseX, mouseY)) { + + if (mouseOverStart == 0) { + mouseOverStart = System.currentTimeMillis(); + } + } else { + mouseOverStart = 0; + } + + lastMouseX = mouseX; + lastMouseY = mouseY; + } + + public boolean shouldDraw() { + if (!visible) { + return false; + } + updateText(); + if (mouseOverStart == 0) { + return false; + } + return System.currentTimeMillis() - mouseOverStart >= DELAY; + } + + protected void updateText() {} + + public void setToolTipText(String... txt) { + text.clear(); + if (txt != null) { + for (String line : txt) { + text.add(line); + } + } + } + + public List getToolTipText() { + return text; + } } 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 bcb9da6..5f212fc 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 @@ -2,106 +2,118 @@ package com.enderio.core.client.gui.widget; import java.lang.reflect.Field; -import com.enderio.core.api.client.gui.IHideable; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; import com.enderio.core.api.client.gui.IGuiScreen; +import com.enderio.core.api.client.gui.IHideable; import com.google.common.base.Strings; - import cpw.mods.fml.relauncher.ReflectionHelper; public class TextFieldEnder extends GuiTextField implements IHideable { - public interface ICharFilter { + public interface ICharFilter { - boolean passesFilter(TextFieldEnder tf, char c); - } + boolean passesFilter(TextFieldEnder tf, char c); + } + + public static final ICharFilter FILTER_NUMERIC = new ICharFilter() { + + @Override + public boolean passesFilter(TextFieldEnder tf, char c) { + return Character.isDigit(c) || (c == '-' && Strings.isNullOrEmpty(tf.getText())); + } + }; + + public static ICharFilter FILTER_ALPHABETICAL = new ICharFilter() { + + @Override + public boolean passesFilter(TextFieldEnder tf, char c) { + return Character.isLetter(c); + } + }; + + public static ICharFilter FILTER_ALPHANUMERIC = new ICharFilter() { + + @Override + public boolean passesFilter(TextFieldEnder tf, char c) { + return FILTER_NUMERIC.passesFilter(tf, c) || FILTER_ALPHABETICAL.passesFilter(tf, c); + } + }; + + private final int xOrigin; + private final int yOrigin; + private ICharFilter filter; + + private static Field canLoseFocus; + + static { + try { + canLoseFocus = ReflectionHelper.findField(GuiTextField.class, "canLoseFocus", "field_146212_n", "n"); + canLoseFocus.setAccessible(true); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + 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; + this.yOrigin = y; + this.filter = charFilter; + } + + public void init(IGuiScreen gui) { + this.xPosition = xOrigin + gui.getGuiLeft(); + this.yPosition = yOrigin + gui.getGuiTop(); + } + + public TextFieldEnder setCharFilter(ICharFilter filter) { + this.filter = filter; + return this; + } - public static final ICharFilter FILTER_NUMERIC = new ICharFilter() { @Override - public boolean passesFilter(TextFieldEnder tf, char c) { - return Character.isDigit(c) || (c == '-' && Strings.isNullOrEmpty(tf.getText())); + public boolean textboxKeyTyped(char c, int key) { + if (filter == null || filter.passesFilter(this, c) || isSpecialChar(c, key)) { + return super.textboxKeyTyped(c, key); + } + return false; + } + + public static boolean isSpecialChar(char c, int key) { + // taken from the giant switch statement in GuiTextField + return c == 1 || c == 3 + || c == 22 + || c == 24 + || key == 14 + || key == 199 + || key == 203 + || key == 205 + || key == 207 + || key == 211; + } + + public boolean getCanLoseFocus() { + try { + return canLoseFocus.getBoolean(this); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public boolean contains(int x, int y) { + return x >= this.xPosition && x < this.xPosition + this.width + && y >= this.yPosition + && y < this.yPosition + this.height; } - }; - public static ICharFilter FILTER_ALPHABETICAL = new ICharFilter() { @Override - public boolean passesFilter(TextFieldEnder tf, char c) { - return Character.isLetter(c); + public boolean isVisible() { + return super.getVisible(); } - }; - - public static ICharFilter FILTER_ALPHANUMERIC = new ICharFilter() { - @Override - public boolean passesFilter(TextFieldEnder tf, char c) { - return FILTER_NUMERIC.passesFilter(tf, c) || FILTER_ALPHABETICAL.passesFilter(tf, c); - } - }; - - private final int xOrigin; - private final int yOrigin; - private ICharFilter filter; - - private static Field canLoseFocus; - - static { - try { - canLoseFocus = ReflectionHelper.findField(GuiTextField.class, "canLoseFocus", "field_146212_n", "n"); - canLoseFocus.setAccessible(true); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - 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; - this.yOrigin = y; - this.filter = charFilter; - } - - public void init(IGuiScreen gui) { - this.xPosition = xOrigin + gui.getGuiLeft(); - this.yPosition = yOrigin + gui.getGuiTop(); - } - - public TextFieldEnder setCharFilter(ICharFilter filter) { - this.filter = filter; - return this; - } - - @Override - public boolean textboxKeyTyped(char c, int key) { - if (filter == null || filter.passesFilter(this, c) || isSpecialChar(c, key)) { - return super.textboxKeyTyped(c, key); - } - return false; - } - - public static boolean isSpecialChar(char c, int key) { - // taken from the giant switch statement in GuiTextField - return c == 1 || c == 3 || c == 22 || c == 24 || key == 14 || key == 199 || key == 203 || key == 205 || key == 207 || key == 211; - } - - public boolean getCanLoseFocus() { - try { - return canLoseFocus.getBoolean(this); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public boolean contains(int x, int y) { - return x >= this.xPosition && x < this.xPosition + this.width && y >= this.yPosition && y < this.yPosition + this.height; - } - - @Override - public boolean isVisible() { - return super.getVisible(); - } } diff --git a/src/main/java/com/enderio/core/client/gui/widget/VScrollbar.java b/src/main/java/com/enderio/core/client/gui/widget/VScrollbar.java index 50bd4e4..6daa332 100644 --- a/src/main/java/com/enderio/core/client/gui/widget/VScrollbar.java +++ b/src/main/java/com/enderio/core/client/gui/widget/VScrollbar.java @@ -2,205 +2,216 @@ package com.enderio.core.client.gui.widget; import java.awt.Rectangle; -import com.enderio.core.api.client.gui.IHideable; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import org.lwjgl.opengl.GL11; import com.enderio.core.api.client.gui.IGuiScreen; +import com.enderio.core.api.client.gui.IHideable; import com.enderio.core.api.client.render.IWidgetIcon; import com.enderio.core.client.render.EnderWidget; import com.enderio.core.client.render.RenderUtil; public class VScrollbar implements IHideable { - protected final IGuiScreen gui; + protected final IGuiScreen gui; - protected int xOrigin; - protected int yOrigin; - protected int height; + protected int xOrigin; + protected int yOrigin; + protected int height; - protected int xPosition; - protected int yPosition; - protected Rectangle wholeArea; - protected Rectangle btnUp; - protected Rectangle btnDown; - protected Rectangle thumbArea; + protected int xPosition; + protected int yPosition; + protected Rectangle wholeArea; + protected Rectangle btnUp; + protected Rectangle btnDown; + protected Rectangle thumbArea; - protected int scrollPos; - protected int scrollMax; + protected int scrollPos; + protected int scrollMax; - protected boolean pressedUp; - protected boolean pressedDown; - protected boolean pressedThumb; - protected int scrollDir; - protected long timeNextScroll; + protected boolean pressedUp; + protected boolean pressedDown; + protected boolean pressedThumb; + protected int scrollDir; + protected long timeNextScroll; - protected boolean visible = true; + protected boolean visible = true; - public VScrollbar(IGuiScreen gui, int xOrigin, int yOrigin, int height) { - this.gui = gui; - this.xOrigin = xOrigin; - this.yOrigin = yOrigin; - this.height = height; - } + public VScrollbar(IGuiScreen gui, int xOrigin, int yOrigin, int height) { + this.gui = gui; + this.xOrigin = xOrigin; + this.yOrigin = yOrigin; + this.height = height; + } - public void adjustPosition() { - xPosition = xOrigin + gui.getGuiLeft(); - yPosition = yOrigin + gui.getGuiTop(); - wholeArea = new Rectangle(xPosition, yPosition, (int) EnderWidget.VSCROLL_THUMB_OFF.width, height); - btnUp = new Rectangle(xPosition, yPosition, (int) EnderWidget.UP_ARROW_OFF.width, (int) EnderWidget.UP_ARROW_OFF.height); - btnDown = new Rectangle(xPosition, yPosition + Math.max(0, height - (int) EnderWidget.DOWN_ARROW_OFF.height), (int) EnderWidget.DOWN_ARROW_OFF.width, - (int) EnderWidget.DOWN_ARROW_OFF.height); - thumbArea = new Rectangle(xPosition, yPosition + btnUp.height, (int) EnderWidget.VSCROLL_THUMB_OFF.width, Math.max(0, height - - (btnUp.height + btnDown.height))); - } + public void adjustPosition() { + xPosition = xOrigin + gui.getGuiLeft(); + yPosition = yOrigin + gui.getGuiTop(); + wholeArea = new Rectangle(xPosition, yPosition, (int) EnderWidget.VSCROLL_THUMB_OFF.width, height); + btnUp = new Rectangle( + xPosition, + yPosition, + (int) EnderWidget.UP_ARROW_OFF.width, + (int) EnderWidget.UP_ARROW_OFF.height); + btnDown = new Rectangle( + xPosition, + yPosition + Math.max(0, height - (int) EnderWidget.DOWN_ARROW_OFF.height), + (int) EnderWidget.DOWN_ARROW_OFF.width, + (int) EnderWidget.DOWN_ARROW_OFF.height); + thumbArea = new Rectangle( + xPosition, + yPosition + btnUp.height, + (int) EnderWidget.VSCROLL_THUMB_OFF.width, + Math.max(0, height - (btnUp.height + btnDown.height))); + } - public int getScrollPos() { - return scrollPos; - } + public int getScrollPos() { + return scrollPos; + } - public void setScrollPos(int scrollPos) { - this.scrollPos = limitPos(scrollPos); - } + public void setScrollPos(int scrollPos) { + this.scrollPos = limitPos(scrollPos); + } - public void scrollBy(int amount) { - setScrollPos(scrollPos + amount); - } + public void scrollBy(int amount) { + setScrollPos(scrollPos + amount); + } - public int getScrollMax() { - return scrollMax; - } + public int getScrollMax() { + return scrollMax; + } - public void setScrollMax(int scrollMax) { - this.scrollMax = scrollMax; - setScrollPos(scrollPos); - } + public void setScrollMax(int scrollMax) { + this.scrollMax = scrollMax; + setScrollPos(scrollPos); + } - public void drawScrollbar(int mouseX, int mouseY) { - if (visible) { - boolean hoverUp = btnUp.contains(mouseX, mouseY); - boolean hoverDown = btnDown.contains(mouseX, mouseY); + public void drawScrollbar(int mouseX, int mouseY) { + if (visible) { + boolean hoverUp = btnUp.contains(mouseX, mouseY); + boolean hoverDown = btnDown.contains(mouseX, mouseY); - IWidgetIcon iconUp; - if (pressedUp) { - iconUp = hoverUp ? EnderWidget.UP_ARROW_HOVER_ON : EnderWidget.UP_ARROW_ON; - } else { - iconUp = hoverUp ? EnderWidget.UP_ARROW_HOVER_OFF : EnderWidget.UP_ARROW_OFF; - } + IWidgetIcon iconUp; + if (pressedUp) { + iconUp = hoverUp ? EnderWidget.UP_ARROW_HOVER_ON : EnderWidget.UP_ARROW_ON; + } else { + iconUp = hoverUp ? EnderWidget.UP_ARROW_HOVER_OFF : EnderWidget.UP_ARROW_OFF; + } - IWidgetIcon iconDown; - if (pressedDown) { - iconDown = hoverDown ? EnderWidget.DOWN_ARROW_HOVER_ON : EnderWidget.DOWN_ARROW_ON; - } else { - iconDown = hoverDown ? EnderWidget.DOWN_ARROW_HOVER_OFF : EnderWidget.DOWN_ARROW_OFF; - } + IWidgetIcon iconDown; + if (pressedDown) { + iconDown = hoverDown ? EnderWidget.DOWN_ARROW_HOVER_ON : EnderWidget.DOWN_ARROW_ON; + } else { + iconDown = hoverDown ? EnderWidget.DOWN_ARROW_HOVER_OFF : EnderWidget.DOWN_ARROW_OFF; + } - if (scrollDir != 0) { - long time = Minecraft.getSystemTime(); - if ((timeNextScroll - time) <= 0) { - timeNextScroll = time + 100; - scrollBy(scrollDir); + if (scrollDir != 0) { + long time = Minecraft.getSystemTime(); + if ((timeNextScroll - time) <= 0) { + timeNextScroll = time + 100; + scrollBy(scrollDir); + } + } + + RenderUtil.bindTexture(EnderWidget.TEXTURE); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor3f(1, 1, 1); + + Tessellator tes = Tessellator.instance; + tes.startDrawingQuads(); + + iconUp.getMap().render(iconUp, btnUp.x, btnUp.y, false); + iconDown.getMap().render(iconDown, btnDown.x, btnDown.y, false); + + if (scrollMax > 0) { + int thumbPos = getThumbPosition(); + boolean hoverThumb = thumbArea.contains(mouseX, mouseY) && mouseY >= thumbPos + && mouseY < thumbPos + (int) EnderWidget.VSCROLL_THUMB_OFF.height; + + EnderWidget iconThumb; + if (pressedThumb) { + iconThumb = EnderWidget.VSCROLL_THUMB_HOVER_ON; + } else { + iconThumb = hoverThumb ? EnderWidget.VSCROLL_THUMB_HOVER_OFF : EnderWidget.VSCROLL_THUMB_OFF; + } + iconThumb.getMap().render(iconThumb, thumbArea.x, thumbPos, false); + } + + tes.draw(); + GL11.glPopAttrib(); } - } + } - RenderUtil.bindTexture(EnderWidget.TEXTURE); - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor3f(1, 1, 1); + public boolean mouseClicked(int x, int y, int button) { + if (button == 0) { + if (scrollMax > 0 && thumbArea.contains(x, y)) { + int thumbPos = getThumbPosition(); + pressedUp = y < thumbPos; + pressedDown = y >= thumbPos + (int) EnderWidget.VSCROLL_THUMB_OFF.height; + pressedThumb = !pressedUp && !pressedDown; + } else { + pressedUp = btnUp.contains(x, y); + pressedDown = btnDown.contains(x, y); + pressedThumb = false; + } - Tessellator tes = Tessellator.instance; - tes.startDrawingQuads(); + scrollDir = (pressedDown ? 1 : 0) - (pressedUp ? 1 : 0); + if (scrollDir != 0) { + timeNextScroll = Minecraft.getSystemTime() + 200; + scrollBy(scrollDir); + } + } + return isDragActive(); + } - iconUp.getMap().render(iconUp, btnUp.x, btnUp.y, false); - iconDown.getMap().render(iconDown, btnDown.x, btnDown.y, false); - - if (scrollMax > 0) { - int thumbPos = getThumbPosition(); - boolean hoverThumb = thumbArea.contains(mouseX, mouseY) && mouseY >= thumbPos && mouseY < thumbPos + (int) EnderWidget.VSCROLL_THUMB_OFF.height; - - EnderWidget iconThumb; + public boolean mouseClickMove(int x, int y, int button, long time) { if (pressedThumb) { - iconThumb = EnderWidget.VSCROLL_THUMB_HOVER_ON; - } else { - iconThumb = hoverThumb ? EnderWidget.VSCROLL_THUMB_HOVER_OFF : EnderWidget.VSCROLL_THUMB_OFF; + int pos = y - (thumbArea.y + (int) EnderWidget.VSCROLL_THUMB_OFF.height / 2); + int len = thumbArea.height - (int) EnderWidget.VSCROLL_THUMB_OFF.height; + if (len > 0) { + setScrollPos(Math.round(pos * (float) scrollMax / (float) len)); + } + return true; } - iconThumb.getMap().render(iconThumb, thumbArea.x, thumbPos, false); - } - - tes.draw(); - GL11.glPopAttrib(); + return false; } - } - public boolean mouseClicked(int x, int y, int button) { - if (button == 0) { - if (scrollMax > 0 && thumbArea.contains(x, y)) { - int thumbPos = getThumbPosition(); - pressedUp = y < thumbPos; - pressedDown = y >= thumbPos + (int) EnderWidget.VSCROLL_THUMB_OFF.height; - pressedThumb = !pressedUp && !pressedDown; - } else { - pressedUp = btnUp.contains(x, y); - pressedDown = btnDown.contains(x, y); + public void mouseMovedOrUp(int x, int y, int button) { + pressedUp = false; + pressedDown = false; pressedThumb = false; - } - - scrollDir = (pressedDown ? 1 : 0) - (pressedUp ? 1 : 0); - if (scrollDir != 0) { - timeNextScroll = Minecraft.getSystemTime() + 200; - scrollBy(scrollDir); - } + scrollDir = 0; } - return isDragActive(); - } - public boolean mouseClickMove(int x, int y, int button, long time) { - if (pressedThumb) { - int pos = y - (thumbArea.y + (int) EnderWidget.VSCROLL_THUMB_OFF.height / 2); - int len = thumbArea.height - (int) EnderWidget.VSCROLL_THUMB_OFF.height; - if (len > 0) { - setScrollPos(Math.round(pos * (float) scrollMax / (float) len)); - } - return true; + public void mouseWheel(int x, int y, int delta) { + if (!isDragActive() && wholeArea.contains(x, y)) { + scrollBy(-Integer.signum(delta)); + } } - return false; - } - public void mouseMovedOrUp(int x, int y, int button) { - pressedUp = false; - pressedDown = false; - pressedThumb = false; - scrollDir = 0; - } - - public void mouseWheel(int x, int y, int delta) { - if (!isDragActive() && wholeArea.contains(x, y)) { - scrollBy(-Integer.signum(delta)); + public boolean isDragActive() { + return pressedUp || pressedDown || pressedThumb; } - } - public boolean isDragActive() { - return pressedUp || pressedDown || pressedThumb; - } + protected int getThumbPosition() { + return thumbArea.y + (thumbArea.height - (int) EnderWidget.VSCROLL_THUMB_OFF.height) * scrollPos / scrollMax; + } - protected int getThumbPosition() { - return thumbArea.y + (thumbArea.height - (int) EnderWidget.VSCROLL_THUMB_OFF.height) * scrollPos / scrollMax; - } + protected int limitPos(int pos) { + return Math.max(0, Math.min(pos, scrollMax)); + } - protected int limitPos(int pos) { - return Math.max(0, Math.min(pos, scrollMax)); - } + @Override + public void setVisible(boolean visible) { + this.visible = visible; + } - @Override - public void setVisible(boolean visible) { - this.visible = visible; - } - - @Override - public boolean isVisible() { - return this.visible; - } + @Override + public boolean isVisible() { + return this.visible; + } } 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 1368732..7109a5c 100644 --- a/src/main/java/com/enderio/core/client/handlers/ClientHandler.java +++ b/src/main/java/com/enderio/core/client/handlers/ClientHandler.java @@ -9,16 +9,16 @@ import cpw.mods.fml.common.gameevent.TickEvent.Phase; @Handler public class ClientHandler { - private static int ticksElapsed; - - public static int getTicksElapsed() { - return ticksElapsed; - } + private static int ticksElapsed; - @SubscribeEvent - public void onClientTick(ClientTickEvent event) { - if (event.phase == Phase.END) { - ticksElapsed++; + public static int getTicksElapsed() { + return 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 b6c5270..6c40170 100644 --- a/src/main/java/com/enderio/core/client/handlers/EnchantTooltipHandler.java +++ b/src/main/java/com/enderio/core/client/handlers/EnchantTooltipHandler.java @@ -10,31 +10,35 @@ import net.minecraftforge.event.entity.player.ItemTooltipEvent; import com.enderio.core.api.common.enchant.IAdvancedEnchant; 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); - for (Integer integer : enchantments.keySet()) { - Enchantment enchant = Enchantment.enchantmentsList[integer]; + @SuppressWarnings("unchecked") + @SubscribeEvent + public void handleTooltip(ItemTooltipEvent event) { + if (event.itemStack.hasTagCompound()) { + Map enchantments = EnchantmentHelper.getEnchantments(event.itemStack); - 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 d694a46..dfe97ec 100644 --- a/src/main/java/com/enderio/core/client/handlers/OreDictTooltipHandler.java +++ b/src/main/java/com/enderio/core/client/handlers/OreDictTooltipHandler.java @@ -1,5 +1,7 @@ package com.enderio.core.client.handlers; +import static com.enderio.core.common.config.ConfigHandler.*; + import net.minecraft.client.Minecraft; import net.minecraft.item.Item; import net.minecraftforge.event.entity.player.ItemTooltipEvent; @@ -9,33 +11,33 @@ import org.lwjgl.input.Keyboard; import com.enderio.core.EnderCore; import com.enderio.core.common.Handlers.Handler; - 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; - if (doRegistry) { - event.toolTip.add(Item.itemRegistry.getNameForObject(event.itemStack.getItem())); - } + @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 (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 f9c3e68..c78de99 100644 --- a/src/main/java/com/enderio/core/client/handlers/SpecialTooltipHandler.java +++ b/src/main/java/com/enderio/core/client/handlers/SpecialTooltipHandler.java @@ -1,5 +1,7 @@ package com.enderio.core.client.handlers; +import static com.enderio.core.common.config.ConfigHandler.showDurabilityTooltips; + import java.util.ArrayList; import java.util.List; @@ -24,177 +26,186 @@ import com.enderio.core.api.client.gui.IResourceTooltipProvider; import com.enderio.core.common.Handlers.Handler; import com.enderio.core.common.util.ItemUtil; import com.google.common.collect.Lists; - import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import static com.enderio.core.common.config.ConfigHandler.showDurabilityTooltips; - @Handler public enum SpecialTooltipHandler { - INSTANCE; - - public interface ITooltipCallback extends IAdvancedTooltipProvider { - boolean shouldHandleItem(ItemStack item); - } - private final List callbacks = Lists.newArrayList(); + INSTANCE; - public void addCallback(ITooltipCallback callback) { - callbacks.add(callback); - } + public interface ITooltipCallback extends IAdvancedTooltipProvider { - @SubscribeEvent - public void addTooltip(ItemTooltipEvent evt) { - if (evt.itemStack == null) { - return; + boolean shouldHandleItem(ItemStack item); } - boolean shiftDown = showAdvancedTooltips(); - boolean debugMode = Minecraft.getMinecraft().gameSettings.advancedItemTooltips; - boolean doDurability = showDurabilityTooltips == 3 ? debugMode : showDurabilityTooltips == 2 ? shiftDown : showDurabilityTooltips == 1; + private final List callbacks = Lists.newArrayList(); - if (doDurability) { - addDurabilityTooltip(evt.toolTip, evt.itemStack); + public void addCallback(ITooltipCallback callback) { + callbacks.add(callback); } - 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) { - addInformation((IResourceTooltipProvider) evt.itemStack.getItem(), evt); - return; + @SubscribeEvent + public void addTooltip(ItemTooltipEvent evt) { + if (evt.itemStack == null) { + return; + } + + boolean shiftDown = showAdvancedTooltips(); + boolean debugMode = Minecraft.getMinecraft().gameSettings.advancedItemTooltips; + boolean doDurability = showDurabilityTooltips == 3 ? debugMode + : showDurabilityTooltips == 2 ? shiftDown : showDurabilityTooltips == 1; + + if (doDurability) { + addDurabilityTooltip(evt.toolTip, evt.itemStack); + } + + 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) { + addInformation((IResourceTooltipProvider) evt.itemStack.getItem(), evt); + return; + } + + Block blk = Block.getBlockFromItem(evt.itemStack.getItem()); + if (blk instanceof IAdvancedTooltipProvider) { + addInformation((IAdvancedTooltipProvider) blk, evt.itemStack, evt.entityPlayer, evt.toolTip, false); + return; + } 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); + } + } } - Block blk = Block.getBlockFromItem(evt.itemStack.getItem()); - if (blk instanceof IAdvancedTooltipProvider) { - addInformation((IAdvancedTooltipProvider) blk, evt.itemStack, evt.entityPlayer, evt.toolTip, false); - return; - } else if (blk instanceof IResourceTooltipProvider) { - addInformation((IResourceTooltipProvider) blk, evt); - return; + public void addDurabilityTooltip(List toolTip, ItemStack itemStack) { + if (!itemStack.isItemStackDamageable()) { + return; + } + Item item = itemStack.getItem(); + if (item instanceof ItemTool || item instanceof ItemArmor + || item instanceof ItemSword + || item instanceof ItemHoe + || item instanceof ItemBow) { + toolTip.add(ItemUtil.getDurabilityString(itemStack)); + } } - for (ITooltipCallback callback : callbacks) { - if (callback.shouldHandleItem(evt.itemStack)) { - addInformation(callback, evt.itemStack, evt.entityPlayer, evt.toolTip, false); - } + public void addInformation(IResourceTooltipProvider item, ItemTooltipEvent evt) { + addInformation(item, evt.itemStack, evt.entityPlayer, evt.toolTip); } - } - public void addDurabilityTooltip(List toolTip, ItemStack itemStack) { - if (!itemStack.isItemStackDamageable()) { - return; + public void addInformation(IResourceTooltipProvider tt, ItemStack itemstack, EntityPlayer entityplayer, List list) { + String name = tt.getUnlocalizedNameForTooltip(itemstack); + if (showAdvancedTooltips()) { + addCommonTooltipFromResources(list, name); + addDetailedTooltipFromResources(list, name); + } else { + addBasicTooltipFromResources(list, name); + addCommonTooltipFromResources(list, name); + if (hasDetailedTooltip(tt, itemstack)) { + addShowDetailsTooltip(list); + } + } } - Item item = itemStack.getItem(); - if (item instanceof ItemTool || item instanceof ItemArmor || item instanceof ItemSword || item instanceof ItemHoe || item instanceof ItemBow) { - toolTip.add(ItemUtil.getDurabilityString(itemStack)); + + public void addInformation(IAdvancedTooltipProvider tt, ItemStack itemstack, EntityPlayer entityplayer, List list, + boolean flag) { + tt.addCommonEntries(itemstack, entityplayer, list, flag); + if (showAdvancedTooltips()) { + tt.addDetailedEntries(itemstack, entityplayer, list, flag); + } else { + tt.addBasicEntries(itemstack, entityplayer, list, flag); + if (hasDetailedTooltip(tt, itemstack, entityplayer, flag)) { + addShowDetailsTooltip(list); + } + } } - } - public void addInformation(IResourceTooltipProvider item, ItemTooltipEvent evt) { - addInformation(item, evt.itemStack, evt.entityPlayer, evt.toolTip); - } + private static final List throwaway = new ArrayList(); - public void addInformation(IResourceTooltipProvider tt, ItemStack itemstack, EntityPlayer entityplayer, List list) { - String name = tt.getUnlocalizedNameForTooltip(itemstack); - if (showAdvancedTooltips()) { - addCommonTooltipFromResources(list, name); - addDetailedTooltipFromResources(list, name); - } else { - addBasicTooltipFromResources(list, name); - addCommonTooltipFromResources(list, name); - if (hasDetailedTooltip(tt, itemstack)) { - addShowDetailsTooltip(list); - } + private static boolean hasDetailedTooltip(IResourceTooltipProvider tt, ItemStack stack) { + throwaway.clear(); + String name = tt.getUnlocalizedNameForTooltip(stack); + addDetailedTooltipFromResources(throwaway, name); + return !throwaway.isEmpty(); } - } - public void addInformation(IAdvancedTooltipProvider tt, ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { - tt.addCommonEntries(itemstack, entityplayer, list, flag); - if (showAdvancedTooltips()) { - tt.addDetailedEntries(itemstack, entityplayer, list, flag); - } else { - tt.addBasicEntries(itemstack, entityplayer, list, flag); - if (hasDetailedTooltip(tt, itemstack, entityplayer, flag)) { - addShowDetailsTooltip(list); - } + private static boolean hasDetailedTooltip(IAdvancedTooltipProvider tt, ItemStack stack, EntityPlayer player, + boolean flag) { + throwaway.clear(); + tt.addDetailedEntries(stack, player, throwaway, flag); + return !throwaway.isEmpty(); } - } - private static final List throwaway = new ArrayList(); - - private static boolean hasDetailedTooltip(IResourceTooltipProvider tt, ItemStack stack) { - throwaway.clear(); - String name = tt.getUnlocalizedNameForTooltip(stack); - addDetailedTooltipFromResources(throwaway, name); - return !throwaway.isEmpty(); - } - - private static boolean hasDetailedTooltip(IAdvancedTooltipProvider tt, ItemStack stack, EntityPlayer player, boolean flag) { - throwaway.clear(); - tt.addDetailedEntries(stack, player, throwaway, flag); - return !throwaway.isEmpty(); - } - - public static void addShowDetailsTooltip(List list) { - list.add(EnumChatFormatting.WHITE + "" + EnumChatFormatting.ITALIC + EnderCore.lang.localize("tooltip.showDetails")); - } - - public static boolean showAdvancedTooltips() { - return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - } - - public static void addDetailedTooltipFromResources(List list, String unlocalizedName) { - addTooltipFromResources(list, unlocalizedName.concat(".tooltip.detailed.line")); - } - - public static void addBasicTooltipFromResources(List list, String unlocalizedName) { - addTooltipFromResources(list, unlocalizedName.concat(".tooltip.basic.line")); - } - - public static void addCommonTooltipFromResources(List list, String unlocalizedName) { - addTooltipFromResources(list, unlocalizedName.concat(".tooltip.common.line")); - } - - public static void addTooltipFromResources(List list, String keyBase) { - boolean done = false; - int line = 1; - while (!done) { - String key = keyBase + line; - String val = EnderCore.lang.localizeExact(key); - if (val == null || val.trim().length() < 0 || val.equals(key) || line > 12) { - done = true; - } else { - list.add(val); - line++; - } + public static void addShowDetailsTooltip(List list) { + list.add( + EnumChatFormatting.WHITE + "" + + EnumChatFormatting.ITALIC + + EnderCore.lang.localize("tooltip.showDetails")); } - } - private static String getUnlocalizedNameForTooltip(ItemStack itemstack) { - String unlocalizedNameForTooltip = null; - if (itemstack.getItem() instanceof IResourceTooltipProvider) { - unlocalizedNameForTooltip = ((IResourceTooltipProvider) itemstack.getItem()).getUnlocalizedNameForTooltip(itemstack); + public static boolean showAdvancedTooltips() { + return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); } - if (unlocalizedNameForTooltip == null) { - unlocalizedNameForTooltip = itemstack.getItem().getUnlocalizedName(itemstack); - } - return unlocalizedNameForTooltip; - } - public static void addCommonTooltipFromResources(List list, ItemStack itemstack) { - if (itemstack.getItem() == null) { - return; + public static void addDetailedTooltipFromResources(List list, String unlocalizedName) { + addTooltipFromResources(list, unlocalizedName.concat(".tooltip.detailed.line")); } - addCommonTooltipFromResources(list, getUnlocalizedNameForTooltip(itemstack)); - } - public static void addDetailedTooltipFromResources(List list, ItemStack itemstack) { - if (itemstack.getItem() == null) { - return; + public static void addBasicTooltipFromResources(List list, String unlocalizedName) { + addTooltipFromResources(list, unlocalizedName.concat(".tooltip.basic.line")); + } + + public static void addCommonTooltipFromResources(List list, String unlocalizedName) { + addTooltipFromResources(list, unlocalizedName.concat(".tooltip.common.line")); + } + + public static void addTooltipFromResources(List list, String keyBase) { + boolean done = false; + int line = 1; + while (!done) { + String key = keyBase + line; + String val = EnderCore.lang.localizeExact(key); + if (val == null || val.trim().length() < 0 || val.equals(key) || line > 12) { + done = true; + } else { + list.add(val); + line++; + } + } + } + + private static String getUnlocalizedNameForTooltip(ItemStack itemstack) { + String unlocalizedNameForTooltip = null; + if (itemstack.getItem() instanceof IResourceTooltipProvider) { + unlocalizedNameForTooltip = ((IResourceTooltipProvider) itemstack.getItem()) + .getUnlocalizedNameForTooltip(itemstack); + } + if (unlocalizedNameForTooltip == null) { + unlocalizedNameForTooltip = itemstack.getItem().getUnlocalizedName(itemstack); + } + return unlocalizedNameForTooltip; + } + + public static void addCommonTooltipFromResources(List list, ItemStack itemstack) { + if (itemstack.getItem() == null) { + return; + } + addCommonTooltipFromResources(list, getUnlocalizedNameForTooltip(itemstack)); + } + + public static void addDetailedTooltipFromResources(List list, ItemStack itemstack) { + if (itemstack.getItem() == null) { + return; + } + addDetailedTooltipFromResources(list, getUnlocalizedNameForTooltip(itemstack)); } - 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 dd38501..5efcc31 100644 --- a/src/main/java/com/enderio/core/client/render/BoundingBox.java +++ b/src/main/java/com/enderio/core/client/render/BoundingBox.java @@ -3,6 +3,10 @@ package com.enderio.core.client.render; import java.util.ArrayList; import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.util.AxisAlignedBB; +import net.minecraftforge.common.util.ForgeDirection; + import com.enderio.core.api.client.render.VertexTransform; import com.enderio.core.common.util.BlockCoord; import com.enderio.core.common.vecmath.Vector2f; @@ -10,371 +14,400 @@ import com.enderio.core.common.vecmath.Vector3d; import com.enderio.core.common.vecmath.Vector3f; import com.enderio.core.common.vecmath.Vertex; -import net.minecraft.block.Block; -import net.minecraft.util.AxisAlignedBB; -import net.minecraftforge.common.util.ForgeDirection; - public final class BoundingBox { - public static final BoundingBox UNIT_CUBE = new BoundingBox(0, 0, 0, 1, 1, 1); + public static final BoundingBox UNIT_CUBE = new BoundingBox(0, 0, 0, 1, 1, 1); - public final float minX; - public final float minY; - public final float minZ; - public final float maxX; - public final float maxY; - public final float maxZ; + public final float minX; + public final float minY; + public final float minZ; + public final float maxX; + public final float maxY; + public final float maxZ; - 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; - this.minZ = minZ; - this.maxX = maxX; - this.maxY = maxY; - this.maxZ = maxZ; - } - - public BoundingBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { - this.minX = (float) minX; - this.minY = (float) minY; - this.minZ = (float) minZ; - this.maxX = (float) maxX; - this.maxY = (float) maxY; - this.maxZ = (float) maxZ; - } - - public BoundingBox(Vector3d min, Vector3d max) { - this(min.x, min.y, min.z, max.x, max.y, max.z); - } - - public BoundingBox(BoundingBox copy) { - this(copy.minX, copy.minY, copy.minZ, copy.maxX, copy.maxY, copy.maxZ); - } - - public BoundingBox(BlockCoord bc) { - this(bc.x, bc.y, bc.z, bc.x + 1, bc.y + 1, bc.z + 1); - } - - public BoundingBox(Block block) { - 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)); - } - - public boolean contains(BoundingBox other) { - return minX >= other.minX && minY <= other.minY && minZ <= other.minZ && maxX >= other.maxX && maxY <= other.maxY && maxZ <= other.maxZ; - } - - public boolean intersects(BoundingBox other) { - return other.maxX > this.minX && other.minX < this.maxX ? (other.maxY > this.minY && other.minY < this.maxY ? other.maxZ > this.minZ - && other.minZ < this.maxZ : false) : false; - } - - public boolean isValid() { - return minX < maxX && minY < maxY && minZ < maxZ; - } - - public BoundingBox scale(double x, double y, double z) { - return scale((float) x, (float) y, (float) z); - } - - public BoundingBox scale(float x, float y, float z) { - x = 1 - x; - y = 1 - y; - z = 1 - z; - float w = ((maxX - minX) * x) / 2; - float h = ((maxY - minY) * y) / 2; - float d = ((maxZ - minZ) * z) / 2; - return new BoundingBox(minX + w, minY + h, minZ + d, maxX - w, maxY - h, maxZ - d); - } - - public BoundingBox translate(float x, float y, float z) { - return new BoundingBox(minX + x, minY + y, minZ + z, maxX + x, maxY + y, maxZ + z); - } - - public BoundingBox translate(Vector3d translation) { - return translate((float) translation.x, (float) translation.y, (float) translation.z); - } - - public BoundingBox translate(Vector3f vec) { - return translate(vec.x, vec.y, vec.z); - } - - public BoundingBox transform(VertexTransform iTransformation) { - Vector3d min = new Vector3d(minX, minY, minZ); - Vector3d max = new Vector3d(maxX, maxY, maxZ); - - 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)); - - } - - /** - * Returns the vertices of the corners for the specified face in counter - * clockwise order. - */ - public List getCornersWithUvForFace(ForgeDirection face) { - return getCornersWithUvForFace(face, 0, 1, 0, 1); - } - - /** - * Returns the vertices of the corners for the specified face in counter - * clockwise order. - */ - public List getCornersWithUvForFace(ForgeDirection face, float minU, float maxU, float minV, float maxV) { - List result = new ArrayList(4); - switch (face) { - case NORTH: - result.add(new Vertex(new Vector3d(maxX, minY, minZ), new Vector3f(0, 0, -1), new Vector2f(minU, minV))); - result.add(new Vertex(new Vector3d(minX, minY, minZ), new Vector3f(0, 0, -1), new Vector2f(maxU, minV))); - result.add(new Vertex(new Vector3d(minX, maxY, minZ), new Vector3f(0, 0, -1), new Vector2f(maxU, maxV))); - result.add(new Vertex(new Vector3d(maxX, maxY, minZ), new Vector3f(0, 0, -1), new Vector2f(minU, maxV))); - break; - case SOUTH: - result.add(new Vertex(new Vector3d(minX, minY, maxZ), new Vector3f(0, 0, 1), new Vector2f(maxU, minV))); - result.add(new Vertex(new Vector3d(maxX, minY, maxZ), new Vector3f(0, 0, 1), new Vector2f(minU, minV))); - result.add(new Vertex(new Vector3d(maxX, maxY, maxZ), new Vector3f(0, 0, 1), new Vector2f(minU, maxV))); - result.add(new Vertex(new Vector3d(minX, maxY, maxZ), new Vector3f(0, 0, 1), new Vector2f(maxU, maxV))); - break; - case EAST: - result.add(new Vertex(new Vector3d(maxX, maxY, minZ), new Vector3f(1, 0, 0), new Vector2f(maxU, maxV))); - result.add(new Vertex(new Vector3d(maxX, maxY, maxZ), new Vector3f(1, 0, 0), new Vector2f(minU, maxV))); - result.add(new Vertex(new Vector3d(maxX, minY, maxZ), new Vector3f(1, 0, 0), new Vector2f(minU, minV))); - result.add(new Vertex(new Vector3d(maxX, minY, minZ), new Vector3f(1, 0, 0), new Vector2f(maxU, minV))); - break; - case WEST: - result.add(new Vertex(new Vector3d(minX, minY, minZ), new Vector3f(-1, 0, 0), new Vector2f(maxU, minV))); - result.add(new Vertex(new Vector3d(minX, minY, maxZ), new Vector3f(-1, 0, 0), new Vector2f(minU, minV))); - result.add(new Vertex(new Vector3d(minX, maxY, maxZ), new Vector3f(-1, 0, 0), new Vector2f(minU, maxV))); - result.add(new Vertex(new Vector3d(minX, maxY, minZ), new Vector3f(-1, 0, 0), new Vector2f(maxU, maxV))); - break; - case UP: - result.add(new Vertex(new Vector3d(maxX, maxY, maxZ), new Vector3f(0, 1, 0), new Vector2f(minU, minV))); - result.add(new Vertex(new Vector3d(maxX, maxY, minZ), new Vector3f(0, 1, 0), new Vector2f(minU, maxV))); - result.add(new Vertex(new Vector3d(minX, maxY, minZ), new Vector3f(0, 1, 0), new Vector2f(maxU, maxV))); - result.add(new Vertex(new Vector3d(minX, maxY, maxZ), new Vector3f(0, 1, 0), new Vector2f(maxU, minV))); - break; - case DOWN: // - case UNKNOWN: - default: - result.add(new Vertex(new Vector3d(minX, minY, minZ), new Vector3f(0, -1, 0), new Vector2f(maxU, maxV))); - result.add(new Vertex(new Vector3d(maxX, minY, minZ), new Vector3f(0, -1, 0), new Vector2f(minU, maxV))); - result.add(new Vertex(new Vector3d(maxX, minY, maxZ), new Vector3f(0, -1, 0), new Vector2f(minU, minV))); - result.add(new Vertex(new Vector3d(minX, minY, maxZ), new Vector3f(0, -1, 0), new Vector2f(maxU, minV))); - break; + public BoundingBox(AxisAlignedBB bb) { + this(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); } - return result; - } - /** - * Returns the vertices of the corners for the specified face in counter - * clockwise order, starting with the top left. - */ - public List getCornersForFace(ForgeDirection face) { - List result = new ArrayList(4); - switch (face) { - case NORTH: - result.add(new Vector3f(minX, maxY, minZ)); - result.add(new Vector3f(maxX, maxY, minZ)); - result.add(new Vector3f(maxX, minY, minZ)); - result.add(new Vector3f(minX, minY, minZ)); - break; - case SOUTH: - result.add(new Vector3f(minX, maxY, maxZ)); - result.add(new Vector3f(minX, minY, maxZ)); - result.add(new Vector3f(maxX, minY, maxZ)); - result.add(new Vector3f(maxX, maxY, maxZ)); - break; - case EAST: - result.add(new Vector3f(maxX, minY, maxZ)); - result.add(new Vector3f(maxX, minY, minZ)); - result.add(new Vector3f(maxX, maxY, minZ)); - result.add(new Vector3f(maxX, maxY, maxZ)); - break; - case WEST: - result.add(new Vector3f(minX, maxY, maxZ)); - result.add(new Vector3f(minX, maxY, minZ)); - result.add(new Vector3f(minX, minY, minZ)); - result.add(new Vector3f(minX, minY, maxZ)); - break; - case UP: - result.add(new Vector3f(maxX, maxY, maxZ)); - result.add(new Vector3f(maxX, maxY, minZ)); - result.add(new Vector3f(minX, maxY, minZ)); - result.add(new Vector3f(minX, maxY, maxZ)); - break; - case DOWN: - case UNKNOWN: - default: - result.add(new Vector3f(minX, minY, maxZ)); - result.add(new Vector3f(minX, minY, minZ)); - result.add(new Vector3f(maxX, minY, minZ)); - result.add(new Vector3f(maxX, minY, maxZ)); - break; + public BoundingBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { + this.minX = minX; + this.minY = minY; + this.minZ = minZ; + this.maxX = maxX; + this.maxY = maxY; + this.maxZ = maxZ; } - return result; - } - /** - * Returns the vertices of the corners for the specified face in counter - * clockwise order, starting with the top left. - */ - public List getCornersForFaceD(ForgeDirection face) { - List result = new ArrayList(4); - switch (face) { - case NORTH: - result.add(new Vector3d(minX, maxY, minZ)); - result.add(new Vector3d(maxX, maxY, minZ)); - result.add(new Vector3d(maxX, minY, minZ)); - result.add(new Vector3d(minX, minY, minZ)); - break; - case SOUTH: - result.add(new Vector3d(minX, maxY, maxZ)); - result.add(new Vector3d(minX, minY, maxZ)); - result.add(new Vector3d(maxX, minY, maxZ)); - result.add(new Vector3d(maxX, maxY, maxZ)); - break; - case EAST: - result.add(new Vector3d(maxX, minY, maxZ)); - result.add(new Vector3d(maxX, minY, minZ)); - result.add(new Vector3d(maxX, maxY, minZ)); - result.add(new Vector3d(maxX, maxY, maxZ)); - break; - case WEST: - result.add(new Vector3d(minX, maxY, maxZ)); - result.add(new Vector3d(minX, maxY, minZ)); - result.add(new Vector3d(minX, minY, minZ)); - result.add(new Vector3d(minX, minY, maxZ)); - break; - case UP: - result.add(new Vector3d(maxX, maxY, maxZ)); - result.add(new Vector3d(maxX, maxY, minZ)); - result.add(new Vector3d(minX, maxY, minZ)); - result.add(new Vector3d(minX, maxY, maxZ)); - break; - case DOWN: - case UNKNOWN: - default: - result.add(new Vector3d(minX, minY, maxZ)); - result.add(new Vector3d(minX, minY, minZ)); - result.add(new Vector3d(maxX, minY, minZ)); - result.add(new Vector3d(maxX, minY, maxZ)); - break; + public BoundingBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + this.minX = (float) minX; + this.minY = (float) minY; + this.minZ = (float) minZ; + this.maxX = (float) maxX; + this.maxY = (float) maxY; + this.maxZ = (float) maxZ; } - return result; - } - public Vector3d getCenter() { - return new Vector3d(minX + (maxX - minX) / 2, minY + (maxY - minY) / 2, minZ + (maxZ - minZ) / 2); - } - - public float sizeX() { - return Math.abs(maxX - minX); - } - - public float sizeY() { - return Math.abs(maxY - minY); - } - - public float sizeZ() { - return Math.abs(maxZ - minZ); - } - - public Vector3d getMin() { - return new Vector3d(minX, minY, minZ); - } - - public Vector3d getMax() { - return new Vector3d(maxX, maxY, maxZ); - } - - public float getArea() { - return sizeX() * sizeY() * sizeZ(); - } - - @Override - public String toString() { - return "BoundingBox [minX=" + minX + ", minY=" + minY + ", minZ=" + minZ + ", maxX=" + maxX + ", maxY=" + maxY + ", maxZ=" + maxZ + "]"; - } - - public BoundingBox fixMinMax() { - float mnX = minX; - float mnY = minY; - float mnZ = minZ; - float mxX = maxX; - float mxY = maxY; - float mxZ = maxZ; - boolean mod = false; - if (minX > maxX) { - mnX = maxX; - mxX = minX; - mod = true; + public BoundingBox(Vector3d min, Vector3d max) { + this(min.x, min.y, min.z, max.x, max.y, max.z); } - if (minY > maxY) { - mnY = maxY; - mxY = minY; - mod = true; - } - if (minZ > maxZ) { - mnZ = maxZ; - mxZ = minZ; - mod = true; - } - if (!mod) { - return this; - } - return new BoundingBox(mnX, mnY, mnZ, mxX, mxY, mxZ); - } - public AxisAlignedBB getAxisAlignedBB() { - return AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); - } + public BoundingBox(BoundingBox copy) { + this(copy.minX, copy.minY, copy.minZ, copy.maxX, copy.maxY, copy.maxZ); + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Float.floatToIntBits(maxX); - result = prime * result + Float.floatToIntBits(maxY); - result = prime * result + Float.floatToIntBits(maxZ); - result = prime * result + Float.floatToIntBits(minX); - result = prime * result + Float.floatToIntBits(minY); - result = prime * result + Float.floatToIntBits(minZ); - return result; - } + public BoundingBox(BlockCoord bc) { + this(bc.x, bc.y, bc.z, bc.x + 1, bc.y + 1, bc.z + 1); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - BoundingBox other = (BoundingBox) obj; - if (Float.floatToIntBits(maxX) != Float.floatToIntBits(other.maxX)) - return false; - if (Float.floatToIntBits(maxY) != Float.floatToIntBits(other.maxY)) - return false; - if (Float.floatToIntBits(maxZ) != Float.floatToIntBits(other.maxZ)) - return false; - if (Float.floatToIntBits(minX) != Float.floatToIntBits(other.minX)) - return false; - if (Float.floatToIntBits(minY) != Float.floatToIntBits(other.minY)) - return false; - if (Float.floatToIntBits(minZ) != Float.floatToIntBits(other.minZ)) - return false; - return true; - } + public BoundingBox(Block block) { + 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)); + } + + public boolean contains(BoundingBox other) { + return minX >= other.minX && minY <= other.minY + && minZ <= other.minZ + && maxX >= other.maxX + && maxY <= other.maxY + && maxZ <= other.maxZ; + } + + public boolean intersects(BoundingBox other) { + return other.maxX > this.minX && other.minX < this.maxX + ? (other.maxY > this.minY && other.minY < this.maxY ? other.maxZ > this.minZ && other.minZ < this.maxZ + : false) + : false; + } + + public boolean isValid() { + return minX < maxX && minY < maxY && minZ < maxZ; + } + + public BoundingBox scale(double x, double y, double z) { + return scale((float) x, (float) y, (float) z); + } + + public BoundingBox scale(float x, float y, float z) { + x = 1 - x; + y = 1 - y; + z = 1 - z; + float w = ((maxX - minX) * x) / 2; + float h = ((maxY - minY) * y) / 2; + float d = ((maxZ - minZ) * z) / 2; + return new BoundingBox(minX + w, minY + h, minZ + d, maxX - w, maxY - h, maxZ - d); + } + + public BoundingBox translate(float x, float y, float z) { + return new BoundingBox(minX + x, minY + y, minZ + z, maxX + x, maxY + y, maxZ + z); + } + + public BoundingBox translate(Vector3d translation) { + return translate((float) translation.x, (float) translation.y, (float) translation.z); + } + + public BoundingBox translate(Vector3f vec) { + return translate(vec.x, vec.y, vec.z); + } + + public BoundingBox transform(VertexTransform iTransformation) { + Vector3d min = new Vector3d(minX, minY, minZ); + Vector3d max = new Vector3d(maxX, maxY, maxZ); + + 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)); + + } + + /** + * Returns the vertices of the corners for the specified face in counter clockwise order. + */ + public List getCornersWithUvForFace(ForgeDirection face) { + return getCornersWithUvForFace(face, 0, 1, 0, 1); + } + + /** + * Returns the vertices of the corners for the specified face in counter clockwise order. + */ + public List getCornersWithUvForFace(ForgeDirection face, float minU, float maxU, float minV, float maxV) { + List result = new ArrayList(4); + switch (face) { + case NORTH: + result.add( + new Vertex(new Vector3d(maxX, minY, minZ), new Vector3f(0, 0, -1), new Vector2f(minU, minV))); + result.add( + new Vertex(new Vector3d(minX, minY, minZ), new Vector3f(0, 0, -1), new Vector2f(maxU, minV))); + result.add( + new Vertex(new Vector3d(minX, maxY, minZ), new Vector3f(0, 0, -1), new Vector2f(maxU, maxV))); + result.add( + new Vertex(new Vector3d(maxX, maxY, minZ), new Vector3f(0, 0, -1), new Vector2f(minU, maxV))); + break; + case SOUTH: + result.add(new Vertex(new Vector3d(minX, minY, maxZ), new Vector3f(0, 0, 1), new Vector2f(maxU, minV))); + result.add(new Vertex(new Vector3d(maxX, minY, maxZ), new Vector3f(0, 0, 1), new Vector2f(minU, minV))); + result.add(new Vertex(new Vector3d(maxX, maxY, maxZ), new Vector3f(0, 0, 1), new Vector2f(minU, maxV))); + result.add(new Vertex(new Vector3d(minX, maxY, maxZ), new Vector3f(0, 0, 1), new Vector2f(maxU, maxV))); + break; + case EAST: + result.add(new Vertex(new Vector3d(maxX, maxY, minZ), new Vector3f(1, 0, 0), new Vector2f(maxU, maxV))); + result.add(new Vertex(new Vector3d(maxX, maxY, maxZ), new Vector3f(1, 0, 0), new Vector2f(minU, maxV))); + result.add(new Vertex(new Vector3d(maxX, minY, maxZ), new Vector3f(1, 0, 0), new Vector2f(minU, minV))); + result.add(new Vertex(new Vector3d(maxX, minY, minZ), new Vector3f(1, 0, 0), new Vector2f(maxU, minV))); + break; + case WEST: + result.add( + new Vertex(new Vector3d(minX, minY, minZ), new Vector3f(-1, 0, 0), new Vector2f(maxU, minV))); + result.add( + new Vertex(new Vector3d(minX, minY, maxZ), new Vector3f(-1, 0, 0), new Vector2f(minU, minV))); + result.add( + new Vertex(new Vector3d(minX, maxY, maxZ), new Vector3f(-1, 0, 0), new Vector2f(minU, maxV))); + result.add( + new Vertex(new Vector3d(minX, maxY, minZ), new Vector3f(-1, 0, 0), new Vector2f(maxU, maxV))); + break; + case UP: + result.add(new Vertex(new Vector3d(maxX, maxY, maxZ), new Vector3f(0, 1, 0), new Vector2f(minU, minV))); + result.add(new Vertex(new Vector3d(maxX, maxY, minZ), new Vector3f(0, 1, 0), new Vector2f(minU, maxV))); + result.add(new Vertex(new Vector3d(minX, maxY, minZ), new Vector3f(0, 1, 0), new Vector2f(maxU, maxV))); + result.add(new Vertex(new Vector3d(minX, maxY, maxZ), new Vector3f(0, 1, 0), new Vector2f(maxU, minV))); + break; + case DOWN: // + case UNKNOWN: + default: + result.add( + new Vertex(new Vector3d(minX, minY, minZ), new Vector3f(0, -1, 0), new Vector2f(maxU, maxV))); + result.add( + new Vertex(new Vector3d(maxX, minY, minZ), new Vector3f(0, -1, 0), new Vector2f(minU, maxV))); + result.add( + new Vertex(new Vector3d(maxX, minY, maxZ), new Vector3f(0, -1, 0), new Vector2f(minU, minV))); + result.add( + new Vertex(new Vector3d(minX, minY, maxZ), new Vector3f(0, -1, 0), new Vector2f(maxU, minV))); + break; + } + return result; + } + + /** + * Returns the vertices of the corners for the specified face in counter clockwise order, starting with the top + * left. + */ + public List getCornersForFace(ForgeDirection face) { + List result = new ArrayList(4); + switch (face) { + case NORTH: + result.add(new Vector3f(minX, maxY, minZ)); + result.add(new Vector3f(maxX, maxY, minZ)); + result.add(new Vector3f(maxX, minY, minZ)); + result.add(new Vector3f(minX, minY, minZ)); + break; + case SOUTH: + result.add(new Vector3f(minX, maxY, maxZ)); + result.add(new Vector3f(minX, minY, maxZ)); + result.add(new Vector3f(maxX, minY, maxZ)); + result.add(new Vector3f(maxX, maxY, maxZ)); + break; + case EAST: + result.add(new Vector3f(maxX, minY, maxZ)); + result.add(new Vector3f(maxX, minY, minZ)); + result.add(new Vector3f(maxX, maxY, minZ)); + result.add(new Vector3f(maxX, maxY, maxZ)); + break; + case WEST: + result.add(new Vector3f(minX, maxY, maxZ)); + result.add(new Vector3f(minX, maxY, minZ)); + result.add(new Vector3f(minX, minY, minZ)); + result.add(new Vector3f(minX, minY, maxZ)); + break; + case UP: + result.add(new Vector3f(maxX, maxY, maxZ)); + result.add(new Vector3f(maxX, maxY, minZ)); + result.add(new Vector3f(minX, maxY, minZ)); + result.add(new Vector3f(minX, maxY, maxZ)); + break; + case DOWN: + case UNKNOWN: + default: + result.add(new Vector3f(minX, minY, maxZ)); + result.add(new Vector3f(minX, minY, minZ)); + result.add(new Vector3f(maxX, minY, minZ)); + result.add(new Vector3f(maxX, minY, maxZ)); + break; + } + return result; + } + + /** + * Returns the vertices of the corners for the specified face in counter clockwise order, starting with the top + * left. + */ + public List getCornersForFaceD(ForgeDirection face) { + List result = new ArrayList(4); + switch (face) { + case NORTH: + result.add(new Vector3d(minX, maxY, minZ)); + result.add(new Vector3d(maxX, maxY, minZ)); + result.add(new Vector3d(maxX, minY, minZ)); + result.add(new Vector3d(minX, minY, minZ)); + break; + case SOUTH: + result.add(new Vector3d(minX, maxY, maxZ)); + result.add(new Vector3d(minX, minY, maxZ)); + result.add(new Vector3d(maxX, minY, maxZ)); + result.add(new Vector3d(maxX, maxY, maxZ)); + break; + case EAST: + result.add(new Vector3d(maxX, minY, maxZ)); + result.add(new Vector3d(maxX, minY, minZ)); + result.add(new Vector3d(maxX, maxY, minZ)); + result.add(new Vector3d(maxX, maxY, maxZ)); + break; + case WEST: + result.add(new Vector3d(minX, maxY, maxZ)); + result.add(new Vector3d(minX, maxY, minZ)); + result.add(new Vector3d(minX, minY, minZ)); + result.add(new Vector3d(minX, minY, maxZ)); + break; + case UP: + result.add(new Vector3d(maxX, maxY, maxZ)); + result.add(new Vector3d(maxX, maxY, minZ)); + result.add(new Vector3d(minX, maxY, minZ)); + result.add(new Vector3d(minX, maxY, maxZ)); + break; + case DOWN: + case UNKNOWN: + default: + result.add(new Vector3d(minX, minY, maxZ)); + result.add(new Vector3d(minX, minY, minZ)); + result.add(new Vector3d(maxX, minY, minZ)); + result.add(new Vector3d(maxX, minY, maxZ)); + break; + } + return result; + } + + public Vector3d getCenter() { + return new Vector3d(minX + (maxX - minX) / 2, minY + (maxY - minY) / 2, minZ + (maxZ - minZ) / 2); + } + + public float sizeX() { + return Math.abs(maxX - minX); + } + + public float sizeY() { + return Math.abs(maxY - minY); + } + + public float sizeZ() { + return Math.abs(maxZ - minZ); + } + + public Vector3d getMin() { + return new Vector3d(minX, minY, minZ); + } + + public Vector3d getMax() { + return new Vector3d(maxX, maxY, maxZ); + } + + public float getArea() { + return sizeX() * sizeY() * sizeZ(); + } + + @Override + public String toString() { + return "BoundingBox [minX=" + minX + + ", minY=" + + minY + + ", minZ=" + + minZ + + ", maxX=" + + maxX + + ", maxY=" + + maxY + + ", maxZ=" + + maxZ + + "]"; + } + + public BoundingBox fixMinMax() { + float mnX = minX; + float mnY = minY; + float mnZ = minZ; + float mxX = maxX; + float mxY = maxY; + float mxZ = maxZ; + boolean mod = false; + if (minX > maxX) { + mnX = maxX; + mxX = minX; + mod = true; + } + if (minY > maxY) { + mnY = maxY; + mxY = minY; + mod = true; + } + if (minZ > maxZ) { + mnZ = maxZ; + mxZ = minZ; + mod = true; + } + if (!mod) { + return this; + } + return new BoundingBox(mnX, mnY, mnZ, mxX, mxY, mxZ); + } + + public AxisAlignedBB getAxisAlignedBB() { + return AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Float.floatToIntBits(maxX); + result = prime * result + Float.floatToIntBits(maxY); + result = prime * result + Float.floatToIntBits(maxZ); + result = prime * result + Float.floatToIntBits(minX); + result = prime * result + Float.floatToIntBits(minY); + result = prime * result + Float.floatToIntBits(minZ); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + BoundingBox other = (BoundingBox) obj; + if (Float.floatToIntBits(maxX) != Float.floatToIntBits(other.maxX)) return false; + if (Float.floatToIntBits(maxY) != Float.floatToIntBits(other.maxY)) return false; + if (Float.floatToIntBits(maxZ) != Float.floatToIntBits(other.maxZ)) return false; + if (Float.floatToIntBits(minX) != Float.floatToIntBits(other.minX)) return false; + if (Float.floatToIntBits(minY) != Float.floatToIntBits(other.minY)) return false; + if (Float.floatToIntBits(minZ) != Float.floatToIntBits(other.minZ)) return false; + return true; + } } diff --git a/src/main/java/com/enderio/core/client/render/ColorUtil.java b/src/main/java/com/enderio/core/client/render/ColorUtil.java index 30e28fa..4846e03 100644 --- a/src/main/java/com/enderio/core/client/render/ColorUtil.java +++ b/src/main/java/com/enderio/core/client/render/ColorUtil.java @@ -9,83 +9,82 @@ import com.enderio.core.common.vecmath.Vector4f; public final class ColorUtil { - public static Vector4f toFloat(Color color) { - float[] rgba = color.getComponents(null); - return new Vector4f(rgba[0], rgba[1], rgba[2], rgba[3]); - } + public static Vector4f toFloat(Color color) { + float[] rgba = color.getComponents(null); + return new Vector4f(rgba[0], rgba[1], rgba[2], rgba[3]); + } - public static Vector3f toFloat(int rgb) { - int r = rgb >> 16 & 255; - int g = rgb >> 8 & 255; - int b = rgb & 255; - return new Vector3f(r / 255F, g / 255F, b / 255F); - } + public static Vector3f toFloat(int rgb) { + int r = rgb >> 16 & 255; + int g = rgb >> 8 & 255; + int b = rgb & 255; + return new Vector3f(r / 255F, g / 255F, b / 255F); + } - public static int getRGB(Color color) { - return getRGB(color.getRed(), color.getGreen(), color.getBlue()); - } + public static int getRGB(Color color) { + return getRGB(color.getRed(), color.getGreen(), color.getBlue()); + } - public static int getRGBA(Color color) { - return getRGBA(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); - } + public static int getRGBA(Color color) { + return getRGBA(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + } - public static int getARGB(Color color) { - return getRGBA(color.getAlpha(), color.getRed(), color.getGreen(), color.getBlue()); - } + public static int getARGB(Color color) { + return getRGBA(color.getAlpha(), color.getRed(), color.getGreen(), color.getBlue()); + } - public static int getRGB(Vector3f rgb) { - return getRGB(rgb.x, rgb.y, rgb.z); - } + public static int getRGB(Vector3f rgb) { + return getRGB(rgb.x, rgb.y, rgb.z); + } - public static int getRGB(float r, float g, float b) { - return getRGB((int) (r * 255), (int) (g * 255), (int) (b * 255)); - } + public static int getRGB(float r, float g, float b) { + return getRGB((int) (r * 255), (int) (g * 255), (int) (b * 255)); + } - public static int getRGBA(Vector4f col) { - return getRGBA(col.x, col.y, col.z, col.w); - } + public static int getRGBA(Vector4f col) { + return getRGBA(col.x, col.y, col.z, col.w); + } - public static int getRGBA(float r, float g, float b, float a) { - return getRGBA((int) (r * 255), (int) (g * 255), (int) (b * 255), (int) (a * 255)); - } + public static int getRGBA(float r, float g, float b, float a) { + return getRGBA((int) (r * 255), (int) (g * 255), (int) (b * 255), (int) (a * 255)); + } - public static int getARGB(float r, float g, float b, float a) { - return getARGB((int) (a * 255), (int) (r * 255), (int) (g * 255), (int) (b * 255)); - } + public static int getARGB(float r, float g, float b, float a) { + return getARGB((int) (a * 255), (int) (r * 255), (int) (g * 255), (int) (b * 255)); + } - public static int getRGB(int r, int g, int b) { - return (r & 0xFF) << 16 | (g & 0xFF) << 8 | (b & 0xFF); - } + public static int getRGB(int r, int g, int b) { + return (r & 0xFF) << 16 | (g & 0xFF) << 8 | (b & 0xFF); + } - public static int getARGB(int r, int g, int b, int a) { - return (a & 0xFF) << 24 | (r & 0xFF) << 16 | (g & 0xFF) << 8 | (b & 0xFF); - } + public static int getARGB(int r, int g, int b, int a) { + return (a & 0xFF) << 24 | (r & 0xFF) << 16 | (g & 0xFF) << 8 | (b & 0xFF); + } - public static int getRGBA(int r, int g, int b, int a) { - return (r & 0xFF) << 24 | (g & 0xFF) << 16 | (b & 0xFF) << 8 | (a & 0xFF); - } + public static int getRGBA(int r, int g, int b, int a) { + return (r & 0xFF) << 24 | (g & 0xFF) << 16 | (b & 0xFF) << 8 | (a & 0xFF); + } - /** - * Turns an int into a glColor4f function - * - * @author Buildcraft team - */ - public static void setGLColorFromInt(int color) { - float red = (color >> 16 & 255) / 255.0F; - float green = (color >> 8 & 255) / 255.0F; - float blue = (color & 255) / 255.0F; - GL11.glColor4f(red, green, blue, 1.0F); - } + /** + * Turns an int into a glColor4f function + * + * @author Buildcraft team + */ + public static void setGLColorFromInt(int color) { + float red = (color >> 16 & 255) / 255.0F; + float green = (color >> 8 & 255) / 255.0F; + float blue = (color & 255) / 255.0F; + GL11.glColor4f(red, green, blue, 1.0F); + } - public static int toHex(int r, int g, int b) { - int hex = 0; - hex = hex | ((r) << 16); - hex = hex | ((g) << 8); - hex = hex | ((b)); - return hex; - } + public static int toHex(int r, int g, int b) { + int hex = 0; + hex = hex | ((r) << 16); + hex = hex | ((g) << 8); + hex = hex | ((b)); + return hex; + } - private ColorUtil() { - } + private ColorUtil() {} } 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 decd064..81cedbf 100644 --- a/src/main/java/com/enderio/core/client/render/ConnectedTextureRenderer.java +++ b/src/main/java/com/enderio/core/client/render/ConnectedTextureRenderer.java @@ -4,6 +4,12 @@ import java.util.ArrayList; import java.util.EnumSet; import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.IIcon; +import net.minecraft.world.IBlockAccess; +import net.minecraftforge.common.util.ForgeDirection; + import com.enderio.core.api.client.render.IConnectedTextureRenderer; import com.enderio.core.api.client.render.IRenderFace; import com.enderio.core.common.util.BlockCoord; @@ -13,325 +19,322 @@ import com.enderio.core.common.vecmath.Vector3d; import com.enderio.core.common.vecmath.Vector4f; import com.enderio.core.common.vecmath.Vertex; -import net.minecraft.block.Block; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.util.IIcon; -import net.minecraft.world.IBlockAccess; -import net.minecraftforge.common.util.ForgeDirection; - public class ConnectedTextureRenderer implements IRenderFace, IConnectedTextureRenderer { - public static interface TextureCallback { - public IIcon getTextureForFace(ForgeDirection dir); - } + public static interface TextureCallback { - public static class DefaultTextureCallback implements TextureCallback { - - private final IIcon tex; - - private final Block block; - private final int meta; - - public DefaultTextureCallback(IIcon borderTex) { - this.tex = borderTex; - block = null; - meta = 0; + public IIcon getTextureForFace(ForgeDirection dir); } - public DefaultTextureCallback(Block block, int meta) { - tex = null; - this.block = block; - this.meta = meta; + public static class DefaultTextureCallback implements TextureCallback { + + private final IIcon tex; + + private final Block block; + private final int meta; + + public DefaultTextureCallback(IIcon borderTex) { + this.tex = borderTex; + block = null; + meta = 0; + } + + public DefaultTextureCallback(Block block, int meta) { + tex = null; + this.block = block; + this.meta = meta; + } + + @Override + public IIcon getTextureForFace(ForgeDirection dir) { + if (tex != null) { + return tex; + } + if (block != null) { + return block.getIcon(dir.ordinal(), meta); + } + return null; + } + + } + + private boolean forceAllEdges = false; + + private TextureCallback edgeTexureCallback; + + private boolean matchMetaData; + + private EnumSet sidesToRender = EnumSet.allOf(ForgeDirection.class); + + public boolean isForceAllEdges() { + return forceAllEdges; + } + + public void setForceAllEdges(boolean forceAllEdges) { + this.forceAllEdges = forceAllEdges; + } + + public TextureCallback getEdgeTexureCallback() { + return edgeTexureCallback; + } + + public void setEdgeTexureCallback(TextureCallback edgeTexureCallback) { + this.edgeTexureCallback = edgeTexureCallback; + } + + public void setEdgeTexture(IIcon texture) { + if (texture == null) { + edgeTexureCallback = null; + return; + } + edgeTexureCallback = new DefaultTextureCallback(texture); + } + + public void setMatchMeta(boolean matchMetaData) { + this.matchMetaData = matchMetaData; + } + + public void setSidesToRender(EnumSet sides) { + sidesToRender = sides.clone(); } @Override - public IIcon getTextureForFace(ForgeDirection dir) { - if (tex != null) { - return tex; - } - if (block != null) { - return block.getIcon(dir.ordinal(), meta); - } - return null; + public boolean matchesMetadata(int meta1, int meta2) { + return !this.matchMetaData || meta1 == meta2; } - } + @Override + public void renderFace(CustomRenderBlocks rb, ForgeDirection face, Block par1Block, double x, double y, double z, + IIcon texture, List refVertices, boolean translateToXYZ) { - private boolean forceAllEdges = false; - - private TextureCallback edgeTexureCallback; - - private boolean matchMetaData; - - private EnumSet sidesToRender = EnumSet.allOf(ForgeDirection.class); - - public boolean isForceAllEdges() { - return forceAllEdges; - } - - public void setForceAllEdges(boolean forceAllEdges) { - this.forceAllEdges = forceAllEdges; - } - - public TextureCallback getEdgeTexureCallback() { - return edgeTexureCallback; - } - - public void setEdgeTexureCallback(TextureCallback edgeTexureCallback) { - this.edgeTexureCallback = edgeTexureCallback; - } - - public void setEdgeTexture(IIcon texture) { - if (texture == null) { - edgeTexureCallback = null; - return; - } - edgeTexureCallback = new DefaultTextureCallback(texture); - } - - public void setMatchMeta(boolean 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; - } - - @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; - } - - List finalVerts = new ArrayList(); - finalVerts.addAll(refVertices); - - IIcon borderTex = edgeTexureCallback == null ? null : edgeTexureCallback.getTextureForFace(face); - if (borderTex != null) { - - texture = borderTex; - List edges; - if (forceAllEdges) { - edges = RenderUtil.getEdgesForFace(face); - } else { - edges = RenderUtil.getNonConectedEdgesForFace(rb.blockAccess, (int) x, (int) y, (int) z, face, this); - } - - List allEdges = RenderUtil.getEdgesForFace(face); - - float scaleFactor = 15f / 16f; - Vector2f uv = new Vector2f(); - - //for each that needs a border, add a geom for the border and move in the 'centre' of the face - //so there is no overlap - for (ForgeDirection edge : edges) { - - //We need to move the 'centre' of the face so it doesn't overlap with the border - moveCorners(refVertices, edge, 1 - scaleFactor); - - //Now create the geometry for this edge of the border - 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(); - - BoundingBox bb = BoundingBox.UNIT_CUBE.scale(xLen, yLen, zLen); - - List corners = bb.getCornersForFaceD(face); - for (Vector3d corner : corners) { - if (translateToXYZ) { - corner.x += x; - corner.y += y; - corner.z += z; - } - corner.x += (float) (edge.offsetX * 0.5) - Math.signum(edge.offsetX) * xLen / 2f; - corner.y += (float) (edge.offsetY * 0.5) - Math.signum(edge.offsetY) * yLen / 2f; - corner.z += (float) (edge.offsetZ * 0.5) - Math.signum(edge.offsetZ) * zLen / 2f; + if (!sidesToRender.contains(face)) { + return; } - int[] indices = new int[] { 0, 1, 2, 3 }; - for (int index : indices) { - Vector3d corner = corners.get(index); - if (translateToXYZ) { - RenderUtil.getUvForCorner(uv, corner, (int) x, (int) y, (int) z, face, texture); - } else { - RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture); - } - Vertex vertex = new Vertex(); - vertex.xyz.set(corner); - //vertex.xyz.add(ForgeDirectionOffsets.offsetScaled(face, 0.00005)); - vertex.uv = new Vector2f(uv); - applyLighting(vertex, corner, refVertices); - finalVerts.add(vertex); + List finalVerts = new ArrayList(); + finalVerts.addAll(refVertices); + + IIcon borderTex = edgeTexureCallback == null ? null : edgeTexureCallback.getTextureForFace(face); + if (borderTex != null) { + + texture = borderTex; + List edges; + if (forceAllEdges) { + edges = RenderUtil.getEdgesForFace(face); + } else { + edges = RenderUtil.getNonConectedEdgesForFace(rb.blockAccess, (int) x, (int) y, (int) z, face, this); + } + + List allEdges = RenderUtil.getEdgesForFace(face); + + float scaleFactor = 15f / 16f; + Vector2f uv = new Vector2f(); + + // for each that needs a border, add a geom for the border and move in the 'centre' of the face + // so there is no overlap + for (ForgeDirection edge : edges) { + + // We need to move the 'centre' of the face so it doesn't overlap with the border + moveCorners(refVertices, edge, 1 - scaleFactor); + + // Now create the geometry for this edge of the border + 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(); + + BoundingBox bb = BoundingBox.UNIT_CUBE.scale(xLen, yLen, zLen); + + List corners = bb.getCornersForFaceD(face); + for (Vector3d corner : corners) { + if (translateToXYZ) { + corner.x += x; + corner.y += y; + corner.z += z; + } + corner.x += (float) (edge.offsetX * 0.5) - Math.signum(edge.offsetX) * xLen / 2f; + corner.y += (float) (edge.offsetY * 0.5) - Math.signum(edge.offsetY) * yLen / 2f; + corner.z += (float) (edge.offsetZ * 0.5) - Math.signum(edge.offsetZ) * zLen / 2f; + } + + int[] indices = new int[] { 0, 1, 2, 3 }; + for (int index : indices) { + Vector3d corner = corners.get(index); + if (translateToXYZ) { + RenderUtil.getUvForCorner(uv, corner, (int) x, (int) y, (int) z, face, texture); + } else { + RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture); + } + Vertex vertex = new Vertex(); + vertex.xyz.set(corner); + // vertex.xyz.add(ForgeDirectionOffsets.offsetScaled(face, 0.00005)); + vertex.uv = new Vector2f(uv); + applyLighting(vertex, corner, refVertices); + finalVerts.add(vertex); + } + } + + 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)) { + + Vertex v = new Vertex(); + v.uv = new Vector2f(); + v.xyz.set(ForgeDirectionOffsets.forDir(dir)); + v.xyz.add(ForgeDirectionOffsets.forDir(dir2)); + // TODO: dodgy hack to just move the corner forward a bit + v.xyz.add(ForgeDirectionOffsets.offsetScaled(face, 0.001f)); + 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)) { + v.xyz.add(ForgeDirectionOffsets.forDir(face)); + } + + if (translateToXYZ) { + v.xyz.x += x; + v.xyz.y += y; + v.xyz.z += z; + RenderUtil.getUvForCorner(v.uv, v.xyz, (int) x, (int) y, (int) z, face, texture); + } else { + RenderUtil.getUvForCorner(v.uv, v.xyz, 0, 0, 0, face, texture); + } + applyLighting(v, v.xyz, refVertices); + + finalVerts.add(v); + + Vector3d corner = new Vector3d(v.xyz); + 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); + } else { + addVertexForCorner(face, x, y, z, texture, translateToXYZ, finalVerts, dir, null, corner); + addVertexForCorner(face, x, y, z, texture, translateToXYZ, finalVerts, dir, dir2, corner); + addVertexForCorner(face, x, y, z, texture, translateToXYZ, finalVerts, dir2, null, corner); + } + } + } } - } - 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)) { + RenderUtil.addVerticesToTessellator(finalVerts, Tessellator.instance); + } - Vertex v = new Vertex(); - v.uv = new Vector2f(); - v.xyz.set(ForgeDirectionOffsets.forDir(dir)); - v.xyz.add(ForgeDirectionOffsets.forDir(dir2)); - //TODO: dodgy hack to just move the corner forward a bit - v.xyz.add(ForgeDirectionOffsets.offsetScaled(face, 0.001f)); - 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)) { - v.xyz.add(ForgeDirectionOffsets.forDir(face)); - } - - if (translateToXYZ) { - v.xyz.x += x; - v.xyz.y += y; - v.xyz.z += z; - RenderUtil.getUvForCorner(v.uv, v.xyz, (int) x, (int) y, (int) z, face, texture); - } else { - RenderUtil.getUvForCorner(v.uv, v.xyz, 0, 0, 0, face, texture); - } - applyLighting(v, v.xyz, refVertices); - - finalVerts.add(v); - - Vector3d corner = new Vector3d(v.xyz); - 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); - } else { - addVertexForCorner(face, x, y, z, texture, translateToXYZ, finalVerts, dir, null, corner); - addVertexForCorner(face, x, y, z, texture, translateToXYZ, finalVerts, dir, dir2, corner); - addVertexForCorner(face, x, y, z, texture, translateToXYZ, finalVerts, dir2, null, corner); - } + private Vertex getClosestVertex(List vertices, Vector3d corner) { + Vertex result = null; + double d2 = Double.MAX_VALUE; + for (Vertex v : vertices) { + double tmp = corner.distanceSquared(v.xyz); + if (tmp <= d2) { + result = v; + d2 = tmp; + } } - } + return result; } - RenderUtil.addVerticesToTessellator(finalVerts, Tessellator.instance); - } - - private Vertex getClosestVertex(List vertices, Vector3d corner) { - Vertex result = null; - double d2 = Double.MAX_VALUE; - for (Vertex v : vertices) { - double tmp = corner.distanceSquared(v.xyz); - if (tmp <= d2) { - result = v; - d2 = tmp; - } - } - return result; - } - - private void addVertexForCorner(ForgeDirection face, double x, double y, double z, IIcon texture, boolean translateToXYZ, List vertices, - ForgeDirection dir, ForgeDirection dir2, Vector3d corner) { - float scale = 1 / 16f; - Vertex vert = new Vertex(); - vert.uv = new Vector2f(); - vert.xyz.set(corner); - vert.xyz.sub(ForgeDirectionOffsets.offsetScaled(dir, scale)); - if (dir2 != null) { - vert.xyz.sub(ForgeDirectionOffsets.offsetScaled(dir2, scale)); - } - 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); - } - applyLighting(vert, corner, vertices); - vertices.add(vert); - } - - private void applyLighting(Vertex vert, Vector3d samplePoint, List litVertices) { - Vertex closest = getClosestVertex(litVertices, samplePoint); - if (closest == null) { - return; - } - vert.setBrightness(closest.brightness); - Vector4f col = closest.getColor(); - if (col != null) { - vert.setColor(col); - } - } - - 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)) { - 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)) { - return true; - } - testLoc = bc.getLocation(dir2); - if (RenderUtil.getNonConectedEdgesForFace(blockAccess, testLoc.x, testLoc.y, testLoc.z, face, this).contains(dir)) { - return true; - } - return false; - } - - private void moveCorners(List vertices, ForgeDirection edge, float scaleFactor) { - int[] indices = getClosest(edge, vertices); - if (indices[0] < 0) { - return; - } - vertices.get(indices[0]).xyz.x -= scaleFactor * edge.offsetX; - vertices.get(indices[1]).xyz.x -= scaleFactor * edge.offsetX; - vertices.get(indices[0]).xyz.y -= scaleFactor * edge.offsetY; - vertices.get(indices[1]).xyz.y -= scaleFactor * edge.offsetY; - vertices.get(indices[0]).xyz.z -= scaleFactor * edge.offsetZ; - vertices.get(indices[1]).xyz.z -= scaleFactor * edge.offsetZ; - } - - private int[] getClosest(ForgeDirection edge, List vertices) { - int[] res = new int[] { -1, -1 }; - boolean highest = edge.offsetX > 0 || edge.offsetY > 0 || edge.offsetZ > 0; - double minMax = highest ? -Double.MAX_VALUE : Double.MAX_VALUE; - int index = 0; - for (Vertex v : vertices) { - double val = get(v.xyz, edge); - if (highest ? val >= minMax : val <= minMax) { - if (val != minMax) { - res[0] = index; + private void addVertexForCorner(ForgeDirection face, double x, double y, double z, IIcon texture, + boolean translateToXYZ, List vertices, ForgeDirection dir, ForgeDirection dir2, Vector3d corner) { + float scale = 1 / 16f; + Vertex vert = new Vertex(); + vert.uv = new Vector2f(); + vert.xyz.set(corner); + vert.xyz.sub(ForgeDirectionOffsets.offsetScaled(dir, scale)); + if (dir2 != null) { + vert.xyz.sub(ForgeDirectionOffsets.offsetScaled(dir2, scale)); + } + if (translateToXYZ) { + RenderUtil.getUvForCorner(vert.uv, vert.xyz, (int) x, (int) y, (int) z, face, texture); } else { - res[1] = index; + RenderUtil.getUvForCorner(vert.uv, vert.xyz, 0, 0, 0, face, texture); } - minMax = val; - } - index++; + applyLighting(vert, corner, vertices); + vertices.add(vert); } - return res; - } - private double get(Vector3d xyz, ForgeDirection edge) { - if (edge == ForgeDirection.EAST || edge == ForgeDirection.WEST) { - return xyz.x; + private void applyLighting(Vertex vert, Vector3d samplePoint, List litVertices) { + Vertex closest = getClosestVertex(litVertices, samplePoint); + if (closest == null) { + return; + } + vert.setBrightness(closest.brightness); + Vector4f col = closest.getColor(); + if (col != null) { + vert.setColor(col); + } } - if (edge == ForgeDirection.UP || edge == ForgeDirection.DOWN) { - return xyz.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)) { + 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)) { + return true; + } + testLoc = bc.getLocation(dir2); + if (RenderUtil.getNonConectedEdgesForFace(blockAccess, testLoc.x, testLoc.y, testLoc.z, face, this) + .contains(dir)) { + return true; + } + return false; + } + + private void moveCorners(List vertices, ForgeDirection edge, float scaleFactor) { + int[] indices = getClosest(edge, vertices); + if (indices[0] < 0) { + return; + } + vertices.get(indices[0]).xyz.x -= scaleFactor * edge.offsetX; + vertices.get(indices[1]).xyz.x -= scaleFactor * edge.offsetX; + vertices.get(indices[0]).xyz.y -= scaleFactor * edge.offsetY; + vertices.get(indices[1]).xyz.y -= scaleFactor * edge.offsetY; + vertices.get(indices[0]).xyz.z -= scaleFactor * edge.offsetZ; + vertices.get(indices[1]).xyz.z -= scaleFactor * edge.offsetZ; + } + + private int[] getClosest(ForgeDirection edge, List vertices) { + int[] res = new int[] { -1, -1 }; + boolean highest = edge.offsetX > 0 || edge.offsetY > 0 || edge.offsetZ > 0; + double minMax = highest ? -Double.MAX_VALUE : Double.MAX_VALUE; + int index = 0; + for (Vertex v : vertices) { + double val = get(v.xyz, edge); + if (highest ? val >= minMax : val <= minMax) { + if (val != minMax) { + res[0] = index; + } else { + res[1] = index; + } + minMax = val; + } + index++; + } + return res; + } + + private double get(Vector3d xyz, ForgeDirection edge) { + if (edge == ForgeDirection.EAST || edge == ForgeDirection.WEST) { + return xyz.x; + } + if (edge == ForgeDirection.UP || edge == ForgeDirection.DOWN) { + return xyz.y; + } + return xyz.z; } - 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 5e1aebe..1a9e5db 100644 --- a/src/main/java/com/enderio/core/client/render/CubeRenderer.java +++ b/src/main/java/com/enderio/core/client/render/CubeRenderer.java @@ -1,337 +1,341 @@ package com.enderio.core.client.render; -import com.enderio.core.api.client.render.VertexTransform; -import com.enderio.core.common.vecmath.Vector3d; - import net.minecraft.block.Block; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; +import com.enderio.core.api.client.render.VertexTransform; +import com.enderio.core.common.vecmath.Vector3d; + public final class CubeRenderer { - public static final Vector3d[] verts = new Vector3d[8]; - static { - for (int i = 0; i < verts.length; i++) { - verts[i] = new Vector3d(); - } - } - - 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) { - 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); - } - - public static void render(BoundingBox bb, IIcon tex, boolean tintSides) { - render(bb, tex, null, tintSides); - } - - 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) { - minU = tex.getMinU(); - minV = tex.getMinV(); - maxU = tex.getMaxU(); - maxV = tex.getMaxV(); - } - render(bb, minU, maxU, minV, maxV, xForm, brightnessPerSide, tintSides); - } - - public static void render(BoundingBox bb, IIcon tex, VertexTransform xForm, boolean tintSides) { - float minU = 0; - float minV = 0; - float maxU = 1; - float maxV = 1; - if (tex != null) { - minU = tex.getMinU(); - minV = tex.getMinV(); - maxU = tex.getMaxU(); - maxV = tex.getMaxV(); - } - render(bb, minU, maxU, minV, maxV, xForm, tintSides); - } - - public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, boolean tintSides) { - render(bb, minU, maxU, minV, maxV, null, tintSides); - } - - public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV) { - render(bb, minU, maxU, minV, maxV, null, false); - } - - public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm) { - render(bb, minU, maxU, minV, maxV, xForm, false); - } - - public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm, boolean tintSides) { - float[] brightnessPerSide = null; - if (tintSides) { - brightnessPerSide = new float[6]; - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { - brightnessPerSide[dir.ordinal()] = RenderUtil.getColorMultiplierForFace(dir); - } - } - render(bb, minU, maxU, minV, maxV, xForm, brightnessPerSide); - } - - 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) { - brightnessPerSide = new float[] { 1, 1, 1, 1, 1, 1 }; - } - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { - brightnessPerSide[dir.ordinal()] = brightnessPerSide[dir.ordinal()] * RenderUtil.getColorMultiplierForFace(dir); - } - - } - render(bb, minU, maxU, minV, maxV, xForm, brightnessPerSide); - } - - public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm, float[] brightnessPerSide) { - - if (brightnessPerSide != null && brightnessPerSide.length != 6) { - brightnessPerSide = null; + public static final Vector3d[] verts = new Vector3d[8]; + static { + for (int i = 0; i < verts.length; i++) { + verts[i] = new Vector3d(); + } } - setupVertices(bb, xForm); - - float tmp = minV; - minV = maxV; - maxV = tmp; - - Tessellator tessellator = Tessellator.instance; - - tessellator.setNormal(0, 0, -1); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.NORTH.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); - } - addVecWithUV(verts[1], minU, minV); - addVecWithUV(verts[0], maxU, minV); - addVecWithUV(verts[3], maxU, maxV); - addVecWithUV(verts[2], minU, maxV); - - tessellator.setNormal(0, 0, 1); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.SOUTH.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); - } - addVecWithUV(verts[4], minU, minV); - addVecWithUV(verts[5], maxU, minV); - addVecWithUV(verts[6], maxU, maxV); - addVecWithUV(verts[7], minU, maxV); - - tessellator.setNormal(0, 1, 0); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.UP.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); - } - addVecWithUV(verts[6], minU, minV); - addVecWithUV(verts[2], minU, maxV); - addVecWithUV(verts[3], maxU, maxV); - addVecWithUV(verts[7], maxU, minV); - - tessellator.setNormal(0, -1, 0); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.DOWN.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); - } - addVecWithUV(verts[0], maxU, maxV); - addVecWithUV(verts[1], minU, maxV); - addVecWithUV(verts[5], minU, minV); - addVecWithUV(verts[4], maxU, minV); - - tessellator.setNormal(1, 0, 0); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.EAST.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); - } - addVecWithUV(verts[2], minU, maxV); - addVecWithUV(verts[6], maxU, maxV); - addVecWithUV(verts[5], maxU, minV); - addVecWithUV(verts[1], minU, minV); - - tessellator.setNormal(-1, 0, 0); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.WEST.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); - } - addVecWithUV(verts[0], minU, minV); - addVecWithUV(verts[4], maxU, minV); - addVecWithUV(verts[7], maxU, maxV); - addVecWithUV(verts[3], minU, maxV); - } - - public static void render(BoundingBox bb, IIcon[] icons, boolean tintSides) { - float[] brightnessPerSide = null; - 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) { - brightnessPerSide = new float[6]; - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { - brightnessPerSide[dir.ordinal()] = RenderUtil.getColorMultiplierForFace(dir); - } - } - render(bb, icons, xForm, brightnessPerSide); - } - - public static void render(BoundingBox bb, IIcon[] faceTextures, VertexTransform xForm, float[] brightnessPerSide) { - setupVertices(bb, xForm); - float minU; - float maxU; - float minV; - float maxV; - IIcon tex; - - Tessellator tessellator = Tessellator.instance; - - tessellator.setNormal(0, 0, -1); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.NORTH.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); + public static void render(Block block, int meta) { + render(block, meta, null); } - tex = faceTextures[ForgeDirection.NORTH.ordinal()]; - minU = tex.getMinU(); - maxU = tex.getMaxU(); - minV = tex.getMinV(); - maxV = tex.getMaxV(); - addVecWithUV(verts[1], minU, maxV); - addVecWithUV(verts[0], maxU, maxV); - addVecWithUV(verts[3], maxU, minV); - addVecWithUV(verts[2], minU, minV); - - tessellator.setNormal(0, 0, 1); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.SOUTH.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); + public static void render(Block block, int meta, VertexTransform xForm) { + IIcon[] icons = new IIcon[6]; + 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); } - tex = faceTextures[ForgeDirection.SOUTH.ordinal()]; - minU = tex.getMinU(); - maxU = tex.getMaxU(); - minV = tex.getMinV(); - maxV = tex.getMaxV(); - addVecWithUV(verts[4], minU, maxV); - addVecWithUV(verts[5], maxU, maxV); - addVecWithUV(verts[6], maxU, minV); - addVecWithUV(verts[7], minU, minV); - tessellator.setNormal(0, 1, 0); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.UP.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); + public static void render(BoundingBox bb, IIcon tex) { + render(bb, tex, null, false); } - tex = faceTextures[ForgeDirection.UP.ordinal()]; - minU = tex.getMinU(); - maxU = tex.getMaxU(); - minV = tex.getMinV(); - maxV = tex.getMaxV(); - addVecWithUV(verts[6], minU, minV); - addVecWithUV(verts[2], minU, maxV); - addVecWithUV(verts[3], maxU, maxV); - addVecWithUV(verts[7], maxU, minV); - tessellator.setNormal(0, -1, 0); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.DOWN.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); + public static void render(BoundingBox bb, IIcon tex, boolean tintSides) { + render(bb, tex, null, tintSides); } - tex = faceTextures[ForgeDirection.DOWN.ordinal()]; - minU = tex.getMinU(); - maxU = tex.getMaxU(); - minV = tex.getMinV(); - maxV = tex.getMaxV(); - addVecWithUV(verts[0], maxU, maxV); - addVecWithUV(verts[1], minU, maxV); - addVecWithUV(verts[5], minU, minV); - addVecWithUV(verts[4], maxU, minV); - tessellator.setNormal(1, 0, 0); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.EAST.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); + public static void render(BoundingBox bb, IIcon tex, VertexTransform xForm) { + render(bb, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), xForm, false); } - tex = faceTextures[ForgeDirection.EAST.ordinal()]; - minU = tex.getMinU(); - maxU = tex.getMaxU(); - minV = tex.getMinV(); - maxV = tex.getMaxV(); - addVecWithUV(verts[2], minU, minV); - addVecWithUV(verts[6], maxU, minV); - addVecWithUV(verts[5], maxU, maxV); - addVecWithUV(verts[1], minU, maxV); - tessellator.setNormal(-1, 0, 0); - if (brightnessPerSide != null) { - float cm = brightnessPerSide[ForgeDirection.WEST.ordinal()]; - tessellator.setColorOpaque_F(cm, cm, cm); + 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) { + minU = tex.getMinU(); + minV = tex.getMinV(); + maxU = tex.getMaxU(); + maxV = tex.getMaxV(); + } + render(bb, minU, maxU, minV, maxV, xForm, brightnessPerSide, tintSides); } - tex = faceTextures[ForgeDirection.WEST.ordinal()]; - minU = tex.getMinU(); - maxU = tex.getMaxU(); - minV = tex.getMinV(); - maxV = tex.getMaxV(); - addVecWithUV(verts[0], minU, maxV); - addVecWithUV(verts[4], maxU, maxV); - addVecWithUV(verts[7], maxU, minV); - addVecWithUV(verts[3], minU, minV); - } - public static void setupVertices(BoundingBox bound) { - setupVertices(bound, null); - } - - public static void setupVertices(BoundingBox bound, VertexTransform xForm) { - verts[0].set(bound.minX, bound.minY, bound.minZ); - verts[1].set(bound.maxX, bound.minY, bound.minZ); - verts[2].set(bound.maxX, bound.maxY, bound.minZ); - verts[3].set(bound.minX, bound.maxY, bound.minZ); - verts[4].set(bound.minX, bound.minY, bound.maxZ); - verts[5].set(bound.maxX, bound.minY, bound.maxZ); - verts[6].set(bound.maxX, bound.maxY, bound.maxZ); - verts[7].set(bound.minX, bound.maxY, bound.maxZ); - - if (xForm != null) { - for (Vector3d vec : verts) { - xForm.apply(vec); - } + public static void render(BoundingBox bb, IIcon tex, VertexTransform xForm, boolean tintSides) { + float minU = 0; + float minV = 0; + float maxU = 1; + float maxV = 1; + if (tex != null) { + minU = tex.getMinU(); + minV = tex.getMinV(); + maxU = tex.getMaxU(); + maxV = tex.getMaxV(); + } + render(bb, minU, maxU, minV, maxV, xForm, tintSides); } - } - public static void addVecWithUV(Vector3d vec, double u, double v) { - Tessellator.instance.addVertexWithUV(vec.x, vec.y, vec.z, u, v); - } + public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, boolean tintSides) { + render(bb, minU, maxU, minV, maxV, null, tintSides); + } - private CubeRenderer() { - } + public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV) { + render(bb, minU, maxU, minV, maxV, null, false); + } + + public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm) { + render(bb, minU, maxU, minV, maxV, xForm, false); + } + + public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm, + boolean tintSides) { + float[] brightnessPerSide = null; + if (tintSides) { + brightnessPerSide = new float[6]; + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + brightnessPerSide[dir.ordinal()] = RenderUtil.getColorMultiplierForFace(dir); + } + } + render(bb, minU, maxU, minV, maxV, xForm, brightnessPerSide); + } + + 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) { + brightnessPerSide = new float[] { 1, 1, 1, 1, 1, 1 }; + } + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + brightnessPerSide[dir.ordinal()] = brightnessPerSide[dir.ordinal()] + * RenderUtil.getColorMultiplierForFace(dir); + } + + } + render(bb, minU, maxU, minV, maxV, xForm, brightnessPerSide); + } + + public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm, + float[] brightnessPerSide) { + + if (brightnessPerSide != null && brightnessPerSide.length != 6) { + brightnessPerSide = null; + } + + setupVertices(bb, xForm); + + float tmp = minV; + minV = maxV; + maxV = tmp; + + Tessellator tessellator = Tessellator.instance; + + tessellator.setNormal(0, 0, -1); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.NORTH.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + addVecWithUV(verts[1], minU, minV); + addVecWithUV(verts[0], maxU, minV); + addVecWithUV(verts[3], maxU, maxV); + addVecWithUV(verts[2], minU, maxV); + + tessellator.setNormal(0, 0, 1); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.SOUTH.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + addVecWithUV(verts[4], minU, minV); + addVecWithUV(verts[5], maxU, minV); + addVecWithUV(verts[6], maxU, maxV); + addVecWithUV(verts[7], minU, maxV); + + tessellator.setNormal(0, 1, 0); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.UP.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + addVecWithUV(verts[6], minU, minV); + addVecWithUV(verts[2], minU, maxV); + addVecWithUV(verts[3], maxU, maxV); + addVecWithUV(verts[7], maxU, minV); + + tessellator.setNormal(0, -1, 0); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.DOWN.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + addVecWithUV(verts[0], maxU, maxV); + addVecWithUV(verts[1], minU, maxV); + addVecWithUV(verts[5], minU, minV); + addVecWithUV(verts[4], maxU, minV); + + tessellator.setNormal(1, 0, 0); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.EAST.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + addVecWithUV(verts[2], minU, maxV); + addVecWithUV(verts[6], maxU, maxV); + addVecWithUV(verts[5], maxU, minV); + addVecWithUV(verts[1], minU, minV); + + tessellator.setNormal(-1, 0, 0); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.WEST.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + addVecWithUV(verts[0], minU, minV); + addVecWithUV(verts[4], maxU, minV); + addVecWithUV(verts[7], maxU, maxV); + addVecWithUV(verts[3], minU, maxV); + } + + public static void render(BoundingBox bb, IIcon[] icons, boolean tintSides) { + float[] brightnessPerSide = null; + 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) { + brightnessPerSide = new float[6]; + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + brightnessPerSide[dir.ordinal()] = RenderUtil.getColorMultiplierForFace(dir); + } + } + render(bb, icons, xForm, brightnessPerSide); + } + + public static void render(BoundingBox bb, IIcon[] faceTextures, VertexTransform xForm, float[] brightnessPerSide) { + setupVertices(bb, xForm); + float minU; + float maxU; + float minV; + float maxV; + IIcon tex; + + Tessellator tessellator = Tessellator.instance; + + tessellator.setNormal(0, 0, -1); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.NORTH.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + + tex = faceTextures[ForgeDirection.NORTH.ordinal()]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + addVecWithUV(verts[1], minU, maxV); + addVecWithUV(verts[0], maxU, maxV); + addVecWithUV(verts[3], maxU, minV); + addVecWithUV(verts[2], minU, minV); + + tessellator.setNormal(0, 0, 1); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.SOUTH.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + tex = faceTextures[ForgeDirection.SOUTH.ordinal()]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + addVecWithUV(verts[4], minU, maxV); + addVecWithUV(verts[5], maxU, maxV); + addVecWithUV(verts[6], maxU, minV); + addVecWithUV(verts[7], minU, minV); + + tessellator.setNormal(0, 1, 0); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.UP.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + tex = faceTextures[ForgeDirection.UP.ordinal()]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + addVecWithUV(verts[6], minU, minV); + addVecWithUV(verts[2], minU, maxV); + addVecWithUV(verts[3], maxU, maxV); + addVecWithUV(verts[7], maxU, minV); + + tessellator.setNormal(0, -1, 0); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.DOWN.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + tex = faceTextures[ForgeDirection.DOWN.ordinal()]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + addVecWithUV(verts[0], maxU, maxV); + addVecWithUV(verts[1], minU, maxV); + addVecWithUV(verts[5], minU, minV); + addVecWithUV(verts[4], maxU, minV); + + tessellator.setNormal(1, 0, 0); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.EAST.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + tex = faceTextures[ForgeDirection.EAST.ordinal()]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + addVecWithUV(verts[2], minU, minV); + addVecWithUV(verts[6], maxU, minV); + addVecWithUV(verts[5], maxU, maxV); + addVecWithUV(verts[1], minU, maxV); + + tessellator.setNormal(-1, 0, 0); + if (brightnessPerSide != null) { + float cm = brightnessPerSide[ForgeDirection.WEST.ordinal()]; + tessellator.setColorOpaque_F(cm, cm, cm); + } + tex = faceTextures[ForgeDirection.WEST.ordinal()]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + addVecWithUV(verts[0], minU, maxV); + addVecWithUV(verts[4], maxU, maxV); + addVecWithUV(verts[7], maxU, minV); + addVecWithUV(verts[3], minU, minV); + } + + public static void setupVertices(BoundingBox bound) { + setupVertices(bound, null); + } + + public static void setupVertices(BoundingBox bound, VertexTransform xForm) { + verts[0].set(bound.minX, bound.minY, bound.minZ); + verts[1].set(bound.maxX, bound.minY, bound.minZ); + verts[2].set(bound.maxX, bound.maxY, bound.minZ); + verts[3].set(bound.minX, bound.maxY, bound.minZ); + verts[4].set(bound.minX, bound.minY, bound.maxZ); + verts[5].set(bound.maxX, bound.minY, bound.maxZ); + verts[6].set(bound.maxX, bound.maxY, bound.maxZ); + verts[7].set(bound.minX, bound.maxY, bound.maxZ); + + if (xForm != null) { + for (Vector3d vec : verts) { + xForm.apply(vec); + } + } + } + + public static void addVecWithUV(Vector3d vec, double u, double v) { + Tessellator.instance.addVertexWithUV(vec.x, vec.y, vec.z, u, v); + } + + 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 de6be92..bba7e5e 100644 --- a/src/main/java/com/enderio/core/client/render/CustomCubeRenderer.java +++ b/src/main/java/com/enderio/core/client/render/CustomCubeRenderer.java @@ -2,61 +2,62 @@ package com.enderio.core.client.render; import java.util.Collection; -import com.enderio.core.api.client.render.IRenderFace; - import net.minecraft.block.Block; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; +import com.enderio.core.api.client.render.IRenderFace; + public class CustomCubeRenderer { - public static final CustomCubeRenderer instance = new CustomCubeRenderer(); + public static final CustomCubeRenderer instance = new CustomCubeRenderer(); - private CustomRenderBlocks rb = null; + private CustomRenderBlocks rb = null; - private IIcon overrideTexture; + private IIcon overrideTexture; - public void renderBlock(IBlockAccess ba, Block par1Block, int par2, int par3, int par4) { - renderBlock(ba, par1Block, par2, par3, par4, (IRenderFace) null); - } - - public void renderBlock(IBlockAccess ba, Block par1Block, int par2, int par3, int par4, IRenderFace renderer) { - if (rb == null) { - rb = new CustomRenderBlocks(ba); + public void renderBlock(IBlockAccess ba, Block par1Block, int par2, int par3, int par4) { + renderBlock(ba, par1Block, par2, par3, par4, (IRenderFace) null); } - rb.blockAccess = ba; - rb.setOverrideTexture(getOverrideTexture()); - rb.setFaceRenderers(null); - if (renderer != null) { - rb.addFaceRenderer(renderer); + + public void renderBlock(IBlockAccess ba, Block par1Block, int par2, int par3, int par4, IRenderFace renderer) { + if (rb == null) { + rb = new CustomRenderBlocks(ba); + } + rb.blockAccess = ba; + rb.setOverrideTexture(getOverrideTexture()); + rb.setFaceRenderers(null); + if (renderer != null) { + rb.addFaceRenderer(renderer); + } + rb.setRenderBoundsFromBlock(par1Block); + rb.renderStandardBlock(par1Block, par2, par3, par4); } - rb.setRenderBoundsFromBlock(par1Block); - rb.renderStandardBlock(par1Block, par2, par3, par4); - } - public void renderBlock(IBlockAccess ba, Block par1Block, int par2, int par3, int par4, Collection renderers) { - if (rb == null) { - rb = new CustomRenderBlocks(ba); + public void renderBlock(IBlockAccess ba, Block par1Block, int par2, int par3, int par4, + Collection renderers) { + if (rb == null) { + rb = new CustomRenderBlocks(ba); + } + rb.blockAccess = ba; + rb.setOverrideTexture(getOverrideTexture()); + rb.setFaceRenderers(renderers); + rb.setRenderBoundsFromBlock(par1Block); + rb.renderStandardBlock(par1Block, par2, par3, par4); } - rb.blockAccess = ba; - rb.setOverrideTexture(getOverrideTexture()); - rb.setFaceRenderers(renderers); - rb.setRenderBoundsFromBlock(par1Block); - rb.renderStandardBlock(par1Block, par2, par3, par4); - } - public IIcon getOverrideTexture() { - return overrideTexture; - } - - public void setOverrideTexture(IIcon overrideTexture) { - this.overrideTexture = overrideTexture; - } - - public CustomRenderBlocks getCustomRenderBlocks() { - if (rb == null) { - rb = new CustomRenderBlocks(); + public IIcon getOverrideTexture() { + return overrideTexture; + } + + public void setOverrideTexture(IIcon overrideTexture) { + this.overrideTexture = overrideTexture; + } + + public CustomRenderBlocks getCustomRenderBlocks() { + if (rb == null) { + rb = new CustomRenderBlocks(); + } + return rb; } - return rb; - } } 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 ac13ec3..ab05526 100644 --- a/src/main/java/com/enderio/core/client/render/CustomRenderBlocks.java +++ b/src/main/java/com/enderio/core/client/render/CustomRenderBlocks.java @@ -5,9 +5,6 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import com.enderio.core.api.client.render.IRenderFace; -import com.enderio.core.common.vecmath.Vertex; - import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; @@ -15,676 +12,952 @@ import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; +import com.enderio.core.api.client.render.IRenderFace; +import com.enderio.core.common.vecmath.Vertex; + public class CustomRenderBlocks extends RenderBlocks { - boolean translateToXYZ = true; - boolean shouldRenderBaseTexture = true; + boolean translateToXYZ = true; + boolean shouldRenderBaseTexture = true; - private final List renderFaceCallbacks = new ArrayList(); - private IIcon overrideTexture; + private final List renderFaceCallbacks = new ArrayList(); + private IIcon overrideTexture; - public CustomRenderBlocks() { - super(); - } - - public CustomRenderBlocks(IBlockAccess par1iBlockAccess) { - super(par1iBlockAccess); - } - - public void addFaceRenderer(IRenderFace renderer) { - renderFaceCallbacks.add(renderer); - } - - public void setFaceRenderers(Collection renderers) { - renderFaceCallbacks.clear(); - if (renderers != null) { - renderFaceCallbacks.addAll(renderers); - } - } - - public void removeFaceRenderer(IRenderFace renderer) { - renderFaceCallbacks.remove(renderer); - } - - public boolean isTranslateToXYZ() { - return translateToXYZ; - } - - public void setTranslateToXYZ(boolean translateToXYZ) { - this.translateToXYZ = translateToXYZ; - } - - public IIcon getOverrideTexture() { - return overrideTexture; - } - - 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()) { - doDefaultRenderFace(face, par1Block, x, y, z, overrideTexture == null ? texture : overrideTexture); - } else { - List faceVertices = createVerticesForFace(face, par1Block, x, y, z, overrideTexture == null ? texture : overrideTexture); - for (IRenderFace rf : renderFaceCallbacks) { - rf.renderFace(this, face, par1Block, x, y, z, overrideTexture == null ? texture : overrideTexture, faceVertices, translateToXYZ); - } - } - } - - public List createVerticesForFace(ForgeDirection face, Block par1Block, double x, double y, double z, IIcon icon) { - switch (face) { - case DOWN: - return calcFaceYNeg(par1Block, x, y, z, icon); - case EAST: - return calcFaceXPos(par1Block, x, y, z, icon); - case NORTH: - return calcFaceZNeg(par1Block, x, y, z, icon); - case SOUTH: - return calcFaceZPos(par1Block, x, y, z, icon); - case UP: - return calcFaceYPos(par1Block, x, y, z, icon); - case WEST: - return calcFaceXNeg(par1Block, x, y, z, icon); - case UNKNOWN: - default: - break; - } - return Collections.emptyList(); - } - - public void doDefaultRenderFace(ForgeDirection face, Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - switch (face) { - case DOWN: - super.renderFaceYNeg(par1Block, par2, par4, par6, par8Icon); - break; - case EAST: - super.renderFaceXPos(par1Block, par2, par4, par6, par8Icon); - break; - case NORTH: - super.renderFaceZNeg(par1Block, par2, par4, par6, par8Icon); - break; - case SOUTH: - super.renderFaceZPos(par1Block, par2, par4, par6, par8Icon); - break; - case UP: - super.renderFaceYPos(par1Block, par2, par4, par6, par8Icon); - break; - case WEST: - super.renderFaceXNeg(par1Block, par2, par4, par6, par8Icon); - break; - case UNKNOWN: - default: - break; - } - } - - @Override - public void renderFaceYNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - renderFace(ForgeDirection.DOWN, par1Block, par2, par4, par6, par8Icon); - } - - @Override - public void renderFaceYPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - renderFace(ForgeDirection.UP, par1Block, par2, par4, par6, par8Icon); - } - - @Override - public void renderFaceZNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - renderFace(ForgeDirection.NORTH, par1Block, par2, par4, par6, par8Icon); - } - - @Override - public void renderFaceZPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - renderFace(ForgeDirection.SOUTH, par1Block, par2, par4, par6, par8Icon); - } - - @Override - public void renderFaceXNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - renderFace(ForgeDirection.WEST, par1Block, par2, par4, par6, par8Icon); - } - - @Override - public void renderFaceXPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - renderFace(ForgeDirection.EAST, par1Block, par2, par4, par6, par8Icon); - } - - private List calcFaceXNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - - if (hasOverrideBlockTexture()) { - par8Icon = this.overrideBlockTexture; + public CustomRenderBlocks() { + super(); } - double d3 = par8Icon.getInterpolatedU(this.renderMinZ * 16.0D); - double d4 = par8Icon.getInterpolatedU(this.renderMaxZ * 16.0D); - double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); - double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); - double d7; - - if (this.flipTexture) { - d7 = d3; - d3 = d4; - d4 = d7; + public CustomRenderBlocks(IBlockAccess par1iBlockAccess) { + super(par1iBlockAccess); } - if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { - d3 = par8Icon.getMinU(); - d4 = par8Icon.getMaxU(); + public void addFaceRenderer(IRenderFace renderer) { + renderFaceCallbacks.add(renderer); } - if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { - d5 = par8Icon.getMinV(); - d6 = par8Icon.getMaxV(); + public void setFaceRenderers(Collection renderers) { + renderFaceCallbacks.clear(); + if (renderers != null) { + renderFaceCallbacks.addAll(renderers); + } } - d7 = d4; - double d8 = d3; - double d9 = d5; - double d10 = d6; - - 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); - d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinZ * 16.0D); - d9 = d5; - d10 = d6; - d7 = d3; - d8 = d4; - d5 = d6; - d6 = d9; - } 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); - d6 = par8Icon.getInterpolatedV(this.renderMaxZ * 16.0D); - d7 = d4; - d8 = d3; - d3 = d4; - d4 = d8; - d9 = d6; - d10 = d5; - } 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); - d6 = par8Icon.getInterpolatedV(this.renderMinY * 16.0D); - d7 = d4; - d8 = d3; - d9 = d5; - d10 = d6; + public void removeFaceRenderer(IRenderFace renderer) { + renderFaceCallbacks.remove(renderer); } - double d11 = par2 + this.renderMinX; - double d12 = par4 + this.renderMinY; - double d13 = par4 + this.renderMaxY; - double d14 = par6 + this.renderMinZ; - double d15 = par6 + this.renderMaxZ; - - List result = new ArrayList(4); - Vertex v; - 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)); - result.add(new Vertex(d11, d12, d15, d4, d6, brightnessTopRight, colorRedTopRight, this.colorGreenTopRight, this.colorBlueTopRight, 1)); - } else { - result.add(new Vertex(d11, d13, d15, d7, d9)); - result.add(new Vertex(d11, d13, d14, d3, d5)); - result.add(new Vertex(d11, d12, d14, d8, d10)); - result.add(new Vertex(d11, d12, d15, d4, d6)); - } - return result; - } - - private List calcFaceYPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - - if (this.hasOverrideBlockTexture()) { - par8Icon = this.overrideBlockTexture; + public boolean isTranslateToXYZ() { + return translateToXYZ; } - double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); - double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); - 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) { - d3 = par8Icon.getMinU(); - d4 = par8Icon.getMaxU(); + public void setTranslateToXYZ(boolean translateToXYZ) { + this.translateToXYZ = translateToXYZ; } - if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { - d5 = par8Icon.getMinV(); - d6 = par8Icon.getMaxV(); + public IIcon getOverrideTexture() { + return overrideTexture; } - double d7 = d4; - double d8 = d3; - double d9 = d5; - double d10 = d6; - - 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); - d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinX * 16.0D); - d9 = d5; - d10 = d6; - d7 = d3; - d8 = d4; - d5 = d6; - d6 = d9; - } 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); - d6 = par8Icon.getInterpolatedV(this.renderMaxX * 16.0D); - d7 = d4; - d8 = d3; - d3 = d4; - d4 = d8; - d9 = d6; - d10 = d5; - } 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); - d6 = par8Icon.getInterpolatedV(16.0D - this.renderMaxZ * 16.0D); - d7 = d4; - d8 = d3; - d9 = d5; - d10 = d6; + public void setOverrideTexture(IIcon overrideTexture) { + this.overrideTexture = overrideTexture; } - double d11 = par2 + this.renderMinX; - double d12 = par2 + this.renderMaxX; - double d13 = par4 + this.renderMaxY; - double d14 = par6 + this.renderMinZ; - double d15 = par6 + this.renderMaxZ; - - List result = new ArrayList(4); - Vertex v; - 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); - result.add(v); - v = new Vertex(d11, d13, d14, d3, d5, brightnessBottomRight, colorRedBottomRight, this.colorGreenBottomRight, this.colorBlueBottomRight, 1); - result.add(v); - v = new Vertex(d11, d13, d15, d8, d10, brightnessTopRight, colorRedTopRight, this.colorGreenTopRight, this.colorBlueTopRight, 1); - result.add(v); - } else { - v = new Vertex(d12, d13, d15, d4, d6); - result.add(v); - v = new Vertex(d12, d13, d14, d7, d9); - result.add(v); - v = new Vertex(d11, d13, d14, d3, d5); - result.add(v); - v = new Vertex(d11, d13, d15, d8, d10); - result.add(v); - } - return result; - } - - private List calcFaceZPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - Tessellator tessellator = Tessellator.instance; - - if (this.hasOverrideBlockTexture()) { - par8Icon = this.overrideBlockTexture; + public void setShouldRenderBaseTexture(boolean val) { + shouldRenderBaseTexture = val; } - double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); - double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); - double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); - double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); - double d7; - - if (this.flipTexture) { - d7 = d3; - d3 = d4; - d4 = d7; + private void renderFace(ForgeDirection face, Block par1Block, double x, double y, double z, IIcon texture) { + 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); + for (IRenderFace rf : renderFaceCallbacks) { + rf.renderFace( + this, + face, + par1Block, + x, + y, + z, + overrideTexture == null ? texture : overrideTexture, + faceVertices, + translateToXYZ); + } + } } - if (this.renderMinX < 0.0D || this.renderMaxX > 1.0D) { - d3 = par8Icon.getMinU(); - d4 = par8Icon.getMaxU(); + public List createVerticesForFace(ForgeDirection face, Block par1Block, double x, double y, double z, + IIcon icon) { + switch (face) { + case DOWN: + return calcFaceYNeg(par1Block, x, y, z, icon); + case EAST: + return calcFaceXPos(par1Block, x, y, z, icon); + case NORTH: + return calcFaceZNeg(par1Block, x, y, z, icon); + case SOUTH: + return calcFaceZPos(par1Block, x, y, z, icon); + case UP: + return calcFaceYPos(par1Block, x, y, z, icon); + case WEST: + return calcFaceXNeg(par1Block, x, y, z, icon); + case UNKNOWN: + default: + break; + } + return Collections.emptyList(); } - if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { - d5 = par8Icon.getMinV(); - d6 = par8Icon.getMaxV(); + public void doDefaultRenderFace(ForgeDirection face, Block par1Block, double par2, double par4, double par6, + IIcon par8Icon) { + switch (face) { + case DOWN: + super.renderFaceYNeg(par1Block, par2, par4, par6, par8Icon); + break; + case EAST: + super.renderFaceXPos(par1Block, par2, par4, par6, par8Icon); + break; + case NORTH: + super.renderFaceZNeg(par1Block, par2, par4, par6, par8Icon); + break; + case SOUTH: + super.renderFaceZPos(par1Block, par2, par4, par6, par8Icon); + break; + case UP: + super.renderFaceYPos(par1Block, par2, par4, par6, par8Icon); + break; + case WEST: + super.renderFaceXNeg(par1Block, par2, par4, par6, par8Icon); + break; + case UNKNOWN: + default: + break; + } } - d7 = d4; - double d8 = d3; - double d9 = d5; - double d10 = d6; - - 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); - d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxX * 16.0D); - d9 = d5; - d10 = d6; - d7 = d3; - d8 = d4; - d5 = d6; - d6 = d9; - } 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); - d6 = par8Icon.getInterpolatedV(this.renderMaxX * 16.0D); - d7 = d4; - d8 = d3; - d3 = d4; - d4 = d8; - d9 = d6; - d10 = d5; - } 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); - d6 = par8Icon.getInterpolatedV(this.renderMinY * 16.0D); - d7 = d4; - d8 = d3; - d9 = d5; - d10 = d6; + @Override + public void renderFaceYNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { + renderFace(ForgeDirection.DOWN, par1Block, par2, par4, par6, par8Icon); } - double d11 = par2 + this.renderMinX; - double d12 = par2 + this.renderMaxX; - double d13 = par4 + this.renderMinY; - double d14 = par4 + this.renderMaxY; - double d15 = par6 + this.renderMaxZ; - - List result = new ArrayList(); - Vertex v; - 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)); - result.add(new Vertex(d12, d14, d15, d7, d9, brightnessTopRight, colorRedTopRight, this.colorGreenTopRight, this.colorBlueTopRight, 1)); - } else { - result.add(new Vertex(d11, d14, d15, d3, d5)); - result.add(new Vertex(d11, d13, d15, d8, d10)); - result.add(new Vertex(d12, d13, d15, d4, d6)); - result.add(new Vertex(d12, d14, d15, d7, d9)); - } - return result; - } - - private List calcFaceZNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - - if (this.hasOverrideBlockTexture()) { - par8Icon = this.overrideBlockTexture; + @Override + public void renderFaceYPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { + renderFace(ForgeDirection.UP, par1Block, par2, par4, par6, par8Icon); } - double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); - double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); - double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); - double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); - double d7; - - if (this.flipTexture) { - d7 = d3; - d3 = d4; - d4 = d7; + @Override + public void renderFaceZNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { + renderFace(ForgeDirection.NORTH, par1Block, par2, par4, par6, par8Icon); } - if (this.renderMinX < 0.0D || this.renderMaxX > 1.0D) { - d3 = par8Icon.getMinU(); - d4 = par8Icon.getMaxU(); + @Override + public void renderFaceZPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { + renderFace(ForgeDirection.SOUTH, par1Block, par2, par4, par6, par8Icon); } - if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { - d5 = par8Icon.getMinV(); - d6 = par8Icon.getMaxV(); + @Override + public void renderFaceXNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { + renderFace(ForgeDirection.WEST, par1Block, par2, par4, par6, par8Icon); } - d7 = d4; - double d8 = d3; - double d9 = d5; - double d10 = d6; - - 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); - d6 = par8Icon.getInterpolatedV(16.0D - this.renderMaxX * 16.0D); - d9 = d5; - d10 = d6; - d7 = d3; - d8 = d4; - d5 = d6; - d6 = d9; - } 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); - d6 = par8Icon.getInterpolatedV(this.renderMinX * 16.0D); - d7 = d4; - d8 = d3; - d3 = d4; - d4 = d8; - d9 = d6; - d10 = d5; - } 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); - d6 = par8Icon.getInterpolatedV(this.renderMinY * 16.0D); - d7 = d4; - d8 = d3; - d9 = d5; - d10 = d6; + @Override + public void renderFaceXPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { + renderFace(ForgeDirection.EAST, par1Block, par2, par4, par6, par8Icon); } - double d11 = par2 + this.renderMinX; - double d12 = par2 + this.renderMaxX; - double d13 = par4 + this.renderMinY; - double d14 = par4 + this.renderMaxY; - double d15 = par6 + this.renderMinZ; + private List calcFaceXNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - List result = new ArrayList(); - Vertex v; - 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)); - result.add(new Vertex(d11, d13, d15, d4, d6, brightnessTopRight, colorRedTopRight, this.colorGreenTopRight, this.colorBlueTopRight, 1)); - } else { - result.add(new Vertex(d11, d14, d15, d7, d9)); - result.add(new Vertex(d12, d14, d15, d3, d5)); - result.add(new Vertex(d12, d13, d15, d8, d10)); - result.add(new Vertex(d11, d13, d15, d4, d6)); - } - return result; - } + if (hasOverrideBlockTexture()) { + par8Icon = this.overrideBlockTexture; + } - private List calcFaceXPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - Tessellator tessellator = Tessellator.instance; + double d3 = par8Icon.getInterpolatedU(this.renderMinZ * 16.0D); + double d4 = par8Icon.getInterpolatedU(this.renderMaxZ * 16.0D); + double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + double d7; - if (this.hasOverrideBlockTexture()) { - par8Icon = this.overrideBlockTexture; + if (this.flipTexture) { + d7 = d3; + d3 = d4; + d4 = d7; + } + + if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { + d3 = par8Icon.getMinU(); + d4 = par8Icon.getMaxU(); + } + + if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { + d5 = par8Icon.getMinV(); + d6 = par8Icon.getMaxV(); + } + + d7 = d4; + double d8 = d3; + double d9 = d5; + double d10 = d6; + + 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); + d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinZ * 16.0D); + d9 = d5; + d10 = d6; + d7 = d3; + d8 = d4; + d5 = d6; + d6 = d9; + } 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); + d6 = par8Icon.getInterpolatedV(this.renderMaxZ * 16.0D); + d7 = d4; + d8 = d3; + d3 = d4; + d4 = d8; + d9 = d6; + d10 = d5; + } 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); + d6 = par8Icon.getInterpolatedV(this.renderMinY * 16.0D); + d7 = d4; + d8 = d3; + d9 = d5; + d10 = d6; + } + + double d11 = par2 + this.renderMinX; + double d12 = par4 + this.renderMinY; + double d13 = par4 + this.renderMaxY; + double d14 = par6 + this.renderMinZ; + double d15 = par6 + this.renderMaxZ; + + List result = new ArrayList(4); + Vertex v; + 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)); + result.add( + new Vertex( + d11, + d12, + d15, + d4, + d6, + brightnessTopRight, + colorRedTopRight, + this.colorGreenTopRight, + this.colorBlueTopRight, + 1)); + } else { + result.add(new Vertex(d11, d13, d15, d7, d9)); + result.add(new Vertex(d11, d13, d14, d3, d5)); + result.add(new Vertex(d11, d12, d14, d8, d10)); + result.add(new Vertex(d11, d12, d15, d4, d6)); + } + return result; } - double d3 = par8Icon.getInterpolatedU(this.renderMinZ * 16.0D); - double d4 = par8Icon.getInterpolatedU(this.renderMaxZ * 16.0D); - double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); - double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); - double d7; + private List calcFaceYPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { - if (this.flipTexture) { - d7 = d3; - d3 = d4; - d4 = d7; + if (this.hasOverrideBlockTexture()) { + par8Icon = this.overrideBlockTexture; + } + + double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); + double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); + 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) { + d3 = par8Icon.getMinU(); + d4 = par8Icon.getMaxU(); + } + + if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { + d5 = par8Icon.getMinV(); + d6 = par8Icon.getMaxV(); + } + + double d7 = d4; + double d8 = d3; + double d9 = d5; + double d10 = d6; + + 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); + d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinX * 16.0D); + d9 = d5; + d10 = d6; + d7 = d3; + d8 = d4; + d5 = d6; + d6 = d9; + } 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); + d6 = par8Icon.getInterpolatedV(this.renderMaxX * 16.0D); + d7 = d4; + d8 = d3; + d3 = d4; + d4 = d8; + d9 = d6; + d10 = d5; + } 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); + d6 = par8Icon.getInterpolatedV(16.0D - this.renderMaxZ * 16.0D); + d7 = d4; + d8 = d3; + d9 = d5; + d10 = d6; + } + + double d11 = par2 + this.renderMinX; + double d12 = par2 + this.renderMaxX; + double d13 = par4 + this.renderMaxY; + double d14 = par6 + this.renderMinZ; + double d15 = par6 + this.renderMaxZ; + + List result = new ArrayList(4); + Vertex v; + 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); + result.add(v); + v = new Vertex( + d11, + d13, + d14, + d3, + d5, + brightnessBottomRight, + colorRedBottomRight, + this.colorGreenBottomRight, + this.colorBlueBottomRight, + 1); + result.add(v); + v = new Vertex( + d11, + d13, + d15, + d8, + d10, + brightnessTopRight, + colorRedTopRight, + this.colorGreenTopRight, + this.colorBlueTopRight, + 1); + result.add(v); + } else { + v = new Vertex(d12, d13, d15, d4, d6); + result.add(v); + v = new Vertex(d12, d13, d14, d7, d9); + result.add(v); + v = new Vertex(d11, d13, d14, d3, d5); + result.add(v); + v = new Vertex(d11, d13, d15, d8, d10); + result.add(v); + } + return result; } - if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { - d3 = par8Icon.getMinU(); - d4 = par8Icon.getMaxU(); + private List calcFaceZPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { + Tessellator tessellator = Tessellator.instance; + + if (this.hasOverrideBlockTexture()) { + par8Icon = this.overrideBlockTexture; + } + + double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); + double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); + double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + double d7; + + if (this.flipTexture) { + d7 = d3; + d3 = d4; + d4 = d7; + } + + if (this.renderMinX < 0.0D || this.renderMaxX > 1.0D) { + d3 = par8Icon.getMinU(); + d4 = par8Icon.getMaxU(); + } + + if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { + d5 = par8Icon.getMinV(); + d6 = par8Icon.getMaxV(); + } + + d7 = d4; + double d8 = d3; + double d9 = d5; + double d10 = d6; + + 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); + d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxX * 16.0D); + d9 = d5; + d10 = d6; + d7 = d3; + d8 = d4; + d5 = d6; + d6 = d9; + } 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); + d6 = par8Icon.getInterpolatedV(this.renderMaxX * 16.0D); + d7 = d4; + d8 = d3; + d3 = d4; + d4 = d8; + d9 = d6; + d10 = d5; + } 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); + d6 = par8Icon.getInterpolatedV(this.renderMinY * 16.0D); + d7 = d4; + d8 = d3; + d9 = d5; + d10 = d6; + } + + double d11 = par2 + this.renderMinX; + double d12 = par2 + this.renderMaxX; + double d13 = par4 + this.renderMinY; + double d14 = par4 + this.renderMaxY; + double d15 = par6 + this.renderMaxZ; + + List result = new ArrayList(); + Vertex v; + 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)); + result.add( + new Vertex( + d12, + d14, + d15, + d7, + d9, + brightnessTopRight, + colorRedTopRight, + this.colorGreenTopRight, + this.colorBlueTopRight, + 1)); + } else { + result.add(new Vertex(d11, d14, d15, d3, d5)); + result.add(new Vertex(d11, d13, d15, d8, d10)); + result.add(new Vertex(d12, d13, d15, d4, d6)); + result.add(new Vertex(d12, d14, d15, d7, d9)); + } + return result; } - if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { - d5 = par8Icon.getMinV(); - d6 = par8Icon.getMaxV(); + private List calcFaceZNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { + + if (this.hasOverrideBlockTexture()) { + par8Icon = this.overrideBlockTexture; + } + + double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); + double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); + double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + double d7; + + if (this.flipTexture) { + d7 = d3; + d3 = d4; + d4 = d7; + } + + if (this.renderMinX < 0.0D || this.renderMaxX > 1.0D) { + d3 = par8Icon.getMinU(); + d4 = par8Icon.getMaxU(); + } + + if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { + d5 = par8Icon.getMinV(); + d6 = par8Icon.getMaxV(); + } + + d7 = d4; + double d8 = d3; + double d9 = d5; + double d10 = d6; + + 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); + d6 = par8Icon.getInterpolatedV(16.0D - this.renderMaxX * 16.0D); + d9 = d5; + d10 = d6; + d7 = d3; + d8 = d4; + d5 = d6; + d6 = d9; + } 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); + d6 = par8Icon.getInterpolatedV(this.renderMinX * 16.0D); + d7 = d4; + d8 = d3; + d3 = d4; + d4 = d8; + d9 = d6; + d10 = d5; + } 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); + d6 = par8Icon.getInterpolatedV(this.renderMinY * 16.0D); + d7 = d4; + d8 = d3; + d9 = d5; + d10 = d6; + } + + double d11 = par2 + this.renderMinX; + double d12 = par2 + this.renderMaxX; + double d13 = par4 + this.renderMinY; + double d14 = par4 + this.renderMaxY; + double d15 = par6 + this.renderMinZ; + + List result = new ArrayList(); + Vertex v; + 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)); + result.add( + new Vertex( + d11, + d13, + d15, + d4, + d6, + brightnessTopRight, + colorRedTopRight, + this.colorGreenTopRight, + this.colorBlueTopRight, + 1)); + } else { + result.add(new Vertex(d11, d14, d15, d7, d9)); + result.add(new Vertex(d12, d14, d15, d3, d5)); + result.add(new Vertex(d12, d13, d15, d8, d10)); + result.add(new Vertex(d11, d13, d15, d4, d6)); + } + return result; } - d7 = d4; - double d8 = d3; - double d9 = d5; - double d10 = d6; + private List calcFaceXPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) { + Tessellator tessellator = Tessellator.instance; - 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); - d6 = par8Icon.getInterpolatedV(16.0D - this.renderMaxZ * 16.0D); - d9 = d5; - d10 = d6; - d7 = d3; - d8 = d4; - d5 = d6; - d6 = d9; - } 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); - d6 = par8Icon.getInterpolatedV(this.renderMinZ * 16.0D); - d7 = d4; - d8 = d3; - d3 = d4; - d4 = d8; - d9 = d6; - d10 = d5; - } 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); - d6 = par8Icon.getInterpolatedV(this.renderMinY * 16.0D); - d7 = d4; - d8 = d3; - d9 = d5; - d10 = d6; + if (this.hasOverrideBlockTexture()) { + par8Icon = this.overrideBlockTexture; + } + + double d3 = par8Icon.getInterpolatedU(this.renderMinZ * 16.0D); + double d4 = par8Icon.getInterpolatedU(this.renderMaxZ * 16.0D); + double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + double d7; + + if (this.flipTexture) { + d7 = d3; + d3 = d4; + d4 = d7; + } + + if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { + d3 = par8Icon.getMinU(); + d4 = par8Icon.getMaxU(); + } + + if (this.renderMinY < 0.0D || this.renderMaxY > 1.0D) { + d5 = par8Icon.getMinV(); + d6 = par8Icon.getMaxV(); + } + + d7 = d4; + double d8 = d3; + double d9 = d5; + double d10 = d6; + + 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); + d6 = par8Icon.getInterpolatedV(16.0D - this.renderMaxZ * 16.0D); + d9 = d5; + d10 = d6; + d7 = d3; + d8 = d4; + d5 = d6; + d6 = d9; + } 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); + d6 = par8Icon.getInterpolatedV(this.renderMinZ * 16.0D); + d7 = d4; + d8 = d3; + d3 = d4; + d4 = d8; + d9 = d6; + d10 = d5; + } 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); + d6 = par8Icon.getInterpolatedV(this.renderMinY * 16.0D); + d7 = d4; + d8 = d3; + d9 = d5; + d10 = d6; + } + + double d11 = par2 + this.renderMaxX; + double d12 = par4 + this.renderMinY; + double d13 = par4 + this.renderMaxY; + double d14 = par6 + this.renderMinZ; + double d15 = par6 + this.renderMaxZ; + + List result = new ArrayList(4); + Vertex v; + 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)); + result.add( + new Vertex( + d11, + d13, + d15, + d3, + d5, + brightnessTopRight, + colorRedTopRight, + this.colorGreenTopRight, + this.colorBlueTopRight, + 1)); + } else { + result.add(new Vertex(d11, d12, d15, d8, d10)); + result.add(new Vertex(d11, d12, d14, d4, d6)); + result.add(new Vertex(d11, d13, d14, d7, d9)); + result.add(new Vertex(d11, d13, d15, d3, d5)); + } + return result; } - double d11 = par2 + this.renderMaxX; - double d12 = par4 + this.renderMinY; - double d13 = par4 + this.renderMaxY; - double d14 = par6 + this.renderMinZ; - double d15 = par6 + this.renderMaxZ; + private List calcFaceYNeg(Block par1Block, double x, double y, double z, IIcon icon) { - List result = new ArrayList(4); - Vertex v; - 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)); - result.add(new Vertex(d11, d13, d15, d3, d5, brightnessTopRight, colorRedTopRight, this.colorGreenTopRight, this.colorBlueTopRight, 1)); - } else { - result.add(new Vertex(d11, d12, d15, d8, d10)); - result.add(new Vertex(d11, d12, d14, d4, d6)); - result.add(new Vertex(d11, d13, d14, d7, d9)); - result.add(new Vertex(d11, d13, d15, d3, d5)); - } - return result; - } + if (hasOverrideBlockTexture()) { + icon = this.overrideBlockTexture; + } - private List calcFaceYNeg(Block par1Block, double x, double y, double z, IIcon icon) { + double minU = icon.getInterpolatedU(this.renderMinX * 16.0D); + double maxU = icon.getInterpolatedU(this.renderMaxX * 16.0D); + double minV = icon.getInterpolatedV(this.renderMinZ * 16.0D); + double maxV = icon.getInterpolatedV(this.renderMaxZ * 16.0D); - if (hasOverrideBlockTexture()) { - icon = this.overrideBlockTexture; + if (renderMinX < 0.0D || renderMaxX > 1.0D) { + minU = icon.getMinU(); + maxU = icon.getMaxU(); + } + + if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { + minV = icon.getMinV(); + maxV = icon.getMaxV(); + } + + double d7 = maxU; + double d8 = minU; + double d9 = minV; + double d10 = maxV; + + 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); + maxV = icon.getInterpolatedV(16.0D - this.renderMinX * 16.0D); + d9 = minV; + d10 = maxV; + d7 = minU; + d8 = maxU; + minV = maxV; + maxV = d9; + } else if (uvRotateBottom == 1) { + + minU = icon.getInterpolatedU(16.0D - this.renderMaxZ * 16.0D); + minV = icon.getInterpolatedV(this.renderMinX * 16.0D); + maxU = icon.getInterpolatedU(16.0D - this.renderMinZ * 16.0D); + maxV = icon.getInterpolatedV(this.renderMaxX * 16.0D); + d7 = maxU; + d8 = minU; + minU = maxU; + maxU = d8; + d9 = maxV; + d10 = minV; + } 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); + maxV = icon.getInterpolatedV(16.0D - this.renderMaxZ * 16.0D); + d7 = maxU; + d8 = minU; + d9 = minV; + d10 = maxV; + } + + double minX = x + this.renderMinX; + double maxX = x + this.renderMaxX; + double minY = y + this.renderMinY; + double minZ = z + this.renderMinZ; + double maxZ = z + this.renderMaxZ; + + List result = new ArrayList(4); + Vertex v; + 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); + result.add(v); + v = new Vertex( + maxX, + minY, + minZ, + d7, + d9, + brightnessBottomRight, + colorRedBottomRight, + colorGreenBottomRight, + colorBlueBottomRight, + 1f); + result.add(v); + v = new Vertex( + maxX, + minY, + maxZ, + maxU, + maxV, + brightnessTopRight, + colorRedTopRight, + colorGreenTopRight, + colorBlueTopRight, + 1f); + result.add(v); + } else { + v = new Vertex(minX, minY, maxZ, d8, d10); + result.add(v); + v = new Vertex(minX, minY, minZ, minU, minV); + result.add(v); + v = new Vertex(maxX, minY, minZ, d7, d9); + result.add(v); + v = new Vertex(maxX, minY, maxZ, maxU, maxV); + result.add(v); + } + return result; } - double minU = icon.getInterpolatedU(this.renderMinX * 16.0D); - double maxU = icon.getInterpolatedU(this.renderMaxX * 16.0D); - double minV = icon.getInterpolatedV(this.renderMinZ * 16.0D); - double maxV = icon.getInterpolatedV(this.renderMaxZ * 16.0D); - - if (renderMinX < 0.0D || renderMaxX > 1.0D) { - minU = icon.getMinU(); - maxU = icon.getMaxU(); - } - - if (this.renderMinZ < 0.0D || this.renderMaxZ > 1.0D) { - minV = icon.getMinV(); - maxV = icon.getMaxV(); - } - - double d7 = maxU; - double d8 = minU; - double d9 = minV; - double d10 = maxV; - - 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); - maxV = icon.getInterpolatedV(16.0D - this.renderMinX * 16.0D); - d9 = minV; - d10 = maxV; - d7 = minU; - d8 = maxU; - minV = maxV; - maxV = d9; - } else if (uvRotateBottom == 1) { - - minU = icon.getInterpolatedU(16.0D - this.renderMaxZ * 16.0D); - minV = icon.getInterpolatedV(this.renderMinX * 16.0D); - maxU = icon.getInterpolatedU(16.0D - this.renderMinZ * 16.0D); - maxV = icon.getInterpolatedV(this.renderMaxX * 16.0D); - d7 = maxU; - d8 = minU; - minU = maxU; - maxU = d8; - d9 = maxV; - d10 = minV; - } 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); - maxV = icon.getInterpolatedV(16.0D - this.renderMaxZ * 16.0D); - d7 = maxU; - d8 = minU; - d9 = minV; - d10 = maxV; - } - - double minX = x + this.renderMinX; - double maxX = x + this.renderMaxX; - double minY = y + this.renderMinY; - double minZ = z + this.renderMinZ; - double maxZ = z + this.renderMaxZ; - - List result = new ArrayList(4); - Vertex v; - 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); - result.add(v); - v = new Vertex(maxX, minY, minZ, d7, d9, brightnessBottomRight, colorRedBottomRight, colorGreenBottomRight, colorBlueBottomRight, 1f); - result.add(v); - v = new Vertex(maxX, minY, maxZ, maxU, maxV, brightnessTopRight, colorRedTopRight, colorGreenTopRight, colorBlueTopRight, 1f); - result.add(v); - } else { - v = new Vertex(minX, minY, maxZ, d8, d10); - result.add(v); - v = new Vertex(minX, minY, minZ, minU, minV); - result.add(v); - v = new Vertex(maxX, minY, minZ, d7, d9); - result.add(v); - v = new Vertex(maxX, minY, maxZ, maxU, maxV); - result.add(v); - } - return result; - } - -} \ No newline at end of file +} 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 761a0fc..9b0b9b4 100644 --- a/src/main/java/com/enderio/core/client/render/CustomWidgetIcon.java +++ b/src/main/java/com/enderio/core/client/render/CustomWidgetIcon.java @@ -5,51 +5,51 @@ import com.enderio.core.api.client.render.IWidgetMap; public class CustomWidgetIcon implements IWidgetIcon { - private final int x, y, width, height; - private final IWidgetMap map; + private final int x, y, width, height; + private final IWidgetMap map; - private IWidgetIcon overlay; + private IWidgetIcon overlay; - public CustomWidgetIcon(int x, int y, int width, int height, IWidgetMap map, IWidgetIcon overlay) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.map = map; - this.overlay = overlay; - } + public CustomWidgetIcon(int x, int y, int width, int height, IWidgetMap map, IWidgetIcon overlay) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.map = map; + this.overlay = overlay; + } - public CustomWidgetIcon(int x, int y, int width, int height, IWidgetMap map) { - this(x, y, width, height, map, null); - } + public CustomWidgetIcon(int x, int y, int width, int height, IWidgetMap map) { + this(x, y, width, height, map, null); + } - @Override - public int getX() { - return x; - } + @Override + public int getX() { + return x; + } - @Override - public int getY() { - return y; - } + @Override + public int getY() { + return y; + } - @Override - public int getWidth() { - return width; - } + @Override + public int getWidth() { + return width; + } - @Override - public int getHeight() { - return height; - } + @Override + public int getHeight() { + return height; + } - @Override - public IWidgetMap getMap() { - return map; - } + @Override + public IWidgetMap getMap() { + return map; + } - @Override - public IWidgetIcon getOverlay() { - return overlay; - } + @Override + public IWidgetIcon getOverlay() { + return 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 2d98999..5dd00ab 100644 --- a/src/main/java/com/enderio/core/client/render/DirectionalModelRenderer.java +++ b/src/main/java/com/enderio/core/client/render/DirectionalModelRenderer.java @@ -20,121 +20,123 @@ 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 DirectionalModelRenderer(ResourceLocation model, ResourceLocation texture) { - this.model = AdvancedModelLoader.loadModel(model); - this.texture = texture; - } + private IModelCustom model; + private ResourceLocation texture; + private IEnderModel modelSMT; - 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(ResourceLocation model, ResourceLocation texture) { + this.model = AdvancedModelLoader.loadModel(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; + public DirectionalModelRenderer(IEnderModel model, ResourceLocation texture) { + this.modelSMT = model; + this.texture = texture; } - renderDirectionalTileEntityAt(null, 0, 0, 0, ItemUtil.getNBTTag(item).getInteger("storedMetaData")); + 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); + } - GL11.glPopMatrix(); - } + 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(); + } } 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 b93de00..6678234 100644 --- a/src/main/java/com/enderio/core/client/render/EnderWidget.java +++ b/src/main/java/com/enderio/core/client/render/EnderWidget.java @@ -8,112 +8,112 @@ import com.enderio.core.api.client.render.IWidgetMap; public enum EnderWidget implements IWidgetIcon { - BUTTON_BASE(0, 0), - UP_ARROW_OFF(212, 64, 11, 8), - UP_ARROW_ON(223, 64, 11, 8), - UP_ARROW_HOVER_OFF(234, 64, 11, 8), - UP_ARROW_HOVER_ON(245, 64, 11, 8), - DOWN_ARROW_OFF(212, 72, 11, 8), - DOWN_ARROW_ON(223, 72, 11, 8), - DOWN_ARROW_HOVER_OFF(234, 72, 11, 8), - DOWN_ARROW_HOVER_ON(245, 72, 11, 8), + BUTTON_BASE(0, 0), + UP_ARROW_OFF(212, 64, 11, 8), + UP_ARROW_ON(223, 64, 11, 8), + UP_ARROW_HOVER_OFF(234, 64, 11, 8), + UP_ARROW_HOVER_ON(245, 64, 11, 8), + DOWN_ARROW_OFF(212, 72, 11, 8), + DOWN_ARROW_ON(223, 72, 11, 8), + DOWN_ARROW_HOVER_OFF(234, 72, 11, 8), + DOWN_ARROW_HOVER_ON(245, 72, 11, 8), - VSCROLL_THUMB_OFF(234, 80, 11, 8), - VSCROLL_THUMB_HOVER_OFF(234, 88, 11, 8), - VSCROLL_THUMB_ON(245, 80, 11, 8), - VSCROLL_THUMB_HOVER_ON(245, 88, 11, 8), + VSCROLL_THUMB_OFF(234, 80, 11, 8), + VSCROLL_THUMB_HOVER_OFF(234, 88, 11, 8), + VSCROLL_THUMB_ON(245, 80, 11, 8), + VSCROLL_THUMB_HOVER_ON(245, 88, 11, 8), - BUTTON(0, 208), - BUTTON_HIGHLIGHT(16, 208), - BUTTON_DISABLED(32, 208), - BUTTON_DOWN(48, 208), - BUTTON_DOWN_HIGHLIGHT(64, 208), - BUTTON_CHECKED(112, 208), + BUTTON(0, 208), + BUTTON_HIGHLIGHT(16, 208), + BUTTON_DISABLED(32, 208), + 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), - LEFT_ARROW_HOVER_PRESSED(240, 48, 8, 16), + LEFT_ARROW(224, 32, 8, 16), + LEFT_ARROW_PRESSED(240, 32, 8, 16), + LEFT_ARROW_HOVER(224, 48, 8, 16), + LEFT_ARROW_HOVER_PRESSED(240, 48, 8, 16), - RIGHT_ARROW(232, 32, 8, 16), - RIGHT_ARROW_PRESSED(248, 32, 8, 16), - RIGHT_ARROW_HOVER(232, 48, 8, 16), - RIGHT_ARROW_HOVER_PRESSED(248, 48, 8, 16), + RIGHT_ARROW(232, 32, 8, 16), + RIGHT_ARROW_PRESSED(248, 32, 8, 16), + RIGHT_ARROW_HOVER(232, 48, 8, 16), + RIGHT_ARROW_HOVER_PRESSED(248, 48, 8, 16), - ADD_BUT(208, 32, 8, 8), - ADD_BUT_PRESSED(216, 32, 8, 8), - ADD_BUT_HOVER(208, 48, 8, 8), - ADD_BUT_HOVER_PRESSED(216, 48, 8, 8), + ADD_BUT(208, 32, 8, 8), + ADD_BUT_PRESSED(216, 32, 8, 8), + ADD_BUT_HOVER(208, 48, 8, 8), + ADD_BUT_HOVER_PRESSED(216, 48, 8, 8), - MINUS_BUT(208, 40, 8, 8), - MINUS_BUT_PRESSED(216, 40, 8, 8), - MINUS_BUT_HOVER(208, 56, 8, 8), - MINUS_BUT_HOVER_PRESSED(216, 56, 8, 8), + MINUS_BUT(208, 40, 8, 8), + MINUS_BUT_PRESSED(216, 40, 8, 8), + MINUS_BUT_HOVER(208, 56, 8, 8), + MINUS_BUT_HOVER_PRESSED(216, 56, 8, 8), - X_BUT(200, 32, 8, 8), - X_BUT_PRESSED(200, 40, 8, 8), - X_BUT_HOVER(200, 48, 8, 8), - X_BUT_HOVER_PRESSED(200, 56, 8, 8), + X_BUT(200, 32, 8, 8), + X_BUT_PRESSED(200, 40, 8, 8), + X_BUT_HOVER(200, 48, 8, 8), + X_BUT_HOVER_PRESSED(200, 56, 8, 8), - NEUTRAL_SLOT_BACKGROUND(112, 176, 16, 16), ; + NEUTRAL_SLOT_BACKGROUND(112, 176, 16, 16),; - public static final ResourceLocation TEXTURE = new ResourceLocation(EnderCore.MODID, "textures/gui/widgets.png"); + public static final ResourceLocation TEXTURE = new ResourceLocation(EnderCore.MODID, "textures/gui/widgets.png"); - public static final IWidgetMap map = new IWidgetMap.WidgetMapImpl(256, TEXTURE); + public static final IWidgetMap map = new IWidgetMap.WidgetMapImpl(256, TEXTURE); - public final int x; - public final int y; - public final int width; - public final int height; - public final IWidgetIcon overlay; + public final int x; + public final int y; + public final int width; + public final int height; + public final IWidgetIcon overlay; - EnderWidget(int x, int y) { - this(x, y, null); - } + EnderWidget(int x, int y) { + this(x, y, null); + } - EnderWidget(int x, int y, IWidgetIcon overlay) { - this(x, y, 16, 16, overlay); - } + EnderWidget(int x, int y, IWidgetIcon overlay) { + this(x, y, 16, 16, overlay); + } - EnderWidget(int x, int y, int width, int height) { - this(x, y, width, height, null); - } - - EnderWidget(int x, int y, int width, int height, IWidgetIcon overlay) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.overlay = overlay; - } + EnderWidget(int x, int y, int width, int height) { + this(x, y, width, height, null); + } - @Override - public int getX() { - return x; - } + EnderWidget(int x, int y, int width, int height, IWidgetIcon overlay) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.overlay = overlay; + } - @Override - public int getY() { - return y; - } - - @Override - public int getWidth() { - return width; - } - - @Override - public int getHeight() { - return height; - } - - @Override - public IWidgetIcon getOverlay() { - return overlay; - } - - @Override - public IWidgetMap getMap() { - return map; - } + @Override + public int getX() { + return x; + } + + @Override + public int getY() { + return y; + } + + @Override + public int getWidth() { + return width; + } + + @Override + public int getHeight() { + return height; + } + + @Override + public IWidgetIcon getOverlay() { + return overlay; + } + + @Override + public IWidgetMap getMap() { + return map; + } } 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 e7a9522..34f1b30 100644 --- a/src/main/java/com/enderio/core/client/render/IconUtil.java +++ b/src/main/java/com/enderio/core/client/render/IconUtil.java @@ -7,63 +7,64 @@ import net.minecraft.item.Item; import net.minecraft.util.IIcon; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.common.MinecraftForge; + import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public class IconUtil { - public static interface IIconProvider { + public static interface IIconProvider { - public void registerIcons(IIconRegister register); + public void registerIcons(IIconRegister register); - /** 0 = terrain.png, 1 = items.png */ - public int getTextureType(); - } - - private static ArrayList iconProviders = new ArrayList(); - - public static IIcon whiteTexture; - public static IIcon blankTexture; - public static IIcon errorTexture; - - static { - MinecraftForge.EVENT_BUS.register(new IconUtil()); - addIconProvider(new IIconProvider() { - - @Override - public void registerIcons(IIconRegister register) { - whiteTexture = register.registerIcon("enderio:white"); - errorTexture = register.registerIcon("enderio:error"); - blankTexture = register.registerIcon("enderio:blank"); - } - - @Override - public int getTextureType() { - return 0; - } - }); - } - - public static void addIconProvider(IIconProvider registrar) { - iconProviders.add(registrar); - } - - @Mod.EventHandler - @SubscribeEvent - public void onIconLoad(TextureStitchEvent.Pre event) { - for (IIconProvider reg : iconProviders) { - if (reg.getTextureType() == event.map.getTextureType()) { - reg.registerIcons(event.map); - } + /** 0 = terrain.png, 1 = items.png */ + public int getTextureType(); } - } - public static IIcon getIconForItem(int itemId, int meta) { - Item item = Item.getItemById(itemId); - if (item == null) { - return null; + private static ArrayList iconProviders = new ArrayList(); + + public static IIcon whiteTexture; + public static IIcon blankTexture; + public static IIcon errorTexture; + + static { + MinecraftForge.EVENT_BUS.register(new IconUtil()); + addIconProvider(new IIconProvider() { + + @Override + public void registerIcons(IIconRegister register) { + whiteTexture = register.registerIcon("enderio:white"); + errorTexture = register.registerIcon("enderio:error"); + blankTexture = register.registerIcon("enderio:blank"); + } + + @Override + public int getTextureType() { + return 0; + } + }); + } + + public static void addIconProvider(IIconProvider registrar) { + iconProviders.add(registrar); + } + + @Mod.EventHandler + @SubscribeEvent + public void onIconLoad(TextureStitchEvent.Pre event) { + for (IIconProvider reg : iconProviders) { + if (reg.getTextureType() == event.map.getTextureType()) { + reg.registerIcons(event.map); + } + } + } + + public static IIcon getIconForItem(int itemId, int meta) { + Item item = Item.getItemById(itemId); + if (item == null) { + return null; + } + return item.getIconFromDamage(meta); } - return item.getIconFromDamage(meta); - } } diff --git a/src/main/java/com/enderio/core/client/render/RenderUtil.java b/src/main/java/com/enderio/core/client/render/RenderUtil.java index 83682d5..35bc193 100644 --- a/src/main/java/com/enderio/core/client/render/RenderUtil.java +++ b/src/main/java/com/enderio/core/client/render/RenderUtil.java @@ -1,5 +1,8 @@ package com.enderio.core.client.render; +import static net.minecraftforge.common.util.ForgeDirection.*; +import static org.lwjgl.opengl.GL11.*; + import java.lang.reflect.Field; import java.nio.FloatBuffer; import java.util.ArrayList; @@ -13,7 +16,6 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderManager; @@ -31,7 +33,6 @@ import net.minecraft.util.Timer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.client.ForgeHooksClient; -import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; @@ -50,693 +51,714 @@ import com.enderio.core.common.vecmath.Vector3f; import com.enderio.core.common.vecmath.Vector4d; import com.enderio.core.common.vecmath.Vector4f; import com.enderio.core.common.vecmath.Vertex; - import cpw.mods.fml.relauncher.ReflectionHelper; -import static net.minecraftforge.common.util.ForgeDirection.*; -import static org.lwjgl.opengl.GL11.*; public class RenderUtil { - public static final Vector4f DEFAULT_TEXT_SHADOW_COL = new Vector4f(0.33f, 0.33f, 0.33f, 0.33f); + public static final Vector4f DEFAULT_TEXT_SHADOW_COL = new Vector4f(0.33f, 0.33f, 0.33f, 0.33f); - public static final Vector4f DEFAULT_TXT_COL = new Vector4f(1, 1, 1, 1); + public static final Vector4f DEFAULT_TXT_COL = new Vector4f(1, 1, 1, 1); - public static final Vector4f DEFAULT_TEXT_BG_COL = new Vector4f(0.275f, 0.08f, 0.4f, 0.75f); + public static final Vector4f DEFAULT_TEXT_BG_COL = new Vector4f(0.275f, 0.08f, 0.4f, 0.75f); - public static final Vector3d UP_V = new Vector3d(0, 1, 0); + public static final Vector3d UP_V = new Vector3d(0, 1, 0); - public static final Vector3d ZERO_V = new Vector3d(0, 0, 0); + public static final Vector3d ZERO_V = new Vector3d(0, 0, 0); - private static final FloatBuffer MATRIX_BUFFER = GLAllocation.createDirectFloatBuffer(16); + private static final FloatBuffer MATRIX_BUFFER = GLAllocation.createDirectFloatBuffer(16); - public static final ResourceLocation BLOCK_TEX = TextureMap.locationBlocksTexture; + public static final ResourceLocation BLOCK_TEX = TextureMap.locationBlocksTexture; - public static final ResourceLocation ITEM_TEX = TextureMap.locationItemsTexture; + public static final ResourceLocation ITEM_TEX = TextureMap.locationItemsTexture; - public static final ResourceLocation GLINT_TEX = new ResourceLocation("textures/misc/enchanted_item_glint.png"); + public static final ResourceLocation GLINT_TEX = new ResourceLocation("textures/misc/enchanted_item_glint.png"); - public static int BRIGHTNESS_MAX = 15 << 20 | 15 << 4; + public static int BRIGHTNESS_MAX = 15 << 20 | 15 << 4; - public static void loadMatrix(Matrix4d mat) { - MATRIX_BUFFER.rewind(); - MATRIX_BUFFER.put((float) mat.m00); - MATRIX_BUFFER.put((float) mat.m01); - MATRIX_BUFFER.put((float) mat.m02); - MATRIX_BUFFER.put((float) mat.m03); - MATRIX_BUFFER.put((float) mat.m10); - MATRIX_BUFFER.put((float) mat.m11); - MATRIX_BUFFER.put((float) mat.m12); - MATRIX_BUFFER.put((float) mat.m13); - MATRIX_BUFFER.put((float) mat.m20); - MATRIX_BUFFER.put((float) mat.m21); - MATRIX_BUFFER.put((float) mat.m22); - MATRIX_BUFFER.put((float) mat.m23); - MATRIX_BUFFER.put((float) mat.m30); - MATRIX_BUFFER.put((float) mat.m31); - MATRIX_BUFFER.put((float) mat.m32); - MATRIX_BUFFER.put((float) mat.m33); - MATRIX_BUFFER.rewind(); - GL11.glLoadMatrix(MATRIX_BUFFER); - } - - private static Field timerField = initTimer(); - - /** - * Non-thread-safe holder for the current render pass. You must update this in - * your block's canRenderInPass method for it to work properly! - * - * DEPRECATED - Should use {@link ForgeHooksClient#getWorldRenderPass()} - */ - @Deprecated - public static volatile int theRenderPass = 0; - - private static Field initTimer() { - Field f = null; - try { - f = ReflectionHelper.findField(Minecraft.class, "field_71428_T", "timer", "Q"); - f.setAccessible(true); - } catch (Exception e) { - Log.error("Failed to initialize timer reflection for IO config."); - e.printStackTrace(); - } - return f; - } - - @Nullable - public static Timer getTimer() { - if (timerField == null) { - return null; - } - try { - return (Timer) timerField.get(Minecraft.getMinecraft()); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public static TextureManager engine() { - return Minecraft.getMinecraft().renderEngine; - } - - public static void bindItemTexture(ItemStack stack) { - engine().bindTexture(stack.getItemSpriteNumber() == 0 ? BLOCK_TEX : ITEM_TEX); - } - - public static void bindItemTexture() { - engine().bindTexture(ITEM_TEX); - } - - public static void bindBlockTexture() { - engine().bindTexture(BLOCK_TEX); - } - - public static void bindGlintTexture() { - engine().bindTexture(BLOCK_TEX); - } - - public static void bindTexture(String string) { - engine().bindTexture(new ResourceLocation(string)); - } - - public static void bindTexture(ResourceLocation tex) { - engine().bindTexture(tex); - } - - public static FontRenderer fontRenderer() { - return Minecraft.getMinecraft().fontRenderer; - } - - public static float[] getDefaultPerSideBrightness() { - float[] brightnessPerSide = new float[6]; - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { - brightnessPerSide[dir.ordinal()] = RenderUtil.getColorMultiplierForFace(dir); - } - return brightnessPerSide; - } - - public static IIcon[] getBlockTextures(Block block, int meta) { - IIcon[] icons = new IIcon[6]; - int i = 0; - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { - icons[i] = block.getIcon(dir.ordinal(), meta); - i++; - } - return icons; - } - - public static IIcon[] getBlockTextures(IBlockAccess world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); - IIcon[] icons = new IIcon[6]; - int i = 0; - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { - icons[i] = block.getIcon(world, x, y, z, dir.ordinal()); - i++; - } - return icons; - } - - public static float claculateTotalBrightnessForLocation(World worldObj, int xCoord, int yCoord, int zCoord) { - int i = worldObj.getLightBrightnessForSkyBlocks(xCoord, yCoord, zCoord, 0); - int j = i % 65536; - int k = i / 65536; - - float minLight = 0; - //0.2 - 1 - float sunBrightness = worldObj.getSunBrightness(1); - - float percentRecievedFromSun = k / 255f; - - //Highest value recieved from a light - float fromLights = j / 255f; - - // 0 - 1 for sun only, 0 - 0.6 for light only - float recievedPercent = worldObj.getLightBrightness(xCoord, yCoord, zCoord); - float highestValue = Math.max(fromLights, percentRecievedFromSun * sunBrightness); - return Math.max(0.2f, highestValue); - } - - public static float getColorMultiplierForFace(ForgeDirection face) { - if (face == ForgeDirection.UP) { - return 1; - } - if (face == ForgeDirection.DOWN) { - return 0.5f; - } - if (face.offsetX != 0) { - return 0.6f; - } - return 0.8f; // z - } - - public static int setTesselatorBrightness(IBlockAccess world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); - int res = block == null ? world.getLightBrightnessForSkyBlocks(x, y, z, 0) : block.getMixedBrightnessForBlock(world, x, y, z); - Tessellator.instance.setBrightness(res); - Tessellator.instance.setColorRGBA_F(1, 1, 1, 1); - return res; - } - - public static void renderQuad2D(double x, double y, double z, double width, double height, int colorRGB) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glDisable(GL11.GL_TEXTURE_2D); - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.setColorOpaque_I(colorRGB); - tessellator.addVertex(x, y + height, z); - tessellator.addVertex(x + width, y + height, z); - tessellator.addVertex(x + width, y, z); - tessellator.addVertex(x, y, z); - tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - } - - public static void renderQuad2D(double x, double y, double z, double width, double height, Vector4f colorRGBA) { - GL11.glColor4f(colorRGBA.x, colorRGBA.y, colorRGBA.z, colorRGBA.w); - GL11.glDisable(GL11.GL_TEXTURE_2D); - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.addVertex(x, y + height, z); - tessellator.addVertex(x + width, y + height, z); - tessellator.addVertex(x + width, y, z); - tessellator.addVertex(x, y, z); - tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - } - - public static Matrix4d createBillboardMatrix(TileEntity te, EntityLivingBase entityPlayer) { - return createBillboardMatrix(new Vector3d(te.xCoord + 0.5, te.yCoord + 0.5, te.zCoord + 0.5), entityPlayer); - } - - public static Matrix4d createBillboardMatrix(Vector3d lookAt, EntityLivingBase entityPlayer) { - Vector3d playerEye = new Vector3d(entityPlayer.posX, entityPlayer.posY + 1.62 - entityPlayer.yOffset, entityPlayer.posZ); - Vector3d blockOrigin = new Vector3d(lookAt.x, lookAt.y, lookAt.z); - Matrix4d lookMat = VecmathUtil.createMatrixAsLookAt(blockOrigin, playerEye, RenderUtil.UP_V); - lookMat.setTranslation(new Vector3d()); - lookMat.invert(); - return lookMat; - } - - public static void renderBillboard(Matrix4d lookMat, float minU, float maxU, float minV, float maxV, double size, int brightness) { - Tessellator tes = Tessellator.instance; - tes.startDrawingQuads(); - tes.setBrightness(brightness); - - double s = size / 2; - Vector3d v = new Vector3d(); - v.set(-s, s, 0); - lookMat.transform(v); - tes.addVertexWithUV(v.x, v.y, v.z, minU, maxV); - v.set(s, s, 0); - lookMat.transform(v); - tes.addVertexWithUV(v.x, v.y, v.z, maxU, maxV); - v.set(s, -s, 0); - lookMat.transform(v); - tes.addVertexWithUV(v.x, v.y, v.z, maxU, minV); - v.set(-s, -s, 0); - lookMat.transform(v); - tes.addVertexWithUV(v.x, v.y, v.z, minU, minV); - tes.draw(); - } - - /** - * @return The edge directions for a face, in the order left, bottom, right, - * top. - */ - public static List getEdgesForFace(ForgeDirection face) { - List result = new ArrayList(4); - if (face.offsetY != 0) { - result.add(NORTH); - result.add(EAST); - result.add(SOUTH); - result.add(WEST); - - } else if (face.offsetX != 0) { - result.add(DOWN); - result.add(SOUTH); - result.add(UP); - result.add(NORTH); - } else { - result.add(DOWN); - result.add(WEST); - result.add(UP); - result.add(EAST); - } - return result; - } - - public static void addVerticesToTesselator(List vertices) { - addVerticesToTessellator(vertices, Tessellator.instance); - } - - public static void addVerticesToTessellator(List vertices, Tessellator tes) { - for (Vertex v : vertices) { - if (v.brightness != -1) { - tes.setBrightness(v.brightness); - } - if (v.color != null) { - tes.setColorRGBA_F(v.r(), v.g(), v.b(), v.a()); - } - if (v.uv != null) { - tes.setTextureUV(v.u(), v.v()); - } - if (v.normal != null) { - tes.setNormal(v.nx(), v.ny(), v.nz()); - } - tes.addVertex(v.x(), v.y(), v.z()); - } - } - - public static void renderConnectedTextureFace(IBlockAccess blockAccess, Block block, int x, int y, int z, ForgeDirection face, IIcon texture, - boolean forceAllEdges) { - renderConnectedTextureFace(blockAccess, block, x, y, z, face, texture, forceAllEdges, true, true); - } - - public static void renderConnectedTextureFace(IBlockAccess blockAccess, Block block, int x, int y, int z, ForgeDirection face, IIcon texture, - boolean forceAllEdges, boolean translateToXYZ, boolean applyFaceShading) { - - if ((blockAccess == null && !forceAllEdges) || face == null || texture == null) { - return; + public static void loadMatrix(Matrix4d mat) { + MATRIX_BUFFER.rewind(); + MATRIX_BUFFER.put((float) mat.m00); + MATRIX_BUFFER.put((float) mat.m01); + MATRIX_BUFFER.put((float) mat.m02); + MATRIX_BUFFER.put((float) mat.m03); + MATRIX_BUFFER.put((float) mat.m10); + MATRIX_BUFFER.put((float) mat.m11); + MATRIX_BUFFER.put((float) mat.m12); + MATRIX_BUFFER.put((float) mat.m13); + MATRIX_BUFFER.put((float) mat.m20); + MATRIX_BUFFER.put((float) mat.m21); + MATRIX_BUFFER.put((float) mat.m22); + MATRIX_BUFFER.put((float) mat.m23); + MATRIX_BUFFER.put((float) mat.m30); + MATRIX_BUFFER.put((float) mat.m31); + MATRIX_BUFFER.put((float) mat.m32); + MATRIX_BUFFER.put((float) mat.m33); + MATRIX_BUFFER.rewind(); + GL11.glLoadMatrix(MATRIX_BUFFER); } - if (!forceAllEdges) { - Block check = blockAccess.getBlock(x, y, z); - if (check == null) { - return; - } - if (!check.shouldSideBeRendered(blockAccess, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal())) { - return; - } - } + private static Field timerField = initTimer(); - List edges; - if (forceAllEdges) { - edges = RenderUtil.getEdgesForFace(face); - } else { - edges = RenderUtil.getNonConectedEdgesForFace(blockAccess, x, y, z, face); - } + /** + * Non-thread-safe holder for the current render pass. You must update this in your block's canRenderInPass method + * for it to work properly! + * + * DEPRECATED - Should use {@link ForgeHooksClient#getWorldRenderPass()} + */ + @Deprecated + public static volatile int theRenderPass = 0; - Tessellator tes = Tessellator.instance; - tes.setNormal(face.offsetX, face.offsetY, face.offsetZ); - if (applyFaceShading) { - float cm = RenderUtil.getColorMultiplierForFace(face); - tes.setColorOpaque_F(cm, cm, cm); - } - - float scaleFactor = 15f / 16f; - Vector2f uv = new Vector2f(); - for (ForgeDirection edge : edges) { - - 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 - block.getBlockBoundsMaxX()) - block.getBlockBoundsMinX(); - yLen -= 2 * (1 - block.getBlockBoundsMaxY()) - block.getBlockBoundsMinY(); - zLen -= 2 * (1 - block.getBlockBoundsMaxZ()) - block.getBlockBoundsMinZ(); - - BoundingBox bb = BoundingBox.UNIT_CUBE.scale(xLen, yLen, zLen); - - List corners = bb.getCornersForFace(face); - - for (Vector3f unitCorn : corners) { - Vector3d corner = new Vector3d(unitCorn); - if (translateToXYZ) { - corner.x += x; - corner.y += y; - corner.z += z; + private static Field initTimer() { + Field f = null; + try { + f = ReflectionHelper.findField(Minecraft.class, "field_71428_T", "timer", "Q"); + f.setAccessible(true); + } catch (Exception e) { + Log.error("Failed to initialize timer reflection for IO config."); + e.printStackTrace(); } + return f; + } - corner.x += (float) (edge.offsetX * 0.5) - Math.signum(edge.offsetX) * xLen / 2f; - corner.y += (float) (edge.offsetY * 0.5) - Math.signum(edge.offsetY) * yLen / 2f; - corner.z += (float) (edge.offsetZ * 0.5) - Math.signum(edge.offsetZ) * zLen / 2f; + @Nullable + public static Timer getTimer() { + if (timerField == null) { + return null; + } + try { + return (Timer) timerField.get(Minecraft.getMinecraft()); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } - if (translateToXYZ) { - RenderUtil.getUvForCorner(uv, corner, x, y, z, face, texture); + public static TextureManager engine() { + return Minecraft.getMinecraft().renderEngine; + } + + public static void bindItemTexture(ItemStack stack) { + engine().bindTexture(stack.getItemSpriteNumber() == 0 ? BLOCK_TEX : ITEM_TEX); + } + + public static void bindItemTexture() { + engine().bindTexture(ITEM_TEX); + } + + public static void bindBlockTexture() { + engine().bindTexture(BLOCK_TEX); + } + + public static void bindGlintTexture() { + engine().bindTexture(BLOCK_TEX); + } + + public static void bindTexture(String string) { + engine().bindTexture(new ResourceLocation(string)); + } + + public static void bindTexture(ResourceLocation tex) { + engine().bindTexture(tex); + } + + public static FontRenderer fontRenderer() { + return Minecraft.getMinecraft().fontRenderer; + } + + public static float[] getDefaultPerSideBrightness() { + float[] brightnessPerSide = new float[6]; + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + brightnessPerSide[dir.ordinal()] = RenderUtil.getColorMultiplierForFace(dir); + } + return brightnessPerSide; + } + + public static IIcon[] getBlockTextures(Block block, int meta) { + IIcon[] icons = new IIcon[6]; + int i = 0; + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + icons[i] = block.getIcon(dir.ordinal(), meta); + i++; + } + return icons; + } + + public static IIcon[] getBlockTextures(IBlockAccess world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); + IIcon[] icons = new IIcon[6]; + int i = 0; + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + icons[i] = block.getIcon(world, x, y, z, dir.ordinal()); + i++; + } + return icons; + } + + public static float claculateTotalBrightnessForLocation(World worldObj, int xCoord, int yCoord, int zCoord) { + int i = worldObj.getLightBrightnessForSkyBlocks(xCoord, yCoord, zCoord, 0); + int j = i % 65536; + int k = i / 65536; + + float minLight = 0; + // 0.2 - 1 + float sunBrightness = worldObj.getSunBrightness(1); + + float percentRecievedFromSun = k / 255f; + + // Highest value recieved from a light + float fromLights = j / 255f; + + // 0 - 1 for sun only, 0 - 0.6 for light only + float recievedPercent = worldObj.getLightBrightness(xCoord, yCoord, zCoord); + float highestValue = Math.max(fromLights, percentRecievedFromSun * sunBrightness); + return Math.max(0.2f, highestValue); + } + + public static float getColorMultiplierForFace(ForgeDirection face) { + if (face == ForgeDirection.UP) { + return 1; + } + if (face == ForgeDirection.DOWN) { + return 0.5f; + } + if (face.offsetX != 0) { + return 0.6f; + } + return 0.8f; // z + } + + public static int setTesselatorBrightness(IBlockAccess world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); + int res = block == null ? world.getLightBrightnessForSkyBlocks(x, y, z, 0) + : block.getMixedBrightnessForBlock(world, x, y, z); + Tessellator.instance.setBrightness(res); + Tessellator.instance.setColorRGBA_F(1, 1, 1, 1); + return res; + } + + public static void renderQuad2D(double x, double y, double z, double width, double height, int colorRGB) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glDisable(GL11.GL_TEXTURE_2D); + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.setColorOpaque_I(colorRGB); + tessellator.addVertex(x, y + height, z); + tessellator.addVertex(x + width, y + height, z); + tessellator.addVertex(x + width, y, z); + tessellator.addVertex(x, y, z); + tessellator.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } + + public static void renderQuad2D(double x, double y, double z, double width, double height, Vector4f colorRGBA) { + GL11.glColor4f(colorRGBA.x, colorRGBA.y, colorRGBA.z, colorRGBA.w); + GL11.glDisable(GL11.GL_TEXTURE_2D); + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.addVertex(x, y + height, z); + tessellator.addVertex(x + width, y + height, z); + tessellator.addVertex(x + width, y, z); + tessellator.addVertex(x, y, z); + tessellator.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } + + public static Matrix4d createBillboardMatrix(TileEntity te, EntityLivingBase entityPlayer) { + return createBillboardMatrix(new Vector3d(te.xCoord + 0.5, te.yCoord + 0.5, te.zCoord + 0.5), entityPlayer); + } + + public static Matrix4d createBillboardMatrix(Vector3d lookAt, EntityLivingBase entityPlayer) { + Vector3d playerEye = new Vector3d( + entityPlayer.posX, + entityPlayer.posY + 1.62 - entityPlayer.yOffset, + entityPlayer.posZ); + Vector3d blockOrigin = new Vector3d(lookAt.x, lookAt.y, lookAt.z); + Matrix4d lookMat = VecmathUtil.createMatrixAsLookAt(blockOrigin, playerEye, RenderUtil.UP_V); + lookMat.setTranslation(new Vector3d()); + lookMat.invert(); + return lookMat; + } + + public static void renderBillboard(Matrix4d lookMat, float minU, float maxU, float minV, float maxV, double size, + int brightness) { + Tessellator tes = Tessellator.instance; + tes.startDrawingQuads(); + tes.setBrightness(brightness); + + double s = size / 2; + Vector3d v = new Vector3d(); + v.set(-s, s, 0); + lookMat.transform(v); + tes.addVertexWithUV(v.x, v.y, v.z, minU, maxV); + v.set(s, s, 0); + lookMat.transform(v); + tes.addVertexWithUV(v.x, v.y, v.z, maxU, maxV); + v.set(s, -s, 0); + lookMat.transform(v); + tes.addVertexWithUV(v.x, v.y, v.z, maxU, minV); + v.set(-s, -s, 0); + lookMat.transform(v); + tes.addVertexWithUV(v.x, v.y, v.z, minU, minV); + tes.draw(); + } + + /** + * @return The edge directions for a face, in the order left, bottom, right, top. + */ + public static List getEdgesForFace(ForgeDirection face) { + List result = new ArrayList(4); + if (face.offsetY != 0) { + result.add(NORTH); + result.add(EAST); + result.add(SOUTH); + result.add(WEST); + + } else if (face.offsetX != 0) { + result.add(DOWN); + result.add(SOUTH); + result.add(UP); + result.add(NORTH); } else { - RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture); + result.add(DOWN); + result.add(WEST); + result.add(UP); + result.add(EAST); + } + return result; + } + + public static void addVerticesToTesselator(List vertices) { + addVerticesToTessellator(vertices, Tessellator.instance); + } + + public static void addVerticesToTessellator(List vertices, Tessellator tes) { + for (Vertex v : vertices) { + if (v.brightness != -1) { + tes.setBrightness(v.brightness); + } + if (v.color != null) { + tes.setColorRGBA_F(v.r(), v.g(), v.b(), v.a()); + } + if (v.uv != null) { + tes.setTextureUV(v.u(), v.v()); + } + if (v.normal != null) { + tes.setNormal(v.nx(), v.ny(), v.nz()); + } + tes.addVertex(v.x(), v.y(), v.z()); + } + } + + public static void renderConnectedTextureFace(IBlockAccess blockAccess, Block block, int x, int y, int z, + ForgeDirection face, IIcon texture, boolean forceAllEdges) { + renderConnectedTextureFace(blockAccess, block, x, y, z, face, texture, forceAllEdges, true, true); + } + + public static void renderConnectedTextureFace(IBlockAccess blockAccess, Block block, int x, int y, int z, + ForgeDirection face, IIcon texture, boolean forceAllEdges, boolean translateToXYZ, + boolean applyFaceShading) { + + if ((blockAccess == null && !forceAllEdges) || face == null || texture == null) { + return; + } + + if (!forceAllEdges) { + Block check = blockAccess.getBlock(x, y, z); + if (check == null) { + return; + } + if (!check.shouldSideBeRendered( + blockAccess, + x + face.offsetX, + y + face.offsetY, + z + face.offsetZ, + face.ordinal())) { + return; + } + } + + List edges; + if (forceAllEdges) { + edges = RenderUtil.getEdgesForFace(face); + } else { + edges = RenderUtil.getNonConectedEdgesForFace(blockAccess, x, y, z, face); + } + + Tessellator tes = Tessellator.instance; + tes.setNormal(face.offsetX, face.offsetY, face.offsetZ); + if (applyFaceShading) { + float cm = RenderUtil.getColorMultiplierForFace(face); + tes.setColorOpaque_F(cm, cm, cm); + } + + float scaleFactor = 15f / 16f; + Vector2f uv = new Vector2f(); + for (ForgeDirection edge : edges) { + + 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 - block.getBlockBoundsMaxX()) - block.getBlockBoundsMinX(); + yLen -= 2 * (1 - block.getBlockBoundsMaxY()) - block.getBlockBoundsMinY(); + zLen -= 2 * (1 - block.getBlockBoundsMaxZ()) - block.getBlockBoundsMinZ(); + + BoundingBox bb = BoundingBox.UNIT_CUBE.scale(xLen, yLen, zLen); + + List corners = bb.getCornersForFace(face); + + for (Vector3f unitCorn : corners) { + Vector3d corner = new Vector3d(unitCorn); + if (translateToXYZ) { + corner.x += x; + corner.y += y; + corner.z += z; + } + + corner.x += (float) (edge.offsetX * 0.5) - Math.signum(edge.offsetX) * xLen / 2f; + corner.y += (float) (edge.offsetY * 0.5) - Math.signum(edge.offsetY) * yLen / 2f; + corner.z += (float) (edge.offsetZ * 0.5) - Math.signum(edge.offsetZ) * zLen / 2f; + + if (translateToXYZ) { + RenderUtil.getUvForCorner(uv, corner, x, y, z, face, texture); + } else { + RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture); + } + tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); + } + } - tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); - } } - } - - public static List getNonConectedEdgesForFace(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection face) { - return getNonConectedEdgesForFace(blockAccess, x, y, z, face, null); - } - - public static List getNonConectedEdgesForFace(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection face, - IConnectedTextureRenderer render) { - - Block block = blockAccess.getBlock(x, y, z); - if (block == null) { - return Collections.emptyList(); - } - if (!block.shouldSideBeRendered(blockAccess, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal())) { - return Collections.emptyList(); - } - BlockCoord bc = new BlockCoord(x, y, z); - - List edges = new ArrayList(4); - for (ForgeDirection dir : getEdgesForFace(face)) { - edges.add(new EdgeNeighbour(bc, dir)); - } - List result = new ArrayList(4); - for (EdgeNeighbour edge : edges) { - boolean matchingNeighbour = blockAccess.getBlock(edge.bc.x, edge.bc.y, edge.bc.z) == block; - if (matchingNeighbour && render != null) { - matchingNeighbour = render.matchesMetadata(blockAccess.getBlockMetadata(x, y, z), blockAccess.getBlockMetadata(edge.bc.x, edge.bc.y, edge.bc.z)); - } - if (!matchingNeighbour) { - result.add(edge.dir); - } - - } - return result; - } - - public static void getUvForCorner(Vector2f uv, Vector3d corner, int x, int y, int z, ForgeDirection face, IIcon icon) { - if (icon == null) { - return; + public static List getNonConectedEdgesForFace(IBlockAccess blockAccess, int x, int y, int z, + ForgeDirection face) { + return getNonConectedEdgesForFace(blockAccess, x, y, z, face, null); } - Vector3d p = new Vector3d(corner); - p.x -= x; - p.y -= y; - p.z -= z; + public static List getNonConectedEdgesForFace(IBlockAccess blockAccess, int x, int y, int z, + ForgeDirection face, IConnectedTextureRenderer render) { - float uWidth = 1; - float vWidth = 1; - if (icon != null) { - uWidth = icon.getMaxU() - icon.getMinU(); - vWidth = icon.getMaxV() - icon.getMinV(); + Block block = blockAccess.getBlock(x, y, z); + if (block == null) { + return Collections.emptyList(); + } + if (!block.shouldSideBeRendered( + blockAccess, + x + face.offsetX, + y + face.offsetY, + z + face.offsetZ, + face.ordinal())) { + return Collections.emptyList(); + } + BlockCoord bc = new BlockCoord(x, y, z); + + List edges = new ArrayList(4); + for (ForgeDirection dir : getEdgesForFace(face)) { + edges.add(new EdgeNeighbour(bc, dir)); + } + List result = new ArrayList(4); + for (EdgeNeighbour edge : edges) { + boolean matchingNeighbour = blockAccess.getBlock(edge.bc.x, edge.bc.y, edge.bc.z) == block; + if (matchingNeighbour && render != null) { + matchingNeighbour = render.matchesMetadata( + blockAccess.getBlockMetadata(x, y, z), + blockAccess.getBlockMetadata(edge.bc.x, edge.bc.y, edge.bc.z)); + } + if (!matchingNeighbour) { + result.add(edge.dir); + } + + } + return result; } - uv.x = (float) VecmathUtil.distanceFromPointToPlane(getUPlaneForFace(face), p); - uv.y = (float) VecmathUtil.distanceFromPointToPlane(getVPlaneForFace(face), p); + public static void getUvForCorner(Vector2f uv, Vector3d corner, int x, int y, int z, ForgeDirection face, + IIcon icon) { + if (icon == null) { + return; + } + + Vector3d p = new Vector3d(corner); + p.x -= x; + p.y -= y; + p.z -= z; + + float uWidth = 1; + float vWidth = 1; + if (icon != null) { + uWidth = icon.getMaxU() - icon.getMinU(); + vWidth = icon.getMaxV() - icon.getMinV(); + } + + uv.x = (float) VecmathUtil.distanceFromPointToPlane(getUPlaneForFace(face), p); + uv.y = (float) VecmathUtil.distanceFromPointToPlane(getVPlaneForFace(face), p); + + if (icon != null) { + uv.x = icon.getMinU() + (uv.x * uWidth); + uv.y = icon.getMinV() + (uv.y * vWidth); + } - if (icon != null) { - uv.x = icon.getMinU() + (uv.x * uWidth); - uv.y = icon.getMinV() + (uv.y * vWidth); } - } - - public static Vector4d getVPlaneForFace(ForgeDirection face) { - switch (face) { - case DOWN: - case UP: - return new Vector4d(0, 0, 1, 0); - case EAST: - case WEST: - case NORTH: - case SOUTH: - return new Vector4d(0, -1, 0, 1); - case UNKNOWN: - default: - break; - } - return null; - } - - public static Vector4d getUPlaneForFace(ForgeDirection face) { - switch (face) { - case DOWN: - case UP: - return new Vector4d(1, 0, 0, 0); - case EAST: - return new Vector4d(0, 0, -1, 1); - case WEST: - return new Vector4d(0, 0, 1, 0); - case NORTH: - return new Vector4d(-1, 0, 0, 1); - case SOUTH: - return new Vector4d(1, 0, 0, 0); - case UNKNOWN: - default: - break; - } - return null; - } - - public static ForgeDirection getVDirForFace(ForgeDirection face) { - switch (face) { - case DOWN: - case UP: - return SOUTH; - case EAST: - case WEST: - case NORTH: - case SOUTH: - return ForgeDirection.UP; - case UNKNOWN: - default: - break; - } - return null; - } - - public static ForgeDirection getUDirForFace(ForgeDirection face) { - switch (face) { - case DOWN: - case UP: - return ForgeDirection.EAST; - case EAST: - return NORTH; - case WEST: - return SOUTH; - case NORTH: - return WEST; - case SOUTH: - return ForgeDirection.EAST; - case UNKNOWN: - default: - break; - } - return null; - } - - public static void renderGuiTank(FluidTank tank, double x, double y, double zLevel, double width, double height) { - renderGuiTank(tank.getFluid(), tank.getCapacity(), tank.getFluidAmount(), x, y, zLevel, width, height); - } - - public static void renderGuiTank(FluidStack fluid, int capacity, int amount, double x, double y, double zLevel, double width, double height) { - if (fluid == null || fluid.getFluid() == null || fluid.amount <= 0) { - return; + public static Vector4d getVPlaneForFace(ForgeDirection face) { + switch (face) { + case DOWN: + case UP: + return new Vector4d(0, 0, 1, 0); + case EAST: + case WEST: + case NORTH: + case SOUTH: + return new Vector4d(0, -1, 0, 1); + case UNKNOWN: + default: + break; + } + return null; } - IIcon icon = fluid.getFluid().getStillIcon(); - if (icon == null) { - icon = fluid.getFluid().getIcon(); - if (icon == null) { - return; - } + public static Vector4d getUPlaneForFace(ForgeDirection face) { + switch (face) { + case DOWN: + case UP: + return new Vector4d(1, 0, 0, 0); + case EAST: + return new Vector4d(0, 0, -1, 1); + case WEST: + return new Vector4d(0, 0, 1, 0); + case NORTH: + return new Vector4d(-1, 0, 0, 1); + case SOUTH: + return new Vector4d(1, 0, 0, 0); + case UNKNOWN: + default: + break; + } + return null; } - int renderAmount = (int) Math.max(Math.min(height, amount * height / capacity), 1); - int posY = (int) (y + height - renderAmount); + public static ForgeDirection getVDirForFace(ForgeDirection face) { + switch (face) { + case DOWN: + case UP: + return SOUTH; + case EAST: + case WEST: + case NORTH: + case SOUTH: + return ForgeDirection.UP; + case UNKNOWN: + default: + break; + } + return null; + } - RenderUtil.bindBlockTexture(); - int color = fluid.getFluid().getColor(fluid); - GL11.glColor3ub((byte) (color >> 16 & 0xFF), (byte) (color >> 8 & 0xFF), (byte) (color & 0xFF)); + public static ForgeDirection getUDirForFace(ForgeDirection face) { + switch (face) { + case DOWN: + case UP: + return ForgeDirection.EAST; + case EAST: + return NORTH; + case WEST: + return SOUTH; + case NORTH: + return WEST; + case SOUTH: + return ForgeDirection.EAST; + case UNKNOWN: + default: + break; + } + return null; + } - GL11.glEnable(GL11.GL_BLEND); - for (int i = 0; i < width; i += 16) { - for (int j = 0; j < renderAmount; j += 16) { - int drawWidth = (int) Math.min(width - i, 16); - int drawHeight = Math.min(renderAmount - j, 16); + public static void renderGuiTank(FluidTank tank, double x, double y, double zLevel, double width, double height) { + renderGuiTank(tank.getFluid(), tank.getCapacity(), tank.getFluidAmount(), x, y, zLevel, width, height); + } - int drawX = (int) (x + i); - int drawY = posY + j; + public static void renderGuiTank(FluidStack fluid, int capacity, int amount, double x, double y, double zLevel, + double width, double height) { + if (fluid == null || fluid.getFluid() == null || fluid.amount <= 0) { + return; + } - double minU = icon.getMinU(); - double maxU = icon.getMaxU(); - double minV = icon.getMinV(); - double maxV = icon.getMaxV(); + IIcon icon = fluid.getFluid().getStillIcon(); + if (icon == null) { + icon = fluid.getFluid().getIcon(); + if (icon == null) { + return; + } + } + + int renderAmount = (int) Math.max(Math.min(height, amount * height / capacity), 1); + int posY = (int) (y + height - renderAmount); + + RenderUtil.bindBlockTexture(); + int color = fluid.getFluid().getColor(fluid); + GL11.glColor3ub((byte) (color >> 16 & 0xFF), (byte) (color >> 8 & 0xFF), (byte) (color & 0xFF)); + + GL11.glEnable(GL11.GL_BLEND); + for (int i = 0; i < width; i += 16) { + for (int j = 0; j < renderAmount; j += 16) { + int drawWidth = (int) Math.min(width - i, 16); + int drawHeight = Math.min(renderAmount - j, 16); + + int drawX = (int) (x + i); + int drawY = posY + j; + + double minU = icon.getMinU(); + double maxU = icon.getMaxU(); + double minV = icon.getMinV(); + double maxV = icon.getMaxV(); + + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator + .addVertexWithUV(drawX, drawY + drawHeight, 0, minU, minV + (maxV - minV) * drawHeight / 16F); + tessellator.addVertexWithUV( + drawX + drawWidth, + drawY + drawHeight, + 0, + minU + (maxU - minU) * drawWidth / 16F, + minV + (maxV - minV) * drawHeight / 16F); + tessellator.addVertexWithUV(drawX + drawWidth, drawY, 0, minU + (maxU - minU) * drawWidth / 16F, minV); + tessellator.addVertexWithUV(drawX, drawY, 0, minU, minV); + tessellator.draw(); + } + } + GL11.glDisable(GL11.GL_BLEND); + } + + public static void drawBillboardedText(Vector3f pos, String text, float size) { + drawBillboardedText(pos, text, size, DEFAULT_TXT_COL, true, DEFAULT_TEXT_SHADOW_COL, true, DEFAULT_TEXT_BG_COL); + } + + public static void drawBillboardedText(Vector3f pos, String text, float size, Vector4f bgCol) { + drawBillboardedText(pos, text, size, DEFAULT_TXT_COL, true, DEFAULT_TEXT_SHADOW_COL, true, bgCol); + } + + public static void drawBillboardedText(Vector3f pos, String text, float size, Vector4f txtCol, boolean drawShadow, + Vector4f shadowCol, boolean drawBackground, Vector4f bgCol) { + GL11.glPushMatrix(); + GL11.glTranslatef(pos.x, pos.y, pos.z); + glRotatef(180, 1, 0, 0); + + FontRenderer fnt = Minecraft.getMinecraft().fontRenderer; + float scale = size / fnt.FONT_HEIGHT; + GL11.glScalef(scale, scale, scale); + glRotatef(RenderManager.instance.playerViewY + 180, 0.0F, 1.0F, 0.0F); + glRotatef(-RenderManager.instance.playerViewX, 1.0F, 0.0F, 0.0F); + + glTranslatef(-fnt.getStringWidth(text) / 2, 0, 0); + if (drawBackground) { + renderBackground(fnt, text, bgCol); + } + fnt.drawString(text, 0, 0, ColorUtil.getRGBA(txtCol)); + if (drawShadow) { + glTranslatef(0.5f, 0.5f, 0.1f); + fnt.drawString(text, 0, 0, ColorUtil.getRGBA(shadowCol)); + } + GL11.glPopMatrix(); + + RenderUtil.bindBlockTexture(); + } + + public static void renderBackground(FontRenderer fnt, String toRender, Vector4f color) { + glPushAttrib(GL_ALL_ATTRIB_BITS); + glDisable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + glShadeModel(GL_SMOOTH); + glDisable(GL_ALPHA_TEST); + glDisable(GL_CULL_FACE); + glDepthMask(false); + RenderHelper.disableStandardItemLighting(); + OpenGlHelper.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); // stop random disappearing + + float width = fnt.getStringWidth(toRender); + float height = fnt.FONT_HEIGHT; + float padding = 2f; + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F(color.x, color.y, color.z, color.w); + tessellator.addVertex(-padding, -padding, 0); + tessellator.addVertex(-padding, height + padding, 0); + tessellator.addVertex(width + padding, height + padding, 0); + tessellator.addVertex(width + padding, -padding, 0); + tessellator.draw(); + + glPopAttrib(); + } + + /** + * Renders an item entity in 3D + * + * @param item The item to render + * @param rotate Whether to "spin" the item like it would if it were a real dropped entity + */ + public static void render3DItem(EntityItem item, boolean rotate) { + float rot = getRotation(1.0f); + + glPushMatrix(); + glDepthMask(true); + rotate &= Minecraft.getMinecraft().gameSettings.fancyGraphics; + + if (rotate) { + glRotatef(rot, 0, 1, 0); + } + + item.hoverStart = 0.0F; + RenderManager.instance.renderEntityWithPosYaw(item, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F); + + glPopMatrix(); + } + + public static float getRotation(float mult) { + return ClientHandler.getTicksElapsed() * mult; + } + + public static void renderBillboardQuad(float rot, double scale) { + glPushMatrix(); + + rotateToPlayer(); + + glPushMatrix(); + + glRotatef(rot, 0, 0, 1); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV(drawX, drawY + drawHeight, 0, minU, minV + (maxV - minV) * drawHeight / 16F); - tessellator.addVertexWithUV(drawX + drawWidth, drawY + drawHeight, 0, minU + (maxU - minU) * drawWidth / 16F, minV + (maxV - minV) * drawHeight / 16F); - tessellator.addVertexWithUV(drawX + drawWidth, drawY, 0, minU + (maxU - minU) * drawWidth / 16F, minV); - tessellator.addVertexWithUV(drawX, drawY, 0, minU, minV); + glColor3f(1, 1, 1); + tessellator.setColorRGBA(255, 255, 255, 255); + tessellator.addVertexWithUV(-scale, -scale, 0, 0, 0); + tessellator.addVertexWithUV(-scale, scale, 0, 0, 1); + tessellator.addVertexWithUV(scale, scale, 0, 1, 1); + tessellator.addVertexWithUV(scale, -scale, 0, 1, 0); tessellator.draw(); - } - } - GL11.glDisable(GL11.GL_BLEND); - } - - public static void drawBillboardedText(Vector3f pos, String text, float size) { - drawBillboardedText(pos, text, size, DEFAULT_TXT_COL, true, DEFAULT_TEXT_SHADOW_COL, true, DEFAULT_TEXT_BG_COL); - } - - public static void drawBillboardedText(Vector3f pos, String text, float size, Vector4f bgCol) { - drawBillboardedText(pos, text, size, DEFAULT_TXT_COL, true, DEFAULT_TEXT_SHADOW_COL, true, bgCol); - } - - public static void drawBillboardedText(Vector3f pos, String text, float size, Vector4f txtCol, boolean drawShadow, Vector4f shadowCol, - boolean drawBackground, Vector4f bgCol) { - GL11.glPushMatrix(); - GL11.glTranslatef(pos.x, pos.y, pos.z); - glRotatef(180, 1, 0, 0); - - FontRenderer fnt = Minecraft.getMinecraft().fontRenderer; - float scale = size / fnt.FONT_HEIGHT; - GL11.glScalef(scale, scale, scale); - glRotatef(RenderManager.instance.playerViewY + 180, 0.0F, 1.0F, 0.0F); - glRotatef(-RenderManager.instance.playerViewX, 1.0F, 0.0F, 0.0F); - - glTranslatef(-fnt.getStringWidth(text) / 2, 0, 0); - if (drawBackground) { - renderBackground(fnt, text, bgCol); - } - fnt.drawString(text, 0, 0, ColorUtil.getRGBA(txtCol)); - if (drawShadow) { - glTranslatef(0.5f, 0.5f, 0.1f); - fnt.drawString(text, 0, 0, ColorUtil.getRGBA(shadowCol)); - } - GL11.glPopMatrix(); - - RenderUtil.bindBlockTexture(); - } - - public static void renderBackground(FontRenderer fnt, String toRender, Vector4f color) { - glPushAttrib(GL_ALL_ATTRIB_BITS); - glDisable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - glShadeModel(GL_SMOOTH); - glDisable(GL_ALPHA_TEST); - glDisable(GL_CULL_FACE); - glDepthMask(false); - RenderHelper.disableStandardItemLighting(); - OpenGlHelper.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); // stop random disappearing - - float width = fnt.getStringWidth(toRender); - float height = fnt.FONT_HEIGHT; - float padding = 2f; - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.setColorRGBA_F(color.x, color.y, color.z, color.w); - tessellator.addVertex(-padding, -padding, 0); - tessellator.addVertex(-padding, height + padding, 0); - tessellator.addVertex(width + padding, height + padding, 0); - tessellator.addVertex(width + padding, -padding, 0); - tessellator.draw(); - - glPopAttrib(); - } - - /** - * Renders an item entity in 3D - * - * @param item - * The item to render - * @param rotate - * Whether to "spin" the item like it would if it were a real dropped - * entity - */ - public static void render3DItem(EntityItem item, boolean rotate) { - float rot = getRotation(1.0f); - - glPushMatrix(); - glDepthMask(true); - rotate &= Minecraft.getMinecraft().gameSettings.fancyGraphics; - - if (rotate) { - glRotatef(rot, 0, 1, 0); + glPopMatrix(); + glPopMatrix(); } - item.hoverStart = 0.0F; - RenderManager.instance.renderEntityWithPosYaw(item, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F); - - glPopMatrix(); - } - - public static float getRotation(float mult) { - return ClientHandler.getTicksElapsed() * mult; - } - - public static void renderBillboardQuad(float rot, double scale) { - glPushMatrix(); - - rotateToPlayer(); - - glPushMatrix(); - - glRotatef(rot, 0, 0, 1); - - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - glColor3f(1, 1, 1); - tessellator.setColorRGBA(255, 255, 255, 255); - tessellator.addVertexWithUV(-scale, -scale, 0, 0, 0); - tessellator.addVertexWithUV(-scale, scale, 0, 0, 1); - tessellator.addVertexWithUV(scale, scale, 0, 1, 1); - tessellator.addVertexWithUV(scale, -scale, 0, 1, 0); - tessellator.draw(); - glPopMatrix(); - glPopMatrix(); - } - - public static void rotateToPlayer() { - glRotatef(-RenderManager.instance.playerViewY, 0.0F, 1.0F, 0.0F); - glRotatef(RenderManager.instance.playerViewX, 1.0F, 0.0F, 0.0F); - } - - private static class EdgeNeighbour { - final ForgeDirection dir; - final BlockCoord bc; - - public EdgeNeighbour(BlockCoord bc, ForgeDirection dir) { - this.dir = dir; - this.bc = bc.getLocation(dir); + public static void rotateToPlayer() { + glRotatef(-RenderManager.instance.playerViewY, 0.0F, 1.0F, 0.0F); + glRotatef(RenderManager.instance.playerViewX, 1.0F, 0.0F, 0.0F); } - } + private static class EdgeNeighbour { - public static void registerReloadListener(IResourceManagerReloadListener obj) { - ((IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).registerReloadListener(obj); - } + final ForgeDirection dir; + final BlockCoord bc; + + public EdgeNeighbour(BlockCoord bc, ForgeDirection dir) { + this.dir = dir; + this.bc = bc.getLocation(dir); + } + + } + + public static void registerReloadListener(IResourceManagerReloadListener obj) { + ((IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).registerReloadListener(obj); + } } diff --git a/src/main/java/com/enderio/core/client/render/SimpleModelRenderer.java b/src/main/java/com/enderio/core/client/render/SimpleModelRenderer.java index 9b26677..1cf783e 100644 --- a/src/main/java/com/enderio/core/client/render/SimpleModelRenderer.java +++ b/src/main/java/com/enderio/core/client/render/SimpleModelRenderer.java @@ -6,47 +6,50 @@ import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.model.obj.WavefrontObject; + import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; public class SimpleModelRenderer implements ISimpleBlockRenderingHandler { - private final Tessellator tes = Tessellator.instance; - private final WavefrontObject model; + private final Tessellator tes = Tessellator.instance; - private final int renderId; - - public SimpleModelRenderer(WavefrontObject model, int renderId) { - this.model = model; - this.renderId = renderId; - } + private final WavefrontObject model; - @Override - public int getRenderId() { - return renderId; - } + private final int renderId; - @Override - public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { - RenderHelper.disableStandardItemLighting(); - tes.startDrawingQuads(); - tes.setColorOpaque_F(1, 1, 1); - TechneUtil.renderWithIcon(model, block.getIcon(0, metadata), tes); - tes.draw(); - RenderHelper.enableStandardItemLighting(); - } + public SimpleModelRenderer(WavefrontObject model, int renderId) { + this.model = model; + this.renderId = renderId; + } - @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { - tes.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z)); - tes.setColorOpaque_F(1, 1, 1); - tes.addTranslation(x + .5F, y + .5F, z + .5F); - TechneUtil.renderWithIcon(model, block.getIcon(0, world.getBlockMetadata(x, y, z)), tes); - tes.addTranslation(-x - .5F, -y - .5F, -z - .5F); - return true; - } + @Override + public int getRenderId() { + return renderId; + } - @Override - public boolean shouldRender3DInInventory(int modelId) { - return true; - } + @Override + public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { + RenderHelper.disableStandardItemLighting(); + tes.startDrawingQuads(); + tes.setColorOpaque_F(1, 1, 1); + TechneUtil.renderWithIcon(model, block.getIcon(0, metadata), tes); + tes.draw(); + RenderHelper.enableStandardItemLighting(); + } + + @Override + public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, + RenderBlocks renderer) { + tes.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z)); + tes.setColorOpaque_F(1, 1, 1); + tes.addTranslation(x + .5F, y + .5F, z + .5F); + TechneUtil.renderWithIcon(model, block.getIcon(0, world.getBlockMetadata(x, y, z)), tes); + tes.addTranslation(-x - .5F, -y - .5F, -z - .5F); + return true; + } + + @Override + public boolean shouldRender3DInInventory(int modelId) { + return true; + } } 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 8fe69ba..4e3afb7 100644 --- a/src/main/java/com/enderio/core/client/render/TechneModelRenderer.java +++ b/src/main/java/com/enderio/core/client/render/TechneModelRenderer.java @@ -10,69 +10,82 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.model.obj.GroupObject; import com.enderio.core.api.client.render.VertexTransform; - import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; public class TechneModelRenderer implements ISimpleBlockRenderingHandler { - protected Map model; - private int renderId; + protected Map model; + private int renderId; - protected VertexTransform vt; + protected VertexTransform vt; - public TechneModelRenderer(String modid, String modelPath, int renderId) { - this(modid, modelPath, renderId, null); - } + public TechneModelRenderer(String modid, String modelPath, int renderId) { + this(modid, modelPath, renderId, null); + } - public TechneModelRenderer(String modid, String modelPath, int renderId, VertexTransform vt) { - this(TechneUtil.getModel(modid, modelPath), renderId, vt); - } + 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); - } + public TechneModelRenderer(Map model, int renderId) { + this(model, renderId, null); + } - public TechneModelRenderer(Map model, int renderId, VertexTransform vt) { - this.model = model; - this.renderId = renderId; - this.vt = vt; - } + public TechneModelRenderer(Map model, int renderId, VertexTransform vt) { + this.model = model; + this.renderId = renderId; + this.vt = vt; + } - protected Collection getModel(Block block, int metadata) { - return model.values(); - } + protected Collection getModel(Block block, int metadata) { + return model.values(); + } - protected Collection getModel(IBlockAccess world, int x, int y, int z) { - return model.values(); - } + protected Collection getModel(IBlockAccess world, int x, int y, int z) { + return model.values(); + } - @Override - public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { - TechneUtil.vt = this.vt; - TechneUtil.renderInventoryBlock(getModel(block, metadata), getModelIcon(block, metadata), block, metadata, renderer); - } + @Override + public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { + TechneUtil.vt = this.vt; + TechneUtil.renderInventoryBlock( + getModel(block, metadata), + getModelIcon(block, metadata), + block, + metadata, + renderer); + } - @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { - TechneUtil.vt = this.vt; - return TechneUtil.renderWorldBlock(getModel(world, x, y, z), getModelIcon(world, x, y, z, block), world, x, y, z, block, renderer); - } + @Override + public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, + RenderBlocks renderer) { + 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); - } + protected IIcon getModelIcon(Block block, int metadata) { + return block.getIcon(0, metadata); + } - protected IIcon getModelIcon(IBlockAccess world, int x, int y, int z, Block block) { - return block.getIcon(world, x, y, z, 0); - } + 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; - } + @Override + public boolean shouldRender3DInInventory(int modelId) { + return true; + } - @Override - public int getRenderId() { - return renderId; - } + @Override + public int getRenderId() { + return renderId; + } } 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 5c28d76..5f9e9dd 100644 --- a/src/main/java/com/enderio/core/client/render/TechneUtil.java +++ b/src/main/java/com/enderio/core/client/render/TechneUtil.java @@ -1,35 +1,18 @@ /* - -Copyright © 2014 RainWarrior - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - - 4. This notice may not be removed or altered from any source - distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - + * Copyright © 2014 RainWarrior Permission is granted to anyone to use this software for any purpose, including + * commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The + * origin of this software must not be misrepresented; you must not claim that you wrote the original software. 2. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided with the distribution. 3. Altered source versions + * must be plainly marked as such, and must not be misrepresented as being the original software. 4. This notice may not + * be removed or altered from any source distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ package com.enderio.core.client.render; @@ -67,357 +50,368 @@ import org.lwjgl.util.vector.Vector4f; import com.enderio.core.api.client.render.VertexTransform; import com.enderio.core.common.vecmath.Vector3d; import com.google.common.collect.Maps; - import cpw.mods.fml.common.ObfuscationReflectionHelper; /** * Slightly modified to fit the EnderIO source. * - * @author Based on RainWarrior's code here. + * @author Based on RainWarrior's code here. */ public class TechneUtil { - public static VertexTransform vt = null; + public static VertexTransform vt = null; - private static final TechneModelLoader modelLoader = new TechneModelLoader(); + private static final TechneModelLoader modelLoader = new TechneModelLoader(); - private static final Tessellator tes = Tessellator.instance; + private static final Tessellator tes = Tessellator.instance; - public static List bakeModel(ModelRenderer model, TechneModel supermodel) { - return bakeModel(model, supermodel, 1); - } - - public static List bakeModel(ModelRenderer model, TechneModel supermodel, float scale) { - return bakeModel(model, supermodel, scale, new Matrix4f()); - } - - public static List bakeModel(ModelRenderer model, TechneModel supermodel, float scale, Matrix4f matrix) { - return bakeModel(model, supermodel, scale, matrix, false); - } - - /** - * Convert ModelRenderer to a list of GroupObjects, for ease of use in ISBRH - * and other static contexts. - * - * @param scale - * the scale factor, usually last argument to rendering methods - * @param matrix - * initial transformation matrix (replaces calling - * glTranslate/glRotate/e.t.c. before rendering) - * @param rotateYFirst - * true, of the order of rotations be like in - * ModelRenderer.renderWithRotation, false if like in - * ModelRenderer.render - */ - @SuppressWarnings("unchecked") - 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 - // never sets the size on the TechneModel, so we can use that value (which - // is taken by the ModelRenderer for the calculations) to correct the - // positions. - - float uCorrection = ((int) model.textureWidth) / supermodel.textureWidth; - float vCorrection = ((int) model.textureHeight) / supermodel.textureHeight; - - Matrix4f m = new Matrix4f(matrix); - - m.translate(new Vector3f(model.offsetX + model.rotationPointX * scale, model.offsetY + model.rotationPointY * scale, model.offsetZ + model.rotationPointZ - * scale)); - - 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) { - m.rotate(model.rotateAngleZ, new Vector3f(0, 0, 1)); + public static List bakeModel(ModelRenderer model, TechneModel supermodel) { + return bakeModel(model, supermodel, 1); } - Vector4f vec = new Vector4f(); - List res = new ArrayList(); + public static List bakeModel(ModelRenderer model, TechneModel supermodel, float scale) { + return bakeModel(model, supermodel, scale, new Matrix4f()); + } - for (ModelBox box : (List) model.cubeList) { - GroupObject obj = new GroupObject("", GL11.GL_QUADS); - TexturedQuad[] quads = (TexturedQuad[]) ObfuscationReflectionHelper.getPrivateValue(ModelBox.class, box, "quadList", "field_78254_i"); - for (int i = 0; i < quads.length; i++) { - Face face = new Face(); - face.vertices = new Vertex[4]; - face.textureCoordinates = new TextureCoordinate[4]; - float minU = -1, minV = -1; - for (int j = 0; j < 4; j++) { - PositionTextureVertex pv = quads[i].vertexPositions[j]; - if (minU < 0 || minU > pv.texturePositionX) { - minU = pv.texturePositionX; - } - if (minV < 0 || minV > pv.texturePositionY) { - minV = pv.texturePositionY; - } + public static List bakeModel(ModelRenderer model, TechneModel supermodel, float scale, + Matrix4f matrix) { + return bakeModel(model, supermodel, scale, matrix, false); + } + + /** + * Convert ModelRenderer to a list of GroupObjects, for ease of use in ISBRH and other static contexts. + * + * @param scale the scale factor, usually last argument to rendering methods + * @param matrix initial transformation matrix (replaces calling glTranslate/glRotate/e.t.c. before rendering) + * @param rotateYFirst true, of the order of rotations be like in ModelRenderer.renderWithRotation, false if like in + * ModelRenderer.render + */ + @SuppressWarnings("unchecked") + 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 + // never sets the size on the TechneModel, so we can use that value (which + // is taken by the ModelRenderer for the calculations) to correct the + // positions. + + float uCorrection = ((int) model.textureWidth) / supermodel.textureWidth; + float vCorrection = ((int) model.textureHeight) / supermodel.textureHeight; + + Matrix4f m = new Matrix4f(matrix); + + m.translate( + new Vector3f( + model.offsetX + model.rotationPointX * scale, + model.offsetY + model.rotationPointY * scale, + model.offsetZ + model.rotationPointZ * scale)); + + if (!rotateYFirst) { + m.rotate(model.rotateAngleZ, new Vector3f(0, 0, 1)); } - for (int j = 0; j < 4; j++) { - PositionTextureVertex pv = quads[i].vertexPositions[j]; + m.rotate(model.rotateAngleY, new Vector3f(0, 1, 0)); + m.rotate(model.rotateAngleX, new Vector3f(1, 0, 0)); - vec.x = (float) pv.vector3D.xCoord * scale; - vec.y = (float) pv.vector3D.yCoord * scale; - vec.z = (float) pv.vector3D.zCoord * scale; - vec.w = 1; - - Matrix4f.transform(m, vec, vec); - - face.vertices[j] = new Vertex(vec.x / vec.w, vec.y / vec.w, vec.z / vec.w); - - // The small offset will reduce the amount of visible errors (white - // pixels) at the edges of textures a lot. The introduced visible - // offset is very small, about 1 screen pixel between a 1/16 block - // wide element and a 1 block wide element when standing "on touch". - float u; - float v; - if (pv.texturePositionX == minU) { - u = pv.texturePositionX / uCorrection + 0.0001f; - } else { - u = pv.texturePositionX / uCorrection - 0.0001f; - } - if (pv.texturePositionY == minV) { - v = pv.texturePositionY / vCorrection + 0.0001f; - } else { - v = pv.texturePositionY / vCorrection - 0.0001f; - } - face.textureCoordinates[j] = new TextureCoordinate(u, v); + if (rotateYFirst) { + m.rotate(model.rotateAngleZ, new Vector3f(0, 0, 1)); } - face.faceNormal = face.calculateFaceNormal(); - obj.faces.add(face); - } - res.add(obj); - } - return res; - } + Vector4f vec = new Vector4f(); + List res = new ArrayList(); - public static Map bakeModel(TechneModel model) { - return bakeModel(model, 1); - } + for (ModelBox box : (List) model.cubeList) { + GroupObject obj = new GroupObject("", GL11.GL_QUADS); + TexturedQuad[] quads = (TexturedQuad[]) ObfuscationReflectionHelper + .getPrivateValue(ModelBox.class, box, "quadList", "field_78254_i"); + for (int i = 0; i < quads.length; i++) { + Face face = new Face(); + face.vertices = new Vertex[4]; + face.textureCoordinates = new TextureCoordinate[4]; + float minU = -1, minV = -1; + for (int j = 0; j < 4; j++) { + PositionTextureVertex pv = quads[i].vertexPositions[j]; + if (minU < 0 || minU > pv.texturePositionX) { + minU = pv.texturePositionX; + } + if (minV < 0 || minV > pv.texturePositionY) { + minV = pv.texturePositionY; + } + } + for (int j = 0; j < 4; j++) { + PositionTextureVertex pv = quads[i].vertexPositions[j]; - public static Map bakeModel(TechneModel model, float scale) { - return bakeModel(model, scale, new Matrix4f()); - } + vec.x = (float) pv.vector3D.xCoord * scale; + vec.y = (float) pv.vector3D.yCoord * scale; + vec.z = (float) pv.vector3D.zCoord * scale; + vec.w = 1; - public static Map bakeModel(TechneModel model, float scale, Matrix4f m) { - return bakeModel(model, scale, m, false); - } + Matrix4f.transform(m, vec, vec); - /** - * Use this to convert TechneModel to it's static representation - */ - @SuppressWarnings("unchecked") - public static Map bakeModel(TechneModel model, float scale, Matrix4f m, boolean rotateYFirst) { - Map parts = (Map) ObfuscationReflectionHelper.getPrivateValue(TechneModel.class, model, "parts"); - Map res = Maps.newHashMap(); + face.vertices[j] = new Vertex(vec.x / vec.w, vec.y / vec.w, vec.z / vec.w); - for (Map.Entry e : parts.entrySet()) { - GroupObject obj = bakeModel(e.getValue(), model, scale, m, rotateYFirst).get(0); - res.put(e.getKey(), obj); - } - - return res; - } - - public static Map getModel(String modid, String modelPath) { - 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))); - } - - public static Collection getModelAll(String modid, String modelPath) { - 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); - } - - public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes) { - renderWithIcon(model, icon, override, tes, null); - } - - public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes, VertexTransform vt) { - renderWithIcon(model, icon, override, tes, null, 0, 0, 0, vt); - } - - public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes, IBlockAccess world, int x, int y, int z) { - renderWithIcon(model, icon, override, tes, world, x, y, z, null); - } - - public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes, IBlockAccess world, int x, int y, int z, - VertexTransform vt) { - renderWithIcon(model, icon, override, tes, world, x, y, z, vt, true); - } - - public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes, IBlockAccess world, int x, int y, int z, - VertexTransform vt, boolean isbrh) { - for (GroupObject go : model) { - renderWithIcon(go, icon, override, tes, world, x, y, z, vt, isbrh); - } - } - - public static void renderWithIcon(GroupObject go, IIcon icon, IIcon override, Tessellator tes, IBlockAccess world, int x, int y, int z, VertexTransform vt, - boolean isbrh) { - for (Face f : go.faces) { - Vertex n = f.faceNormal; - tes.setNormal(n.x, n.y, n.z); - ForgeDirection normal = getNormalFor(n); - ForgeDirection right = normal.getRotation(ForgeDirection.DOWN); - if (normal == right) { - right = ForgeDirection.EAST; - } - ForgeDirection down = normal.getRotation(right.getOpposite()); - - 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; - tes.setBrightness(world.getBlock(bx, by, bz).getMixedBrightnessForBlock(world, bx, by, bz)); - } - - for (int i = 0; i < f.vertices.length; i++) { - Vertex vert = f.vertices[i]; - Vector3d v = new Vector3d(vert); - Vector3d tv = new Vector3d(v); - tv.add(0.5, 0, 0.5); - if (vt != null) { - vt.apply(v); - // TODO BLECH - if (vt instanceof VertexRotationFacing) { - normal = ((VertexRotationFacing) vt).rotate(normal); - } - if (vt instanceof VertexTransformComposite) { - for (VertexTransform xform : ((VertexTransformComposite) vt).xforms) { - if (xform instanceof VertexRotationFacing) { - normal = ((VertexRotationFacing) xform).rotate(normal); - } + // The small offset will reduce the amount of visible errors (white + // pixels) at the edges of textures a lot. The introduced visible + // offset is very small, about 1 screen pixel between a 1/16 block + // wide element and a 1 block wide element when standing "on touch". + float u; + float v; + if (pv.texturePositionX == minU) { + u = pv.texturePositionX / uCorrection + 0.0001f; + } else { + u = pv.texturePositionX / uCorrection - 0.0001f; + } + if (pv.texturePositionY == minV) { + v = pv.texturePositionY / vCorrection + 0.0001f; + } else { + v = pv.texturePositionY / vCorrection - 0.0001f; + } + face.textureCoordinates[j] = new TextureCoordinate(u, v); + } + face.faceNormal = face.calculateFaceNormal(); + obj.faces.add(face); } - } + res.add(obj); } - if (isbrh) { - int c = (int) (0xFF * RenderUtil.getColorMultiplierForFace(normal)); - tes.setColorOpaque(c, c, c); + return res; + } + + public static Map bakeModel(TechneModel model) { + return bakeModel(model, 1); + } + + public static Map bakeModel(TechneModel model, float scale) { + return bakeModel(model, scale, new Matrix4f()); + } + + public static Map bakeModel(TechneModel model, float scale, Matrix4f m) { + return bakeModel(model, scale, m, false); + } + + /** + * Use this to convert TechneModel to it's static representation + */ + @SuppressWarnings("unchecked") + public static Map bakeModel(TechneModel model, float scale, Matrix4f m, boolean rotateYFirst) { + Map parts = (Map) ObfuscationReflectionHelper + .getPrivateValue(TechneModel.class, model, "parts"); + Map res = Maps.newHashMap(); + + for (Map.Entry e : parts.entrySet()) { + GroupObject obj = bakeModel(e.getValue(), model, scale, m, rotateYFirst).get(0); + res.put(e.getKey(), obj); } - if (override != null) { + return res; + } - 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); + public static Map getModel(String modid, String modelPath) { + 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))); + } - // Handles verts outside block bounds. Modulo fails at 1.0. - while (interpX > 1) { - interpX--; - } - while (interpY > 1) { - interpY--; - } + public static Collection getModelAll(String modid, String modelPath) { + 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(); + } - if (normal == ForgeDirection.SOUTH || normal == ForgeDirection.WEST) { - interpX = 1 - interpX; - } - 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)); + public static void renderWithIcon(WavefrontObject model, IIcon icon, Tessellator tes) { + renderWithIcon(model.groupObjects, icon, null, tes); + } + + public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes) { + renderWithIcon(model, icon, override, tes, null); + } + + public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes, + VertexTransform vt) { + renderWithIcon(model, icon, override, tes, null, 0, 0, 0, vt); + } + + public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes, + IBlockAccess world, int x, int y, int z) { + renderWithIcon(model, icon, override, tes, world, x, y, z, null); + } + + public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes, + IBlockAccess world, int x, int y, int z, VertexTransform vt) { + renderWithIcon(model, icon, override, tes, world, x, y, z, vt, true); + } + + public static void renderWithIcon(Collection model, IIcon icon, IIcon override, Tessellator tes, + IBlockAccess world, int x, int y, int z, VertexTransform vt, boolean isbrh) { + for (GroupObject go : model) { + renderWithIcon(go, icon, override, tes, world, x, y, z, vt, isbrh); + } + } + + public static void renderWithIcon(GroupObject go, IIcon icon, IIcon override, Tessellator tes, IBlockAccess world, + int x, int y, int z, VertexTransform vt, boolean isbrh) { + for (Face f : go.faces) { + Vertex n = f.faceNormal; + tes.setNormal(n.x, n.y, n.z); + ForgeDirection normal = getNormalFor(n); + ForgeDirection right = normal.getRotation(ForgeDirection.DOWN); + if (normal == right) { + right = ForgeDirection.EAST; + } + ForgeDirection down = normal.getRotation(right.getOpposite()); + + 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; + tes.setBrightness(world.getBlock(bx, by, bz).getMixedBrightnessForBlock(world, bx, by, bz)); + } + + for (int i = 0; i < f.vertices.length; i++) { + Vertex vert = f.vertices[i]; + Vector3d v = new Vector3d(vert); + Vector3d tv = new Vector3d(v); + tv.add(0.5, 0, 0.5); + if (vt != null) { + vt.apply(v); + // TODO BLECH + if (vt instanceof VertexRotationFacing) { + normal = ((VertexRotationFacing) vt).rotate(normal); + } + if (vt instanceof VertexTransformComposite) { + for (VertexTransform xform : ((VertexTransformComposite) vt).xforms) { + if (xform instanceof VertexRotationFacing) { + normal = ((VertexRotationFacing) xform).rotate(normal); + } + } + } + } + + if (isbrh) { + int c = (int) (0xFF * RenderUtil.getColorMultiplierForFace(normal)); + tes.setColorOpaque(c, c, c); + } + + 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); + + // Handles verts outside block bounds. Modulo fails at 1.0. + while (interpX > 1) { + interpX--; + } + while (interpY > 1) { + interpY--; + } + + if (normal == ForgeDirection.SOUTH || normal == ForgeDirection.WEST) { + interpX = 1 - interpX; + } + 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)); + } else { + TextureCoordinate t = f.textureCoordinates[i]; + tes.addVertexWithUV(v.x, v.y, v.z, getInterpolatedU(icon, t.u), getInterpolatedV(icon, t.v)); + } + } + } + } + + // reducing texture positioning error by working in double and not multiplying + // and dividing by 16. + public static double getInterpolatedV(IIcon icon, double offset) { + return icon.getMinV() + (icon.getMaxV() - icon.getMinV()) * offset; + } + + public static double getInterpolatedU(IIcon icon, double offset) { + return icon.getMinU() + (icon.getMaxU() - icon.getMinU()) * offset; + } + + private static ForgeDirection getNormalFor(Vertex n) { + if (n.x != 0) { + return n.x > 0 ? ForgeDirection.EAST : ForgeDirection.WEST; + } else if (n.y != 0) { + return n.y > 0 ? ForgeDirection.UP : ForgeDirection.DOWN; } else { - TextureCoordinate t = f.textureCoordinates[i]; - tes.addVertexWithUV(v.x, v.y, v.z, getInterpolatedU(icon, t.u), getInterpolatedV(icon, t.v)); + return n.z > 0 ? ForgeDirection.SOUTH : ForgeDirection.NORTH; } - } } - } - // reducing texture positioning error by working in double and not multiplying - // and dividing by 16. - public static double getInterpolatedV(IIcon icon, double offset) { - return icon.getMinV() + (icon.getMaxV() - icon.getMinV()) * offset; - } - - public static double getInterpolatedU(IIcon icon, double offset) { - return icon.getMinU() + (icon.getMaxU() - icon.getMinU()) * offset; - } - - private static ForgeDirection getNormalFor(Vertex n) { - if (n.x != 0) { - return n.x > 0 ? ForgeDirection.EAST : ForgeDirection.WEST; - } else if (n.y != 0) { - return n.y > 0 ? ForgeDirection.UP : ForgeDirection.DOWN; - } else { - return n.z > 0 ? ForgeDirection.SOUTH : ForgeDirection.NORTH; + public static void renderInventoryBlock(Collection model, Block block, int metadata, RenderBlocks rb) { + renderInventoryBlock(model, getIconFor(block, metadata), block, metadata, rb); } - } - public static void renderInventoryBlock(Collection model, Block block, int metadata, RenderBlocks rb) { - renderInventoryBlock(model, getIconFor(block, metadata), block, metadata, rb); - } - - public static void renderInventoryBlock(Collection model, IIcon icon, Block block, int metadata, RenderBlocks rb) { - tes.startDrawingQuads(); - tes.setColorOpaque_F(1, 1, 1); - tes.addTranslation(0, -0.47f, 0); - renderWithIcon(model, icon, rb.overrideBlockTexture, tes, vt); - tes.addTranslation(0, 0.47f, 0); - tes.draw(); - resetVT(); - } - - public static void renderInventoryBlock(GroupObject model, Block block, int metadata, RenderBlocks rb) { - IIcon icon = getIconFor(block, metadata); - tes.startDrawingQuads(); - tes.setColorOpaque_F(1, 1, 1); - tes.addTranslation(0, -0.47f, 0); - renderWithIcon(model, icon, rb.overrideBlockTexture, tes, null, 0, 0, 0, vt, true); - tes.addTranslation(0, 0.47f, 0); - tes.draw(); - resetVT(); - } - - public static boolean renderWorldBlock(Collection model, IBlockAccess world, int x, int y, int z, Block block, RenderBlocks rb) { - IIcon icon = getIconFor(block, world, x, y, z); - return renderWorldBlock(model, icon, world, x, y, z, block, rb); - } - - public static boolean renderWorldBlock(Collection model, IIcon icon, IBlockAccess world, int x, int y, int z, Block block, RenderBlocks rb) { - if (icon == null) { - return false; + public static void renderInventoryBlock(Collection model, IIcon icon, Block block, int metadata, + RenderBlocks rb) { + tes.startDrawingQuads(); + tes.setColorOpaque_F(1, 1, 1); + tes.addTranslation(0, -0.47f, 0); + renderWithIcon(model, icon, rb.overrideBlockTexture, tes, vt); + tes.addTranslation(0, 0.47f, 0); + tes.draw(); + resetVT(); } - tes.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z)); - tes.setColorOpaque_F(1, 1, 1); - tes.addTranslation(x + .5F, y + 0.0375f, z + .5F); - renderWithIcon(model, icon, rb.overrideBlockTexture, tes, world, x, y, z, vt); - tes.addTranslation(-x - .5F, -y - 0.0375f, -z - .5F); - resetVT(); - return true; - } - public static boolean renderWorldBlock(GroupObject model, IBlockAccess world, int x, int y, int z, Block block, RenderBlocks rb) { - IIcon icon = getIconFor(block, world, x, y, z); - tes.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z)); - tes.setColorOpaque_F(1, 1, 1); - tes.addTranslation(x + .5F, y + 0.0375f, z + .5F); - renderWithIcon(model, icon, rb.overrideBlockTexture, tes, world, x, y, z, vt, true); - tes.addTranslation(-x - .5F, -y - 0.0375f, -z - .5F); - resetVT(); - return true; - } + public static void renderInventoryBlock(GroupObject model, Block block, int metadata, RenderBlocks rb) { + IIcon icon = getIconFor(block, metadata); + tes.startDrawingQuads(); + tes.setColorOpaque_F(1, 1, 1); + tes.addTranslation(0, -0.47f, 0); + renderWithIcon(model, icon, rb.overrideBlockTexture, tes, null, 0, 0, 0, vt, true); + tes.addTranslation(0, 0.47f, 0); + tes.draw(); + resetVT(); + } - private static void resetVT() { - vt = null; - } + public static boolean renderWorldBlock(Collection model, IBlockAccess world, int x, int y, int z, + Block block, RenderBlocks rb) { + IIcon icon = getIconFor(block, world, x, y, z); + return renderWorldBlock(model, icon, world, x, y, z, block, rb); + } - private static IIcon getIconFor(Block block, IBlockAccess world, int x, int y, int z) { - return block.getIcon(world, x, y, z, 0); - } + public static boolean renderWorldBlock(Collection model, IIcon icon, IBlockAccess world, int x, int y, + int z, Block block, RenderBlocks rb) { + if (icon == null) { + return false; + } + tes.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z)); + tes.setColorOpaque_F(1, 1, 1); + tes.addTranslation(x + .5F, y + 0.0375f, z + .5F); + renderWithIcon(model, icon, rb.overrideBlockTexture, tes, world, x, y, z, vt); + tes.addTranslation(-x - .5F, -y - 0.0375f, -z - .5F); + resetVT(); + return true; + } - private static IIcon getIconFor(Block block, int metadata) { - return block.getIcon(0, metadata); - } + public static boolean renderWorldBlock(GroupObject model, IBlockAccess world, int x, int y, int z, Block block, + RenderBlocks rb) { + IIcon icon = getIconFor(block, world, x, y, z); + tes.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z)); + tes.setColorOpaque_F(1, 1, 1); + tes.addTranslation(x + .5F, y + 0.0375f, z + .5F); + renderWithIcon(model, icon, rb.overrideBlockTexture, tes, world, x, y, z, vt, true); + tes.addTranslation(-x - .5F, -y - 0.0375f, -z - .5F); + resetVT(); + return true; + } + + private static void resetVT() { + vt = null; + } + + private static IIcon getIconFor(Block block, IBlockAccess world, int x, int y, int z) { + return block.getIcon(world, x, y, z, 0); + } + + private static IIcon getIconFor(Block block, int metadata) { + return block.getIcon(0, metadata); + } } 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 e8d35eb..dfede67 100644 --- a/src/main/java/com/enderio/core/client/render/VertexRotation.java +++ b/src/main/java/com/enderio/core/client/render/VertexRotation.java @@ -8,51 +8,51 @@ import com.enderio.core.common.vecmath.Vertex; public class VertexRotation implements VertexTransform { - private final Vector3d center; - private Quat4d quat; - private double angle; - private final Vector3d axis; + private final Vector3d center; + private Quat4d quat; + private double angle; + private final Vector3d axis; - public VertexRotation(double angle, Vector3d axis, Vector3d center) { - this.center = new Vector3d(center); - this.axis = new Vector3d(axis); - this.angle = angle; - quat = Quat4d.makeRotate(angle, axis); - } + public VertexRotation(double angle, Vector3d axis, Vector3d center) { + this.center = new Vector3d(center); + this.axis = new Vector3d(axis); + this.angle = angle; + quat = Quat4d.makeRotate(angle, axis); + } - @Override - public void apply(Vertex vertex) { - apply(vertex.xyz); - } + @Override + public void apply(Vertex vertex) { + apply(vertex.xyz); + } - @Override - public void apply(Vector3d vec) { - vec.sub(center); - quat.rotate(vec); - vec.add(center); - } + @Override + public void apply(Vector3d vec) { + vec.sub(center); + quat.rotate(vec); + vec.add(center); + } - public void setAngle(double angle) { - this.angle = angle; - quat = Quat4d.makeRotate(angle, axis); - } + public void setAngle(double angle) { + this.angle = angle; + quat = Quat4d.makeRotate(angle, axis); + } - public double getAngle() { - return angle; - } + public double getAngle() { + return angle; + } - public void setAxis(Vector3d axis) { - this.axis.set(axis); - quat = Quat4d.makeRotate(angle, axis); - } + public void setAxis(Vector3d axis) { + this.axis.set(axis); + quat = Quat4d.makeRotate(angle, axis); + } - public void setCenter(Vector3d cen) { - center.set(cen); - } + public void setCenter(Vector3d cen) { + center.set(cen); + } - @Override - public void applyToNormal(Vector3f vec) { - quat.rotate(vec); - } + @Override + public void applyToNormal(Vector3f vec) { + quat.rotate(vec); + } } 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 93b15d9..b7536af 100644 --- a/src/main/java/com/enderio/core/client/render/VertexRotationFacing.java +++ b/src/main/java/com/enderio/core/client/render/VertexRotationFacing.java @@ -1,45 +1,45 @@ package com.enderio.core.client.render; -import com.enderio.core.common.vecmath.Vector3d; - import net.minecraftforge.common.util.ForgeDirection; +import com.enderio.core.common.vecmath.Vector3d; + public class VertexRotationFacing extends VertexRotation { - private static final double ROTATION_AMOUNT = Math.PI / 2; + private static final double ROTATION_AMOUNT = Math.PI / 2; - private ForgeDirection defaultDir; + private ForgeDirection defaultDir; - public VertexRotationFacing(ForgeDirection defaultDir) { - super(0, new Vector3d(0, 0.5, 0), new Vector3d(0, 0, 0)); - this.defaultDir = defaultDir; - } + public VertexRotationFacing(ForgeDirection defaultDir) { + super(0, new Vector3d(0, 0.5, 0), new Vector3d(0, 0, 0)); + this.defaultDir = defaultDir; + } - public void setRotation(ForgeDirection dir) { - if (dir == defaultDir) { - setAngle(0); - } else if (dir == defaultDir.getOpposite()) { - setAngle(ROTATION_AMOUNT * 2); - } else if (dir == defaultDir.getRotation(ForgeDirection.DOWN)) { - setAngle(ROTATION_AMOUNT); - } else { - setAngle(ROTATION_AMOUNT * 3); + public void setRotation(ForgeDirection dir) { + if (dir == defaultDir) { + setAngle(0); + } else if (dir == defaultDir.getOpposite()) { + setAngle(ROTATION_AMOUNT * 2); + } 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; + 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); + } + 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); - } - return dir; - } } diff --git a/src/main/java/com/enderio/core/client/render/VertexTransformComposite.java b/src/main/java/com/enderio/core/client/render/VertexTransformComposite.java index 1eb6d4c..89b92ff 100644 --- a/src/main/java/com/enderio/core/client/render/VertexTransformComposite.java +++ b/src/main/java/com/enderio/core/client/render/VertexTransformComposite.java @@ -9,40 +9,40 @@ import com.enderio.core.common.vecmath.Vertex; public class VertexTransformComposite implements VertexTransform { - public final VertexTransform[] xforms; + public final VertexTransform[] xforms; - public VertexTransformComposite(VertexTransform... xforms) { - this.xforms = xforms; - } - - VertexTransformComposite(Collection xformsIn) { - xforms = new VertexTransform[xformsIn.size()]; - int i = 0; - for (VertexTransform xform : xformsIn) { - xforms[i] = xform; - i++; + public VertexTransformComposite(VertexTransform... xforms) { + this.xforms = xforms; } - } - @Override - public void apply(Vertex vertex) { - for (VertexTransform xform : xforms) { - xform.apply(vertex); + VertexTransformComposite(Collection xformsIn) { + xforms = new VertexTransform[xformsIn.size()]; + int i = 0; + for (VertexTransform xform : xformsIn) { + xforms[i] = xform; + i++; + } } - } - @Override - public void apply(Vector3d vec) { - for (VertexTransform xform : xforms) { - xform.apply(vec); + @Override + public void apply(Vertex vertex) { + for (VertexTransform xform : xforms) { + xform.apply(vertex); + } } - } - @Override - public void applyToNormal(Vector3f vec) { - for (VertexTransform xform : xforms) { - xform.applyToNormal(vec); + @Override + public void apply(Vector3d vec) { + for (VertexTransform xform : xforms) { + xform.apply(vec); + } + } + + @Override + public void applyToNormal(Vector3f vec) { + for (VertexTransform xform : xforms) { + xform.applyToNormal(vec); + } } - } } diff --git a/src/main/java/com/enderio/core/client/render/VertexTranslation.java b/src/main/java/com/enderio/core/client/render/VertexTranslation.java index 1b7182f..636148f 100644 --- a/src/main/java/com/enderio/core/client/render/VertexTranslation.java +++ b/src/main/java/com/enderio/core/client/render/VertexTranslation.java @@ -7,55 +7,55 @@ import com.enderio.core.common.vecmath.Vertex; public class VertexTranslation implements VertexTransform { - private double x; - private double y; - private double z; + private double x; + private double y; + private double z; - public VertexTranslation(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } + public VertexTranslation(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } - public VertexTranslation(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } + public VertexTranslation(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } - public VertexTranslation(Vector3d trans) { - this(trans.x, trans.y, trans.z); - } + public VertexTranslation(Vector3d trans) { + this(trans.x, trans.y, trans.z); + } - public VertexTranslation(Vector3f trans) { - this(trans.x, trans.y, trans.z); - } + public VertexTranslation(Vector3f trans) { + this(trans.x, trans.y, trans.z); + } - @Override - public void apply(Vertex vertex) { - apply(vertex.xyz); - } + @Override + public void apply(Vertex vertex) { + apply(vertex.xyz); + } - @Override - public void apply(Vector3d vec) { - vec.x += x; - vec.y += y; - vec.z += z; - } + @Override + public void apply(Vector3d vec) { + vec.x += x; + vec.y += y; + vec.z += z; + } - public void set(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } + public void set(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } - public void set(Vector3d trans) { - set(trans.x, trans.y, trans.z); - } + public void set(Vector3d trans) { + set(trans.x, trans.y, trans.z); + } - @Override - public void applyToNormal(Vector3f vec) { + @Override + public void applyToNormal(Vector3f vec) { - } + } } 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 be35f41..4cac175 100644 --- a/src/main/java/com/enderio/core/client/sound/BlockSound.java +++ b/src/main/java/com/enderio/core/client/sound/BlockSound.java @@ -6,45 +6,45 @@ import net.minecraft.util.ResourceLocation; public class BlockSound extends PositionedSound implements ITickableSound { - private boolean donePlaying = false; + 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 boolean isDonePlaying() { - return this.donePlaying; - } + public boolean isDonePlaying() { + return this.donePlaying; + } - public BlockSound setDonePlaying(boolean donePlaying) { - this.donePlaying = donePlaying; - return this; - } + public BlockSound setDonePlaying(boolean donePlaying) { + this.donePlaying = donePlaying; + return this; + } - 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/BlockEnder.java b/src/main/java/com/enderio/core/common/BlockEnder.java index 55e490c..0644ebb 100644 --- a/src/main/java/com/enderio/core/common/BlockEnder.java +++ b/src/main/java/com/enderio/core/common/BlockEnder.java @@ -28,190 +28,192 @@ import cpw.mods.fml.relauncher.SideOnly; public abstract class BlockEnder extends Block { - protected final @Nullable Class teClass; - protected final String name; - protected final boolean hasComparatorInputOverride; + protected final @Nullable Class teClass; + protected final String name; + protected final boolean hasComparatorInputOverride; - protected BlockEnder(String name, Class teClass) { - this(name, teClass, new Material(MapColor.ironColor)); - } - - protected BlockEnder(String name, Class teClass, Material mat) { - super(mat); - this.teClass = teClass; - this.name = name; - setHardness(0.5F); - setBlockName(name); - setStepSound(Block.soundTypeMetal); - setHarvestLevel("pickaxe", 0); - hasComparatorInputOverride = teClass != null && IComparatorOutput.class.isAssignableFrom(teClass); - } - - protected void init() { - GameRegistry.registerBlock(this, name); - if (teClass != null) { - GameRegistry.registerTileEntity(teClass, name + "TileEntity"); - } - } - - @Override - public boolean hasTileEntity(int metadata) { - return teClass != null; - } - - @Override - public TileEntity createTileEntity(World world, int metadata) { - if (teClass != null) { - try { - TileEntityEnder te = teClass.newInstance(); - te.init(); - return te; - } catch (Exception e) { - Log.error("Could not create tile entity for block " + name + " for class " + teClass); - } - } - return null; - } - - @Override - @SideOnly(Side.CLIENT) - public void registerBlockIcons(IIconRegister iIconRegister) { - blockIcon = iIconRegister.registerIcon("enderio:" + name); - } - - /* Subclass Helpers */ - - @Override - public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float par7, float par8, float par9) { - - TileEntity te = world.getTileEntity(x, y, z); - - if (entityPlayer.isSneaking()) { - return false; + protected BlockEnder(String name, Class teClass) { + this(name, teClass, new Material(MapColor.ironColor)); } - if (te instanceof ITankAccess) { - if (FluidUtil.fillInternalTankFromPlayerHandItem(world, x, y, z, entityPlayer, (ITankAccess) te)) { + protected BlockEnder(String name, Class teClass, Material mat) { + super(mat); + this.teClass = teClass; + this.name = name; + setHardness(0.5F); + setBlockName(name); + setStepSound(Block.soundTypeMetal); + setHarvestLevel("pickaxe", 0); + hasComparatorInputOverride = teClass != null && IComparatorOutput.class.isAssignableFrom(teClass); + } + + protected void init() { + GameRegistry.registerBlock(this, name); + if (teClass != null) { + GameRegistry.registerTileEntity(teClass, name + "TileEntity"); + } + } + + @Override + public boolean hasTileEntity(int metadata) { + return teClass != null; + } + + @Override + public TileEntity createTileEntity(World world, int metadata) { + if (teClass != null) { + try { + TileEntityEnder te = teClass.newInstance(); + te.init(); + return te; + } catch (Exception e) { + Log.error("Could not create tile entity for block " + name + " for class " + teClass); + } + } + return null; + } + + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(IIconRegister iIconRegister) { + blockIcon = iIconRegister.registerIcon("enderio:" + name); + } + + /* Subclass Helpers */ + + @Override + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float par7, + float par8, float par9) { + + TileEntity te = world.getTileEntity(x, y, z); + + if (entityPlayer.isSneaking()) { + return false; + } + + if (te instanceof ITankAccess) { + if (FluidUtil.fillInternalTankFromPlayerHandItem(world, x, y, z, entityPlayer, (ITankAccess) te)) { + return true; + } + if (FluidUtil.fillPlayerHandItemFromInternalTank(world, x, y, z, entityPlayer, (ITankAccess) te)) { + return true; + } + } + + return openGui(world, x, y, z, entityPlayer, side); + } + + protected boolean shouldWrench(World world, int x, int y, int z, EntityPlayer entityPlayer, int side) { return true; - } - if (FluidUtil.fillPlayerHandItemFromInternalTank(world, x, y, z, entityPlayer, (ITankAccess) te)) { + } + + protected boolean openGui(World world, int x, int y, int z, EntityPlayer entityPlayer, int side) { + return false; + } + + public boolean doNormalDrops(World world, int x, int y, int z) { return true; - } } - return openGui(world, x, y, z, entityPlayer, side); - } - - protected boolean shouldWrench(World world, int x, int y, int z, EntityPlayer entityPlayer, int side) { - return true; - } - - protected boolean openGui(World world, int x, int y, int z, EntityPlayer entityPlayer, int side) { - return false; - } - - public boolean doNormalDrops(World world, int x, int y, int z) { - return true; - } - - @Override - public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z, boolean willHarvest) { - if (willHarvest) { - return true; + @Override + public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z, boolean willHarvest) { + if (willHarvest) { + return true; + } + return super.removedByPlayer(world, player, x, y, z, willHarvest); } - return super.removedByPlayer(world, player, x, y, z, willHarvest); - } - @Override - public void harvestBlock(World world, EntityPlayer player, int x, int y, int z, int meta) { - super.harvestBlock(world, player, x, y, z, meta); - world.setBlockToAir(x, y, z); - } - - @Override - public final ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - if (doNormalDrops(world, x, y, z)) { - return super.getDrops(world, x, y, z, metadata, fortune); + @Override + public void harvestBlock(World world, EntityPlayer player, int x, int y, int z, int meta) { + super.harvestBlock(world, player, x, y, z, meta); + world.setBlockToAir(x, y, z); } - return Lists.newArrayList(getNBTDrop(world, x, y, z, (TileEntityEnder) world.getTileEntity(x, y, z))); - } - - @Override - public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - return getPickBlock(target, world, x, y, z, null); - } - - @Override - public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z, @Nullable EntityPlayer player) { - return getNBTDrop(world, x, y, z, teClass != null ? getTileEntityEio(world, x, y, z) : null); - } - public ItemStack getNBTDrop(World world, int x, int y, int z, @Nullable TileEntityEnder te) { - int meta = te != null ? damageDropped(te.getBlockMetadata()) : world.getBlockMetadata(x, y, z); - ItemStack itemStack = new ItemStack(this, 1, meta); - processDrop(world, x, y, z, te, itemStack); - return itemStack; - } - - protected void processDrop(World world, int x, int y, int z, @Nullable TileEntityEnder te, ItemStack drop) { - } - - @SuppressWarnings("null") - protected @Nullable TileEntityEnder getTileEntityEio(IBlockAccess world, int x, int y, int z) { - if (teClass != null) { - TileEntity te = world.getTileEntity(x, y, z); - if (teClass.isInstance(te)) { // no need to null-check teClass here, it was checked 2 lines above and is *final* - return (TileEntityEnder) te; - } + @Override + public final ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + if (doNormalDrops(world, x, y, z)) { + return super.getDrops(world, x, y, z, metadata, fortune); + } + return Lists.newArrayList(getNBTDrop(world, x, y, z, (TileEntityEnder) world.getTileEntity(x, y, z))); } - return null; - } - protected boolean shouldDoWorkThisTick(World world, int x, int y, int z, int interval) { - TileEntityEnder te = getTileEntityEio(world, x, y, z); - if (te == null) { - return world.getTotalWorldTime() % interval == 0; - } else { - return te.shouldDoWorkThisTick(interval); + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + return getPickBlock(target, world, x, y, z, null); } - } - protected boolean shouldDoWorkThisTick(World world, int x, int y, int z, int interval, int offset) { - TileEntityEnder te = getTileEntityEio(world, x, y, z); - if (te == null) { - return (world.getTotalWorldTime() + offset) % interval == 0; - } else { - return te.shouldDoWorkThisTick(interval, offset); + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z, + @Nullable EntityPlayer player) { + return getNBTDrop(world, x, y, z, teClass != null ? getTileEntityEio(world, x, y, z) : null); } - } - @Override - public boolean hasComparatorInputOverride() { - return hasComparatorInputOverride; - } - - @Override - public int getComparatorInputOverride(World w, int x, int y, int z, int side) { - if (hasComparatorInputOverride) { - TileEntityEnder te = getTileEntityEio(w, x, y, z); - if (te != null) { - return ((IComparatorOutput) te).getComparatorOutput(); - } + public ItemStack getNBTDrop(World world, int x, int y, int z, @Nullable TileEntityEnder te) { + int meta = te != null ? damageDropped(te.getBlockMetadata()) : world.getBlockMetadata(x, y, z); + ItemStack itemStack = new ItemStack(this, 1, meta); + processDrop(world, x, y, z, te, itemStack); + return itemStack; } - return 0; - } - - //Because the vanilla method takes floats... - public void setBlockBounds(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { - this.minX = minX; - this.minY = minY; - this.minZ = minZ; - this.maxX = maxX; - this.maxY = maxY; - this.maxZ = maxZ; - } - public void setBlockBounds(AxisAlignedBB bb) { - setBlockBounds(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); - } + protected void processDrop(World world, int x, int y, int z, @Nullable TileEntityEnder te, ItemStack drop) {} + + @SuppressWarnings("null") + protected @Nullable TileEntityEnder getTileEntityEio(IBlockAccess world, int x, int y, int z) { + if (teClass != null) { + TileEntity te = world.getTileEntity(x, y, z); + if (teClass.isInstance(te)) { // no need to null-check teClass here, it was checked 2 lines above and is + // *final* + return (TileEntityEnder) te; + } + } + return null; + } + + protected boolean shouldDoWorkThisTick(World world, int x, int y, int z, int interval) { + TileEntityEnder te = getTileEntityEio(world, x, y, z); + if (te == null) { + return world.getTotalWorldTime() % interval == 0; + } else { + return te.shouldDoWorkThisTick(interval); + } + } + + protected boolean shouldDoWorkThisTick(World world, int x, int y, int z, int interval, int offset) { + TileEntityEnder te = getTileEntityEio(world, x, y, z); + if (te == null) { + return (world.getTotalWorldTime() + offset) % interval == 0; + } else { + return te.shouldDoWorkThisTick(interval, offset); + } + } + + @Override + public boolean hasComparatorInputOverride() { + return hasComparatorInputOverride; + } + + @Override + public int getComparatorInputOverride(World w, int x, int y, int z, int side) { + if (hasComparatorInputOverride) { + TileEntityEnder te = getTileEntityEio(w, x, y, z); + if (te != null) { + return ((IComparatorOutput) te).getComparatorOutput(); + } + } + return 0; + } + + // Because the vanilla method takes floats... + public void setBlockBounds(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + this.minX = minX; + this.minY = minY; + this.minZ = minZ; + this.maxX = maxX; + this.maxY = maxY; + this.maxZ = maxZ; + } + + public void setBlockBounds(AxisAlignedBB bb) { + setBlockBounds(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); + } } diff --git a/src/main/java/com/enderio/core/common/CommonProxy.java b/src/main/java/com/enderio/core/common/CommonProxy.java index c4306d8..de85637 100644 --- a/src/main/java/com/enderio/core/common/CommonProxy.java +++ b/src/main/java/com/enderio/core/common/CommonProxy.java @@ -5,33 +5,33 @@ import net.minecraft.world.World; import com.enderio.core.common.util.Scheduler; public class CommonProxy { - protected Scheduler scheduler; - /** - * Returns a scheduler for the current side - *

- * For internal use only, please call {@link Scheduler#instance()} to obtain - * an {@link Scheduler} instance. - */ - public Scheduler getScheduler() { - if (scheduler == null) { - scheduler = new Scheduler(true); + protected Scheduler scheduler; + + /** + * Returns a scheduler for the current side + *

+ * For internal use only, please call {@link Scheduler#instance()} to obtain an {@link Scheduler} instance. + */ + public Scheduler getScheduler() { + if (scheduler == null) { + scheduler = new Scheduler(true); + } + return scheduler; } - return scheduler; - } - public World getClientWorld() { - return null; - } - - public void throwModCompatibilityError(String... msgs) { - StringBuilder sb = new StringBuilder(); - for (String msg : msgs) { - if (sb.length() > 0) { - sb.append("\n"); - } - sb.append(msg); + public World getClientWorld() { + return null; + } + + public void throwModCompatibilityError(String... msgs) { + StringBuilder sb = new StringBuilder(); + for (String msg : msgs) { + if (sb.length() > 0) { + sb.append("\n"); + } + sb.append(msg); + } + throw new RuntimeException(sb.toString()); } - throw new RuntimeException(sb.toString()); - } } diff --git a/src/main/java/com/enderio/core/common/ContainerEnder.java b/src/main/java/com/enderio/core/common/ContainerEnder.java index 345ddf9..921c42c 100644 --- a/src/main/java/com/enderio/core/common/ContainerEnder.java +++ b/src/main/java/com/enderio/core/common/ContainerEnder.java @@ -16,187 +16,190 @@ import com.google.common.collect.Maps; public class ContainerEnder extends Container { - protected Map playerSlotLocations = Maps.newLinkedHashMap(); + protected Map playerSlotLocations = Maps.newLinkedHashMap(); - protected final int startPlayerSlot; - protected final int endPlayerSlot; - protected final int startHotBarSlot; - protected final int endHotBarSlot; + protected final int startPlayerSlot; + protected final int endPlayerSlot; + protected final int startHotBarSlot; + protected final int endHotBarSlot; - private final @Nonnull T inv; - private final @Nonnull InventoryPlayer playerInv; + private final @Nonnull T inv; + private final @Nonnull InventoryPlayer playerInv; - @Nonnull - private static T checkNotNull(T reference) { - if (reference == null) { - throw new NullPointerException(); - } - return reference; - } - - public ContainerEnder(InventoryPlayer playerInv, T inv) { - this.inv = checkNotNull(inv); - this.playerInv = checkNotNull(playerInv); - - addSlots(playerInv); - - int x = getPlayerInventoryOffset().x; - int y = getPlayerInventoryOffset().y; - - // add players inventory - startPlayerSlot = inventorySlots.size(); - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 9; ++j) { - Point loc = new Point(x + j * 18, y + i * 18); - Slot slot = new Slot(playerInv, j + i * 9 + 9, loc.x, loc.y); - addSlotToContainer(slot); - playerSlotLocations.put(slot, loc); - } - } - endPlayerSlot = inventorySlots.size(); - - startHotBarSlot = inventorySlots.size(); - for (int i = 0; i < 9; ++i) { - Point loc = new Point(x + i * 18, y + 58); - Slot slot = new Slot(playerInv, i, loc.x, loc.y); - addSlotToContainer(slot); - playerSlotLocations.put(slot, loc); - } - endHotBarSlot = inventorySlots.size(); - } - - protected void addSlots(InventoryPlayer playerInv) { - } - - public Point getPlayerInventoryOffset() { - return new Point(8, 84); - } - - public Point getUpgradeOffset() { - return new Point(12, 60); - } - - @Nonnull - public T getInv() { - return inv; - } - - @Override - public boolean canInteractWith(EntityPlayer player) { - return getInv().isUseableByPlayer(player); - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(p_82846_2_); - - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - int minPlayerSlot = inventorySlots.size() - playerInv.mainInventory.length; - if (p_82846_2_ < minPlayerSlot) { - if (!this.mergeItemStack(itemstack1, minPlayerSlot, this.inventorySlots.size(), true)) { - return null; + @Nonnull + private static T checkNotNull(T reference) { + if (reference == null) { + throw new NullPointerException(); } - } else if (!this.mergeItemStack(itemstack1, 0, minPlayerSlot, false)) { - return null; - } - - if (itemstack1.stackSize == 0) { - slot.putStack((ItemStack) null); - } else { - slot.onSlotChanged(); - } + return reference; } - return itemstack; - } + public ContainerEnder(InventoryPlayer playerInv, T inv) { + this.inv = checkNotNull(inv); + this.playerInv = checkNotNull(playerInv); - /** - * Added validation of slot input - */ - @Override - protected boolean mergeItemStack(ItemStack par1ItemStack, int fromIndex, int toIndex, boolean reversOrder) { + addSlots(playerInv); - boolean result = false; - int checkIndex = fromIndex; + int x = getPlayerInventoryOffset().x; + int y = getPlayerInventoryOffset().y; - if (reversOrder) { - checkIndex = toIndex - 1; - } - - Slot slot; - ItemStack itemstack1; - - if (par1ItemStack.isStackable()) { - - while (par1ItemStack.stackSize > 0 && (!reversOrder && checkIndex < toIndex || reversOrder && checkIndex >= fromIndex)) { - slot = (Slot) this.inventorySlots.get(checkIndex); - itemstack1 = slot.getStack(); - - if (itemstack1 != null && itemstack1.getItem() == par1ItemStack.getItem() - && (!par1ItemStack.getHasSubtypes() || par1ItemStack.getItemDamage() == itemstack1.getItemDamage()) - && ItemStack.areItemStackTagsEqual(par1ItemStack, itemstack1) && slot.isItemValid(par1ItemStack) && par1ItemStack != itemstack1) { - - int mergedSize = itemstack1.stackSize + par1ItemStack.stackSize; - int maxStackSize = Math.min(par1ItemStack.getMaxStackSize(), slot.getSlotStackLimit()); - if (mergedSize <= maxStackSize) { - par1ItemStack.stackSize = 0; - itemstack1.stackSize = mergedSize; - slot.onSlotChanged(); - result = true; - } else if (itemstack1.stackSize < maxStackSize) { - par1ItemStack.stackSize -= maxStackSize - itemstack1.stackSize; - itemstack1.stackSize = maxStackSize; - slot.onSlotChanged(); - result = true; - } + // add players inventory + startPlayerSlot = inventorySlots.size(); + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + Point loc = new Point(x + j * 18, y + i * 18); + Slot slot = new Slot(playerInv, j + i * 9 + 9, loc.x, loc.y); + addSlotToContainer(slot); + playerSlotLocations.put(slot, loc); + } } + endPlayerSlot = inventorySlots.size(); + + startHotBarSlot = inventorySlots.size(); + for (int i = 0; i < 9; ++i) { + Point loc = new Point(x + i * 18, y + 58); + Slot slot = new Slot(playerInv, i, loc.x, loc.y); + addSlotToContainer(slot); + playerSlotLocations.put(slot, loc); + } + endHotBarSlot = inventorySlots.size(); + } + + protected void addSlots(InventoryPlayer playerInv) {} + + public Point getPlayerInventoryOffset() { + return new Point(8, 84); + } + + public Point getUpgradeOffset() { + return new Point(12, 60); + } + + @Nonnull + public T getInv() { + return inv; + } + + @Override + public boolean canInteractWith(EntityPlayer player) { + return getInv().isUseableByPlayer(player); + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(p_82846_2_); + + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + int minPlayerSlot = inventorySlots.size() - playerInv.mainInventory.length; + if (p_82846_2_ < minPlayerSlot) { + if (!this.mergeItemStack(itemstack1, minPlayerSlot, this.inventorySlots.size(), true)) { + return null; + } + } else if (!this.mergeItemStack(itemstack1, 0, minPlayerSlot, false)) { + return null; + } + + if (itemstack1.stackSize == 0) { + slot.putStack((ItemStack) null); + } else { + slot.onSlotChanged(); + } + } + + return itemstack; + } + + /** + * Added validation of slot input + */ + @Override + protected boolean mergeItemStack(ItemStack par1ItemStack, int fromIndex, int toIndex, boolean reversOrder) { + + boolean result = false; + int checkIndex = fromIndex; if (reversOrder) { - --checkIndex; - } else { - ++checkIndex; + checkIndex = toIndex - 1; } - } + + Slot slot; + ItemStack itemstack1; + + if (par1ItemStack.isStackable()) { + + while (par1ItemStack.stackSize > 0 + && (!reversOrder && checkIndex < toIndex || reversOrder && checkIndex >= fromIndex)) { + slot = (Slot) this.inventorySlots.get(checkIndex); + itemstack1 = slot.getStack(); + + if (itemstack1 != null && itemstack1.getItem() == par1ItemStack.getItem() + && (!par1ItemStack.getHasSubtypes() + || par1ItemStack.getItemDamage() == itemstack1.getItemDamage()) + && ItemStack.areItemStackTagsEqual(par1ItemStack, itemstack1) + && slot.isItemValid(par1ItemStack) + && par1ItemStack != itemstack1) { + + int mergedSize = itemstack1.stackSize + par1ItemStack.stackSize; + int maxStackSize = Math.min(par1ItemStack.getMaxStackSize(), slot.getSlotStackLimit()); + if (mergedSize <= maxStackSize) { + par1ItemStack.stackSize = 0; + itemstack1.stackSize = mergedSize; + slot.onSlotChanged(); + result = true; + } else if (itemstack1.stackSize < maxStackSize) { + par1ItemStack.stackSize -= maxStackSize - itemstack1.stackSize; + itemstack1.stackSize = maxStackSize; + slot.onSlotChanged(); + result = true; + } + } + + if (reversOrder) { + --checkIndex; + } else { + ++checkIndex; + } + } + } + + if (par1ItemStack.stackSize > 0) { + if (reversOrder) { + checkIndex = toIndex - 1; + } else { + checkIndex = fromIndex; + } + + while (!reversOrder && checkIndex < toIndex || reversOrder && checkIndex >= fromIndex) { + slot = (Slot) this.inventorySlots.get(checkIndex); + itemstack1 = slot.getStack(); + + if (itemstack1 == null && slot.isItemValid(par1ItemStack)) { + ItemStack in = par1ItemStack.copy(); + in.stackSize = Math.min(in.stackSize, slot.getSlotStackLimit()); + + slot.putStack(in); + slot.onSlotChanged(); + if (in.stackSize >= par1ItemStack.stackSize) { + par1ItemStack.stackSize = 0; + } else { + par1ItemStack.stackSize -= in.stackSize; + } + result = true; + break; + } + + if (reversOrder) { + --checkIndex; + } else { + ++checkIndex; + } + } + } + + return result; } - - if (par1ItemStack.stackSize > 0) { - if (reversOrder) { - checkIndex = toIndex - 1; - } else { - checkIndex = fromIndex; - } - - while (!reversOrder && checkIndex < toIndex || reversOrder && checkIndex >= fromIndex) { - slot = (Slot) this.inventorySlots.get(checkIndex); - itemstack1 = slot.getStack(); - - if (itemstack1 == null && slot.isItemValid(par1ItemStack)) { - ItemStack in = par1ItemStack.copy(); - in.stackSize = Math.min(in.stackSize, slot.getSlotStackLimit()); - - slot.putStack(in); - slot.onSlotChanged(); - if (in.stackSize >= par1ItemStack.stackSize) { - par1ItemStack.stackSize = 0; - } else { - par1ItemStack.stackSize -= in.stackSize; - } - result = true; - break; - } - - if (reversOrder) { - --checkIndex; - } else { - ++checkIndex; - } - } - } - - return result; - } } diff --git a/src/main/java/com/enderio/core/common/Handlers.java b/src/main/java/com/enderio/core/common/Handlers.java index 72044e2..c13ed8a 100644 --- a/src/main/java/com/enderio/core/common/Handlers.java +++ b/src/main/java/com/enderio/core/common/Handlers.java @@ -1,5 +1,7 @@ package com.enderio.core.common; +import static com.enderio.core.common.Handlers.Handler.Inst.*; + import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -32,336 +34,331 @@ import cpw.mods.fml.common.eventhandler.EventBus; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.ReflectionHelper; import cpw.mods.fml.relauncher.Side; -import static com.enderio.core.common.Handlers.Handler.Inst.*; public class Handlers { - /** - * New enum to represent handler types. Possible to use to figure out what - * type a method is without direct info. - * - * The order of the constants is the order they are tried. This is VERY - * important! - */ - public enum HandlerType { - /** - * Represents the {@link MinecraftForge#ORE_GEN_BUS} + * New enum to represent handler types. Possible to use to figure out what type a method is without direct info. + * + * The order of the constants is the order they are tried. This is VERY important! */ - FORGE_OREGEN("net.minecraftforge.event.terraingen.OreGenEvent", MinecraftForge.ORE_GEN_BUS), - - /** - * Represents the {@link MinecraftForge#TERRAIN_GEN_BUS} - */ - FORGE_TERRAIN("net.minecraftforge.event.terraingen", MinecraftForge.TERRAIN_GEN_BUS), - - /** - * Represents the {@link MinecraftForge#EVENT_BUS} - */ - FORGE("net.minecraftforge", MinecraftForge.EVENT_BUS), - - /** - * Represents the {@link FMLCommonHandler#bus()} - */ - FML("cpw.mods.fml", FMLCommonHandler.instance().bus()); - - private HandlerType(String eventIdentifier, EventBus bus) { - this.eventIdentifier = eventIdentifier; - this.bus = bus; - } - - public final String eventIdentifier; - public final EventBus bus; - } - - /** - * To be put on classes that are Forge/FML event handlers. EnderCore will - * automatically figure out what busses it needs to be registered to. - *

- * It can get the instance of the handler in a few ways:
- * A public no args constructor (or lombok {@link NoArgsConstructor}) - * OR
- * A static singleton object with field name {@code INSTANCE} (public or - * private). OR
- * A static method with name instance() (public or private) - *

- * This can also be explicitly set using {@link #getInstFrom()} to avoid - * invoking code that may cause issues. - */ - @Target(ElementType.TYPE) - @Retention(RetentionPolicy.RUNTIME) - public @interface Handler { - @Deprecated public enum HandlerType { - /** - * Represents the {@link MinecraftForge#EVENT_BUS} - */ - FORGE, - /** - * Represents the {@link FMLCommonHandler#bus()} - */ - FML - } + /** + * Represents the {@link MinecraftForge#ORE_GEN_BUS} + */ + FORGE_OREGEN("net.minecraftforge.event.terraingen.OreGenEvent", MinecraftForge.ORE_GEN_BUS), - public enum Inst { - /** - * The default, will try all three methods, in the order - * {@link Inst#CONSTRUCTOR}, {@link Inst#FIELD}, {@link Inst#METHOD} - */ - AUTO, + /** + * Represents the {@link MinecraftForge#TERRAIN_GEN_BUS} + */ + FORGE_TERRAIN("net.minecraftforge.event.terraingen", MinecraftForge.TERRAIN_GEN_BUS), - /** - * The handler should be constructed from the default constructor of the - * class - */ - CONSTRUCTOR, + /** + * Represents the {@link MinecraftForge#EVENT_BUS} + */ + FORGE("net.minecraftforge", MinecraftForge.EVENT_BUS), - /** - * The handler should be grabbed from the static {@code INSTANCE} field of - * the class - */ - FIELD, + /** + * Represents the {@link FMLCommonHandler#bus()} + */ + FML("cpw.mods.fml", FMLCommonHandler.instance().bus()); - /** - * The handler should be grabbed from the static {@code instance()} method - * of the class - */ - METHOD, - - /** - * Added for scala compat, not necessary to set explicitly ({@link #AUTO} - * will find this). - */ - SCALA_OBJECT; - - boolean matches(Inst other) { - return this == AUTO || other == AUTO || other == this; - } - } - - public enum HandlerSide { - - /** - * Whether to load this handler or not will be determined by the package - * name. If it contains "client" it will only load clientside. The default - * value. - */ - AUTO, - - /** - * Will load on both sides. - */ - COMMON, - - /** - * Will load only clientside. - */ - CLIENT, - - /** - * Will load only serverside. - */ - SERVER; - - public boolean equals(Side other) { - if (this == COMMON) { - return true; - } else { - return this == CLIENT ? other == Side.CLIENT : other == Side.SERVER; + private HandlerType(String eventIdentifier, EventBus bus) { + this.eventIdentifier = eventIdentifier; + this.bus = bus; } - } + + public final String eventIdentifier; + public final EventBus bus; } /** - * Array of buses to register this handler to. Leave blank for all. + * To be put on classes that are Forge/FML event handlers. EnderCore will automatically figure out what busses it + * needs to be registered to. + *

+ * It can get the instance of the handler in a few ways:
+ * A public no args constructor (or lombok {@link NoArgsConstructor}) OR
+ * A static singleton object with field name {@code INSTANCE} (public or private). OR
+ * A static method with name instance() (public or private) + *

+ * This can also be explicitly set using {@link #getInstFrom()} to avoid invoking code that may cause issues. + */ + @Target(ElementType.TYPE) + @Retention(RetentionPolicy.RUNTIME) + public @interface Handler { + + @Deprecated + public enum HandlerType { + /** + * Represents the {@link MinecraftForge#EVENT_BUS} + */ + FORGE, + + /** + * Represents the {@link FMLCommonHandler#bus()} + */ + FML + } + + public enum Inst { + + /** + * The default, will try all three methods, in the order {@link Inst#CONSTRUCTOR}, {@link Inst#FIELD}, + * {@link Inst#METHOD} + */ + AUTO, + + /** + * The handler should be constructed from the default constructor of the class + */ + CONSTRUCTOR, + + /** + * The handler should be grabbed from the static {@code INSTANCE} field of the class + */ + FIELD, + + /** + * The handler should be grabbed from the static {@code instance()} method of the class + */ + METHOD, + + /** + * Added for scala compat, not necessary to set explicitly ({@link #AUTO} will find this). + */ + SCALA_OBJECT; + + boolean matches(Inst other) { + return this == AUTO || other == AUTO || other == this; + } + } + + public enum HandlerSide { + + /** + * Whether to load this handler or not will be determined by the package name. If it contains "client" it + * will only load clientside. The default value. + */ + AUTO, + + /** + * Will load on both sides. + */ + COMMON, + + /** + * Will load only clientside. + */ + CLIENT, + + /** + * Will load only serverside. + */ + SERVER; + + public boolean equals(Side other) { + if (this == COMMON) { + return true; + } else { + return this == CLIENT ? other == Side.CLIENT : other == Side.SERVER; + } + } + } + + /** + * Array of buses to register this handler to. Leave blank for all. + */ + @Deprecated + HandlerType[] value() default { HandlerType.FORGE, HandlerType.FML }; + + /** + * The method of getting your handler's instance. Defaults to {@link Inst#AUTO} + */ + Inst getInstFrom() default AUTO; + + /** + * The side to load this handler on. Defaults to {@link HandlerSide#AUTO} + */ + HandlerSide side() default HandlerSide.AUTO; + } + + private static final Set packageSet = new HashSet(); + + private static Set annotations; + + public static void preInit(FMLPreInitializationEvent event) { + annotations = event.getAsmData().getAll(Handler.class.getName()); + } + + // private String getEnclosingPackage(Object obj) { + // Class modClass = obj.getClass(); + // + // while (modClass.getComponentType() != null) { + // modClass = modClass.getComponentType(); + // } + // + // while (modClass.getEnclosingClass() != null) { + // modClass = modClass.getEnclosingClass(); + // } + // + // String name = modClass.getName(); + // int lastDot = name.lastIndexOf('.'); + // + // return lastDot == -1 ? name : name.substring(0, lastDot); + // } + + /** + * Registers a top level package to be searched for {@link Handler} classes. Not needed if your {@code @Mod} class + * implements {@link IEnderMod} + * + * @param packageName + * @deprecated This is not needed, period. */ @Deprecated - HandlerType[] value() default { HandlerType.FORGE, HandlerType.FML }; - - /** - * The method of getting your handler's instance. Defaults to - * {@link Inst#AUTO} - */ - Inst getInstFrom() default AUTO; - - /** - * The side to load this handler on. Defaults to {@link HandlerSide#AUTO} - */ - HandlerSide side() default HandlerSide.AUTO; - } - - private static final Set packageSet = new HashSet(); - - private static Set annotations; - - public static void preInit(FMLPreInitializationEvent event) { - annotations = event.getAsmData().getAll(Handler.class.getName()); - } - - // private String getEnclosingPackage(Object obj) { - // Class modClass = obj.getClass(); - // - // while (modClass.getComponentType() != null) { - // modClass = modClass.getComponentType(); - // } - // - // while (modClass.getEnclosingClass() != null) { - // modClass = modClass.getEnclosingClass(); - // } - // - // String name = modClass.getName(); - // int lastDot = name.lastIndexOf('.'); - // - // return lastDot == -1 ? name : name.substring(0, lastDot); - // } - - /** - * Registers a top level package to be searched for {@link Handler} classes. - * Not needed if your {@code @Mod} class implements {@link IEnderMod} - * - * @param packageName - * @deprecated This is not needed, period. - */ - @Deprecated - public static void addPackage(String packageName) { - if (Loader.instance().hasReachedState(LoaderState.INITIALIZATION)) { - throw new RuntimeException("This method must only be called in preinit"); - } - - EnderCore.logger.info("Adding package " + packageName + " to handler search."); - packageSet.add(packageName); - } - - private static boolean registered = false; - - /** - * For internal use only. Do not call. Callers will be sacked. - * - * @param event - */ - public static void register(FMLInitializationEvent event) { - if (registered) { - throw new IllegalStateException("I warned you!"); - } - - for (ASMData data : annotations) { - String className = data.getClassName(); - // if not client handler, or we are on client, continue - if (shouldLoad(data)) { - try { - Class c = Class.forName(className); - Annotation a = c.getAnnotation(Handler.class); - if (a != null) { - registerHandler(c, data, (Handler) a); - } - } catch (Throwable t) { - EnderCore.logger.error(String.format("[Handlers] %s threw an error on load, skipping...", className)); - t.printStackTrace(); + public static void addPackage(String packageName) { + if (Loader.instance().hasReachedState(LoaderState.INITIALIZATION)) { + throw new RuntimeException("This method must only be called in preinit"); } - } else { - EnderCore.logger.info(String.format("[Handlers] Skipping class %s, it is not loaded on this side.", className)); - } + + EnderCore.logger.info("Adding package " + packageName + " to handler search."); + packageSet.add(packageName); } - registered = true; - } + private static boolean registered = false; - private static final Field _value = ReflectionHelper.findField(EnumHolder.class, "value"); + /** + * For internal use only. Do not call. Callers will be sacked. + * + * @param event + */ + public static void register(FMLInitializationEvent event) { + if (registered) { + throw new IllegalStateException("I warned you!"); + } - private static boolean shouldLoad(ASMData data) { - EnumHolder holder = (EnumHolder) data.getAnnotationInfo().get("side"); - HandlerSide side; - try { - if (holder == null) { - side = HandlerSide.AUTO; - } else { - side = HandlerSide.valueOf((String) _value.get(holder)); - } - Side currentSide = FMLCommonHandler.instance().getEffectiveSide(); - - if (side == null || side == HandlerSide.AUTO) { - return !data.getClassName().contains("client") || currentSide.isClient(); - } else { - return side.equals(currentSide); - } - } catch (Exception e) { - Throwables.propagate(e); - } - return false; - } - - private static void registerHandler(Class c, ASMData data, Handler handler) throws InstantiationException, IllegalAccessException { - EnderCore.logger.info(String.format("[Handlers] Registering handler %s to busses: %s", c.getSimpleName(), Arrays.deepToString(handler.value()))); - - Object inst = tryInit(handler, c); - - Method[] methods = c.getDeclaredMethods(); - EnumSet types = EnumSet.noneOf(HandlerType.class); - - // Iterate over all methods to find those with @SubscribeEvent, then figure out what type that method is - for (Method m : methods) { - if (m.isAnnotationPresent(SubscribeEvent.class)) { - Class[] params = m.getParameterTypes(); - if (params.length >= 1) { - Class param = params[0]; - l: while (param != Event.class && param != null && param != Object.class) { - for (HandlerType type : HandlerType.values()) { - if (param.getName().contains(type.eventIdentifier)) { - types.add(type); - break l; - } + for (ASMData data : annotations) { + String className = data.getClassName(); + // if not client handler, or we are on client, continue + if (shouldLoad(data)) { + try { + Class c = Class.forName(className); + Annotation a = c.getAnnotation(Handler.class); + if (a != null) { + registerHandler(c, data, (Handler) a); + } + } catch (Throwable t) { + EnderCore.logger + .error(String.format("[Handlers] %s threw an error on load, skipping...", className)); + t.printStackTrace(); + } + } else { + EnderCore.logger + .info(String.format("[Handlers] Skipping class %s, it is not loaded on this side.", className)); } - param = param.getSuperclass(); - } } - } + + registered = true; } - for (HandlerType type : types) { - type.bus.register(inst); - } - } + private static final Field _value = ReflectionHelper.findField(EnumHolder.class, "value"); - private static Object tryInit(Handler annot, Class c) { - Inst pref = annot.getInstFrom(); + private static boolean shouldLoad(ASMData data) { + EnumHolder holder = (EnumHolder) data.getAnnotationInfo().get("side"); + HandlerSide side; + try { + if (holder == null) { + side = HandlerSide.AUTO; + } else { + side = HandlerSide.valueOf((String) _value.get(holder)); + } + Side currentSide = FMLCommonHandler.instance().getEffectiveSide(); - // Silence all exceptions to trickle down to next if statement. - // If all three fail, RuntimeException is thrown. - if (pref.matches(CONSTRUCTOR)) { - try { - return c.newInstance(); - } catch (Exception e) { - } + if (side == null || side == HandlerSide.AUTO) { + return !data.getClassName().contains("client") || currentSide.isClient(); + } else { + return side.equals(currentSide); + } + } catch (Exception e) { + Throwables.propagate(e); + } + return false; } - if (pref.matches(FIELD)) { - try { - Field inst = c.getDeclaredField("INSTANCE"); - inst.setAccessible(true); - return inst.get(null); - } catch (Exception e) { - } + private static void registerHandler(Class c, ASMData data, Handler handler) + throws InstantiationException, IllegalAccessException { + EnderCore.logger.info( + String.format( + "[Handlers] Registering handler %s to busses: %s", + c.getSimpleName(), + Arrays.deepToString(handler.value()))); + + Object inst = tryInit(handler, c); + + Method[] methods = c.getDeclaredMethods(); + EnumSet types = EnumSet.noneOf(HandlerType.class); + + // Iterate over all methods to find those with @SubscribeEvent, then figure out what type that method is + for (Method m : methods) { + if (m.isAnnotationPresent(SubscribeEvent.class)) { + Class[] params = m.getParameterTypes(); + if (params.length >= 1) { + Class param = params[0]; + l: while (param != Event.class && param != null && param != Object.class) { + for (HandlerType type : HandlerType.values()) { + if (param.getName().contains(type.eventIdentifier)) { + types.add(type); + break l; + } + } + param = param.getSuperclass(); + } + } + } + } + + for (HandlerType type : types) { + type.bus.register(inst); + } } - if (pref.matches(METHOD)) { - try { - Method inst = c.getDeclaredMethod("instance"); - inst.setAccessible(true); - return inst.invoke(null); - } catch (Exception e) { - } - } + private static Object tryInit(Handler annot, Class c) { + Inst pref = annot.getInstFrom(); - if (pref.matches(SCALA_OBJECT)) { - try { - Field inst = Class.forName(c.getName() + "$").getDeclaredField("MODULE$"); - inst.setAccessible(true); - return inst.get(null); - } catch (Exception e) { - } - } + // Silence all exceptions to trickle down to next if statement. + // If all three fail, RuntimeException is thrown. + if (pref.matches(CONSTRUCTOR)) { + try { + return c.newInstance(); + } catch (Exception e) {} + } - throw new RuntimeException("Could not instantiate @Handler class " + c.getName() + " or access INSTANCE field or instance() method."); - } + if (pref.matches(FIELD)) { + try { + Field inst = c.getDeclaredField("INSTANCE"); + inst.setAccessible(true); + return inst.get(null); + } catch (Exception e) {} + } + + if (pref.matches(METHOD)) { + try { + Method inst = c.getDeclaredMethod("instance"); + inst.setAccessible(true); + return inst.invoke(null); + } catch (Exception e) {} + } + + if (pref.matches(SCALA_OBJECT)) { + try { + Field inst = Class.forName(c.getName() + "$").getDeclaredField("MODULE$"); + inst.setAccessible(true); + return inst.get(null); + } catch (Exception e) {} + } + + throw new RuntimeException( + "Could not instantiate @Handler class " + c.getName() + + " or access INSTANCE field or instance() method."); + } } diff --git a/src/main/java/com/enderio/core/common/Lang.java b/src/main/java/com/enderio/core/common/Lang.java index 7ecd784..c6f2327 100644 --- a/src/main/java/com/enderio/core/common/Lang.java +++ b/src/main/java/com/enderio/core/common/Lang.java @@ -8,180 +8,159 @@ import com.google.common.collect.Lists; public class Lang { - private static final String REGEX = "\\" + '|'; - public static final char CHAR = '|'; + private static final String REGEX = "\\" + '|'; + public static final char CHAR = '|'; - private final String prefix; + private final String prefix; - public Lang(String locKey) { - this.prefix = locKey.concat("."); - } - - /** - * @return The prefix assigned to this Lang object. - */ - public String getPrefix() { - return this.prefix; - } - - /** - * Adds the stored prefix to this string, separating with a period. Using this - * method returns the string that is used for localizing if you passed this - * arg into {@link #localize(String, Object...)}. - * - * @param suffix - * The suffix string - * @return The full string - */ - public String addPrefix(String suffix) { - return prefix.concat(suffix); - } - - /** - * Localizes the string passed, first appending the prefix stored in this - * instance of the class. - * - * @param unloc - * The unlocalized string. - * @param args - * The args to format the localized text with. - * - * @return A localized string. - */ - public String localize(String unloc, Object... args) { - return localizeExact(addPrefix(unloc), args); - } - - /** - * Localizes the string passed, first appending the prefix stored in this - * instance of the class. - * - * @param unloc - * The unlocalized string. - * - * @return A localized string. - */ - public String localize(String unloc) { - return localizeExact(addPrefix(unloc)); - } - - /** - * Ignores the prefix stored in this instance of the class and localizes the - * raw string passed. - * - * @param unloc - * The unlocalized string. - * @param args - * The args to format the localized text with. - * - * @return A localized string. - */ - public String localizeExact(String unloc, Object... args) { - return StatCollector.translateToLocalFormatted(unloc, args); - } - - /** - * Ignores the prefix stored in this instance of the class and localizes the - * raw string passed. - * - * @param unloc - * The unlocalized string. - * - * @return A localized string. - */ - public String localizeExact(String unloc) { - return StatCollector.translateToLocal(unloc); - } - - /** - * Splits the localized text on "|" into a String[]. - * - * @param unloc - * The unlocalized string. - * @param args - * The args to format the localized text with. - * @return A localized list of strings. - */ - public String[] localizeList(String unloc, String... args) { - return splitList(localize(unloc, (Object[]) args)); - } - - /** - * Splits the localized text on "|" into a String[]. - * - * @param unloc - * The unlocalized string. - * @return A localized list of strings. - */ - public String[] localizeList(String unloc) { - return splitList(localize(unloc)); - } - - /** - * Localizes all strings in a list, using the prefix. - * - * @param unloc - * The list of unlocalized strings. - * @return A list of localized versions of the passed strings. - */ - public List localizeAll(List unloc) { - List ret = Lists.newArrayList(); - for (String s : unloc) { - ret.add(localize(s)); + public Lang(String locKey) { + this.prefix = locKey.concat("."); } - return ret; - } - /** - * Localizes all strings in an array, using the prefix. - * - * @param unloc - * The array of unlocalized strings. - * @return An array of localized versions of the passed strings. - */ - public String[] localizeAll(Lang lang, String... unloc) { - String[] ret = new String[unloc.length]; - for (int i = 0; i < ret.length; i++) { - ret[i] = lang.localize(unloc[i]); + /** + * @return The prefix assigned to this Lang object. + */ + public String getPrefix() { + return this.prefix; } - return ret; - } - /** - * Splits a list of strings based on {@value #CHAR} - * - * @param list - * The list of strings to split - * @return An array of strings split on {@value #CHAR} - */ - public String[] splitList(String list) { - return list.split(REGEX); - } + /** + * Adds the stored prefix to this string, separating with a period. Using this method returns the string that is + * used for localizing if you passed this arg into {@link #localize(String, Object...)}. + * + * @param suffix The suffix string + * @return The full string + */ + public String addPrefix(String suffix) { + return prefix.concat(suffix); + } - public String[] splitList(String list, String split) { - return list.split(split); - } + /** + * Localizes the string passed, first appending the prefix stored in this instance of the class. + * + * @param unloc The unlocalized string. + * @param args The args to format the localized text with. + * + * @return A localized string. + */ + public String localize(String unloc, Object... args) { + return localizeExact(addPrefix(unloc), args); + } - /** - * Checks if the passed string (plus the prefix) has a localization mapped. - * - * @param unloc - * The unlocalized suffix - * @return True if there is a localization mapped, false otherwise. - */ - public boolean canLocalize(String unloc) { - return canLocalizeExact(addPrefix(unloc)); - } + /** + * Localizes the string passed, first appending the prefix stored in this instance of the class. + * + * @param unloc The unlocalized string. + * + * @return A localized string. + */ + public String localize(String unloc) { + return localizeExact(addPrefix(unloc)); + } - /** - * Checks if the passed string has a localization mapped. Does not use the - * prefix. - * - * @param unloc - * The unlocalized string - * @return True if there is a localization mapped, false otherwise. - */ - public boolean canLocalizeExact(String unloc) { - return StatCollector.canTranslate(unloc); - } + /** + * Ignores the prefix stored in this instance of the class and localizes the raw string passed. + * + * @param unloc The unlocalized string. + * @param args The args to format the localized text with. + * + * @return A localized string. + */ + public String localizeExact(String unloc, Object... args) { + return StatCollector.translateToLocalFormatted(unloc, args); + } + + /** + * Ignores the prefix stored in this instance of the class and localizes the raw string passed. + * + * @param unloc The unlocalized string. + * + * @return A localized string. + */ + public String localizeExact(String unloc) { + return StatCollector.translateToLocal(unloc); + } + + /** + * Splits the localized text on "|" into a String[]. + * + * @param unloc The unlocalized string. + * @param args The args to format the localized text with. + * @return A localized list of strings. + */ + public String[] localizeList(String unloc, String... args) { + return splitList(localize(unloc, (Object[]) args)); + } + + /** + * Splits the localized text on "|" into a String[]. + * + * @param unloc The unlocalized string. + * @return A localized list of strings. + */ + public String[] localizeList(String unloc) { + return splitList(localize(unloc)); + } + + /** + * Localizes all strings in a list, using the prefix. + * + * @param unloc The list of unlocalized strings. + * @return A list of localized versions of the passed strings. + */ + public List localizeAll(List unloc) { + List ret = Lists.newArrayList(); + for (String s : unloc) { + ret.add(localize(s)); + } + return ret; + } + + /** + * Localizes all strings in an array, using the prefix. + * + * @param unloc The array of unlocalized strings. + * @return An array of localized versions of the passed strings. + */ + public String[] localizeAll(Lang lang, String... unloc) { + String[] ret = new String[unloc.length]; + for (int i = 0; i < ret.length; i++) { + ret[i] = lang.localize(unloc[i]); + } + return ret; + } + + /** + * Splits a list of strings based on {@value #CHAR} + * + * @param list The list of strings to split + * @return An array of strings split on {@value #CHAR} + */ + public String[] splitList(String list) { + return list.split(REGEX); + } + + public String[] splitList(String list, String split) { + return list.split(split); + } + + /** + * Checks if the passed string (plus the prefix) has a localization mapped. + * + * @param unloc The unlocalized suffix + * @return True if there is a localization mapped, false otherwise. + */ + public boolean canLocalize(String unloc) { + return canLocalizeExact(addPrefix(unloc)); + } + + /** + * Checks if the passed string has a localization mapped. Does not use the prefix. + * + * @param unloc The unlocalized string + * @return True if there is a localization mapped, false otherwise. + */ + public boolean canLocalizeExact(String unloc) { + return StatCollector.canTranslate(unloc); + } } diff --git a/src/main/java/com/enderio/core/common/OreDict.java b/src/main/java/com/enderio/core/common/OreDict.java index 887e034..5101460 100644 --- a/src/main/java/com/enderio/core/common/OreDict.java +++ b/src/main/java/com/enderio/core/common/OreDict.java @@ -11,62 +11,64 @@ import net.minecraftforge.oredict.OreDictionary; public final class OreDict { - public static 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("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 static void safeRegister(String name, Block block) { - safeRegister(name, Item.getItemFromBlock(block)); - } - - public static void safeRegister(String name, Item item) { - safeRegister(name, new ItemStack(item)); - } - - public static void safeRegister(String name, ItemStack stack) { - if (!isRegistered(stack, OreDictionary.getOres(name))) OreDictionary.registerOre(name, stack); - } - - private static 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; - } + public static 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("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)); } - return false; - } - private OreDict() { - throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); - } -} \ No newline at end of file + public static void safeRegister(String name, Block block) { + safeRegister(name, Item.getItemFromBlock(block)); + } + + public static void safeRegister(String name, Item item) { + safeRegister(name, new ItemStack(item)); + } + + public static void safeRegister(String name, ItemStack stack) { + if (!isRegistered(stack, OreDictionary.getOres(name))) OreDictionary.registerOre(name, stack); + } + + private static 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; + } + + private OreDict() { + throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); + } +} diff --git a/src/main/java/com/enderio/core/common/TileEntityEnder.java b/src/main/java/com/enderio/core/common/TileEntityEnder.java index b97da6b..2908e82 100644 --- a/src/main/java/com/enderio/core/common/TileEntityEnder.java +++ b/src/main/java/com/enderio/core/common/TileEntityEnder.java @@ -17,158 +17,152 @@ import com.enderio.core.common.util.Util; public abstract class TileEntityEnder extends TileEntity { - private final int checkOffset = (int) (Math.random() * 20); - protected final boolean isProgressTile; + private final int checkOffset = (int) (Math.random() * 20); + protected final boolean isProgressTile; - protected int lastProgressScaled = -1; - protected int ticksSinceLastProgressUpdate; + protected int lastProgressScaled = -1; + protected int ticksSinceLastProgressUpdate; - public TileEntityEnder() { - isProgressTile = this instanceof IProgressTile; - } + public TileEntityEnder() { + isProgressTile = this instanceof IProgressTile; + } - @Override - public final boolean canUpdate() { - return shouldUpdate() || isProgressTile; - } + @Override + public final boolean canUpdate() { + return shouldUpdate() || isProgressTile; + } - protected boolean shouldUpdate() { - return true; - } + protected boolean shouldUpdate() { + return true; + } - private long lastUpdate = 0; + private long lastUpdate = 0; - @Override - public final void updateEntity() { - if (ConfigHandler.allowExternalTickSpeedup || worldObj.getTotalWorldTime() != lastUpdate) { - lastUpdate = worldObj.getTotalWorldTime(); - doUpdate(); - if (isProgressTile && !worldObj.isRemote) { - int curScaled = getProgressScaled(16); - if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { - sendTaskProgressPacket(); - lastProgressScaled = curScaled; + @Override + public final void updateEntity() { + if (ConfigHandler.allowExternalTickSpeedup || worldObj.getTotalWorldTime() != lastUpdate) { + lastUpdate = worldObj.getTotalWorldTime(); + doUpdate(); + if (isProgressTile && !worldObj.isRemote) { + int curScaled = getProgressScaled(16); + if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { + sendTaskProgressPacket(); + lastProgressScaled = curScaled; + } + } } - } } - } - public final int getProgressScaled(int scale) { - if (isProgressTile) { - return Util.getProgressScaled(scale, (IProgressTile) this); + public final int getProgressScaled(int scale) { + if (isProgressTile) { + return Util.getProgressScaled(scale, (IProgressTile) this); + } + return 0; } - return 0; - } - protected void doUpdate() { + protected void doUpdate() { - } - - protected void sendTaskProgressPacket() { - if (isProgressTile) { - EnderPacketHandler.sendToAllAround(new PacketProgress((IProgressTile) this), this); } - ticksSinceLastProgressUpdate = 0; - } - /** - * Controls how often progress updates. Has no effect if your TE is not - * {@link IProgressTile}. - */ - protected int getProgressUpdateFreq() { - return 20; - } - - @Override - public final void readFromNBT(NBTTagCompound root) { - super.readFromNBT(root); - readCustomNBT(root); - } - - @Override - public final void writeToNBT(NBTTagCompound root) { - super.writeToNBT(root); - writeCustomNBT(root); - } - - @Override - public Packet getDescriptionPacket() { - NBTTagCompound tag = new NBTTagCompound(); - writeCustomNBT(tag); - return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tag); - } - - @Override - 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; - } - - protected abstract void writeCustomNBT(NBTTagCompound root); - - protected abstract void readCustomNBT(NBTTagCompound root); - - protected void updateBlock() { - if (worldObj != null) { - worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); + protected void sendTaskProgressPacket() { + if (isProgressTile) { + EnderPacketHandler.sendToAllAround(new PacketProgress((IProgressTile) this), this); + } + ticksSinceLastProgressUpdate = 0; } - } - protected boolean isPoweredRedstone() { - return worldObj.blockExists(xCoord, yCoord, zCoord) ? worldObj.getStrongestIndirectPower(xCoord, yCoord, zCoord) > 0 : false; - } + /** + * Controls how often progress updates. Has no effect if your TE is not {@link IProgressTile}. + */ + protected int getProgressUpdateFreq() { + return 20; + } - /** - * Called directly after the TE is constructed. This is the place to call - * non-final methods. - * - * Note: This will not be called when the TE is loaded from the save. Hook - * into the nbt methods for that. - */ - public void init() { - } + @Override + public final void readFromNBT(NBTTagCompound root) { + super.readFromNBT(root); + readCustomNBT(root); + } - private BlockCoord cachedLocation = null; + @Override + public final void writeToNBT(NBTTagCompound root) { + super.writeToNBT(root); + writeCustomNBT(root); + } - public BlockCoord getLocation() { - return cachedLocation == null || !cachedLocation.equals(xCoord, yCoord, zCoord) ? (cachedLocation = new BlockCoord(this)) : cachedLocation; - } + @Override + public Packet getDescriptionPacket() { + NBTTagCompound tag = new NBTTagCompound(); + writeCustomNBT(tag); + return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tag); + } - /** - * Call this with an interval (in ticks) to find out if the current tick is - * the one you want to do some work. This is staggered so the work of - * different TEs is stretched out over time. - * - * @see #shouldDoWorkThisTick(int, int) If you need to offset work ticks - */ - protected boolean shouldDoWorkThisTick(int interval) { - return shouldDoWorkThisTick(interval, 0); - } + @Override + public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { + readCustomNBT(pkt.func_148857_g()); + } - /** - * Call this with an interval (in ticks) to find out if the current tick is - * the one you want to do some work. This is staggered so the work of - * different TEs is stretched out over time. - * - * If you have different work items in your TE, use this variant to stagger - * your work. - */ - protected boolean shouldDoWorkThisTick(int interval, int offset) { - return (worldObj.getTotalWorldTime() + checkOffset + offset) % interval == 0; - } + public boolean canPlayerAccess(EntityPlayer player) { + return !isInvalid() && player.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64D; + } - /** - * Called server-side when a GhostSlot is changed. Check that the given slot - * number really is a ghost slot before storing the given stack. - * - * @param slot - * The slot number that was given to the ghost slot - * @param stack - * The stack that should be placed, null to clear - */ - public void setGhostSlotContents(int slot, ItemStack stack) { - } + protected abstract void writeCustomNBT(NBTTagCompound root); + + protected abstract void readCustomNBT(NBTTagCompound root); + + protected void updateBlock() { + if (worldObj != null) { + worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); + } + } + + protected boolean isPoweredRedstone() { + return worldObj.blockExists(xCoord, yCoord, zCoord) + ? worldObj.getStrongestIndirectPower(xCoord, yCoord, zCoord) > 0 + : false; + } + + /** + * Called directly after the TE is constructed. This is the place to call non-final methods. + * + * Note: This will not be called when the TE is loaded from the save. Hook into the nbt methods for that. + */ + public void init() {} + + private BlockCoord cachedLocation = null; + + public BlockCoord getLocation() { + return cachedLocation == null || !cachedLocation.equals(xCoord, yCoord, zCoord) + ? (cachedLocation = new BlockCoord(this)) + : cachedLocation; + } + + /** + * Call this with an interval (in ticks) to find out if the current tick is the one you want to do some work. This + * is staggered so the work of different TEs is stretched out over time. + * + * @see #shouldDoWorkThisTick(int, int) If you need to offset work ticks + */ + protected boolean shouldDoWorkThisTick(int interval) { + return shouldDoWorkThisTick(interval, 0); + } + + /** + * Call this with an interval (in ticks) to find out if the current tick is the one you want to do some work. This + * is staggered so the work of different TEs is stretched out over time. + * + * If you have different work items in your TE, use this variant to stagger your work. + */ + protected boolean shouldDoWorkThisTick(int interval, int offset) { + return (worldObj.getTotalWorldTime() + checkOffset + offset) % interval == 0; + } + + /** + * Called server-side when a GhostSlot is changed. Check that the given slot number really is a ghost slot before + * storing the given stack. + * + * @param slot The slot number that was given to the ghost slot + * @param stack The stack that should be placed, null to clear + */ + public void setGhostSlotContents(int slot, ItemStack stack) {} } 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 fd32752..12202c1 100644 --- a/src/main/java/com/enderio/core/common/command/CommandReloadConfigs.java +++ b/src/main/java/com/enderio/core/common/command/CommandReloadConfigs.java @@ -18,93 +18,93 @@ import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.relauncher.Side; 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(); + public static final CommandReloadConfigs SERVER = new CommandReloadConfigs(Side.SERVER); + public static final CommandReloadConfigs CLIENT = new CommandReloadConfigs(Side.CLIENT); - 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()); - } - } - } - - private CommandReloadConfigs(Side side) { - this.side = side; - } + for (ModContainer mod : Loader.instance().getActiveModList()) { + ConfigFileChangedEvent event = new ConfigFileChangedEvent(mod.getModId()); + FMLCommonHandler.instance().bus().post(event); - @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); + if (event.isSuccessful()) { + validModIDs.add(mod.getModId()); + } + } } - return null; - } + private CommandReloadConfigs(Side side) { + this.side = side; + } - @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; - } + @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); } - if (validModid) { - ConfigFileChangedEvent event = new ConfigFileChangedEvent(s); - FMLCommonHandler.instance().bus().post(event); + return null; + } - if (event.isSuccessful()) { - sendResult(player, s, "success"); - } else { - sendResult(player, s, "fail"); - } - } else { - sendResult(player, s, "invalid"); + @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"); + } } - } - } + } - 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 19734e8..1960bc4 100644 --- a/src/main/java/com/enderio/core/common/command/CommandScoreboardInfo.java +++ b/src/main/java/com/enderio/core/common/command/CommandScoreboardInfo.java @@ -14,74 +14,78 @@ import net.minecraft.scoreboard.Scoreboard; import net.minecraft.util.ChatComponentText; 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 getCommandName() { + return "scoreboardinfo"; } - Scoreboard board = player.getEntityWorld().getScoreboard(); - - ScoreObjective obj = board.getObjective(args[0]); - - if (obj == null) { - player.addChatMessage(new ChatComponentText("No such board " + args[0])); + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/scoreboardinfo "; } - 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; - } + @Override + public int getRequiredPermissionLevel() { + return 0; } - player.addChatMessage(new ChatComponentText("No score for " + args[1] + " on board \"" + args[0] + "\"")); - } - - @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); + @Override + public boolean canCommandSenderUseCommand(ICommandSender p_71519_1_) { + return true; } - if (args.length == 2) { - List players = new ArrayList(); - for (EntityPlayer p : (List) player.getEntityWorld().playerEntities) { - players.add(p.getCommandSenderName()); - } + @SuppressWarnings("unchecked") + @Override + public void processCommand(ICommandSender player, String[] args) { + if (args.length < 2) { + throw new WrongUsageException("This command requires 2 args: "); + } - return getListOfStringsFromIterableMatchingLastWord(args, players); + 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] + "\"")); } - 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 b3bb657..954c609 100644 --- a/src/main/java/com/enderio/core/common/compat/CompatRegistry.java +++ b/src/main/java/com/enderio/core/common/compat/CompatRegistry.java @@ -16,120 +16,127 @@ import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLStateEvent; public enum CompatRegistry { - INSTANCE; - private static class Registration { - private final String[] modids; - private final RegisterTime[] times; + INSTANCE; - private Registration(RegisterTime time, String... modids) { - this.modids = modids; - this.times = new RegisterTime[] { time }; + private static class Registration { + + private final String[] modids; + private final 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; + } + + public String[] getModids() { + return this.modids; + } + + public RegisterTime[] getTimes() { + return this.times; + } + + @Override + @Generated("lombok") + public boolean equals(final java.lang.Object o) { + if (o == this) return true; + if (!(o instanceof CompatRegistry.Registration)) return false; + final Registration other = (Registration) o; + if (!java.util.Arrays.deepEquals(this.getModids(), other.getModids())) return false; + if (!java.util.Arrays.deepEquals(this.getTimes(), other.getTimes())) return false; + return true; + } + + @Override + @Generated("lombok") + public int hashCode() { + final int PRIME = 59; + int result = 1; + result = result * PRIME + java.util.Arrays.deepHashCode(this.getModids()); + result = result * PRIME + java.util.Arrays.deepHashCode(this.getTimes()); + return result; + } + + @Override + @Generated("lombok") + public java.lang.String toString() { + return "CompatRegistry.Registration(modids=" + java.util.Arrays.deepToString(this.getModids()) + + ", times=" + + java.util.Arrays.deepToString(this.getTimes()) + + ")"; + } } - private Registration(RegisterTime[] times, String... modids) { - this.modids = modids; - this.times = times; - } - - public String[] getModids() { - return this.modids; + private Map compatMap = new HashMap(); + + private RegisterTime state = null; + + private CompatRegistry() {} + + public RegisterTime getState() { + return state; } - public RegisterTime[] getTimes() { - return this.times; + public void registerCompat(RegisterTime time, String clazz, String... modids) { + compatMap.put(new Registration(time, modids), clazz); } - @Override - @Generated("lombok") - public boolean equals(final java.lang.Object o) { - if (o == this) return true; - if (!(o instanceof CompatRegistry.Registration)) return false; - final Registration other = (Registration)o; - if (!java.util.Arrays.deepEquals(this.getModids(), other.getModids())) return false; - if (!java.util.Arrays.deepEquals(this.getTimes(), other.getTimes())) return false; - return true; + public void registerCompat(RegisterTime[] times, String clazz, String... modids) { + compatMap.put(new Registration(times, modids), clazz); } - @Override - @Generated("lombok") - public int hashCode() { - final int PRIME = 59; - int result = 1; - result = result * PRIME + java.util.Arrays.deepHashCode(this.getModids()); - result = result * PRIME + java.util.Arrays.deepHashCode(this.getTimes()); - return result; + 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)); + } + } } - @Override - @Generated("lombok") - public java.lang.String toString() { - return "CompatRegistry.Registration(modids=" + java.util.Arrays.deepToString(this.getModids()) + ", times=" + java.util.Arrays.deepToString(this.getTimes()) + ")"; + private boolean allModsLoaded(String[] modids) { + for (String s : modids) { + if (!Loader.isModLoaded(s)) { + return false; + } + } + return true; } - } - - private Map compatMap = new HashMap(); - private RegisterTime state = null; - - private CompatRegistry() { - } - - public RegisterTime getState() { - return state; - } - - public void registerCompat(RegisterTime time, String clazz, String... modids) { - compatMap.put(new Registration(time, modids), clazz); - } - - 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)); - } + 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 boolean allModsLoaded(String[] modids) { - for (String s : modids) { - if (!Loader.isModLoaded(s)) { - return false; - } + 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(); + } } - 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 d6f09df..4093c48 100644 --- a/src/main/java/com/enderio/core/common/compat/ICompat.java +++ b/src/main/java/com/enderio/core/common/compat/ICompat.java @@ -1,9 +1,10 @@ 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 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 0f9451f..10e4ad1 100644 --- a/src/main/java/com/enderio/core/common/config/AbstractConfigHandler.java +++ b/src/main/java/com/enderio/core/common/config/AbstractConfigHandler.java @@ -23,571 +23,513 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; 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 { - /** - * No restart needed for this config to be applied. Default value. - */ - NONE, /** - * This config requires the world to be restarted to take effect. + * Represents a section in a config handler. */ - REQUIRES_WORLD_RESTART, + 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(); + } /** - * This config requires the game to be restarted to take effect. - * {@code REQUIRES_WORLD_RESTART} is implied when using this. + * Called after config is loaded, but before properties are processed. + *

+ * Use this method to add your sections and do other setup. */ - REQUIRES_MC_RESTART; + protected abstract void init(); - public Property apply(Property prop) { - if (this == REQUIRES_MC_RESTART) { - prop.setRequiresMcRestart(true); - } else if (this == REQUIRES_WORLD_RESTART) { - prop.setRequiresWorldRestart(true); - } - return prop; - } - } + /** + * 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(); - String modid; - Configuration config; + /** + * 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(); - 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. 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); } - 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 + * @return A {@link Section} representing your section in the config + */ + protected Section addSection(String sectionName, String langKey) { + return addSection(sectionName, langKey, null); } - return section.register(); - } + /** + * 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); - private void checkInitialized() { - if (activeSection == null) { - throw new IllegalStateException("No section is active!"); - } - } + if (activeSection == null && sections.isEmpty()) { + activeSection = section; + } - /** - * Activates a section - * - * @param sectionName - * The name of the section - * - * @throws IllegalArgumentException - * if {@code sectionName} is not valid - */ - protected void activateSection(String sectionName) { - Section section = getSectionByName(sectionName); - if (section == null) { - throw new IllegalArgumentException("Section " + sectionName + " does not exist!"); - } - activateSection(section); - } + if (comment != null) { + config.addCustomCategoryComment(sectionName, comment); + } - /** - * Activates a section - * - * @param section - * The section to activate - */ - protected void activateSection(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 - */ - protected Section getSectionByName(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; + return section.register(); } - 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(); + private void checkInitialized() { + if (activeSection == null) { + throw new IllegalStateException("No section is active!"); + } } - 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; + /** + * Activates a section + * + * @param sectionName The name of the section + * + * @throws IllegalArgumentException if {@code sectionName} is not valid + */ + protected void activateSection(String sectionName) { + Section section = getSectionByName(sectionName); + if (section == null) { + throw new IllegalArgumentException("Section " + sectionName + " does not exist!"); + } + activateSection(section); } - 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)); + + /** + * Activates a section + * + * @param section The section to activate + */ + protected void activateSection(Section section) { + activeSection = section; } - } - 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]); + /** + * 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 + */ + protected Section getSectionByName(String sectionName) { + for (Section s : sections) { + if (s.name.equalsIgnoreCase(sectionName)) { + return s; + } + } + return null; } - 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]); + /** + * 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); } - 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); + /** + * 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); } - if (defVal instanceof Double) { - return (T) boundDouble(prop, (Bound) b); + + /** + * 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); } - if (defVal instanceof Float) { - return (T) boundFloat(prop, (Bound) b); + + /** + * 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); } - 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 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 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 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 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 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; + } + + 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 // same logic as above method, mostly @@ -613,53 +555,51 @@ 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 (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 (prop != null) { - return req.apply(prop); + /** + * @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; } - throw new IllegalArgumentException("default value is not a config value type."); - } + /* IConfigHandler impl */ - /** - * @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 initHook() {} - /* IConfigHandler impl */ + @Override + public void postInitHook() {} - @Override - public void initHook() { - } + // no need to override these, they are merely utilities, and reference private fields anyways - @Override - public void postInitHook() { - } + @Override + public final List

getSections() { + return ImmutableList.copyOf(sections); + } - // no need to override these, they are merely utilities, and reference private fields anyways + @Override + public final ConfigCategory getCategory(String name) { + return config.getCategory(name); + } - @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; - } + @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 ae570b9..cfc8dc6 100644 --- a/src/main/java/com/enderio/core/common/config/BaseConfigFactory.java +++ b/src/main/java/com/enderio/core/common/config/BaseConfigFactory.java @@ -2,31 +2,32 @@ package com.enderio.core.common.config; import java.util.Set; -import com.enderio.core.client.config.BaseConfigGui; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; + +import com.enderio.core.client.config.BaseConfigGui; import cpw.mods.fml.client.IModGuiFactory; public class BaseConfigFactory implements IModGuiFactory { - @Override - public void initialize(Minecraft minecraftInstance) { - ; - } - @Override - public Class mainConfigGuiClass() { - return BaseConfigGui.class; - } + @Override + public void initialize(Minecraft minecraftInstance) { + ; + } - @Override - public Set runtimeGuiCategories() { - return null; - } + @Override + public Class mainConfigGuiClass() { + return BaseConfigGui.class; + } - @Override - public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { - return null; - } + @Override + public Set runtimeGuiCategories() { + return null; + } + + @Override + public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { + return null; + } } diff --git a/src/main/java/com/enderio/core/common/config/ConfigHandler.java b/src/main/java/com/enderio/core/common/config/ConfigHandler.java index 3b3e043..ef6358e 100644 --- a/src/main/java/com/enderio/core/common/config/ConfigHandler.java +++ b/src/main/java/com/enderio/core/common/config/ConfigHandler.java @@ -19,149 +19,157 @@ import com.enderio.core.common.tweaks.Tweak; import com.enderio.core.common.tweaks.Tweaks; public class ConfigHandler extends AbstractConfigHandler implements ITweakConfigHandler, IReloadCallback { - private static final String sectionGeneral = Configuration.CATEGORY_GENERAL; - private static final String sectionEnchants = "enchants"; - @Config - @Comment({ "Show oredictionary names of every item in its tooltip.", "0 - Off", "1 - Always on", "2 - Only with shift", "3 - Only in debug mode" }) - @Range(min = 0, max = 3) - @NoSync - public static int showOredictTooltips = 2; + private static final String sectionGeneral = Configuration.CATEGORY_GENERAL; + private static final String sectionEnchants = "enchants"; - @Config - @Comment({ "Show item registry names in tooltips.", "0 - Off", "1 - Always on", "2 - Only with shift", "3 - Only in debug mode" }) - @Range(min = 0, max = 3) - @NoSync - public static int showRegistryNameTooltips = 3; + @Config + @Comment({ "Show oredictionary names of every item in its tooltip.", "0 - Off", "1 - Always on", + "2 - Only with shift", "3 - Only in debug mode" }) + @Range(min = 0, max = 3) + @NoSync + public static int showOredictTooltips = 2; - @Config - @Comment({ "Show durability on item tooltips.", "0 - Off", "1 - Always on", "2 - Only with shift", "3 - Only in debug mode" }) - @Range(min = 0, max = 3) - @NoSync - public static int showDurabilityTooltips = 1; + @Config + @Comment({ "Show item registry names in tooltips.", "0 - Off", "1 - Always on", "2 - Only with shift", + "3 - Only in debug mode" }) + @Range(min = 0, max = 3) + @NoSync + public static int showRegistryNameTooltips = 3; - @Config - @Comment({ "Removes all void fog.", "0 = off", "1 = DEFAULT worldtype only", "2 = all world types" }) - @NoSync - @Range(min = 0, max = 2) - public static int disableVoidFog = 1; + @Config + @Comment({ "Show durability on item tooltips.", "0 - Off", "1 - Always on", "2 - Only with shift", + "3 - Only in debug mode" }) + @Range(min = 0, max = 3) + @NoSync + public static int showDurabilityTooltips = 1; - @Config - @Comment("The max amount of XP levels an anvil recipe can use.") - public static int anvilMaxLevel = 40; + @Config + @Comment({ "Removes all void fog.", "0 = off", "1 = DEFAULT worldtype only", "2 = all world types" }) + @NoSync + @Range(min = 0, max = 2) + public static int disableVoidFog = 1; - @Config - @Comment("The way the game should have been made (Yes this is the fireworks thing).") - public static boolean betterAchievements = true; + @Config + @Comment("The max amount of XP levels an anvil recipe can use.") + public static int anvilMaxLevel = 40; - @Config - @Comment("Disabling this option will prevent any crops added to the config json from being right clickable.") - public static boolean allowCropRC = true; + @Config + @Comment("The way the game should have been made (Yes this is the fireworks thing).") + public static boolean betterAchievements = true; - @Config - @Comment("Prevent tick speedup (i.e. torcherino) on any TE that uses the base TE class from EnderCore") - public static boolean allowExternalTickSpeedup = false; + @Config + @Comment("Disabling this option will prevent any crops added to the config json from being right clickable.") + public static boolean allowCropRC = true; - @Config - @Comment({ "0 - Do nothing", "1 - Remove stacktraces, leave 1-line missing texture errors", "2 - Remove all missing texture errors completely." }) - @NoSync - @Range(min = 0, max = 2) - public static int textureErrorRemover = 1; + @Config + @Comment("Prevent tick speedup (i.e. torcherino) on any TE that uses the base TE class from EnderCore") + public static boolean allowExternalTickSpeedup = false; - @Config - @Comment({ "Controls the default sorting on the mod list GUI.", "0 - Default sort (load order)", "1 - A to Z sort", "2 - Z to A sort" }) - @NoSync - @Range(min = 0, max = 2) - public static int defaultModSort = 1; + @Config + @Comment({ "0 - Do nothing", "1 - Remove stacktraces, leave 1-line missing texture errors", + "2 - Remove all missing texture errors completely." }) + @NoSync + @Range(min = 0, max = 2) + public static int textureErrorRemover = 1; - @Config(sectionEnchants) - @Comment("Enchant ID for the XP boost enchant.") - @RestartReq(RestartReqs.REQUIRES_MC_RESTART) - @Range(min = 0, max = 255) - public static int enchantIDXPBoost = 45; + @Config + @Comment({ "Controls the default sorting on the mod list GUI.", "0 - Default sort (load order)", "1 - A to Z sort", + "2 - Z to A sort" }) + @NoSync + @Range(min = 0, max = 2) + public static int defaultModSort = 1; - @Config(sectionEnchants) - @Comment("Allow the XP Boost enchant to be registered.") - @RestartReq(RestartReqs.REQUIRES_MC_RESTART) - public static boolean allowXPBoost = true; + @Config(sectionEnchants) + @Comment("Enchant ID for the XP boost enchant.") + @RestartReq(RestartReqs.REQUIRES_MC_RESTART) + @Range(min = 0, max = 255) + public static int enchantIDXPBoost = 45; - @Config(sectionEnchants) - @Comment("Enchant ID for the Auto Smelt enchant.") - @RestartReq(RestartReqs.REQUIRES_MC_RESTART) - @Range(min = 0, max = 255) - public static int enchantIDAutoSmelt = 46; + @Config(sectionEnchants) + @Comment("Allow the XP Boost enchant to be registered.") + @RestartReq(RestartReqs.REQUIRES_MC_RESTART) + public static boolean allowXPBoost = true; - @Config(sectionEnchants) - @Comment("Allow the Auto Smelt enchant to be registered.") - @RestartReq(RestartReqs.REQUIRES_MC_RESTART) - public static boolean allowAutoSmelt = true; + @Config(sectionEnchants) + @Comment("Enchant ID for the Auto Smelt enchant.") + @RestartReq(RestartReqs.REQUIRES_MC_RESTART) + @Range(min = 0, max = 255) + public static int enchantIDAutoSmelt = 46; - @Config(sectionEnchants) - @Comment("Allow the Auto Smelt enchant to work with Fortune.") - public static boolean allowAutoSmeltWithFortune = true; + @Config(sectionEnchants) + @Comment("Allow the Auto Smelt enchant to be registered.") + @RestartReq(RestartReqs.REQUIRES_MC_RESTART) + public static boolean allowAutoSmelt = true; - // @Config("test") - // public static List test1 = Lists.newArrayList(1, 2, 3); - // @Config("test") - // public static List test2 = Lists.newArrayList(0.1, 0.2, 0.3); - // @Config("test") - // public static List test3 = Lists.newArrayList(true, false, true); - // @Config("test") - // public static List test4 = Lists.newArrayList("test1", "test2", "test3"); + @Config(sectionEnchants) + @Comment("Allow the Auto Smelt enchant to work with Fortune.") + public static boolean allowAutoSmeltWithFortune = true; - private static ConfigHandler INSTANCE; + // @Config("test") + // public static List test1 = Lists.newArrayList(1, 2, 3); + // @Config("test") + // public static List test2 = Lists.newArrayList(0.1, 0.2, 0.3); + // @Config("test") + // public static List test3 = Lists.newArrayList(true, false, true); + // @Config("test") + // public static List test4 = Lists.newArrayList("test1", "test2", "test3"); - public static File configFolder, enderConfigFolder; - public static File configFile; - public static ConfigProcessor processor; + private static ConfigHandler INSTANCE; - public static ConfigHandler instance() { - if (INSTANCE == null) { - INSTANCE = new ConfigHandler(); + public static File configFolder, enderConfigFolder; + public static File configFile; + public static ConfigProcessor processor; + + public static ConfigHandler instance() { + if (INSTANCE == null) { + INSTANCE = new ConfigHandler(); + } + return INSTANCE; } - return INSTANCE; - } - protected ConfigHandler() { - super(EnderCore.MODID); - } - - @Override - public void init() { - addSection(sectionGeneral); - addSection(sectionEnchants); - addSection("tweaks"); - processor = new ConfigProcessor(getClass(), this, this); - processor.process(true); - } - - @Override - protected void reloadIngameConfigs() { - Tweaks.loadIngameTweaks(); - } - - @Override - protected void reloadNonIngameConfigs() { - Tweaks.loadNonIngameTweaks(); - } - - @Override - public void callback(ConfigProcessor inst) { - Tweaks.loadIngameTweaks(); - } - - @Override - public boolean addBooleanFor(Tweak tweak) { - activateSection("tweaks"); - return getValue(tweak.getName(), tweak.getComment(), true); - } - - public void loadRightClickCrops() { - JsonConfigReader reader = new JsonConfigReader(new ModToken(EnderCore.class, EnderCore.MODID.toLowerCase(Locale.US) + "/config"), - enderConfigFolder.getAbsolutePath() + "/cropConfig.json", PlantInfo.class); - for (PlantInfo i : reader) { - i.init(); - RightClickCropHandler.INSTANCE.addCrop(i); + protected ConfigHandler() { + super(EnderCore.MODID); + } + + @Override + public void init() { + addSection(sectionGeneral); + addSection(sectionEnchants); + addSection("tweaks"); + processor = new ConfigProcessor(getClass(), this, this); + processor.process(true); + } + + @Override + protected void reloadIngameConfigs() { + Tweaks.loadIngameTweaks(); + } + + @Override + protected void reloadNonIngameConfigs() { + Tweaks.loadNonIngameTweaks(); + } + + @Override + public void callback(ConfigProcessor inst) { + Tweaks.loadIngameTweaks(); + } + + @Override + public boolean addBooleanFor(Tweak tweak) { + activateSection("tweaks"); + return getValue(tweak.getName(), tweak.getComment(), true); + } + + public void loadRightClickCrops() { + JsonConfigReader reader = new JsonConfigReader( + new ModToken(EnderCore.class, EnderCore.MODID.toLowerCase(Locale.US) + "/config"), + enderConfigFolder.getAbsolutePath() + "/cropConfig.json", + PlantInfo.class); + for (PlantInfo i : reader) { + i.init(); + RightClickCropHandler.INSTANCE.addCrop(i); + } } - } } 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 be50b04..be13be0 100644 --- a/src/main/java/com/enderio/core/common/config/ConfigProcessor.java +++ b/src/main/java/com/enderio/core/common/config/ConfigProcessor.java @@ -8,13 +8,13 @@ import java.util.Set; import javax.annotation.Nullable; -import org.apache.commons.lang3.StringUtils; - import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; +import org.apache.commons.lang3.StringUtils; + import com.enderio.core.EnderCore; import com.enderio.core.common.config.AbstractConfigHandler.RestartReqs; import com.enderio.core.common.config.annot.Comment; @@ -38,359 +38,356 @@ 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); - } - /** - * 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(); + public interface IReloadCallback { - Property.Type getType(); + void callback(ConfigProcessor inst); + } /** - * 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. + * 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. */ - @Nullable - Class getPrimitiveType(); + public interface ITypeAdapter { - ACTUAL createActualType(BASE base); + TypeToken getActualType(); - BASE createBaseType(ACTUAL actual); - } + Property.Type getType(); - static final Map processorMap = Maps.newHashMap(); + /** + * 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(); - private final List> adapters = Lists.newArrayList(); + ACTUAL createActualType(BASE base); - 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(); + BASE createBaseType(ACTUAL actual); } - try { - for (Field f : configs.getDeclaredFields()) { - processField(f); - } - if (callback != null) { - callback.callback(this); - } - } catch (Exception e) { - throw new RuntimeException(e); + 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); } - 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); + /** + * 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); } - Object newValue = getConfigValue(cfg.value(), getComment(f), f, 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} + */ + public ConfigProcessor(Class configs, AbstractConfigHandler handler) { + this(configs, handler, null); + } - configValues.put(f.getName(), newValue); - originalValues.put(f.getName(), newValue); - f.set(null, newValue); + /** + * 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); + } - sections.add(cfg.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); + } - return !value.equals(newValue); - } + public ConfigProcessor addAdapter(ITypeAdapter adapter) { + adapters.add(adapter); + return this; + } - @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(); + public ConfigProcessor addAdapters(ITypeAdapter... adapters) { + for (ITypeAdapter adapter : adapters) { + addAdapter(adapter); } - 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); + 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 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); + + try { + for (Field f : configs.getDeclaredFields()) { + processField(f); + } + if (callback != null) { + callback.callback(this); + } + } 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(); + } + + // 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; } - 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)); - } - - @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); } - } catch (Exception e) { - throw new RuntimeException(e); - } + + 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); } - } - private String[] getComment(Field f) { - Comment c = f.getAnnotation(Comment.class); - return c == null ? new String[0] : c.value(); - } - - private Bound getBound(Field f) { - Range r = f.getAnnotation(Range.class); - return r == null ? Bound.MAX_BOUND : Bound.of(r.min(), r.max()); - } - - private boolean getNoSync(Field f) { - return f.getAnnotation(NoSync.class) != null; - } - - 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); + @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)); } - } - @SubscribeEvent - public void onConfigFileChanged(ConfigFileChangedEvent event) { - if (event.modID.equals(modid)) { - process(true); + @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()); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + private String[] getComment(Field f) { + Comment c = f.getAnnotation(Comment.class); + return c == null ? new String[0] : c.value(); + } + + private Bound getBound(Field f) { + Range r = f.getAnnotation(Range.class); + return r == null ? Bound.MAX_BOUND : Bound.of(r.min(), r.max()); + } + + private boolean getNoSync(Field f) { + return f.getAnnotation(NoSync.class) != null; + } + + 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); + } } - } } 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 07e8439..2403d0a 100644 --- a/src/main/java/com/enderio/core/common/config/ITweakConfigHandler.java +++ b/src/main/java/com/enderio/core/common/config/ITweakConfigHandler.java @@ -3,5 +3,6 @@ package com.enderio.core.common.config; import com.enderio.core.common.tweaks.Tweak; public interface ITweakConfigHandler { - public boolean addBooleanFor(Tweak tweak); + + public boolean addBooleanFor(Tweak tweak); } diff --git a/src/main/java/com/enderio/core/common/config/JsonConfigReader.java b/src/main/java/com/enderio/core/common/config/JsonConfigReader.java index 62dc51f..112f9fe 100644 --- a/src/main/java/com/enderio/core/common/config/JsonConfigReader.java +++ b/src/main/java/com/enderio/core/common/config/JsonConfigReader.java @@ -28,233 +28,207 @@ import com.google.gson.reflect.TypeToken; *

* Where the objects go inbetween the brackets ( [] ) * - * @param - * The type of the object to be read in. If this type is generic in - * itself (ex. {@code HashMap}) you should use one of the TypeToken - * constructors. + * @param The type of the object to be read in. If this type is generic in itself (ex. {@code HashMap}) you should + * use one of the TypeToken constructors. */ public class JsonConfigReader implements Iterable { - /** - * A class representing some info about your mod. - *

- * mainClass is a class in your mod so that files can be copied out of - * your jar.
- * assetPath is the path to your default json file. This includes the - * /modid part and whatever subfolders follow. - */ - public static class ModToken { - private Class mainClass; - private String assetPath; - public ModToken(Class mainClass, String assetPath) { - this.mainClass = mainClass; - this.assetPath = assetPath; - } - - public Class getMainClass() { - return mainClass; - } - - public String getAssetPath() { - return assetPath; - } - } + /** + * A class representing some info about your mod. + *

+ * mainClass is a class in your mod so that files can be copied out of your jar.
+ * assetPath is the path to your default json file. This includes the /modid part and whatever subfolders + * follow. + */ + public static class ModToken { - /** - * The default key for the json data. This is what is used when calling - * {@link #getElements()}. - */ - public static final String DEFAULT_KEY = "data"; - private static final JsonParser parser = new JsonParser(); + private Class mainClass; + private String assetPath; - private final GsonBuilder builder = new GsonBuilder(); + public ModToken(Class mainClass, String assetPath) { + this.mainClass = mainClass; + this.assetPath = assetPath; + } - private File file; - private JsonObject root; + public Class getMainClass() { + return mainClass; + } - private Class type = null; - private TypeToken typeToken = null; - - /** - * An easy way to read in config files in JSON format - * - * @param mod - * A {@link ModToken} object to hold data about your mod. This is - * used to automatically copy the file from your jar if it does not - * exist in the config folder - * @param fullFileName - * The full file path and name of your JSON config. Can be relative - * to the working directory or absolute. - * @param objClass - * The type of the object being deserialized. Must be of the same - * type as the generic type of this class. - */ - public JsonConfigReader(ModToken mod, String fullFileName, Class objClass) { - this(mod, new File(fullFileName), objClass); - } - - /** - * An easy way to read in config files in JSON format - * - * @param mod - * A {@link ModToken} object to hold data about your mod. This is - * used to automatically copy the file from your jar if it does not - * exist in the config folder - * @param file - * The {@link File} representing your JSON config. - * @param objClass - * The type of the object being deserialized. Must be of the same - * type as the generic type of this class. - */ - public JsonConfigReader(ModToken mod, File file, Class objClass) { - this.type = objClass; - initialize(mod, file); - } - - /** - * An easy way to read in config files in JSON format. Use this constructor if - * the type of this class is generic in itself. (ex. {@code HashMap}) - * - * @param mod - * A {@link ModToken} object to hold data about your mod. This is - * used to automatically copy the file from your jar if it does not - * exist in the config folder - * @param fullFileName - * The full file path and name of your JSON config. Can be relative - * to the working directory or absolute. - * @param objType - * A {@link TypeToken} representing the type of the object to be - * deserialized. Must be of the same type as the generic type of this - * class. - */ - public JsonConfigReader(ModToken mod, String fullFileName, TypeToken objType) { - this(mod, new File(fullFileName), objType); - } - - /** - * An easy way to read in config files in JSON format. Use this constructor if - * the type of this class is generic in itself. (ex. {@code HashMap}) - * - * @param mod - * A {@link ModToken} object to hold data about your mod. This is - * used to automatically copy the file from your jar if it does not - * exist in the config folder - * @param file - * The {@link File} representing your JSON config. - * @param objType - * A {@link TypeToken} representing the type of the object to be - * deserialized. Must be of the same type as the generic type of this - * class. - */ - public JsonConfigReader(ModToken mod, File file, TypeToken objType) { - this.typeToken = objType; - initialize(mod, file); - } - - private void initialize(ModToken mod, File file) { - this.file = file; - - if (!file.exists()) { - file.getParentFile().mkdirs(); - String assetPath = mod.getAssetPath(); - if (!assetPath.endsWith("/")) { - assetPath = assetPath + "/"; - } - - EnderFileUtils.copyFromJar(mod.getMainClass(), assetPath + file.getName(), file); + public String getAssetPath() { + return assetPath; + } } - refresh(); - } + /** + * The default key for the json data. This is what is used when calling {@link #getElements()}. + */ + public static final String DEFAULT_KEY = "data"; + private static final JsonParser parser = new JsonParser(); - /** - * Reparses the config file. - * - * @return The {@link JsonObject} read. - * - * @throws RuntimeException - * If there is an exception while reading the file. - */ - public JsonObject parseFile() { - try { - return parser.parse(new FileReader(file)).getAsJsonObject(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + private final GsonBuilder builder = new GsonBuilder(); - /** - * Reparses the config file and stores the result in this class. Use this if - * your JSON config was edited and you want to reload from disk. - * - * @throws RuntimeException - * If there is an exception while reading the file. - */ - public void refresh() { - this.root = parseFile(); - } + private File file; + private JsonObject root; - /** - * If this key exists in the current JSON data. - * - * @param key - * The String key - * @return True if this JSON has the given key. False otherwise. - */ - public boolean hasKey(String key) { - return root.get(key) != null; - } + private Class type = null; + private TypeToken typeToken = null; - /** - * Gives this reader's {@link GsonBuilder} object so that you may configure - * type adapters and other settings. - */ - public GsonBuilder getBuilder() { - return builder; - } - - /** - * Reads from the {@link JsonObject} linked to the {@link String key} and - * returns a List of all the elements contained in its array. - * - * @return A list of the generic type of this class containing the - * deserialized elements from the passed key. - */ - @SuppressWarnings("unchecked") - public List getElements(String key) { - if (!hasKey(key)) { - return Lists.newArrayList(); + /** + * An easy way to read in config files in JSON format + * + * @param mod A {@link ModToken} object to hold data about your mod. This is used to automatically copy the + * file from your jar if it does not exist in the config folder + * @param fullFileName The full file path and name of your JSON config. Can be relative to the working directory or + * absolute. + * @param objClass The type of the object being deserialized. Must be of the same type as the generic type of + * this class. + */ + public JsonConfigReader(ModToken mod, String fullFileName, Class objClass) { + this(mod, new File(fullFileName), objClass); } - Gson gson = builder.create(); - JsonArray elements = root.get(key).getAsJsonArray(); - List list = new ArrayList(); - for (int i = 0; i < elements.size(); i++) { - if (type == null) { - list.add((T) gson.fromJson(elements.get(i), typeToken.getType())); - } else { - list.add(gson.fromJson(elements.get(i), type)); - } + /** + * An easy way to read in config files in JSON format + * + * @param mod A {@link ModToken} object to hold data about your mod. This is used to automatically copy the + * file from your jar if it does not exist in the config folder + * @param file The {@link File} representing your JSON config. + * @param objClass The type of the object being deserialized. Must be of the same type as the generic type of this + * class. + */ + public JsonConfigReader(ModToken mod, File file, Class objClass) { + this.type = objClass; + initialize(mod, file); } - return list; - } - /** - * Reads the default (defined by {@value #DEFAULT_KEY}) cached JsonObject in - * this class and returns a List of all the elements contained in its array. - *

- * {@link #getElements(String)} should be used if your config has multiple - * keys. - * - * @return A list of the generic type of this class containing the - * deserialized elements from your JSON config's default key. - */ - public List getElements() { - return getElements(DEFAULT_KEY); - } + /** + * An easy way to read in config files in JSON format. Use this constructor if the type of this class is generic in + * itself. (ex. {@code HashMap}) + * + * @param mod A {@link ModToken} object to hold data about your mod. This is used to automatically copy the + * file from your jar if it does not exist in the config folder + * @param fullFileName The full file path and name of your JSON config. Can be relative to the working directory or + * absolute. + * @param objType A {@link TypeToken} representing the type of the object to be deserialized. Must be of the + * same type as the generic type of this class. + */ + public JsonConfigReader(ModToken mod, String fullFileName, TypeToken objType) { + this(mod, new File(fullFileName), objType); + } - @Override - public Iterator iterator() { - return getElements().iterator(); - } + /** + * An easy way to read in config files in JSON format. Use this constructor if the type of this class is generic in + * itself. (ex. {@code HashMap}) + * + * @param mod A {@link ModToken} object to hold data about your mod. This is used to automatically copy the file + * from your jar if it does not exist in the config folder + * @param file The {@link File} representing your JSON config. + * @param objType A {@link TypeToken} representing the type of the object to be deserialized. Must be of the same + * type as the generic type of this class. + */ + public JsonConfigReader(ModToken mod, File file, TypeToken objType) { + this.typeToken = objType; + initialize(mod, file); + } + + private void initialize(ModToken mod, File file) { + this.file = file; + + if (!file.exists()) { + file.getParentFile().mkdirs(); + String assetPath = mod.getAssetPath(); + if (!assetPath.endsWith("/")) { + assetPath = assetPath + "/"; + } + + EnderFileUtils.copyFromJar(mod.getMainClass(), assetPath + file.getName(), file); + } + + refresh(); + } + + /** + * Reparses the config file. + * + * @return The {@link JsonObject} read. + * + * @throws RuntimeException If there is an exception while reading the file. + */ + public JsonObject parseFile() { + try { + return parser.parse(new FileReader(file)).getAsJsonObject(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Reparses the config file and stores the result in this class. Use this if your JSON config was edited and you + * want to reload from disk. + * + * @throws RuntimeException If there is an exception while reading the file. + */ + public void refresh() { + this.root = parseFile(); + } + + /** + * If this key exists in the current JSON data. + * + * @param key The String key + * @return True if this JSON has the given key. False otherwise. + */ + public boolean hasKey(String key) { + return root.get(key) != null; + } + + /** + * Gives this reader's {@link GsonBuilder} object so that you may configure type adapters and other settings. + */ + public GsonBuilder getBuilder() { + return builder; + } + + /** + * Reads from the {@link JsonObject} linked to the {@link String key} and returns a List of all the elements + * contained in its array. + * + * @return A list of the generic type of this class containing the deserialized elements from the passed key. + */ + @SuppressWarnings("unchecked") + public List getElements(String key) { + if (!hasKey(key)) { + return Lists.newArrayList(); + } + + Gson gson = builder.create(); + JsonArray elements = root.get(key).getAsJsonArray(); + List list = new ArrayList(); + for (int i = 0; i < elements.size(); i++) { + if (type == null) { + list.add((T) gson.fromJson(elements.get(i), typeToken.getType())); + } else { + list.add(gson.fromJson(elements.get(i), type)); + } + } + return list; + } + + /** + * Reads the default (defined by {@value #DEFAULT_KEY}) cached JsonObject in this class and returns a List of all + * the elements contained in its array. + *

+ * {@link #getElements(String)} should be used if your config has multiple keys. + * + * @return A list of the generic type of this class containing the deserialized elements from your JSON config's + * default key. + */ + public List getElements() { + return getElements(DEFAULT_KEY); + } + + @Override + public Iterator iterator() { + return getElements().iterator(); + } } diff --git a/src/main/java/com/enderio/core/common/config/PacketConfigSync.java b/src/main/java/com/enderio/core/common/config/PacketConfigSync.java index b41f62b..246fb46 100644 --- a/src/main/java/com/enderio/core/common/config/PacketConfigSync.java +++ b/src/main/java/com/enderio/core/common/config/PacketConfigSync.java @@ -1,9 +1,5 @@ package com.enderio.core.common.config; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import io.netty.buffer.ByteBuf; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -15,80 +11,82 @@ import java.util.zip.GZIPOutputStream; import com.google.common.base.Throwables; +import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; +import cpw.mods.fml.relauncher.Side; +import io.netty.buffer.ByteBuf; public class PacketConfigSync implements IMessage { - public PacketConfigSync() { - } + public PacketConfigSync() {} - private Map configValues; - private String modid; + private Map configValues; + private String modid; - public PacketConfigSync(ConfigProcessor toSync) { - this.configValues = toSync.configValues; - this.modid = toSync.modid; - } - - @Override - public void toBytes(ByteBuf buf) { - ByteArrayOutputStream obj = new ByteArrayOutputStream(); - - try { - GZIPOutputStream gzip = new GZIPOutputStream(obj); - ObjectOutputStream objStream = new ObjectOutputStream(gzip); - objStream.writeObject(configValues); - objStream.close(); - } catch (IOException e) { - Throwables.propagate(e); + public PacketConfigSync(ConfigProcessor toSync) { + this.configValues = toSync.configValues; + this.modid = toSync.modid; } - buf.writeShort(obj.size()); - buf.writeBytes(obj.toByteArray()); - - ByteBufUtils.writeUTF8String(buf, modid); - } - - /** - * Pa4ok - * you can trick forge network system & send client packet to server - * and then use different hacks with serialization of untrusted data - */ - @SuppressWarnings("unchecked") - @Override - public void fromBytes(ByteBuf buf) { - if(FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { - return; - } - - short len = buf.readShort(); - byte[] compressedBody = new byte[len]; - - for (short i = 0; i < len; i++) - compressedBody[i] = buf.readByte(); - - try { - ObjectInputStream obj = new ObjectInputStream(new GZIPInputStream(new ByteArrayInputStream(compressedBody))); - configValues = (Map) obj.readObject(); - obj.close(); - } catch (Exception e) { - Throwables.propagate(e); - } - - modid = ByteBufUtils.readUTF8String(buf); - } - - public static class Handler implements IMessageHandler { @Override - public PacketConfigSync onMessage(PacketConfigSync message, MessageContext ctx) { - ConfigProcessor processor = ConfigProcessor.processorMap.get(message.modid); - if (processor != null) { - processor.syncTo(message.configValues); - } - return null; + public void toBytes(ByteBuf buf) { + ByteArrayOutputStream obj = new ByteArrayOutputStream(); + + try { + GZIPOutputStream gzip = new GZIPOutputStream(obj); + ObjectOutputStream objStream = new ObjectOutputStream(gzip); + objStream.writeObject(configValues); + objStream.close(); + } catch (IOException e) { + Throwables.propagate(e); + } + + buf.writeShort(obj.size()); + buf.writeBytes(obj.toByteArray()); + + ByteBufUtils.writeUTF8String(buf, modid); + } + + /** + * Pa4ok you can trick forge network system & send client packet to server and then use different hacks with + * serialization of untrusted data + */ + @SuppressWarnings("unchecked") + @Override + public void fromBytes(ByteBuf buf) { + if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { + return; + } + + short len = buf.readShort(); + byte[] compressedBody = new byte[len]; + + for (short i = 0; i < len; i++) compressedBody[i] = buf.readByte(); + + try { + ObjectInputStream obj = new ObjectInputStream( + new GZIPInputStream(new ByteArrayInputStream(compressedBody))); + configValues = (Map) obj.readObject(); + obj.close(); + } catch (Exception e) { + Throwables.propagate(e); + } + + modid = ByteBufUtils.readUTF8String(buf); + } + + public static class Handler implements IMessageHandler { + + @Override + public PacketConfigSync onMessage(PacketConfigSync message, MessageContext ctx) { + ConfigProcessor processor = ConfigProcessor.processorMap.get(message.modid); + if (processor != null) { + processor.syncTo(message.configValues); + } + return null; + } } - } } 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 1331104..3a1001b 100644 --- a/src/main/java/com/enderio/core/common/config/TypeAdapterBase.java +++ b/src/main/java/com/enderio/core/common/config/TypeAdapterBase.java @@ -15,54 +15,56 @@ import com.google.common.reflect.TypeToken; @SuppressWarnings({ "serial", "unchecked" }) 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 type, Class primitiveType) { - this.actualType = actualType; - this.type = type; - this.primitiveType = primitiveType; - } + private final TypeToken actualType; + private final Property.Type type; + private final Class primitiveType; - public TypeAdapterBase(TypeToken actualType, Property.Type baseType) { - this(actualType, baseType, null); - } - - @Override - public TypeToken getActualType() { - return actualType; - } - - @Override - public Property.Type getType() { - return type; - } - - @Override - public Class getPrimitiveType() { - return primitiveType; - } - - public static final class TypeAdapterSame extends TypeAdapterBase { - public TypeAdapterSame(TypeToken actual, Property.Type base) { - super(actual, base); + public TypeAdapterBase(TypeToken actualType, Property.Type type, Class primitiveType) { + this.actualType = actualType; + this.type = type; + this.primitiveType = primitiveType; } - public TypeAdapterSame(TypeToken actual, Property.Type base, Class primitiveType) { - super(actual, base, primitiveType); + public TypeAdapterBase(TypeToken actualType, Property.Type baseType) { + this(actualType, baseType, null); } @Override - public TYPE createActualType(TYPE base) { - return base; + public TypeToken getActualType() { + return actualType; } @Override - public TYPE createBaseType(TYPE actual) { - return actual; + public Property.Type getType() { + return type; + } + + @Override + public Class getPrimitiveType() { + return primitiveType; + } + + 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; + } } - } // @formatter:off public static final TypeAdapterSame INTEGER = new TypeAdapterSame(TypeToken.of(Integer.class), Type.INTEGER, int.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 ead370e..659e494 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,16 +7,15 @@ 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 ""; + + /** + * 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 a4f28ae..54d388a 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 @@ -6,24 +6,25 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.enderio.core.common.config.ConfigProcessor; - import net.minecraftforge.common.config.Configuration; +import com.enderio.core.common.config.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} + * 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; + + /** + * 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 9557ccf..42501ae 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,12 +7,10 @@ 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 - * with {@link Config}. + * 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) 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 735c667..b2b5b98 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,33 +7,30 @@ 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 { - /** - * 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 02f376e..94534e2 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 - * effect is this field is not also annotated with {@link Config}. + * 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; + + /** + * 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 a4bde07..b48d0c9 100644 --- a/src/main/java/com/enderio/core/common/enchant/EnchantAutoSmelt.java +++ b/src/main/java/com/enderio/core/common/enchant/EnchantAutoSmelt.java @@ -1,69 +1,72 @@ package com.enderio.core.common.enchant; -import com.enderio.core.EnderCore; -import com.enderio.core.api.common.enchant.IAdvancedEnchant; -import com.enderio.core.common.config.ConfigHandler; - -import cpw.mods.fml.common.event.FMLInterModComms; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; +import com.enderio.core.EnderCore; +import com.enderio.core.api.common.enchant.IAdvancedEnchant; +import com.enderio.core.common.config.ConfigHandler; +import cpw.mods.fml.common.event.FMLInterModComms; + 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); - } + public static final EnchantAutoSmelt INSTANCE = new EnchantAutoSmelt(ConfigHandler.enchantIDAutoSmelt); - @Override - public int getMaxEnchantability(int level) { - return super.getMaxEnchantability(level) + 30; - } - - @Override - public int getMinEnchantability(int level) { - return super.getMinEnchantability(level); - } - - @Override - public int getMaxLevel() { - return 1; - } - - @Override - public boolean canApply(ItemStack stack) { - return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor); - } - - @Override - public String getName() { - return "enchantment.autosmelt"; - } - - @Override - public boolean isAllowedOnBooks() { - return ConfigHandler.allowAutoSmelt; - } - - @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; + private EnchantAutoSmelt(int id) { + super(id, 2, EnumEnchantmentType.breakable); } - } - public boolean canApplyTogether(Enchantment ench) { - return super.canApplyTogether(ench) && ench.effectId != silkTouch.effectId - && ((ench.effectId != fortune.effectId) || ConfigHandler.allowAutoSmeltWithFortune); - } + @Override + public int getMaxEnchantability(int level) { + return super.getMaxEnchantability(level) + 30; + } + + @Override + public int getMinEnchantability(int level) { + return super.getMinEnchantability(level); + } + + @Override + public int getMaxLevel() { + return 1; + } + + @Override + public boolean canApply(ItemStack stack) { + return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor); + } + + @Override + public String getName() { + return "enchantment.autosmelt"; + } + + @Override + public boolean isAllowedOnBooks() { + return ConfigHandler.allowAutoSmelt; + } + + @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 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 0e7dcbb..2fe471a 100644 --- a/src/main/java/com/enderio/core/common/enchant/EnchantXPBoost.java +++ b/src/main/java/com/enderio/core/common/enchant/EnchantXPBoost.java @@ -1,63 +1,66 @@ package com.enderio.core.common.enchant; -import com.enderio.core.EnderCore; -import com.enderio.core.api.common.enchant.IAdvancedEnchant; -import com.enderio.core.common.config.ConfigHandler; - import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; + +import com.enderio.core.EnderCore; +import com.enderio.core.api.common.enchant.IAdvancedEnchant; +import com.enderio.core.common.config.ConfigHandler; import cpw.mods.fml.common.event.FMLInterModComms; 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); - } + public static final EnchantXPBoost INSTANCE = new EnchantXPBoost(ConfigHandler.enchantIDXPBoost); - @Override - public int getMaxEnchantability(int level) { - return super.getMaxEnchantability(level) + 30; - } - - @Override - public int getMinEnchantability(int level) { - return super.getMinEnchantability(level); - } - - @Override - public int getMaxLevel() { - return 3; - } - - @Override - public boolean canApply(ItemStack stack) { - return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor); - } - - @Override - public String getName() { - return "enchantment.xpboost"; - } - - @Override - public boolean isAllowedOnBooks() { - return ConfigHandler.allowXPBoost; - } - - @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; + private EnchantXPBoost(int id) { + super(id, 2, EnumEnchantmentType.breakable); + } + + @Override + public int getMaxEnchantability(int level) { + return super.getMaxEnchantability(level) + 30; + } + + @Override + public int getMinEnchantability(int level) { + return super.getMinEnchantability(level); + } + + @Override + public int getMaxLevel() { + return 3; + } + + @Override + public boolean canApply(ItemStack stack) { + return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor); + } + + @Override + public String getName() { + return "enchantment.xpboost"; + } + + @Override + public boolean isAllowedOnBooks() { + return ConfigHandler.allowXPBoost; + } + + @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; + } } - } } 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 9c98531..503ced3 100644 --- a/src/main/java/com/enderio/core/common/event/ArrowUpdateEvent.java +++ b/src/main/java/com/enderio/core/common/event/ArrowUpdateEvent.java @@ -3,6 +3,7 @@ package com.enderio.core.common.event; import net.minecraft.entity.Entity; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityEvent; + import cpw.mods.fml.common.eventhandler.Cancelable; /** @@ -16,7 +17,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 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 2b52b6a..6cd545f 100644 --- a/src/main/java/com/enderio/core/common/event/ConfigFileChangedEvent.java +++ b/src/main/java/com/enderio/core/common/event/ConfigFileChangedEvent.java @@ -3,33 +3,31 @@ package com.enderio.core.common.event; import cpw.mods.fml.client.event.ConfigChangedEvent; /** - * This event is posted to the FML bus when the /reloadConfigs command is run, - * and should be used to reload your config file and parse its contents. + * This event is posted to the FML bus when the /reloadConfigs command is run, and should be used to reload your config + * file and parse its contents. *

- * This differs from the existing events because you should call config.load() - * before re-parsing the contents, to reload the file from disk. + * This differs from the existing events because you should call config.load() before re-parsing the contents, to reload + * the file from disk. *

- * This event will be sent once to all mods on load to determine if they are - * valid candidates for receiving the event. + * This event will be sent once to all mods on load to determine if they are valid candidates for receiving the event. *

- * Note that requiresMcRestart is always false, so this might not work 100% of - * the time + * Note that requiresMcRestart is always false, so this might not work 100% of the time *

- * If setSuccessful() is not called, the event post will be - * considered a failure! + * If setSuccessful() is not called, the event post will be considered a failure! */ public class ConfigFileChangedEvent extends ConfigChangedEvent { - private boolean successful; - public ConfigFileChangedEvent(String modID) { - super(modID, "null", true, false); - } - - public boolean isSuccessful() { - return this.successful; - } + private boolean successful; - public void setSuccessful() { - this.successful = true; - } + public ConfigFileChangedEvent(String modID) { + super(modID, "null", true, false); + } + + public boolean isSuccessful() { + return this.successful; + } + + 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 e12ed68..060a81e 100644 --- a/src/main/java/com/enderio/core/common/event/ItemStackEvent.java +++ b/src/main/java/com/enderio/core/common/event/ItemStackEvent.java @@ -3,62 +3,63 @@ package com.enderio.core.common.event; import net.minecraft.item.EnumRarity; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; + import cpw.mods.fml.common.eventhandler.Cancelable; import cpw.mods.fml.common.eventhandler.Event; /** * ItemEvent is fired when an event involving any ItemStack occurs.
- * If a method utilizes this {@link Event} as its parameter, the method will - * receive every child event of this class.
+ * If a method utilizes this {@link Event} as its parameter, the method will receive every child event of this + * class.
*
* {@link #item} contains the ItemStack that caused this event to occur.
*
* All children of this event are fired on the {@link MinecraftForge#EVENT_BUS}.
**/ public class ItemStackEvent extends Event { - public final ItemStack item; - public ItemStackEvent(ItemStack item) { - this.item = item; - } + 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; - - public ItemEnchantabilityEvent(ItemStack itemStack, int baseEnchantability) { - super(itemStack); - enchantability = baseEnchantability; + public ItemStackEvent(ItemStack item) { + this.item = item; } - } - /** - * 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; + /** + * 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 ItemRarityEvent(ItemStack itemStack, EnumRarity baseRarity) { - super(itemStack); - rarity = baseRarity; + public int enchantability; + + 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; + + public ItemRarityEvent(ItemStack itemStack, EnumRarity baseRarity) { + super(itemStack); + rarity = baseRarity; + } } - } } diff --git a/src/main/java/com/enderio/core/common/handlers/AutoSmeltHandler.java b/src/main/java/com/enderio/core/common/handlers/AutoSmeltHandler.java index e64cb44..694fa82 100644 --- a/src/main/java/com/enderio/core/common/handlers/AutoSmeltHandler.java +++ b/src/main/java/com/enderio/core/common/handlers/AutoSmeltHandler.java @@ -13,77 +13,78 @@ import net.minecraftforge.event.world.BlockEvent; import com.enderio.core.common.Handlers.Handler; import com.enderio.core.common.config.ConfigHandler; import com.enderio.core.common.enchant.EnchantAutoSmelt; - import cpw.mods.fml.common.eventhandler.SubscribeEvent; @Handler public class AutoSmeltHandler { - @SubscribeEvent - public void handleBlockBreak(BlockEvent.HarvestDropsEvent event) { - if (!event.world.isRemote && event.harvester != null) { - ItemStack held = event.harvester.getCurrentEquippedItem(); - if (held != null) { - int level = getAutoSmeltLevel(held); - int fortune = EnchantmentHelper.getEnchantmentLevel(Enchantment.fortune.effectId, held); + @SubscribeEvent + public void handleBlockBreak(BlockEvent.HarvestDropsEvent event) { + if (!event.world.isRemote && event.harvester != null) { + ItemStack held = event.harvester.getCurrentEquippedItem(); + if (held != null) { + int level = getAutoSmeltLevel(held); + int fortune = EnchantmentHelper.getEnchantmentLevel(Enchantment.fortune.effectId, held); - if (level >= 0) { - for (int i = 0; i < event.drops.size(); i++) { - { - ItemStack stack = event.drops.get(i); - if (stack != null && !event.isSilkTouching) { - if (FurnaceRecipes.smelting().getSmeltingResult(stack) != null) { - ItemStack furnaceStack = FurnaceRecipes.smelting().getSmeltingResult(stack).copy(); - //Fortune stuffs - if (fortune > 0 && ConfigHandler.allowAutoSmeltWithFortune) - furnaceStack.stackSize *= (event.world.rand.nextInt(fortune + 1) + 1); + if (level >= 0) { + for (int i = 0; i < event.drops.size(); i++) { + { + ItemStack stack = event.drops.get(i); + if (stack != null && !event.isSilkTouching) { + if (FurnaceRecipes.smelting().getSmeltingResult(stack) != null) { + ItemStack furnaceStack = FurnaceRecipes.smelting().getSmeltingResult(stack).copy(); + // Fortune stuffs + if (fortune > 0 && ConfigHandler.allowAutoSmeltWithFortune) + furnaceStack.stackSize *= (event.world.rand.nextInt(fortune + 1) + 1); - event.drops.set(i, furnaceStack); + event.drops.set(i, furnaceStack); - //XP (adapted vanilla code) - int xp = furnaceStack.stackSize; - float f = FurnaceRecipes.smelting().func_151398_b(furnaceStack); - int j; + // XP (adapted vanilla code) + int xp = furnaceStack.stackSize; + float f = FurnaceRecipes.smelting().func_151398_b(furnaceStack); + int j; - if (f == 0.0F) { - xp = 0; - } else if (f < 1.0F) { - j = MathHelper.floor_float((float) xp * f); + if (f == 0.0F) { + xp = 0; + } else if (f < 1.0F) { + j = MathHelper.floor_float((float) xp * f); - if (j < MathHelper.ceiling_float_int((float) xp * f) && (float) Math.random() < (float) xp * f - (float) j) { - ++j; + if (j < MathHelper.ceiling_float_int((float) xp * f) + && (float) Math.random() < (float) xp * f - (float) j) { + ++j; + } + + xp = j; + } + + while (xp > 0) { + j = EntityXPOrb.getXPSplit(xp); + xp -= j; + event.world.spawnEntityInWorld( + new EntityXPOrb(event.world, event.x, event.y + 0.5, event.z, j)); + } + } + } + } } - - xp = j; - } - - while (xp > 0) { - j = EntityXPOrb.getXPSplit(xp); - xp -= j; - event.world.spawnEntityInWorld(new EntityXPOrb(event.world, event.x, event.y + 0.5, event.z, j)); - } } - } } - } } - } - } - } - - @SuppressWarnings("unchecked") - private int getAutoSmeltLevel(ItemStack tool) { - if (tool == null) { - return -1; } - Map enchants = EnchantmentHelper.getEnchantments(tool); - for (int i : enchants.keySet()) { - Enchantment enchant = Enchantment.enchantmentsList[i]; - if (enchant == EnchantAutoSmelt.INSTANCE) { - return enchants.get(i); - } + @SuppressWarnings("unchecked") + private int getAutoSmeltLevel(ItemStack tool) { + if (tool == null) { + return -1; + } + + Map enchants = EnchantmentHelper.getEnchantments(tool); + for (int i : enchants.keySet()) { + Enchantment enchant = Enchantment.enchantmentsList[i]; + if (enchant == EnchantAutoSmelt.INSTANCE) { + return enchants.get(i); + } + } + return -1; } - return -1; - } } 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 4a0529a..d8991ed 100644 --- a/src/main/java/com/enderio/core/common/handlers/FireworkHandler.java +++ b/src/main/java/com/enderio/core/common/handlers/FireworkHandler.java @@ -1,5 +1,7 @@ package com.enderio.core.common.handlers; +import static java.util.Calendar.*; + import java.util.Calendar; import net.minecraft.entity.player.EntityPlayer; @@ -20,55 +22,61 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; 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); - } - } - @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 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); } - } - - 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); - } - } } - } - private BlockCoord getBlockCoord(EntityPlayer player) { - return new BlockCoord((int) Math.floor(player.posX), (int) Math.floor(player.posY), (int) Math.floor(player.posZ)); - } + @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"))); + } + } + + 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); + } + } + } + } + + 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 827f374..d68a87c 100644 --- a/src/main/java/com/enderio/core/common/handlers/RightClickCropHandler.java +++ b/src/main/java/com/enderio/core/common/handlers/RightClickCropHandler.java @@ -19,79 +19,81 @@ import cpw.mods.fml.common.registry.GameRegistry; @Handler public class RightClickCropHandler { - 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; - - public PlantInfo() { - } + public static class PlantInfo { - public PlantInfo(String seed, String block, int meta, int resetMeta) { - this.seed = seed; - this.block = block; - this.meta = meta; - this.resetMeta = resetMeta; - } + public String seed; + public String block; + public int meta = 7; + public int resetMeta = 0; - public void init() { - seedStack = ItemUtil.parseStringIntoItemStack(seed); - String[] blockinfo = block.split(":"); - blockInst = GameRegistry.findBlock(blockinfo[0], blockinfo[1]); - } - } + private transient ItemStack seedStack; + private transient Block blockInst; - private List plants = Lists.newArrayList(); + public PlantInfo() {} - 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 PlantInfo(String seed, String block, int meta, int resetMeta) { + this.seed = seed; + this.block = block; + this.meta = meta; + this.resetMeta = resetMeta; } - } - } - } - @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; + 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; + } + } } - } } - } } 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 00bfd91..23fb8fd 100644 --- a/src/main/java/com/enderio/core/common/handlers/XPBoostHandler.java +++ b/src/main/java/com/enderio/core/common/handlers/XPBoostHandler.java @@ -27,107 +27,120 @@ 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"; + 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())); + } } - } - } - } - - private int getXPBoost(EntityLivingBase killed, EntityPlayer player) { - return getXPBoost(killed, player, getXPBoostLevel(player.getCurrentEquippedItem())); - } - - private int getXPBoost(EntityLivingBase killed, EntityPlayer player, int level) { - if (level >= 0) { - try { - int xp = (Integer) getExperiencePoints.invoke(killed, player); - return getXPBoost(xp, level); - } catch (Exception e) { - Throwables.propagate(e); - } - } - 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; - } + @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); - 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; + 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))); + } + } + } } - Scheduler.instance().schedule(20, new Runnable() { - @Override - public void run() { - world.spawnEntityInWorld(new EntityXPOrb(world, x, y, z, boost)); - } - }); - } + private int getXPBoost(EntityLivingBase killed, EntityPlayer player) { + return getXPBoost(killed, player, getXPBoostLevel(player.getCurrentEquippedItem())); + } + + private int getXPBoost(EntityLivingBase killed, EntityPlayer player, int level) { + if (level >= 0) { + try { + int xp = (Integer) getExperiencePoints.invoke(killed, player); + return getXPBoost(xp, level); + } catch (Exception e) { + Throwables.propagate(e); + } + } + 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)); + } + }); + } } 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 a72fd1c..fb74924 100644 --- a/src/main/java/com/enderio/core/common/imc/IMCRegistry.java +++ b/src/main/java/com/enderio/core/common/imc/IMCRegistry.java @@ -9,47 +9,49 @@ import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; public class IMCRegistry { - public interface IIMC { - String getKey(); - void act(IMCMessage msg); - } + public interface IIMC { - public static abstract class IMCBase implements IIMC { - private String key; + String getKey(); - public IMCBase(String key) { - this.key = key; + void act(IMCMessage msg); } - @Override - public String getKey() { - return key; - } - } + public static abstract class IMCBase implements IIMC { - public static final IMCRegistry INSTANCE = new IMCRegistry(); + private String key; - 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 IMCBase(String key) { + this.key = key; } - } - } - } - public void init() { - addIMCHandler(new IMCRightClickCrop()); - } + @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()); + } } 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 8b7be53..3b03384 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 @@ -4,28 +4,28 @@ import com.enderio.core.api.common.imc.IMC; import com.enderio.core.common.handlers.RightClickCropHandler; import com.enderio.core.common.handlers.RightClickCropHandler.PlantInfo; 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); - } - @Override - public void act(IMCMessage msg) { - if (!msg.isStringMessage()) { - return; + public IMCRightClickCrop() { + super(IMC.ADD_RIGHT_CLICK_CROP); } - String[] data = msg.getStringValue().split("\\|"); + @Override + public void act(IMCMessage msg) { + if (!msg.isStringMessage()) { + return; + } - if (data.length != 3) { - return; + 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); } - - 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/interfaces/IComparatorOutput.java b/src/main/java/com/enderio/core/common/interfaces/IComparatorOutput.java index b993a5c..8057838 100644 --- a/src/main/java/com/enderio/core/common/interfaces/IComparatorOutput.java +++ b/src/main/java/com/enderio/core/common/interfaces/IComparatorOutput.java @@ -2,5 +2,5 @@ package com.enderio.core.common.interfaces; public interface IComparatorOutput { - int getComparatorOutput(); + int getComparatorOutput(); } 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 34d8f10..a4bd79b 100644 --- a/src/main/java/com/enderio/core/common/network/CompressedDataInput.java +++ b/src/main/java/com/enderio/core/common/network/CompressedDataInput.java @@ -9,22 +9,22 @@ import java.util.zip.InflaterInputStream; public class CompressedDataInput extends DataInputStream { - public CompressedDataInput(byte[] compressed) { - this(new ByteArrayInputStream(compressed)); - } + public CompressedDataInput(byte[] compressed) { + this(new ByteArrayInputStream(compressed)); + } - public CompressedDataInput(InputStream in) { - super(new BufferedInputStream(new InflaterInputStream(in))); - } + public CompressedDataInput(InputStream in) { + super(new BufferedInputStream(new InflaterInputStream(in))); + } - public int readVariable() throws IOException { - int b, res = 0; - int shift = 0; - do { - b = readUnsignedByte(); - res |= (b & 0x7F) << shift; - shift += 7; - } while (b >= 0x80); - return res; - } + public int readVariable() throws IOException { + int b, res = 0; + int shift = 0; + do { + b = readUnsignedByte(); + res |= (b & 0x7F) << shift; + shift += 7; + } 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 0cdb442..3448bd3 100644 --- a/src/main/java/com/enderio/core/common/network/CompressedDataOutput.java +++ b/src/main/java/com/enderio/core/common/network/CompressedDataOutput.java @@ -8,27 +8,27 @@ import java.util.zip.DeflaterOutputStream; public class CompressedDataOutput extends DataOutputStream { - final ByteArrayOutputStream baos; + final ByteArrayOutputStream baos; - public CompressedDataOutput() { - this(new ByteArrayOutputStream()); - } - - private CompressedDataOutput(ByteArrayOutputStream baos) { - super(new BufferedOutputStream(new DeflaterOutputStream(baos))); - this.baos = baos; - } - - public void writeVariable(int value) throws IOException { - while ((value & ~0x7F) != 0) { - writeByte(value | 0x80); - value >>= 7; + public CompressedDataOutput() { + this(new ByteArrayOutputStream()); } - writeByte(value); - } - public byte[] getCompressed() throws IOException { - close(); - return baos.toByteArray(); - } + private CompressedDataOutput(ByteArrayOutputStream baos) { + super(new BufferedOutputStream(new DeflaterOutputStream(baos))); + this.baos = baos; + } + + public void writeVariable(int value) throws IOException { + while ((value & ~0x7F) != 0) { + writeByte(value | 0x80); + value >>= 7; + } + writeByte(value); + } + + public byte[] getCompressed() throws IOException { + close(); + return baos.toByteArray(); + } } 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 4744e88..427c0bc 100644 --- a/src/main/java/com/enderio/core/common/network/EnderPacketHandler.java +++ b/src/main/java/com/enderio/core/common/network/EnderPacketHandler.java @@ -14,28 +14,30 @@ import cpw.mods.fml.relauncher.Side; public class EnderPacketHandler { - public static final SimpleNetworkWrapper INSTANCE = new SimpleNetworkWrapper(EnderCore.NAME); + public static final SimpleNetworkWrapper INSTANCE = new SimpleNetworkWrapper(EnderCore.NAME); - public static void init() { - INSTANCE.registerMessage(PacketConfigSync.Handler.class, PacketConfigSync.class, 0, Side.CLIENT); - INSTANCE.registerMessage(PacketProgress.Handler.class, PacketProgress.class, 1, Side.CLIENT); - INSTANCE.registerMessage(PacketNoSpamChat.Handler.class, PacketNoSpamChat.class, 2, Side.CLIENT); - INSTANCE.registerMessage(PacketGhostSlot.Handler.class, PacketGhostSlot.class, 3, Side.SERVER); - } + public static void init() { + INSTANCE.registerMessage(PacketConfigSync.Handler.class, PacketConfigSync.class, 0, Side.CLIENT); + INSTANCE.registerMessage(PacketProgress.Handler.class, PacketProgress.class, 1, Side.CLIENT); + INSTANCE.registerMessage(PacketNoSpamChat.Handler.class, PacketNoSpamChat.class, 2, Side.CLIENT); + INSTANCE.registerMessage(PacketGhostSlot.Handler.class, PacketGhostSlot.class, 3, Side.SERVER); + } - public static void sendToAllAround(IMessage message, TileEntity te, int range) { - INSTANCE.sendToAllAround(message, new TargetPoint(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, range)); - } + public static void sendToAllAround(IMessage message, TileEntity te, int range) { + INSTANCE.sendToAllAround( + message, + new TargetPoint(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, range)); + } - public static void sendToAllAround(IMessage message, TileEntity te) { - sendToAllAround(message, te, 64); - } + public static void sendToAllAround(IMessage message, TileEntity te) { + sendToAllAround(message, te, 64); + } - public static void sendTo(IMessage message, EntityPlayerMP player) { - INSTANCE.sendTo(message, player); - } + public static void sendTo(IMessage message, EntityPlayerMP player) { + INSTANCE.sendTo(message, player); + } - public static void sendToServer(IMessage message) { - INSTANCE.sendToServer(message); - } + public static void sendToServer(IMessage message) { + INSTANCE.sendToServer(message); + } } 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 75e72a5..65936a3 100644 --- a/src/main/java/com/enderio/core/common/network/MessageTileEntity.java +++ b/src/main/java/com/enderio/core/common/network/MessageTileEntity.java @@ -1,58 +1,58 @@ package com.enderio.core.common.network; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + import com.google.common.reflect.TypeToken; -import io.netty.buffer.ByteBuf; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.MessageContext; +import io.netty.buffer.ByteBuf; public abstract class MessageTileEntity implements IMessage { - protected int x; - protected int y; - protected int z; + protected int x; + protected int y; + protected int z; - protected MessageTileEntity() { - } + protected MessageTileEntity() {} - protected MessageTileEntity(T tile) { - x = tile.xCoord; - y = tile.yCoord; - z = tile.zCoord; - } - - public void toBytes(ByteBuf buf) { - buf.writeInt(x); - buf.writeInt(y); - buf.writeInt(z); - } - - @Override - public void fromBytes(ByteBuf buf) { - x = buf.readInt(); - y = buf.readInt(); - z = buf.readInt(); - } - - @SuppressWarnings("unchecked") - protected T getTileEntity(World worldObj) { - if (worldObj == null) { - return null; + protected MessageTileEntity(T tile) { + x = tile.xCoord; + y = tile.yCoord; + z = tile.zCoord; } - TileEntity te = worldObj.getTileEntity(x, y, z); - if (te == null) { - return null; - } - TypeToken teType = TypeToken.of(getClass()).resolveType(MessageTileEntity.class.getTypeParameters()[0]); - if (teType.isAssignableFrom(te.getClass())) { - return (T) te; - } - return null; - } - protected World getWorld(MessageContext ctx) { - return ctx.getServerHandler().playerEntity.worldObj; - } + public void toBytes(ByteBuf buf) { + buf.writeInt(x); + buf.writeInt(y); + buf.writeInt(z); + } + + @Override + public void fromBytes(ByteBuf buf) { + x = buf.readInt(); + y = buf.readInt(); + z = buf.readInt(); + } + + @SuppressWarnings("unchecked") + protected T getTileEntity(World worldObj) { + if (worldObj == null) { + return null; + } + TileEntity te = worldObj.getTileEntity(x, y, z); + if (te == null) { + return null; + } + TypeToken teType = TypeToken.of(getClass()).resolveType(MessageTileEntity.class.getTypeParameters()[0]); + if (teType.isAssignableFrom(te.getClass())) { + return (T) te; + } + return null; + } + + protected World getWorld(MessageContext ctx) { + 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 9500eb5..5042f89 100644 --- a/src/main/java/com/enderio/core/common/network/MessageTileNBT.java +++ b/src/main/java/com/enderio/core/common/network/MessageTileNBT.java @@ -1,6 +1,5 @@ package com.enderio.core.common.network; -import io.netty.buffer.ByteBuf; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; @@ -10,70 +9,71 @@ import com.enderio.core.common.util.Log; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; +import io.netty.buffer.ByteBuf; /** * Created by CrazyPants on 27/02/14. */ public class MessageTileNBT implements IMessage, IMessageHandler { - TileEntity te; + TileEntity te; - int x; - int y; - int z; - NBTTagCompound tags; + int x; + int y; + int z; + NBTTagCompound tags; - boolean renderOnUpdate = false; + boolean renderOnUpdate = false; - public MessageTileNBT() { + public MessageTileNBT() { - } - - public MessageTileNBT(TileEntity te) { - this.te = te; - x = te.xCoord; - y = te.yCoord; - z = te.zCoord; - tags = new NBTTagCompound(); - te.writeToNBT(tags); - } - - @Override - public void toBytes(ByteBuf buffer) { - buffer.writeInt(x); - buffer.writeInt(y); - buffer.writeInt(z); - NetworkUtil.writeNBTTagCompound(tags, buffer); - } - - @Override - public void fromBytes(ByteBuf dis) { - x = dis.readInt(); - y = dis.readInt(); - z = dis.readInt(); - tags = NetworkUtil.readNBTTagCompound(dis); - } - - @Override - public IMessage onMessage(MessageTileNBT msg, MessageContext ctx) { - te = handle(ctx.getServerHandler().playerEntity.worldObj); - if (te != null && renderOnUpdate) { - te.getWorldObj().markBlockForUpdate(x, y, z); } - return null; - } - private TileEntity handle(World world) { - if (world == null) { - Log.warn("PacketUtil.handleTileEntityPacket: TileEntity null world processing tile entity packet."); - return null; + public MessageTileNBT(TileEntity te) { + this.te = te; + x = te.xCoord; + y = te.yCoord; + z = te.zCoord; + tags = new NBTTagCompound(); + te.writeToNBT(tags); } - TileEntity te = world.getTileEntity(x, y, z); - if (te == null) { - Log.warn("PacketUtil.handleTileEntityPacket: TileEntity null when processing tile entity packet."); - return null; + + @Override + public void toBytes(ByteBuf buffer) { + buffer.writeInt(x); + buffer.writeInt(y); + buffer.writeInt(z); + NetworkUtil.writeNBTTagCompound(tags, buffer); + } + + @Override + public void fromBytes(ByteBuf dis) { + x = dis.readInt(); + y = dis.readInt(); + z = dis.readInt(); + tags = NetworkUtil.readNBTTagCompound(dis); + } + + @Override + public IMessage onMessage(MessageTileNBT msg, MessageContext ctx) { + te = handle(ctx.getServerHandler().playerEntity.worldObj); + if (te != null && renderOnUpdate) { + te.getWorldObj().markBlockForUpdate(x, y, z); + } + return null; + } + + private TileEntity handle(World world) { + if (world == null) { + Log.warn("PacketUtil.handleTileEntityPacket: TileEntity null world processing tile entity packet."); + return null; + } + TileEntity te = world.getTileEntity(x, y, z); + if (te == null) { + Log.warn("PacketUtil.handleTileEntityPacket: TileEntity null when processing tile entity packet."); + return null; + } + te.readFromNBT(tags); + return te; } - te.readFromNBT(tags); - return te; - } } diff --git a/src/main/java/com/enderio/core/common/network/NetworkUtil.java b/src/main/java/com/enderio/core/common/network/NetworkUtil.java index e3f5130..f4e548b 100644 --- a/src/main/java/com/enderio/core/common/network/NetworkUtil.java +++ b/src/main/java/com/enderio/core/common/network/NetworkUtil.java @@ -1,58 +1,58 @@ package com.enderio.core.common.network; -import io.netty.buffer.ByteBuf; - import java.io.IOException; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTSizeTracker; import net.minecraft.nbt.NBTTagCompound; + import cpw.mods.fml.common.FMLCommonHandler; +import io.netty.buffer.ByteBuf; /** * Created by CrazyPants on 27/02/14. */ public class NetworkUtil { - public static NBTTagCompound readNBTTagCompound(ByteBuf dataIn) { - try { - short size = dataIn.readShort(); - if (size < 0) { - return null; - } else { - byte[] buffer = new byte[size]; - dataIn.readBytes(buffer); - return CompressedStreamTools.func_152457_a(buffer, NBTSizeTracker.field_152451_a); - } - } catch (IOException e) { - FMLCommonHandler.instance().raiseException(e, "Custom Packet", true); - return null; + public static NBTTagCompound readNBTTagCompound(ByteBuf dataIn) { + try { + short size = dataIn.readShort(); + if (size < 0) { + return null; + } else { + byte[] buffer = new byte[size]; + dataIn.readBytes(buffer); + return CompressedStreamTools.func_152457_a(buffer, NBTSizeTracker.field_152451_a); + } + } catch (IOException e) { + FMLCommonHandler.instance().raiseException(e, "Custom Packet", true); + return null; + } } - } - public static void writeNBTTagCompound(NBTTagCompound compound, ByteBuf dataout) { - try { - if (compound == null) { - dataout.writeShort(-1); - } else { - byte[] buf = CompressedStreamTools.compress(compound); - dataout.writeShort((short) buf.length); - dataout.writeBytes(buf); - } - } catch (IOException e) { - FMLCommonHandler.instance().raiseException(e, "PacketUtil.readTileEntityPacket.writeNBTTagCompound", true); + public static void writeNBTTagCompound(NBTTagCompound compound, ByteBuf dataout) { + try { + if (compound == null) { + dataout.writeShort(-1); + } else { + byte[] buf = CompressedStreamTools.compress(compound); + dataout.writeShort((short) buf.length); + dataout.writeBytes(buf); + } + } catch (IOException e) { + FMLCommonHandler.instance().raiseException(e, "PacketUtil.readTileEntityPacket.writeNBTTagCompound", true); + } } - } - public static byte[] readByteArray(ByteBuf buf) { - int size = buf.readMedium(); - byte[] res = new byte[size]; - buf.readBytes(res); - return res; - } + public static byte[] readByteArray(ByteBuf buf) { + int size = buf.readMedium(); + byte[] res = new byte[size]; + buf.readBytes(res); + return res; + } - public static void writeByteArray(ByteBuf buf, byte[] arr) { - buf.writeMedium(arr.length); - buf.writeBytes(arr); - } + public static void writeByteArray(ByteBuf buf, byte[] arr) { + buf.writeMedium(arr.length); + buf.writeBytes(arr); + } } diff --git a/src/main/java/com/enderio/core/common/network/PacketGhostSlot.java b/src/main/java/com/enderio/core/common/network/PacketGhostSlot.java index fd1dc10..7f4cc03 100644 --- a/src/main/java/com/enderio/core/common/network/PacketGhostSlot.java +++ b/src/main/java/com/enderio/core/common/network/PacketGhostSlot.java @@ -1,63 +1,58 @@ package com.enderio.core.common.network; -import io.netty.buffer.ByteBuf; import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import com.enderio.core.EnderCore; -import com.enderio.core.api.common.util.IProgressTile; import com.enderio.core.common.TileEntityEnder; -import com.enderio.core.common.network.MessageTileEntity; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; +import io.netty.buffer.ByteBuf; public class PacketGhostSlot extends MessageTileEntity { - private int slot; - private ItemStack stack; + private int slot; + private ItemStack stack; - public PacketGhostSlot() { - } + public PacketGhostSlot() {} - private PacketGhostSlot(TileEntityEnder tile) { - super(tile); - } + private PacketGhostSlot(TileEntityEnder tile) { + super(tile); + } - public static PacketGhostSlot setGhostSlotContents(TileEntityEnder te, int slot, ItemStack stack) { - PacketGhostSlot msg = new PacketGhostSlot(te); - msg.slot = slot; - msg.stack = stack; - return msg; - } - - @Override - public void fromBytes(ByteBuf buf) { - super.fromBytes(buf); - slot = buf.readShort(); - stack = ByteBufUtils.readItemStack(buf); - } - - @Override - public void toBytes(ByteBuf buf) { - super.toBytes(buf); - buf.writeShort(slot); - ByteBufUtils.writeItemStack(buf, stack); - } - - public static class Handler implements IMessageHandler { + public static PacketGhostSlot setGhostSlotContents(TileEntityEnder te, int slot, ItemStack stack) { + PacketGhostSlot msg = new PacketGhostSlot(te); + msg.slot = slot; + msg.stack = stack; + return msg; + } @Override - public IMessage onMessage(PacketGhostSlot msg, MessageContext ctx) { - TileEntityEnder te = msg.getTileEntity(ctx.getServerHandler().playerEntity.worldObj); - if (te != null) { - te.setGhostSlotContents(msg.slot, msg.stack); - te.getWorldObj().markBlockForUpdate(msg.x, msg.y, msg.z); - } - return null; + public void fromBytes(ByteBuf buf) { + super.fromBytes(buf); + slot = buf.readShort(); + stack = ByteBufUtils.readItemStack(buf); + } + + @Override + public void toBytes(ByteBuf buf) { + super.toBytes(buf); + buf.writeShort(slot); + ByteBufUtils.writeItemStack(buf, stack); + } + + public static class Handler implements IMessageHandler { + + @Override + public IMessage onMessage(PacketGhostSlot msg, MessageContext ctx) { + TileEntityEnder te = msg.getTileEntity(ctx.getServerHandler().playerEntity.worldObj); + if (te != null) { + te.setGhostSlotContents(msg.slot, msg.stack); + te.getWorldObj().markBlockForUpdate(msg.x, msg.y, msg.z); + } + return null; + } } - } } diff --git a/src/main/java/com/enderio/core/common/network/PacketProgress.java b/src/main/java/com/enderio/core/common/network/PacketProgress.java index bd45945..6106485 100644 --- a/src/main/java/com/enderio/core/common/network/PacketProgress.java +++ b/src/main/java/com/enderio/core/common/network/PacketProgress.java @@ -1,6 +1,5 @@ package com.enderio.core.common.network; -import io.netty.buffer.ByteBuf; import net.minecraft.tileentity.TileEntity; import com.enderio.core.EnderCore; @@ -9,43 +8,43 @@ import com.enderio.core.api.common.util.IProgressTile; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; +import io.netty.buffer.ByteBuf; public class PacketProgress extends MessageTileEntity { - private float progress; + private float progress; - public PacketProgress() { - } + public PacketProgress() {} - public PacketProgress(IProgressTile tile) { - super(tile.getTileEntity()); - progress = tile.getProgress(); - if (progress == 0) { - progress = -1; + public PacketProgress(IProgressTile tile) { + super(tile.getTileEntity()); + progress = tile.getProgress(); + if (progress == 0) { + progress = -1; + } } - } - - @Override - public void toBytes(ByteBuf buf) { - super.toBytes(buf); - buf.writeFloat(progress); - } - - @Override - public void fromBytes(ByteBuf buf) { - super.fromBytes(buf); - progress = buf.readFloat(); - } - - public static class Handler implements IMessageHandler { @Override - public IMessage onMessage(PacketProgress message, MessageContext ctx) { - TileEntity tile = message.getTileEntity(EnderCore.proxy.getClientWorld()); - if (tile instanceof IProgressTile) { - ((IProgressTile) tile).setProgress(message.progress); - } - return null; + public void toBytes(ByteBuf buf) { + super.toBytes(buf); + buf.writeFloat(progress); + } + + @Override + public void fromBytes(ByteBuf buf) { + super.fromBytes(buf); + progress = buf.readFloat(); + } + + public static class Handler implements IMessageHandler { + + @Override + public IMessage onMessage(PacketProgress message, MessageContext ctx) { + TileEntity tile = message.getTileEntity(EnderCore.proxy.getClientWorld()); + if (tile instanceof IProgressTile) { + ((IProgressTile) tile).setProgress(message.progress); + } + return null; + } } - } } 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 53faff4..1bff08e 100644 --- a/src/main/java/com/enderio/core/common/transform/EnderCoreMethods.java +++ b/src/main/java/com/enderio/core/common/transform/EnderCoreMethods.java @@ -18,164 +18,166 @@ import com.enderio.core.common.event.ItemStackEvent.ItemEnchantabilityEvent; import com.enderio.core.common.event.ItemStackEvent.ItemRarityEvent; public class EnderCoreMethods { - public static 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 static int getMaxAnvilCost() { - return ConfigHandler.anvilMaxLevel; - } - - public static int getItemEnchantability(ItemStack stack, int base) { - ItemEnchantabilityEvent event = new ItemEnchantabilityEvent(stack, base); - MinecraftForge.EVENT_BUS.post(event); - return event.enchantability; - } - - public static EnumRarity getItemRarity(ItemStack stack) { - ItemRarityEvent event = new ItemRarityEvent(stack, stack.getItem().getRarity(stack)); - MinecraftForge.EVENT_BUS.post(event); - return event.rarity; - } - - public static void onArrowUpdate(EntityArrow entity) { - MinecraftForge.EVENT_BUS.post(new ArrowUpdateEvent(entity)); - } - - // mostly copied from ContainerFurnace - public static 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; + public static 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; } + } - 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)) { + public static int getMaxAnvilCost() { + return ConfigHandler.anvilMaxLevel; + } + + public static int getItemEnchantability(ItemStack stack, int base) { + ItemEnchantabilityEvent event = new ItemEnchantabilityEvent(stack, base); + MinecraftForge.EVENT_BUS.post(event); + return event.enchantability; + } + + public static EnumRarity getItemRarity(ItemStack stack) { + ItemRarityEvent event = new ItemRarityEvent(stack, stack.getItem().getRarity(stack)); + MinecraftForge.EVENT_BUS.post(event); + return event.rarity; + } + + public static void onArrowUpdate(EntityArrow entity) { + MinecraftForge.EVENT_BUS.post(new ArrowUpdateEvent(entity)); + } + + // mostly copied from ContainerFurnace + public static 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)) { 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; + + 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 (!mergeItemStack(inv, itemstack1, 3, 39, 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); + return itemstack; } - return itemstack; - } - - // copied from Container - private static 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_; - - 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; - } - } + // copied from Container + private static 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_; if (p_75135_4_) { - --k; - } else { - ++k; + 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; } - - 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 6fa24db..e65e221 100644 --- a/src/main/java/com/enderio/core/common/transform/EnderCorePlugin.java +++ b/src/main/java/com/enderio/core/common/transform/EnderCorePlugin.java @@ -10,30 +10,32 @@ import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; @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" }; - } + public static boolean runtimeDeobfEnabled = false; - @Override - public String getModContainerClass() { - return null; - } + @Override + public String[] getASMTransformerClass() { + return new String[] { "com.enderio.core.common.transform.EnderCoreTransformer", + "com.enderio.core.common.transform.EnderCoreTransformerClient" }; + } - @Override - public String getSetupClass() { - return null; - } + @Override + public String getModContainerClass() { + return null; + } - @Override - public void injectData(Map data) { - runtimeDeobfEnabled = (Boolean) data.get("runtimeDeobfuscationEnabled"); - } + @Override + public String getSetupClass() { + return null; + } - @Override - public String getAccessTransformerClass() { - return null; - } + @Override + public void injectData(Map data) { + runtimeDeobfEnabled = (Boolean) data.get("runtimeDeobfuscationEnabled"); + } + + @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 70831aa..2b887df 100644 --- a/src/main/java/com/enderio/core/common/transform/EnderCoreTransformer.java +++ b/src/main/java/com/enderio/core/common/transform/EnderCoreTransformer.java @@ -1,5 +1,7 @@ package com.enderio.core.common.transform; +import static org.objectweb.asm.Opcodes.*; + import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -18,240 +20,282 @@ import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; import com.enderio.core.EnderCore; - import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; -import static org.objectweb.asm.Opcodes.*; - @MCVersion(value = "1.7.10") public class EnderCoreTransformer implements IClassTransformer { - protected static class ObfSafeName { - private String deobf, srg; - public ObfSafeName(String deobf, String srg) { - this.deobf = deobf; - this.srg = srg; + protected static class ObfSafeName { + + private String deobf, srg; + + public ObfSafeName(String deobf, String srg) { + this.deobf = deobf; + this.srg = 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 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; - } + public byte[] transform(String name, String transformedName, byte[] basicClass) { + // Void fog removal + if (transformedName.equals(worldTypeClass)) { + basicClass = transform(basicClass, worldTypeClass, voidFogMethod, new Transform() { - // no hashcode because I'm naughty - } + @Override + void transform(Iterator methods) { + while (methods.hasNext()) { + MethodNode m = methods.next(); + if (voidFogMethod.equals(m.name)) { + m.localVariables.clear(); + m.instructions.clear(); - protected static abstract class Transform { - abstract void transform(Iterator methods); - } + 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)); - 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.localVariables.clear(); - 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)); + break; + } + } } - } - } - } + }); } - }); - } - // 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; - } + // 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)); + } + } + } + } } - } - - break; - } - } + }); } - }; + // 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() { - 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(); + @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; + } + } + } - 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; + } + } } - } - 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; - } - } + 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; } - return basicClass; - } + protected final byte[] transform(byte[] classBytes, String className, ObfSafeName methodName, + Transform transformer) { + EnderCore.logger.info("Transforming Class [" + className + "], Method [" + methodName.getName() + "]"); - 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); - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(classBytes); - classReader.accept(classNode, 0); + Iterator methods = classNode.methods.iterator(); - Iterator methods = classNode.methods.iterator(); + transformer.transform(methods); - transformer.transform(methods); - - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - classNode.accept(cw); - EnderCore.logger.info("Transforming " + className + " Finished."); - return cw.toByteArray(); - } + 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 593376a..af6fb6c 100644 --- a/src/main/java/com/enderio/core/common/transform/EnderCoreTransformerClient.java +++ b/src/main/java/com/enderio/core/common/transform/EnderCoreTransformerClient.java @@ -1,5 +1,7 @@ package com.enderio.core.common.transform; +import static org.objectweb.asm.Opcodes.*; + import java.util.Iterator; import org.objectweb.asm.Type; @@ -13,82 +15,97 @@ import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; 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"); - private static final String slotModListClass = "cpw.mods.fml.client.GuiSlotModList"; - private static final ObfSafeName drawBackground = new ObfSafeName("drawBackground", "drawBackground"); + private static final String scrollingListClass = "cpw.mods.fml.client.GuiScrollingList"; + private static final ObfSafeName drawScreen = new ObfSafeName("func_73863_a", "drawScreen"); - @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)); - - JumpInsnNode jmp = (JumpInsnNode) m.instructions.get(i); - - InsnList newInstructions = new InsnList(); - newInstructions.add(new VarInsnNode(ALOAD, 0)); - newInstructions.add(new MethodInsnNode(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;", false)); - newInstructions.add(new LdcInsnNode(Type.getObjectType("cpw/mods/fml/client/GuiSlotModList"))); - newInstructions.add(new JumpInsnNode(IF_ACMPNE, jmp.label)); - - m.instructions.remove(jmp); - - m.instructions.insert(insertPoint, newInstructions); - } + 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)); + + JumpInsnNode jmp = (JumpInsnNode) m.instructions.get(i); + + InsnList newInstructions = new InsnList(); + newInstructions.add(new VarInsnNode(ALOAD, 0)); + newInstructions.add( + new MethodInsnNode( + INVOKEVIRTUAL, + "java/lang/Object", + "getClass", + "()Ljava/lang/Class;", + false)); + newInstructions.add( + new LdcInsnNode( + Type.getObjectType("cpw/mods/fml/client/GuiSlotModList"))); + newInstructions.add(new JumpInsnNode(IF_ACMPNE, jmp.label)); + + m.instructions.remove(jmp); + + m.instructions.insert(insertPoint, newInstructions); + } + } + } + break; + } + } } - } - 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() { - 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)); + @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;"; - m.instructions.insert(list); - break; - } - } + 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; + } + } + } + }); } - }); + return basicClass; } - return basicClass; - } } diff --git a/src/main/java/com/enderio/core/common/tweaks/InfiniBow.java b/src/main/java/com/enderio/core/common/tweaks/InfiniBow.java index 8b3d349..ca10b28 100644 --- a/src/main/java/com/enderio/core/common/tweaks/InfiniBow.java +++ b/src/main/java/com/enderio/core/common/tweaks/InfiniBow.java @@ -7,30 +7,31 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.ArrowNockEvent; + import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public class InfiniBow extends Tweak { - public InfiniBow() { - super("infinibow", "Makes bows with Infinity enchant able to be fired with no arrows in the inventory."); - } - - @Override - public void load() { - MinecraftForge.EVENT_BUS.register(this); - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onArrowNock(ArrowNockEvent event) { - EntityPlayer player = event.entityPlayer; - ItemStack stack = player.getHeldItem(); - if (player.capabilities.isCreativeMode || player.inventory.hasItem(Items.arrow) - || EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0) { - player.setItemInUse(stack, stack.getItem().getMaxItemUseDuration(stack)); + public InfiniBow() { + super("infinibow", "Makes bows with Infinity enchant able to be fired with no arrows in the inventory."); } - event.result = stack; - event.setCanceled(true); - } + @Override + public void load() { + MinecraftForge.EVENT_BUS.register(this); + } + + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onArrowNock(ArrowNockEvent event) { + EntityPlayer player = event.entityPlayer; + ItemStack stack = player.getHeldItem(); + if (player.capabilities.isCreativeMode || player.inventory.hasItem(Items.arrow) + || EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0) { + player.setItemInUse(stack, stack.getItem().getMaxItemUseDuration(stack)); + } + + event.result = stack; + event.setCanceled(true); + } } 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 69c8421..2a41b76 100644 --- a/src/main/java/com/enderio/core/common/tweaks/SlabRecipes.java +++ b/src/main/java/com/enderio/core/common/tweaks/SlabRecipes.java @@ -4,33 +4,40 @@ import net.minecraft.block.Block; import net.minecraft.init.Blocks; 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 static final SlabRecipes INSTANCE = new SlabRecipes(); + 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 }; - SlabRecipes() { - super("slabToBlockRecipes", "Adds recipes to turn any two slabs back into a full block"); - } + public static final SlabRecipes INSTANCE = new SlabRecipes(); - @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 d547b10..0c870a0 100644 --- a/src/main/java/com/enderio/core/common/tweaks/Tweak.java +++ b/src/main/java/com/enderio/core/common/tweaks/Tweak.java @@ -3,23 +3,24 @@ package com.enderio.core.common.tweaks; import com.enderio.core.common.config.ConfigHandler; 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(); + private String name, comment; + + public Tweak(String key, String comment) { + this.name = key; + this.comment = comment; + if (ConfigHandler.instance().addBooleanFor(this)) { + load(); + } } - } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getComment() { - return comment; - } + public String getComment() { + return comment; + } - 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 a046e80..f4d5f99 100644 --- a/src/main/java/com/enderio/core/common/tweaks/Tweaks.java +++ b/src/main/java/com/enderio/core/common/tweaks/Tweaks.java @@ -7,15 +7,17 @@ import net.minecraft.block.Block; import net.minecraft.init.Blocks; 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 static void loadIngameTweaks() { + /** + * 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 tweaks.add(new Tweak("fixBedSound", "Makes the bed stepSound wool instead of stone") { @Override diff --git a/src/main/java/com/enderio/core/common/util/ArrayInventory.java b/src/main/java/com/enderio/core/common/util/ArrayInventory.java index 77060eb..c88d74f 100644 --- a/src/main/java/com/enderio/core/common/util/ArrayInventory.java +++ b/src/main/java/com/enderio/core/common/util/ArrayInventory.java @@ -6,79 +6,79 @@ import net.minecraft.item.ItemStack; public class ArrayInventory implements IInventory { - protected ItemStack[] items; + protected ItemStack[] items; - public ArrayInventory(ItemStack[] items) { - this.items = items; - } + public ArrayInventory(ItemStack[] items) { + this.items = items; + } - public ArrayInventory(int size) { - items = new ItemStack[size]; - } + public ArrayInventory(int size) { + items = new ItemStack[size]; + } - @Override - public int getSizeInventory() { - return items.length; - } + @Override + public int getSizeInventory() { + return items.length; + } - @Override - public ItemStack getStackInSlot(int slot) { - return items[slot]; - } + @Override + public ItemStack getStackInSlot(int slot) { + return items[slot]; + } - @Override - public ItemStack decrStackSize(int slot, int amount) { - return Util.decrStackSize(this, slot, amount); - } + @Override + public ItemStack decrStackSize(int slot, int amount) { + return Util.decrStackSize(this, slot, amount); + } - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - return null; - } + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return null; + } - @Override - public void setInventorySlotContents(int slot, ItemStack stack) { - items[slot] = stack; - markDirty(); - } + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + items[slot] = stack; + markDirty(); + } - @Override - public int getInventoryStackLimit() { - return 64; - } + @Override + public int getInventoryStackLimit() { + return 64; + } - @Override - public boolean isUseableByPlayer(EntityPlayer var1) { - return true; - } + @Override + public boolean isUseableByPlayer(EntityPlayer var1) { + return true; + } - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - return true; - } + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return true; + } - @Override - public String getInventoryName() { - return "ArrayInventory"; - } + @Override + public String getInventoryName() { + return "ArrayInventory"; + } - @Override - public boolean hasCustomInventoryName() { - return false; - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public void markDirty() { + @Override + public void markDirty() { - } + } - @Override - public void openInventory() { + @Override + public void openInventory() { - } + } - @Override - public void closeInventory() { + @Override + public void closeInventory() { - } + } } 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 ed0ae79..9eca71a 100644 --- a/src/main/java/com/enderio/core/common/util/BlockCoord.java +++ b/src/main/java/com/enderio/core/common/util/BlockCoord.java @@ -1,7 +1,5 @@ package com.enderio.core.common.util; -import io.netty.buffer.ByteBuf; - import javax.annotation.Generated; import net.minecraft.block.Block; @@ -15,161 +13,172 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; import com.google.common.base.Strings; +import io.netty.buffer.ByteBuf; public class BlockCoord { - public final int x, y, z; + public final int x, y, z; - public BlockCoord() { - this(0, 0, 0); - } - - public BlockCoord(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - } + public BlockCoord() { + this(0, 0, 0); + } - public BlockCoord(double x, double y, double z) { - this(MathHelper.floor_double(x), MathHelper.floor_double(y), MathHelper.floor_double(z)); - } + public BlockCoord(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } - public BlockCoord(TileEntity tile) { - this(tile.xCoord, tile.yCoord, tile.zCoord); - } + public BlockCoord(double x, double y, double z) { + this(MathHelper.floor_double(x), MathHelper.floor_double(y), MathHelper.floor_double(z)); + } - public BlockCoord(Entity e) { - this(e.posX, e.posY, e.posZ); - } + public BlockCoord(TileEntity tile) { + this(tile.xCoord, tile.yCoord, tile.zCoord); + } - public BlockCoord(BlockCoord bc) { - this(bc.x, bc.y, bc.z); - } + public BlockCoord(Entity e) { + this(e.posX, e.posY, e.posZ); + } - public BlockCoord getLocation(ForgeDirection dir) { - return new BlockCoord(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ); - } + public BlockCoord(BlockCoord bc) { + this(bc.x, bc.y, bc.z); + } - public BlockCoord(String x, String y, String z) { - this(Strings.isNullOrEmpty(x) ? 0 : Integer.parseInt(x), Strings.isNullOrEmpty(y) ? 0 : Integer.parseInt(y), Strings.isNullOrEmpty(z) ? 0 : Integer - .parseInt(z)); - } + public BlockCoord getLocation(ForgeDirection dir) { + return new BlockCoord(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ); + } - public BlockCoord(MovingObjectPosition mop) { - this(mop.blockX, mop.blockY, mop.blockZ); - } + public BlockCoord(String x, String y, String z) { + this( + Strings.isNullOrEmpty(x) ? 0 : Integer.parseInt(x), + Strings.isNullOrEmpty(y) ? 0 : Integer.parseInt(y), + Strings.isNullOrEmpty(z) ? 0 : Integer.parseInt(z)); + } - public Block getBlock(IBlockAccess world) { - return world.getBlock(x, y, z); - } + public BlockCoord(MovingObjectPosition mop) { + this(mop.blockX, mop.blockY, mop.blockZ); + } - public int getMetadata(IBlockAccess world) { - return world.getBlockMetadata(x, y, z); - } + public Block getBlock(IBlockAccess world) { + return world.getBlock(x, y, z); + } - public TileEntity getTileEntity(IBlockAccess world) { - return world.getTileEntity(x, y, z); - } + public int getMetadata(IBlockAccess world) { + return world.getBlockMetadata(x, y, z); + } - public int getDistSq(BlockCoord other) { - int xDiff = x - other.x; - int yDiff = y - other.y; - int zDiff = z - other.z; - return xDiff * xDiff + yDiff * yDiff + zDiff * zDiff; - } + public TileEntity getTileEntity(IBlockAccess world) { + return world.getTileEntity(x, y, z); + } - public int getDistSq(TileEntity other) { - return getDistSq(new BlockCoord(other)); - } + public int getDistSq(BlockCoord other) { + int xDiff = x - other.x; + int yDiff = y - other.y; + int zDiff = z - other.z; + return xDiff * xDiff + yDiff * yDiff + zDiff * zDiff; + } - public int getDist(BlockCoord other) { - double dsq = getDistSq(other); - return (int) Math.ceil(Math.sqrt(dsq)); - } + public int getDistSq(TileEntity other) { + return getDistSq(new BlockCoord(other)); + } - public int getDist(TileEntity other) { - return getDist(new BlockCoord(other)); - } + public int getDist(BlockCoord other) { + double dsq = getDistSq(other); + return (int) Math.ceil(Math.sqrt(dsq)); + } - public void writeToBuf(ByteBuf buf) { - buf.writeInt(x); - buf.writeInt(y); - buf.writeInt(z); - } + public int getDist(TileEntity other) { + return getDist(new BlockCoord(other)); + } - public static BlockCoord readFromBuf(ByteBuf buf) { - return new BlockCoord(buf.readInt(), buf.readInt(), buf.readInt()); - } + public void writeToBuf(ByteBuf buf) { + buf.writeInt(x); + buf.writeInt(y); + buf.writeInt(z); + } - public void writeToNBT(NBTTagCompound tag) { - tag.setInteger("bc:x", x); - tag.setInteger("bc:y", y); - tag.setInteger("bc:z", z); - } + public static BlockCoord readFromBuf(ByteBuf buf) { + return new BlockCoord(buf.readInt(), buf.readInt(), buf.readInt()); + } - public static BlockCoord readFromNBT(NBTTagCompound tag) { - return new BlockCoord(tag.getInteger("bc:x"), tag.getInteger("bc:y"), tag.getInteger("bc:z")); - } + public void writeToNBT(NBTTagCompound tag) { + tag.setInteger("bc:x", x); + tag.setInteger("bc:y", y); + tag.setInteger("bc:z", z); + } - public String chatString() { - return chatString(EnumChatFormatting.WHITE); - } + public static BlockCoord readFromNBT(NBTTagCompound tag) { + return new BlockCoord(tag.getInteger("bc:x"), tag.getInteger("bc:y"), tag.getInteger("bc:z")); + } - 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); - } + public String chatString() { + return chatString(EnumChatFormatting.WHITE); + } - public boolean equals(int x, int y, int z) { - return equals(new BlockCoord(x, y, z)); - } + 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); + } - @Override - public String toString() { - return "X: " + x + " Y: " + y + " Z: " + z; - } - - @Override - @Generated("lombok") - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof BlockCoord)) return false; - final BlockCoord other = (BlockCoord)o; - if (!other.canEqual((Object)this)) return false; - if (this.x != other.x) return false; - if (this.y != other.y) return false; - if (this.z != other.z) return false; - return true; - } + public boolean equals(int x, int y, int z) { + return equals(new BlockCoord(x, y, z)); + } - @Generated("lombok") - protected boolean canEqual(final Object other) { - return other instanceof BlockCoord; - } + @Override + public String toString() { + return "X: " + x + " Y: " + y + " Z: " + z; + } - @Override - @Generated("lombok") - public int hashCode() { - final int PRIME = 59; - int result = 1; - result = result * PRIME + this.x; - result = result * PRIME + this.y; - result = result * PRIME + this.z; - return result; - } + @Override + @Generated("lombok") + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof BlockCoord)) return false; + final BlockCoord other = (BlockCoord) o; + if (!other.canEqual((Object) this)) return false; + if (this.x != other.x) return false; + if (this.y != other.y) return false; + if (this.z != other.z) return false; + return true; + } - @Generated("lombok") - public BlockCoord withX(final int x) { - return this.x == x ? this : new BlockCoord(x, this.y, this.z); - } + @Generated("lombok") + protected boolean canEqual(final Object other) { + return other instanceof BlockCoord; + } - @Generated("lombok") - public BlockCoord withY(final int y) { - return this.y == y ? this : new BlockCoord(this.x, y, this.z); - } + @Override + @Generated("lombok") + public int hashCode() { + final int PRIME = 59; + int result = 1; + result = result * PRIME + this.x; + result = result * PRIME + this.y; + result = result * PRIME + this.z; + return result; + } - @Generated("lombok") - public BlockCoord withZ(final int z) { - return this.z == z ? this : new BlockCoord(this.x, this.y, z); - } + @Generated("lombok") + public BlockCoord withX(final int x) { + return this.x == x ? this : new BlockCoord(x, this.y, this.z); + } + + @Generated("lombok") + public BlockCoord withY(final int y) { + return this.y == y ? this : new BlockCoord(this.x, y, this.z); + } + + @Generated("lombok") + public BlockCoord withZ(final int z) { + return this.z == z ? this : new BlockCoord(this.x, this.y, z); + } } diff --git a/src/main/java/com/enderio/core/common/util/Bound.java b/src/main/java/com/enderio/core/common/util/Bound.java index 146844d..4002c60 100644 --- a/src/main/java/com/enderio/core/common/util/Bound.java +++ b/src/main/java/com/enderio/core/common/util/Bound.java @@ -6,82 +6,77 @@ import javax.annotation.concurrent.Immutable; /** * An object to represent a bounds limit on a property. * - * @param - * The type of the bound. + * @param The type of the bound. */ @Immutable public final class Bound> { - public static final Bound MAX_BOUND = Bound.of(Double.MIN_VALUE, Double.MAX_VALUE); + public static final Bound MAX_BOUND = Bound.of(Double.MIN_VALUE, Double.MAX_VALUE); - public static > Bound of(T min, T max) { - return new Bound(min, max); - } + public static > Bound of(T min, T max) { + return new Bound(min, max); + } - public final T min; - public final T max; + public final T min; + public final T max; - private Bound(final T min, final T max) { - this.min = min; - this.max = max; - } + private Bound(final T min, final T max) { + this.min = min; + this.max = max; + } - public T getMin() { - return this.min; - } + public T getMin() { + return this.min; + } - public T getMax() { - return this.max; - } + public T getMax() { + return this.max; + } - public T clamp(T val) { - return val.compareTo(min) < 0 ? min : val.compareTo(max) > 0 ? max : val; - } + public T clamp(T val) { + return val.compareTo(min) < 0 ? min : val.compareTo(max) > 0 ? max : val; + } - @Override - @Generated("lombok") - public boolean equals(final java.lang.Object o) { - if (o == this) - return true; - if (!(o instanceof Bound)) - return false; - final Bound other = (Bound) o; - final java.lang.Object this$min = this.getMin(); - final java.lang.Object other$min = other.getMin(); - if (this$min == null ? other$min != null : !this$min.equals(other$min)) - return false; - final java.lang.Object this$max = this.getMax(); - final java.lang.Object other$max = other.getMax(); - if (this$max == null ? other$max != null : !this$max.equals(other$max)) - return false; - return true; - } + @Override + @Generated("lombok") + public boolean equals(final java.lang.Object o) { + if (o == this) return true; + if (!(o instanceof Bound)) return false; + final Bound other = (Bound) o; + final java.lang.Object this$min = this.getMin(); + final java.lang.Object other$min = other.getMin(); + if (this$min == null ? other$min != null : !this$min.equals(other$min)) return false; + final java.lang.Object this$max = this.getMax(); + final java.lang.Object other$max = other.getMax(); + if (this$max == null ? other$max != null : !this$max.equals(other$max)) return false; + return true; + } - @Override - @Generated("lombok") - public int hashCode() { - final int PRIME = 59; - int result = 1; - final java.lang.Object $min = this.getMin(); - result = result * PRIME + ($min == null ? 43 : $min.hashCode()); - final java.lang.Object $max = this.getMax(); - result = result * PRIME + ($max == null ? 43 : $max.hashCode()); - return result; - } + @Override + @Generated("lombok") + public int hashCode() { + final int PRIME = 59; + int result = 1; + final java.lang.Object $min = this.getMin(); + result = result * PRIME + ($min == null ? 43 : $min.hashCode()); + final java.lang.Object $max = this.getMax(); + result = result * PRIME + ($max == null ? 43 : $max.hashCode()); + return result; + } - @Override - @Generated("lombok") - public java.lang.String toString() { - return "Bound(min=" + this.getMin() + ", max=" + this.getMax() + ")"; - } + @Override + @Generated("lombok") + public java.lang.String toString() { + return "Bound(min=" + this.getMin() + ", max=" + this.getMax() + ")"; + } - @Generated("lombok") - public Bound withMin(final T min) { - return this.min == min ? this : new Bound(min, this.max); - } + @Generated("lombok") + public Bound withMin(final T min) { + return this.min == min ? this : new Bound(min, this.max); + } - @Generated("lombok") - public Bound withMax(final T max) { - return this.max == max ? this : new Bound(this.min, max); - } -} \ No newline at end of file + @Generated("lombok") + public Bound withMax(final T max) { + return this.max == max ? this : new Bound(this.min, max); + } +} diff --git a/src/main/java/com/enderio/core/common/util/ChatUtil.java b/src/main/java/com/enderio/core/common/util/ChatUtil.java index be9cb9a..75543ff 100644 --- a/src/main/java/com/enderio/core/common/util/ChatUtil.java +++ b/src/main/java/com/enderio/core/common/util/ChatUtil.java @@ -1,6 +1,5 @@ package com.enderio.core.common.util; -import io.netty.buffer.ByteBuf; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiNewChat; import net.minecraft.entity.player.EntityPlayer; @@ -16,221 +15,209 @@ import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; +import io.netty.buffer.ByteBuf; public class ChatUtil { - public static class PacketNoSpamChat implements IMessage { + public static class PacketNoSpamChat implements IMessage { - private IChatComponent[] chatLines; + private IChatComponent[] chatLines; - public PacketNoSpamChat() { - chatLines = new IChatComponent[0]; - } - - private PacketNoSpamChat(IChatComponent... lines) { - // this is guaranteed to be >1 length by accessing methods - this.chatLines = lines; + public PacketNoSpamChat() { + chatLines = new IChatComponent[0]; + } + + private PacketNoSpamChat(IChatComponent... lines) { + // this is guaranteed to be >1 length by accessing methods + this.chatLines = lines; + } + + @Override + public void toBytes(ByteBuf buf) { + buf.writeInt(chatLines.length); + for (IChatComponent c : chatLines) { + ByteBufUtils.writeUTF8String(buf, IChatComponent.Serializer.func_150696_a(c)); + } + } + + @Override + public void fromBytes(ByteBuf buf) { + chatLines = new IChatComponent[buf.readInt()]; + for (int i = 0; i < chatLines.length; i++) { + chatLines[i] = IChatComponent.Serializer.func_150699_a(ByteBufUtils.readUTF8String(buf)); + } + } + + public static class Handler implements IMessageHandler { + + @Override + public IMessage onMessage(PacketNoSpamChat message, MessageContext ctx) { + sendNoSpamMessages(message.chatLines); + return null; + } + } } - @Override - public void toBytes(ByteBuf buf) { - buf.writeInt(chatLines.length); - for (IChatComponent c : chatLines) { - ByteBufUtils.writeUTF8String(buf, IChatComponent.Serializer.func_150696_a(c)); - } + private static final int DELETION_ID = 8675309; + private static int lastAdded; + + private static void sendNoSpamMessages(IChatComponent[] messages) { + GuiNewChat chat = Minecraft.getMinecraft().ingameGUI.getChatGUI(); + for (int i = DELETION_ID + messages.length - 1; i <= lastAdded; i++) { + chat.deleteChatLine(i); + } + for (int i = 0; i < messages.length; i++) { + chat.printChatMessageWithOptionalDeletion(messages[i], DELETION_ID + i); + } + lastAdded = DELETION_ID + messages.length - 1; } - @Override - public void fromBytes(ByteBuf buf) { - chatLines = new IChatComponent[buf.readInt()]; - for (int i = 0; i < chatLines.length; i++) { - chatLines[i] = IChatComponent.Serializer.func_150699_a(ByteBufUtils.readUTF8String(buf)); - } + /** + * Returns a standard {@link ChatComponentText} for the given {@link String}. + * + * @param s The string to wrap. + * @return An {@link IChatComponent} containing the string. + */ + public static IChatComponent wrap(String s) { + return new ChatComponentText(s); } - public static class Handler implements IMessageHandler { - - @Override - public IMessage onMessage(PacketNoSpamChat message, MessageContext ctx) { - sendNoSpamMessages(message.chatLines); - return null; - } + /** + * @see #wrap(String) + */ + public static IChatComponent[] wrap(String... s) { + IChatComponent[] ret = new IChatComponent[s.length]; + for (int i = 0; i < ret.length; i++) { + ret[i] = wrap(s[i]); + } + return ret; } - } - private static final int DELETION_ID = 8675309; - private static int lastAdded; - - private static void sendNoSpamMessages(IChatComponent[] messages) { - GuiNewChat chat = Minecraft.getMinecraft().ingameGUI.getChatGUI(); - for (int i = DELETION_ID + messages.length - 1; i <= lastAdded; i++) { - chat.deleteChatLine(i); + /** + * Returns a translatable chat component for the given string and format args. + * + * @param s The string to format + * @param args The args to apply to the format + */ + public static IChatComponent wrapFormatted(String s, Object... args) { + return new ChatComponentTranslation(s, args); } - for (int i = 0; i < messages.length; i++) { - chat.printChatMessageWithOptionalDeletion(messages[i], DELETION_ID + i); + + /** + * Simply sends the passed lines to the player in a chat message. + * + * @param player The player to send the chat to + * @param lines The lines to send + */ + public static void sendChat(EntityPlayer player, String... lines) { + sendChat(player, wrap(lines)); } - lastAdded = DELETION_ID + messages.length - 1; - } - /** - * Returns a standard {@link ChatComponentText} for the given {@link String}. - * - * @param s - * The string to wrap. - * @return An {@link IChatComponent} containing the string. - */ - public static IChatComponent wrap(String s) { - return new ChatComponentText(s); - } - - /** - * @see #wrap(String) - */ - public static IChatComponent[] wrap(String... s) { - IChatComponent[] ret = new IChatComponent[s.length]; - for (int i = 0; i < ret.length; i++) { - ret[i] = wrap(s[i]); + /** + * Localizes the lines before sending them. + * + * @see #sendChat(EntityPlayer, String...) + */ + public static void sendChatUnloc(EntityPlayer player, Lang lang, String... unlocLines) { + sendChat(player, lang.localizeAll(lang, unlocLines)); } - return ret; - } - /** - * Returns a translatable chat component for the given string and format args. - * - * @param s - * The string to format - * @param args - * The args to apply to the format - */ - public static IChatComponent wrapFormatted(String s, Object... args) { - return new ChatComponentTranslation(s, args); - } - - /** - * Simply sends the passed lines to the player in a chat message. - * - * @param player - * The player to send the chat to - * @param lines - * The lines to send - */ - public static void sendChat(EntityPlayer player, String... lines) { - sendChat(player, wrap(lines)); - } - - /** - * Localizes the lines before sending them. - * - * @see #sendChat(EntityPlayer, String...) - */ - public static void sendChatUnloc(EntityPlayer player, Lang lang, String... unlocLines) { - sendChat(player, lang.localizeAll(lang, unlocLines)); - } - - /** - * Sends all passed chat components to the player. - * - * @param player - * The player to send the chat lines to. - * @param lines - * The {@link IChatComponent chat components} to send.yes - */ - public static void sendChat(EntityPlayer player, IChatComponent... lines) { - for (IChatComponent c : lines) { - player.addChatComponentMessage(c); + /** + * Sends all passed chat components to the player. + * + * @param player The player to send the chat lines to. + * @param lines The {@link IChatComponent chat components} to send.yes + */ + public static void sendChat(EntityPlayer player, IChatComponent... lines) { + for (IChatComponent c : lines) { + player.addChatComponentMessage(c); + } } - } - /** - * Localizes the strings before sending them. - * - * @see #sendNoSpamClient(String...) - */ - public static void sendNoSpamClientUnloc(Lang lang, String... unlocLines) { - sendNoSpamClient(lang.localizeAll(lang, unlocLines)); - } - - /** - * Same as {@link #sendNoSpamClient(IChatComponent...)}, but wraps the Strings - * automatically. - * - * @param lines - * The chat lines to send - * @see #wrap(String) - */ - public static void sendNoSpamClient(String... lines) { - sendNoSpamClient(wrap(lines)); - } - - /** - * Skips the packet sending, unsafe to call on servers. - * - * @see #sendNoSpam(EntityPlayerMP, IChatComponent...) - */ - public static void sendNoSpamClient(IChatComponent... lines) { - sendNoSpamMessages(lines); - } - - /** - * Localizes the strings before sending them. - * - * @see #sendNoSpam(EntityPlayer, String...) - */ - public static void sendNoSpamUnloc(EntityPlayer player, Lang lang, String... unlocLines) { - sendNoSpam(player, lang.localizeAll(lang, unlocLines)); - } - - /** - * @see #wrap(String) - * @see #sendNoSpam(EntityPlayer, IChatComponent...) - */ - public static void sendNoSpam(EntityPlayer player, String... lines) { - sendNoSpam(player, wrap(lines)); - } - - /** - * First checks if the player is instanceof {@link EntityPlayerMP} before - * casting. - * - * @see #sendNoSpam(EntityPlayerMP, IChatComponent...) - */ - public static void sendNoSpam(EntityPlayer player, IChatComponent... lines) { - if (player instanceof EntityPlayerMP) { - sendNoSpam((EntityPlayerMP) player, lines); + /** + * Localizes the strings before sending them. + * + * @see #sendNoSpamClient(String...) + */ + public static void sendNoSpamClientUnloc(Lang lang, String... unlocLines) { + sendNoSpamClient(lang.localizeAll(lang, unlocLines)); } - } - /** - * Localizes the strings before sending them. - * - * @see #sendNoSpam(EntityPlayerMP, String...) - */ - public static void sendNoSpamUnloc(EntityPlayerMP player, Lang lang, String... unlocLines) { - sendNoSpam(player, lang.localizeAll(lang, unlocLines)); - } - - /** - * @see #wrap(String) - * @see #sendNoSpam(EntityPlayerMP, IChatComponent...) - */ - public static void sendNoSpam(EntityPlayerMP player, String... lines) { - sendNoSpam(player, wrap(lines)); - } - - /** - * Sends a chat message to the client, deleting past messages also sent via - * this method. - *

- * Credit to RWTema for the idea - * - * @param player - * The player to send the chat message to - * @param lines - * The chat lines to send. - */ - public static void sendNoSpam(EntityPlayerMP player, IChatComponent... lines) { - if (lines.length > 0) { - EnderPacketHandler.INSTANCE.sendTo(new PacketNoSpamChat(lines), player); + /** + * Same as {@link #sendNoSpamClient(IChatComponent...)}, but wraps the Strings automatically. + * + * @param lines The chat lines to send + * @see #wrap(String) + */ + public static void sendNoSpamClient(String... lines) { + sendNoSpamClient(wrap(lines)); + } + + /** + * Skips the packet sending, unsafe to call on servers. + * + * @see #sendNoSpam(EntityPlayerMP, IChatComponent...) + */ + public static void sendNoSpamClient(IChatComponent... lines) { + sendNoSpamMessages(lines); + } + + /** + * Localizes the strings before sending them. + * + * @see #sendNoSpam(EntityPlayer, String...) + */ + public static void sendNoSpamUnloc(EntityPlayer player, Lang lang, String... unlocLines) { + sendNoSpam(player, lang.localizeAll(lang, unlocLines)); + } + + /** + * @see #wrap(String) + * @see #sendNoSpam(EntityPlayer, IChatComponent...) + */ + public static void sendNoSpam(EntityPlayer player, String... lines) { + sendNoSpam(player, wrap(lines)); + } + + /** + * First checks if the player is instanceof {@link EntityPlayerMP} before casting. + * + * @see #sendNoSpam(EntityPlayerMP, IChatComponent...) + */ + public static void sendNoSpam(EntityPlayer player, IChatComponent... lines) { + if (player instanceof EntityPlayerMP) { + sendNoSpam((EntityPlayerMP) player, lines); + } + } + + /** + * Localizes the strings before sending them. + * + * @see #sendNoSpam(EntityPlayerMP, String...) + */ + public static void sendNoSpamUnloc(EntityPlayerMP player, Lang lang, String... unlocLines) { + sendNoSpam(player, lang.localizeAll(lang, unlocLines)); + } + + /** + * @see #wrap(String) + * @see #sendNoSpam(EntityPlayerMP, IChatComponent...) + */ + public static void sendNoSpam(EntityPlayerMP player, String... lines) { + sendNoSpam(player, wrap(lines)); + } + + /** + * Sends a chat message to the client, deleting past messages also sent via this method. + *

+ * Credit to RWTema for the idea + * + * @param player The player to send the chat message to + * @param lines The chat lines to send. + */ + public static void sendNoSpam(EntityPlayerMP player, IChatComponent... lines) { + if (lines.length > 0) { + EnderPacketHandler.INSTANCE.sendTo(new PacketNoSpamChat(lines), player); + } } - } } 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 610e5fa..e862928 100644 --- a/src/main/java/com/enderio/core/common/util/CreativeTabsCustom.java +++ b/src/main/java/com/enderio/core/common/util/CreativeTabsCustom.java @@ -6,46 +6,43 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public class CreativeTabsCustom extends CreativeTabs { - private ItemStack displayStack; - public CreativeTabsCustom(String unloc) { - super(unloc); - } + private ItemStack displayStack; - /** - * @param item - * Item to display - */ - public CreativeTabsCustom setDisplay(Item item) { - return setDisplay(item, 0); - } + public CreativeTabsCustom(String unloc) { + super(unloc); + } - /** - * @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 + */ + public CreativeTabsCustom setDisplay(Item item) { + return setDisplay(item, 0); + } - /** - * @param display - * ItemStack to display - */ - public CreativeTabsCustom setDisplay(ItemStack display) { - this.displayStack = display.copy(); - return this; - } + /** + * @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)); + } - @Override - public ItemStack getIconItemStack() { - return displayStack == null ? new ItemStack(Items.diamond) : displayStack; - } + /** + * @param display ItemStack to display + */ + public CreativeTabsCustom setDisplay(ItemStack display) { + this.displayStack = display.copy(); + return this; + } - @Override - public Item getTabIconItem() { - return null; // defaults to getIconItemStack() - } + @Override + public ItemStack getIconItemStack() { + return displayStack == null ? new ItemStack(Items.diamond) : displayStack; + } + + @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 e0e0587..2349876 100644 --- a/src/main/java/com/enderio/core/common/util/DyeColor.java +++ b/src/main/java/com/enderio/core/common/util/DyeColor.java @@ -1,88 +1,90 @@ package com.enderio.core.common.util; -import com.enderio.core.EnderCore; - import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; +import com.enderio.core.EnderCore; + public enum DyeColor { - BLACK, - RED, - GREEN, - BROWN, - BLUE, - PURPLE, - CYAN, - SILVER, - GRAY, - PINK, - LIME, - YELLOW, - LIGHT_BLUE, - MAGENTA, - ORANGE, - WHITE; + BLACK, + RED, + GREEN, + BROWN, + BLUE, + PURPLE, + CYAN, + SILVER, + GRAY, + PINK, + LIME, + YELLOW, + LIGHT_BLUE, + MAGENTA, + 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 = { + 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) { - ord = 0; - } - return DyeColor.values()[ord]; - } - - public static DyeColor getColorFromDye(ItemStack dye) { - if (dye == null) { - return null; - } - int[] oreIDs = OreDictionary.getOreIDs(dye); - for (int i = 0; i < DYE_ORE_NAMES.length; i++) { - int dyeID = OreDictionary.getOreID(DYE_ORE_NAMES[i]); - for (int oreId : oreIDs) { - if (dyeID == oreId) { - return DyeColor.values()[i]; + public static DyeColor getNext(DyeColor col) { + int ord = col.ordinal() + 1; + if (ord >= DyeColor.values().length) { + ord = 0; } - } + return DyeColor.values()[ord]; } - return null; - } - public static DyeColor fromIndex(int index) { - return DyeColor.values()[index]; - } + public static DyeColor getColorFromDye(ItemStack dye) { + if (dye == null) { + return null; + } + int[] oreIDs = OreDictionary.getOreIDs(dye); + for (int i = 0; i < DYE_ORE_NAMES.length; i++) { + int dyeID = OreDictionary.getOreID(DYE_ORE_NAMES[i]); + for (int oreId : oreIDs) { + if (dyeID == oreId) { + return DyeColor.values()[i]; + } + } + } + return null; + } - private DyeColor() { - } + public static DyeColor fromIndex(int index) { + return DyeColor.values()[index]; + } - public int getColor() { - return ItemDye.field_150922_c[ordinal()]; - } + private DyeColor() {} - public String getName() { - return ItemDye.field_150921_b[ordinal()]; - } + public int getColor() { + return ItemDye.field_150922_c[ordinal()]; + } - public String getLocalisedName() { - return EnderCore.lang.localizeExact(DYE_ORE_UNLOCAL_NAMES[ordinal()], false); - } + public String getName() { + return ItemDye.field_150921_b[ordinal()]; + } - @Override - public String toString() { - return getName(); - } + public String getLocalisedName() { + return EnderCore.lang.localizeExact(DYE_ORE_UNLOCAL_NAMES[ordinal()], false); + } -} \ No newline at end of file + @Override + public String toString() { + return getName(); + } + +} 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 07e1b0c..4339159 100644 --- a/src/main/java/com/enderio/core/common/util/EnderFileUtils.java +++ b/src/main/java/com/enderio/core/common/util/EnderFileUtils.java @@ -35,296 +35,279 @@ import com.enderio.core.EnderCore; import com.enderio.core.common.config.ConfigHandler; public class EnderFileUtils { - public static final FileFilter pngFilter = FileFilterUtils.suffixFileFilter(".png"); - public static 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 static void copyFromJar(Class jarClass, String filename, File to) { - EnderCore.logger.info("Copying file " + filename + " from jar"); - URL url = jarClass.getResource("/assets/" + filename); + public static final FileFilter pngFilter = FileFilterUtils.suffixFileFilter(".png"); + public static final FileFilter langFilter = FileFilterUtils.suffixFileFilter(".lang"); - try { - FileUtils.copyURLToFile(url, to); - } catch (IOException e) { - throw new RuntimeException(e); - } - } + /** + * @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 static void copyFromJar(Class jarClass, String filename, File to) { + EnderCore.logger.info("Copying file " + filename + " from jar"); + URL url = jarClass.getResource("/assets/" + filename); - /** - * @author Ilias Tsagklis - *

- * From this site. - * - * @param zip - * - The zip file to extract - * - * @return The folder extracted to - */ - @Nonnull - public static 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(); + try { + FileUtils.copyURLToFile(url, to); + } 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); - } } - return temp; - } + /** + * @author Ilias Tsagklis + *

+ * From + * + * this site. + * + * @param zip - The zip file to extract + * + * @return The folder extracted to + */ + @Nonnull + public static File extractZip(File zip) { + String zipPath = zip.getParent() + "/extracted"; + File temp = new File(zipPath); + temp.mkdir(); - /** - * @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 static 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(); - } - } + ZipFile zipFile = null; - /** @see #zipFolderContents(File, File) */ - private static 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); - } - } + try { + zipFile = new ZipFile(zip); - /** @see #zipFolderContents(File, File) */ - private static void copy(File file, OutputStream out) throws IOException { - InputStream in = new FileInputStream(file); - try { - copy(in, out); - } finally { - in.close(); - } - } + // get an enumeration of the ZIP file entries + Enumeration e = zipFile.entries(); - @Nonnull - public static File writeToFile(String filepath, String json) { - File file = new File(filepath); + while (e.hasMoreElements()) { + ZipEntry entry = e.nextElement(); - try { - file.createNewFile(); - FileWriter fw = new FileWriter(file); - fw.write(json); - fw.flush(); - fw.close(); - return file; - } catch (IOException e) { - throw new RuntimeException(e); - } - } + File destinationPath = new File(zipPath, entry.getName()); - @Nonnull - public static void safeDelete(File file) { - try { - file.delete(); - } catch (Exception e) { - EnderCore.logger.error("Deleting file " + file.getAbsolutePath() + " failed."); - } - } + // create parent directories + destinationPath.getParentFile().mkdirs(); - @Nonnull - public static void safeDeleteDirectory(File file) { - try { - FileUtils.deleteDirectory(file); - } catch (Exception e) { - EnderCore.logger.error("Deleting directory " + file.getAbsolutePath() + " failed."); - } - } + // if the entry is a file extract it + if (entry.isDirectory()) { + continue; + } else { + EnderCore.logger.info("Extracting file: " + destinationPath); - /** - * I don't think this ever worked. - * - * @param directory - */ - @Deprecated - public static void loadLangFiles(File directory) { - // NO-OP - } + BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); - /** - * 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 static boolean manuallyChangeConfigValue(String filePathFromConfigFolder, String prefix, String from, String to) { - File config = new File(ConfigHandler.configFolder.getAbsolutePath() + "/" + filePathFromConfigFolder); - boolean found = false; + int b; + byte buffer[] = new byte[1024]; - try { - FileReader fr1 = new FileReader(config); - BufferedReader read = new BufferedReader(fr1); + FileOutputStream fos = new FileOutputStream(destinationPath); - ArrayList strings = new ArrayList(); + BufferedOutputStream bos = new BufferedOutputStream(fos, 1024); - while (read.ready()) { - strings.add(read.readLine()); - } + while ((b = bis.read(buffer, 0, 1024)) != -1) { + bos.write(buffer, 0, b); + } - 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; + bos.close(); + bis.close(); + } + } + } 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); + } } - fw.write(s + "\n"); - } - - bw.flush(); - bw.close(); - } catch (Throwable t) { - t.printStackTrace(); + return temp; } - 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 static 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 ""; + /** + * @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 static 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(); + } } - while (scan.hasNext()) { - String s = scan.next(); + /** @see #zipFolderContents(File, File) */ + private static 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 static void copy(File file, OutputStream out) throws IOException { + InputStream in = new FileInputStream(file); + try { + copy(in, out); + } finally { + in.close(); + } + } + + @Nonnull + public static 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 static void safeDelete(File file) { + try { + file.delete(); + } catch (Exception e) { + EnderCore.logger.error("Deleting file " + file.getAbsolutePath() + " failed."); + } + } + + @Nonnull + public static void safeDeleteDirectory(File file) { + try { + FileUtils.deleteDirectory(file); + } catch (Exception e) { + EnderCore.logger.error("Deleting directory " + file.getAbsolutePath() + " failed."); + } + } + + /** + * I don't think this ever worked. + * + * @param directory + */ + @Deprecated + public static void loadLangFiles(File directory) { + // NO-OP + } + + /** + * 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 static 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 static 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()); + } + } - if (s.contains(key)) { scan.close(); - return s.substring(s.indexOf("=") + 1, s.length()); - } + return ""; } - - 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 8501b9e..e120650 100644 --- a/src/main/java/com/enderio/core/common/util/EnderRegistryUtils.java +++ b/src/main/java/com/enderio/core/common/util/EnderRegistryUtils.java @@ -19,105 +19,94 @@ 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). */ public class EnderRegistryUtils { - private static Method getMain; - private static Method registerItem; - private static 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); - } - } + private static Method getMain; + private static Method registerItem; + private static Method registerBlock; - /** - * 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 - */ - public static void registerItem(Item item, String modid, String name) { - try { - registerItem.invoke(getMain.invoke(null), item, modid + ":" + name, -1); - } catch (Exception e) { - Throwables.propagate(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 modid - * The modid to register the block to - * @param name - * The name of the block - */ - public static 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. - */ - public static 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(); + 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 + */ + public static void registerItem(Item item, String modid, String name) { + try { + registerItem.invoke(getMain.invoke(null), item, modid + ":" + name, -1); + } catch (Exception e) { + Throwables.propagate(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 modid The modid to register the block to + * @param name The name of the block + */ + public static 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. + */ + public static 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); } - 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 bafc370..77c4812 100644 --- a/src/main/java/com/enderio/core/common/util/EnderStringUtils.java +++ b/src/main/java/com/enderio/core/common/util/EnderStringUtils.java @@ -6,114 +6,131 @@ import net.minecraft.util.EnumChatFormatting; import com.enderio.core.EnderCore; 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 static 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 + * @param formatK - Whether or not to format the thousands + * @return A string numeric formatted to use SI suffixes + */ + public static 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; + } } - 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 static String formatString(String prefix, String suffix, long amnt, boolean useDecimals) { - return formatString(prefix, suffix, amnt, useDecimals, false); - } - - private static 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 static 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 static 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); + /** + * 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 static String formatString(String prefix, String suffix, long amnt, boolean useDecimals) { + return formatString(prefix, suffix, amnt, useDecimals, false); } - return name; - } + private static 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 static 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 static 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; + } } diff --git a/src/main/java/com/enderio/core/common/util/EntityUtil.java b/src/main/java/com/enderio/core/common/util/EntityUtil.java index dd36a70..ba0a6db 100644 --- a/src/main/java/com/enderio/core/common/util/EntityUtil.java +++ b/src/main/java/com/enderio/core/common/util/EntityUtil.java @@ -28,144 +28,144 @@ import com.enderio.core.common.vecmath.Vector3d; public class EntityUtil { - private static final Random rand = new Random(); + private static final Random rand = new Random(); - public static void setEntityVelocity(Entity entity, double velX, double velY, double velZ) { - entity.motionX = velX; - entity.motionY = velY; - entity.motionZ = velZ; - } - - public static EntityFireworkRocket getRandomFirework(World world) { - return getRandomFirework(world, new BlockCoord(0, 0, 0)); - } - - public static EntityFireworkRocket getRandomFirework(World world, BlockCoord pos) { - ItemStack firework = new ItemStack(Items.fireworks); - firework.stackTagCompound = new NBTTagCompound(); - NBTTagCompound expl = new NBTTagCompound(); - expl.setBoolean("Flicker", true); - expl.setBoolean("Trail", true); - - int[] colors = new int[rand.nextInt(8) + 1]; - for (int i = 0; i < colors.length; i++) { - colors[i] = ItemDye.field_150922_c[rand.nextInt(16)]; + public static void setEntityVelocity(Entity entity, double velX, double velY, double velZ) { + entity.motionX = velX; + entity.motionY = velY; + entity.motionZ = velZ; } - expl.setIntArray("Colors", colors); - byte type = (byte) (rand.nextInt(3) + 1); - type = type == 3 ? 4 : type; - expl.setByte("Type", type); - NBTTagList explosions = new NBTTagList(); - explosions.appendTag(expl); + public static EntityFireworkRocket getRandomFirework(World world) { + return getRandomFirework(world, new BlockCoord(0, 0, 0)); + } - NBTTagCompound fireworkTag = new NBTTagCompound(); - fireworkTag.setTag("Explosions", explosions); - fireworkTag.setByte("Flight", (byte) 1); - firework.stackTagCompound.setTag("Fireworks", fireworkTag); + public static EntityFireworkRocket getRandomFirework(World world, BlockCoord pos) { + ItemStack firework = new ItemStack(Items.fireworks); + firework.stackTagCompound = new NBTTagCompound(); + NBTTagCompound expl = new NBTTagCompound(); + expl.setBoolean("Flicker", true); + expl.setBoolean("Trail", true); - EntityFireworkRocket e = new EntityFireworkRocket(world, pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, firework); - return e; - } - - public static void spawnFirework(BlockCoord block, int dimID) { - spawnFirework(block, dimID, 0); - } - - public static void spawnFirework(BlockCoord block, int dimID, int range) { - World world = DimensionManager.getWorld(dimID); - - BlockCoord pos = new BlockCoord(block.x, block.y, block.z); - - // don't bother if there's no randomness at all - if (range > 0) { - pos = new BlockCoord(moveRandomly(block.x, range), block.y, moveRandomly(block.z, range)); - - int tries = -1; - while (!world.isAirBlock(pos.x, pos.y, pos.z) && !world.getBlock(pos.x, pos.y, pos.z).isReplaceable(world, pos.x, pos.y, pos.z)) { - tries++; - if (tries > 100) { - return; + int[] colors = new int[rand.nextInt(8) + 1]; + for (int i = 0; i < colors.length; i++) { + colors[i] = ItemDye.field_150922_c[rand.nextInt(16)]; } - } + expl.setIntArray("Colors", colors); + byte type = (byte) (rand.nextInt(3) + 1); + type = type == 3 ? 4 : type; + expl.setByte("Type", type); + + NBTTagList explosions = new NBTTagList(); + explosions.appendTag(expl); + + NBTTagCompound fireworkTag = new NBTTagCompound(); + fireworkTag.setTag("Explosions", explosions); + fireworkTag.setByte("Flight", (byte) 1); + firework.stackTagCompound.setTag("Fireworks", fireworkTag); + + EntityFireworkRocket e = new EntityFireworkRocket(world, pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, firework); + return e; } - world.spawnEntityInWorld(getRandomFirework(world, pos)); - } + public static void spawnFirework(BlockCoord block, int dimID) { + spawnFirework(block, dimID, 0); + } - private static double moveRandomly(double base, double range) { - return base + 0.5 + rand.nextDouble() * range - (range / 2); - } + public static void spawnFirework(BlockCoord block, int dimID, int range) { + World world = DimensionManager.getWorld(dimID); - public static String getDisplayNameForEntity(String mobName) { - return StatCollector.translateToLocal("entity." + mobName + ".name"); - } + BlockCoord pos = new BlockCoord(block.x, block.y, block.z); - public static List getAllRegisteredMobNames(boolean excludeBosses) { - List result = new ArrayList(); - Set> entries = EntityList.classToStringMapping.entrySet(); - for (Map.Entry entry : entries) { - if (EntityLiving.class.isAssignableFrom(entry.getKey())) { - if (!excludeBosses || !IBossDisplayData.class.isAssignableFrom(entry.getKey())) { - result.add(entry.getValue()); + // don't bother if there's no randomness at all + if (range > 0) { + pos = new BlockCoord(moveRandomly(block.x, range), block.y, moveRandomly(block.z, range)); + + int tries = -1; + while (!world.isAirBlock(pos.x, pos.y, pos.z) + && !world.getBlock(pos.x, pos.y, pos.z).isReplaceable(world, pos.x, pos.y, pos.z)) { + tries++; + if (tries > 100) { + return; + } + } } - } + + world.spawnEntityInWorld(getRandomFirework(world, pos)); } - return result; - } - private EntityUtil() { - } + private static double moveRandomly(double base, double range) { + return base + 0.5 + rand.nextDouble() * range - (range / 2); + } - public static Vector3d getEntityPosition(Entity ent) { - return new Vector3d(ent.posX, ent.posY, ent.posZ); - } + public static String getDisplayNameForEntity(String mobName) { + return StatCollector.translateToLocal("entity." + mobName + ".name"); + } - public static List getCollidingBlockGeometry(World world, Entity entity) { - AxisAlignedBB entityBounds = entity.boundingBox; - ArrayList collidingBoundingBoxes = new ArrayList(); - int minX = MathHelper.floor_double(entityBounds.minX); - int minY = MathHelper.floor_double(entityBounds.minY); - int minZ = MathHelper.floor_double(entityBounds.minZ); - int maxX = MathHelper.floor_double(entityBounds.maxX + 1.0D); - int maxY = MathHelper.floor_double(entityBounds.maxY + 1.0D); - int maxZ = MathHelper.floor_double(entityBounds.maxZ + 1.0D); - for (int x = minX; x < maxX; x++) { - for (int z = minZ; z < maxZ; z++) { - for (int y = minY; y < maxY; y++) { - Block block = world.getBlock(x, y, z); - if (block != null) { - block.addCollisionBoxesToList(world, x, y, z, entityBounds, collidingBoundingBoxes, entity); - } + public static List getAllRegisteredMobNames(boolean excludeBosses) { + List result = new ArrayList(); + Set> entries = EntityList.classToStringMapping.entrySet(); + for (Map.Entry entry : entries) { + if (EntityLiving.class.isAssignableFrom(entry.getKey())) { + if (!excludeBosses || !IBossDisplayData.class.isAssignableFrom(entry.getKey())) { + result.add(entry.getValue()); + } + } } - } + return result; } - return collidingBoundingBoxes; - } - public static void spawnItemInWorldWithRandomMotion(World world, ItemStack item, int x, int y, int z) { - if (item != null) { - spawnItemInWorldWithRandomMotion(world, item, x + 0.5, y + 0.5, z + 0.5); + private EntityUtil() {} + + public static Vector3d getEntityPosition(Entity ent) { + return new Vector3d(ent.posX, ent.posY, ent.posZ); } - } - public static void spawnItemInWorldWithRandomMotion(World world, ItemStack item, double x, double y, double z) { - if (item != null) { - spawnItemInWorldWithRandomMotion(new EntityItem(world, x, y, z, item)); + public static List getCollidingBlockGeometry(World world, Entity entity) { + AxisAlignedBB entityBounds = entity.boundingBox; + ArrayList collidingBoundingBoxes = new ArrayList(); + int minX = MathHelper.floor_double(entityBounds.minX); + int minY = MathHelper.floor_double(entityBounds.minY); + int minZ = MathHelper.floor_double(entityBounds.minZ); + int maxX = MathHelper.floor_double(entityBounds.maxX + 1.0D); + int maxY = MathHelper.floor_double(entityBounds.maxY + 1.0D); + int maxZ = MathHelper.floor_double(entityBounds.maxZ + 1.0D); + for (int x = minX; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + for (int y = minY; y < maxY; y++) { + Block block = world.getBlock(x, y, z); + if (block != null) { + block.addCollisionBoxesToList(world, x, y, z, entityBounds, collidingBoundingBoxes, entity); + } + } + } + } + return collidingBoundingBoxes; } - } - public static void spawnItemInWorldWithRandomMotion(EntityItem entity) { - entity.delayBeforeCanPickup = 10; + public static void spawnItemInWorldWithRandomMotion(World world, ItemStack item, int x, int y, int z) { + if (item != null) { + spawnItemInWorldWithRandomMotion(world, item, x + 0.5, y + 0.5, z + 0.5); + } + } - float f = (entity.worldObj.rand.nextFloat() * 0.1f) - 0.05f; - float f1 = (entity.worldObj.rand.nextFloat() * 0.1f) - 0.05f; - float f2 = (entity.worldObj.rand.nextFloat() * 0.1f) - 0.05f; + public static void spawnItemInWorldWithRandomMotion(World world, ItemStack item, double x, double y, double z) { + if (item != null) { + spawnItemInWorldWithRandomMotion(new EntityItem(world, x, y, z, item)); + } + } - entity.motionX += f; - entity.motionY += f1; - entity.motionZ += f2; + public static void spawnItemInWorldWithRandomMotion(EntityItem entity) { + entity.delayBeforeCanPickup = 10; - entity.worldObj.spawnEntityInWorld(entity); - } + float f = (entity.worldObj.rand.nextFloat() * 0.1f) - 0.05f; + float f1 = (entity.worldObj.rand.nextFloat() * 0.1f) - 0.05f; + float f2 = (entity.worldObj.rand.nextFloat() * 0.1f) - 0.05f; + + entity.motionX += f; + entity.motionY += f1; + entity.motionZ += f2; + + entity.worldObj.spawnEntityInWorld(entity); + } } 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 ed2e154..ffaa85b 100644 --- a/src/main/java/com/enderio/core/common/util/FluidUtil.java +++ b/src/main/java/com/enderio/core/common/util/FluidUtil.java @@ -5,14 +5,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import codechicken.nei.recipe.StackInfo; -import com.enderio.core.api.common.util.IFluidReceptor; -import com.enderio.core.api.common.util.ITankAccess; - import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraft.item.ItemPotion; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; @@ -27,435 +21,460 @@ import net.minecraftforge.fluids.IFluidBlock; import net.minecraftforge.fluids.IFluidContainerItem; import net.minecraftforge.fluids.IFluidHandler; import net.minecraftforge.fluids.IFluidTank; + +import codechicken.nei.recipe.StackInfo; + +import com.enderio.core.api.common.util.IFluidReceptor; +import com.enderio.core.api.common.util.ITankAccess; import cpw.mods.fml.common.Loader; public class FluidUtil { - public static final List fluidReceptors = new ArrayList(); + public static final List fluidReceptors = new ArrayList(); - static { - try { - Class.forName("crazypants.util.BuildcraftUtil"); - } catch (Exception e) { - 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 - } - } - - public static Map getNeighbouringFluidHandlers(IBlockAccess world, BlockCoord bc) { - Map res = new HashMap(); - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { - IFluidHandler fh = getFluidHandler(world, bc.getLocation(dir)); - if (fh != null) { - res.put(dir, fh); - } - } - return res; - } - - public static IFluidHandler getFluidHandler(IBlockAccess world, BlockCoord bc) { - return getFluidHandler(world, bc.x, bc.y, bc.z); - } - - public static IFluidHandler getFluidHandler(IBlockAccess world, int x, int y, int z) { - TileEntity te = world.getTileEntity(x, y, z); - return getFluidHandler(te); - } - - public static IFluidHandler getFluidHandler(TileEntity te) { - if (te instanceof IFluidHandler) { - IFluidHandler res = (IFluidHandler) te; - for (IFluidReceptor rec : fluidReceptors) { - if (!rec.isValidReceptor(res)) { - return null; + static { + try { + Class.forName("crazypants.util.BuildcraftUtil"); + } catch (Exception e) { + 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 } - } - return res; } - return null; - } - public static FluidStack getFluidFromItem(ItemStack stack) { - if (stack != null) { - FluidStack fluidStack = null; - if (stack.getItem() instanceof IFluidContainerItem) { - fluidStack = ((IFluidContainerItem) stack.getItem()).getFluid(stack); - } - if (fluidStack == null) { - fluidStack = FluidContainerRegistry.getFluidForFilledItem(stack); - } - if (fluidStack == null && Block.getBlockFromItem(stack.getItem()) instanceof IFluidBlock) { - Fluid fluid = ((IFluidBlock) Block.getBlockFromItem(stack.getItem())).getFluid(); - if (fluid != null) { - return new FluidStack(fluid, 1000); + public static Map getNeighbouringFluidHandlers(IBlockAccess world, BlockCoord bc) { + Map res = new HashMap(); + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + IFluidHandler fh = getFluidHandler(world, bc.getLocation(dir)); + if (fh != null) { + res.put(dir, fh); + } } - } - if (fluidStack == null && Loader.isModLoaded("NotEnoughItems")) { - fluidStack = StackInfo.getFluid(stack); - } - return fluidStack; + return res; } - return null; - } - public static boolean doPull(IFluidHandler into, ForgeDirection fromDir, int maxVolume) { - TileEntity te = (TileEntity) into; - BlockCoord loc = new BlockCoord(te).getLocation(fromDir); - IFluidHandler target = FluidUtil.getFluidHandler(te.getWorldObj(), loc); - if (target != null) { - FluidTankInfo[] infos = target.getTankInfo(fromDir.getOpposite()); - if (infos != null) { - for (FluidTankInfo info : infos) { - 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) { - int filled = into.fill(fromDir, drained, false); - if (filled > 0) { - drained = target.drain(fromDir.getOpposite(), filled, true); - into.fill(fromDir, drained, true); - return true; + public static IFluidHandler getFluidHandler(IBlockAccess world, BlockCoord bc) { + return getFluidHandler(world, bc.x, bc.y, bc.z); + } + + public static IFluidHandler getFluidHandler(IBlockAccess world, int x, int y, int z) { + TileEntity te = world.getTileEntity(x, y, z); + return getFluidHandler(te); + } + + public static IFluidHandler getFluidHandler(TileEntity te) { + if (te instanceof IFluidHandler) { + IFluidHandler res = (IFluidHandler) te; + for (IFluidReceptor rec : fluidReceptors) { + if (!rec.isValidReceptor(res)) { + return null; } - } } - } + return res; } - } + return null; } - return false; - } - public static boolean doPush(IFluidHandler from, ForgeDirection fromDir, int maxVolume) { - - TileEntity te = (TileEntity) from; - BlockCoord loc = new BlockCoord(te).getLocation(fromDir); - IFluidHandler target = getFluidHandler(te.getWorldObj(), loc); - if (target == null) { - return false; - } - FluidTankInfo[] infos = from.getTankInfo(fromDir); - boolean res = false; - if (infos != null) { - for (FluidTankInfo info : infos) { - if (info.fluid != null && info.fluid.amount > 0 && from.canDrain(fromDir, info.fluid.getFluid())) { - FluidStack maxDrain = new FluidStack(info.fluid, maxVolume); - FluidStack canDrain = from.drain(fromDir, maxDrain, false); - if (canDrain != null && canDrain.amount > 0) { - int filled = target.fill(fromDir.getOpposite(), canDrain, true); - from.drain(fromDir, new FluidStack(info.fluid, filled), true); - res |= true; - } - } - } - } - return res; - } - - public static FluidAndStackResult tryFillContainer(ItemStack target, FluidStack source) { - if (target != null && target.getItem() != null && source != null && source.getFluid() != null && source.amount > 0) { - - if (target.getItem() instanceof IFluidContainerItem) { - ItemStack resultStack = target.copy(); - resultStack.stackSize = 1; - int amount = ((IFluidContainerItem) target.getItem()).fill(resultStack, source, true); - if (amount <= 0) { - return new FluidAndStackResult(null, null, target, source); - } - FluidStack resultFluid = source.copy(); - resultFluid.amount = amount; - ItemStack remainderStack = target.copy(); - remainderStack.stackSize--; - if (remainderStack.stackSize <= 0) { - remainderStack = null; - } - FluidStack remainderFluid = source.copy(); - remainderFluid.amount -= amount; - if (remainderFluid.amount <= 0) { - remainderFluid = null; - } - return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); - } - - ItemStack resultStack = FluidContainerRegistry.fillFluidContainer(source.copy(), target); - if (resultStack != null) { - FluidStack resultFluid = FluidContainerRegistry.getFluidForFilledItem(resultStack); - if (resultFluid != null) { - ItemStack remainderStack = target.copy(); - remainderStack.stackSize--; - if (remainderStack.stackSize <= 0) { - remainderStack = null; - } - FluidStack remainderFluid = source.copy(); - remainderFluid.amount -= resultFluid.amount; - if (remainderFluid.amount <= 0) { - remainderFluid = null; - } - return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); - } - } - - } - return new FluidAndStackResult(null, null, target, source); - } - - public static FluidAndStackResult tryDrainContainer(ItemStack source, FluidStack target, int capacity) { - if (source != null && source.getItem() != null) { - - int maxDrain = capacity - (target != null ? target.amount : 0); - if (source.getItem() instanceof IFluidContainerItem) { - ItemStack resultStack = source.copy(); - resultStack.stackSize = 1; - FluidStack resultFluid = ((IFluidContainerItem) source.getItem()).drain(resultStack, maxDrain, true); - if (resultFluid == null || resultFluid.amount <= 0 || (target != null && resultFluid.getFluid() != target.getFluid())) { - return new FluidAndStackResult(null, null, source, target); - } - ItemStack remainderStack = source.copy(); - remainderStack.stackSize--; - if (remainderStack.stackSize <= 0) { - remainderStack = null; - } - FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid, 0); - remainderFluid.amount += resultFluid.amount; - return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); - } - - FluidStack resultFluid = FluidContainerRegistry.getFluidForFilledItem(source); - if (resultFluid != null && resultFluid.amount > 0 && resultFluid.amount <= maxDrain && (target == null || resultFluid.isFluidEqual(target))) { - 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); - // } - ItemStack remainderStack = source.copy(); - remainderStack.stackSize--; - if (remainderStack.stackSize <= 0) { - remainderStack = null; - } - FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid, 0); - remainderFluid.amount += resultFluid.amount; - return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); - } - - } - return new FluidAndStackResult(null, null, source, target); - } - - public static FluidAndStackResult tryDrainContainer(ItemStack source, ITankAccess tank) { - if (source != null && source.getItem() != null) { - - if (source.getItem() instanceof IFluidContainerItem) { - FluidStack fluid = ((IFluidContainerItem) source.getItem()).getFluid(source); - IFluidTank targetTank = fluid != null ? tank.getInputTank(fluid) : null; - if (targetTank != null) { - FluidStack target = targetTank.getFluid(); - int maxDrain = targetTank.getCapacity() - (target != null ? target.amount : 0); - ItemStack resultStack = source.copy(); - resultStack.stackSize = 1; - FluidStack resultFluid = ((IFluidContainerItem) source.getItem()).drain(resultStack, maxDrain, true); - if (resultFluid == null || resultFluid.amount <= 0 || (target != null && !resultFluid.isFluidEqual(target))) { - return new FluidAndStackResult(null, null, source, target); - } - ItemStack remainderStack = source.copy(); - remainderStack.stackSize--; - if (remainderStack.stackSize <= 0) { - remainderStack = null; - } - FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid, 0); - remainderFluid.amount += resultFluid.amount; - return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); - } - } - - FluidStack resultFluid = FluidContainerRegistry.getFluidForFilledItem(source); - if (resultFluid != null && resultFluid.amount > 0) { - IFluidTank targetTank = tank.getInputTank(resultFluid); - if (targetTank != null) { - FluidStack target = targetTank.getFluid(); - int maxDrain = targetTank.getCapacity() - (target != null ? target.amount : 0); - if (resultFluid.amount <= maxDrain && (target == null || resultFluid.isFluidEqual(target))) { - ItemStack resultStack = source.getItem().getContainerItem(source); - // 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) { - remainderStack = null; + public static FluidStack getFluidFromItem(ItemStack stack) { + if (stack != null) { + FluidStack fluidStack = null; + if (stack.getItem() instanceof IFluidContainerItem) { + fluidStack = ((IFluidContainerItem) stack.getItem()).getFluid(stack); } - FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid, 0); - remainderFluid.amount += resultFluid.amount; - return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); - } + if (fluidStack == null) { + fluidStack = FluidContainerRegistry.getFluidForFilledItem(stack); + } + if (fluidStack == null && Block.getBlockFromItem(stack.getItem()) instanceof IFluidBlock) { + Fluid fluid = ((IFluidBlock) Block.getBlockFromItem(stack.getItem())).getFluid(); + if (fluid != null) { + return new FluidStack(fluid, 1000); + } + } + if (fluidStack == null && Loader.isModLoaded("NotEnoughItems")) { + fluidStack = StackInfo.getFluid(stack); + } + return fluidStack; } - } - + return null; } - return new FluidAndStackResult(null, null, source, null); - } - /** - * If the currently held item of the given player can be filled with the - * liquid in the given tank's output tank, do so and put the resultant filled - * container item where it can go. This will also drain the tank and set it to - * dirty. - * - *

- * Cases handled for the the filled container: - * - *

    - *
  • If the stacksize of the held item is one, then it will be replaced by - * the filled container unless the player in in creative. - *
  • If the filled container is stackable and the player already has a - * non-maxed stack in the inventory, it is put there. - *
  • If the player has space in his inventory, it is put there. - *
  • Otherwise it will be dropped on the ground between the position given - * as parameter and the player's position. - *
- * - * @param world - * @param x - * @param y - * @param z - * @param entityPlayer - * @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 doPull(IFluidHandler into, ForgeDirection fromDir, int maxVolume) { + TileEntity te = (TileEntity) into; + BlockCoord loc = new BlockCoord(te).getLocation(fromDir); + IFluidHandler target = FluidUtil.getFluidHandler(te.getWorldObj(), loc); + if (target != null) { + FluidTankInfo[] infos = target.getTankInfo(fromDir.getOpposite()); + if (infos != null) { + for (FluidTankInfo info : infos) { + 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) { + int filled = into.fill(fromDir, drained, false); + if (filled > 0) { + drained = target.drain(fromDir.getOpposite(), filled, true); + into.fill(fromDir, drained, true); + return true; + } + } + } + } + } + } + } + return false; + } - for (FluidTank subTank : tank.getOutputTanks()) { - FluidAndStackResult fill = tryFillContainer(entityPlayer.inventory.getCurrentItem(), subTank.getFluid()); - if (fill.result.fluidStack != null) { + public static boolean doPush(IFluidHandler from, ForgeDirection fromDir, int maxVolume) { - subTank.setFluid(fill.remainder.fluidStack); - tank.setTanksDirty(); - 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); - } + TileEntity te = (TileEntity) from; + BlockCoord loc = new BlockCoord(te).getLocation(fromDir); + IFluidHandler target = getFluidHandler(te.getWorldObj(), loc); + if (target == null) { + return false; + } + FluidTankInfo[] infos = from.getTankInfo(fromDir); + boolean res = false; + if (infos != null) { + for (FluidTankInfo info : infos) { + if (info.fluid != null && info.fluid.amount > 0 && from.canDrain(fromDir, info.fluid.getFluid())) { + FluidStack maxDrain = new FluidStack(info.fluid, maxVolume); + FluidStack canDrain = from.drain(fromDir, maxDrain, false); + if (canDrain != null && canDrain.amount > 0) { + int filled = target.fill(fromDir.getOpposite(), canDrain, true); + from.drain(fromDir, new FluidStack(info.fluid, filled), true); + res |= true; + } + } + } + } + return res; + } + + public static FluidAndStackResult tryFillContainer(ItemStack target, FluidStack source) { + if (target != null && target.getItem() != null + && source != null + && source.getFluid() != null + && source.amount > 0) { + + if (target.getItem() instanceof IFluidContainerItem) { + ItemStack resultStack = target.copy(); + resultStack.stackSize = 1; + int amount = ((IFluidContainerItem) target.getItem()).fill(resultStack, source, true); + if (amount <= 0) { + return new FluidAndStackResult(null, null, target, source); + } + FluidStack resultFluid = source.copy(); + resultFluid.amount = amount; + ItemStack remainderStack = target.copy(); + remainderStack.stackSize--; + if (remainderStack.stackSize <= 0) { + remainderStack = null; + } + FluidStack remainderFluid = source.copy(); + remainderFluid.amount -= amount; + if (remainderFluid.amount <= 0) { + remainderFluid = null; + } + return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); + } + + ItemStack resultStack = FluidContainerRegistry.fillFluidContainer(source.copy(), target); + if (resultStack != null) { + FluidStack resultFluid = FluidContainerRegistry.getFluidForFilledItem(resultStack); + if (resultFluid != null) { + ItemStack remainderStack = target.copy(); + remainderStack.stackSize--; + if (remainderStack.stackSize <= 0) { + remainderStack = null; + } + FluidStack remainderFluid = source.copy(); + remainderFluid.amount -= resultFluid.amount; + if (remainderFluid.amount <= 0) { + remainderFluid = null; + } + return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); + } + } + + } + return new FluidAndStackResult(null, null, target, source); + } + + public static FluidAndStackResult tryDrainContainer(ItemStack source, FluidStack target, int capacity) { + if (source != null && source.getItem() != null) { + + int maxDrain = capacity - (target != null ? target.amount : 0); + if (source.getItem() instanceof IFluidContainerItem) { + ItemStack resultStack = source.copy(); + resultStack.stackSize = 1; + FluidStack resultFluid = ((IFluidContainerItem) source.getItem()).drain(resultStack, maxDrain, true); + if (resultFluid == null || resultFluid.amount <= 0 + || (target != null && resultFluid.getFluid() != target.getFluid())) { + return new FluidAndStackResult(null, null, source, target); + } + ItemStack remainderStack = source.copy(); + remainderStack.stackSize--; + if (remainderStack.stackSize <= 0) { + remainderStack = null; + } + FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid, 0); + remainderFluid.amount += resultFluid.amount; + return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); + } + + FluidStack resultFluid = FluidContainerRegistry.getFluidForFilledItem(source); + if (resultFluid != null && resultFluid.amount > 0 + && resultFluid.amount <= maxDrain + && (target == null || resultFluid.isFluidEqual(target))) { + 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); + // } + ItemStack remainderStack = source.copy(); + remainderStack.stackSize--; + if (remainderStack.stackSize <= 0) { + remainderStack = null; + } + FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid, 0); + remainderFluid.amount += resultFluid.amount; + return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); + } + + } + return new FluidAndStackResult(null, null, source, target); + } + + public static FluidAndStackResult tryDrainContainer(ItemStack source, ITankAccess tank) { + if (source != null && source.getItem() != null) { + + if (source.getItem() instanceof IFluidContainerItem) { + FluidStack fluid = ((IFluidContainerItem) source.getItem()).getFluid(source); + IFluidTank targetTank = fluid != null ? tank.getInputTank(fluid) : null; + if (targetTank != null) { + FluidStack target = targetTank.getFluid(); + int maxDrain = targetTank.getCapacity() - (target != null ? target.amount : 0); + ItemStack resultStack = source.copy(); + resultStack.stackSize = 1; + FluidStack resultFluid = ((IFluidContainerItem) source.getItem()) + .drain(resultStack, maxDrain, true); + if (resultFluid == null || resultFluid.amount <= 0 + || (target != null && !resultFluid.isFluidEqual(target))) { + return new FluidAndStackResult(null, null, source, target); + } + ItemStack remainderStack = source.copy(); + remainderStack.stackSize--; + if (remainderStack.stackSize <= 0) { + remainderStack = null; + } + FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid, 0); + remainderFluid.amount += resultFluid.amount; + return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); + } + } + + FluidStack resultFluid = FluidContainerRegistry.getFluidForFilledItem(source); + if (resultFluid != null && resultFluid.amount > 0) { + IFluidTank targetTank = tank.getInputTank(resultFluid); + if (targetTank != null) { + FluidStack target = targetTank.getFluid(); + int maxDrain = targetTank.getCapacity() - (target != null ? target.amount : 0); + if (resultFluid.amount <= maxDrain && (target == null || resultFluid.isFluidEqual(target))) { + ItemStack resultStack = source.getItem().getContainerItem(source); + // 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) { + remainderStack = null; + } + FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid, 0); + remainderFluid.amount += resultFluid.amount; + return new FluidAndStackResult(resultStack, resultFluid, remainderStack, remainderFluid); + } + } + } + + } + return new FluidAndStackResult(null, null, source, null); + } + + /** + * If the currently held item of the given player can be filled with the liquid in the given tank's output tank, do + * so and put the resultant filled container item where it can go. This will also drain the tank and set it to + * dirty. + * + *

+ * Cases handled for the the filled container: + * + *

    + *
  • If the stacksize of the held item is one, then it will be replaced by the filled container unless the player + * in in creative. + *
  • If the filled container is stackable and the player already has a non-maxed stack in the inventory, it is put + * there. + *
  • If the player has space in his inventory, it is put there. + *
  • Otherwise it will be dropped on the ground between the position given as parameter and the player's position. + *
+ * + * @param world + * @param x + * @param y + * @param z + * @param entityPlayer + * @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) { + + for (FluidTank subTank : tank.getOutputTanks()) { + FluidAndStackResult fill = tryFillContainer(entityPlayer.inventory.getCurrentItem(), subTank.getFluid()); + if (fill.result.fluidStack != null) { + + subTank.setFluid(fill.remainder.fluidStack); + tank.setTanksDirty(); + 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()) { + 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()) { + fill.result.itemStack.stackSize += inventoryItem.stackSize; + entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); + return true; + } + } + } + + for (int i = 0; i < entityPlayer.inventory.mainInventory.length; i++) { + if (entityPlayer.inventory.mainInventory[i] == null) { + entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); + return true; + } + } + + 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; + Util.dropItems(world, fill.result.itemStack, x0, y0, z0, true); + } + } - 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()) { - fill.result.itemStack.stackSize += inventoryItem.stackSize; - entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); return true; - } } - } + } + return false; + } - for (int i = 0; i < entityPlayer.inventory.mainInventory.length; i++) { - if (entityPlayer.inventory.mainInventory[i] == null) { - entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); - return true; + 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) { + return false; + } + + tank.getInputTank(fill.result.fluidStack).setFluid(fill.remainder.fluidStack); + tank.setTanksDirty(); + + 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 (!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; - Util.dropItems(world, fill.result.itemStack, x0, y0, z0, true); - } + if (fill.result.itemStack == null) { + return true; + } + + 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()) { + fill.result.itemStack.stackSize += inventoryItem.stackSize; + entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); + return true; + } + } + } + + for (int i = 0; i < entityPlayer.inventory.mainInventory.length; i++) { + if (entityPlayer.inventory.mainInventory[i] == null) { + entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); + return true; + } + } + + 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; + Util.dropItems(world, fill.result.itemStack, x0, y0, z0, true); + } } return true; - } - } - return false; - } - - 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) { - return false; } - tank.getInputTank(fill.result.fluidStack).setFluid(fill.remainder.fluidStack); - tank.setTanksDirty(); + public static class FluidAndStack { - 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); - } + public final FluidStack fluidStack; + public final ItemStack itemStack; - if (fill.result.itemStack == null) { - return true; - } - - 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()) { - fill.result.itemStack.stackSize += inventoryItem.stackSize; - entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); - return true; - } + public FluidAndStack(FluidStack fluidStack, ItemStack itemStack) { + this.fluidStack = fluidStack; + this.itemStack = itemStack; } - } - for (int i = 0; i < entityPlayer.inventory.mainInventory.length; i++) { - if (entityPlayer.inventory.mainInventory[i] == null) { - entityPlayer.inventory.setInventorySlotContents(i, fill.result.itemStack); - return true; + public FluidAndStack(ItemStack itemStack, FluidStack fluidStack) { + this.fluidStack = fluidStack; + this.itemStack = itemStack; } - } - - 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; - Util.dropItems(world, fill.result.itemStack, x0, y0, z0, true); - } } - return true; - } + public static class FluidAndStackResult { - public static class FluidAndStack { - public final FluidStack fluidStack; - public final ItemStack itemStack; + public final FluidAndStack result; + public final FluidAndStack remainder; - public FluidAndStack(FluidStack fluidStack, ItemStack itemStack) { - this.fluidStack = fluidStack; - this.itemStack = itemStack; + public FluidAndStackResult(FluidAndStack result, FluidAndStack remainder) { + this.result = result; + this.remainder = remainder; + } + + 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) { + this.result = new FluidAndStack(fluidStackResult, itemStackResult); + this.remainder = new FluidAndStack(fluidStackRemainder, itemStackRemainder); + } } - public FluidAndStack(ItemStack itemStack, FluidStack fluidStack) { - this.fluidStack = fluidStack; - this.itemStack = itemStack; - } - } - - public static class FluidAndStackResult { - public final FluidAndStack result; - public final FluidAndStack remainder; - - public FluidAndStackResult(FluidAndStack result, FluidAndStack remainder) { - this.result = result; - this.remainder = remainder; - } - - 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) { - 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 c621dea..cd3e005 100644 --- a/src/main/java/com/enderio/core/common/util/ForgeDirectionOffsets.java +++ b/src/main/java/com/enderio/core/common/util/ForgeDirectionOffsets.java @@ -6,55 +6,54 @@ import com.enderio.core.common.vecmath.Vector3d; public final class ForgeDirectionOffsets { - public static final Vector3d[] OFFSETS = new Vector3d[ForgeDirection.values().length]; + public static final Vector3d[] OFFSETS = new Vector3d[ForgeDirection.values().length]; - static { - for (ForgeDirection dir : ForgeDirection.values()) { - OFFSETS[dir.ordinal()] = new Vector3d(dir.offsetX, dir.offsetY, dir.offsetZ); + static { + for (ForgeDirection dir : ForgeDirection.values()) { + OFFSETS[dir.ordinal()] = new Vector3d(dir.offsetX, dir.offsetY, dir.offsetZ); + } } - } - public static Vector3d forDir(ForgeDirection dir) { - return OFFSETS[dir.ordinal()]; - } - - public static Vector3d forDirCopy(ForgeDirection dir) { - return new Vector3d(OFFSETS[dir.ordinal()]); - } - - public static Vector3d offsetScaled(ForgeDirection dir, double scale) { - Vector3d res = forDirCopy(dir); - res.scale(scale); - return res; - } - - public static Vector3d absolueOffset(ForgeDirection dir) { - Vector3d res = forDirCopy(dir); - res.x = Math.abs(res.x); - res.y = Math.abs(res.y); - res.z = Math.abs(res.z); - return res; - } - - public ForgeDirection closest(float x, float y, float z) { - float ax = Math.abs(x); - float ay = Math.abs(y); - float az = Math.abs(z); - - if (ax >= ay && ax >= az) { - return x > 0 ? ForgeDirection.EAST : ForgeDirection.WEST; + public static Vector3d forDir(ForgeDirection dir) { + return OFFSETS[dir.ordinal()]; } - if (ay >= ax && ay >= az) { - return y > 0 ? ForgeDirection.UP : ForgeDirection.DOWN; + + public static Vector3d forDirCopy(ForgeDirection dir) { + return new Vector3d(OFFSETS[dir.ordinal()]); } - return z > 0 ? ForgeDirection.SOUTH : ForgeDirection.NORTH; - } - private ForgeDirectionOffsets() { - } + public static Vector3d offsetScaled(ForgeDirection dir, double scale) { + Vector3d res = forDirCopy(dir); + res.scale(scale); + return res; + } - public static boolean isPositiveOffset(ForgeDirection dir) { - return dir == ForgeDirection.SOUTH || dir == ForgeDirection.EAST || dir == ForgeDirection.UP; - } + public static Vector3d absolueOffset(ForgeDirection dir) { + Vector3d res = forDirCopy(dir); + res.x = Math.abs(res.x); + res.y = Math.abs(res.y); + res.z = Math.abs(res.z); + return res; + } + + public ForgeDirection closest(float x, float y, float z) { + float ax = Math.abs(x); + float ay = Math.abs(y); + float az = Math.abs(z); + + if (ax >= ay && ax >= az) { + return x > 0 ? ForgeDirection.EAST : ForgeDirection.WEST; + } + if (ay >= ax && ay >= az) { + return y > 0 ? ForgeDirection.UP : ForgeDirection.DOWN; + } + return z > 0 ? ForgeDirection.SOUTH : ForgeDirection.NORTH; + } + + private ForgeDirectionOffsets() {} + + public static boolean isPositiveOffset(ForgeDirection dir) { + return dir == ForgeDirection.SOUTH || dir == ForgeDirection.EAST || dir == ForgeDirection.UP; + } } diff --git a/src/main/java/com/enderio/core/common/util/IBlockAccessWrapper.java b/src/main/java/com/enderio/core/common/util/IBlockAccessWrapper.java index 3610170..2716382 100644 --- a/src/main/java/com/enderio/core/common/util/IBlockAccessWrapper.java +++ b/src/main/java/com/enderio/core/common/util/IBlockAccessWrapper.java @@ -5,74 +5,75 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.util.ForgeDirection; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class IBlockAccessWrapper implements IBlockAccess { - protected IBlockAccess wrapped; + protected IBlockAccess wrapped; - public IBlockAccessWrapper(IBlockAccess ba) { - wrapped = ba; - } - - @Override - public boolean isSideSolid(int x, int y, int z, ForgeDirection side, boolean _default) { - return wrapped.isSideSolid(x, y, z, side, _default); - } - - @Override - public int isBlockProvidingPowerTo(int var1, int var2, int var3, int var4) { - return wrapped.isBlockProvidingPowerTo(var1, var2, var3, var4); - } - - @Override - public boolean isAirBlock(int var1, int var2, int var3) { - return wrapped.isAirBlock(var1, var2, var3); - } - - @Override - public TileEntity getTileEntity(int var1, int var2, int var3) { - if (var2 >= 0 && var2 < 256) { - return wrapped.getTileEntity(var1, var2, var3); - } else { - return null; + public IBlockAccessWrapper(IBlockAccess ba) { + wrapped = ba; } - } - @Override - @SideOnly(Side.CLIENT) - public int getLightBrightnessForSkyBlocks(int var1, int var2, int var3, int var4) { - return 15 << 20 | 15 << 4; - } + @Override + public boolean isSideSolid(int x, int y, int z, ForgeDirection side, boolean _default) { + return wrapped.isSideSolid(x, y, z, side, _default); + } - @Override - @SideOnly(Side.CLIENT) - public int getHeight() { - return wrapped.getHeight(); - } + @Override + public int isBlockProvidingPowerTo(int var1, int var2, int var3, int var4) { + return wrapped.isBlockProvidingPowerTo(var1, var2, var3, var4); + } - @Override - public int getBlockMetadata(int var1, int var2, int var3) { - return wrapped.getBlockMetadata(var1, var2, var3); - } + @Override + public boolean isAirBlock(int var1, int var2, int var3) { + return wrapped.isAirBlock(var1, var2, var3); + } - @Override - public Block getBlock(int var1, int var2, int var3) { - return wrapped.getBlock(var1, var2, var3); - } + @Override + public TileEntity getTileEntity(int var1, int var2, int var3) { + if (var2 >= 0 && var2 < 256) { + return wrapped.getTileEntity(var1, var2, var3); + } else { + return null; + } + } - @Override - @SideOnly(Side.CLIENT) - public BiomeGenBase getBiomeGenForCoords(int var1, int var2) { + @Override + @SideOnly(Side.CLIENT) + public int getLightBrightnessForSkyBlocks(int var1, int var2, int var3, int var4) { + return 15 << 20 | 15 << 4; + } - return wrapped.getBiomeGenForCoords(var1, var2); - } + @Override + @SideOnly(Side.CLIENT) + public int getHeight() { + return wrapped.getHeight(); + } - @Override - @SideOnly(Side.CLIENT) - public boolean extendedLevelsInChunkCache() { - return wrapped.extendedLevelsInChunkCache(); - } + @Override + public int getBlockMetadata(int var1, int var2, int var3) { + return wrapped.getBlockMetadata(var1, var2, var3); + } + + @Override + public Block getBlock(int var1, int var2, int var3) { + return wrapped.getBlock(var1, var2, var3); + } + + @Override + @SideOnly(Side.CLIENT) + public BiomeGenBase getBiomeGenForCoords(int var1, int var2) { + + return wrapped.getBiomeGenForCoords(var1, var2); + } + + @Override + @SideOnly(Side.CLIENT) + public boolean extendedLevelsInChunkCache() { + return wrapped.extendedLevelsInChunkCache(); + } } 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 6f7a528..237e496 100644 --- a/src/main/java/com/enderio/core/common/util/InventoryWrapper.java +++ b/src/main/java/com/enderio/core/common/util/InventoryWrapper.java @@ -7,112 +7,112 @@ import net.minecraft.item.ItemStack; public class InventoryWrapper implements ISidedInventory { - public static ISidedInventory asSidedInventory(IInventory inv) { - if (inv == null) { - return null; + public static ISidedInventory asSidedInventory(IInventory inv) { + if (inv == null) { + return null; + } + if (inv instanceof ISidedInventory) { + return (ISidedInventory) inv; + } + return new InventoryWrapper(inv); } - if (inv instanceof ISidedInventory) { - return (ISidedInventory) inv; + + private IInventory inv; + + public InventoryWrapper(IInventory inventory) { + this.inv = ItemUtil.getInventory(inventory); } - return new InventoryWrapper(inv); - } - private IInventory inv; - - public InventoryWrapper(IInventory inventory) { - this.inv = ItemUtil.getInventory(inventory); - } - - public IInventory getWrappedInv() { - return inv; - } - - @Override - public int getSizeInventory() { - return inv.getSizeInventory(); - } - - @Override - public ItemStack getStackInSlot(int slot) { - if (slot < 0 || slot >= inv.getSizeInventory()) { - return null; + public IInventory getWrappedInv() { + return inv; } - return inv.getStackInSlot(slot); - } - @Override - public ItemStack decrStackSize(int slot, int amount) { - return inv.decrStackSize(slot, amount); - } - - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - return inv.getStackInSlotOnClosing(slot); - } - - @Override - public void setInventorySlotContents(int slot, ItemStack itemStack) { - if (slot >= 0 && slot < inv.getSizeInventory()) { - inv.setInventorySlotContents(slot, itemStack); + @Override + public int getSizeInventory() { + return inv.getSizeInventory(); } - } - @Override - public String getInventoryName() { - return inv.getInventoryName(); - } - - @Override - public int getInventoryStackLimit() { - return inv.getInventoryStackLimit(); - } - - @Override - public void markDirty() { - inv.markDirty(); - } - - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return inv.isUseableByPlayer(entityplayer); - } - - @Override - public void openInventory() { - inv.openInventory(); - } - - @Override - public void closeInventory() { - inv.closeInventory(); - } - - @Override - public boolean isItemValidForSlot(int slot, ItemStack itemStack) { - return slot >= 0 && slot < getSizeInventory() && inv.isItemValidForSlot(slot, itemStack); - } - - @Override - public int[] getAccessibleSlotsFromSide(int var1) { - int[] slots = new int[inv.getSizeInventory()]; - for (int i = 0; i < slots.length; i++) { - slots[i] = i; + @Override + public ItemStack getStackInSlot(int slot) { + if (slot < 0 || slot >= inv.getSizeInventory()) { + return null; + } + return inv.getStackInSlot(slot); } - return slots; - } - @Override - public boolean canInsertItem(int slot, ItemStack itemStack, int side) { - return isItemValidForSlot(slot, itemStack); - } + @Override + public ItemStack decrStackSize(int slot, int amount) { + return inv.decrStackSize(slot, amount); + } - @Override - public boolean canExtractItem(int slot, ItemStack itemStack, int side) { - return slot >= 0 && slot < getSizeInventory(); - } + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return inv.getStackInSlotOnClosing(slot); + } - @Override - public boolean hasCustomInventoryName() { - return false; - } -} \ No newline at end of file + @Override + public void setInventorySlotContents(int slot, ItemStack itemStack) { + if (slot >= 0 && slot < inv.getSizeInventory()) { + inv.setInventorySlotContents(slot, itemStack); + } + } + + @Override + public String getInventoryName() { + return inv.getInventoryName(); + } + + @Override + public int getInventoryStackLimit() { + return inv.getInventoryStackLimit(); + } + + @Override + public void markDirty() { + inv.markDirty(); + } + + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return inv.isUseableByPlayer(entityplayer); + } + + @Override + public void openInventory() { + inv.openInventory(); + } + + @Override + public void closeInventory() { + inv.closeInventory(); + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack itemStack) { + return slot >= 0 && slot < getSizeInventory() && inv.isItemValidForSlot(slot, itemStack); + } + + @Override + public int[] getAccessibleSlotsFromSide(int var1) { + int[] slots = new int[inv.getSizeInventory()]; + for (int i = 0; i < slots.length; i++) { + slots[i] = i; + } + return slots; + } + + @Override + public boolean canInsertItem(int slot, ItemStack itemStack, int side) { + return isItemValidForSlot(slot, itemStack); + } + + @Override + public boolean canExtractItem(int slot, ItemStack itemStack, int side) { + return slot >= 0 && slot < getSizeInventory(); + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } +} 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 ce4de02..a83d65e 100755 --- a/src/main/java/com/enderio/core/common/util/ItemUtil.java +++ b/src/main/java/com/enderio/core/common/util/ItemUtil.java @@ -4,9 +4,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; -import com.enderio.core.EnderCore; -import com.enderio.core.api.common.util.IItemReceptor; - import net.minecraft.block.Block; import net.minecraft.entity.item.EntityItem; import net.minecraft.inventory.IInventory; @@ -24,531 +21,534 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; + import cofh.api.transport.IItemDuct; + +import com.enderio.core.EnderCore; +import com.enderio.core.api.common.util.IItemReceptor; import cpw.mods.fml.common.Loader; public class ItemUtil { - public static final List receptors = new ArrayList(); - private static final Random rand = new Random(); + public static final List receptors = new ArrayList(); + private static final Random rand = new Random(); - static { - try { - Class.forName("crazypants.util.BuildcraftUtil"); - } catch (Exception e) { - if (Loader.isModLoaded("BuildCraft|Transport")) { - Log.warn("ItemUtil: Could not register Build Craft pipe handler. Machines will not be able to output to BC pipes."); - } //Don't log if BC isn't installed, but we still check in case another mod is using their API - } - } - - /** - * Turns a String into an item that can be used in a recipe. This is one of: - *
    - *
  • String
  • - *
  • Item
  • - *
  • Block
  • - *
  • ItemStack
  • - *
- * Because this method can return a String, it is highly recommended that you - * use the result in a {@link ShapedOreRecipe} or {@link ShapelessOreRecipe}. - * - * @param string - * The String to parse. - * @return An object for use in recipes. - */ - public static Object parseStringIntoRecipeItem(String string) { - return parseStringIntoRecipeItem(string, false); - } - - /** - * Turns a String into an item that can be used in a recipe. This is one of: - *
    - *
  • String
  • - *
  • Item
  • - *
  • Block
  • - *
  • ItemStack
  • - *
- * Because this method can return a String, it is highly recommended that you - * use the result in a {@link ShapedOreRecipe} or {@link ShapelessOreRecipe}. - * - * @see #parseStringIntoItemStack(String) - * @param string - * The String to parse. - * @param forceItemStack - * True if the result should be forced to be an ItemStack. - * @return AN object for use in recipes. - */ - public static Object parseStringIntoRecipeItem(String string, boolean forceItemStack) { - if ("null".equals(string)) { - return null; - } else if (OreDictionary.getOres(string).isEmpty()) { - ItemStack stack = null; - - String[] info = string.split(";"); - Object temp = null; - int damage = OreDictionary.WILDCARD_VALUE; - temp = Item.itemRegistry.getObject(info[0]); - if (info.length > 1) { - damage = Integer.parseInt(info[1]); - } - - if (temp instanceof Item) { - stack = new ItemStack((Item) temp, 1, damage); - } else if (temp instanceof Block) { - stack = new ItemStack((Block) temp, 1, damage); - } else if (temp instanceof ItemStack) { - stack = ((ItemStack) temp).copy(); - stack.setItemDamage(damage); - } else { - throw new IllegalArgumentException(string - + " is not a vaild string. Strings should be either an oredict name, or in the format objectname;damage (damage is optional)"); - } - - return stack; - } else if (forceItemStack) { - return OreDictionary.getOres(string).get(0).copy(); - } else { - return string; - } - } - - /** - * Turns a string into an ItemStack. - *

- * This is basically a convenience method that casts the result of - * {@link #parseStringIntoRecipeItem(String, boolean)}, but with one extra - * feature. - *

- * A '#' character may be used at the end of the string to signify stack size, - * e.g. "minecraft:diamond#2" would be a stack of 2 diamonds. - *

- * The stack size will automatically be clamped to be below the give Item's - * max stack size. - * - * @param string - * The String to parse. - * @return An ItemStack the string represents. - */ - public static ItemStack parseStringIntoItemStack(String string) { - int size = 1; - int numIdx = string.indexOf('#'); - int nbtIdx = string.indexOf('$'); - - NBTTagCompound tag = null; - - if (numIdx > -1) { - String num = string.substring(numIdx + 1, nbtIdx == -1 ? string.length() : nbtIdx); - - try { - size = Integer.parseInt(num); - } catch (NumberFormatException e) { - throw new IllegalArgumentException(num + " is not a valid stack size", e); - } - - string = string.replace('#' + num, ""); - nbtIdx -= num.length() + 1; - } - - if (nbtIdx > -1) { - String nbt = string.substring(nbtIdx + 1); - try { - tag = (NBTTagCompound) JsonToNBT.func_150315_a(nbt); - } catch (NBTException e) { - throw new IllegalArgumentException(nbt + " is not valid NBT json.", e); - } - - string = string.replace('$' + nbt, ""); + static { + try { + Class.forName("crazypants.util.BuildcraftUtil"); + } catch (Exception e) { + if (Loader.isModLoaded("BuildCraft|Transport")) { + Log.warn( + "ItemUtil: Could not register Build Craft pipe handler. Machines will not be able to output to BC pipes."); + } // Don't log if BC isn't installed, but we still check in case another mod is using their API + } } - ItemStack stack = (ItemStack) parseStringIntoRecipeItem(string, true); - stack.stackSize = MathHelper.clamp_int(size, 1, stack.getMaxStackSize()); - stack.setTagCompound(tag); - return stack; - } - - /** - * Returns the appropriate config string for the given {@link ItemStack} - *

- * This does not take into account ore dict. - * - * @param stack - * The {@link ItemStack} to serialize - * @param damage - * If damage should be taken into account - * @param size - * If stack size should be taken into account - * @return A string that will be the equivalent of if {@link ItemStack stack} - * was constructed from it using - * {@link #parseStringIntoItemStack(String)} - */ - public static String getStringForItemStack(ItemStack stack, boolean damage, boolean size) { - if (stack == null) { - return null; + /** + * Turns a String into an item that can be used in a recipe. This is one of: + *

    + *
  • String
  • + *
  • Item
  • + *
  • Block
  • + *
  • ItemStack
  • + *
+ * Because this method can return a String, it is highly recommended that you use the result in a + * {@link ShapedOreRecipe} or {@link ShapelessOreRecipe}. + * + * @param string The String to parse. + * @return An object for use in recipes. + */ + public static Object parseStringIntoRecipeItem(String string) { + return parseStringIntoRecipeItem(string, false); } - String base = Item.itemRegistry.getNameForObject(stack.getItem()); + /** + * Turns a String into an item that can be used in a recipe. This is one of: + *
    + *
  • String
  • + *
  • Item
  • + *
  • Block
  • + *
  • ItemStack
  • + *
+ * Because this method can return a String, it is highly recommended that you use the result in a + * {@link ShapedOreRecipe} or {@link ShapelessOreRecipe}. + * + * @see #parseStringIntoItemStack(String) + * @param string The String to parse. + * @param forceItemStack True if the result should be forced to be an ItemStack. + * @return AN object for use in recipes. + */ + public static Object parseStringIntoRecipeItem(String string, boolean forceItemStack) { + if ("null".equals(string)) { + return null; + } else if (OreDictionary.getOres(string).isEmpty()) { + ItemStack stack = null; - if (damage) { - base += ";" + stack.getItemDamage(); - } - - if (size) { - base += "#" + stack.stackSize; - } - - return base; - } - - /** - * Tests if two {@link ItemStack}s are completely equal, forgoing stack size. - * This means that for this method to return true, Item type, damage value, - * and NBT data of both ItemStacks must be identical. - * - * @param s1 - * The first ItemStack to compare. - * @param s2 - * The second ItemStack to compare. - * @author powercrystals - */ - public static boolean stacksEqual(ItemStack s1, ItemStack s2) { - if (s1 == null && s2 == null) - return true; - if (s1 == null || s2 == null) - return false; - if (!s1.isItemEqual(s2)) - return false; - if (s1.getTagCompound() == null && s2.getTagCompound() == null) - return true; - if (s1.getTagCompound() == null || s2.getTagCompound() == null) - return false; - return s1.getTagCompound().equals(s2.getTagCompound()); - } - - /** - * Spawns an ItemStack into the world with motion that simulates a normal - * block drop. - * - * @param world - * The world object. - * @param item - * The ItemStack to spawn. - * @param x - * X coordinate of the block in which to spawn the entity. - * @param y - * Y coordinate of the block in which to spawn the entity. - * @param z - * Z coordinate of the block in which to spawn the entity. - */ - public static void spawnItemInWorldWithRandomMotion(World world, ItemStack item, int x, int y, int z) { - if (item != null) { - spawnItemInWorldWithRandomMotion(new EntityItem(world, x + 0.5, y + 0.5, z + 0.5, item)); - } - } - - /** - * Spawns an EntityItem into the world with motion that simulates a normal - * block drop. - * - * @param entity - * The entity to spawn. - */ - public static void spawnItemInWorldWithRandomMotion(EntityItem entity) { - entity.delayBeforeCanPickup = 10; - - float f = (rand.nextFloat() * 0.1f) - 0.05f; - float f1 = (rand.nextFloat() * 0.1f) - 0.05f; - float f2 = (rand.nextFloat() * 0.1f) - 0.05f; - - entity.motionX += f; - entity.motionY += f1; - entity.motionZ += f2; - - entity.worldObj.spawnEntityInWorld(entity); - } - - /** - * Returns true if the given stack has the given Ore Dictionary name applied - * to it. - * - * @param stack - * The ItemStack to check. - * @param oredict - * The oredict name. - * @return True if the ItemStack matches the name passed. - */ - public static boolean itemStackMatchesOredict(ItemStack stack, String oredict) { - int[] ids = OreDictionary.getOreIDs(stack); - for (int i : ids) { - String name = OreDictionary.getOreName(i); - if (name.equals(oredict)) { - return true; - } - } - return false; - } - - /** - * Gets an NBT tag from an ItemStack, creating it if needed. The tag returned - * will always be the same as the one on the stack. - * - * @param stack - * The ItemStack to get the tag from. - * @return An NBTTagCompound from the stack. - */ - public static NBTTagCompound getNBTTag(ItemStack stack) { - if (!stack.hasTagCompound()) { - stack.stackTagCompound = new NBTTagCompound(); - } - return stack.stackTagCompound; - } - - public static String getDurabilityString(ItemStack item) { - if (item == null) { - return null; - } - return EnderCore.lang.localize("tooltip.durability") + " " + (item.getMaxDamage() - item.getItemDamage()) + "/" + item.getMaxDamage(); - } - - public static NBTTagCompound getOrCreateNBT(ItemStack stack) { - if (stack.stackTagCompound == null) { - stack.stackTagCompound = new NBTTagCompound(); - } - return stack.stackTagCompound; - } - - public static int doInsertItem(Object into, ItemStack item, ForgeDirection side) { - if (into == null || item == null) { - return 0; - } - if (into instanceof ISidedInventory) { - return ItemUtil.doInsertItemInv((ISidedInventory) into, item, side, true); - } else if (into instanceof IInventory) { - return ItemUtil.doInsertItemInv(getInventory((IInventory) into), item, side, true); - } else if (into instanceof IItemDuct) { - return ItemUtil.doInsertItem((IItemDuct) into, item, side); - } - - for (IItemReceptor rec : receptors) { - if (rec.canInsertIntoObject(into, side)) { - return rec.doInsertItem(into, item, side); - } - } - - return 0; - } - - public static int doInsertItem(IItemDuct con, ItemStack item, ForgeDirection inventorySide) { - int startedWith = item.stackSize; - ItemStack remaining = con.insertItem(inventorySide, item); - if (remaining == null) { - return startedWith; - } - return startedWith - remaining.stackSize; - } - - public static int doInsertItem(IInventory inv, int startSlot, int endSlot, ItemStack item) { - return doInsertItemInv(inv, null, invSlotter.getInstance(startSlot, endSlot), item, ForgeDirection.UNKNOWN, true); - } - - public static int doInsertItem(IInventory inv, int startSlot, int endSlot, ItemStack item, boolean doInsert) { - return doInsertItemInv(inv, null, invSlotter.getInstance(startSlot, endSlot), item, ForgeDirection.UNKNOWN, doInsert); - } - - /* - * Insert items into an IInventory or an ISidedInventory. - */ - private static int doInsertItemInv(IInventory inv, ItemStack item, ForgeDirection inventorySide, boolean doInsert) { - final ISidedInventory sidedInv = inv instanceof ISidedInventory ? (ISidedInventory) inv : null; - ISlotIterator slots; - - if (sidedInv != null) { - if (inventorySide == null) { - inventorySide = ForgeDirection.UNKNOWN; - } - // Note: This is not thread-safe. Change to getInstance() to constructor when needed (1.8++?). - slots = sidedSlotter.getInstance(sidedInv.getAccessibleSlotsFromSide(inventorySide.ordinal())); - } else { - slots = invSlotter.getInstance(0, inv.getSizeInventory()); - } - - return doInsertItemInv(inv, sidedInv, slots, item, inventorySide, 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; - - // PASS1: Try to add to an existing stack - while (numToInsert > 0 && slots.hasNext()) { - final int slot = slots.nextSlot(); - if (sidedInv == null || sidedInv.canInsertItem(slot, item, inventorySide.ordinal())) { - final ItemStack contents = inv.getStackInSlot(slot); - if (contents != null) { - if (areStackMergable(contents, item)) { - final int freeSpace = Math.min(inv.getInventoryStackLimit(), contents.getMaxStackSize()) - contents.stackSize; // some inventories like using itemstacks with invalid stack sizes - if (freeSpace > 0) { - final int noToInsert = Math.min(numToInsert, freeSpace); - final ItemStack toInsert = item.copy(); - toInsert.stackSize = contents.stackSize + noToInsert; - // isItemValidForSlot() may check the stacksize, so give it the number the stack would have in the end. - // If it does something funny, like "only even numbers", we are screwed. - if (sidedInv != null || inv.isItemValidForSlot(slot, toInsert)) { - numInserted += noToInsert; - numToInsert -= noToInsert; - if (doInsert) { - inv.setInventorySlotContents(slot, toInsert); - } - } + String[] info = string.split(";"); + Object temp = null; + int damage = OreDictionary.WILDCARD_VALUE; + temp = Item.itemRegistry.getObject(info[0]); + if (info.length > 1) { + damage = Integer.parseInt(info[1]); } - } - } else if (firstFreeSlot == -1) { - firstFreeSlot = slot; - } - } - } - // PASS2: Try to insert into an empty slot - if (numToInsert > 0 && firstFreeSlot != -1) { - final ItemStack toInsert = item.copy(); - toInsert.stackSize = min(numToInsert, inv.getInventoryStackLimit(), toInsert.getMaxStackSize()); // some inventories like using itemstacks with invalid stack sizes - if (sidedInv != null || inv.isItemValidForSlot(firstFreeSlot, toInsert)) { - numInserted += toInsert.stackSize; - numToInsert -= toInsert.stackSize; - if (doInsert) { - inv.setInventorySlotContents(firstFreeSlot, toInsert); - } - } - } + if (temp instanceof Item) { + stack = new ItemStack((Item) temp, 1, damage); + } else if (temp instanceof Block) { + stack = new ItemStack((Block) temp, 1, damage); + } else if (temp instanceof ItemStack) { + stack = ((ItemStack) temp).copy(); + stack.setItemDamage(damage); + } else { + throw new IllegalArgumentException( + string + " is not a vaild string. Strings should be either an oredict name, or in the format objectname;damage (damage is optional)"); + } - if (numInserted > 0 && doInsert) { - inv.markDirty(); - } - return numInserted; - } - - private final static int min(int i1, int i2, int i3) { - return i1 < i2 ? (i1 < i3 ? i1 : i3) : (i2 < i3 ? i2 : i3); - } - - public static boolean isStackFull(ItemStack contents) { - if (contents == null) { - return false; - } - return contents.stackSize >= contents.getMaxStackSize(); - } - - public static IInventory getInventory(IInventory inv) { - if (inv instanceof TileEntityChest) { - TileEntityChest chest = (TileEntityChest) inv; - TileEntityChest neighbour = null; - boolean reverse = false; - if (chest.adjacentChestXNeg != null) { - neighbour = chest.adjacentChestXNeg; - reverse = true; - } else if (chest.adjacentChestXPos != null) { - neighbour = chest.adjacentChestXPos; - } else if (chest.adjacentChestZNeg != null) { - neighbour = chest.adjacentChestZNeg; - reverse = true; - } else if (chest.adjacentChestZPos != null) { - neighbour = chest.adjacentChestZPos; - } - if (neighbour != null) { - if (reverse) { - return new InventoryLargeChest("", neighbour, inv); + return stack; + } else if (forceItemStack) { + return OreDictionary.getOres(string).get(0).copy(); } else { - return new InventoryLargeChest("", inv, neighbour); + return string; } - } - } - return inv; - } - - /** - * Checks if items, damage and NBT are equal and the items are stackable. - * - * @param s1 - * @param s2 - * @return True if the two stacks are mergeable, false otherwise. - */ - public static boolean areStackMergable(ItemStack s1, ItemStack s2) { - if (s1 == null || s2 == null || !s1.isStackable() || !s2.isStackable()) { - return false; - } - if (!s1.isItemEqual(s2)) { - return false; - } - return ItemStack.areItemStackTagsEqual(s1, s2); - } - - /** - * Checks if items, damage and NBT are equal. - * - * @param s1 - * @param s2 - * @return True if the two stacks are equal, false otherwise. - */ - public static boolean areStacksEqual(ItemStack s1, ItemStack s2) { - if (s1 == null || s2 == null) { - return false; - } - if (!s1.isItemEqual(s2)) { - return false; - } - return ItemStack.areItemStackTagsEqual(s1, s2); - } - - private interface ISlotIterator { - int nextSlot(); - - boolean hasNext(); - } - - private final static class invSlotter implements ISlotIterator { - private static final invSlotter me = new invSlotter(); - private int end; - private int current; - - public final static invSlotter getInstance(int start, int end) { - me.end = end; - me.current = start; - return me; } - @Override - public final int nextSlot() { - return current++; + /** + * Turns a string into an ItemStack. + *

+ * This is basically a convenience method that casts the result of + * {@link #parseStringIntoRecipeItem(String, boolean)}, but with one extra feature. + *

+ * A '#' character may be used at the end of the string to signify stack size, e.g. "minecraft:diamond#2" would be a + * stack of 2 diamonds. + *

+ * The stack size will automatically be clamped to be below the give Item's max stack size. + * + * @param string The String to parse. + * @return An ItemStack the string represents. + */ + public static ItemStack parseStringIntoItemStack(String string) { + int size = 1; + int numIdx = string.indexOf('#'); + int nbtIdx = string.indexOf('$'); + + NBTTagCompound tag = null; + + if (numIdx > -1) { + String num = string.substring(numIdx + 1, nbtIdx == -1 ? string.length() : nbtIdx); + + try { + size = Integer.parseInt(num); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(num + " is not a valid stack size", e); + } + + string = string.replace('#' + num, ""); + nbtIdx -= num.length() + 1; + } + + if (nbtIdx > -1) { + String nbt = string.substring(nbtIdx + 1); + try { + tag = (NBTTagCompound) JsonToNBT.func_150315_a(nbt); + } catch (NBTException e) { + throw new IllegalArgumentException(nbt + " is not valid NBT json.", e); + } + + string = string.replace('$' + nbt, ""); + } + + ItemStack stack = (ItemStack) parseStringIntoRecipeItem(string, true); + stack.stackSize = MathHelper.clamp_int(size, 1, stack.getMaxStackSize()); + stack.setTagCompound(tag); + return stack; } - @Override - public final boolean hasNext() { - return current < end; - } - } + /** + * Returns the appropriate config string for the given {@link ItemStack} + *

+ * This does not take into account ore dict. + * + * @param stack The {@link ItemStack} to serialize + * @param damage If damage should be taken into account + * @param size If stack size should be taken into account + * @return A string that will be the equivalent of if {@link ItemStack stack} was constructed from it using + * {@link #parseStringIntoItemStack(String)} + */ + public static String getStringForItemStack(ItemStack stack, boolean damage, boolean size) { + if (stack == null) { + return null; + } - private final static class sidedSlotter implements ISlotIterator { - private static final sidedSlotter me = new sidedSlotter(); - private int[] slots; - private int current; + String base = Item.itemRegistry.getNameForObject(stack.getItem()); - public final static sidedSlotter getInstance(int[] slots) { - me.slots = slots; - me.current = 0; - return me; + if (damage) { + base += ";" + stack.getItemDamage(); + } + + if (size) { + base += "#" + stack.stackSize; + } + + return base; } - @Override - public final int nextSlot() { - return slots[current++]; + /** + * Tests if two {@link ItemStack}s are completely equal, forgoing stack size. This means that for this method to + * return true, Item type, damage value, and NBT data of both ItemStacks must be identical. + * + * @param s1 The first ItemStack to compare. + * @param s2 The second ItemStack to compare. + * @author powercrystals + */ + public static boolean stacksEqual(ItemStack s1, ItemStack s2) { + if (s1 == null && s2 == null) return true; + if (s1 == null || s2 == null) return false; + if (!s1.isItemEqual(s2)) return false; + if (s1.getTagCompound() == null && s2.getTagCompound() == null) return true; + if (s1.getTagCompound() == null || s2.getTagCompound() == null) return false; + return s1.getTagCompound().equals(s2.getTagCompound()); } - @Override - public final boolean hasNext() { - return slots != null && current < slots.length; + /** + * Spawns an ItemStack into the world with motion that simulates a normal block drop. + * + * @param world The world object. + * @param item The ItemStack to spawn. + * @param x X coordinate of the block in which to spawn the entity. + * @param y Y coordinate of the block in which to spawn the entity. + * @param z Z coordinate of the block in which to spawn the entity. + */ + public static void spawnItemInWorldWithRandomMotion(World world, ItemStack item, int x, int y, int z) { + if (item != null) { + spawnItemInWorldWithRandomMotion(new EntityItem(world, x + 0.5, y + 0.5, z + 0.5, item)); + } + } + + /** + * Spawns an EntityItem into the world with motion that simulates a normal block drop. + * + * @param entity The entity to spawn. + */ + public static void spawnItemInWorldWithRandomMotion(EntityItem entity) { + entity.delayBeforeCanPickup = 10; + + float f = (rand.nextFloat() * 0.1f) - 0.05f; + float f1 = (rand.nextFloat() * 0.1f) - 0.05f; + float f2 = (rand.nextFloat() * 0.1f) - 0.05f; + + entity.motionX += f; + entity.motionY += f1; + entity.motionZ += f2; + + entity.worldObj.spawnEntityInWorld(entity); + } + + /** + * Returns true if the given stack has the given Ore Dictionary name applied to it. + * + * @param stack The ItemStack to check. + * @param oredict The oredict name. + * @return True if the ItemStack matches the name passed. + */ + public static boolean itemStackMatchesOredict(ItemStack stack, String oredict) { + int[] ids = OreDictionary.getOreIDs(stack); + for (int i : ids) { + String name = OreDictionary.getOreName(i); + if (name.equals(oredict)) { + return true; + } + } + return false; + } + + /** + * Gets an NBT tag from an ItemStack, creating it if needed. The tag returned will always be the same as the one on + * the stack. + * + * @param stack The ItemStack to get the tag from. + * @return An NBTTagCompound from the stack. + */ + public static NBTTagCompound getNBTTag(ItemStack stack) { + if (!stack.hasTagCompound()) { + stack.stackTagCompound = new NBTTagCompound(); + } + return stack.stackTagCompound; + } + + public static String getDurabilityString(ItemStack item) { + if (item == null) { + return null; + } + return EnderCore.lang.localize("tooltip.durability") + " " + + (item.getMaxDamage() - item.getItemDamage()) + + "/" + + item.getMaxDamage(); + } + + public static NBTTagCompound getOrCreateNBT(ItemStack stack) { + if (stack.stackTagCompound == null) { + stack.stackTagCompound = new NBTTagCompound(); + } + return stack.stackTagCompound; + } + + public static int doInsertItem(Object into, ItemStack item, ForgeDirection side) { + if (into == null || item == null) { + return 0; + } + if (into instanceof ISidedInventory) { + return ItemUtil.doInsertItemInv((ISidedInventory) into, item, side, true); + } else if (into instanceof IInventory) { + return ItemUtil.doInsertItemInv(getInventory((IInventory) into), item, side, true); + } else if (into instanceof IItemDuct) { + return ItemUtil.doInsertItem((IItemDuct) into, item, side); + } + + for (IItemReceptor rec : receptors) { + if (rec.canInsertIntoObject(into, side)) { + return rec.doInsertItem(into, item, side); + } + } + + return 0; + } + + public static int doInsertItem(IItemDuct con, ItemStack item, ForgeDirection inventorySide) { + int startedWith = item.stackSize; + ItemStack remaining = con.insertItem(inventorySide, item); + if (remaining == null) { + return startedWith; + } + return startedWith - remaining.stackSize; + } + + public static int doInsertItem(IInventory inv, int startSlot, int endSlot, ItemStack item) { + return doInsertItemInv( + inv, + null, + invSlotter.getInstance(startSlot, endSlot), + item, + ForgeDirection.UNKNOWN, + true); + } + + public static int doInsertItem(IInventory inv, int startSlot, int endSlot, ItemStack item, boolean doInsert) { + return doInsertItemInv( + inv, + null, + invSlotter.getInstance(startSlot, endSlot), + item, + ForgeDirection.UNKNOWN, + doInsert); + } + + /* + * Insert items into an IInventory or an ISidedInventory. + */ + private static int doInsertItemInv(IInventory inv, ItemStack item, ForgeDirection inventorySide, boolean doInsert) { + final ISidedInventory sidedInv = inv instanceof ISidedInventory ? (ISidedInventory) inv : null; + ISlotIterator slots; + + if (sidedInv != null) { + if (inventorySide == null) { + inventorySide = ForgeDirection.UNKNOWN; + } + // Note: This is not thread-safe. Change to getInstance() to constructor when needed (1.8++?). + slots = sidedSlotter.getInstance(sidedInv.getAccessibleSlotsFromSide(inventorySide.ordinal())); + } else { + slots = invSlotter.getInstance(0, inv.getSizeInventory()); + } + + return doInsertItemInv(inv, sidedInv, slots, item, inventorySide, 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; + + // PASS1: Try to add to an existing stack + while (numToInsert > 0 && slots.hasNext()) { + final int slot = slots.nextSlot(); + if (sidedInv == null || sidedInv.canInsertItem(slot, item, inventorySide.ordinal())) { + final ItemStack contents = inv.getStackInSlot(slot); + if (contents != null) { + if (areStackMergable(contents, item)) { + final int freeSpace = Math.min(inv.getInventoryStackLimit(), contents.getMaxStackSize()) + - contents.stackSize; // some inventories like using itemstacks with invalid stack sizes + if (freeSpace > 0) { + final int noToInsert = Math.min(numToInsert, freeSpace); + final ItemStack toInsert = item.copy(); + toInsert.stackSize = contents.stackSize + noToInsert; + // isItemValidForSlot() may check the stacksize, so give it the number the stack would have + // in the end. + // If it does something funny, like "only even numbers", we are screwed. + if (sidedInv != null || inv.isItemValidForSlot(slot, toInsert)) { + numInserted += noToInsert; + numToInsert -= noToInsert; + if (doInsert) { + inv.setInventorySlotContents(slot, toInsert); + } + } + } + } + } else if (firstFreeSlot == -1) { + firstFreeSlot = slot; + } + } + } + + // PASS2: Try to insert into an empty slot + if (numToInsert > 0 && firstFreeSlot != -1) { + final ItemStack toInsert = item.copy(); + toInsert.stackSize = min(numToInsert, inv.getInventoryStackLimit(), toInsert.getMaxStackSize()); // some + // inventories + // like + // using + // itemstacks + // with + // invalid + // stack + // sizes + if (sidedInv != null || inv.isItemValidForSlot(firstFreeSlot, toInsert)) { + numInserted += toInsert.stackSize; + numToInsert -= toInsert.stackSize; + if (doInsert) { + inv.setInventorySlotContents(firstFreeSlot, toInsert); + } + } + } + + if (numInserted > 0 && doInsert) { + inv.markDirty(); + } + return numInserted; + } + + private final static int min(int i1, int i2, int i3) { + return i1 < i2 ? (i1 < i3 ? i1 : i3) : (i2 < i3 ? i2 : i3); + } + + public static boolean isStackFull(ItemStack contents) { + if (contents == null) { + return false; + } + return contents.stackSize >= contents.getMaxStackSize(); + } + + public static IInventory getInventory(IInventory inv) { + if (inv instanceof TileEntityChest) { + TileEntityChest chest = (TileEntityChest) inv; + TileEntityChest neighbour = null; + boolean reverse = false; + if (chest.adjacentChestXNeg != null) { + neighbour = chest.adjacentChestXNeg; + reverse = true; + } else if (chest.adjacentChestXPos != null) { + neighbour = chest.adjacentChestXPos; + } else if (chest.adjacentChestZNeg != null) { + neighbour = chest.adjacentChestZNeg; + reverse = true; + } else if (chest.adjacentChestZPos != null) { + neighbour = chest.adjacentChestZPos; + } + if (neighbour != null) { + if (reverse) { + return new InventoryLargeChest("", neighbour, inv); + } else { + return new InventoryLargeChest("", inv, neighbour); + } + } + } + return inv; + } + + /** + * Checks if items, damage and NBT are equal and the items are stackable. + * + * @param s1 + * @param s2 + * @return True if the two stacks are mergeable, false otherwise. + */ + public static boolean areStackMergable(ItemStack s1, ItemStack s2) { + if (s1 == null || s2 == null || !s1.isStackable() || !s2.isStackable()) { + return false; + } + if (!s1.isItemEqual(s2)) { + return false; + } + return ItemStack.areItemStackTagsEqual(s1, s2); + } + + /** + * Checks if items, damage and NBT are equal. + * + * @param s1 + * @param s2 + * @return True if the two stacks are equal, false otherwise. + */ + public static boolean areStacksEqual(ItemStack s1, ItemStack s2) { + if (s1 == null || s2 == null) { + return false; + } + if (!s1.isItemEqual(s2)) { + return false; + } + return ItemStack.areItemStackTagsEqual(s1, s2); + } + + private interface ISlotIterator { + + int nextSlot(); + + boolean hasNext(); + } + + private final static class invSlotter implements ISlotIterator { + + private static final invSlotter me = new invSlotter(); + private int end; + private int current; + + public final static invSlotter getInstance(int start, int end) { + me.end = end; + me.current = start; + return me; + } + + @Override + public final int nextSlot() { + return current++; + } + + @Override + public final boolean hasNext() { + return current < end; + } + } + + private final static class sidedSlotter implements ISlotIterator { + + private static final sidedSlotter me = new sidedSlotter(); + private int[] slots; + private int current; + + public final static sidedSlotter getInstance(int[] slots) { + me.slots = slots; + me.current = 0; + return me; + } + + @Override + public final int nextSlot() { + return slots[current++]; + } + + @Override + public final boolean hasNext() { + return slots != null && current < slots.length; + } } - } } 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 1565517..638de6e 100644 --- a/src/main/java/com/enderio/core/common/util/Log.java +++ b/src/main/java/com/enderio/core/common/util/Log.java @@ -7,25 +7,24 @@ import com.enderio.core.EnderCore; public final class Log { - public static final Logger LOGGER = LogManager.getLogger(EnderCore.MODID); + public static final Logger LOGGER = LogManager.getLogger(EnderCore.MODID); - public static void warn(String msg) { - LOGGER.warn(msg); - } + public static void warn(String msg) { + LOGGER.warn(msg); + } - public static void error(String msg) { - LOGGER.error(msg); - } + public static void error(String msg) { + LOGGER.error(msg); + } - public static void info(String msg) { - LOGGER.info(msg); - } + public static void info(String msg) { + LOGGER.info(msg); + } - public static void debug(String msg) { - LOGGER.debug(msg); - } + public static void debug(String msg) { + LOGGER.debug(msg); + } - private Log() { - } + private Log() {} } 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 50ea897..1ed380e 100644 --- a/src/main/java/com/enderio/core/common/util/MetadataUtil.java +++ b/src/main/java/com/enderio/core/common/util/MetadataUtil.java @@ -2,42 +2,42 @@ package com.enderio.core.common.util; public class MetadataUtil { - public static void printBits(int meta) { - for (int k = 0; k < 4; k++) { - if (((meta >> k) & 1) == 1) { - System.out.print(1); - } else { - System.out.print(0); - } + public static void printBits(int meta) { + for (int k = 0; k < 4; k++) { + if (((meta >> k) & 1) == 1) { + System.out.print(1); + } else { + System.out.print(0); + } + } + System.out.println(); } - System.out.println(); - } - public static String toBitString(int meta) { - StringBuilder sb = new StringBuilder(); - for (int k = 0; k < 4; k++) { - if (((meta >> k) & 1) == 1) { - sb.append(1); - } else { - sb.append(0); - } + public static String toBitString(int meta) { + StringBuilder sb = new StringBuilder(); + for (int k = 0; k < 4; k++) { + if (((meta >> k) & 1) == 1) { + sb.append(1); + } else { + sb.append(0); + } + } + return sb.toString(); } - return sb.toString(); - } - public static boolean isBitSet(int position, int meta) { - return ((meta >> position) & 1) == 1; - } - - public static int setBit(int position, boolean value, int meta) { - if (value) { - return meta | (1 << position); + public static boolean isBitSet(int position, int meta) { + return ((meta >> position) & 1) == 1; } - return meta & ~(1 << position); - } - public static int toggleBit(int position, int meta) { - return setBit(position, !isBitSet(position, meta), meta); - } + public static int setBit(int position, boolean value, int meta) { + if (value) { + return meta | (1 << position); + } + return meta & ~(1 << position); + } + + public static int toggleBit(int position, int meta) { + return setBit(position, !isBitSet(position, meta), meta); + } } diff --git a/src/main/java/com/enderio/core/common/util/OreDictionaryHelper.java b/src/main/java/com/enderio/core/common/util/OreDictionaryHelper.java index 224c9c5..287c097 100644 --- a/src/main/java/com/enderio/core/common/util/OreDictionaryHelper.java +++ b/src/main/java/com/enderio/core/common/util/OreDictionaryHelper.java @@ -2,59 +2,58 @@ package com.enderio.core.common.util; import java.util.List; -import org.apache.commons.lang3.ArrayUtils; - import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; +import org.apache.commons.lang3.ArrayUtils; + public final class OreDictionaryHelper { - public static final String INGOT_COPPER = "ingotCopper"; - public static final String INGOT_TIN = "ingotTin"; - public static final String DUST_ENDERPEARL = "dustEnderPearl"; - public static final String INGOT_ENDERIUM = "ingotEnderium"; + public static final String INGOT_COPPER = "ingotCopper"; + public static final String INGOT_TIN = "ingotTin"; + public static final String DUST_ENDERPEARL = "dustEnderPearl"; + public static final String INGOT_ENDERIUM = "ingotEnderium"; - public static boolean isRegistered(String name) { - if (!getOres(name).isEmpty()) { - return true; + public static boolean isRegistered(String name) { + if (!getOres(name).isEmpty()) { + return true; + } + return false; } - return false; - } - public static List getOres(String name) { - return OreDictionary.getOres(name); - } - - public static boolean hasCopper() { - return isRegistered(INGOT_COPPER); - } - - public static boolean hasTin() { - return isRegistered(INGOT_TIN); - } - - public static boolean hasEnderPearlDust() { - return isRegistered(DUST_ENDERPEARL); - } - - private OreDictionaryHelper() { - } - - public static boolean hasEnderium() { - return isRegistered(INGOT_ENDERIUM); - } - - public static String[] getOreNames(ItemStack stack) { - int[] ids = OreDictionary.getOreIDs(stack); - String[] ret = new String[ids.length]; - for (int i = 0; i < ids.length; i++) { - ret[i] = OreDictionary.getOreName(ids[i]); + public static List getOres(String name) { + return OreDictionary.getOres(name); } - return ret; - } - public static boolean hasName(ItemStack stack, String oreName) { - return ArrayUtils.contains(getOreNames(stack), oreName); - } + public static boolean hasCopper() { + return isRegistered(INGOT_COPPER); + } + + public static boolean hasTin() { + return isRegistered(INGOT_TIN); + } + + public static boolean hasEnderPearlDust() { + return isRegistered(DUST_ENDERPEARL); + } + + private OreDictionaryHelper() {} + + public static boolean hasEnderium() { + return isRegistered(INGOT_ENDERIUM); + } + + public static String[] getOreNames(ItemStack stack) { + int[] ids = OreDictionary.getOreIDs(stack); + String[] ret = new String[ids.length]; + for (int i = 0; i < ids.length; i++) { + ret[i] = OreDictionary.getOreName(ids[i]); + } + return ret; + } + + public static boolean hasName(ItemStack stack, String oreName) { + return ArrayUtils.contains(getOreNames(stack), oreName); + } } 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 0cbe8a4..d478d2c 100644 --- a/src/main/java/com/enderio/core/common/util/PermanentCache.java +++ b/src/main/java/com/enderio/core/common/util/PermanentCache.java @@ -6,57 +6,56 @@ import java.util.List; import com.google.common.base.Throwables; import com.google.common.collect.Lists; - import cpw.mods.fml.common.FMLCommonHandler; public class PermanentCache extends WorldCache { - private static final List> allCaches = Lists.newArrayList(); + private static final List> allCaches = Lists.newArrayList(); - public PermanentCache(String ident) { - super(ident); - try { - loadData(getSaveFile()); - } catch (IOException e) { - Throwables.propagate(e); + public PermanentCache(String ident) { + super(ident); + try { + loadData(getSaveFile()); + } catch (IOException e) { + Throwables.propagate(e); + } } - } - @Override - protected File getSaveFile() { - if (FMLCommonHandler.instance().getSide().isServer()) { - return new File(ident + ".dat"); + @Override + protected File getSaveFile() { + if (FMLCommonHandler.instance().getSide().isServer()) { + return new File(ident + ".dat"); + } + return new File("saves", ident + ".dat"); } - return new File("saves", ident + ".dat"); - } - @Override - protected void blockOldIDs() { - if (!objToName.isEmpty()) { - super.blockOldIDs(); + @Override + protected void blockOldIDs() { + if (!objToName.isEmpty()) { + super.blockOldIDs(); + } } - } - @Override - protected void mergeNewIDs() { - if (!objToName.isEmpty()) { - super.mergeNewIDs(); + @Override + protected void mergeNewIDs() { + if (!objToName.isEmpty()) { + super.mergeNewIDs(); + } } - } - @Override - public void addObject(I object, String name) { - super.addObject(object, name); - setID(name); - } - - public static void saveCaches() { - for (PermanentCache c : allCaches) { - try { - c.saveData(c.getSaveFile()); - } catch (IOException e) { - Throwables.propagate(e); - } + @Override + public void addObject(I object, String name) { + super.addObject(object, name); + setID(name); + } + + public static void saveCaches() { + for (PermanentCache c : allCaches) { + try { + c.saveData(c.getSaveFile()); + } catch (IOException e) { + Throwables.propagate(e); + } + } } - } } 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 1bbb5f7..ea6128c 100644 --- a/src/main/java/com/enderio/core/common/util/PlayerUtil.java +++ b/src/main/java/com/enderio/core/common/util/PlayerUtil.java @@ -7,24 +7,23 @@ import net.minecraftforge.common.UsernameCache; public class PlayerUtil { - public static UUID getPlayerUUID(String username) { - for (Map.Entry entry : UsernameCache.getMap().entrySet()) { - if (entry.getValue().equalsIgnoreCase(username)) { - return entry.getKey(); - } + public static UUID getPlayerUUID(String username) { + for (Map.Entry entry : UsernameCache.getMap().entrySet()) { + if (entry.getValue().equalsIgnoreCase(username)) { + return entry.getKey(); + } + } + return null; } - return null; - } - public static UUID getPlayerUIDUnstable(String possibleUUID) { - if (possibleUUID == null || possibleUUID.isEmpty()) - return null; - UUID uuid = null; - try { - uuid = UUID.fromString(possibleUUID); - } catch (IllegalArgumentException e) { - uuid = getPlayerUUID(possibleUUID); + public static UUID getPlayerUIDUnstable(String possibleUUID) { + if (possibleUUID == null || possibleUUID.isEmpty()) return null; + UUID uuid = null; + try { + uuid = UUID.fromString(possibleUUID); + } catch (IllegalArgumentException e) { + uuid = getPlayerUUID(possibleUUID); + } + return uuid; } - return uuid; - } } 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 9a7017a..e442f0e 100644 --- a/src/main/java/com/enderio/core/common/util/RegisterTime.java +++ b/src/main/java/com/enderio/core/common/util/RegisterTime.java @@ -6,22 +6,23 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLStateEvent; public enum RegisterTime { - PREINIT(FMLPreInitializationEvent.class), - INIT(FMLInitializationEvent.class), - POSTINIT(FMLPostInitializationEvent.class); - private Class clazz; + PREINIT(FMLPreInitializationEvent.class), + INIT(FMLInitializationEvent.class), + POSTINIT(FMLPostInitializationEvent.class); - private RegisterTime(Class clazz) { - this.clazz = clazz; - } + private Class clazz; - public static RegisterTime timeFor(FMLStateEvent event) { - for (RegisterTime time : values()) { - if (time.clazz == event.getClass()) { - return time; - } + private RegisterTime(Class clazz) { + this.clazz = clazz; + } + + public static RegisterTime timeFor(FMLStateEvent event) { + for (RegisterTime time : values()) { + if (time.clazz == event.getClass()) { + return time; + } + } + return null; } - 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 2daab29..cb95391 100644 --- a/src/main/java/com/enderio/core/common/util/ResourcePackAssembler.java +++ b/src/main/java/com/enderio/core/common/util/ResourcePackAssembler.java @@ -19,217 +19,211 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.ReflectionHelper; /** - * A class that can be used to inject resources from files/folders outside your - * mod resources. Useful for loading textures and other assets from the config - * dir or elsewhere. + * A class that can be used to inject resources from files/folders outside your mod resources. Useful for loading + * textures and other assets from the config dir or elsewhere. *

- * To use, first construct an instance of this class, then add all your assets - * using {@link #addIcon(File)}, {@link #addLang(File)}, and - * {@link #addCustomFile(String, File)}. + * To use, first construct an instance of this class, then add all your assets using {@link #addIcon(File)}, + * {@link #addLang(File)}, and {@link #addCustomFile(String, File)}. *

- * Once all files have been added, {@link #assemble()} Will create a zip of all - * the files in the {@link File directory} passed into the constructor. + * Once all files have been added, {@link #assemble()} Will create a zip of all the files in the {@link File directory} + * passed into the constructor. *

* Finally, {@link #inject()} will insert this resource pack into the game. *

* Also, {@link #setHasPackPng(Class)} allows your resource pack to have a logo. */ public class ResourcePackAssembler { - private class CustomFile { - private String ext; - private File file; - private CustomFile(String ext, File file) { - this.ext = ext; - this.file = file; - } - } + private class CustomFile { - private List icons = new ArrayList(); - private List langs = new ArrayList(); - private List customs = new ArrayList(); + private String ext; + private File file; - 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 CustomFile(String ext, File file) { + this.ext = ext; + this.file = file; + } } - return this; - } + private List icons = new ArrayList(); + private List langs = new ArrayList(); + private List customs = new ArrayList(); - /** - * 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 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); } - 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."); + return this; } - } - private void writeNewFile(File file, String defaultText) throws IOException { - EnderFileUtils.safeDelete(file); - file.delete(); - file.getParentFile().mkdirs(); - file.createNewFile(); + /** + * 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"); + } - FileWriter fw = new FileWriter(file); - fw.write(defaultText); - fw.flush(); - fw.close(); - } + 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(); + } } 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 9bea26d..d8b17d2 100644 --- a/src/main/java/com/enderio/core/common/util/RoundRobinIterator.java +++ b/src/main/java/com/enderio/core/common/util/RoundRobinIterator.java @@ -5,40 +5,39 @@ import java.util.List; public class RoundRobinIterator implements Iterable, Iterator { - private int index = -1; - private int currentCount = 0; - private final List itOver; + private int index = -1; + private int currentCount = 0; + private final List itOver; - public RoundRobinIterator(List itOver) { - this.itOver = itOver; - } - - @Override - public Iterator iterator() { - currentCount = 0; - return this; - } - - @Override - public boolean hasNext() { - return !itOver.isEmpty() && currentCount < itOver.size(); - } - - @Override - public T next() { - if (itOver.isEmpty()) { - return null; + public RoundRobinIterator(List itOver) { + this.itOver = itOver; } - currentCount++; - index++; - if (index >= itOver.size()) { - index = 0; - } - return itOver.get(index); - } - @Override - public void remove() { - } + @Override + public Iterator iterator() { + currentCount = 0; + return this; + } + + @Override + public boolean hasNext() { + return !itOver.isEmpty() && currentCount < itOver.size(); + } + + @Override + public T next() { + if (itOver.isEmpty()) { + return null; + } + currentCount++; + index++; + if (index >= itOver.size()) { + index = 0; + } + return itOver.get(index); + } + + @Override + 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 a1e9f18..f61ceec 100644 --- a/src/main/java/com/enderio/core/common/util/Scheduler.java +++ b/src/main/java/com/enderio/core/common/util/Scheduler.java @@ -5,11 +5,12 @@ import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.client.Minecraft; + import com.enderio.core.EnderCore; import com.enderio.core.common.Handlers.Handler; import com.enderio.core.common.Handlers.Handler.Inst; -import net.minecraft.client.Minecraft; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; @@ -23,156 +24,151 @@ import cpw.mods.fml.relauncher.SideOnly; @Handler(getInstFrom = Inst.METHOD) public class Scheduler { - /** - * A task to be executed later. - * - */ - public static interface ITask { /** - * This method will be called at the next post tick event. It can return a new task (or itself) to be enqueued again. + * A task to be executed later. * - * @return null or a task to be enqueued */ - ITask run(); - } + public static interface ITask { - private static final class Task implements ITask { - private int delay; - private Runnable toRun; - - private Task(int delay, Runnable toRun) { - this.delay = delay; - this.toRun = toRun; + /** + * This method will be called at the next post tick event. It can return a new task (or itself) to be enqueued + * again. + * + * @return null or a task to be enqueued + */ + ITask run(); } - @Override - public ITask run() { - if (delay <= 0) { - toRun.run(); - return null; - } else { - delay--; - return this; - } - } - } + private static final class Task implements ITask { - private final Queue clientQueue; - private final Queue serverQueue = new ConcurrentLinkedQueue(); + private int delay; + private Runnable toRun; - /** - * Please use the single instance available from instance(). - */ - public Scheduler(boolean isServer) { - if (isServer) { - clientQueue = null; - } else { - clientQueue = new ConcurrentLinkedQueue(); - } - } - - /** - * 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 #schedule(int, Runnable, Side) - */ - 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. - *

- * 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) { - schedule(new Task(delay, task), side); - } - - /** - * Schedules a task to be called later - * - * @param task - * The {@link ITask} to be run at the next tick - * @param side - * The side to schedule the task on. - *

- * 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(ITask task, Side side) { - if (side == Side.SERVER) { - serverQueue.add(task); - } else if (clientQueue != null) { - clientQueue.add(task); - } - } - - /** - * Returns the {@link Scheduler} instance for the current side. - * - * @see #schedule(int, Runnable) - * - * @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(serverQueue); - } - } - - /** - * For internal use only. Do not call. - */ - @SideOnly(Side.CLIENT) - @SubscribeEvent - public void onClientTick(ClientTickEvent event) { - if (event.phase == Phase.END) { - runTasks(clientQueue); - if (!serverQueue.isEmpty() && !Minecraft.getMinecraft().isIntegratedServerRunning()) { - serverQueue.clear(); - } - } - } - - private void runTasks(Queue queue) { - if (!queue.isEmpty()) { - List newtasks = new ArrayList(queue.size()); - while (!queue.isEmpty()) { - ITask task = queue.poll(); - if (task != null) { - task = task.run(); - if (task != null) { - newtasks.add(task); - } + private Task(int delay, Runnable toRun) { + this.delay = delay; + this.toRun = toRun; + } + + @Override + public ITask run() { + if (delay <= 0) { + toRun.run(); + return null; + } else { + delay--; + return this; + } + } + } + + private final Queue clientQueue; + private final Queue serverQueue = new ConcurrentLinkedQueue(); + + /** + * Please use the single instance available from instance(). + */ + public Scheduler(boolean isServer) { + if (isServer) { + clientQueue = null; + } else { + clientQueue = new ConcurrentLinkedQueue(); + } + } + + /** + * 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 #schedule(int, Runnable, Side) + */ + 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. + *

+ * 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) { + schedule(new Task(delay, task), side); + } + + /** + * Schedules a task to be called later + * + * @param task The {@link ITask} to be run at the next tick + * @param side The side to schedule the task on. + *

+ * 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(ITask task, Side side) { + if (side == Side.SERVER) { + serverQueue.add(task); + } else if (clientQueue != null) { + clientQueue.add(task); + } + } + + /** + * Returns the {@link Scheduler} instance for the current side. + * + * @see #schedule(int, Runnable) + * + * @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(serverQueue); + } + } + + /** + * For internal use only. Do not call. + */ + @SideOnly(Side.CLIENT) + @SubscribeEvent + public void onClientTick(ClientTickEvent event) { + if (event.phase == Phase.END) { + runTasks(clientQueue); + if (!serverQueue.isEmpty() && !Minecraft.getMinecraft().isIntegratedServerRunning()) { + serverQueue.clear(); + } + } + } + + private void runTasks(Queue queue) { + if (!queue.isEmpty()) { + List newtasks = new ArrayList(queue.size()); + while (!queue.isEmpty()) { + ITask task = queue.poll(); + if (task != null) { + task = task.run(); + if (task != null) { + newtasks.add(task); + } + } + } + for (ITask task : newtasks) { + queue.add(task); + } } - } - for (ITask task : newtasks) { - queue.add(task); - } } - } } 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 e46b046..47c2731 100644 --- a/src/main/java/com/enderio/core/common/util/SoundUtil.java +++ b/src/main/java/com/enderio/core/common/util/SoundUtil.java @@ -3,16 +3,23 @@ package com.enderio.core.common.util; import net.minecraft.client.Minecraft; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; 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); - } + @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); + } } 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 d794ead..2cdf590 100644 --- a/src/main/java/com/enderio/core/common/util/TextureErrorRemover.java +++ b/src/main/java/com/enderio/core/common/util/TextureErrorRemover.java @@ -14,50 +14,54 @@ import org.apache.logging.log4j.message.Message; import com.enderio.core.EnderCore; 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; - private TextureErrorRemover(Logger other) { - super(other.getContext(), other.getName(), other.getMessageFactory()); - } + private static TextureErrorRemover INSTANCE; + private int removed = 0; - @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); + 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; } - 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 db2e72b..29d96a5 100644 --- a/src/main/java/com/enderio/core/common/util/Util.java +++ b/src/main/java/com/enderio/core/common/util/Util.java @@ -32,496 +32,512 @@ import com.google.common.io.Files; public class Util { - public static Block getBlockFromItemId(ItemStack itemId) { - Item item = itemId.getItem(); - 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) { - return new ItemStack(Items.glass_bottle); - } else { - stack.splitStack(1); - return stack; - } - } - if (stack.stackSize == 1) { - if (stack.getItem().hasContainerItem(stack)) { - return stack.getItem().getContainerItem(stack); - } else { + public static Block getBlockFromItemId(ItemStack itemId) { + Item item = itemId.getItem(); + if (item instanceof ItemBlock) { + return ((ItemBlock) item).field_150939_a; + } return null; - } - } else { - stack.splitStack(1); - return stack; - } - } - - public static void giveExperience(EntityPlayer thePlayer, float experience) { - int intExp = (int) experience; - float fractional = experience - intExp; - if (fractional > 0.0F) { - if ((float) Math.random() < fractional) { - ++intExp; - } - } - while (intExp > 0) { - int j = EntityXPOrb.getXPSplit(intExp); - intExp -= j; - thePlayer.worldObj.spawnEntityInWorld(new EntityXPOrb(thePlayer.worldObj, thePlayer.posX, thePlayer.posY + 0.5D, thePlayer.posZ + 0.5D, j)); - } - } - - // 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) { - return null; } - Block block = world.getBlock(x, y, z); - - 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))) { - - if (side == 0) { - --y; - } else if (side == 1) { - ++y; - } else if (side == 2) { - --z; - } else if (side == 3) { - ++z; - } else if (side == 4) { - --x; - } else if (side == 5) { - ++x; - } - } - - if (itemUsed.stackSize == 0) { - return null; - } else if (!player.canPlayerEdit(x, y, z, side, itemUsed)) { - return null; - } else if (y == 255 && blockIdToBePlaced.getMaterial().isSolid()) { - return null; - } else if (world.canPlaceEntityOnSide(blockIdToBePlaced, x, y, z, false, side, player, itemUsed)) { - return new BlockCoord(x, y, z); - } - return null; - - } - - public static EntityItem createDrop(World world, ItemStack stack, double x, double y, double z, boolean doRandomSpread) { - if (stack == null || stack.stackSize <= 0) { - return null; - } - 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; - double d2 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; - EntityItem entityitem = new EntityItem(world, x + d, y + d1, z + d2, stack); - entityitem.delayBeforeCanPickup = 10; - return entityitem; - } else { - EntityItem entityitem = new EntityItem(world, x, y, z, stack); - entityitem.motionX = 0; - entityitem.motionY = 0; - entityitem.motionZ = 0; - entityitem.delayBeforeCanPickup = 0; - return entityitem; - } - } - - public static void dropItems(World world, ItemStack stack, double x, double y, double z, boolean doRandomSpread) { - if (stack == null || stack.stackSize <= 0) { - return; - } - - EntityItem entityitem = createEntityItem(world, stack, x, y, z, doRandomSpread); - world.spawnEntityInWorld(entityitem); - - } - - public static EntityItem createEntityItem(World world, ItemStack stack, double x, double y, double z) { - return createEntityItem(world, stack, x, y, z, true); - } - - public static EntityItem createEntityItem(World world, ItemStack stack, double x, double y, double z, boolean doRandomSpread) { - EntityItem entityitem; - 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; - double d2 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; - entityitem = new EntityItem(world, x + d, y + d1, z + d2, stack); - entityitem.delayBeforeCanPickup = 10; - } else { - entityitem = new EntityItem(world, x, y, z, stack); - entityitem.motionX = 0; - entityitem.motionY = 0; - entityitem.motionZ = 0; - entityitem.delayBeforeCanPickup = 0; - } - return entityitem; - } - - public static void dropItems(World world, ItemStack stack, int x, int y, int z, boolean doRandomSpread) { - if (stack == null || stack.stackSize <= 0) { - return; - } - - 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; - double d2 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; - EntityItem entityitem = new EntityItem(world, x + d, y + d1, z + d2, stack); - entityitem.delayBeforeCanPickup = 10; - world.spawnEntityInWorld(entityitem); - } else { - EntityItem entityitem = new EntityItem(world, x + 0.5, y + 0.5, z + 0.5, stack); - entityitem.motionX = 0; - entityitem.motionY = 0; - entityitem.motionZ = 0; - entityitem.delayBeforeCanPickup = 0; - world.spawnEntityInWorld(entityitem); - } - - } - - public static void dropItems(World world, ItemStack[] inventory, int x, int y, int z, boolean doRandomSpread) { - if (inventory == null) { - return; - } - for (ItemStack stack : inventory) { - if (stack != null && stack.stackSize > 0) { - dropItems(world, stack.copy(), x, y, z, doRandomSpread); - } - } - } - - public static void dropItems(World world, IInventory inventory, int x, int y, int z, boolean doRandomSpread) { - for (int l = 0; l < inventory.getSizeInventory(); ++l) { - ItemStack items = inventory.getStackInSlot(l); - - if (items != null && items.stackSize > 0) { - dropItems(world, inventory.getStackInSlot(l).copy(), x, y, z, doRandomSpread); - } - } - } - - public static boolean dumpModObjects(File file) { - - StringBuilder sb = new StringBuilder(); - for (Object key : Block.blockRegistry.getKeys()) { - if (key != null) { - sb.append(key.toString()); - sb.append("\n"); - } - } - for (Object key : Item.itemRegistry.getKeys()) { - if (key != null) { - sb.append(key.toString()); - sb.append("\n"); - } - } - - try { - Files.write(sb, file, Charsets.UTF_8); - return true; - } catch (IOException e) { - Log.warn("Error dumping ore dictionary entries: " + e.getMessage()); - e.printStackTrace(); - return false; - } - } - - public static boolean dumpOreNames(File file) { - - try { - String[] oreNames = OreDictionary.getOreNames(); - Files.write(Joiner.on("\n").join(oreNames), file, Charsets.UTF_8); - return true; - } catch (IOException e) { - Log.warn("Error dumping ore dictionary entries: " + e.getMessage()); - e.printStackTrace(); - return false; - } - } - - public static ItemStack decrStackSize(IInventory inventory, int slot, int size) { - ItemStack item = inventory.getStackInSlot(slot); - 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) { - inventory.setInventorySlotContents(slot, null); - } - inventory.markDirty(); - return split; - } - return null; - } - - public static Vec3 getEyePosition(EntityPlayer player) { - Vec3 v = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); - 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()) { - v.yCoord -= 0.08; - } - } - return v; - } - - public static Vector3d getEyePositionEio(EntityPlayer player) { - Vector3d res = new Vector3d(player.posX, player.posY, player.posZ); - 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()) { - res.y -= 0.08; - } - } - return res; - } - - public static Vector3d getLookVecEio(EntityPlayer player) { - Vec3 lv = player.getLookVec(); - return new Vector3d(lv.xCoord, lv.yCoord, lv.zCoord); - } - - public static boolean isEquipped(EntityPlayer player, Class class1) { - if (player == null || player.inventory == null || player.inventory.getCurrentItem() == null) { - return false; - } - //player.inventory.getCurrentItem().getClass().getItem().isAssignableFrom(class1) - return class1.isAssignableFrom(player.inventory.getCurrentItem().getItem().getClass()); - } - - public static boolean isType(ItemStack stack, Class class1) { - if (stack == null || class1 == null) { - return false; - } - return class1.isAssignableFrom(stack.getItem().getClass()); - } - - //Code adapted from World.func_147447_a (rayTraceBlocks) to return all collided blocks - public static List raytraceAll(World world, Vec3 startVec, Vec3 endVec, boolean includeLiquids) { - - List result = new ArrayList(); - 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)) { - - int i = MathHelper.floor_double(endVec.xCoord); - int j = MathHelper.floor_double(endVec.yCoord); - int k = MathHelper.floor_double(endVec.zCoord); - int l = MathHelper.floor_double(startVec.xCoord); - int i1 = MathHelper.floor_double(startVec.yCoord); - int j1 = MathHelper.floor_double(startVec.zCoord); - 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)) { - MovingObjectPosition movingobjectposition = block.collisionRayTrace(world, l, i1, j1, startVec, endVec); - if (movingobjectposition != null) { - result.add(movingobjectposition); - } + public static ItemStack consumeItem(ItemStack stack) { + if (stack.getItem() instanceof ItemPotion) { + if (stack.stackSize == 1) { + return new ItemStack(Items.glass_bottle); + } else { + stack.splitStack(1); + return stack; + } } - - MovingObjectPosition movingobjectposition2 = null; - k1 = 200; - - while (k1-- >= 0) { - 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_) { - result.add(movingobjectposition2); + if (stack.stackSize == 1) { + if (stack.getItem().hasContainerItem(stack)) { + return stack.getItem().getContainerItem(stack); } else { - return result; + return null; } - } - - boolean flag6 = true; - boolean flag3 = true; - boolean flag4 = true; - double d0 = 999.0D; - double d1 = 999.0D; - double d2 = 999.0D; - - if (i > l) { - d0 = l + 1.0D; - } else if (i < l) { - d0 = l + 0.0D; - } else { - flag6 = false; - } - - if (j > i1) { - d1 = i1 + 1.0D; - } else if (j < i1) { - d1 = i1 + 0.0D; - } else { - flag3 = false; - } - - if (k > j1) { - d2 = j1 + 1.0D; - } else if (k < j1) { - d2 = j1 + 0.0D; - } else { - flag4 = false; - } - - double d3 = 999.0D; - double d4 = 999.0D; - double d5 = 999.0D; - double d6 = endVec.xCoord - startVec.xCoord; - double d7 = endVec.yCoord - startVec.yCoord; - double d8 = endVec.zCoord - startVec.zCoord; - - if (flag6) { - d3 = (d0 - startVec.xCoord) / d6; - } - if (flag3) { - d4 = (d1 - startVec.yCoord) / d7; - } - if (flag4) { - d5 = (d2 - startVec.zCoord) / d8; - } - - boolean flag5 = false; - byte b0; - - if (d3 < d4 && d3 < d5) { - if (i > l) { - b0 = 4; - } else { - b0 = 5; - } - - startVec.xCoord = d0; - startVec.yCoord += d7 * d3; - startVec.zCoord += d8 * d3; - } else if (d4 < d5) { - if (j > i1) { - b0 = 0; - } else { - b0 = 1; - } - - startVec.xCoord += d6 * d4; - startVec.yCoord = d1; - startVec.zCoord += d8 * d4; - } else { - if (k > j1) { - b0 = 2; - } else { - b0 = 3; - } - - startVec.xCoord += d6 * d5; - startVec.yCoord += d7 * d5; - startVec.zCoord = d2; - } - - Vec3 vec32 = Vec3.createVectorHelper(startVec.xCoord, startVec.yCoord, startVec.zCoord); - l = (int) (vec32.xCoord = MathHelper.floor_double(startVec.xCoord)); - if (b0 == 5) { - --l; - ++vec32.xCoord; - } - - i1 = (int) (vec32.yCoord = MathHelper.floor_double(startVec.yCoord)); - - if (b0 == 1) { - --i1; - ++vec32.yCoord; - } - - j1 = (int) (vec32.zCoord = MathHelper.floor_double(startVec.zCoord)); - - if (b0 == 3) { - --j1; - ++vec32.zCoord; - } - - 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)) { - MovingObjectPosition movingobjectposition1 = block1.collisionRayTrace(world, l, i1, j1, startVec, endVec); - if (movingobjectposition1 != null) { - result.add(movingobjectposition1); - } - } else { - movingobjectposition2 = new MovingObjectPosition(l, i1, j1, b0, startVec, false); - } - } - } - if (p_147447_5_) { - result.add(movingobjectposition2); } else { - return result; + stack.splitStack(1); + return stack; + } + } + + public static void giveExperience(EntityPlayer thePlayer, float experience) { + int intExp = (int) experience; + float fractional = experience - intExp; + if (fractional > 0.0F) { + if ((float) Math.random() < fractional) { + ++intExp; + } + } + while (intExp > 0) { + int j = EntityXPOrb.getXPSplit(intExp); + intExp -= j; + thePlayer.worldObj.spawnEntityInWorld( + new EntityXPOrb( + thePlayer.worldObj, + thePlayer.posX, + thePlayer.posY + 0.5D, + thePlayer.posZ + 0.5D, + j)); + } + } + + // 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) { + return null; + } + + Block block = world.getBlock(x, y, z); + + 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))) { + + if (side == 0) { + --y; + } else if (side == 1) { + ++y; + } else if (side == 2) { + --z; + } else if (side == 3) { + ++z; + } else if (side == 4) { + --x; + } else if (side == 5) { + ++x; + } + } + + if (itemUsed.stackSize == 0) { + return null; + } else if (!player.canPlayerEdit(x, y, z, side, itemUsed)) { + return null; + } else if (y == 255 && blockIdToBePlaced.getMaterial().isSolid()) { + return null; + } else if (world.canPlaceEntityOnSide(blockIdToBePlaced, x, y, z, false, side, player, itemUsed)) { + return new BlockCoord(x, y, z); + } + return null; + + } + + public static EntityItem createDrop(World world, ItemStack stack, double x, double y, double z, + boolean doRandomSpread) { + if (stack == null || stack.stackSize <= 0) { + return null; + } + 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; + double d2 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; + EntityItem entityitem = new EntityItem(world, x + d, y + d1, z + d2, stack); + entityitem.delayBeforeCanPickup = 10; + return entityitem; + } else { + EntityItem entityitem = new EntityItem(world, x, y, z, stack); + entityitem.motionX = 0; + entityitem.motionY = 0; + entityitem.motionZ = 0; + entityitem.delayBeforeCanPickup = 0; + return entityitem; + } + } + + public static void dropItems(World world, ItemStack stack, double x, double y, double z, boolean doRandomSpread) { + if (stack == null || stack.stackSize <= 0) { + return; + } + + EntityItem entityitem = createEntityItem(world, stack, x, y, z, doRandomSpread); + world.spawnEntityInWorld(entityitem); + + } + + public static EntityItem createEntityItem(World world, ItemStack stack, double x, double y, double z) { + return createEntityItem(world, stack, x, y, z, true); + } + + public static EntityItem createEntityItem(World world, ItemStack stack, double x, double y, double z, + boolean doRandomSpread) { + EntityItem entityitem; + 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; + double d2 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; + entityitem = new EntityItem(world, x + d, y + d1, z + d2, stack); + entityitem.delayBeforeCanPickup = 10; + } else { + entityitem = new EntityItem(world, x, y, z, stack); + entityitem.motionX = 0; + entityitem.motionY = 0; + entityitem.motionZ = 0; + entityitem.delayBeforeCanPickup = 0; + } + return entityitem; + } + + public static void dropItems(World world, ItemStack stack, int x, int y, int z, boolean doRandomSpread) { + if (stack == null || stack.stackSize <= 0) { + return; + } + + 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; + double d2 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; + EntityItem entityitem = new EntityItem(world, x + d, y + d1, z + d2, stack); + entityitem.delayBeforeCanPickup = 10; + world.spawnEntityInWorld(entityitem); + } else { + EntityItem entityitem = new EntityItem(world, x + 0.5, y + 0.5, z + 0.5, stack); + entityitem.motionX = 0; + entityitem.motionY = 0; + entityitem.motionZ = 0; + entityitem.delayBeforeCanPickup = 0; + world.spawnEntityInWorld(entityitem); + } + + } + + public static void dropItems(World world, ItemStack[] inventory, int x, int y, int z, boolean doRandomSpread) { + if (inventory == null) { + return; + } + for (ItemStack stack : inventory) { + if (stack != null && stack.stackSize > 0) { + dropItems(world, stack.copy(), x, y, z, doRandomSpread); + } + } + } + + public static void dropItems(World world, IInventory inventory, int x, int y, int z, boolean doRandomSpread) { + for (int l = 0; l < inventory.getSizeInventory(); ++l) { + ItemStack items = inventory.getStackInSlot(l); + + if (items != null && items.stackSize > 0) { + dropItems(world, inventory.getStackInSlot(l).copy(), x, y, z, doRandomSpread); + } + } + } + + public static boolean dumpModObjects(File file) { + + StringBuilder sb = new StringBuilder(); + for (Object key : Block.blockRegistry.getKeys()) { + if (key != null) { + sb.append(key.toString()); + sb.append("\n"); + } + } + for (Object key : Item.itemRegistry.getKeys()) { + if (key != null) { + sb.append(key.toString()); + sb.append("\n"); + } + } + + try { + Files.write(sb, file, Charsets.UTF_8); + return true; + } catch (IOException e) { + Log.warn("Error dumping ore dictionary entries: " + e.getMessage()); + e.printStackTrace(); + return false; + } + } + + public static boolean dumpOreNames(File file) { + + try { + String[] oreNames = OreDictionary.getOreNames(); + Files.write(Joiner.on("\n").join(oreNames), file, Charsets.UTF_8); + return true; + } catch (IOException e) { + Log.warn("Error dumping ore dictionary entries: " + e.getMessage()); + e.printStackTrace(); + return false; + } + } + + public static ItemStack decrStackSize(IInventory inventory, int slot, int size) { + ItemStack item = inventory.getStackInSlot(slot); + 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) { + inventory.setInventorySlotContents(slot, null); + } + inventory.markDirty(); + return split; + } + return null; + } + + public static Vec3 getEyePosition(EntityPlayer player) { + Vec3 v = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); + 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()) { + v.yCoord -= 0.08; + } + } + return v; + } + + public static Vector3d getEyePositionEio(EntityPlayer player) { + Vector3d res = new Vector3d(player.posX, player.posY, player.posZ); + 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()) { + res.y -= 0.08; + } + } + return res; + } + + public static Vector3d getLookVecEio(EntityPlayer player) { + Vec3 lv = player.getLookVec(); + return new Vector3d(lv.xCoord, lv.yCoord, lv.zCoord); + } + + public static boolean isEquipped(EntityPlayer player, Class class1) { + if (player == null || player.inventory == null || player.inventory.getCurrentItem() == null) { + return false; + } + // player.inventory.getCurrentItem().getClass().getItem().isAssignableFrom(class1) + return class1.isAssignableFrom(player.inventory.getCurrentItem().getItem().getClass()); + } + + public static boolean isType(ItemStack stack, Class class1) { + if (stack == null || class1 == null) { + return false; + } + return class1.isAssignableFrom(stack.getItem().getClass()); + } + + // Code adapted from World.func_147447_a (rayTraceBlocks) to return all collided blocks + public static List raytraceAll(World world, Vec3 startVec, Vec3 endVec, + boolean includeLiquids) { + + List result = new ArrayList(); + 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)) { + + int i = MathHelper.floor_double(endVec.xCoord); + int j = MathHelper.floor_double(endVec.yCoord); + int k = MathHelper.floor_double(endVec.zCoord); + int l = MathHelper.floor_double(startVec.xCoord); + int i1 = MathHelper.floor_double(startVec.yCoord); + int j1 = MathHelper.floor_double(startVec.zCoord); + 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)) { + MovingObjectPosition movingobjectposition = block + .collisionRayTrace(world, l, i1, j1, startVec, endVec); + if (movingobjectposition != null) { + result.add(movingobjectposition); + } + } + + MovingObjectPosition movingobjectposition2 = null; + k1 = 200; + + while (k1-- >= 0) { + 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_) { + result.add(movingobjectposition2); + } else { + return result; + } + } + + boolean flag6 = true; + boolean flag3 = true; + boolean flag4 = true; + double d0 = 999.0D; + double d1 = 999.0D; + double d2 = 999.0D; + + if (i > l) { + d0 = l + 1.0D; + } else if (i < l) { + d0 = l + 0.0D; + } else { + flag6 = false; + } + + if (j > i1) { + d1 = i1 + 1.0D; + } else if (j < i1) { + d1 = i1 + 0.0D; + } else { + flag3 = false; + } + + if (k > j1) { + d2 = j1 + 1.0D; + } else if (k < j1) { + d2 = j1 + 0.0D; + } else { + flag4 = false; + } + + double d3 = 999.0D; + double d4 = 999.0D; + double d5 = 999.0D; + double d6 = endVec.xCoord - startVec.xCoord; + double d7 = endVec.yCoord - startVec.yCoord; + double d8 = endVec.zCoord - startVec.zCoord; + + if (flag6) { + d3 = (d0 - startVec.xCoord) / d6; + } + if (flag3) { + d4 = (d1 - startVec.yCoord) / d7; + } + if (flag4) { + d5 = (d2 - startVec.zCoord) / d8; + } + + boolean flag5 = false; + byte b0; + + if (d3 < d4 && d3 < d5) { + if (i > l) { + b0 = 4; + } else { + b0 = 5; + } + + startVec.xCoord = d0; + startVec.yCoord += d7 * d3; + startVec.zCoord += d8 * d3; + } else if (d4 < d5) { + if (j > i1) { + b0 = 0; + } else { + b0 = 1; + } + + startVec.xCoord += d6 * d4; + startVec.yCoord = d1; + startVec.zCoord += d8 * d4; + } else { + if (k > j1) { + b0 = 2; + } else { + b0 = 3; + } + + startVec.xCoord += d6 * d5; + startVec.yCoord += d7 * d5; + startVec.zCoord = d2; + } + + Vec3 vec32 = Vec3.createVectorHelper(startVec.xCoord, startVec.yCoord, startVec.zCoord); + l = (int) (vec32.xCoord = MathHelper.floor_double(startVec.xCoord)); + if (b0 == 5) { + --l; + ++vec32.xCoord; + } + + i1 = (int) (vec32.yCoord = MathHelper.floor_double(startVec.yCoord)); + + if (b0 == 1) { + --i1; + ++vec32.yCoord; + } + + j1 = (int) (vec32.zCoord = MathHelper.floor_double(startVec.zCoord)); + + if (b0 == 3) { + --j1; + ++vec32.zCoord; + } + + 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)) { + MovingObjectPosition movingobjectposition1 = block1 + .collisionRayTrace(world, l, i1, j1, startVec, endVec); + if (movingobjectposition1 != null) { + result.add(movingobjectposition1); + } + } else { + movingobjectposition2 = new MovingObjectPosition(l, i1, j1, b0, startVec, false); + } + } + } + if (p_147447_5_) { + result.add(movingobjectposition2); + } else { + return result; + } + } else { + return result; + } + } else { + return result; } - } else { return result; - } - } else { - return result; } - return result; - } - public static ForgeDirection getDirFromOffset(int xOff, int yOff, int zOff) { - if (xOff != 0 && yOff == 0 && zOff == 0) { - return xOff < 0 ? ForgeDirection.WEST : ForgeDirection.EAST; + public static ForgeDirection getDirFromOffset(int xOff, int yOff, int zOff) { + if (xOff != 0 && yOff == 0 && zOff == 0) { + return xOff < 0 ? ForgeDirection.WEST : ForgeDirection.EAST; + } + if (zOff != 0 && yOff == 0 && xOff == 0) { + return zOff < 0 ? ForgeDirection.NORTH : ForgeDirection.SOUTH; + } + if (yOff != 0 && xOff == 0 && zOff == 0) { + return yOff < 0 ? ForgeDirection.DOWN : ForgeDirection.UP; + } + return ForgeDirection.UNKNOWN; } - if (zOff != 0 && yOff == 0 && xOff == 0) { - return zOff < 0 ? ForgeDirection.NORTH : ForgeDirection.SOUTH; - } - 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); - } + 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"; + // 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"; } 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 bc67613..73a29dd 100644 --- a/src/main/java/com/enderio/core/common/util/WorldCache.java +++ b/src/main/java/com/enderio/core/common/util/WorldCache.java @@ -1,8 +1,5 @@ package com.enderio.core.common.util; -import gnu.trove.map.TIntObjectMap; -import gnu.trove.map.hash.TIntObjectHashMap; - import java.io.File; import java.io.IOException; import java.util.BitSet; @@ -26,203 +23,204 @@ import com.google.common.collect.HashBiMap; import com.google.common.collect.Sets; import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import gnu.trove.map.TIntObjectMap; +import gnu.trove.map.hash.TIntObjectHashMap; /** - * Untested way to save arbitrary to a game save. The name to ID map will be - * hot-swapped when a new save is loaded. + * Untested way to save arbitrary to a game save. The name to ID map will be hot-swapped when a new save is loaded. */ public class WorldCache { - public static final int MAX_ID = Short.MAX_VALUE; + public static final int MAX_ID = Short.MAX_VALUE; - protected String ident; - protected boolean locked; + protected String ident; + protected boolean locked; - protected BitSet usedIDs = new BitSet(MAX_ID); - protected Set blockedIDs = Sets.newHashSet(); + protected BitSet usedIDs = new BitSet(MAX_ID); + protected Set blockedIDs = Sets.newHashSet(); - protected BiMap objToName = HashBiMap.create(); + protected BiMap objToName = HashBiMap.create(); - protected BiMap nameToID = HashBiMap.create(); + protected BiMap nameToID = HashBiMap.create(); - public WorldCache(String ident) { - this(ident, true); - } - - protected WorldCache(String ident, boolean registerToEventBus) { - this.ident = ident; - if (registerToEventBus) { - MinecraftForge.EVENT_BUS.register(this); + public WorldCache(String ident) { + this(ident, true); } - } - @SubscribeEvent - public void onWorldSave(WorldEvent.Save event) { - if (!event.world.isRemote && event.world.provider.dimensionId == 0) { - try { - saveData(getSaveFile()); - } catch (IOException e) { - Throwables.propagate(e); - } + protected WorldCache(String ident, boolean registerToEventBus) { + this.ident = ident; + if (registerToEventBus) { + MinecraftForge.EVENT_BUS.register(this); + } } - } - @SubscribeEvent - public void onWorldLoad(WorldEvent.Load event) { - if (!event.world.isRemote && event.world.provider.dimensionId == 0) { - try { - loadData(getSaveFile()); - } catch (IOException e) { - Throwables.propagate(e); - } + @SubscribeEvent + public void onWorldSave(WorldEvent.Save event) { + if (!event.world.isRemote && event.world.provider.dimensionId == 0) { + try { + saveData(getSaveFile()); + } catch (IOException e) { + Throwables.propagate(e); + } + } } - locked = true; - } - protected void loadData(File file) throws IOException { - if (!file.createNewFile()) { - NBTTagCompound tag = null; - try { - tag = CompressedStreamTools.read(file); - } catch (Exception e) { + @SubscribeEvent + public void onWorldLoad(WorldEvent.Load event) { + if (!event.world.isRemote && event.world.provider.dimensionId == 0) { + try { + loadData(getSaveFile()); + } catch (IOException e) { + Throwables.propagate(e); + } + } + locked = true; + } + + protected void loadData(File file) throws IOException { + if (!file.createNewFile()) { + NBTTagCompound tag = null; + try { + tag = CompressedStreamTools.read(file); + } catch (Exception e) { + generateIDs(); + return; + } + if (tag.hasKey("ItemData")) { + // name <-> id mappings + NBTTagList list = tag.getTagList("ItemData", Constants.NBT.TAG_COMPOUND); + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound dataTag = list.getCompoundTagAt(i); + int id = dataTag.getInteger("V"); + String name = dataTag.getString("K"); + nameToID.put(name, id); + if (objToName.values().contains(name)) { + usedIDs.set(id, true); + } + } + + // blocked ids + for (int id : tag.getIntArray("BlockedItemIds")) { + blockedIDs.add(id); + } + + blockOldIDs(); + mergeNewIDs(); + return; + } + } generateIDs(); - return; - } - if (tag.hasKey("ItemData")) { + } + + protected void saveData(File file) throws IOException { + NBTTagCompound data = new NBTTagCompound(); + // name <-> id mappings - NBTTagList list = tag.getTagList("ItemData", Constants.NBT.TAG_COMPOUND); - for (int i = 0; i < list.tagCount(); i++) { - NBTTagCompound dataTag = list.getCompoundTagAt(i); - int id = dataTag.getInteger("V"); - String name = dataTag.getString("K"); - nameToID.put(name, id); - if (objToName.values().contains(name)) { - usedIDs.set(id, true); - } + NBTTagList dataList = new NBTTagList(); + for (String key : nameToID.keySet()) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setString("K", key); + tag.setInteger("V", nameToID.get(key)); + dataList.appendTag(tag); } - + data.setTag("ItemData", dataList); // blocked ids - for (int id : tag.getIntArray("BlockedItemIds")) { - blockedIDs.add(id); + data.setIntArray("BlockedItemIds", ArrayUtils.toPrimitive(blockedIDs.toArray(new Integer[0]))); + + CompressedStreamTools.write(data, file); + } + + protected void blockOldIDs() { + for (String s : nameToID.keySet()) { + if (!objToName.containsValue(s)) { + blockedIDs.add(nameToID.get(s)); + } + } + Iterator iter = nameToID.keySet().iterator(); + while (iter.hasNext()) { + if (blockedIDs.contains(nameToID.get(iter.next()))) { + iter.remove(); + } } - - blockOldIDs(); - mergeNewIDs(); - return; - } } - generateIDs(); - } - protected void saveData(File file) throws IOException { - NBTTagCompound data = new NBTTagCompound(); - - // name <-> id mappings - NBTTagList dataList = new NBTTagList(); - for (String key : nameToID.keySet()) { - NBTTagCompound tag = new NBTTagCompound(); - tag.setString("K", key); - tag.setInteger("V", nameToID.get(key)); - dataList.appendTag(tag); + protected void mergeNewIDs() { + for (String s : objToName.values()) { + Integer id = nameToID.get(s); + if (id != null) { + setID(s); + } + } } - data.setTag("ItemData", dataList); - // blocked ids - data.setIntArray("BlockedItemIds", ArrayUtils.toPrimitive(blockedIDs.toArray(new Integer[0]))); - CompressedStreamTools.write(data, file); - } - - protected void blockOldIDs() { - for (String s : nameToID.keySet()) { - if (!objToName.containsValue(s)) { - blockedIDs.add(nameToID.get(s)); - } + protected void generateIDs() { + for (Entry e : objToName.entrySet()) { + if (!nameToID.containsKey(e.getValue())) { + setID(e.getValue()); + } + } } - Iterator iter = nameToID.keySet().iterator(); - while (iter.hasNext()) { - if (blockedIDs.contains(nameToID.get(iter.next()))) { - iter.remove(); - } + + protected int getNextAvailableID(String name) { + Integer nextID = nameToID.get(name); + if (nextID != null) { + return nextID; + } else { + nextID = usedIDs.nextClearBit(0); + } + while (blockedIDs.contains(nextID) || nameToID.values().contains(nextID)) { + usedIDs.nextClearBit(nextID++); + } + return nextID; } - } - protected void mergeNewIDs() { - for (String s : objToName.values()) { - Integer id = nameToID.get(s); - if (id != null) { - setID(s); - } + protected void setID(String name) { + setID(name, getNextAvailableID(name)); } - } - protected void generateIDs() { - for (Entry e : objToName.entrySet()) { - if (!nameToID.containsKey(e.getValue())) { - setID(e.getValue()); - } + protected void setID(String name, int id) { + nameToID.put(name, id); + usedIDs.set(id, true); } - } - protected int getNextAvailableID(String name) { - Integer nextID = nameToID.get(name); - if (nextID != null) { - return nextID; - } else { - nextID = usedIDs.nextClearBit(0); + protected File getSaveFile() { + return new File(DimensionManager.getCurrentSaveRootDirectory(), ident + ".json"); } - while (blockedIDs.contains(nextID) || nameToID.values().contains(nextID)) { - usedIDs.nextClearBit(nextID++); + + public void addObject(I object, String name) { + if (locked) { + throw new IllegalStateException("Cannot add to world cache after world load!"); + } + objToName.put(object, name); } - return nextID; - } - protected void setID(String name) { - setID(name, getNextAvailableID(name)); - } - - protected void setID(String name, int id) { - nameToID.put(name, id); - usedIDs.set(id, true); - } - - protected File getSaveFile() { - return new File(DimensionManager.getCurrentSaveRootDirectory(), ident + ".json"); - } - - public void addObject(I object, String name) { - if (locked) { - throw new IllegalStateException("Cannot add to world cache after world load!"); + public int getID(I obj) { + return nameToID.get(getName(obj)); } - objToName.put(object, name); - } - public int getID(I obj) { - return nameToID.get(getName(obj)); - } - - public String getName(I obj) { - return objToName.get(obj); - } - - public I getObject(int id) { - return getObject(nameToID.inverse().get(id)); - } - - public I getObject(String string) { - return objToName.inverse().get(string); - } - - public Iterator getObjects() { - return objToName.keySet().iterator(); - } - - public TIntObjectMap getEnumeratedObjects() { - TIntObjectMap ret = new TIntObjectHashMap(); - for (int i = 0; i <= MAX_ID && usedIDs.nextSetBit(i) >= 0; i++) { - if (usedIDs.get(i)) { - ret.put(i, getObject(i)); - } + public String getName(I obj) { + return objToName.get(obj); + } + + public I getObject(int id) { + return getObject(nameToID.inverse().get(id)); + } + + public I getObject(String string) { + return objToName.inverse().get(string); + } + + public Iterator getObjects() { + return objToName.keySet().iterator(); + } + + public TIntObjectMap getEnumeratedObjects() { + TIntObjectMap ret = new TIntObjectHashMap(); + for (int i = 0; i <= MAX_ID && usedIDs.nextSetBit(i) >= 0; i++) { + if (usedIDs.get(i)) { + ret.put(i, getObject(i)); + } + } + return ret; } - return ret; - } } 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 3a67775..9ae3645 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 @@ -5,19 +5,20 @@ import java.util.Iterator; import com.enderio.core.common.util.BlockCoord; public abstract class AbstractBlockIterator implements Iterable, Iterator { - protected BlockCoord base; - protected AbstractBlockIterator(BlockCoord base) { - this.base = base; - } + protected BlockCoord base; - @Override - public void remove() { - throw new UnsupportedOperationException("You can't remove blocks silly!"); - } + protected AbstractBlockIterator(BlockCoord base) { + this.base = base; + } - @Override - public Iterator iterator() { - return this; - } + @Override + public void remove() { + throw new UnsupportedOperationException("You can't remove blocks silly!"); + } + + @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 6c06b21..f46bc02 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 @@ -3,35 +3,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 CubicBlockIterator(BlockCoord base, int radius) { - super(base); - this.radius = radius; + protected int radius; + protected int minX, minY, minZ; + protected int curX, curY, curZ; + protected int maxX, maxY, maxZ; - curX = minX = base.x - radius; - curY = minY = base.y - radius; - curZ = minZ = base.z - radius; + public CubicBlockIterator(BlockCoord base, int radius) { + super(base); + this.radius = radius; - maxX = base.x + radius; - maxY = base.y + radius; - maxZ = base.z + radius; - } + curX = minX = base.x - radius; + curY = minY = base.y - radius; + curZ = minZ = 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; - } + maxX = base.x + radius; + maxY = base.y + radius; + maxZ = base.z + radius; + } - @Override - public boolean hasNext() { - return curZ <= maxZ; - } + @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; + } } 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 f5779b5..7ec4829 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 @@ -1,59 +1,61 @@ package com.enderio.core.common.util.blockiterators; -import com.enderio.core.common.util.BlockCoord; - import net.minecraftforge.common.util.ForgeDirection; +import com.enderio.core.common.util.BlockCoord; + 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 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; + } + } } - } - 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; - } - - @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; + this.orientation = orientation; } - return coord; - } - @Override - public boolean hasNext() { - return curX <= maxX && curY <= maxY && curZ <= maxZ; - } + @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; + } } 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 96f3084..ad87b1b 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Camera.java +++ b/src/main/java/com/enderio/core/common/vecmath/Camera.java @@ -4,143 +4,152 @@ import java.awt.Rectangle; public class Camera { - private Rectangle viewport; + private Rectangle viewport; - private Matrix4d projectionTranspose; - private Matrix4d projectionMatrix; - private Matrix4d projectionInverse; + private Matrix4d projectionTranspose; + private Matrix4d projectionMatrix; + private Matrix4d projectionInverse; - private Matrix4d viewTranspose; - private Matrix4d viewMatrix; - private Matrix4d viewInverse; + private Matrix4d viewTranspose; + private Matrix4d viewMatrix; + private Matrix4d viewInverse; - public boolean isValid() { - return viewMatrix != null && projectionMatrix != null && viewport != null; - } - - public void setProjectionMatrixAsPerspective(double fovDegrees, double near, double far, int viewportWidth, int viewportHeight) { - setProjectionMatrix(VecmathUtil.createProjectionMatrixAsPerspective(fovDegrees, near, far, viewportWidth, viewportHeight)); - } - - public void setViewMatrixAsLookAt(Vector3d eyePos, Vector3d lookAtPos, Vector3d upVec) { - setViewMatrix(VecmathUtil.createMatrixAsLookAt(eyePos, lookAtPos, upVec)); - } - - public Vector3d getEyePoint() { - Matrix4d vpm = new Matrix4d(); - Matrix4d ivm = getInverseViewMatrix(); - if (ivm == null) { - return null; + public boolean isValid() { + return viewMatrix != null && projectionMatrix != null && viewport != null; } - Matrix4d ipm = getInverseProjectionMatrix(); - if (ipm == null) { - return null; + + public void setProjectionMatrixAsPerspective(double fovDegrees, double near, double far, int viewportWidth, + int viewportHeight) { + setProjectionMatrix( + VecmathUtil.createProjectionMatrixAsPerspective(fovDegrees, near, far, viewportWidth, viewportHeight)); } - vpm.mul(ivm, ipm); - Vector3d eye = new Vector3d(); - ivm.getTranslation(eye); - return eye; - } - - public boolean getRayForPixel(int x, int y, Vector3d eyeOut, Vector3d normalOut) { - if (isValid()) { - VecmathUtil.computeRayForPixel(viewport, getInverseProjectionMatrix(), getInverseViewMatrix(), x, y, eyeOut, normalOut); - return true; + public void setViewMatrixAsLookAt(Vector3d eyePos, Vector3d lookAtPos, Vector3d upVec) { + setViewMatrix(VecmathUtil.createMatrixAsLookAt(eyePos, lookAtPos, upVec)); } - return false; - } - public Vector2d getScreenPoint(Vector3d point3d) { - Vector4d transPoint = new Vector4d(point3d.x, point3d.y, point3d.z, 1); + public Vector3d getEyePoint() { + Matrix4d vpm = new Matrix4d(); + Matrix4d ivm = getInverseViewMatrix(); + if (ivm == null) { + return null; + } + Matrix4d ipm = getInverseProjectionMatrix(); + if (ipm == null) { + return null; + } + vpm.mul(ivm, ipm); - viewMatrix.transform(transPoint); - projectionMatrix.transform(transPoint); - - int halfWidth = viewport.width / 2; - int halfHeight = viewport.height / 2; - Vector2d screenPos = new Vector2d(transPoint.x, transPoint.y); - screenPos.scale(1 / transPoint.w); - screenPos.x = screenPos.x * halfWidth + halfWidth; - screenPos.y = -screenPos.y * halfHeight + halfHeight; - - return screenPos; - } - - public void setViewport(Rectangle viewport) { - if (viewport != null) { - setViewport(viewport.x, viewport.y, viewport.width, viewport.height); + Vector3d eye = new Vector3d(); + ivm.getTranslation(eye); + return eye; } - } - public void setViewport(int x, int y, int width, int height) { - viewport = new Rectangle(x, y, width, height); - } - - public Rectangle getViewport() { - return viewport; - } - - public Matrix4d getProjectionMatrix() { - return projectionMatrix; - } - - public Matrix4d getTransposeProjectionMatrix() { - return projectionTranspose; - } - - public Matrix4d getInverseProjectionMatrix() { - if (projectionMatrix != null) { - if (projectionInverse == null) { - projectionInverse = new Matrix4d(projectionMatrix); - projectionInverse.invert(); - } - return projectionInverse; - } else { - return null; + public boolean getRayForPixel(int x, int y, Vector3d eyeOut, Vector3d normalOut) { + if (isValid()) { + VecmathUtil.computeRayForPixel( + viewport, + getInverseProjectionMatrix(), + getInverseViewMatrix(), + x, + y, + eyeOut, + normalOut); + return true; + } + return false; } - } - public void setProjectionMatrix(Matrix4d matrix) { - if (projectionMatrix == null) { - projectionMatrix = new Matrix4d(); - projectionTranspose = new Matrix4d(); + public Vector2d getScreenPoint(Vector3d point3d) { + Vector4d transPoint = new Vector4d(point3d.x, point3d.y, point3d.z, 1); + + viewMatrix.transform(transPoint); + projectionMatrix.transform(transPoint); + + int halfWidth = viewport.width / 2; + int halfHeight = viewport.height / 2; + Vector2d screenPos = new Vector2d(transPoint.x, transPoint.y); + screenPos.scale(1 / transPoint.w); + screenPos.x = screenPos.x * halfWidth + halfWidth; + screenPos.y = -screenPos.y * halfHeight + halfHeight; + + return screenPos; } - projectionMatrix.set(matrix); - projectionTranspose.set(matrix); - projectionTranspose.transpose(); - projectionInverse = null; - } - public Matrix4d getViewMatrix() { - return viewMatrix; - } - - public Matrix4d getTransposeViewMatrix() { - return viewTranspose; - } - - public Matrix4d getInverseViewMatrix() { - if (viewMatrix != null) { - if (viewInverse == null) { - viewInverse = new Matrix4d(viewMatrix); - viewInverse.invert(); - } - return viewInverse; - } else { - return null; + public void setViewport(Rectangle viewport) { + if (viewport != null) { + setViewport(viewport.x, viewport.y, viewport.width, viewport.height); + } } - } - public void setViewMatrix(Matrix4d matrix) { - if (viewMatrix == null) { - viewMatrix = new Matrix4d(); - viewTranspose = new Matrix4d(); + public void setViewport(int x, int y, int width, int height) { + viewport = new Rectangle(x, y, width, height); + } + + public Rectangle getViewport() { + return viewport; + } + + public Matrix4d getProjectionMatrix() { + return projectionMatrix; + } + + public Matrix4d getTransposeProjectionMatrix() { + return projectionTranspose; + } + + public Matrix4d getInverseProjectionMatrix() { + if (projectionMatrix != null) { + if (projectionInverse == null) { + projectionInverse = new Matrix4d(projectionMatrix); + projectionInverse.invert(); + } + return projectionInverse; + } else { + return null; + } + } + + public void setProjectionMatrix(Matrix4d matrix) { + if (projectionMatrix == null) { + projectionMatrix = new Matrix4d(); + projectionTranspose = new Matrix4d(); + } + projectionMatrix.set(matrix); + projectionTranspose.set(matrix); + projectionTranspose.transpose(); + projectionInverse = null; + } + + public Matrix4d getViewMatrix() { + return viewMatrix; + } + + public Matrix4d getTransposeViewMatrix() { + return viewTranspose; + } + + public Matrix4d getInverseViewMatrix() { + if (viewMatrix != null) { + if (viewInverse == null) { + viewInverse = new Matrix4d(viewMatrix); + viewInverse.invert(); + } + return viewInverse; + } else { + return null; + } + } + + public void setViewMatrix(Matrix4d matrix) { + if (viewMatrix == null) { + viewMatrix = new Matrix4d(); + viewTranspose = new Matrix4d(); + } + viewMatrix.set(matrix); + viewTranspose.set(matrix); + viewTranspose.transpose(); + viewInverse = null; } - viewMatrix.set(matrix); - viewTranspose.set(matrix); - viewTranspose.transpose(); - viewInverse = null; - } } 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 52166bb..e44d3db 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Matrix4d.java +++ b/src/main/java/com/enderio/core/common/vecmath/Matrix4d.java @@ -4,565 +4,608 @@ import java.nio.FloatBuffer; public class Matrix4d { - public double m00 = 0; - public double m01 = 0; - public double m02 = 0; - public double m03 = 0; - public double m10 = 0; - public double m11 = 0; - public double m12 = 0; - public double m13 = 0; - public double m20 = 0; - public double m21 = 0; - public double m22 = 0; - public double m23 = 0; - public double m30 = 0; - public double m31 = 0; - public double m32 = 0; - public double m33 = 0; + public double m00 = 0; + public double m01 = 0; + public double m02 = 0; + public double m03 = 0; + public double m10 = 0; + public double m11 = 0; + public double m12 = 0; + public double m13 = 0; + public double m20 = 0; + public double m21 = 0; + public double m22 = 0; + public double m23 = 0; + public double m30 = 0; + public double m31 = 0; + public double m32 = 0; + public double m33 = 0; - public Matrix4d() { - } + public Matrix4d() {} - public Matrix4d(float[] arr) { - m00 = arr[0]; - m01 = arr[1]; - m02 = arr[2]; - m03 = arr[3]; + public Matrix4d(float[] arr) { + m00 = arr[0]; + m01 = arr[1]; + m02 = arr[2]; + m03 = arr[3]; - m10 = arr[4]; - m11 = arr[5]; - m12 = arr[6]; - m13 = arr[7]; + m10 = arr[4]; + m11 = arr[5]; + m12 = arr[6]; + m13 = arr[7]; - m20 = arr[8]; - m21 = arr[9]; - m22 = arr[10]; - m23 = arr[11]; + m20 = arr[8]; + m21 = arr[9]; + m22 = arr[10]; + m23 = arr[11]; - m30 = arr[12]; - m31 = arr[13]; - m32 = arr[14]; - m33 = arr[15]; - } - - public Matrix4d(double[] arr) { - m00 = arr[0]; - m01 = arr[1]; - m02 = arr[2]; - m03 = arr[3]; - - m10 = arr[4]; - m11 = arr[5]; - m12 = arr[6]; - m13 = arr[7]; - - m20 = arr[8]; - m21 = arr[9]; - m22 = arr[10]; - m23 = arr[11]; - - m30 = arr[12]; - m31 = arr[13]; - m32 = arr[14]; - m33 = arr[15]; - } - - public Matrix4d(Matrix4d other) { - m00 = other.m00; - m01 = other.m01; - m02 = other.m02; - m03 = other.m03; - - m10 = other.m10; - m11 = other.m11; - m12 = other.m12; - m13 = other.m13; - - m20 = other.m20; - m21 = other.m21; - m22 = other.m22; - m23 = other.m23; - - m30 = other.m30; - m31 = other.m31; - m32 = other.m32; - 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) { - - this.m00 = m00; - this.m01 = m01; - this.m02 = m02; - this.m03 = m03; - - this.m10 = m10; - this.m11 = m11; - this.m12 = m12; - this.m13 = m13; - - this.m20 = m20; - this.m21 = m21; - this.m22 = m22; - this.m23 = m23; - - this.m30 = m30; - this.m31 = m31; - this.m32 = m32; - this.m33 = m33; - - } - - public Matrix4d(FloatBuffer modelview) { - m00 = modelview.get(0); - m01 = modelview.get(1); - m02 = modelview.get(2); - m03 = modelview.get(3); - - m10 = modelview.get(4); - m11 = modelview.get(5); - m12 = modelview.get(6); - m13 = modelview.get(7); - - m20 = modelview.get(8); - m21 = modelview.get(9); - m22 = modelview.get(10); - m23 = modelview.get(11); - - m30 = modelview.get(12); - m31 = modelview.get(13); - m32 = modelview.get(14); - m33 = modelview.get(15); - } - - public final void setIdentity() { - m00 = 1.0; - m01 = 0.0; - m02 = 0.0; - m03 = 0.0; - - m10 = 0.0; - m11 = 1.0; - m12 = 0.0; - m13 = 0.0; - - m20 = 0.0; - m21 = 0.0; - m22 = 1.0; - m23 = 0.0; - - m30 = 0.0; - m31 = 0.0; - m32 = 0.0; - m33 = 1.0; - } - - public void set(Matrix4d other) { - m00 = other.m00; - m01 = other.m01; - m02 = other.m02; - m03 = other.m03; - - m10 = other.m10; - m11 = other.m11; - m12 = other.m12; - m13 = other.m13; - - m20 = other.m20; - m21 = other.m21; - m22 = other.m22; - m23 = other.m23; - - m30 = other.m30; - m31 = other.m31; - m32 = other.m32; - m33 = other.m33; - - } - - public void set(double[] values) { - m00 = values[0]; - m01 = values[1]; - m02 = values[2]; - m03 = values[3]; - m10 = values[4]; - m11 = values[5]; - m12 = values[6]; - m13 = values[7]; - m20 = values[8]; - m21 = values[9]; - m22 = values[10]; - m23 = values[11]; - m30 = values[12]; - m31 = values[13]; - m32 = values[14]; - m33 = values[15]; - } - - public double getElement(int row, int col) { - switch (row) { - case 0: - switch (col) { - case 0: - return m00; - case 1: - return m01; - case 2: - return m02; - case 3: - return m03; - default: - break; - } - break; - - case 1: - switch (col) { - case 0: - return m10; - case 1: - return m11; - case 2: - return m12; - case 3: - return m13; - default: - break; - } - break; - - case 2: - switch (col) { - case 0: - return m20; - case 1: - return m21; - case 2: - return m22; - case 3: - return m23; - default: - break; - } - break; - - case 3: - switch (col) { - case 0: - return m30; - case 1: - return m31; - case 2: - return m32; - case 3: - return m33; - default: - break; - } - break; - - default: - break; - } - return 0; - } - - public void setElement(int row, int column, double val) { - switch (row) { - - case 0: - switch (column) { - case 0: - m00 = val; - break; - case 1: - m01 = val; - break; - case 2: - m02 = val; - break; - case 3: - m03 = val; - break; - default: - break; - } - break; - - case 1: - switch (column) { - case 0: - m10 = val; - break; - case 1: - m11 = val; - break; - case 2: - m12 = val; - break; - case 3: - m13 = val; - break; - default: - break; - } - break; - - case 2: - switch (column) { - case 0: - m20 = val; - break; - case 1: - m21 = val; - break; - case 2: - m22 = val; - break; - case 3: - m23 = val; - break; - default: - break; - } - break; - - case 3: - switch (column) { - case 0: - m30 = val; - break; - case 1: - m31 = val; - break; - case 2: - m32 = val; - break; - case 3: - m33 = val; - break; - default: - break; - } - break; - - default: - break; + m30 = arr[12]; + m31 = arr[13]; + m32 = arr[14]; + m33 = arr[15]; } - } + public Matrix4d(double[] arr) { + m00 = arr[0]; + m01 = arr[1]; + m02 = arr[2]; + m03 = arr[3]; - public void getTranslation(Vector3d trans) { - trans.x = m03; - trans.y = m13; - trans.z = m23; - } + m10 = arr[4]; + m11 = arr[5]; + m12 = arr[6]; + m13 = arr[7]; - public void setTranslation(Vector3d trans) { - m03 = trans.x; - m13 = trans.y; - m23 = trans.z; - } + m20 = arr[8]; + m21 = arr[9]; + m22 = arr[10]; + m23 = arr[11]; - public void makeRotationX(double angle) { - setIdentity(); - double sin = Math.sin(angle); - double cos = Math.cos(angle); - m11 = cos; - m12 = -sin; - m21 = sin; - m22 = cos; - } - - public void makeRotationY(double angle) { - setIdentity(); - double sin = Math.sin(angle); - double cos = Math.cos(angle); - m00 = cos; - m02 = sin; - m20 = -sin; - m22 = cos; - } - - public void makeRotationZ(double angle) { - setIdentity(); - double sin = Math.sin(angle); - double cos = Math.cos(angle); - m00 = cos; - m01 = -sin; - m10 = sin; - m11 = cos; - } - - public void transform(Vector3d vec) { - double x = m00 * vec.x + m01 * vec.y + m02 * vec.z + m03; - double y = m10 * vec.x + m11 * vec.y + m12 * vec.z + m13; - vec.z = m20 * vec.x + m21 * vec.y + m22 * vec.z + m23; - vec.x = x; - vec.y = y; - } - - public void transform(Vector4d vec) { - double x = m00 * vec.x + m01 * vec.y + m02 * vec.z + m03 * vec.w; - double y = m10 * vec.x + m11 * vec.y + m12 * vec.z + m13 * vec.w; - double z = m20 * vec.x + m21 * vec.y + m22 * vec.z + m23 * vec.w; - vec.w = m30 * vec.x + m31 * vec.y + m32 * vec.z + m33 * vec.w; - vec.x = x; - vec.y = y; - vec.z = z; - } - - public void transformNormal(Vector3f normal) { - double x = m00 * normal.x + m01 * normal.y + m02 * normal.z; - double y = m10 * normal.x + m11 * normal.y + m12 * normal.z; - normal.z = (float) (m20 * normal.x + m21 * normal.y + m22 * normal.z); - normal.x = (float) x; - normal.y = (float) y; - - } - - public void transformNormal(Vector3d normal) { - double x = m00 * normal.x + m01 * normal.y + m02 * normal.z; - double y = m10 * normal.x + m11 * normal.y + m12 * normal.z; - normal.z = m20 * normal.x + m21 * normal.y + m22 * normal.z; - normal.x = x; - normal.y = y; - } - - public void mul(Matrix4d m1, Matrix4d m2) { - set(m1); - mul(m2); - } - - public void mul(Matrix4d m) { - double m00Tmp = m00 * m.m00 + m01 * m.m10 + m02 * m.m20 + m03 * m.m30; - double m01Tmp = m00 * m.m01 + m01 * m.m11 + m02 * m.m21 + m03 * m.m31; - double m02Tmp = m00 * m.m02 + m01 * m.m12 + m02 * m.m22 + m03 * m.m32; - double m03Tmp = m00 * m.m03 + m01 * m.m13 + m02 * m.m23 + m03 * m.m33; - - double m10Tmp = m10 * m.m00 + m11 * m.m10 + m12 * m.m20 + m13 * m.m30; - double m11Tmp = m10 * m.m01 + m11 * m.m11 + m12 * m.m21 + m13 * m.m31; - double m12Tmp = m10 * m.m02 + m11 * m.m12 + m12 * m.m22 + m13 * m.m32; - double m13Tmp = m10 * m.m03 + m11 * m.m13 + m12 * m.m23 + m13 * m.m33; - - double m20Tmp = m20 * m.m00 + m21 * m.m10 + m22 * m.m20 + m23 * m.m30; - double m21Tmp = m20 * m.m01 + m21 * m.m11 + m22 * m.m21 + m23 * m.m31; - double m22Tmp = m20 * m.m02 + m21 * m.m12 + m22 * m.m22 + m23 * m.m32; - double m23Tmp = m20 * m.m03 + m21 * m.m13 + m22 * m.m23 + m23 * m.m33; - - double m30Tmp = m30 * m.m00 + m31 * m.m10 + m32 * m.m20 + m33 * m.m30; - double m31Tmp = m30 * m.m01 + m31 * m.m11 + m32 * m.m21 + m33 * m.m31; - double m32Tmp = m30 * m.m02 + m31 * m.m12 + m32 * m.m22 + m33 * m.m32; - double m33Tmp = m30 * m.m03 + m31 * m.m13 + m32 * m.m23 + m33 * m.m33; - - m00 = m00Tmp; - m01 = m01Tmp; - m02 = m02Tmp; - m03 = m03Tmp; - m10 = m10Tmp; - m11 = m11Tmp; - m12 = m12Tmp; - m13 = m13Tmp; - m20 = m20Tmp; - m21 = m21Tmp; - m22 = m22Tmp; - m23 = m23Tmp; - m30 = m30Tmp; - m31 = m31Tmp; - m32 = m32Tmp; - m33 = m33Tmp; - } - - public void transpose() { - double tmp = m10; - m10 = m01; - m01 = tmp; - - tmp = m20; - m20 = m02; - m02 = tmp; - - tmp = m30; - m30 = m03; - m03 = tmp; - - tmp = m21; - m21 = m12; - m12 = tmp; - - tmp = m31; - m31 = m13; - m13 = tmp; - - tmp = m32; - m32 = m23; - m23 = tmp; - } - - public void invert() { - double det = determinant(); - if (det == 0) { - throw new RuntimeException("Cannot invert matrix with a determinat of 0."); + m30 = arr[12]; + m31 = arr[13]; + m32 = arr[14]; + m33 = arr[15]; } - double detInv = 1f / det; - // first row - double t00 = determinant3x3(m11, m21, m31, m12, m22, m32, m13, m23, m33); - double t01 = -determinant3x3(m01, m21, m31, m02, m22, m32, m03, m23, m33); - double t02 = determinant3x3(m01, m11, m31, m02, m12, m32, m03, m13, m33); - double t03 = -determinant3x3(m01, m11, m21, m02, m12, m22, m03, m13, m23); - // second row - double t10 = -determinant3x3(m10, m20, m30, m12, m22, m32, m13, m23, m33); - double t11 = determinant3x3(m00, m20, m30, m02, m22, m32, m03, m23, m33); - double t12 = -determinant3x3(m00, m10, m30, m02, m12, m32, m03, m13, m33); - double t13 = determinant3x3(m00, m10, m20, m02, m12, m22, m03, m13, m23); - // third row - double t20 = determinant3x3(m10, m20, m30, m11, m21, m31, m13, m23, m33); - double t21 = -determinant3x3(m00, m20, m30, m01, m21, m31, m03, m23, m33); - double t22 = determinant3x3(m00, m10, m30, m01, m11, m31, m03, m13, m33); - double t23 = -determinant3x3(m00, m10, m20, m01, m11, m21, m03, m13, m23); - // fourth row - double t30 = -determinant3x3(m10, m20, m30, m11, m21, m31, m12, m22, m32); - double t31 = determinant3x3(m00, m20, m30, m01, m21, m31, m02, m22, m32); - double t32 = -determinant3x3(m00, m10, m30, m01, m11, m31, m02, m12, m32); - double t33 = determinant3x3(m00, m10, m20, m01, m11, m21, m02, m12, m22); + public Matrix4d(Matrix4d other) { + m00 = other.m00; + m01 = other.m01; + m02 = other.m02; + m03 = other.m03; - m00 = t00 * detInv; - m11 = t11 * detInv; - m22 = t22 * detInv; - m33 = t33 * detInv; - m10 = t10 * detInv; - m01 = t01 * detInv; - m02 = t02 * detInv; - m20 = t20 * detInv; - m21 = t21 * detInv; - m12 = t12 * detInv; - m30 = t30 * detInv; - m03 = t03 * detInv; - m31 = t31 * detInv; - m13 = t13 * detInv; - m23 = t23 * detInv; - m32 = t32 * detInv; + m10 = other.m10; + m11 = other.m11; + m12 = other.m12; + m13 = other.m13; - } + m20 = other.m20; + m21 = other.m21; + m22 = other.m22; + m23 = other.m23; - 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); - return result; - } + m30 = other.m30; + m31 = other.m31; + m32 = other.m32; + m33 = other.m33; + } - private double determinant3x3(double e00, double e01, double e02, double e10, double e11, double e12, double e20, double e21, double e22) { - return e00 * (e11 * e22 - e12 * e21) + e01 * (e12 * e20 - e10 * e22) + e02 * (e10 * e21 - e11 * e20); - } + 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) { - @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"; - } + this.m00 = m00; + this.m01 = m01; + this.m02 = m02; + this.m03 = m03; + + this.m10 = m10; + this.m11 = m11; + this.m12 = m12; + this.m13 = m13; + + this.m20 = m20; + this.m21 = m21; + this.m22 = m22; + this.m23 = m23; + + this.m30 = m30; + this.m31 = m31; + this.m32 = m32; + this.m33 = m33; + + } + + public Matrix4d(FloatBuffer modelview) { + m00 = modelview.get(0); + m01 = modelview.get(1); + m02 = modelview.get(2); + m03 = modelview.get(3); + + m10 = modelview.get(4); + m11 = modelview.get(5); + m12 = modelview.get(6); + m13 = modelview.get(7); + + m20 = modelview.get(8); + m21 = modelview.get(9); + m22 = modelview.get(10); + m23 = modelview.get(11); + + m30 = modelview.get(12); + m31 = modelview.get(13); + m32 = modelview.get(14); + m33 = modelview.get(15); + } + + public final void setIdentity() { + m00 = 1.0; + m01 = 0.0; + m02 = 0.0; + m03 = 0.0; + + m10 = 0.0; + m11 = 1.0; + m12 = 0.0; + m13 = 0.0; + + m20 = 0.0; + m21 = 0.0; + m22 = 1.0; + m23 = 0.0; + + m30 = 0.0; + m31 = 0.0; + m32 = 0.0; + m33 = 1.0; + } + + public void set(Matrix4d other) { + m00 = other.m00; + m01 = other.m01; + m02 = other.m02; + m03 = other.m03; + + m10 = other.m10; + m11 = other.m11; + m12 = other.m12; + m13 = other.m13; + + m20 = other.m20; + m21 = other.m21; + m22 = other.m22; + m23 = other.m23; + + m30 = other.m30; + m31 = other.m31; + m32 = other.m32; + m33 = other.m33; + + } + + public void set(double[] values) { + m00 = values[0]; + m01 = values[1]; + m02 = values[2]; + m03 = values[3]; + m10 = values[4]; + m11 = values[5]; + m12 = values[6]; + m13 = values[7]; + m20 = values[8]; + m21 = values[9]; + m22 = values[10]; + m23 = values[11]; + m30 = values[12]; + m31 = values[13]; + m32 = values[14]; + m33 = values[15]; + } + + public double getElement(int row, int col) { + switch (row) { + case 0: + switch (col) { + case 0: + return m00; + case 1: + return m01; + case 2: + return m02; + case 3: + return m03; + default: + break; + } + break; + + case 1: + switch (col) { + case 0: + return m10; + case 1: + return m11; + case 2: + return m12; + case 3: + return m13; + default: + break; + } + break; + + case 2: + switch (col) { + case 0: + return m20; + case 1: + return m21; + case 2: + return m22; + case 3: + return m23; + default: + break; + } + break; + + case 3: + switch (col) { + case 0: + return m30; + case 1: + return m31; + case 2: + return m32; + case 3: + return m33; + default: + break; + } + break; + + default: + break; + } + return 0; + } + + public void setElement(int row, int column, double val) { + switch (row) { + + case 0: + switch (column) { + case 0: + m00 = val; + break; + case 1: + m01 = val; + break; + case 2: + m02 = val; + break; + case 3: + m03 = val; + break; + default: + break; + } + break; + + case 1: + switch (column) { + case 0: + m10 = val; + break; + case 1: + m11 = val; + break; + case 2: + m12 = val; + break; + case 3: + m13 = val; + break; + default: + break; + } + break; + + case 2: + switch (column) { + case 0: + m20 = val; + break; + case 1: + m21 = val; + break; + case 2: + m22 = val; + break; + case 3: + m23 = val; + break; + default: + break; + } + break; + + case 3: + switch (column) { + case 0: + m30 = val; + break; + case 1: + m31 = val; + break; + case 2: + m32 = val; + break; + case 3: + m33 = val; + break; + default: + break; + } + break; + + default: + break; + } + + } + + public void getTranslation(Vector3d trans) { + trans.x = m03; + trans.y = m13; + trans.z = m23; + } + + public void setTranslation(Vector3d trans) { + m03 = trans.x; + m13 = trans.y; + m23 = trans.z; + } + + public void makeRotationX(double angle) { + setIdentity(); + double sin = Math.sin(angle); + double cos = Math.cos(angle); + m11 = cos; + m12 = -sin; + m21 = sin; + m22 = cos; + } + + public void makeRotationY(double angle) { + setIdentity(); + double sin = Math.sin(angle); + double cos = Math.cos(angle); + m00 = cos; + m02 = sin; + m20 = -sin; + m22 = cos; + } + + public void makeRotationZ(double angle) { + setIdentity(); + double sin = Math.sin(angle); + double cos = Math.cos(angle); + m00 = cos; + m01 = -sin; + m10 = sin; + m11 = cos; + } + + public void transform(Vector3d vec) { + double x = m00 * vec.x + m01 * vec.y + m02 * vec.z + m03; + double y = m10 * vec.x + m11 * vec.y + m12 * vec.z + m13; + vec.z = m20 * vec.x + m21 * vec.y + m22 * vec.z + m23; + vec.x = x; + vec.y = y; + } + + public void transform(Vector4d vec) { + double x = m00 * vec.x + m01 * vec.y + m02 * vec.z + m03 * vec.w; + double y = m10 * vec.x + m11 * vec.y + m12 * vec.z + m13 * vec.w; + double z = m20 * vec.x + m21 * vec.y + m22 * vec.z + m23 * vec.w; + vec.w = m30 * vec.x + m31 * vec.y + m32 * vec.z + m33 * vec.w; + vec.x = x; + vec.y = y; + vec.z = z; + } + + public void transformNormal(Vector3f normal) { + double x = m00 * normal.x + m01 * normal.y + m02 * normal.z; + double y = m10 * normal.x + m11 * normal.y + m12 * normal.z; + normal.z = (float) (m20 * normal.x + m21 * normal.y + m22 * normal.z); + normal.x = (float) x; + normal.y = (float) y; + + } + + public void transformNormal(Vector3d normal) { + double x = m00 * normal.x + m01 * normal.y + m02 * normal.z; + double y = m10 * normal.x + m11 * normal.y + m12 * normal.z; + normal.z = m20 * normal.x + m21 * normal.y + m22 * normal.z; + normal.x = x; + normal.y = y; + } + + public void mul(Matrix4d m1, Matrix4d m2) { + set(m1); + mul(m2); + } + + public void mul(Matrix4d m) { + double m00Tmp = m00 * m.m00 + m01 * m.m10 + m02 * m.m20 + m03 * m.m30; + double m01Tmp = m00 * m.m01 + m01 * m.m11 + m02 * m.m21 + m03 * m.m31; + double m02Tmp = m00 * m.m02 + m01 * m.m12 + m02 * m.m22 + m03 * m.m32; + double m03Tmp = m00 * m.m03 + m01 * m.m13 + m02 * m.m23 + m03 * m.m33; + + double m10Tmp = m10 * m.m00 + m11 * m.m10 + m12 * m.m20 + m13 * m.m30; + double m11Tmp = m10 * m.m01 + m11 * m.m11 + m12 * m.m21 + m13 * m.m31; + double m12Tmp = m10 * m.m02 + m11 * m.m12 + m12 * m.m22 + m13 * m.m32; + double m13Tmp = m10 * m.m03 + m11 * m.m13 + m12 * m.m23 + m13 * m.m33; + + double m20Tmp = m20 * m.m00 + m21 * m.m10 + m22 * m.m20 + m23 * m.m30; + double m21Tmp = m20 * m.m01 + m21 * m.m11 + m22 * m.m21 + m23 * m.m31; + double m22Tmp = m20 * m.m02 + m21 * m.m12 + m22 * m.m22 + m23 * m.m32; + double m23Tmp = m20 * m.m03 + m21 * m.m13 + m22 * m.m23 + m23 * m.m33; + + double m30Tmp = m30 * m.m00 + m31 * m.m10 + m32 * m.m20 + m33 * m.m30; + double m31Tmp = m30 * m.m01 + m31 * m.m11 + m32 * m.m21 + m33 * m.m31; + double m32Tmp = m30 * m.m02 + m31 * m.m12 + m32 * m.m22 + m33 * m.m32; + double m33Tmp = m30 * m.m03 + m31 * m.m13 + m32 * m.m23 + m33 * m.m33; + + m00 = m00Tmp; + m01 = m01Tmp; + m02 = m02Tmp; + m03 = m03Tmp; + m10 = m10Tmp; + m11 = m11Tmp; + m12 = m12Tmp; + m13 = m13Tmp; + m20 = m20Tmp; + m21 = m21Tmp; + m22 = m22Tmp; + m23 = m23Tmp; + m30 = m30Tmp; + m31 = m31Tmp; + m32 = m32Tmp; + m33 = m33Tmp; + } + + public void transpose() { + double tmp = m10; + m10 = m01; + m01 = tmp; + + tmp = m20; + m20 = m02; + m02 = tmp; + + tmp = m30; + m30 = m03; + m03 = tmp; + + tmp = m21; + m21 = m12; + m12 = tmp; + + tmp = m31; + m31 = m13; + m13 = tmp; + + tmp = m32; + m32 = m23; + m23 = tmp; + } + + public void invert() { + double det = determinant(); + if (det == 0) { + throw new RuntimeException("Cannot invert matrix with a determinat of 0."); + } + double detInv = 1f / det; + + // first row + double t00 = determinant3x3(m11, m21, m31, m12, m22, m32, m13, m23, m33); + double t01 = -determinant3x3(m01, m21, m31, m02, m22, m32, m03, m23, m33); + double t02 = determinant3x3(m01, m11, m31, m02, m12, m32, m03, m13, m33); + double t03 = -determinant3x3(m01, m11, m21, m02, m12, m22, m03, m13, m23); + // second row + double t10 = -determinant3x3(m10, m20, m30, m12, m22, m32, m13, m23, m33); + double t11 = determinant3x3(m00, m20, m30, m02, m22, m32, m03, m23, m33); + double t12 = -determinant3x3(m00, m10, m30, m02, m12, m32, m03, m13, m33); + double t13 = determinant3x3(m00, m10, m20, m02, m12, m22, m03, m13, m23); + // third row + double t20 = determinant3x3(m10, m20, m30, m11, m21, m31, m13, m23, m33); + double t21 = -determinant3x3(m00, m20, m30, m01, m21, m31, m03, m23, m33); + double t22 = determinant3x3(m00, m10, m30, m01, m11, m31, m03, m13, m33); + double t23 = -determinant3x3(m00, m10, m20, m01, m11, m21, m03, m13, m23); + // fourth row + double t30 = -determinant3x3(m10, m20, m30, m11, m21, m31, m12, m22, m32); + double t31 = determinant3x3(m00, m20, m30, m01, m21, m31, m02, m22, m32); + double t32 = -determinant3x3(m00, m10, m30, m01, m11, m31, m02, m12, m32); + double t33 = determinant3x3(m00, m10, m20, m01, m11, m21, m02, m12, m22); + + m00 = t00 * detInv; + m11 = t11 * detInv; + m22 = t22 * detInv; + m33 = t33 * detInv; + m10 = t10 * detInv; + m01 = t01 * detInv; + m02 = t02 * detInv; + m20 = t20 * detInv; + m21 = t21 * detInv; + m12 = t12 * detInv; + m30 = t30 * detInv; + m03 = t03 * detInv; + m31 = t31 * detInv; + m13 = t13 * detInv; + m23 = t23 * detInv; + m32 = t32 * detInv; + + } + + 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); + return result; + } + + private double determinant3x3(double e00, double e01, double e02, double e10, double e11, double e12, double e20, + double e21, double e22) { + return e00 * (e11 * e22 - e12 * e21) + e01 * (e12 * e20 - e10 * e22) + e02 * (e10 * e21 - e11 * e20); + } + + @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"; + } } 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 ea6866e..054e4c3 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Quat4d.java +++ b/src/main/java/com/enderio/core/common/vecmath/Quat4d.java @@ -2,56 +2,55 @@ package com.enderio.core.common.vecmath; public class Quat4d { - public static Quat4d makeRotate(double angle, Vector3d axis) { - double epsilon = 0.0000001; + public static Quat4d makeRotate(double angle, Vector3d axis) { + double epsilon = 0.0000001; - double x = axis.x; - double y = axis.y; - double z = axis.z; - double length = Math.sqrt(x * x + y * y + z * z); - if (length < epsilon) { - // ~zero length axis, so reset rotation to zero. - return new Quat4d(); + double x = axis.x; + double y = axis.y; + double z = axis.z; + double length = Math.sqrt(x * x + y * y + z * z); + if (length < epsilon) { + // ~zero length axis, so reset rotation to zero. + return new Quat4d(); + } + + double inversenorm = 1.0 / length; + double coshalfangle = Math.cos(0.5 * angle); + double sinhalfangle = Math.sin(0.5 * angle); + + Quat4d res = new Quat4d(); + res.x = x * sinhalfangle * inversenorm; + res.y = y * sinhalfangle * inversenorm; + res.z = z * sinhalfangle * inversenorm; + res.w = coshalfangle; + return res; } - double inversenorm = 1.0 / length; - double coshalfangle = Math.cos(0.5 * angle); - double sinhalfangle = Math.sin(0.5 * angle); + public double x; + public double y; + public double z; + public double w; - Quat4d res = new Quat4d(); - res.x = x * sinhalfangle * inversenorm; - res.y = y * sinhalfangle * inversenorm; - res.z = z * sinhalfangle * inversenorm; - res.w = coshalfangle; - return res; - } + public Quat4d() {} - public double x; - public double y; - public double z; - public double w; + public void rotate(Vector3d vec) { + double d = -x * vec.x - y * vec.y - z * vec.z; + double d1 = w * vec.x + y * vec.z - z * vec.y; + double d2 = w * vec.y - x * vec.z + z * vec.x; + double d3 = w * vec.z + x * vec.y - y * vec.x; + vec.x = d1 * w - d * x - d2 * z + d3 * y; + vec.y = d2 * w - d * y + d1 * z - d3 * x; + vec.z = d3 * w - d * z - d1 * y + d2 * x; + } - public Quat4d() { - } - - public void rotate(Vector3d vec) { - double d = -x * vec.x - y * vec.y - z * vec.z; - double d1 = w * vec.x + y * vec.z - z * vec.y; - double d2 = w * vec.y - x * vec.z + z * vec.x; - double d3 = w * vec.z + x * vec.y - y * vec.x; - vec.x = d1 * w - d * x - d2 * z + d3 * y; - vec.y = d2 * w - d * y + d1 * z - d3 * x; - vec.z = d3 * w - d * z - d1 * y + d2 * x; - } - - public void rotate(Vector3f vec) { - double d = -x * vec.x - y * vec.y - z * vec.z; - double d1 = w * vec.x + y * vec.z - z * vec.y; - double d2 = w * vec.y - x * vec.z + z * vec.x; - double d3 = w * vec.z + x * vec.y - y * vec.x; - vec.x = (float) (d1 * w - d * x - d2 * z + d3 * y); - vec.y = (float) (d2 * w - d * y + d1 * z - d3 * x); - vec.z = (float) (d3 * w - d * z - d1 * y + d2 * x); - } + public void rotate(Vector3f vec) { + double d = -x * vec.x - y * vec.y - z * vec.z; + double d1 = w * vec.x + y * vec.z - z * vec.y; + double d2 = w * vec.y - x * vec.z + z * vec.x; + double d3 = w * vec.z + x * vec.y - y * vec.x; + vec.x = (float) (d1 * w - d * x - d2 * z + d3 * y); + vec.y = (float) (d2 * w - d * y + d1 * z - d3 * x); + vec.z = (float) (d3 * w - d * z - d1 * y + d2 * x); + } } 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 093893f..5d479b4 100644 --- a/src/main/java/com/enderio/core/common/vecmath/VecmathUtil.java +++ b/src/main/java/com/enderio/core/common/vecmath/VecmathUtil.java @@ -4,610 +4,607 @@ import java.awt.Rectangle; public class VecmathUtil { - /** - * Returns the distance from a point to a plane. - * - * @param plane - * the plane. - * @param point - * the point. - * @return the distance between them. - */ - public static double distanceFromPointToPlane(Vector4d plane, Vector3d point) { - Vector4d newPoint = new Vector4d(point.x, point.y, point.z, 1); - return plane.dot(newPoint); - } - - public static void computePlaneEquation(Vector4d a, Vector4d b, Vector4d c, Vector4d result) { - computePlaneEquation(new Vector3d(a.x, a.y, a.z), new Vector3d(b.x, b.y, b.z), new Vector3d(c.x, c.y, c.z), result); - } - - public static Vector3d clamp(Vector3d v, double min, double max) { - v.x = clamp(v.x, min, max); - v.y = clamp(v.y, min, max); - v.z = clamp(v.z, min, max); - return v; - } - - public static double clamp(double val, double min, double max) { - return val < min ? min : (val > max ? max : val); - } - - public static int clamp(int val, int min, int max) { - return val < min ? min : (val > max ? max : val); - } - - /** - * Compute the plane equation Ax + By + Cz + D = 0 for the plane - * defined by the three points which lie on the plane, a, b, and c, and - * placing the result into r. The plane equation can be summarised as the - * normal vector of the plane (A,B,C) and the distance to the plane from the - * origin (D). - * - * @param a - * vector a. - * @param b - * vector b. - * @param c - * vector c. - * @param result - * the result (A,B,C,D) of plane equation. - */ - public static void computePlaneEquation(Vector3d a, Vector3d b, Vector3d c, Vector4d result) { - Vector3d i = new Vector3d(); - Vector3d j = new Vector3d(); - Vector3d k = new Vector3d(); - - // compute normal vector - i.x = c.x - a.x; - i.y = c.y - a.y; - i.z = c.z - a.z; - - j.x = b.x - a.x; - j.y = b.y - a.y; - j.z = b.z - a.z; - - k.cross(j, i); - k.normalize(); - - // plane equation: Ax + By + Cz + D = 0 - result.x = k.x; // A - result.y = k.y; // B - result.z = k.z; // C - result.w = -(result.x * a.x + result.y * a.y + result.z * a.z); // D - } - - /** - * Projects the point onto the plane. - * - * @param plane - * the plane. - * @param point - * the point. - */ - public static void projectPointOntoPlane(Vector4d plane, Vector4d point) { - double distance = plane.dot(point); - Vector4d newPoint = new Vector4d(point); - Vector3d planeNormal = new Vector3d(plane.x, plane.y, plane.z); - planeNormal.normalize(); - planeNormal.scale(distance); - newPoint.sub(new Vector4d(planeNormal.x, planeNormal.y, planeNormal.z, 0)); - point.set(newPoint); - } - - /** - * This method calculates the intersection between a line and a plane. - * - * @param plane - * the plane (x,y,z = normal, w = distance from origin) - * @param pointInLine - * a point in the line. - * @param lineDirection - * the direction of the line. - * @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) { - // check for no intersection - Vector3d planeNormal = new Vector3d(plane.x, plane.y, plane.z); - 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) { - return null; + /** + * Returns the distance from a point to a plane. + * + * @param plane the plane. + * @param point the point. + * @return the distance between them. + */ + public static double distanceFromPointToPlane(Vector4d plane, Vector3d point) { + Vector4d newPoint = new Vector4d(point.x, point.y, point.z, 1); + return plane.dot(newPoint); } - // we have an intersection - Vector4d point = new Vector4d(pointInLine.x, pointInLine.y, pointInLine.z, 1); - Vector4d lineNorm = new Vector4d(lineDirection.x, lineDirection.y, lineDirection.z, 0); - double t = -(plane.dot(point) / plane.dot(lineNorm)); + public static void computePlaneEquation(Vector4d a, Vector4d b, Vector4d c, Vector4d result) { + computePlaneEquation( + new Vector3d(a.x, a.y, a.z), + new Vector3d(b.x, b.y, b.z), + new Vector3d(c.x, c.y, c.z), + result); + } - Vector3d result = new Vector3d(pointInLine); - lineDirection.scale(t); - result.add(lineDirection); - return result; - } + public static Vector3d clamp(Vector3d v, double min, double max) { + v.x = clamp(v.x, min, max); + v.y = clamp(v.y, min, max); + v.z = clamp(v.z, min, max); + return v; + } - /** - * This function computes the ray that goes from the eye, through the - * specified pixel. - * - * @param x - * the x pixel location (x = 0 is the left most pixel) - * @param y - * the y pixel location (y = 0 is the bottom most pixel) - * @param eyeOut - * the eyes position. - * @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 double clamp(double val, double min, double max) { + return val < min ? min : (val > max ? max : val); + } - // grab the eye's position - ivm.getTranslation(eyeOut); + public static int clamp(int val, int min, int max) { + return val < min ? min : (val > max ? max : val); + } - Matrix4d vpm = new Matrix4d(); - vpm.mul(ivm, ipm); + /** + * Compute the plane equation Ax + By + Cz + D = 0 for the plane defined by the three points which lie + * on the plane, a, b, and c, and placing the result into r. The plane equation can be summarised as the normal + * vector of the plane (A,B,C) and the distance to the plane from the origin (D). + * + * @param a vector a. + * @param b vector b. + * @param c vector c. + * @param result the result (A,B,C,D) of plane equation. + */ + public static void computePlaneEquation(Vector3d a, Vector3d b, Vector3d c, Vector4d result) { + Vector3d i = new Vector3d(); + Vector3d j = new Vector3d(); + Vector3d k = new Vector3d(); - // Calculate the pixel location in screen clip space (width and height from - // -1 to 1) - double screenX = (x - vp.getX()) / vp.getWidth(); - double screenY = (y - vp.getY()) / vp.getHeight(); - screenX = (screenX * 2.0) - 1.0; - screenY = (screenY * 2.0) - 1.0; + // compute normal vector + i.x = c.x - a.x; + i.y = c.y - a.y; + i.z = c.z - a.z; - // Now calculate the XYZ location of this point on the near plane - Vector4d tmp = new Vector4d(); - tmp.x = screenX; - tmp.y = screenY; - tmp.z = -1; - tmp.w = 1.0; - vpm.transform(tmp); + j.x = b.x - a.x; + j.y = b.y - a.y; + j.z = b.z - a.z; - double w = tmp.w; - Vector3d nearXYZ = new Vector3d(tmp.x / w, tmp.y / w, tmp.z / w); + k.cross(j, i); + k.normalize(); - // and then on the far plane - tmp.x = screenX; - tmp.y = screenY; - tmp.z = 1; - tmp.w = 1.0; - vpm.transform(tmp); + // plane equation: Ax + By + Cz + D = 0 + result.x = k.x; // A + result.y = k.y; // B + result.z = k.z; // C + result.w = -(result.x * a.x + result.y * a.y + result.z * a.z); // D + } - w = tmp.w; - Vector3d farXYZ = new Vector3d(tmp.x / w, tmp.y / w, tmp.z / w); + /** + * Projects the point onto the plane. + * + * @param plane the plane. + * @param point the point. + */ + public static void projectPointOntoPlane(Vector4d plane, Vector4d point) { + double distance = plane.dot(point); + Vector4d newPoint = new Vector4d(point); + Vector3d planeNormal = new Vector3d(plane.x, plane.y, plane.z); + planeNormal.normalize(); + planeNormal.scale(distance); + newPoint.sub(new Vector4d(planeNormal.x, planeNormal.y, planeNormal.z, 0)); + point.set(newPoint); + } - normalOut.set(farXYZ); - normalOut.sub(nearXYZ); - normalOut.normalize(); + /** + * This method calculates the intersection between a line and a plane. + * + * @param plane the plane (x,y,z = normal, w = distance from origin) + * @param pointInLine a point in the line. + * @param lineDirection the direction of the line. + * @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) { + // check for no intersection + Vector3d planeNormal = new Vector3d(plane.x, plane.y, plane.z); + 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) { + return null; + } - } + // we have an intersection + Vector4d point = new Vector4d(pointInLine.x, pointInLine.y, pointInLine.z, 1); + Vector4d lineNorm = new Vector4d(lineDirection.x, lineDirection.y, lineDirection.z, 0); + double t = -(plane.dot(point) / plane.dot(lineNorm)); - // /** - // * Make a rotation Quat which will rotate vec1 to vec2 - // *

- // * This routine uses only fast geometric transforms, without costly acos/sin - // computations. It's - // * exact, fast, and with less degenerate cases than the acos/sin method. - // *

- // * For an explanation of the math used, you may see for example: - // * http://logiciels.cnes.fr/MARMOTTES/marmottes-mathematique.pdf - // *

- // * NB: This is the rotation with shortest angle, which is the one equivalent - // to the acos/sin - // * transform method. Other rotations exists, for example to additionally - // keep a local horizontal - // * attitude. - // * - // * @param from - // * rotate from this vector - // * @param to - // * to this one - // * @return the rotation to apply to from to get to to. - // */ - // - // public static Quat4d makeRotate( Vector3d from, Vector3d to) { - // - // Quat4d res = new Quat4d(); - // - // // This routine takes any vector as argument but normalized - // // vectors are necessary, if only for computing the dot product. - // // Too bad the API is that generic, it leads to performance loss. - // // Even in the case the 2 vectors are not normalized but same length, - // // the sqrt could be shared, but we have no way to know beforehand - // // at this point, while the caller may know. - // // So, we have to test... in the hope of saving at least a sqrt - // Vector3d sourceVector = new Vector3d(from); - // Vector3d targetVector = new Vector3d(to); - // - // double fromLen2 = sourceVector.lengthSquared(); - // double fromLen; - // // normalize only when necessary, epsilon test - // if ((fromLen2 < 1.0 - 1e-7) || (fromLen2 > 1.0 + 1e-7)) { - // fromLen = Math.sqrt(fromLen2); - // sourceVector.x /= fromLen; - // sourceVector.y /= fromLen; - // sourceVector.z /= fromLen; - // - // } else { - // fromLen = 1.0; - // } - // - // double toLen2 = targetVector.lengthSquared(); - // // normalize only when necessary, epsilon test - // if ((toLen2 < 1.0 - 1e-7) || (toLen2 > 1.0 + 1e-7)) { - // double toLen; - // // re-use fromLen for case of mapping 2 vectors of the same length - // if ((toLen2 > fromLen2 - 1e-7) && (toLen2 < fromLen2 + 1e-7)) { - // toLen = fromLen; - // } else { - // toLen = Math.sqrt(toLen2); - // } - // - // targetVector.x /= toLen; - // targetVector.y /= toLen; - // targetVector.z /= toLen; - // } - // - // // Now let's get into the real stuff - // // Use "dot product plus one" as test as it can be re-used later on - // double dotProdPlus1 = 1.0 + sourceVector.dot(targetVector); - // - // // Check for degenerate case of full u-turn. Use epsilon for detection - // if (dotProdPlus1 < 1e-7) { - // - // // Get an orthogonal vector of the given vector - // // in a plane with maximum vector coordinates. - // // Then use it as quaternion axis with pi angle - // // Trick is to realize one value at least is >0.6 for a normalized vector. - // if (Math.abs(sourceVector.x) < 0.6) { - // - // double norm = Math.sqrt(1.0 - sourceVector.x * sourceVector.x); - // res.x = 0.0; - // res.y = sourceVector.z / norm; - // res.z = -sourceVector.y / norm; - // res.w = 0.0; - // } else if (Math.abs(sourceVector.y) < 0.6) { - // double norm = Math.sqrt(1.0 - sourceVector.y * sourceVector.y); - // res.x = -sourceVector.z / norm; - // res.y = 0.0; - // res.z = sourceVector.x / norm; - // res.w = 0.0; - // } else { - // double norm = Math.sqrt(1.0 - sourceVector.z * sourceVector.z); - // res.x = sourceVector.y / norm; - // res.y = -sourceVector.x / norm; - // res.z = 0.0; - // res.w = 0.0; - // } - // } else { - // // Find the shortest angle quaternion that transforms normalized vectors - // // into one other. Formula is still valid when vectors are colinear - // double s = Math.sqrt(0.5 * dotProdPlus1); - // double val = (2.0 * s); - // targetVector.x /= val; - // targetVector.y /= val; - // targetVector.z /= val; - // - // Vector3d tmp = new Vector3d(); - // tmp.cross(sourceVector, targetVector); - // - // res.x = tmp.x; - // res.y = tmp.y; - // res.z = tmp.z; - // res.w = s; - // } - // - // return res; - // } - // - // /** - // * Makes a rotation of angle (radians) around the axis specified by the - // x,y,z values. - // * - // * @param angle - // * the angle in radians for the rotation - // * @param axis - // * the axis to rotate about. - // * @return the quaternion defining the rotation. - // */ + Vector3d result = new Vector3d(pointInLine); + lineDirection.scale(t); + result.add(lineDirection); + return result; + } - /** - * Creates a perspective projection matrix. - * - * @param fovDegrees - * The field of view angle in degrees. - * @param near - * near plane. - * @param far - * far plane. - * @param viewportWidth - * viewport width. - * @param viewportHeight - * viewport height. - * @return the matrix. - */ + /** + * This function computes the ray that goes from the eye, through the specified pixel. + * + * @param x the x pixel location (x = 0 is the left most pixel) + * @param y the y pixel location (y = 0 is the bottom most pixel) + * @param eyeOut the eyes position. + * @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 Matrix4d createProjectionMatrixAsPerspective(double fovDegrees, double near, double far, int viewportWidth, int viewportHeight) { + // grab the eye's position + ivm.getTranslation(eyeOut); - Matrix4d matrix = new Matrix4d(); - // for impl details see gluPerspective doco in OpenGL reference manual - double aspect = (double) viewportWidth / (double) viewportHeight; + Matrix4d vpm = new Matrix4d(); + vpm.mul(ivm, ipm); - double theta = (Math.toRadians(fovDegrees) / 2d); - double f = Math.cos(theta) / Math.sin(theta); + // Calculate the pixel location in screen clip space (width and height from + // -1 to 1) + double screenX = (x - vp.getX()) / vp.getWidth(); + double screenY = (y - vp.getY()) / vp.getHeight(); + screenX = (screenX * 2.0) - 1.0; + screenY = (screenY * 2.0) - 1.0; - double a = (far + near) / (near - far); - double b = (2d * far * near) / (near - far); + // Now calculate the XYZ location of this point on the near plane + Vector4d tmp = new Vector4d(); + tmp.x = screenX; + tmp.y = screenY; + tmp.z = -1; + tmp.w = 1.0; + vpm.transform(tmp); - matrix.set(new double[] { f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, a, b, 0, 0, -1, 0 }); + double w = tmp.w; + Vector3d nearXYZ = new Vector3d(tmp.x / w, tmp.y / w, tmp.z / w); - return matrix; - } + // and then on the far plane + tmp.x = screenX; + tmp.y = screenY; + tmp.z = 1; + tmp.w = 1.0; + vpm.transform(tmp); - /** - * Creates a projection matrix as per glFrustrum. - * - * @param left - * coordinate of left clip plane. - * @param right - * coordinate of right clip plane. - * @param bottom - * coordinate of bottom clip plane. - * @param top - * coordinate of left top plane. - * @param zNear - * distance of the near plane. - * @param zFar - * distance of the near plane. - * @return the matrix. - */ + w = tmp.w; + Vector3d farXYZ = new Vector3d(tmp.x / w, tmp.y / w, tmp.z / w); - public static Matrix4d createProjectionMatrixAsPerspective(double left, double right, double bottom, double top, double zNear, double zFar) { + normalOut.set(farXYZ); + normalOut.sub(nearXYZ); + normalOut.normalize(); - 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); + } - 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 + // /** + // * Make a rotation Quat which will rotate vec1 to vec2 + // *

+ // * This routine uses only fast geometric transforms, without costly acos/sin + // computations. It's + // * exact, fast, and with less degenerate cases than the acos/sin method. + // *

+ // * For an explanation of the math used, you may see for example: + // * http://logiciels.cnes.fr/MARMOTTES/marmottes-mathematique.pdf + // *

+ // * NB: This is the rotation with shortest angle, which is the one equivalent + // to the acos/sin + // * transform method. Other rotations exists, for example to additionally + // keep a local horizontal + // * attitude. + // * + // * @param from + // * rotate from this vector + // * @param to + // * to this one + // * @return the rotation to apply to from to get to to. + // */ + // + // public static Quat4d makeRotate( Vector3d from, Vector3d to) { + // + // Quat4d res = new Quat4d(); + // + // // This routine takes any vector as argument but normalized + // // vectors are necessary, if only for computing the dot product. + // // Too bad the API is that generic, it leads to performance loss. + // // Even in the case the 2 vectors are not normalized but same length, + // // the sqrt could be shared, but we have no way to know beforehand + // // at this point, while the caller may know. + // // So, we have to test... in the hope of saving at least a sqrt + // Vector3d sourceVector = new Vector3d(from); + // Vector3d targetVector = new Vector3d(to); + // + // double fromLen2 = sourceVector.lengthSquared(); + // double fromLen; + // // normalize only when necessary, epsilon test + // if ((fromLen2 < 1.0 - 1e-7) || (fromLen2 > 1.0 + 1e-7)) { + // fromLen = Math.sqrt(fromLen2); + // sourceVector.x /= fromLen; + // sourceVector.y /= fromLen; + // sourceVector.z /= fromLen; + // + // } else { + // fromLen = 1.0; + // } + // + // double toLen2 = targetVector.lengthSquared(); + // // normalize only when necessary, epsilon test + // if ((toLen2 < 1.0 - 1e-7) || (toLen2 > 1.0 + 1e-7)) { + // double toLen; + // // re-use fromLen for case of mapping 2 vectors of the same length + // if ((toLen2 > fromLen2 - 1e-7) && (toLen2 < fromLen2 + 1e-7)) { + // toLen = fromLen; + // } else { + // toLen = Math.sqrt(toLen2); + // } + // + // targetVector.x /= toLen; + // targetVector.y /= toLen; + // targetVector.z /= toLen; + // } + // + // // Now let's get into the real stuff + // // Use "dot product plus one" as test as it can be re-used later on + // double dotProdPlus1 = 1.0 + sourceVector.dot(targetVector); + // + // // Check for degenerate case of full u-turn. Use epsilon for detection + // if (dotProdPlus1 < 1e-7) { + // + // // Get an orthogonal vector of the given vector + // // in a plane with maximum vector coordinates. + // // Then use it as quaternion axis with pi angle + // // Trick is to realize one value at least is >0.6 for a normalized vector. + // if (Math.abs(sourceVector.x) < 0.6) { + // + // double norm = Math.sqrt(1.0 - sourceVector.x * sourceVector.x); + // res.x = 0.0; + // res.y = sourceVector.z / norm; + // res.z = -sourceVector.y / norm; + // res.w = 0.0; + // } else if (Math.abs(sourceVector.y) < 0.6) { + // double norm = Math.sqrt(1.0 - sourceVector.y * sourceVector.y); + // res.x = -sourceVector.z / norm; + // res.y = 0.0; + // res.z = sourceVector.x / norm; + // res.w = 0.0; + // } else { + // double norm = Math.sqrt(1.0 - sourceVector.z * sourceVector.z); + // res.x = sourceVector.y / norm; + // res.y = -sourceVector.x / norm; + // res.z = 0.0; + // res.w = 0.0; + // } + // } else { + // // Find the shortest angle quaternion that transforms normalized vectors + // // into one other. Formula is still valid when vectors are colinear + // double s = Math.sqrt(0.5 * dotProdPlus1); + // double val = (2.0 * s); + // targetVector.x /= val; + // targetVector.y /= val; + // targetVector.z /= val; + // + // Vector3d tmp = new Vector3d(); + // tmp.cross(sourceVector, targetVector); + // + // res.x = tmp.x; + // res.y = tmp.y; + // res.z = tmp.z; + // res.w = s; + // } + // + // return res; + // } + // + // /** + // * Makes a rotation of angle (radians) around the axis specified by the + // x,y,z values. + // * + // * @param angle + // * the angle in radians for the rotation + // * @param axis + // * the axis to rotate about. + // * @return the quaternion defining the rotation. + // */ - }); + /** + * Creates a perspective projection matrix. + * + * @param fovDegrees The field of view angle in degrees. + * @param near near plane. + * @param far far plane. + * @param viewportWidth viewport width. + * @param viewportHeight viewport height. + * @return the matrix. + */ - matrix.transpose(); - return matrix; - } + public static Matrix4d createProjectionMatrixAsPerspective(double fovDegrees, double near, double far, + int viewportWidth, int viewportHeight) { - /** - * Sets the orthographic projection matrix. - * - * @param left - * the left value. - * @param right - * the right value. - * @param bottom - * the bottom value. - * @param top - * the top value. - * @param near - * near plane. - * @param far - * far plane. - * @return the ortho matrix. - */ + Matrix4d matrix = new Matrix4d(); + // for impl details see gluPerspective doco in OpenGL reference manual + double aspect = (double) viewportWidth / (double) viewportHeight; - public static Matrix4d createProjectionMatrixAsOrtho(double left, double right, double bottom, double top, double near, double far) { + double theta = (Math.toRadians(fovDegrees) / 2d); + double f = Math.cos(theta) / Math.sin(theta); - Matrix4d matrix = new Matrix4d(); - // for impl details see glOrtho doco in OpenGL reference manual - double tx = -((right + left) / (right - left)); - double ty = -((top + bottom) / (top - bottom)); - double tz = -((far + near) / (far - near)); + double a = (far + near) / (near - far); + double b = (2d * far * near) / (near - far); - 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[] { f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, a, b, 0, 0, -1, 0 }); - return matrix; - } + return matrix; + } - /** - * Sets the near and far values on an existing perspective projection matrix. - * - * @param projMat - * the matrix to be modified. - * @param near - * the new near value. - * @param far - * the new far value. - */ - public static void setNearFarOnPerspectiveProjectionMatrix(Matrix4d projMat, double near, double far) { + /** + * Creates a projection matrix as per glFrustrum. + * + * @param left coordinate of left clip plane. + * @param right coordinate of right clip plane. + * @param bottom coordinate of bottom clip plane. + * @param top coordinate of left top plane. + * @param zNear distance of the near plane. + * @param zFar distance of the near plane. + * @return the matrix. + */ - projMat.transpose(); + public static Matrix4d createProjectionMatrixAsPerspective(double left, double right, double bottom, double top, + double zNear, double zFar) { - 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 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 ratio = Math.abs(2.0 / (transNearPlane - transFarPlane)); - double center = -(transNearPlane + transFarPlane) / 2.0; + 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 - Matrix4d mat = new Matrix4d(); - mat.setIdentity(); - mat.setElement(2, 2, ratio); - mat.setElement(3, 2, center * ratio); + }); - projMat.mul(mat); - projMat.transpose(); + matrix.transpose(); + return matrix; + } - } + /** + * Sets the orthographic projection matrix. + * + * @param left the left value. + * @param right the right value. + * @param bottom the bottom value. + * @param top the top value. + * @param near near plane. + * @param far far plane. + * @return the ortho matrix. + */ - /** - * Creates a look at matrix. - * - * @param eyePos - * the position of the eye. - * @param lookAtPos - * the point to look at. - * @param upVec - * the up vector. - * @return the look at matrix. - */ + public static Matrix4d createProjectionMatrixAsOrtho(double left, double right, double bottom, double top, + double near, double far) { - public static Matrix4d createMatrixAsLookAt(Vector3d eyePos, Vector3d lookAtPos, Vector3d upVec) { + Matrix4d matrix = new Matrix4d(); + // for impl details see glOrtho doco in OpenGL reference manual + double tx = -((right + left) / (right - left)); + double ty = -((top + bottom) / (top - bottom)); + double tz = -((far + near) / (far - near)); - Vector3d eye = new Vector3d(eyePos); - Vector3d lookAt = new Vector3d(lookAtPos); - Vector3d up = new Vector3d(upVec); + 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 }); - Vector3d forwardVec = new Vector3d(lookAt); - forwardVec.sub(eye); - forwardVec.normalize(); + return matrix; + } - Vector3d sideVec = new Vector3d(); - sideVec.cross(forwardVec, up); - sideVec.normalize(); + /** + * Sets the near and far values on an existing perspective projection matrix. + * + * @param projMat the matrix to be modified. + * @param near the new near value. + * @param far the new far value. + */ + public static void setNearFarOnPerspectiveProjectionMatrix(Matrix4d projMat, double near, double far) { - Vector3d upVed = new Vector3d(); - upVed.cross(sideVec, forwardVec); - upVed.normalize(); + projMat.transpose(); - 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); + 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)); - eye.negate(); - // mat.transform(eye); - mat.transformNormal(eye); - mat.setTranslation(eye); + double ratio = Math.abs(2.0 / (transNearPlane - transFarPlane)); + double center = -(transNearPlane + transFarPlane) / 2.0; - return mat; - } + Matrix4d mat = new Matrix4d(); + mat.setIdentity(); + mat.setElement(2, 2, ratio); + mat.setElement(3, 2, center * ratio); - /** - * Pre-multiplies the vector by the matrix. - * - * @param v - * the vector. - * @param mat - * the matrix. - * @return the result of the multiplication. - */ + projMat.mul(mat); + projMat.transpose(); - 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); - return new Vector3d(x, y, z); - } + } - /** - * Extracts the s,t,r and q eye planes from the specified matrix. - * - * @param matrix - * the matrix to extract the planes from. - * @return the s,t,r and q planes from the specified matrix. - */ + /** + * Creates a look at matrix. + * + * @param eyePos the position of the eye. + * @param lookAtPos the point to look at. + * @param upVec the up vector. + * @return the look at matrix. + */ - public static Vector4d[] getEyePlanesForMatrix(Matrix4d matrix) { + public static Matrix4d createMatrixAsLookAt(Vector3d eyePos, Vector3d lookAtPos, Vector3d upVec) { - Matrix4d copy = new Matrix4d(matrix); - copy.transpose(); + Vector3d eye = new Vector3d(eyePos); + Vector3d lookAt = new Vector3d(lookAtPos); + Vector3d up = new Vector3d(upVec); - 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)); - // t plane - 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)); - // q plane - res[3] = new Vector4d(copy.getElement(0, 3), copy.getElement(1, 3), copy.getElement(2, 3), copy.getElement(3, 3)); + Vector3d forwardVec = new Vector3d(lookAt); + forwardVec.sub(eye); + forwardVec.normalize(); - return res; - } + Vector3d sideVec = new Vector3d(); + sideVec.cross(forwardVec, up); + sideVec.normalize(); - /** - * Computes the cross product of the two tuples. - * - * @param vec1 - * the first tuple. - * @param vec2 - * the second tuple. - * @return the cross product of the two tuples. - */ + Vector3d upVed = new Vector3d(); + upVed.cross(sideVec, forwardVec); + upVed.normalize(); - public static Vector3d cross(Vector3d vec1, Vector3d vec2) { - Vector3d res = new Vector3d(); - res.cross(new Vector3d(vec1), new Vector3d(vec2)); - return res; - } + 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); - /** - * Returns the distance between the two point from and to. - * - * @param from - * the from point. - * @param to - * the to point. - * @return the distance between the two point from and to. - */ - public static double distance(Vector3d from, Vector3d to) { - return from.distance(to); - } + eye.negate(); + // mat.transform(eye); + mat.transformNormal(eye); + mat.setTranslation(eye); - /** - * Returns the distance squared between the two point from and to. - * - * @param from - * the from point. - * @param to - * the to point. - * @return the distance squared between the two point from and to. - */ - public static double distanceSquared(Vector3d from, Vector3d to) { - return from.distanceSquared(to); - } + return mat; + } - /** - * Extracts the directional vectors from the specified view matrix. - * - * @param matrix - * the view matrix. - * @param upVecOut - * the up vector. - * @param sideVecOut - * the side vector. - * @param lookVecOut - * the look vector. - */ - public static void getVectorsForMatrix(Matrix4d matrix, Vector3d upVecOut, Vector3d sideVecOut, Vector3d lookVecOut) { + /** + * Pre-multiplies the vector by the matrix. + * + * @param v the vector. + * @param mat the matrix. + * @return the result of the multiplication. + */ - sideVecOut.set(matrix.getElement(0, 0), matrix.getElement(0, 1), matrix.getElement(0, 2)); - sideVecOut.normalize(); + 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); + return new Vector3d(x, y, z); + } - upVecOut.set(matrix.getElement(1, 0), matrix.getElement(1, 1), matrix.getElement(1, 2)); - upVecOut.normalize(); + /** + * Extracts the s,t,r and q eye planes from the specified matrix. + * + * @param matrix the matrix to extract the planes from. + * @return the s,t,r and q planes from the specified matrix. + */ - lookVecOut.set(matrix.getElement(2, 0), matrix.getElement(2, 1), matrix.getElement(2, 2)); - lookVecOut.negate(); - lookVecOut.normalize(); + public static Vector4d[] getEyePlanesForMatrix(Matrix4d matrix) { - } + Matrix4d copy = new Matrix4d(matrix); + copy.transpose(); - /** - * Extracts the up vector from the specified view matrix. - * - * @param matrix - * the matrix. - * @return the up vector from the specified view matrix. - */ + 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)); + // t plane + 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)); + // q plane + res[3] = new Vector4d( + copy.getElement(0, 3), + copy.getElement(1, 3), + copy.getElement(2, 3), + copy.getElement(3, 3)); - public static Vector3d getUpFromMatrix(Matrix4d matrix) { - Vector3d res = new Vector3d(matrix.getElement(1, 0), matrix.getElement(1, 1), matrix.getElement(1, 2)); - res.normalize(); - return res; - } + return res; + } + + /** + * Computes the cross product of the two tuples. + * + * @param vec1 the first tuple. + * @param vec2 the second tuple. + * @return the cross product of the two tuples. + */ + + public static Vector3d cross(Vector3d vec1, Vector3d vec2) { + Vector3d res = new Vector3d(); + res.cross(new Vector3d(vec1), new Vector3d(vec2)); + return res; + } + + /** + * Returns the distance between the two point from and to. + * + * @param from the from point. + * @param to the to point. + * @return the distance between the two point from and to. + */ + public static double distance(Vector3d from, Vector3d to) { + return from.distance(to); + } + + /** + * Returns the distance squared between the two point from and to. + * + * @param from the from point. + * @param to the to point. + * @return the distance squared between the two point from and to. + */ + public static double distanceSquared(Vector3d from, Vector3d to) { + return from.distanceSquared(to); + } + + /** + * Extracts the directional vectors from the specified view matrix. + * + * @param matrix the view matrix. + * @param upVecOut the up vector. + * @param sideVecOut the side vector. + * @param lookVecOut the look vector. + */ + 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(); + + upVecOut.set(matrix.getElement(1, 0), matrix.getElement(1, 1), matrix.getElement(1, 2)); + upVecOut.normalize(); + + lookVecOut.set(matrix.getElement(2, 0), matrix.getElement(2, 1), matrix.getElement(2, 2)); + lookVecOut.negate(); + lookVecOut.normalize(); + + } + + /** + * Extracts the up vector from the specified view matrix. + * + * @param matrix the matrix. + * @return the up vector from the specified view matrix. + */ + + public static Vector3d getUpFromMatrix(Matrix4d matrix) { + 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/Vector2d.java b/src/main/java/com/enderio/core/common/vecmath/Vector2d.java index 83b61ca..b866f75 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Vector2d.java +++ b/src/main/java/com/enderio/core/common/vecmath/Vector2d.java @@ -2,95 +2,95 @@ package com.enderio.core.common.vecmath; public class Vector2d { - public double x; - public double y; + public double x; + public double y; - public Vector2d() { - x = 0; - y = 0; - } + public Vector2d() { + x = 0; + y = 0; + } - public Vector2d(double x, double y) { - this.x = x; - this.y = y; - } + public Vector2d(double x, double y) { + this.x = x; + this.y = y; + } - public Vector2d(Vector2d other) { - this(other.x, other.y); - } + public Vector2d(Vector2d other) { + this(other.x, other.y); + } - public void set(double x, double y) { - this.x = x; - this.y = y; - } + public void set(double x, double y) { + this.x = x; + this.y = y; + } - public void set(Vector2f vec) { - x = vec.x; - y = vec.y; - } + public void set(Vector2f vec) { + x = vec.x; + y = vec.y; + } - public void set(Vector2d vec) { - x = vec.x; - y = vec.y; - } + public void set(Vector2d vec) { + x = vec.x; + y = vec.y; + } - public void add(Vector2d vec) { - x += vec.x; - y += vec.y; - } + public void add(Vector2d vec) { + x += vec.x; + y += vec.y; + } - public void sub(Vector2d vec) { - x -= vec.x; - y -= vec.y; - } + public void sub(Vector2d vec) { + x -= vec.x; + y -= vec.y; + } - public void add(Vector2f vec) { - x += vec.x; - y += vec.y; - } + public void add(Vector2f vec) { + x += vec.x; + y += vec.y; + } - public void sub(Vector2f vec) { - x -= vec.x; - y -= vec.y; - } + public void sub(Vector2f vec) { + x -= vec.x; + y -= vec.y; + } - public void negate() { - x = -x; - y = -y; - } + public void negate() { + x = -x; + y = -y; + } - public void scale(double s) { - x *= s; - y *= s; - } + public void scale(double s) { + x *= s; + y *= s; + } - public void normalize() { - double scale = 1.0 / Math.sqrt(x * x + y * y); - scale(scale); - } + public void normalize() { + double scale = 1.0 / Math.sqrt(x * x + y * y); + scale(scale); + } - public double lengthSquared() { - return x * x + y * y; - } + public double lengthSquared() { + return x * x + y * y; + } - public double length() { - return Math.sqrt(lengthSquared()); - } + public double length() { + return Math.sqrt(lengthSquared()); + } - public double distanceSquared(Vector2d v) { - double dx, dy, dz; - dx = x - v.x; - dy = y - v.y; - return (dx * dx + dy * dy); - } + public double distanceSquared(Vector2d v) { + double dx, dy, dz; + dx = x - v.x; + dy = y - v.y; + return (dx * dx + dy * dy); + } - public double distance(Vector2d v) { - return Math.sqrt(distanceSquared(v)); - } + public double distance(Vector2d v) { + return Math.sqrt(distanceSquared(v)); + } - @Override - public String toString() { - return "Vector2d(" + x + ", " + y + ")"; - } + @Override + public String toString() { + return "Vector2d(" + x + ", " + y + ")"; + } } diff --git a/src/main/java/com/enderio/core/common/vecmath/Vector2f.java b/src/main/java/com/enderio/core/common/vecmath/Vector2f.java index 41ca18a..e4af407 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Vector2f.java +++ b/src/main/java/com/enderio/core/common/vecmath/Vector2f.java @@ -2,94 +2,94 @@ package com.enderio.core.common.vecmath; public class Vector2f { - public float x; - public float y; + public float x; + public float y; - public Vector2f() { - x = 0; - y = 0; - } + public Vector2f() { + x = 0; + y = 0; + } - public Vector2f(double x, double y) { - this.x = (float) x; - this.y = (float) y; - } + public Vector2f(double x, double y) { + this.x = (float) x; + this.y = (float) y; + } - public Vector2f(float x, float y) { - this.x = x; - this.y = y; - } + public Vector2f(float x, float y) { + this.x = x; + this.y = y; + } - public Vector2f(Vector2d other) { - this(other.x, other.y); - } + public Vector2f(Vector2d other) { + this(other.x, other.y); + } - public Vector2f(Vector2f other) { - this(other.x, other.y); - } + public Vector2f(Vector2f other) { + this(other.x, other.y); + } - public void set(double x, double y) { - this.x = (float) x; - this.y = (float) y; - } + public void set(double x, double y) { + this.x = (float) x; + this.y = (float) y; + } - public void set(float x, float y) { - this.x = x; - this.y = y; - } + public void set(float x, float y) { + this.x = x; + this.y = y; + } - public void set(Vector2f vec) { - x = vec.x; - y = vec.y; - } + public void set(Vector2f vec) { + x = vec.x; + y = vec.y; + } - public void add(Vector2f vec) { - x += vec.x; - y += vec.y; - } + public void add(Vector2f vec) { + x += vec.x; + y += vec.y; + } - public void sub(Vector2f vec) { - x -= vec.x; - y -= vec.y; - } + public void sub(Vector2f vec) { + x -= vec.x; + y -= vec.y; + } - public void negate() { - x = -x; - y = -y; - } + public void negate() { + x = -x; + y = -y; + } - public void scale(double s) { - x *= s; - y *= s; - } + public void scale(double s) { + x *= s; + y *= s; + } - public void normalize() { - double scale = 1.0 / Math.sqrt(x * x + y * y); - scale(scale); - } + public void normalize() { + double scale = 1.0 / Math.sqrt(x * x + y * y); + scale(scale); + } - public double lengthSquared() { - return x * x + y * y; - } + public double lengthSquared() { + return x * x + y * y; + } - public double length() { - return Math.sqrt(lengthSquared()); - } + public double length() { + return Math.sqrt(lengthSquared()); + } - public double distanceSquared(Vector2f v) { - double dx, dy, dz; - dx = x - v.x; - dy = y - v.y; - return (dx * dx + dy * dy); - } + public double distanceSquared(Vector2f v) { + double dx, dy, dz; + dx = x - v.x; + dy = y - v.y; + return (dx * dx + dy * dy); + } - public double distance(Vector2f v) { - return Math.sqrt(distanceSquared(v)); - } + public double distance(Vector2f v) { + return Math.sqrt(distanceSquared(v)); + } - @Override - public String toString() { - return "Vector2f(" + x + ", " + y + ")"; - } + @Override + public String toString() { + return "Vector2f(" + x + ", " + y + ")"; + } } diff --git a/src/main/java/com/enderio/core/common/vecmath/Vector3d.java b/src/main/java/com/enderio/core/common/vecmath/Vector3d.java index fc2fba7..99798b1 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Vector3d.java +++ b/src/main/java/com/enderio/core/common/vecmath/Vector3d.java @@ -5,149 +5,149 @@ import net.minecraftforge.client.model.obj.Vertex; public class Vector3d { - public double x; - public double y; - public double z; + public double x; + public double y; + public double z; - public Vector3d() { - x = 0; - y = 0; - z = 0; - } + public Vector3d() { + x = 0; + y = 0; + z = 0; + } - public Vector3d(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } + public Vector3d(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } - public Vector3d(Vector3d other) { - this(other.x, other.y, other.z); - } + public Vector3d(Vector3d other) { + this(other.x, other.y, other.z); + } - public Vector3d(Vector3f corner) { - this(corner.x, corner.y, corner.z); - } + public Vector3d(Vector3f corner) { + this(corner.x, corner.y, corner.z); + } - public Vector3d(Vertex vert) { - this(vert.x, vert.y, vert.z); - } + public Vector3d(Vertex vert) { + this(vert.x, vert.y, vert.z); + } - public void set(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } + public void set(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } - public void set(Vector3f v) { - set(v.x, v.y, v.z); - } + public void set(Vector3f v) { + set(v.x, v.y, v.z); + } - public void set(Vector3d vec) { - x = vec.x; - y = vec.y; - z = vec.z; - } + public void set(Vector3d vec) { + x = vec.x; + y = vec.y; + z = vec.z; + } - public Vector3d add(Vector3d vec) { - x += vec.x; - y += vec.y; - z += vec.z; - return this; - } + public Vector3d add(Vector3d vec) { + x += vec.x; + y += vec.y; + z += vec.z; + return this; + } - public Vector3d add(Vector3f vec) { - x += vec.x; - y += vec.y; - z += vec.z; - return this; - } + public Vector3d add(Vector3f vec) { + x += vec.x; + y += vec.y; + z += vec.z; + return this; + } - public Vector3d add(double x2, double y2, double z2) { - x += x2; - y += y2; - z += z2; - return this; - } + public Vector3d add(double x2, double y2, double z2) { + x += x2; + y += y2; + z += z2; + return this; + } - public void sub(Vector3d vec) { - x -= vec.x; - y -= vec.y; - z -= vec.z; - } + public void sub(Vector3d vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + } - public void sub(Vector3f vec) { - x -= vec.x; - y -= vec.y; - z -= vec.z; - } + public void sub(Vector3f vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + } - public Vector3d negate() { - x = -x; - y = -y; - z = -z; - return this; - } + public Vector3d negate() { + x = -x; + y = -y; + z = -z; + return this; + } - public void scale(double s) { - x *= s; - y *= s; - z *= s; - } + public void scale(double s) { + x *= s; + y *= s; + z *= s; + } - public void scale(double sx, double sy, double sz) { - x *= sx; - y *= sy; - z *= sz; - } + public void scale(double sx, double sy, double sz) { + x *= sx; + y *= sy; + z *= sz; + } - public void normalize() { - double scale = 1.0 / Math.sqrt(x * x + y * y + z * z); - scale(scale); - } + public void normalize() { + double scale = 1.0 / Math.sqrt(x * x + y * y + z * z); + scale(scale); + } - public double dot(Vector3d other) { - return x * other.x + y * other.y + z * other.z; - } + public double dot(Vector3d other) { + return x * other.x + y * other.y + z * other.z; + } - public void cross(Vector3d v1, Vector3d v2) { - x = v1.y * v2.z - v1.z * v2.y; - y = v2.x * v1.z - v2.z * v1.x; - z = v1.x * v2.y - v1.y * v2.x; - } + public void cross(Vector3d v1, Vector3d v2) { + x = v1.y * v2.z - v1.z * v2.y; + y = v2.x * v1.z - v2.z * v1.x; + z = v1.x * v2.y - v1.y * v2.x; + } - public double lengthSquared() { - return x * x + y * y + z * z; - } + public double lengthSquared() { + return x * x + y * y + z * z; + } - public double length() { - return Math.sqrt(lengthSquared()); - } + public double length() { + return Math.sqrt(lengthSquared()); + } - public double distanceSquared(Vector3d v) { - double dx, dy, dz; - dx = x - v.x; - dy = y - v.y; - dz = z - v.z; - return (dx * dx + dy * dy + dz * dz); - } + public double distanceSquared(Vector3d v) { + double dx, dy, dz; + dx = x - v.x; + dy = y - v.y; + dz = z - v.z; + return (dx * dx + dy * dy + dz * dz); + } - public double distance(Vector3d v) { - return Math.sqrt(distanceSquared(v)); - } + public double distance(Vector3d v) { + return Math.sqrt(distanceSquared(v)); + } - @Override - public String toString() { - return "Vector3d(" + x + ", " + y + ", " + z + ")"; - } + @Override + public String toString() { + return "Vector3d(" + x + ", " + y + ", " + z + ")"; + } - public void abs() { - x = Math.abs(x); - y = Math.abs(y); - z = Math.abs(z); - } + public void abs() { + x = Math.abs(x); + y = Math.abs(y); + z = Math.abs(z); + } - public Vec3 getVec3() { - return Vec3.createVectorHelper(x, y, z); - } + public Vec3 getVec3() { + return Vec3.createVectorHelper(x, y, z); + } } 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 f8ea4c2..b161e00 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Vector3f.java +++ b/src/main/java/com/enderio/core/common/vecmath/Vector3f.java @@ -2,116 +2,116 @@ package com.enderio.core.common.vecmath; public class Vector3f { - public float x; - public float y; - public float z; + public float x; + public float y; + public float z; - public Vector3f() { - x = 0; - y = 0; - z = 0; - } + public Vector3f() { + x = 0; + y = 0; + z = 0; + } - public Vector3f(double x, double y, double z) { - this.x = (float) x; - this.y = (float) y; - this.z = (float) z; - } + public Vector3f(double x, double y, double z) { + this.x = (float) x; + this.y = (float) y; + this.z = (float) z; + } - public Vector3f(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } + public Vector3f(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } - public Vector3f(Vector3d other) { - this(other.x, other.y, other.z); - } + public Vector3f(Vector3d other) { + this(other.x, other.y, other.z); + } - public Vector3f(Vector3f other) { - this(other.x, other.y, other.z); - } + public Vector3f(Vector3f other) { + this(other.x, other.y, other.z); + } - public void set(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } + public void set(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } - public void set(Vector3f vec) { - x = vec.x; - y = vec.y; - z = vec.z; - } + public void set(Vector3f vec) { + x = vec.x; + y = vec.y; + z = vec.z; + } - public void add(Vector3f vec) { - x += vec.x; - y += vec.y; - z += vec.z; - } + public void add(Vector3f vec) { + x += vec.x; + y += vec.y; + z += vec.z; + } - public void add(Vector3d vec) { - x += vec.x; - y += vec.y; - z += vec.z; - } + public void add(Vector3d vec) { + x += vec.x; + y += vec.y; + z += vec.z; + } - public void add(int x2, int y2, int z2) { - x += x2; - y += y2; - z += z2; - } + public void add(int x2, int y2, int z2) { + x += x2; + y += y2; + z += z2; + } - public void sub(Vector3f vec) { - x -= vec.x; - y -= vec.y; - z -= vec.z; - } + public void sub(Vector3f vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + } - public void sub(Vector3d vec) { - x -= vec.x; - y -= vec.y; - z -= vec.z; - } + public void sub(Vector3d vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + } - public void negate() { - x = -x; - y = -y; - z = -z; - } + public void negate() { + x = -x; + y = -y; + z = -z; + } - public void scale(float s) { - x *= s; - y *= s; - z *= s; - } + public void scale(float s) { + x *= s; + y *= s; + z *= s; + } - public void normalize() { - double scale = 1.0 / Math.sqrt(x * x + y * y + z * z); - x *= scale; - y *= scale; - z *= scale; - } + public void normalize() { + double scale = 1.0 / Math.sqrt(x * x + y * y + z * z); + x *= scale; + y *= scale; + z *= scale; + } - public double dot(Vector3f other) { - return x * other.x + y * other.y + z * other.z; - } + public double dot(Vector3f other) { + return x * other.x + y * other.y + z * other.z; + } - public double lengthSquared() { - return x * x + y * y + z * z; - } + public double lengthSquared() { + return x * x + y * y + z * z; + } - public double length() { - return Math.sqrt(lengthSquared()); - } + public double length() { + return Math.sqrt(lengthSquared()); + } - @Override - public String toString() { - return "Vector3f(" + x + ", " + y + ", " + z + ")"; - } + @Override + public String toString() { + return "Vector3f(" + x + ", " + y + ", " + z + ")"; + } - public Vector3d asVector3d() { - return new Vector3d(x, y, z); - } + public Vector3d asVector3d() { + return new Vector3d(x, y, z); + } } diff --git a/src/main/java/com/enderio/core/common/vecmath/Vector4d.java b/src/main/java/com/enderio/core/common/vecmath/Vector4d.java index babaea9..4187e0e 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Vector4d.java +++ b/src/main/java/com/enderio/core/common/vecmath/Vector4d.java @@ -2,90 +2,90 @@ package com.enderio.core.common.vecmath; public class Vector4d { - public double x; - public double y; - public double z; - public double w; + public double x; + public double y; + public double z; + public double w; - public Vector4d() { - x = 0; - y = 0; - z = 0; - w = 0; - } + public Vector4d() { + x = 0; + y = 0; + z = 0; + w = 0; + } - public Vector4d(double x, double y, double z, double w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } + public Vector4d(double x, double y, double z, double w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } - public Vector4d(Vector4d other) { - this(other.x, other.y, other.z, other.w); - } + public Vector4d(Vector4d other) { + this(other.x, other.y, other.z, other.w); + } - public void set(Vector4d vec) { - x = vec.x; - y = vec.y; - z = vec.z; - w = vec.w; - } + public void set(Vector4d vec) { + x = vec.x; + y = vec.y; + z = vec.z; + w = vec.w; + } - public void set(double x, double y, double z, double w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } + public void set(double x, double y, double z, double w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } - public void add(Vector4d vec) { - x += vec.x; - y += vec.y; - z += vec.z; - w += vec.w; - } + public void add(Vector4d vec) { + x += vec.x; + y += vec.y; + z += vec.z; + w += vec.w; + } - public void sub(Vector4d vec) { - x -= vec.x; - y -= vec.y; - z -= vec.z; - w -= vec.w; - } + public void sub(Vector4d vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + w -= vec.w; + } - public void negate() { - x = -x; - y = -y; - z = -z; - w = -w; - } + public void negate() { + x = -x; + y = -y; + z = -z; + w = -w; + } - public void scale(double s) { - x *= s; - y *= s; - z *= s; - w *= s; - } + public void scale(double s) { + x *= s; + y *= s; + z *= s; + w *= s; + } - public void normalize() { - double scale = 1.0 / Math.sqrt(x * x + y * y + z * z + w * w); - scale(scale); - } + public void normalize() { + double scale = 1.0 / Math.sqrt(x * x + y * y + z * z + w * w); + scale(scale); + } - public double dot(Vector4d other) { - return x * other.x + y * other.y + z * other.z + w * other.w; - } + public double dot(Vector4d other) { + return x * other.x + y * other.y + z * other.z + w * other.w; + } - public double lengthSquared() { - return x * x + y * y + z * z + w * w; - } + public double lengthSquared() { + return x * x + y * y + z * z + w * w; + } - public double length() { - return Math.sqrt(lengthSquared()); - } + public double length() { + return Math.sqrt(lengthSquared()); + } - @Override - public String toString() { - return "Vector4d(" + x + ", " + y + ", " + z + ", " + w + ")"; - } + @Override + public String toString() { + return "Vector4d(" + x + ", " + y + ", " + z + ", " + w + ")"; + } } diff --git a/src/main/java/com/enderio/core/common/vecmath/Vector4f.java b/src/main/java/com/enderio/core/common/vecmath/Vector4f.java index fbde6c8..200cda1 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Vector4f.java +++ b/src/main/java/com/enderio/core/common/vecmath/Vector4f.java @@ -1,108 +1,109 @@ package com.enderio.core.common.vecmath; public class Vector4f { - public float x; - public float y; - public float z; - public float w; - public Vector4f() { - x = 0; - y = 0; - z = 0; - w = 0; - } + public float x; + public float y; + public float z; + public float w; - public Vector4f(float x, float y, float z, float w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } + public Vector4f() { + x = 0; + y = 0; + z = 0; + w = 0; + } - public Vector4f(double x, double y, double z, double w) { - this.x = (float) x; - this.y = (float) y; - this.z = (float) z; - this.w = (float) w; - } + public Vector4f(float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } - public Vector4f(Vector4f other) { - this(other.x, other.y, other.z, other.w); - } + public Vector4f(double x, double y, double z, double w) { + this.x = (float) x; + this.y = (float) y; + this.z = (float) z; + this.w = (float) w; + } - public void interpolate(Vector4f destination, float factor) { - x = (1 - factor) * x + factor * destination.x; - y = (1 - factor) * y + factor * destination.y; - z = (1 - factor) * z + factor * destination.z; - w = (1 - factor) * w + factor * destination.w; - } + public Vector4f(Vector4f other) { + this(other.x, other.y, other.z, other.w); + } - public void set(Vector4f vec) { - x = vec.x; - y = vec.y; - z = vec.z; - w = vec.w; - } + public void interpolate(Vector4f destination, float factor) { + x = (1 - factor) * x + factor * destination.x; + y = (1 - factor) * y + factor * destination.y; + z = (1 - factor) * z + factor * destination.z; + w = (1 - factor) * w + factor * destination.w; + } - public void set(float x, float y, float z, float w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } + public void set(Vector4f vec) { + x = vec.x; + y = vec.y; + z = vec.z; + w = vec.w; + } - public void add(Vector4f vec) { - x += vec.x; - y += vec.y; - z += vec.z; - w += vec.w; - } + public void set(float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } - public void sub(Vector4f vec) { - x -= vec.x; - y -= vec.y; - z -= vec.z; - w -= vec.w; - } + public void add(Vector4f vec) { + x += vec.x; + y += vec.y; + z += vec.z; + w += vec.w; + } - public void negate() { - x = -x; - y = -y; - z = -z; - w = -w; - } + public void sub(Vector4f vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + w -= vec.w; + } - public void scale(double s) { - x *= s; - y *= s; - z *= s; - w *= s; - } + public void negate() { + x = -x; + y = -y; + z = -z; + w = -w; + } - public void normalize() { - double scale = 1.0 / Math.sqrt(x * x + y * y + z * z + w * w); - scale(scale); - } + public void scale(double s) { + x *= s; + y *= s; + z *= s; + w *= s; + } - public double dot(Vector4f other) { - return x * other.x + y * other.y + z * other.z + w * other.w; - } + public void normalize() { + double scale = 1.0 / Math.sqrt(x * x + y * y + z * z + w * w); + scale(scale); + } - public double lengthSquared() { - return x * x + y * y + z * z + w * w; - } + public double dot(Vector4f other) { + return x * other.x + y * other.y + z * other.z + w * other.w; + } - public double length() { - return Math.sqrt(lengthSquared()); - } + public double lengthSquared() { + return x * x + y * y + z * z + w * w; + } - public Vector3f toVector3f() { - return new Vector3f(x, y, z); - } + public double length() { + return Math.sqrt(lengthSquared()); + } - @Override - public String toString() { - return "Vector4f(" + x + ", " + y + ", " + z + ", " + w + ")"; - } + public Vector3f toVector3f() { + return new Vector3f(x, y, z); + } + + @Override + public String toString() { + return "Vector4f(" + x + ", " + y + ", " + z + ", " + w + ")"; + } } 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 1d8a9ff..f65f2eb 100644 --- a/src/main/java/com/enderio/core/common/vecmath/Vertex.java +++ b/src/main/java/com/enderio/core/common/vecmath/Vertex.java @@ -2,148 +2,157 @@ package com.enderio.core.common.vecmath; public class Vertex { - public Vector3d xyz = new Vector3d(); - public Vector2f uv = null; - public Vector3f normal = null; - public Vector4f color = null; + public Vector3d xyz = new Vector3d(); + public Vector2f uv = null; + public Vector3f normal = null; + public Vector4f color = null; - public int brightness = -1; + public int brightness = -1; - public Vertex() { - } + public Vertex() {} - public Vertex(Vertex other) { - xyz.set(other.xyz); - if (other.uv != null) { - uv = new Vector2f(other.uv); + public Vertex(Vertex other) { + xyz.set(other.xyz); + if (other.uv != null) { + uv = new Vector2f(other.uv); + } + if (other.normal != null) { + normal = new Vector3f(other.normal); + } + if (other.color != null) { + color = new Vector4f(other.color); + } + brightness = other.brightness; } - if (other.normal != null) { - normal = new Vector3f(other.normal); + + public Vertex(Vector3d xyz, Vector3f normal, Vector2f uv) { + this.xyz.set(xyz); + this.normal = new Vector3f(normal); + this.uv = new Vector2f(uv); } - if (other.color != null) { - color = new Vector4f(other.color); + + public Vertex(double x, double y, double z, double u, double v, int brightness, float r, float g, float b, + float a) { + xyz.set(x, y, z); + uv = new Vector2f(u, v); + this.brightness = brightness; + color = new Vector4f(r, g, b, a); } - brightness = other.brightness; - } - public Vertex(Vector3d xyz, Vector3f normal, Vector2f uv) { - this.xyz.set(xyz); - this.normal = new Vector3f(normal); - this.uv = new Vector2f(uv); - } - - public Vertex(double x, double y, double z, double u, double v, int brightness, float r, float g, float b, float a) { - xyz.set(x, y, z); - uv = new Vector2f(u, v); - this.brightness = brightness; - color = new Vector4f(r, g, b, a); - } - - public Vertex(double x, double y, double z, double u, double v) { - xyz.set(x, y, z); - uv = new Vector2f(u, v); - } - - public void setXYZ(double x, double y, double z) { - xyz.set(x, y, z); - } - - public void setUV(double u, double v) { - if (uv == null) { - uv = new Vector2f(u, v); - } else { - uv.set(u, v); + public Vertex(double x, double y, double z, double u, double v) { + xyz.set(x, y, z); + uv = new Vector2f(u, v); } - } - public void setNormal(double x, double y, double z) { - if (normal == null) { - normal = new Vector3f(); + public void setXYZ(double x, double y, double z) { + xyz.set(x, y, z); } - normal.set((float) x, (float) y, (float) z); - normal.normalize(); - } - public void setNormal(Vector3f normal2) { - if (normal2 == null) { - normal = null; - return; + public void setUV(double u, double v) { + if (uv == null) { + uv = new Vector2f(u, v); + } else { + uv.set(u, v); + } } - setNormal(normal2.x, normal2.y, normal2.z); - } - public void setBrightness(int brightness) { - this.brightness = brightness; - } + public void setNormal(double x, double y, double z) { + if (normal == null) { + normal = new Vector3f(); + } + normal.set((float) x, (float) y, (float) z); + normal.normalize(); + } - public Vector4f getColor() { - return color; - } + public void setNormal(Vector3f normal2) { + if (normal2 == null) { + normal = null; + return; + } + setNormal(normal2.x, normal2.y, normal2.z); + } - public void setColor(Vector4f color) { - this.color = color; - } + public void setBrightness(int brightness) { + this.brightness = brightness; + } - public void transform(Matrix4d xform) { - xform.transform(xyz); - xform.transformNormal(normal); - } + public Vector4f getColor() { + return color; + } - public void translate(Vector3d trans) { - xyz.add(trans); - } + public void setColor(Vector4f color) { + this.color = color; + } - public double x() { - return xyz.x; - } + public void transform(Matrix4d xform) { + xform.transform(xyz); + xform.transformNormal(normal); + } - public double y() { - return xyz.y; - } + public void translate(Vector3d trans) { + xyz.add(trans); + } - public double z() { - return xyz.z; - } + public double x() { + return xyz.x; + } - public float nx() { - return normal.x; - } + public double y() { + return xyz.y; + } - public float ny() { - return normal.y; - } + public double z() { + return xyz.z; + } - public float nz() { - return normal.z; - } + public float nx() { + return normal.x; + } - public float u() { - return uv.x; - } + public float ny() { + return normal.y; + } - public float v() { - return uv.y; - } + public float nz() { + return normal.z; + } - public float r() { - return color.x; - } + public float u() { + return uv.x; + } - public float g() { - return color.y; - } + public float v() { + return uv.y; + } - public float b() { - return color.z; - } + public float r() { + return color.x; + } - public float a() { - return color.w; - } + public float g() { + return color.y; + } - @Override - public String toString() { - return "Vertex [xyz=" + xyz + ", uv=" + uv + ", normal=" + normal + ", color=" + color + ", brightness=" + brightness + "]"; - } + public float b() { + return color.z; + } + + public float a() { + return color.w; + } + + @Override + public String toString() { + return "Vertex [xyz=" + xyz + + ", uv=" + + uv + + ", normal=" + + normal + + ", color=" + + color + + ", brightness=" + + brightness + + "]"; + } } 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 505c18c..ce1e628 100644 --- a/src/main/java/com/enderio/core/common/vecmath/ViewFrustum.java +++ b/src/main/java/com/enderio/core/common/vecmath/ViewFrustum.java @@ -2,171 +2,169 @@ package com.enderio.core.common.vecmath; public class ViewFrustum { - public static final int LTN = 0; - public static final int LTF = 1; - public static final int LBN = 2; - public static final int LBF = 3; - public static final int RTN = 4; - public static final int RTF = 5; - public static final int RBN = 6; - public static final int RBF = 7; + public static final int LTN = 0; + public static final int LTF = 1; + public static final int LBN = 2; + public static final int LBF = 3; + public static final int RTN = 4; + public static final int RTF = 5; + public static final int RBN = 6; + public static final int RBF = 7; - public static final int VERTEX_COUNT = 8; + public static final int VERTEX_COUNT = 8; - public static final int PLANE_COUNT = 6; + public static final int PLANE_COUNT = 6; - private static final int TOP = 0; - private static final int BOTTOM = 1; - private static final int LEFT = 2; - private static final int RIGHT = 3; - private static final int NEAR = 4; - private static final int FAR = 5; + private static final int TOP = 0; + private static final int BOTTOM = 1; + private static final int LEFT = 2; + private static final int RIGHT = 3; + private static final int NEAR = 4; + private static final int FAR = 5; - private Vector4d vertices[] = new Vector4d[8]; - private Vector4d planes[] = new Vector4d[6]; + private Vector4d vertices[] = new Vector4d[8]; + private Vector4d planes[] = new Vector4d[6]; - private Vector3d eye; + private Vector3d eye; - private Vector3d min; - private Vector3d max; + private Vector3d min; + private Vector3d max; - public ViewFrustum() { - eye = new Vector3d(); - min = new Vector3d(); - max = new Vector3d(); - for (int i = 0; i < VERTEX_COUNT; i++) { - vertices[i] = new Vector4d(); - } - for (int i = 0; i < PLANE_COUNT; i++) { - planes[i] = new Vector4d(); - } - } - - public ViewFrustum(ViewFrustum other) { - eye = new Vector3d(other.eye); - min = new Vector3d(other.min); - max = new Vector3d(other.max); - for (int i = 0; i < VERTEX_COUNT; i++) { - vertices[i] = new Vector4d(other.vertices[i]); - } - for (int i = 0; i < PLANE_COUNT; i++) { - planes[i] = new Vector4d(other.planes[i]); - } - } - - public boolean containsPoint(Vector3d point) { - for (Vector4d plane : planes) { - if (distanceFromPointToPlane(plane, point) < 0) { - return false; - } - } - return true; - } - - private Vector3d toThreeComponent(Vector3d from) { - return new Vector3d(from.x, from.y, from.z); - } - - private double distanceFromPointToPlane(Vector4d plane, Vector3d point) { - Vector4d newPoint = new Vector4d(point.x, point.y, point.z, 1); - return plane.dot(newPoint); - } - - public Vector4d getVertex(int index) { - return vertices[index]; - } - - public Vector3d getEye() { - return eye; - } - - public Vector3d getMin() { - return min; - } - - public Vector3d getMax() { - return max; - } - - public Vector4d getLeftPlane() { - return getPlane(LEFT); - } - - public Vector4d getRightPlane() { - return getPlane(RIGHT); - } - - public Vector4d getTopPlane() { - return getPlane(TOP); - } - - public Vector4d getBottomPlane() { - return getPlane(BOTTOM); - } - - public Vector4d getNearPlane() { - return getPlane(NEAR); - } - - public Vector4d getFarPlane() { - return getPlane(FAR); - } - - /** - * @param ivm - * the inverse view transformation matrix - * @param ipm - * the inverse projection matrix - */ - public void computeFrustum(Matrix4d ivm, Matrix4d ipm) { - - Matrix4d vpm = new Matrix4d(); - vpm.mul(ivm, ipm); - - ivm.getTranslation(eye); - - vertices[LBF].set(-1, -1, 1, 1); - vertices[LTF].set(-1, 1, 1, 1); - vertices[RTF].set(1, 1, 1, 1); - vertices[RBF].set(1, -1, 1, 1); - vertices[LBN].set(-1, -1, -1, 1); - vertices[LTN].set(-1, 1, -1, 1); - vertices[RTN].set(1, 1, -1, 1); - vertices[RBN].set(1, -1, -1, 1); - - min.set(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE); - max.set(-Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE); - - for (int i = 0; i < VERTEX_COUNT; i++) { - vpm.transform(vertices[i]); - double w = vertices[i].w; - // apply perspective - vertices[i].x /= w; - vertices[i].y /= w; - vertices[i].z /= w; - - min.x = Math.min(min.x, vertices[i].x); - min.y = Math.min(min.y, vertices[i].y); - min.z = Math.min(min.z, vertices[i].z); - - max.x = Math.max(max.x, vertices[i].x); - max.y = Math.max(max.y, vertices[i].y); - max.z = Math.max(max.z, vertices[i].z); + public ViewFrustum() { + eye = new Vector3d(); + min = new Vector3d(); + max = new Vector3d(); + for (int i = 0; i < VERTEX_COUNT; i++) { + vertices[i] = new Vector4d(); + } + for (int i = 0; i < PLANE_COUNT; i++) { + planes[i] = new Vector4d(); + } } - VecmathUtil.computePlaneEquation(vertices[LBN], vertices[LBF], vertices[LTF], planes[LEFT]); - VecmathUtil.computePlaneEquation(vertices[LBN], vertices[LBF], vertices[LTF], planes[LEFT]); - VecmathUtil.computePlaneEquation(vertices[RBN], vertices[RTF], vertices[RBF], planes[RIGHT]); - VecmathUtil.computePlaneEquation(vertices[LTN], vertices[LTF], vertices[RTF], planes[TOP]); - VecmathUtil.computePlaneEquation(vertices[LBN], vertices[RBF], vertices[LBF], planes[BOTTOM]); - VecmathUtil.computePlaneEquation(vertices[LBN], vertices[LTN], vertices[RTN], planes[NEAR]); - VecmathUtil.computePlaneEquation(vertices[LBF], vertices[RTF], vertices[LTF], planes[FAR]); + public ViewFrustum(ViewFrustum other) { + eye = new Vector3d(other.eye); + min = new Vector3d(other.min); + max = new Vector3d(other.max); + for (int i = 0; i < VERTEX_COUNT; i++) { + vertices[i] = new Vector4d(other.vertices[i]); + } + for (int i = 0; i < PLANE_COUNT; i++) { + planes[i] = new Vector4d(other.planes[i]); + } + } - } + public boolean containsPoint(Vector3d point) { + for (Vector4d plane : planes) { + if (distanceFromPointToPlane(plane, point) < 0) { + return false; + } + } + return true; + } - private final Vector4d getPlane(int index) { - assert ((index >= 0) && (index < PLANE_COUNT)) : "Illegal index : 0 <= index < " + PLANE_COUNT; - return planes[index]; - } + private Vector3d toThreeComponent(Vector3d from) { + return new Vector3d(from.x, from.y, from.z); + } + + private double distanceFromPointToPlane(Vector4d plane, Vector3d point) { + Vector4d newPoint = new Vector4d(point.x, point.y, point.z, 1); + return plane.dot(newPoint); + } + + public Vector4d getVertex(int index) { + return vertices[index]; + } + + public Vector3d getEye() { + return eye; + } + + public Vector3d getMin() { + return min; + } + + public Vector3d getMax() { + return max; + } + + public Vector4d getLeftPlane() { + return getPlane(LEFT); + } + + public Vector4d getRightPlane() { + return getPlane(RIGHT); + } + + public Vector4d getTopPlane() { + return getPlane(TOP); + } + + public Vector4d getBottomPlane() { + return getPlane(BOTTOM); + } + + public Vector4d getNearPlane() { + return getPlane(NEAR); + } + + public Vector4d getFarPlane() { + return getPlane(FAR); + } + + /** + * @param ivm the inverse view transformation matrix + * @param ipm the inverse projection matrix + */ + public void computeFrustum(Matrix4d ivm, Matrix4d ipm) { + + Matrix4d vpm = new Matrix4d(); + vpm.mul(ivm, ipm); + + ivm.getTranslation(eye); + + vertices[LBF].set(-1, -1, 1, 1); + vertices[LTF].set(-1, 1, 1, 1); + vertices[RTF].set(1, 1, 1, 1); + vertices[RBF].set(1, -1, 1, 1); + vertices[LBN].set(-1, -1, -1, 1); + vertices[LTN].set(-1, 1, -1, 1); + vertices[RTN].set(1, 1, -1, 1); + vertices[RBN].set(1, -1, -1, 1); + + min.set(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE); + max.set(-Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE); + + for (int i = 0; i < VERTEX_COUNT; i++) { + vpm.transform(vertices[i]); + double w = vertices[i].w; + // apply perspective + vertices[i].x /= w; + vertices[i].y /= w; + vertices[i].z /= w; + + min.x = Math.min(min.x, vertices[i].x); + min.y = Math.min(min.y, vertices[i].y); + min.z = Math.min(min.z, vertices[i].z); + + max.x = Math.max(max.x, vertices[i].x); + max.y = Math.max(max.y, vertices[i].y); + max.z = Math.max(max.z, vertices[i].z); + } + + VecmathUtil.computePlaneEquation(vertices[LBN], vertices[LBF], vertices[LTF], planes[LEFT]); + VecmathUtil.computePlaneEquation(vertices[LBN], vertices[LBF], vertices[LTF], planes[LEFT]); + VecmathUtil.computePlaneEquation(vertices[RBN], vertices[RTF], vertices[RBF], planes[RIGHT]); + VecmathUtil.computePlaneEquation(vertices[LTN], vertices[LTF], vertices[RTF], planes[TOP]); + VecmathUtil.computePlaneEquation(vertices[LBN], vertices[RBF], vertices[LBF], planes[BOTTOM]); + VecmathUtil.computePlaneEquation(vertices[LBN], vertices[LTN], vertices[RTN], planes[NEAR]); + VecmathUtil.computePlaneEquation(vertices[LBF], vertices[RTF], vertices[LTF], planes[FAR]); + + } + + private final Vector4d getPlane(int index) { + assert ((index >= 0) && (index < PLANE_COUNT)) : "Illegal index : 0 <= index < " + PLANE_COUNT; + return planes[index]; + } }