diff --git a/src/main/java/cofh/api/CoFHAPIProps.java b/src/main/java/cofh/api/CoFHAPIProps.java new file mode 100644 index 0000000..775d8d2 --- /dev/null +++ b/src/main/java/cofh/api/CoFHAPIProps.java @@ -0,0 +1,11 @@ +package cofh.api; + +public class CoFHAPIProps { + + private CoFHAPIProps() { + + } + + public static final String VERSION = "1.7.10R1.0.3"; + +} diff --git a/src/main/java/cofh/api/package-info.java b/src/main/java/cofh/api/package-info.java new file mode 100644 index 0000000..08ff5fc --- /dev/null +++ b/src/main/java/cofh/api/package-info.java @@ -0,0 +1,9 @@ +/** + * (C) 2014 Team CoFH / CoFH / Cult of the Full Hub + * http://www.teamcofh.com + */ +@API(apiVersion = CoFHAPIProps.VERSION, owner = "CoFHLib", provides = "CoFHAPI") +package cofh.api; + +import cpw.mods.fml.common.API; + diff --git a/src/main/java/cofh/api/transport/IEnderAttuned.java b/src/main/java/cofh/api/transport/IEnderAttuned.java new file mode 100644 index 0000000..4a453f5 --- /dev/null +++ b/src/main/java/cofh/api/transport/IEnderAttuned.java @@ -0,0 +1,13 @@ +package cofh.api.transport; + +interface IEnderAttuned { + + public String getChannelString(); + + public int getFrequency(); + + public boolean setFrequency(int frequency); + + public boolean clearFrequency(); + +} diff --git a/src/main/java/cofh/api/transport/IEnderEnergyHandler.java b/src/main/java/cofh/api/transport/IEnderEnergyHandler.java new file mode 100644 index 0000000..0886be7 --- /dev/null +++ b/src/main/java/cofh/api/transport/IEnderEnergyHandler.java @@ -0,0 +1,35 @@ +package cofh.api.transport; + +/** + * This interface is implemented on Ender Attuned objects which can receive Energy (Redstone Flux). + * + * @author King Lemming + * + */ +public interface IEnderEnergyHandler extends IEnderAttuned { + + /** + * Return whether or not the Ender Attuned object can currently send energy (Redstone Flux). + */ + boolean canSendEnergy(); + + /** + * This should be checked to see if the Ender Attuned object can currently receive energy (Redstone Flux). + * + * Note: In practice, this can (and should) be used to ensure that something does not send to itself. + */ + boolean canReceiveEnergy(); + + /** + * This tells the Ender Attuned object to receive energy. This returns the amount remaining, *not* the amount received - a return of 0 means that all energy + * was received! + * + * @param energy + * Amount of energy to be received. + * @param simulate + * If TRUE, the result will only be simulated. + * @return Amount of energy that is remaining (or would be remaining, if simulated). + */ + int receiveEnergy(int energy, boolean simulate); + +} diff --git a/src/main/java/cofh/api/transport/IEnderFluidHandler.java b/src/main/java/cofh/api/transport/IEnderFluidHandler.java new file mode 100644 index 0000000..3927fe1 --- /dev/null +++ b/src/main/java/cofh/api/transport/IEnderFluidHandler.java @@ -0,0 +1,37 @@ +package cofh.api.transport; + +import net.minecraftforge.fluids.FluidStack; + +/** + * This interface is implemented on Ender Attuned objects which can receive Fluid. + * + * @author King Lemming + * + */ +public interface IEnderFluidHandler extends IEnderAttuned { + + /** + * Return whether or not the Ender Attuned object can currently send FluidStacks. + */ + boolean canSendFluid(); + + /** + * This should be checked to see if the Ender Attuned object can currently receive a FluidStack. + * + * Note: In practice, this can (and should) be used to ensure that something does not send to itself. + */ + boolean canReceiveFluid(); + + /** + * This tells the Ender Attuned object to receive a FluidStack. This returns what remains of the original stack, *not* the amount received - a null return + * means that the entire stack was received! + * + * @param fluid + * FluidStack to be received. + * @param simulate + * If TRUE, the result will only be simulated. + * @return FluidStack representing how much fluid is remaining (or would be remaining, if simulated). + */ + FluidStack receiveFluid(FluidStack fluid, boolean simulate); + +} diff --git a/src/main/java/cofh/api/transport/IEnderItemHandler.java b/src/main/java/cofh/api/transport/IEnderItemHandler.java new file mode 100644 index 0000000..2944a00 --- /dev/null +++ b/src/main/java/cofh/api/transport/IEnderItemHandler.java @@ -0,0 +1,38 @@ +package cofh.api.transport; + +import net.minecraft.item.ItemStack; + +/** + * This interface is implemented on Ender Attuned objects which can receive Items. + * + * @author King Lemming + * + */ +public interface IEnderItemHandler extends IEnderAttuned { + + /** + * Return whether or not the Ender Attuned object can currently send ItemStacks. + */ + boolean canSendItems(); + + /** + * This should be checked to see if the Ender Attuned object can currently receive an ItemStack. + * + * Note: In practice, this can (and should) be used to ensure that something does not send to itself. + */ + boolean canReceiveItems(); + + /** + * This tells the Ender Attuned object to receive an ItemStack. This returns what remains of the original stack, *not* the amount received - a null return + * means that the entire stack was received! + * + * This function does not support simulation because Inventory manipulation in Minecraft is an absolute mess and it would be a computational liability to do + * so. + * + * @param item + * ItemStack to be received. + * @return An ItemStack representing how much is remaining. + */ + ItemStack receiveItem(ItemStack item); + +} diff --git a/src/main/java/cofh/api/transport/IItemDuct.java b/src/main/java/cofh/api/transport/IItemDuct.java new file mode 100644 index 0000000..4c50c85 --- /dev/null +++ b/src/main/java/cofh/api/transport/IItemDuct.java @@ -0,0 +1,26 @@ +package cofh.api.transport; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.ForgeDirection; + +/** + * This interface is implemented on ItemDucts. Use it to attempt to eject items into an entry point. + * + * @author Zeldo Kavira, King Lemming + * + */ +public interface IItemDuct { + + /** + * Insert an ItemStack into the IItemDuct. Will only accept items if there is a valid destination. This returns what is remaining of the original stack - a + * null return means that the entire stack was accepted/routed! + * + * @param from + * Orientation the item is inserted from. + * @param item + * ItemStack to be inserted. The size of this stack corresponds to the maximum amount to insert. + * @return An ItemStack representing how much is remaining after the item was inserted into the Duct. + */ + public ItemStack insertItem(ForgeDirection from, ItemStack item); + +} diff --git a/src/main/java/cofh/api/transport/RegistryEnderAttuned.java b/src/main/java/cofh/api/transport/RegistryEnderAttuned.java new file mode 100644 index 0000000..0f91b21 --- /dev/null +++ b/src/main/java/cofh/api/transport/RegistryEnderAttuned.java @@ -0,0 +1,287 @@ +package cofh.api.transport; + +import gnu.trove.map.hash.THashMap; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import net.minecraftforge.common.config.Configuration; + +public final class RegistryEnderAttuned { + + public static Map>> inputItem = new THashMap>>(); + public static Map>> inputFluid = new THashMap>>(); + public static Map>> inputEnergy = new THashMap>>(); + + public static Map>> outputItem = new THashMap>>(); + public static Map>> outputFluid = new THashMap>>(); + public static Map>> outputEnergy = new THashMap>>(); + + public static Configuration linkConf; + + public static Map clientFrequencyNames = new LinkedHashMap(); + public static Map clientFrequencyNamesReversed = new LinkedHashMap(); + + public static void clear() { + + inputItem.clear(); + inputFluid.clear(); + inputEnergy.clear(); + outputItem.clear(); + outputFluid.clear(); + outputEnergy.clear(); + } + + public static List getLinkedItemInputs(IEnderItemHandler theAttuned) { + + if (inputItem.get(theAttuned.getChannelString()) == null) { + return null; + } + return inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); + } + + public static List getLinkedItemOutputs(IEnderItemHandler theAttuned) { + + if (outputItem.get(theAttuned.getChannelString()) == null) { + return null; + } + return outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); + } + + public static List getLinkedFluidInputs(IEnderFluidHandler theAttuned) { + + if (inputFluid.get(theAttuned.getChannelString()) == null) { + return null; + } + return inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); + } + + public static List getLinkedFluidOutputs(IEnderFluidHandler theAttuned) { + + if (outputFluid.get(theAttuned.getChannelString()) == null) { + return null; + } + return outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); + } + + public static List getLinkedEnergyInputs(IEnderEnergyHandler theAttuned) { + + if (inputEnergy.get(theAttuned.getChannelString()) == null) { + return null; + } + return inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); + } + + public static List getLinkedEnergyOutputs(IEnderEnergyHandler theAttuned) { + + if (outputEnergy.get(theAttuned.getChannelString()) == null) { + return null; + } + return outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); + } + + /* HELPER FUNCTIONS */ + public static void addItemHandler(IEnderItemHandler theAttuned) { + + if (theAttuned.canSendItems()) { + if (inputItem.get(theAttuned.getChannelString()) == null) { + inputItem.put(theAttuned.getChannelString(), new HashMap>()); + } + if (inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { + inputItem.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList()); + } + if (!inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { + inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); + } + } + if (theAttuned.canReceiveItems()) { + if (outputItem.get(theAttuned.getChannelString()) == null) { + outputItem.put(theAttuned.getChannelString(), new HashMap>()); + } + if (outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { + outputItem.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList()); + } + if (!outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { + outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); + } + } + } + + public static void addFluidHandler(IEnderFluidHandler theAttuned) { + + if (theAttuned.canSendFluid()) { + if (inputFluid.get(theAttuned.getChannelString()) == null) { + inputFluid.put(theAttuned.getChannelString(), new HashMap>()); + } + if (inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { + inputFluid.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList()); + } + if (!inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { + inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); + } + } + if (theAttuned.canReceiveFluid()) { + if (outputFluid.get(theAttuned.getChannelString()) == null) { + outputFluid.put(theAttuned.getChannelString(), new HashMap>()); + } + if (outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { + outputFluid.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList()); + } + if (!outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { + outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); + } + } + } + + public static void addEnergyHandler(IEnderEnergyHandler theAttuned) { + + if (theAttuned.canSendEnergy()) { + if (inputEnergy.get(theAttuned.getChannelString()) == null) { + inputEnergy.put(theAttuned.getChannelString(), new HashMap>()); + } + if (inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { + inputEnergy.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList()); + } + if (!inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { + inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); + } + } + if (theAttuned.canReceiveEnergy()) { + if (outputEnergy.get(theAttuned.getChannelString()) == null) { + outputEnergy.put(theAttuned.getChannelString(), new HashMap>()); + } + if (outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { + outputEnergy.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList()); + } + if (!outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { + outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); + } + } + } + + public static void removeItemHandler(IEnderItemHandler theAttuned) { + + if (inputItem.get(theAttuned.getChannelString()) != null) { + if (inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { + inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); + if (inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { + inputItem.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); + } + } + } + if (outputItem.get(theAttuned.getChannelString()) != null) { + if (outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { + outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); + if (outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { + outputItem.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); + } + } + } + } + + public static void removeFluidHandler(IEnderFluidHandler theAttuned) { + + if (inputFluid.get(theAttuned.getChannelString()) != null) { + if (inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { + inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); + if (inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { + inputFluid.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); + } + } + } + if (outputFluid.get(theAttuned.getChannelString()) != null) { + if (outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { + outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); + if (outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { + outputFluid.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); + } + } + } + } + + public static void removeEnergyHandler(IEnderEnergyHandler theAttuned) { + + if (inputEnergy.get(theAttuned.getChannelString()) != null) { + if (inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { + inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); + if (inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { + inputEnergy.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); + } + } + } + if (outputEnergy.get(theAttuned.getChannelString()) != null) { + if (outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { + outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); + if (outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { + outputEnergy.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); + } + } + } + } + + public static void add(IEnderAttuned theAttuned) { + + if (theAttuned instanceof IEnderItemHandler) { + addItemHandler((IEnderItemHandler) theAttuned); + } + if (theAttuned instanceof IEnderFluidHandler) { + addFluidHandler((IEnderFluidHandler) theAttuned); + } + if (theAttuned instanceof IEnderEnergyHandler) { + addEnergyHandler((IEnderEnergyHandler) theAttuned); + } + } + + public static void remove(IEnderAttuned theAttuned) { + + if (theAttuned instanceof IEnderItemHandler) { + removeItemHandler((IEnderItemHandler) theAttuned); + } + if (theAttuned instanceof IEnderFluidHandler) { + removeFluidHandler((IEnderFluidHandler) theAttuned); + } + if (theAttuned instanceof IEnderEnergyHandler) { + removeEnergyHandler((IEnderEnergyHandler) theAttuned); + } + } + + public static void sortClientNames() { + + List> list = new ArrayList>(clientFrequencyNames.entrySet()); + Collections.sort(list, new Comparator>() { + + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + + int int1 = Integer.valueOf(clientFrequencyNamesReversed.get(o1.getValue())); + int int2 = Integer.valueOf(clientFrequencyNamesReversed.get(o2.getValue())); + return int1 > int2 ? 1 : int1 == int2 ? 0 : -1; + } + }); + Map result = new LinkedHashMap(); + for (Map.Entry entry : list) { + result.put(entry.getKey(), entry.getValue()); + } + clientFrequencyNames = result; + } + + public static void clearClientNames() { + + clientFrequencyNames.clear(); + clientFrequencyNamesReversed.clear(); + } + + public static void addClientNames(String owner, String name) { + + if (!owner.isEmpty()) { + clientFrequencyNames.put(owner, name); + clientFrequencyNamesReversed.put(name, owner); + } + } + +} diff --git a/src/main/java/cofh/api/transport/package-info.java b/src/main/java/cofh/api/transport/package-info.java new file mode 100644 index 0000000..fae0150 --- /dev/null +++ b/src/main/java/cofh/api/transport/package-info.java @@ -0,0 +1,10 @@ +/** + * (C) 2014 Team CoFH / CoFH / Cult of the Full Hub + * http://www.teamcofh.com + */ +@API(apiVersion = CoFHAPIProps.VERSION, owner = "CoFHAPI", provides = "CoFHAPI|transport") +package cofh.api.transport; + +import cofh.api.CoFHAPIProps; +import cpw.mods.fml.common.API; + diff --git a/src/main/java/com/enderio/core/client/gui/FakeEmptySlot.java b/src/main/java/com/enderio/core/client/gui/FakeEmptySlot.java new file mode 100644 index 0000000..433721d --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/FakeEmptySlot.java @@ -0,0 +1,42 @@ +package com.enderio.core.client.gui; + +import net.minecraft.client.gui.GuiScreen; + +import org.lwjgl.opengl.GL11; + +import com.enderio.core.client.render.RenderUtil; + +class FakeEmptySlot { + + private static final int WIDTH = ItemButton.DEFAULT_WIDTH; + private static final int HWIDTH = ItemButton.HWIDTH; + private static final int HEIGHT = ItemButton.DEFAULT_HEIGHT; + private static final int HHEIGHT = ItemButton.HHEIGHT; + + private int xPosition; + private int yPosition; + private GuiScreen g; + + public FakeEmptySlot(GuiScreen g, int x, int y) { + xPosition = x; + yPosition = y; + this.g = g; + + } + + @SuppressWarnings("synthetic-access") + public void drawSlot() { + RenderUtil.bindItemTexture(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + int hoverState = 0; + // top half + g.drawTexturedModalRect(xPosition, yPosition, 0, 46 + hoverState * 20, HWIDTH, HHEIGHT); + g.drawTexturedModalRect(xPosition + HWIDTH, yPosition, 200 - HWIDTH, 46 + hoverState * 20, HWIDTH, HHEIGHT); + // bottom half + g.drawTexturedModalRect(xPosition, yPosition + HHEIGHT, 0, 64 - HHEIGHT + (hoverState * 20), HWIDTH, HHEIGHT); + g.drawTexturedModalRect(xPosition + HWIDTH, yPosition + HHEIGHT, 200 - HWIDTH, 64 - HHEIGHT + (hoverState * 20), HWIDTH, HHEIGHT); + + } + +} \ No newline at end of file diff --git a/src/main/java/com/enderio/core/client/gui/GhostSlot.java b/src/main/java/com/enderio/core/client/gui/GhostSlot.java new file mode 100644 index 0000000..7f1abdf --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/GhostSlot.java @@ -0,0 +1,26 @@ +package com.enderio.core.client.gui; + +import net.minecraft.item.ItemStack; + +public class GhostSlot { + + public int x; + public int y; + public boolean visible = true; + public ItemStack stack; + + public boolean isMouseOver(int mx, int my) { + return mx >= x && mx < (x+16) && my >= y && my < (y+16); + } + + public boolean isVisible() { + return visible; + } + + public ItemStack getStack() { + return stack; + } + + public void putStack(ItemStack stack) { + } +} diff --git a/src/main/java/com/enderio/core/client/gui/GuiContainerBase.java b/src/main/java/com/enderio/core/client/gui/GuiContainerBase.java new file mode 100644 index 0000000..64b82d0 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/GuiContainerBase.java @@ -0,0 +1,636 @@ +package com.enderio.core.client.gui; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.minecraft.util.Timer; + +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import codechicken.nei.VisiblityData; +import codechicken.nei.api.INEIGuiHandler; +import codechicken.nei.api.TaggedInventoryArea; + +import com.enderio.core.client.gui.ToolTipManager.ToolTipRenderer; +import com.enderio.core.client.render.RenderUtil; +import com.google.common.collect.Lists; + +import cpw.mods.fml.common.Optional; +import crazypants.enderio.gui.IGuiOverlay; +import crazypants.enderio.gui.IconButtonEIO; +import crazypants.enderio.gui.TextFieldEIO; +import crazypants.enderio.gui.VScrollbarEIO; + +@Optional.InterfaceList({ + @Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems") +}) +public abstract class GuiContainerBase extends GuiContainer implements ToolTipRenderer, IGuiScreen, INEIGuiHandler { + + protected ToolTipManager ttMan = new ToolTipManager(); + protected List overlays = new ArrayList(); + protected List textFields = Lists.newArrayList(); + protected List scrollbars = new ArrayList(); + protected List ghostSlots = new ArrayList(); + + protected GhostSlot hoverGhostSlot; + protected VScrollbarEIO draggingScrollbar; + + protected GuiContainerBase(Container par1Container) { + super(par1Container); + } + + @Override + public void initGui() { + super.initGui(); + fixupGuiPosition(); + for (IGuiOverlay overlay : overlays) { + overlay.init(this); + } + for (TextFieldEIO f : textFields) { + f.init(this); + } + } + + protected void fixupGuiPosition() { + } + + @Override + protected void keyTyped(char c, int key) { + GuiTextField focused = null; + for (GuiTextField 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++) { + TextFieldEIO 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) { + if(focused.textboxKeyTyped(c, key)) { + 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); + } + + 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(); + + 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)) { + 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 ghostSlots; + } + + protected void ghostSlotClicked(GhostSlot slot, int x, int y, int button) { + ItemStack st = Minecraft.getMinecraft().thePlayer.inventory.getItemStack(); + slot.putStack(st); + } + + @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(VScrollbarEIO vs : scrollbars) { + if(vs.mouseClicked(x, y, button)) { + draggingScrollbar = vs; + return; + } + } + } + if(!ghostSlots.isEmpty()) { + GhostSlot slot = getGhostSlot(x, y); + if(slot != null) { + ghostSlotClicked(slot, x, y, button); + return; + } + } + // Right click field clearing + if(button == 1) { + for (TextFieldEIO tf : textFields) { + if(tf.contains(x, y)) { + tf.setText(""); + } + } + } + // Button events for non-left-clicks + if(button >= 1) { + for(Object obj : buttonList) { + if(obj instanceof IconButtonEIO) { + IconButtonEIO btn = (IconButtonEIO) obj; + if(btn.mousePressedButton(mc, x, y, button)) { + btn.func_146113_a(this.mc.getSoundHandler()); + actionPerformedButton(btn, button); + } + } + } + } + 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(VScrollbarEIO vs : scrollbars) { + vs.mouseWheel(x, y, delta); + } + } + } + + protected void actionPerformedButton(IconButtonEIO btn, int mouseButton) { + actionPerformed(btn); + } + + public void addOverlay(IGuiOverlay overlay) { + overlays.add(overlay); + } + + public void removeOverlay(IGuiOverlay overlay) { + overlays.remove(overlay); + } + + public void addScrollbar(VScrollbarEIO vs) { + scrollbars.add(vs); + vs.adjustPosition(); + } + + public void removeScrollbar(VScrollbarEIO vs) { + scrollbars.remove(vs); + if(draggingScrollbar == vs) { + draggingScrollbar = null; + } + } + + 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); + } + } + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glPopMatrix(); + } + } + + @Override + protected void drawGuiContainerBackgroundLayer(float par1, int mouseX, int mouseY) { + for (GuiTextField f : textFields) { + f.drawTextBox(); + } + if(!scrollbars.isEmpty()) { + for(VScrollbarEIO vs : scrollbars) { + vs.drawScrollbar(mouseX, mouseY); + } + } + drawGhostSlots(mouseX, mouseY); + } + + @Override + public void drawScreen(int par1, int par2, float par3) { + hoverGhostSlot = null; + int mx = realMx = par1; + int my = realMy = par2; + for (IGuiOverlay overlay : overlays) { + if(overlay != null && overlay.isVisible() && isMouseInOverlay(par1, par2, overlay)) { + mx = -5000; + my = -5000; + this.drawItemStack(this.mc.thePlayer.inventory.getItemStack(), par1 - this.guiLeft - 8, par2 - this.guiTop - 8, null); + } + } + + super.drawScreen(mx, my, par3); + + if(draggingScrollbar == null) { + if(hoverGhostSlot != null && mc.thePlayer.inventory.getItemStack() == null) { + ItemStack stack = hoverGhostSlot.getStack(); + if(stack != null) { + renderToolTip(stack, 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 = 100.0F; + itemRender.zLevel = 100.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 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; + } + + protected void drawGhostSlots(int mouseX, int mouseY) { + if(ghostSlots.isEmpty()) { + return; + } + int sx = getGuiLeft(); + int sy = getGuiTop(); + drawFakeItemsStart(); + try { + hoverGhostSlot = null; + for(GhostSlot slot : ghostSlots) { + ItemStack stack = slot.getStack(); + if(slot.isVisible()) { + if(stack != null) { + drawFakeItemStack(slot.x + sx, slot.y + sy, stack); + } + if(slot.isMouseOver(mouseX - sx, mouseY - sy)) { + hoverGhostSlot = slot; + } + } + } + if(hoverGhostSlot != null) { + // draw hover last to prevent it from affecting rendering of other slots ... + drawFakeItemHover(hoverGhostSlot.x + sx, hoverGhostSlot.y + sy); + } + } finally { + drawFakeItemsEnd(); + } + } + + protected GhostSlot getGhostSlot(int mouseX, int mouseY) { + mouseX -= getGuiLeft(); + mouseY -= getGuiTop(); + for(GhostSlot slot : ghostSlots) { + if(slot.isVisible() && slot.isMouseOver(mouseX, mouseY)) { + return slot; + } + } + return null; + } + + private boolean isMouseInOverlay(int mouseX, int mouseY, IGuiOverlay overlay) { + int x = mouseX - getGuiLeft(); + int y = mouseY - getGuiTop(); + return overlay.getBounds().contains(x, y); + } + + @Override + public void removeToolTip(GuiToolTip toolTip) { + 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); + } + } + + @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); + } + + @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 i, int i1, ItemStack is, int i2) { + return false; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public boolean hideItemPanelSlot(GuiContainer gc, int x, int y, int w, int h) { + return false; + } +} diff --git a/src/main/java/com/enderio/core/client/gui/GuiIconRenderer.java b/src/main/java/com/enderio/core/client/gui/GuiIconRenderer.java new file mode 100644 index 0000000..9d9b5e3 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/GuiIconRenderer.java @@ -0,0 +1,101 @@ +package com.enderio.core.client.gui; + +import net.minecraft.client.gui.Gui; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; + +import org.lwjgl.opengl.GL11; + +import com.enderio.core.client.render.IconUtil; +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; + + protected int hwidth = HWIDTH; + protected int hheight = HHEIGHT; + protected int width = DEFAULT_WIDTH; + protected int height = DEFAULT_HEIGHT; + + protected IIcon icon; + protected ResourceLocation texture; + + private int yPosition; + private int xPosition; + + 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, 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 int getWidth() { + return width; + } + + public int getHeight() { + return height; + } + + public IIcon getIcon() { + return icon; + } + + public float getAlpha() { + return alpha; + } + + public void setAlpha(float alpha) { + this.alpha = alpha; + } + + public void setIcon(IIcon icon) { + this.icon = icon; + } + + public ResourceLocation getTexture() { + return texture; + } + + public void setTexture(ResourceLocation textureName) { + this.texture = textureName; + } + + public void draw() { + + 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); + + RenderUtil.bindTexture(texture); + drawTexturedModelRectFromIcon(xPosition, yPosition, icon, width, height); + + GL11.glPopAttrib(); + + 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 new file mode 100644 index 0000000..3a4d642 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/GuiScreenBase.java @@ -0,0 +1,230 @@ +package com.enderio.core.client.gui; + +import java.util.Iterator; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.RenderHelper; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import com.enderio.core.client.gui.ToolTipManager.ToolTipRenderer; + +public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer, IGuiScreen { + + protected ToolTipManager ttMan = new ToolTipManager(); + + /** 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; + + /** + * 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; + + protected boolean drawButtons = true; + + protected GuiScreenBase(int xSize, int ySize) { + this.xSize = xSize; + this.ySize = ySize; + } + + @Override + public void addToolTip(GuiToolTip toolTip) { + ttMan.addToolTip(toolTip); + } + + @Override + public void removeToolTip(GuiToolTip toolTip) { + 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); + } + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + + GL11.glPushMatrix(); + GL11.glTranslatef(guiLeft, guiTop, 0.0F); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + GL11.glDisable(GL11.GL_LIGHTING); + drawForegroundLayer(par1, par2); + GL11.glEnable(GL11.GL_LIGHTING); + + GL11.glPopMatrix(); + + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + } + + protected abstract void drawBackgroundLayer(float par3, int par1, int 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; + } + } + + 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(); + + } + } + + @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 void removeButton(GuiButton button) { + buttonList.remove(button); + } + + @Override + public void doActionPerformed(GuiButton guiButton) { + actionPerformed(guiButton); + } + +} diff --git a/src/main/java/com/enderio/core/client/gui/GuiScrollableList.java b/src/main/java/com/enderio/core/client/gui/GuiScrollableList.java new file mode 100644 index 0000000..75f78ee --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/GuiScrollableList.java @@ -0,0 +1,407 @@ +package com.enderio.core.client.gui; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.Tessellator; + +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; + +public abstract class GuiScrollableList { + + 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 final int slotHeight; + + private int scrollUpButtonID; + + private int scrollDownButtonID; + + protected int mouseX; + + protected int mouseY; + + private float initialClickY = -2.0F; + + private float scrollMultiplier; + + private float amountScrolled; + + protected int selectedIndex = -1; + + private long lastClickedTime; + + private boolean showSelectionBox = true; + + protected int margin = 4; + + 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; + + 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; + } + 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(); + + clampScrollToBounds(); + + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_FOG); + + 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); + + Tessellator tessellator = Tessellator.instance; + drawContainerBackground(tessellator); + + int contentYOffset = this.minY + margin - (int) this.amountScrolled; + + for (int i = 0; i < getNumElements(); ++i) { + + 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); + } + } + + 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); + } + + protected void renderScrollBar(Tessellator tessellator) { + + int contentHeightOverBounds = getContentOverhang(); + if(contentHeightOverBounds > 0) { + + int clear = (maxY - minY) * (maxY - minY) / getContentHeight(); + + if(clear < 32) { + clear = 32; + } + + if(clear > maxY - minY - 8) { + clear = maxY - minY - 8; + } + + 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; + } + } + 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; + + } 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/GuiToolTip.java b/src/main/java/com/enderio/core/client/gui/GuiToolTip.java new file mode 100644 index 0000000..5be02a4 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/GuiToolTip.java @@ -0,0 +1,105 @@ +package com.enderio.core.client.gui; + +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.List; + +public class GuiToolTip { + + private static final long DELAY = 0; + + protected Rectangle bounds; + + private long mouseOverStart; + + protected final List text; + + private int lastMouseX = -1; + + private int lastMouseY = -1; + + 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; + } + + 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/IGuiOverlay.java b/src/main/java/com/enderio/core/client/gui/IGuiOverlay.java new file mode 100644 index 0000000..a1ab35e --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/IGuiOverlay.java @@ -0,0 +1,29 @@ +package com.enderio.core.client.gui; + +import java.awt.Rectangle; + +public interface IGuiOverlay { + + void init(IGuiScreen screen); + + + Rectangle getBounds(); + + 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); + + void setVisible(boolean visible); + + boolean isVisible(); + + boolean handleMouseInput(int x, int y, int b); + + boolean isMouseInBounds(int mouseX, int mouseY); + +} diff --git a/src/main/java/com/enderio/core/client/gui/IGuiScreen.java b/src/main/java/com/enderio/core/client/gui/IGuiScreen.java new file mode 100644 index 0000000..ac0b017 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/IGuiScreen.java @@ -0,0 +1,30 @@ +package com.enderio.core.client.gui; + +import java.util.List; +import net.minecraft.client.gui.GuiButton; + +public interface IGuiScreen { + + void addToolTip(GuiToolTip toolTip); + + void removeToolTip(GuiToolTip toolTip); + + int getGuiLeft(); + + int getGuiTop(); + + int getXSize(); + + int getYSize(); + + void addButton(GuiButton button); + + void removeButton(GuiButton button); + + int getOverlayOffsetX(); + + void doActionPerformed(GuiButton but); + + List getGhostSlots(); + +} diff --git a/src/main/java/com/enderio/core/client/gui/IconButton.java b/src/main/java/com/enderio/core/client/gui/IconButton.java new file mode 100644 index 0000000..61bd544 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/IconButton.java @@ -0,0 +1,98 @@ +package com.enderio.core.client.gui; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; + +import org.lwjgl.opengl.GL11; + +import com.enderio.core.client.render.RenderUtil; + +public class IconButton 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; + + protected int hwidth; + protected int hheight; + + protected IIcon icon; + protected ResourceLocation texture; + + public IconButton(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/IconToggleButton.java b/src/main/java/com/enderio/core/client/gui/IconToggleButton.java new file mode 100644 index 0000000..b93e468 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/IconToggleButton.java @@ -0,0 +1,33 @@ +package com.enderio.core.client.gui; + +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; + +public class IconToggleButton extends IconButton { + + 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; + } + return result; + } +} diff --git a/src/main/java/com/enderio/core/client/gui/ItemButton.java b/src/main/java/com/enderio/core/client/gui/ItemButton.java new file mode 100644 index 0000000..94be292 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/ItemButton.java @@ -0,0 +1,85 @@ +package com.enderio.core.client.gui; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +import org.lwjgl.opengl.GL11; + +import com.enderio.core.client.render.RenderUtil; + +public class ItemButton extends GuiButton { + + 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; + + private ItemStack item; + + private FontRenderer fr; + + 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); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/enderio/core/client/gui/ListSelectionListener.java b/src/main/java/com/enderio/core/client/gui/ListSelectionListener.java new file mode 100644 index 0000000..42e4c7c --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/ListSelectionListener.java @@ -0,0 +1,7 @@ +package com.enderio.core.client.gui; + +public interface ListSelectionListener { + + void selectionChanged(GuiScrollableList list, int selectedIndex); + +} diff --git a/src/main/java/com/enderio/core/client/gui/TemplateSlot.java b/src/main/java/com/enderio/core/client/gui/TemplateSlot.java new file mode 100644 index 0000000..a4aaf4d --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/TemplateSlot.java @@ -0,0 +1,41 @@ +package com.enderio.core.client.gui; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +public class TemplateSlot extends Slot { + + protected int slotIndex; + + public TemplateSlot(IInventory inventory, int slotIndex, int x, int y) { + super(inventory, slotIndex, x, y); + this.slotIndex = slotIndex; + } + + @Override + public boolean canTakeStack(EntityPlayer player) { + return true; + } + + @Override + public ItemStack decrStackSize(int par1) { + return null; + } + + @Override + public boolean isItemValid(ItemStack stack) { + return true; + } + + @Override + public void putStack(ItemStack par1ItemStack) { + if(par1ItemStack != null) { + par1ItemStack.stackSize = 0; + } + inventory.setInventorySlotContents(slotIndex, par1ItemStack); + onSlotChanged(); + } + +} diff --git a/src/main/java/com/enderio/core/client/gui/TextFieldEIO.java b/src/main/java/com/enderio/core/client/gui/TextFieldEIO.java new file mode 100644 index 0000000..ce45d54 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/TextFieldEIO.java @@ -0,0 +1,100 @@ +package com.enderio.core.client.gui; + +import java.lang.reflect.Field; + +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiTextField; + +import com.google.common.base.Strings; + +import cpw.mods.fml.relauncher.ReflectionHelper; + +public class TextFieldEIO extends GuiTextField { + + public interface ICharFilter { + + boolean passesFilter(TextFieldEIO tf, char c); + } + + public static final ICharFilter FILTER_NUMERIC = new ICharFilter() { + @Override + public boolean passesFilter(TextFieldEIO tf, char c) { + return Character.isDigit(c) || (c == '-' && Strings.isNullOrEmpty(tf.getText())); + } + }; + + public static ICharFilter FILTER_ALPHABETICAL = new ICharFilter() { + @Override + public boolean passesFilter(TextFieldEIO tf, char c) { + return Character.isLetter(c); + } + }; + + public static ICharFilter FILTER_ALPHANUMERIC = new ICharFilter() { + @Override + public boolean passesFilter(TextFieldEIO 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 TextFieldEIO(FontRenderer fnt, int x, int y, int width, int height) { + this(fnt, x, y, width, height, null); + } + + public TextFieldEIO(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 TextFieldEIO 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; + } +} diff --git a/src/main/java/com/enderio/core/client/gui/ToolTipManager.java b/src/main/java/com/enderio/core/client/gui/ToolTipManager.java new file mode 100644 index 0000000..97ee139 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/ToolTipManager.java @@ -0,0 +1,74 @@ +package com.enderio.core.client.gui; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.minecraft.client.gui.FontRenderer; + +public class ToolTipManager { + + public static interface ToolTipRenderer { + int getGuiLeft(); + + int getGuiTop(); + + int getXSize(); + + FontRenderer getFontRenderer(); + + void drawHoveringText(List par1List, int par2, int par3, FontRenderer font); + } + + private List toolTips = new ArrayList(); + + public void addToolTip(GuiToolTip toolTip) { + if(!toolTips.contains(toolTip)) { + toolTips.add(toolTip); + } + } + + public void removeToolTip(GuiToolTip toolTip) { + 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/VScrollbarEIO.java b/src/main/java/com/enderio/core/client/gui/VScrollbarEIO.java new file mode 100644 index 0000000..49a1769 --- /dev/null +++ b/src/main/java/com/enderio/core/client/gui/VScrollbarEIO.java @@ -0,0 +1,190 @@ +package com.enderio.core.client.gui; + +import java.awt.Rectangle; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.Tessellator; + +import org.lwjgl.opengl.GL11; + +import com.enderio.core.client.render.RenderUtil; + +public class VScrollbarEIO { + + protected final IGuiScreen gui; + + 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 scrollPos; + protected int scrollMax; + + protected boolean pressedUp; + protected boolean pressedDown; + protected boolean pressedThumb; + protected int scrollDir; + protected long timeNextScroll; + + public VScrollbarEIO(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)IconEIO.VSCROLL_THUMB_OFF.width, height); + btnUp = new Rectangle(xPosition, yPosition, + (int)IconEIO.UP_ARROW_OFF.width, (int)IconEIO.UP_ARROW_OFF.height); + btnDown = new Rectangle(xPosition, yPosition + Math.max(0, height - (int)IconEIO.DOWN_ARROW_OFF.height), + (int)IconEIO.DOWN_ARROW_OFF.width, (int)IconEIO.DOWN_ARROW_OFF.height); + thumbArea = new Rectangle(xPosition, yPosition + btnUp.height, + (int)IconEIO.VSCROLL_THUMB_OFF.width, Math.max(0, height - (btnUp.height + btnDown.height))); + } + + public int getScrollPos() { + return scrollPos; + } + + public void setScrollPos(int scrollPos) { + this.scrollPos = limitPos(scrollPos); + } + + public void scrollBy(int amount) { + setScrollPos(scrollPos + amount); + } + + public int getScrollMax() { + return scrollMax; + } + + public void setScrollMax(int scrollMax) { + this.scrollMax = scrollMax; + setScrollPos(scrollPos); + } + + public void drawScrollbar(int mouseX, int mouseY) { + boolean hoverUp = btnUp.contains(mouseX, mouseY); + boolean hoverDown = btnDown.contains(mouseX, mouseY); + + IconEIO iconUp; + if(pressedUp) { + iconUp = hoverUp ? IconEIO.UP_ARROW_HOVER_ON : IconEIO.UP_ARROW_ON; + } else { + iconUp = hoverUp ? IconEIO.UP_ARROW_HOVER_OFF : IconEIO.UP_ARROW_OFF; + } + + IconEIO iconDown; + if(pressedDown) { + iconDown = hoverDown ? IconEIO.DOWN_ARROW_HOVER_ON : IconEIO.DOWN_ARROW_ON; + } else { + iconDown = hoverDown ? IconEIO.DOWN_ARROW_HOVER_OFF : IconEIO.DOWN_ARROW_OFF; + } + + if(scrollDir != 0) { + long time = Minecraft.getSystemTime(); + if((timeNextScroll - time) <= 0) { + timeNextScroll = time + 100; + scrollBy(scrollDir); + } + } + + RenderUtil.bindTexture(IconEIO.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.renderIcon(btnUp.x, btnUp.y, false); + iconDown.renderIcon(btnDown.x, btnDown.y, false); + + if(scrollMax > 0) { + int thumbPos = getThumbPosition(); + boolean hoverThumb = thumbArea.contains(mouseX, mouseY) && mouseY >= thumbPos && mouseY < thumbPos + (int) IconEIO.VSCROLL_THUMB_OFF.height; + + IconEIO iconThumb; + if(pressedThumb) { + iconThumb = IconEIO.VSCROLL_THUMB_HOVER_ON; + } else { + iconThumb = hoverThumb ? IconEIO.VSCROLL_THUMB_HOVER_OFF : IconEIO.VSCROLL_THUMB_OFF; + } + iconThumb.renderIcon(thumbArea.x, thumbPos, false); + } + + tes.draw(); + GL11.glPopAttrib(); + } + + 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)IconEIO.VSCROLL_THUMB_OFF.height; + pressedThumb = !pressedUp && !pressedDown; + } else { + pressedUp = btnUp.contains(x, y); + pressedDown = btnDown.contains(x, y); + pressedThumb = false; + } + + scrollDir = (pressedDown ? 1 : 0) - (pressedUp ? 1 : 0); + if(scrollDir != 0) { + timeNextScroll = Minecraft.getSystemTime() + 200; + scrollBy(scrollDir); + } + } + return isDragActive(); + } + + public boolean mouseClickMove(int x, int y, int button, long time) { + if(pressedThumb) { + int pos = y - (thumbArea.y + (int)IconEIO.VSCROLL_THUMB_OFF.height/2); + int len = thumbArea.height - (int)IconEIO.VSCROLL_THUMB_OFF.height; + if(len > 0) { + setScrollPos(Math.round(pos * (float)scrollMax / (float)len)); + } + return true; + } + 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; + } + + protected int getThumbPosition() { + return thumbArea.y + (thumbArea.height - (int)IconEIO.VSCROLL_THUMB_OFF.height) * scrollPos / scrollMax; + } + + protected int limitPos(int pos) { + return Math.max(0, Math.min(pos, scrollMax)); + } +} diff --git a/src/main/java/com/enderio/core/client/render/BoundingBox.java b/src/main/java/com/enderio/core/client/render/BoundingBox.java new file mode 100644 index 0000000..b3b75f5 --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/BoundingBox.java @@ -0,0 +1,385 @@ +package com.enderio.core.client.render; + +import java.util.ArrayList; +import java.util.List; + +import com.enderio.core.common.util.BlockCoord; +import com.enderio.core.common.vecmath.Vector2f; +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 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. + * + * @param face + * @return + */ + public List getCornersWithUvForFace(ForgeDirection face) { + return getCornersWithUvForFace(face, 0, 1, 0, 1); + } + + 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. + * + * @param face + * @return + */ + 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. + * + * @param face + * @return + */ + 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 new file mode 100644 index 0000000..5596dec --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/ColorUtil.java @@ -0,0 +1,69 @@ +package com.enderio.core.client.render; + +import java.awt.Color; + +import com.enderio.core.common.vecmath.Vector3f; +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 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 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 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 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 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 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); + } + + 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 new file mode 100644 index 0000000..fd59533 --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/ConnectedTextureRenderer.java @@ -0,0 +1,337 @@ +package com.enderio.core.client.render; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; + +import com.enderio.core.common.util.BlockCoord; +import com.enderio.core.common.util.ForgeDirectionOffsets; +import com.enderio.core.common.vecmath.Vector2f; +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 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 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; + } + + 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); + } + } + } + } + + 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; + } 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; + } + + +} diff --git a/src/main/java/com/enderio/core/client/render/CubeRenderer.java b/src/main/java/com/enderio/core/client/render/CubeRenderer.java new file mode 100644 index 0000000..6a79b3c --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/CubeRenderer.java @@ -0,0 +1,340 @@ +package com.enderio.core.client.render; + +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; + +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; + } + + 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 new file mode 100644 index 0000000..2e0b6eb --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/CustomCubeRenderer.java @@ -0,0 +1,58 @@ +package com.enderio.core.client.render; + +import java.util.Collection; + +import net.minecraft.block.Block; +import net.minecraft.util.IIcon; +import net.minecraft.world.IBlockAccess; + +public class CustomCubeRenderer { + + public static final CustomCubeRenderer instance = new CustomCubeRenderer(); + + private CustomRenderBlocks rb = null; + + 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); + } + rb.blockAccess = ba; + rb.setOverrideTexture(getOverrideTexture()); + rb.setFaceRenderers(null); + if(renderer != null) { + rb.addFaceRenderer(renderer); + } + rb.setRenderBoundsFromBlock(par1Block); + rb.renderStandardBlock(par1Block, par2, par3, par4); + } + + public void renderBlock(IBlockAccess ba, Block par1Block, int par2, int par3, int par4, Collection renderers) { + + 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(); + } + 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 new file mode 100644 index 0000000..fc06f1a --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/CustomRenderBlocks.java @@ -0,0 +1,710 @@ +package com.enderio.core.client.render; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import com.enderio.core.common.vecmath.Vertex; + +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.IIcon; +import net.minecraft.world.IBlockAccess; +import net.minecraftforge.common.util.ForgeDirection; + +public class CustomRenderBlocks extends RenderBlocks { + + boolean translateToXYZ = true; + boolean shouldRenderBaseTexture = true; + + 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; + } + + 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.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; + } + + private List calcFaceYPos(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(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; + } + + 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; + } + + 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; + } + + private List calcFaceXPos(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.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; + } + + private List calcFaceYNeg(Block par1Block, double x, double y, double z, IIcon icon) { + + if(hasOverrideBlockTexture()) { + icon = this.overrideBlockTexture; + } + + 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/IConnectedTextureRenderer.java b/src/main/java/com/enderio/core/client/render/IConnectedTextureRenderer.java new file mode 100644 index 0000000..6580b2c --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/IConnectedTextureRenderer.java @@ -0,0 +1,7 @@ +package com.enderio.core.client.render; + +public interface IConnectedTextureRenderer { + + boolean matchesMetadata(int meta1, int meta2); + +} diff --git a/src/main/java/com/enderio/core/client/render/IRenderFace.java b/src/main/java/com/enderio/core/client/render/IRenderFace.java new file mode 100644 index 0000000..3a4d833 --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/IRenderFace.java @@ -0,0 +1,16 @@ +package com.enderio.core.client.render; + +import java.util.List; + +import com.enderio.core.common.vecmath.Vertex; + +import net.minecraft.block.Block; +import net.minecraft.util.IIcon; +import net.minecraftforge.common.util.ForgeDirection; + +public interface IRenderFace { + + 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/client/render/IconUtil.java b/src/main/java/com/enderio/core/client/render/IconUtil.java new file mode 100644 index 0000000..906050c --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/IconUtil.java @@ -0,0 +1,69 @@ +package com.enderio.core.client.render; + +import java.util.ArrayList; + +import net.minecraft.client.renderer.texture.IIconRegister; +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 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); + } + } + } + + public static IIcon getIconForItem(int itemId, int meta) { + Item item = Item.getItemById(itemId); + if(item == null) { + return null; + } + 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 new file mode 100644 index 0000000..d45fdf3 --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/RenderUtil.java @@ -0,0 +1,681 @@ +package com.enderio.core.client.render; + +import java.lang.reflect.Field; +import java.nio.FloatBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.annotation.Nullable; + +import net.minecraft.block.Block; +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.RenderHelper; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.client.resources.IReloadableResourceManager; +import net.minecraft.client.resources.IResourceManagerReloadListener; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.Timer; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; + +import org.lwjgl.opengl.GL11; + +import com.enderio.core.common.util.BlockCoord; +import com.enderio.core.common.util.Log; +import com.enderio.core.common.vecmath.Matrix4d; +import com.enderio.core.common.vecmath.VecmathUtil; +import com.enderio.core.common.vecmath.Vector2f; +import com.enderio.core.common.vecmath.Vector3d; +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_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 Vector3d UP_V = new Vector3d(0, 1, 0); + + public static final Vector3d ZERO_V = new Vector3d(0, 0, 0); + + private static final FloatBuffer MATRIX_BUFFER = GLAllocation.createDirectFloatBuffer(16); + + public static final ResourceLocation BLOCK_TEX = TextureMap.locationBlocksTexture; + + public static final ResourceLocation ITEM_TEX = TextureMap.locationItemsTexture; + + 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 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! + */ + 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(); + } + + /** + * left, bottom, right, top + * + * @param face + * @return + */ + 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; + } + + 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; + } + } + + BlockCoord bc = new BlockCoord(x, y, z); + + 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); + } + + } + + } + + 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; + } + + 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); + } + + } + + 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; + } + + 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(); + } + + 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 registerReloadListener(IResourceManagerReloadListener obj) { + ((IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).registerReloadListener(obj); + } +} diff --git a/src/main/java/com/enderio/core/client/render/TechneModelRenderer.java b/src/main/java/com/enderio/core/client/render/TechneModelRenderer.java new file mode 100644 index 0000000..83e2860 --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/TechneModelRenderer.java @@ -0,0 +1,57 @@ +package com.enderio.core.client.render; + +import java.util.Collection; + +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.world.IBlockAccess; +import net.minecraftforge.client.model.obj.GroupObject; +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; + +public class TechneModelRenderer implements ISimpleBlockRenderingHandler { + + private Collection model; + private int renderId; + + protected VertexTransform vt; + + 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.getModelAll(modid, modelPath), renderId, vt); + } + + public TechneModelRenderer(Collection model, int renderId) { + this(model, renderId, null); + } + + public TechneModelRenderer(Collection model, int renderId, VertexTransform vt) { + this.model = model; + this.renderId = renderId; + this.vt = vt; + } + + @Override + public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { + TechneUtil.vt = this.vt; + TechneUtil.renderInventoryBlock(model, 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(model, world, x, y, z, block, renderer); + } + + @Override + public boolean shouldRender3DInInventory(int modelId) { + return true; + } + + @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 new file mode 100644 index 0000000..9272418 --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/TechneUtil.java @@ -0,0 +1,367 @@ +/* + +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; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import net.minecraft.block.Block; +import net.minecraft.client.model.ModelBox; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.client.model.PositionTextureVertex; +import net.minecraft.client.model.TexturedQuad; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.IBlockAccess; +import net.minecraftforge.client.model.obj.Face; +import net.minecraftforge.client.model.obj.GroupObject; +import net.minecraftforge.client.model.obj.TextureCoordinate; +import net.minecraftforge.client.model.obj.Vertex; +import net.minecraftforge.client.model.techne.TechneModel; +import net.minecraftforge.client.model.techne.TechneModelLoader; +import net.minecraftforge.common.util.ForgeDirection; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.util.vector.Matrix4f; +import org.lwjgl.util.vector.Vector3f; +import org.lwjgl.util.vector.Vector4f; + +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. + */ +public class TechneUtil { + + public static VertexTransform vt = null; + + private static final TechneModelLoader modelLoader = new TechneModelLoader(); + + private static final Tessellator tes = Tessellator.instance; + + public static List bakeModel(ModelRenderer model) { + return bakeModel(model, 1); + } + + public static List bakeModel(ModelRenderer model, float scale) { + return bakeModel(model, scale, new Matrix4f()); + } + + public static List bakeModel(ModelRenderer model, float scale, Matrix4f matrix) { + return bakeModel(model, 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, float scale, Matrix4f matrix, boolean rotateYFirst) { + 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)); + } + + Vector4f vec = new Vector4f(); + List res = new ArrayList(); + + 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]; + for (int j = 0; j < 4; j++) { + PositionTextureVertex pv = quads[i].vertexPositions[j]; + + 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); + + // Increase the interpolation scale by multiples of 2 + while (pv.texturePositionX > uMult) { + uMult *= 2; + } + while (pv.texturePositionY > vMult) { + vMult *= 2; + } + + face.textureCoordinates[j] = new TextureCoordinate(pv.texturePositionX, pv.texturePositionY); + } + face.faceNormal = face.calculateFaceNormal(); + obj.faces.add(face); + } + res.add(obj); + } + + 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); + } + + // Used in the second pass of baking to adjust UVs to the proper interpolation + private static int uMult = 1, vMult = 1; + + /** + * 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(), scale, m, rotateYFirst).get(0); + res.put(e.getKey(), obj); + } + + // Second pass, adjust the UVs to be on a 0-1 interpolation scale + if(uMult + vMult != 2) { + for (GroupObject go : res.values()) { + for (Face f : go.faces) { + for (TextureCoordinate tc : f.textureCoordinates) { + tc.u /= uMult; + tc.v /= vMult; + } + } + } + } + + uMult = vMult = 1; + + return res; + } + + public static Map getModel(String modid, String modelPath) { + TechneModel tm = (TechneModel) modelLoader.loadInstance(new ResourceLocation(modid.toLowerCase(), 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(), modelPath + ".tcn")); + return TechneUtil.bakeModel(tm, 1f / 16, new Matrix4f().scale(new Vector3f(-1, -1, 1))).values(); + } + + 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); + } + + if(isbrh) { + float factor = normal.offsetX != 0 ? 0.8f : normal.offsetZ != 0 ? 0.6f : normal.offsetY < 0 ? 0.5f : 1; + int c = (int) (0xFF * factor); + + 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, icon.getInterpolatedU(t.u * 16), icon.getInterpolatedV(t.v * 16)); + } + } + } + } + + 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, 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 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) { + 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 void resetVT() { + vt = null; + } + + private static IIcon getIconFor(Block block, IBlockAccess world, int x, int y, int z) { + if(block instanceof AbstractMachineBlock) { + return ((AbstractMachineBlock) block).getModelIcon(world, x, y, z); + } + return block.getIcon(world, x, y, z, 0); + } + + private static IIcon getIconFor(Block block, int metadata) { + if(block instanceof AbstractMachineBlock) { + return ((AbstractMachineBlock) block).getModelIcon(); + } + 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 new file mode 100644 index 0000000..9f057ea --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/VertexRotation.java @@ -0,0 +1,57 @@ +package com.enderio.core.client.render; + +import com.enderio.core.common.vecmath.Quat4d; +import com.enderio.core.common.vecmath.Vector3d; +import com.enderio.core.common.vecmath.Vector3f; +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; + + 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(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 double getAngle() { + return angle; + } + + public void setAxis(Vector3d axis) { + this.axis.set(axis); + quat = Quat4d.makeRotate(angle, axis); + } + + public void setCenter(Vector3d cen) { + center.set(cen); + } + + @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 new file mode 100644 index 0000000..485d627 --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/VertexRotationFacing.java @@ -0,0 +1,29 @@ +package com.enderio.core.client.render; + +import com.enderio.core.common.vecmath.Vector3d; + +import net.minecraftforge.common.util.ForgeDirection; + +public class VertexRotationFacing extends VertexRotation { + + private static final double ROTATION_AMOUNT = Math.PI / 2; + + private ForgeDirection 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); + } + } +} diff --git a/src/main/java/com/enderio/core/client/render/VertexTransform.java b/src/main/java/com/enderio/core/client/render/VertexTransform.java new file mode 100644 index 0000000..d5edd23 --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/VertexTransform.java @@ -0,0 +1,15 @@ +package com.enderio.core.client.render; + +import com.enderio.core.common.vecmath.Vector3d; +import com.enderio.core.common.vecmath.Vector3f; +import com.enderio.core.common.vecmath.Vertex; + +public interface VertexTransform { + + public abstract void apply(Vertex vertex); + + public abstract void apply(Vector3d vec); + + public abstract void applyToNormal(Vector3f vec); + +} diff --git a/src/main/java/com/enderio/core/client/render/VertexTransformComposite.java b/src/main/java/com/enderio/core/client/render/VertexTransformComposite.java new file mode 100644 index 0000000..1a203a1 --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/VertexTransformComposite.java @@ -0,0 +1,47 @@ +package com.enderio.core.client.render; + +import java.util.Collection; + +import com.enderio.core.common.vecmath.Vector3d; +import com.enderio.core.common.vecmath.Vector3f; +import com.enderio.core.common.vecmath.Vertex; + +public class VertexTransformComposite implements VertexTransform { + + 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++; + } + } + + @Override + public void apply(Vertex vertex) { + for (VertexTransform xform : xforms) { + xform.apply(vertex); + } + } + + @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 new file mode 100644 index 0000000..d98ad3d --- /dev/null +++ b/src/main/java/com/enderio/core/client/render/VertexTranslation.java @@ -0,0 +1,60 @@ +package com.enderio.core.client.render; + +import com.enderio.core.common.vecmath.Vector3d; +import com.enderio.core.common.vecmath.Vector3f; +import com.enderio.core.common.vecmath.Vertex; + +public class VertexTranslation implements VertexTransform { + + 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(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(Vector3f trans) { + this(trans.x, trans.y, trans.z); + } + + @Override + public void apply(Vertex vertex) { + apply(vertex.xyz); + } + + @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(Vector3d trans) { + set(trans.x, trans.y, trans.z); + } + + @Override + public void applyToNormal(Vector3f vec) { + + } + +} 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 75cca4a..6e824f2 100644 --- a/src/main/java/com/enderio/core/common/handlers/FireworkHandler.java +++ b/src/main/java/com/enderio/core/common/handlers/FireworkHandler.java @@ -60,7 +60,7 @@ public class FireworkHandler if (fireworksLeft > 0 && (!player.getEntityData().getBoolean("fireworkDelay") || player.worldObj.getTotalWorldTime() % 20 == 0)) { BlockCoord pos = getBlockCoord(player); - pos.y += 2; + pos = pos.withY(pos.y + 2); EnderEntityUtils.spawnFirework(pos, player.worldObj.provider.dimensionId, 12); player.getEntityData().setInteger("fireworksLeft", fireworksLeft - 1); diff --git a/src/main/java/com/enderio/core/common/util/ArrayInventory.java b/src/main/java/com/enderio/core/common/util/ArrayInventory.java new file mode 100644 index 0000000..77060eb --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/ArrayInventory.java @@ -0,0 +1,84 @@ +package com.enderio.core.common.util; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +public class ArrayInventory implements IInventory { + + protected ItemStack[] items; + + public ArrayInventory(ItemStack[] items) { + this.items = items; + } + + public ArrayInventory(int size) { + items = new ItemStack[size]; + } + + @Override + public int getSizeInventory() { + return items.length; + } + + @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 getStackInSlotOnClosing(int slot) { + return null; + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + items[slot] = stack; + markDirty(); + } + + @Override + public int getInventoryStackLimit() { + return 64; + } + + @Override + public boolean isUseableByPlayer(EntityPlayer var1) { + return true; + } + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return true; + } + + @Override + public String getInventoryName() { + return "ArrayInventory"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public void markDirty() { + + } + + @Override + public void openInventory() { + + } + + @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 468a716..87c04e4 100644 --- a/src/main/java/com/enderio/core/common/util/BlockCoord.java +++ b/src/main/java/com/enderio/core/common/util/BlockCoord.java @@ -1,91 +1,123 @@ package com.enderio.core.common.util; +import io.netty.buffer.ByteBuf; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.experimental.Wither; -import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; +import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.google.common.base.Strings; @AllArgsConstructor @EqualsAndHashCode -public class BlockCoord -{ - @Wither - public int x, y, z; +public class BlockCoord { + @Wither + public final int x, y, z; - public BlockCoord(Entity e) - { - this(MathHelper.floor_double(e.posX), MathHelper.floor_double(e.posY), MathHelper.floor_double(e.posZ)); - } + public BlockCoord() { + this(0, 0, 0); + } - public BlockCoord(TileEntity te) - { - this(te.xCoord, te.yCoord, te.zCoord); - } + public BlockCoord(double x, double y, double z) { + this(MathHelper.floor_double(x), MathHelper.floor_double(y), MathHelper.floor_double(z)); + } - public BlockCoord(BlockCoord other) - { - this(other.x, other.y, other.z); - } + public BlockCoord(TileEntity tile) { + this(tile.xCoord, tile.yCoord, tile.zCoord); + } - public Block getBlock(World world) - { - return world.getBlock(x, y, z); - } + public BlockCoord(Entity e) { + this(e.posX, e.posY, e.posZ); + } - public int getMetadata(World world) - { - return world.getBlockMetadata(x, y, z); - } + public BlockCoord(BlockCoord bc) { + this(bc.x, bc.y, bc.z); + } - public TileEntity getTileEntity(World world) - { - return world.getTileEntity(x, y, z); - } + public BlockCoord getLocation(ForgeDirection dir) { + return new BlockCoord(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ); + } - public double getDistSq(BlockCoord other) - { - double xDiff = x + 0.5D - other.x; - double yDiff = y + 0.5D - other.y; - double zDiff = z + 0.5D - other.z; - return xDiff * xDiff + yDiff * yDiff + zDiff * zDiff; - } + 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 double getDistSq(TileEntity other) - { - return other.getDistanceFrom(x + 0.5, y + 0.5, z + 0.5); - } + public BlockCoord(MovingObjectPosition mop) { + this(mop.blockX, mop.blockY, mop.blockZ); + } - public void writeToNBT(NBTTagCompound tag) - { - tag.setInteger("blockCoordx", x); - tag.setInteger("blockCoordy", y); - tag.setInteger("blockCoordz", z); - } + public int getMetadata(World world) { + return world.getBlockMetadata(x, y, z); + } - public static BlockCoord readFromNBT(NBTTagCompound tag) - { - int x = tag.getInteger("blockCoordx"); - int y = tag.getInteger("blockCoordy"); - int z = tag.getInteger("blockCoordz"); + public TileEntity getTileEntity(World world) { + return world.getTileEntity(x, y, z); + } - return new BlockCoord(x, y, z); - } + public double getDistSq(BlockCoord other) { + double xDiff = x + 0.5D - other.x; + double yDiff = y + 0.5D - other.y; + double zDiff = z + 0.5D - other.z; + return xDiff * xDiff + yDiff * yDiff + zDiff * zDiff; + } - public void setPosition(double x, double y, double z) - { - this.x = MathHelper.floor_double(x); - this.y = MathHelper.floor_double(y); - this.z = MathHelper.floor_double(z); - } + public double getDistSq(TileEntity other) { + return other.getDistanceFrom(x + 0.5, y + 0.5, z + 0.5); + } - @Override - public String toString() - { - return "X: " + x + " Y: " + y + " Z: " + z; - } + public int getDist(BlockCoord other) { + double dsq = getDistSq(other); + return (int) Math.ceil(Math.sqrt(dsq)); + } + + public int getDist(TileEntity 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 static BlockCoord readFromBuf(ByteBuf buf) { + return new BlockCoord(buf.readInt(), buf.readInt(), buf.readInt()); + } + + public void writeToNBT(NBTTagCompound tag) { + tag.setInteger("bc:x", x); + tag.setInteger("bc:y", y); + tag.setInteger("bc:z", z); + } + + public static BlockCoord readFromNBT(NBTTagCompound tag) { + return new BlockCoord(tag.getInteger("bc:x"), tag.getInteger("bc:y"), tag.getInteger("bc:z")); + } + + public String chatString() { + return chatString(EnumChatFormatting.WHITE); + } + + 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; + } } diff --git a/src/main/java/com/enderio/core/common/util/DyeColor.java b/src/main/java/com/enderio/core/common/util/DyeColor.java new file mode 100644 index 0000000..fc71a25 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/DyeColor.java @@ -0,0 +1,115 @@ +package com.enderio.core.common.util; + +import net.minecraft.item.ItemDye; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; + +public enum DyeColor { + + 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_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" + + }; + + 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 oreId = OreDictionary.getOreID(dye); + if(oreId < 0) { + return null; + } + for (int i = 0; i < DYE_ORE_NAMES.length; i++) { + String dyeName = DYE_ORE_NAMES[i]; + if(OreDictionary.getOreID(dyeName) == oreId) { + return DyeColor.values()[i]; + } + } + return null; + } + + public static DyeColor fromIndex(int index) { + return DyeColor.values()[index]; + } + + private DyeColor() { + } + + public int getColor() { + return ItemDye.field_150922_c[ordinal()]; + } + + public String getName() { + return ItemDye.field_150921_b[ordinal()]; + } + + public String getLocalisedName() { + return Lang.localize(DYE_ORE_UNLOCAL_NAMES[ordinal()], false); + } + + @Override + public String toString() { + return getName(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/enderio/core/common/util/EnderEntityUtils.java b/src/main/java/com/enderio/core/common/util/EnderEntityUtils.java index eed4b7e..6d07932 100644 --- a/src/main/java/com/enderio/core/common/util/EnderEntityUtils.java +++ b/src/main/java/com/enderio/core/common/util/EnderEntityUtils.java @@ -69,13 +69,12 @@ public class EnderEntityUtils { World world = DimensionManager.getWorld(dimID); - BlockCoord pos = new BlockCoord(0, 0, 0); - pos.setPosition(block.x, block.y, block.z); + BlockCoord pos = new BlockCoord(block.x, block.y, block.z); // don't bother if there's no randomness at all if (range > 0) { - pos.setPosition(moveRandomly(block.x, range), block.y, moveRandomly(block.z, range)); + 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)) diff --git a/src/main/java/com/enderio/core/common/util/EntityUtil.java b/src/main/java/com/enderio/core/common/util/EntityUtil.java new file mode 100644 index 0000000..eb8a630 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/EntityUtil.java @@ -0,0 +1,95 @@ +package com.enderio.core.common.util; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.minecraft.block.Block; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityList; +import net.minecraft.entity.EntityLiving; +import net.minecraft.entity.boss.IBossDisplayData; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.item.ItemStack; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.MathHelper; +import net.minecraft.util.StatCollector; +import net.minecraft.world.World; + +import com.enderio.core.common.vecmath.Vector3d; + +public class EntityUtil { + + public static String getDisplayNameForEntity(String mobName) { + return StatCollector.translateToLocal("entity." + mobName + ".name"); + } + + 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; + } + + private EntityUtil() { + } + + public static Vector3d getEntityPosition(Entity ent) { + return new Vector3d(ent.posX, ent.posY, ent.posZ); + } + + 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(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); + } + } + + 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 void spawnItemInWorldWithRandomMotion(EntityItem entity) { + entity.delayBeforeCanPickup = 10; + + 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 new file mode 100644 index 0000000..70a3792 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/FluidUtil.java @@ -0,0 +1,460 @@ +package com.enderio.core.common.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidBlock; +import net.minecraftforge.fluids.IFluidContainerItem; +import net.minecraftforge.fluids.IFluidHandler; +import net.minecraftforge.fluids.IFluidTank; +import cpw.mods.fml.common.Loader; + +public class FluidUtil { + + 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 getExternalFluidHandler(IBlockAccess world, BlockCoord bc) { +// IFluidHandler con = getFluidHandler(world, bc); +// return (con != null && !(con instanceof IConduitBundle)) ? con : null; +// } + + 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; + } + + 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); + } + } + return fluidStack; + } + 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; + } + } + } + } + } + } + } + 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.getFluid(), 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.getFluid(), 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.getFluid(), 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.getFluid() == target.getFluid())) { + ItemStack resultStack = source.getItem().getContainerItem(source); + // TODO +// if (resultStack == null && Config.enableWaterFromBottles && source.getItem() instanceof ItemPotion +// && source.stackTagCompound == null) { +// resultStack = new ItemStack(Items.glass_bottle); +// } + ItemStack remainderStack = source.copy(); + remainderStack.stackSize--; + if (remainderStack.stackSize <= 0) { + remainderStack = null; + } + FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid.getFluid(), 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) { + IFluidTank targetTank = tank.getInputTank(((IFluidContainerItem) source.getItem()).getFluid(source)); + 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.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.getFluid(), 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.getFluid() == target.getFluid())) { + ItemStack resultStack = source.getItem().getContainerItem(source); +// if (resultStack == null && Config.enableWaterFromBottles && source.getItem() instanceof ItemPotion +// && source.stackTagCompound == null) { +// resultStack = new ItemStack(Items.glass_bottle); +// } + ItemStack remainderStack = source.copy(); + remainderStack.stackSize--; + if (remainderStack.stackSize <= 0) { + remainderStack = null; + } + FluidStack remainderFluid = target != null ? target.copy() : new FluidStack(resultFluid.getFluid(), 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); + } + } + + 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(); + + 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); + } + } + + return true; + } + + public static class FluidAndStack { + public final FluidStack fluidStack; + public final ItemStack itemStack; + + public FluidAndStack(FluidStack fluidStack, ItemStack itemStack) { + this.fluidStack = fluidStack; + this.itemStack = itemStack; + } + + 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 new file mode 100644 index 0000000..1dff19f --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/ForgeDirectionOffsets.java @@ -0,0 +1,60 @@ +package com.enderio.core.common.util; + +import net.minecraftforge.common.util.ForgeDirection; + +import com.enderio.core.common.vecmath.Vector3d; + +public final class ForgeDirectionOffsets { + + 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); + } + } + + 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; + } + 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 new file mode 100644 index 0000000..3610170 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/IBlockAccessWrapper.java @@ -0,0 +1,78 @@ +package com.enderio.core.common.util; + +import net.minecraft.block.Block; +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; + + 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; + } + } + + @Override + @SideOnly(Side.CLIENT) + public int getLightBrightnessForSkyBlocks(int var1, int var2, int var3, int var4) { + return 15 << 20 | 15 << 4; + } + + @Override + @SideOnly(Side.CLIENT) + public int getHeight() { + return wrapped.getHeight(); + } + + @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/IFluidReceptor.java b/src/main/java/com/enderio/core/common/util/IFluidReceptor.java new file mode 100644 index 0000000..18ed6e3 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/IFluidReceptor.java @@ -0,0 +1,9 @@ +package com.enderio.core.common.util; + +import net.minecraftforge.fluids.IFluidHandler; + +public interface IFluidReceptor { + + boolean isValidReceptor(IFluidHandler handler); + +} diff --git a/src/main/java/com/enderio/core/common/util/IItemReceptor.java b/src/main/java/com/enderio/core/common/util/IItemReceptor.java new file mode 100644 index 0000000..ef19cc4 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/IItemReceptor.java @@ -0,0 +1,12 @@ +package com.enderio.core.common.util; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.ForgeDirection; + +public interface IItemReceptor { + + boolean canInsertIntoObject(Object into, ForgeDirection side); + + int doInsertItem(Object into, ItemStack item, ForgeDirection side); + +} diff --git a/src/main/java/com/enderio/core/common/util/IProgressTile.java b/src/main/java/com/enderio/core/common/util/IProgressTile.java new file mode 100644 index 0000000..fcf5ba2 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/IProgressTile.java @@ -0,0 +1,22 @@ +package com.enderio.core.common.util; + +import net.minecraft.tileentity.TileEntity; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +public interface IProgressTile { + + float getProgress(); + + /** + * Client-only. Called to set clientside progress for syncing/rendering + * purposes. + * + * @param progress + * The % progress. + */ + @SideOnly(Side.CLIENT) + void setProgress(float progress); + + TileEntity getTileEntity(); +} diff --git a/src/main/java/com/enderio/core/common/util/ITankAccess.java b/src/main/java/com/enderio/core/common/util/ITankAccess.java new file mode 100644 index 0000000..acb905d --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/ITankAccess.java @@ -0,0 +1,33 @@ +package com.enderio.core.common.util; + +import net.minecraftforge.fluids.FluidStack; +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); + + /** + * 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(); + +} diff --git a/src/main/java/com/enderio/core/common/util/InventoryWrapper.java b/src/main/java/com/enderio/core/common/util/InventoryWrapper.java new file mode 100644 index 0000000..2953d4c --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/InventoryWrapper.java @@ -0,0 +1,118 @@ +package com.enderio.core.common.util; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; + +public class InventoryWrapper implements ISidedInventory { + + public static ISidedInventory asSidedInventory(IInventory inv) { + if(inv == null) { + return null; + } + if(inv instanceof ISidedInventory) { + return (ISidedInventory) inv; + } + 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; + } + 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 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; + } +} \ No newline at end of file diff --git a/src/main/java/com/enderio/core/common/util/ItemUtil.java b/src/main/java/com/enderio/core/common/util/ItemUtil.java new file mode 100644 index 0000000..3692c1d --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/ItemUtil.java @@ -0,0 +1,256 @@ +package com.enderio.core.common.util; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.inventory.InventoryLargeChest; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntityChest; +import net.minecraftforge.common.util.ForgeDirection; +import cofh.api.transport.IItemDuct; +import cpw.mods.fml.common.Loader; + +public class ItemUtil { + + public static final List receptors = 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. 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 + } + } + + public static String getDurabilityString(ItemStack item) { + if(item == null) { + return null; + } + return Lang.localize("item.darkSteel.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); + } else if(into instanceof IInventory) { + return ItemUtil.doInsertItemInv(getInventory((IInventory) into), item, side); + } 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); + } + + /* + * Insert items into an IInventory or an ISidedInventory. + */ + private static int doInsertItemInv(IInventory inv, ItemStack item, ForgeDirection inventorySide) { + 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); + } + + private static int doInsertItemInv(IInventory inv, ISidedInventory sidedInv, ISlotIterator slots, ItemStack item, ForgeDirection inventorySide) { + 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; + 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; + inv.setInventorySlotContents(firstFreeSlot, toInsert); + } + } + + if(numInserted > 0) { + 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; + if(chest.adjacentChestXNeg != null) { + neighbour = chest.adjacentChestXNeg; + } else if(chest.adjacentChestXPos != null) { + neighbour = chest.adjacentChestXPos; + } else if(chest.adjacentChestZNeg != null) { + neighbour = chest.adjacentChestZNeg; + } else if(chest.adjacentChestZPos != null) { + neighbour = chest.adjacentChestZPos; + } + if(neighbour != null) { + return new InventoryLargeChest("", inv, neighbour); + } + return inv; + } + return inv; + } + + /** + * Checks if items, damage and NBT are equal and the items are stackable. + * + * @param s1 + * @param s2 + * @return + */ + 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 + */ + 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/Lang.java b/src/main/java/com/enderio/core/common/util/Lang.java new file mode 100644 index 0000000..bcdfee4 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/Lang.java @@ -0,0 +1,31 @@ +package com.enderio.core.common.util; + +import java.util.IllegalFormatException; + +import net.minecraft.util.StatCollector; + +public class Lang { + + public static final String prefix = "enderio."; + + public static String localize(String s, String... args) { + return localize(s, true, args); + } + + public static String localize(String s, boolean appendEIO, String... args) { + if(appendEIO) { + s = prefix + s; + } + String ret = StatCollector.translateToLocal(s); + try { + return String.format(ret, (Object[]) args); + } catch (IllegalFormatException e) { + return ret; + } + } + + public static String[] localizeList(String string) { + String s = localize(string); + return s.split("\\|"); + } +} diff --git a/src/main/java/com/enderio/core/common/util/Log.java b/src/main/java/com/enderio/core/common/util/Log.java new file mode 100644 index 0000000..51e7929 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/Log.java @@ -0,0 +1,32 @@ +package com.enderio.core.common.util; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.enderio.core.EnderCore; + + +public final class Log { + + public static final Logger LOGGER = LogManager.getLogger(EnderCore.MODID); + + public static void warn(String msg) { + LOGGER.warn(msg); + } + + public static void error(String msg) { + LOGGER.error(msg); + } + + public static void info(String msg) { + LOGGER.info(msg); + } + + public static void debug(String msg) { + LOGGER.debug(msg); + } + + 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 new file mode 100644 index 0000000..74eb87c --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/MetadataUtil.java @@ -0,0 +1,43 @@ +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); + } + } + 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); + } + } + 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); + } + 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 new file mode 100644 index 0000000..3fc909e --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/OreDictionaryHelper.java @@ -0,0 +1,45 @@ +package com.enderio.core.common.util; + +import java.util.List; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; + +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 boolean isRegistered(String name) { + if(!getOres(name).isEmpty()) { + return true; + } + 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); + } + +} diff --git a/src/main/java/com/enderio/core/common/util/PlayerUtil.java b/src/main/java/com/enderio/core/common/util/PlayerUtil.java new file mode 100644 index 0000000..d071802 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/PlayerUtil.java @@ -0,0 +1,31 @@ +package com.enderio.core.common.util; + +import java.util.Map; +import java.util.UUID; + +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(); + } + } + 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); + } + return uuid; + } +} diff --git a/src/main/java/com/enderio/core/common/util/RoundRobinIterator.java b/src/main/java/com/enderio/core/common/util/RoundRobinIterator.java new file mode 100644 index 0000000..67b41bf --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/RoundRobinIterator.java @@ -0,0 +1,44 @@ +package com.enderio.core.common.util; + +import java.util.Iterator; +import java.util.List; + +public class RoundRobinIterator implements Iterable, Iterator { + + 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; + } + 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 c23db6f..f40818e 100644 --- a/src/main/java/com/enderio/core/common/util/Scheduler.java +++ b/src/main/java/com/enderio/core/common/util/Scheduler.java @@ -4,12 +4,13 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import lombok.AllArgsConstructor; + import com.enderio.core.EnderCore; import com.enderio.core.common.Handlers.Handler; import com.enderio.core.common.Handlers.Handler.HandlerType; import com.enderio.core.common.Handlers.Handler.Inst; -import lombok.AllArgsConstructor; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent; diff --git a/src/main/java/com/enderio/core/common/util/SoundUtil.java b/src/main/java/com/enderio/core/common/util/SoundUtil.java new file mode 100644 index 0000000..00a5ea2 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/SoundUtil.java @@ -0,0 +1,17 @@ +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); + } + +} diff --git a/src/main/java/com/enderio/core/common/util/Util.java b/src/main/java/com/enderio/core/common/util/Util.java new file mode 100644 index 0000000..ecd5b59 --- /dev/null +++ b/src/main/java/com/enderio/core/common/util/Util.java @@ -0,0 +1,528 @@ +package com.enderio.core.common.util; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.item.EntityXPOrb; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemPotion; +import net.minecraft.item.ItemStack; +import net.minecraft.util.MathHelper; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.oredict.OreDictionary; + +import com.enderio.core.common.vecmath.Vector3d; +import com.google.common.base.Charsets; +import com.google.common.base.Joiner; +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 { + return null; + } + } else { + stack.splitStack(1); + return stack; + } + } + + public static void giveExperience(EntityPlayer thePlayer, float experience) { + if(experience < 1.0F) { + int rndRound = MathHelper.floor_float(experience); + if(rndRound < MathHelper.ceiling_float_int(experience) && (float) Math.random() < experience) { + ++rndRound; + } + experience = rndRound; + } + int intExp = Math.round(experience); + 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; + } + 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; + } + 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); + } + + // 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/vecmath/Camera.java b/src/main/java/com/enderio/core/common/vecmath/Camera.java new file mode 100644 index 0000000..405aadc --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Camera.java @@ -0,0 +1,146 @@ +package com.enderio.core.common.vecmath; + +import java.awt.Rectangle; + +public class Camera { + + private Rectangle viewport; + + private Matrix4d projectionTranspose; + private Matrix4d projectionMatrix; + private Matrix4d projectionInverse; + + 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; + } + Matrix4d ipm = getInverseProjectionMatrix(); + if(ipm == null) { + return null; + } + 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; + } + return false; + } + + 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; + } + + public void setViewport(Rectangle viewport) { + if(viewport != null) { + setViewport(viewport.x, viewport.y, viewport.width, viewport.height); + } + } + + 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; + } + +} diff --git a/src/main/java/com/enderio/core/common/vecmath/Matrix4d.java b/src/main/java/com/enderio/core/common/vecmath/Matrix4d.java new file mode 100644 index 0000000..95c2a2a --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Matrix4d.java @@ -0,0 +1,591 @@ +package com.enderio.core.common.vecmath; + +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 Matrix4d() { + } + + 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]; + + 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; + } + + } + + 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 new file mode 100644 index 0000000..8fc5b5b --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Quat4d.java @@ -0,0 +1,57 @@ +package com.enderio.core.common.vecmath; + +public class Quat4d { + + 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 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; + } + + public double x; + public double y; + public double z; + public double w; + + 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); + } + +} diff --git a/src/main/java/com/enderio/core/common/vecmath/VecmathUtil.java b/src/main/java/com/enderio/core/common/vecmath/VecmathUtil.java new file mode 100644 index 0000000..860c7de --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/VecmathUtil.java @@ -0,0 +1,637 @@ +package com.enderio.core.common.vecmath; + +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; + } + + // 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)); + + Vector3d result = new Vector3d(pointInLine); + lineDirection.scale(t); + result.add(lineDirection); + return result; + } + + /** + * 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) { + + // grab the eye's position + ivm.getTranslation(eyeOut); + + Matrix4d vpm = new Matrix4d(); + vpm.mul(ivm, ipm); + + // 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; + + // 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); + + double w = tmp.w; + Vector3d nearXYZ = new Vector3d(tmp.x / w, tmp.y / w, tmp.z / w); + + // and then on the far plane + tmp.x = screenX; + tmp.y = screenY; + tmp.z = 1; + tmp.w = 1.0; + vpm.transform(tmp); + + w = tmp.w; + Vector3d farXYZ = new Vector3d(tmp.x / w, tmp.y / w, tmp.z / w); + + normalOut.set(farXYZ); + normalOut.sub(nearXYZ); + normalOut.normalize(); + + } + + // /** + // * 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. + */ + + public static Matrix4d createProjectionMatrixAsPerspective(double fovDegrees, double near, + double far, int viewportWidth, int viewportHeight) { + + Matrix4d matrix = new Matrix4d(); + // for impl details see gluPerspective doco in OpenGL reference manual + double aspect = (double) viewportWidth / (double) viewportHeight; + + double theta = (Math.toRadians(fovDegrees) / 2d); + double f = Math.cos(theta) / Math.sin(theta); + + double a = (far + near) / (near - far); + double b = (2d * far * near) / (near - far); + + matrix.set(new double[] { f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, a, b, 0, 0, -1, 0 }); + + return matrix; + } + + /** + * 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. + */ + + public static Matrix4d createProjectionMatrixAsPerspective(double left, double right, + double bottom, double top, double zNear, double zFar) { + + double A = (right + left) / (right - left); + double B = (top + bottom) / (top - bottom); + double C = (Math.abs(zFar) > Double.MAX_VALUE) ? -1. : -(zFar + zNear) / (zFar - zNear); + double D = (Math.abs(zFar) > Double.MAX_VALUE) ? -2. * zNear : -2.0 * zFar * zNear + / (zFar - zNear); + + Matrix4d matrix = new Matrix4d(); + matrix.set(new double[] { 2.0 * zNear / (right - left), 0.0, 0.0, 0.0, 0.0, + 2.0 * zNear / (top - bottom), 0.0, 0.0, A, B, C, -1.0, 0.0, 0.0, D, 0.0 + + }); + + matrix.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. + */ + + public static Matrix4d createProjectionMatrixAsOrtho(double left, double right, double bottom, + double top, double near, double far) { + + Matrix4d matrix = new Matrix4d(); + // for impl details see glOrtho doco in OpenGL reference manual + double tx = -((right + left) / (right - left)); + double ty = -((top + bottom) / (top - bottom)); + double tz = -((far + near) / (far - near)); + + matrix.set(new double[] { 2d / (right - left), 0, 0, tx, 0, 2d / (top - bottom), 0, ty, 0, 0, + -2d / (far - near), tz, 0, 0, 0, 1 }); + + 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) { + + projMat.transpose(); + + double transNearPlane = (-near * projMat.getElement(2, 2) + projMat.getElement(3, 2)) + / (-near * projMat.getElement(2, 3) + projMat.getElement(3, 3)); + double transFarPlane = (-far * projMat.getElement(2, 2) + projMat.getElement(3, 2)) + / (-far * projMat.getElement(2, 3) + projMat.getElement(3, 3)); + + double ratio = Math.abs(2.0 / (transNearPlane - transFarPlane)); + double center = -(transNearPlane + transFarPlane) / 2.0; + + Matrix4d mat = new Matrix4d(); + mat.setIdentity(); + mat.setElement(2, 2, ratio); + mat.setElement(3, 2, center * ratio); + + projMat.mul(mat); + projMat.transpose(); + + } + + /** + * 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 createMatrixAsLookAt(Vector3d eyePos, + Vector3d lookAtPos, Vector3d upVec) { + + Vector3d eye = new Vector3d(eyePos); + Vector3d lookAt = new Vector3d(lookAtPos); + Vector3d up = new Vector3d(upVec); + + Vector3d forwardVec = new Vector3d(lookAt); + forwardVec.sub(eye); + forwardVec.normalize(); + + Vector3d sideVec = new Vector3d(); + sideVec.cross(forwardVec, up); + sideVec.normalize(); + + Vector3d upVed = new Vector3d(); + upVed.cross(sideVec, forwardVec); + upVed.normalize(); + + Matrix4d mat = new Matrix4d(sideVec.x, sideVec.y, sideVec.z, 0, upVed.x, upVed.y, upVed.z, 0, + -forwardVec.x, -forwardVec.y, -forwardVec.z, 0, 0, 0, 0, 1); + + eye.negate(); + // mat.transform(eye); + mat.transformNormal(eye); + mat.setTranslation(eye); + + return mat; + } + + /** + * Pre-multiplies the vector by the matrix. + * + * @param v + * the vector. + * @param mat + * the matrix. + * @return the result of the multiplication. + */ + + 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. + */ + + public static Vector4d[] getEyePlanesForMatrix(Matrix4d matrix) { + + Matrix4d copy = new Matrix4d(matrix); + copy.transpose(); + + 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)); + + 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 new file mode 100644 index 0000000..83b61ca --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Vector2d.java @@ -0,0 +1,96 @@ +package com.enderio.core.common.vecmath; + +public class Vector2d { + + public double x; + public double y; + + public Vector2d() { + x = 0; + y = 0; + } + + public Vector2d(double x, double y) { + this.x = x; + this.y = 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(Vector2f 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 sub(Vector2d 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 negate() { + x = -x; + y = -y; + } + + 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 double lengthSquared() { + return x * x + y * y; + } + + 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 distance(Vector2d v) { + return Math.sqrt(distanceSquared(v)); + } + + @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 new file mode 100644 index 0000000..41ca18a --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Vector2f.java @@ -0,0 +1,95 @@ +package com.enderio.core.common.vecmath; + +public class Vector2f { + + public float x; + public float y; + + public Vector2f() { + x = 0; + y = 0; + } + + 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(Vector2d 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(float x, float y) { + this.x = x; + this.y = 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 sub(Vector2f vec) { + x -= vec.x; + y -= vec.y; + } + + public void negate() { + x = -x; + y = -y; + } + + 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 double lengthSquared() { + return x * x + y * y; + } + + 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 distance(Vector2f v) { + return Math.sqrt(distanceSquared(v)); + } + + @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 new file mode 100644 index 0000000..fc2fba7 --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Vector3d.java @@ -0,0 +1,153 @@ +package com.enderio.core.common.vecmath; + +import net.minecraft.util.Vec3; +import net.minecraftforge.client.model.obj.Vertex; + +public class Vector3d { + + public double x; + public double y; + public double z; + + 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(Vector3d other) { + this(other.x, other.y, other.z); + } + + public Vector3d(Vector3f corner) { + this(corner.x, corner.y, corner.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(Vector3f v) { + set(v.x, v.y, v.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(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 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 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 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 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 double lengthSquared() { + return x * x + y * y + z * z; + } + + 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 distance(Vector3d v) { + return Math.sqrt(distanceSquared(v)); + } + + @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 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 new file mode 100644 index 0000000..fca964f --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Vector3f.java @@ -0,0 +1,119 @@ +package com.enderio.core.common.vecmath; + +public class Vector3f { + + public float x; + public float y; + public float z; + + 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(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(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(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(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(Vector3d vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + } + + public void negate() { + x = -x; + y = -y; + z = -z; + } + + 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 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 length() { + return Math.sqrt(lengthSquared()); + } + + @Override + public String toString() { + return "Vector3f(" + 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 new file mode 100644 index 0000000..babaea9 --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Vector4d.java @@ -0,0 +1,91 @@ +package com.enderio.core.common.vecmath; + +public class Vector4d { + + public double x; + public double y; + public double z; + public double w; + + 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(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(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 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 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 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 length() { + return Math.sqrt(lengthSquared()); + } + + @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 new file mode 100644 index 0000000..fbde6c8 --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Vector4f.java @@ -0,0 +1,108 @@ +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 Vector4f(float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = 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 Vector4f(Vector4f other) { + this(other.x, other.y, other.z, other.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(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 add(Vector4f vec) { + x += vec.x; + y += vec.y; + z += vec.z; + w += vec.w; + } + + public void sub(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 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 double dot(Vector4f 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 length() { + return Math.sqrt(lengthSquared()); + } + + 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 new file mode 100644 index 0000000..5cd88af --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/Vertex.java @@ -0,0 +1,149 @@ +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 int brightness = -1; + + public Vertex() { + } + + 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; + } + + 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 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 void setNormal(Vector3f normal2) { + if(normal2 == null) { + normal = null; + return; + } + setNormal(normal2.x, normal2.y, normal2.z); + } + + public void setBrightness(int brightness) { + this.brightness = brightness; + } + + public Vector4f getColor() { + return color; + } + + public void setColor(Vector4f color) { + this.color = color; + } + + public void transform(Matrix4d xform) { + xform.transform(xyz); + xform.transformNormal(normal); + } + + public void translate(Vector3d trans) { + xyz.add(trans); + } + + public double x() { + return xyz.x; + } + + public double y() { + return xyz.y; + } + + public double z() { + return xyz.z; + } + + public float nx() { + return normal.x; + } + + public float ny() { + return normal.y; + } + + public float nz() { + return normal.z; + } + + public float u() { + return uv.x; + } + + public float v() { + return uv.y; + } + + public float r() { + return color.x; + } + + public float g() { + return color.y; + } + + 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 new file mode 100644 index 0000000..7640eea --- /dev/null +++ b/src/main/java/com/enderio/core/common/vecmath/ViewFrustum.java @@ -0,0 +1,172 @@ +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 VERTEX_COUNT = 8; + + 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 Vector4d vertices[] = new Vector4d[8]; + private Vector4d planes[] = new Vector4d[6]; + + private Vector3d eye; + + 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); + } + + 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]; + } + +}