diff --git a/.classpath b/.classpath new file mode 100644 index 00000000..4a9e7474 --- /dev/null +++ b/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ff007088 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/bin +/build +/download diff --git a/.project b/.project new file mode 100644 index 00000000..97fca3a4 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + EnderIO + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/README.md b/README.md index f554c7c6..658dabc9 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,6 @@ EnderIO ======= + +All code (excluding the build craft API, which is covered by the build craft liscence) is 'unliscenced' into the public domain. +Do what you want with it, as long as you smile while doing so. While it is not a requirement, it would be nice to know if it is being used and how, so send me hello to crazypants.mc at gmail.com. + diff --git a/build.xml b/build.xml new file mode 100644 index 00000000..e510b19c --- /dev/null +++ b/build.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/common/buildcraft/api/blueprints/BlockSignature.java b/common/buildcraft/api/blueprints/BlockSignature.java new file mode 100644 index 00000000..51db24d4 --- /dev/null +++ b/common/buildcraft/api/blueprints/BlockSignature.java @@ -0,0 +1,77 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.blueprints; + +public class BlockSignature { + + public String blockClassName; + public String tileClassName; + public String blockName; + public String mod; + public String modVersion; + public String customField; + + public BlockSignature(String str) { + String[] values = str.split("/"); + + int i = 0; + + if (values[0].equals("#B")) { + i++; + } + + blockClassName = values[i]; + tileClassName = values[i + 1]; + blockName = values[i + 2]; + mod = values[i + 3]; + modVersion = values[i + 4]; + customField = values[i + 5]; + + replaceNullWithStar(); + + } + + public BlockSignature() { + replaceNullWithStar(); + } + + @Override + public String toString() { + replaceNullWithStar(); + + return "#B/" + blockClassName + "/" + tileClassName + "/" + blockName + "/" + mod + "/" + modVersion + "/" + customField; + } + + public void replaceNullWithStar() { + if (blockClassName == null) { + blockClassName = "*"; + } + + if (tileClassName == null) { + tileClassName = "*"; + } + + if (blockName == null) { + blockName = "*"; + } + + if (mod == null) { + mod = "*"; + } + + if (modVersion == null) { + modVersion = "*"; + } + + if (customField == null) { + customField = "*"; + } + } +} diff --git a/common/buildcraft/api/blueprints/BlueprintManager.java b/common/buildcraft/api/blueprints/BlueprintManager.java new file mode 100644 index 00000000..c71b710e --- /dev/null +++ b/common/buildcraft/api/blueprints/BlueprintManager.java @@ -0,0 +1,35 @@ +package buildcraft.api.blueprints; + +import buildcraft.api.core.BuildCraftAPI; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BlueprintManager { + + public static BptBlock[] blockBptProps = new BptBlock[Block.blocksList.length]; + + public static ItemSignature getItemSignature(Item item) { + ItemSignature sig = new ItemSignature(); + + if (item.itemID >= Block.blocksList.length + BuildCraftAPI.LAST_ORIGINAL_ITEM) { + sig.itemClassName = item.getClass().getSimpleName(); + } + + sig.itemName = item.getUnlocalizedName(new ItemStack(item)); + + return sig; + } + + public static BlockSignature getBlockSignature(Block block) { + return BlueprintManager.blockBptProps[0].getSignature(block); + } + + static { + // Initialize defaults for block properties. + for (int i = 0; i < BlueprintManager.blockBptProps.length; ++i) { + new BptBlock(i); + } + } +} diff --git a/common/buildcraft/api/blueprints/BptBlock.java b/common/buildcraft/api/blueprints/BptBlock.java new file mode 100644 index 00000000..4f48d35e --- /dev/null +++ b/common/buildcraft/api/blueprints/BptBlock.java @@ -0,0 +1,234 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.blueprints; + +import buildcraft.api.core.BuildCraftAPI; +import java.util.ArrayList; +import java.util.LinkedList; +import net.minecraft.block.Block; +import net.minecraft.block.BlockContainer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +/** + * This class allow to specify specific behavior for blocks stored in blueprints: + * + * - what items needs to be used to create that block - how the block has to be built on the world - how to rotate the block - what extra data to store / load + * in the blueprint + * + * Default implementations of this can be seen in the package buildcraft.api.bptblocks. The class BptBlockUtils provide some additional utilities. + * + * Blueprints perform "id translation" in case the block ids between a blueprint and the world installation are different. In order to translate block ids, + * blocks needs to be uniquely identified. By default, this identification is done by: + * + * - the block simple class name - the tile simple class name (if any) - the block name + * + * In certain circumstances, the above is not enough (e.g. if several blocks share the same class and the same name, with no tile). In this case, additional + * data may be provided by children of this class: + * + * - mod name - custom signature + * + * At blueprint load time, BuildCraft will check that each block id of the blueprint corresponds to the block id in the installation. If not, it will perform a + * search through the block list, and upon matching signature, it will translate all blocks ids of the blueprint to the installation ones. If no such block id + * is found, BuildCraft will assume that the block is not installed and will not load the blueprint. + */ + +@Deprecated +public class BptBlock { + + public final int blockId; + + public BptBlock(int blockId) { + this.blockId = blockId; + + BlueprintManager.blockBptProps[blockId] = this; + } + + /** + * Returns the requirements needed to build this block. When the requirements are met, they will be removed all at once from the builder, before calling + * buildBlock. + */ + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + if (slot.blockId != 0) { + if (slot.storedRequirements.size() != 0) { + requirements.addAll(slot.storedRequirements); + } else { + requirements.add(new ItemStack(slot.blockId, 1, slot.meta)); + } + } + } + + /** + * This is called each time an item matches a reqquirement, that is: (req id == stack id) for damageable items (req id == stack id && req dmg == stack dmg) + * for other items by default, it will increase damage of damageable items by the amount of damage of the requirement, and remove the intended amount of non + * damageable item. + * + * Client may override this behavior for default items. Note that this subprogram may be called twice with the same parameters, once with a copy of + * requirements and stack to check if the entire requirements can be fullfilled, and once with the real inventory. Implementer is responsible for updating + * req (with the remaining requirements if any) and stack (after usage) + * + * returns: what was used (similer to req, but created from stack, so that any NBT based differences are drawn from the correct source) + */ + public ItemStack useItem(BptSlotInfo slot, IBptContext context, ItemStack req, ItemStack stack) { + ItemStack result = stack.copy(); + if (stack.isItemStackDamageable()) { + if (req.getItemDamage() + stack.getItemDamage() <= stack.getMaxDamage()) { + stack.setItemDamage(req.getItemDamage() + stack.getItemDamage()); + result.setItemDamage(req.getItemDamage()); + req.stackSize = 0; + } + + if (stack.getItemDamage() >= stack.getMaxDamage()) { + stack.stackSize = 0; + } + } else { + if (stack.stackSize >= req.stackSize) { + result.stackSize = req.stackSize; + stack.stackSize -= req.stackSize; + req.stackSize = 0; + } else { + req.stackSize -= stack.stackSize; + stack.stackSize = 0; + } + } + + if (stack.stackSize == 0 && stack.getItem().getContainerItem() != null) { + Item container = stack.getItem().getContainerItem(); + + stack.itemID = container.itemID; + stack.stackSize = 1; + stack.setItemDamage(0); + } + return result; + } + + /** + * Return true if the block on the world correspond to the block stored in the blueprint at the location given by the slot. By default, this subprogram is + * permissive and doesn't take into account metadata. + * + * Added metadata sensitivity //Krapht + */ + public boolean isValid(BptSlotInfo slot, IBptContext context) { + return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z) && slot.meta == context.world().getBlockMetadata(slot.x, slot.y, slot.z); + } + + /** + * Perform a 90 degree rotation to the slot. + */ + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + + } + + /** + * Places the block in the world, at the location specified in the slot. + */ + public void buildBlock(BptSlotInfo slot, IBptContext context) { + // Meta needs to be specified twice, depending on the block behavior + context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, slot.meta,3); + context.world().setBlockMetadataWithNotify(slot.x, slot.y, slot.z, slot.meta,3); + + if (Block.blocksList[slot.blockId] instanceof BlockContainer) { + TileEntity tile = context.world().getBlockTileEntity(slot.x, slot.y, slot.z); + + slot.cpt.setInteger("x", slot.x); + slot.cpt.setInteger("y", slot.y); + slot.cpt.setInteger("z", slot.z); + + if (tile != null) { + tile.readFromNBT(slot.cpt); + } + } + } + + /** + * Return true if the block should not be placed to the world. Requirements will not be asked on such a block, and building will not be called. + */ + public boolean ignoreBuilding(BptSlotInfo slot) { + return false; + } + + /** + * Initializes a slot from the blueprint according to an objet placed on {x, y, z} on the world. This typically means adding entries in slot.cpt. Note that + * "id" and "meta" will be set automatically, corresponding to the block id and meta. + * + * By default, if the block is a BlockContainer, tile information will be to save / load the block. + */ + public void initializeFromWorld(BptSlotInfo slot, IBptContext context, int x, int y, int z) { + if (Block.blocksList[slot.blockId] instanceof BlockContainer) { + TileEntity tile = context.world().getBlockTileEntity(x, y, z); + + if (tile != null) { + tile.writeToNBT(slot.cpt); + } + } + + if (Block.blocksList[slot.blockId] != null) { + ArrayList req = Block.blocksList[slot.blockId].getBlockDropped(context.world(), x, y, z, context.world().getBlockMetadata(x, y, z), 0); + + if (req != null) { + slot.storedRequirements.addAll(req); + } + } + } + + /** + * Called on a block when the blueprint has finished to place all the blocks. This may be useful to adjust variable depending on surrounding blocks that may + * not be there already at initial building. + */ + public void postProcessing(BptSlotInfo slot, IBptContext context) { + + } + + /** + * By default, block class name, block tile name and block name are used to define block signature. Overriding this subprogram may allow to replace some of + * these with stars, specify the mod that this block kind is coming from or add custom data to the signature. + */ + public BlockSignature getSignature(Block block) { + BlockSignature sig = new BlockSignature(); + + if (block.blockID > BuildCraftAPI.LAST_ORIGINAL_BLOCK) { + sig.blockClassName = block.getClass().getSimpleName(); + + if (block instanceof BlockContainer) { + // TODO: Try to see if we can get a world instance to call with instead of null + TileEntity tile = ((BlockContainer) block).createNewTileEntity(null); + + if (tile != null) { + sig.tileClassName = tile.getClass().getSimpleName(); + } + } + } + + sig.blockName = block.getUnlocalizedName(); + sig.replaceNullWithStar(); + + return sig; + } + + /** + * By default, block name, block and tile classes, mod name and custom signature are matched to verify if a blueprint block corresponds to the installation + * block - except for the default blocks which don't check for classes. For any value, * means match with anything. For compatibilty and evolution reasons, + * mods may want to write a different policy, allowing to migrate one format to the other. + */ + public boolean match(Block block, BlockSignature sig) { + if (block == null) + return false; + + BlockSignature inst = BlueprintManager.getBlockSignature(block); + + return starMatch(sig.blockName, inst.blockName) && starMatch(sig.blockClassName, inst.blockClassName) + && starMatch(sig.tileClassName, inst.tileClassName) && starMatch(sig.customField, inst.customField) && starMatch(sig.mod, inst.mod); + } + + private boolean starMatch(String s1, String s2) { + return s1.equals("*") || s2.equals("*") || s1.equals(s2); + } +} diff --git a/common/buildcraft/api/blueprints/BptBlockUtils.java b/common/buildcraft/api/blueprints/BptBlockUtils.java new file mode 100644 index 00000000..a46d9b12 --- /dev/null +++ b/common/buildcraft/api/blueprints/BptBlockUtils.java @@ -0,0 +1,85 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.blueprints; + +import java.util.LinkedList; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +@Deprecated +public class BptBlockUtils { + + public static void requestInventoryContents(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + ItemStack[] stacks = getItemStacks(slot, context); + + for (ItemStack stack : stacks) { + if (stack != null) { + requirements.add(stack); + } + } + } + + public static void initializeInventoryContents(BptSlotInfo slot, IBptContext context, IInventory inventory) { + ItemStack[] stacks = new ItemStack[inventory.getSizeInventory()]; + + for (int i = 0; i < inventory.getSizeInventory(); ++i) { + stacks[i] = inventory.getStackInSlot(i); + } + + setItemStacks(slot, context, stacks); + } + + public static void buildInventoryContents(BptSlotInfo slot, IBptContext context, IInventory inventory) { + ItemStack[] stacks = getItemStacks(slot, context); + + for (int i = 0; i < stacks.length; ++i) { + inventory.setInventorySlotContents(i, stacks[i]); + } + } + + public static ItemStack[] getItemStacks(BptSlotInfo slot, IBptContext context) { + NBTTagList list = (NBTTagList) slot.cpt.getTag("inv"); + + if (list == null) + return new ItemStack[0]; + + ItemStack stacks[] = new ItemStack[list.tagCount()]; + + for (int i = 0; i < list.tagCount(); ++i) { + ItemStack stack = ItemStack.loadItemStackFromNBT((NBTTagCompound) list.tagAt(i)); + + if (stack != null && stack.itemID != 0 && stack.stackSize > 0) { + stacks[i] = context.mapItemStack(stack); + } + } + + return stacks; + } + + public static void setItemStacks(BptSlotInfo slot, IBptContext context, ItemStack[] stacks) { + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < stacks.length; ++i) { + NBTTagCompound cpt = new NBTTagCompound(); + nbttaglist.appendTag(cpt); + ItemStack stack = stacks[i]; + + if (stack != null && stack.stackSize != 0) { + stack.writeToNBT(cpt); + context.storeId(stack.itemID); + } + } + + slot.cpt.setTag("inv", nbttaglist); + } + +} diff --git a/common/buildcraft/api/blueprints/BptSlotInfo.java b/common/buildcraft/api/blueprints/BptSlotInfo.java new file mode 100644 index 00000000..799a3b4f --- /dev/null +++ b/common/buildcraft/api/blueprints/BptSlotInfo.java @@ -0,0 +1,54 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.blueprints; + +import java.util.LinkedList; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +/** + * This class records a slot, either from a blueprint or from a block placed in the world. + */ + +@Deprecated +public class BptSlotInfo { + + public int blockId = 0; + public int meta = 0; + public int x; + public int y; + public int z; + + /** + * This field contains requirements for a given block when stored in the blueprint. Modders can either rely on this list or compute their own int BptBlock. + */ + public LinkedList storedRequirements = new LinkedList(); + + /** + * This tree contains additional data to be stored in the blueprint. By default, it will be initialized from BptBlock.initializeFromWorld with the standard + * readNBT function of the corresponding tile (if any) and will be loaded from BptBlock.buildBlock using the standard writeNBT function. + */ + public NBTTagCompound cpt = new NBTTagCompound(); + + @Override + public BptSlotInfo clone() { + BptSlotInfo obj = new BptSlotInfo(); + + obj.x = x; + obj.y = y; + obj.z = z; + obj.blockId = blockId; + obj.meta = meta; + obj.cpt = (NBTTagCompound) cpt.copy(); + + return obj; + } + +} diff --git a/common/buildcraft/api/blueprints/IBptContext.java b/common/buildcraft/api/blueprints/IBptContext.java new file mode 100644 index 00000000..8498bfd3 --- /dev/null +++ b/common/buildcraft/api/blueprints/IBptContext.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.blueprints; + +import buildcraft.api.core.IBox; +import buildcraft.api.core.Position; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +/** + * This interface provide contextual information when building or initializing blueprint slots. + */ + +@Deprecated +public interface IBptContext { + + /** + * If bptItemStack is an ItemStack extracted from the blueprint containing this mapping, this will return an item stack with the id of the current world + */ + public ItemStack mapItemStack(ItemStack bptItemStack); + + /** + * Blueprints may be created in a world with a given id setting, and then ported to a world with different ids. Heuristics are used to retreive these new + * ids automatically. This interface provide services to map ids from a blueprints to current ids in the world, and should be used whenever storing block + * numbers or item stacks in blueprints.. + */ + public int mapWorldId(int bptWorldId); + + /** + * This asks the id mapping to store a mapping from this Id, which may be either an itemId or a blockId. In effect, the blueprint will record it and make it + * available upon blueprint load. Note that block present in the blueprint are automatically stored upon blueprint save, so this is really only needed when + * writing ids that are e.g. in inventory stacks. + */ + public void storeId(int worldId); + + public Position rotatePositionLeft(Position pos); + + public IBox surroundingBox(); + + public World world(); +} diff --git a/common/buildcraft/api/blueprints/ItemSignature.java b/common/buildcraft/api/blueprints/ItemSignature.java new file mode 100644 index 00000000..d6bd0310 --- /dev/null +++ b/common/buildcraft/api/blueprints/ItemSignature.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.blueprints; + +@Deprecated +public class ItemSignature { + + public String itemClassName; + public String itemName; + + public ItemSignature(String str) { + String[] values = str.split("/"); + + itemClassName = values[1]; + itemName = values[2]; + + replaceNullWithStar(); + + } + + public ItemSignature() { + replaceNullWithStar(); + } + + @Override + public String toString() { + replaceNullWithStar(); + + return "#I/" + itemClassName + "/" + itemName; + } + + public void replaceNullWithStar() { + if (itemClassName == null) { + itemClassName = "*"; + } + + if (itemName == null) { + itemName = "*"; + } + } +} diff --git a/common/buildcraft/api/bptblocks/BptBlockBed.java b/common/buildcraft/api/bptblocks/BptBlockBed.java new file mode 100644 index 00000000..e2dae05c --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockBed.java @@ -0,0 +1,86 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockBed extends BptBlock { + + public BptBlockBed(int blockId) { + super(blockId); + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + if ((slot.meta & 8) == 0) { + requirements.add(new ItemStack(Item.bed)); + } + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + int orientation = (slot.meta & 7); + int others = slot.meta - orientation; + + switch (orientation) { + case 0: + slot.meta = 1 + others; + break; + case 1: + slot.meta = 2 + others; + break; + case 2: + slot.meta = 3 + others; + break; + case 3: + slot.meta = 0 + others; + break; + } + } + + @Override + public void buildBlock(BptSlotInfo slot, IBptContext context) { + if ((slot.meta & 8) != 0) + return; + + context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, slot.meta,1); + + int x2 = slot.x; + int z2 = slot.z; + + switch (slot.meta) { + case 0: + z2++; + break; + case 1: + x2--; + break; + case 2: + z2--; + break; + case 3: + x2++; + break; + } + + context.world().setBlock(x2, slot.y, z2, slot.blockId, slot.meta + 8,1); + } + + @Override + public boolean ignoreBuilding(BptSlotInfo slot) { + return (slot.meta & 8) != 0; + } +} diff --git a/common/buildcraft/api/bptblocks/BptBlockCustomStack.java b/common/buildcraft/api/bptblocks/BptBlockCustomStack.java new file mode 100644 index 00000000..79aef15c --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockCustomStack.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockCustomStack extends BptBlock { + + final ItemStack customStack; + + public BptBlockCustomStack(int blockId, ItemStack customStack) { + super(blockId); + + this.customStack = customStack; + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(customStack.copy()); + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockDelegate.java b/common/buildcraft/api/bptblocks/BptBlockDelegate.java new file mode 100644 index 00000000..035dc556 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockDelegate.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BlueprintManager; +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockDelegate extends BptBlock { + + final int delegateTo; + + public BptBlockDelegate(int blockId, int delegateTo) { + super(blockId); + + this.delegateTo = delegateTo; + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + BptSlotInfo newSlot = slot.clone(); + slot.blockId = delegateTo; + + if (BlueprintManager.blockBptProps[delegateTo] != null) { + BlueprintManager.blockBptProps[delegateTo].addRequirements(newSlot, context, requirements); + } else { + super.addRequirements(newSlot, context, requirements); + } + } + + @Override + public boolean isValid(BptSlotInfo slot, IBptContext context) { + BptSlotInfo newSlot = slot.clone(); + slot.blockId = delegateTo; + + if (BlueprintManager.blockBptProps[delegateTo] != null) + return BlueprintManager.blockBptProps[delegateTo].isValid(newSlot, context); + else + return super.isValid(newSlot, context); + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + BptSlotInfo newSlot = slot.clone(); + slot.blockId = delegateTo; + + if (BlueprintManager.blockBptProps[delegateTo] != null) { + BlueprintManager.blockBptProps[delegateTo].rotateLeft(newSlot, context); + } else { + super.rotateLeft(newSlot, context); + } + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockDirt.java b/common/buildcraft/api/bptblocks/BptBlockDirt.java new file mode 100644 index 00000000..365cbc45 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockDirt.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockDirt extends BptBlock { + + public BptBlockDirt(int blockId) { + super(blockId); + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(Block.dirt)); + } + + @Override + public void buildBlock(BptSlotInfo slot, IBptContext context) { + context.world().setBlock(slot.x, slot.y, slot.z, Block.dirt.blockID, slot.meta,1); + } + + @Override + public boolean isValid(BptSlotInfo slot, IBptContext context) { + int id = context.world().getBlockId(slot.x, slot.y, slot.z); + + return id == Block.dirt.blockID || id == Block.grass.blockID || id == Block.tilledField.blockID; + } +} diff --git a/common/buildcraft/api/bptblocks/BptBlockDoor.java b/common/buildcraft/api/bptblocks/BptBlockDoor.java new file mode 100644 index 00000000..196e83b3 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockDoor.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockDoor extends BptBlock { + + final ItemStack stack; + + public BptBlockDoor(int blockId, ItemStack stack) { + super(blockId); + + this.stack = stack; + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + if ((slot.meta & 8) == 0) { + requirements.add(stack.copy()); + } + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + int orientation = (slot.meta & 3); + int others = slot.meta - orientation; + + switch (orientation) { + case 0: + slot.meta = 1 + others; + break; + case 1: + slot.meta = 2 + others; + break; + case 2: + slot.meta = 3 + others; + break; + case 3: + slot.meta = 0 + others; + break; + } + } + + @Override + public boolean ignoreBuilding(BptSlotInfo slot) { + return (slot.meta & 8) != 0; + } + + @Override + public void buildBlock(BptSlotInfo slot, IBptContext context) { + context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, slot.meta,1); + context.world().setBlock(slot.x, slot.y + 1, slot.z, slot.blockId, slot.meta + 8,1); + + context.world().setBlockMetadataWithNotify(slot.x, slot.y + 1, slot.z, slot.meta + 8,1); + context.world().setBlockMetadataWithNotify(slot.x, slot.y, slot.z, slot.meta,1); + + } +} diff --git a/common/buildcraft/api/bptblocks/BptBlockFluid.java b/common/buildcraft/api/bptblocks/BptBlockFluid.java new file mode 100644 index 00000000..1769c394 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockFluid.java @@ -0,0 +1,61 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockFluid extends BptBlock { + + private final ItemStack bucketStack; + + public BptBlockFluid(int blockId, ItemStack bucketStack) { + super(blockId); + + this.bucketStack = bucketStack; + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + if (slot.meta == 0) { + requirements.add(bucketStack.copy()); + } + } + + @Override + public boolean isValid(BptSlotInfo slot, IBptContext context) { + if (slot.meta == 0) + return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z) && context.world().getBlockMetadata(slot.x, slot.y, slot.z) == 0; + else + return true; + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + + } + + @Override + public boolean ignoreBuilding(BptSlotInfo slot) { + return slot.meta != 0; + } + + @Override + public void buildBlock(BptSlotInfo slot, IBptContext context) { + if (slot.meta == 0) { + context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, 0,1); + } + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockIgnore.java b/common/buildcraft/api/bptblocks/BptBlockIgnore.java new file mode 100644 index 00000000..12a058bc --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockIgnore.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockIgnore extends BptBlock { + + public BptBlockIgnore(int blockId) { + super(blockId); + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(slot.blockId, 0, 0)); + } + + @Override + public boolean isValid(BptSlotInfo slot, IBptContext context) { + return true; + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + + } + + @Override + public boolean ignoreBuilding(BptSlotInfo slot) { + return true; + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockIgnoreMeta.java b/common/buildcraft/api/bptblocks/BptBlockIgnoreMeta.java new file mode 100644 index 00000000..7f39f637 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockIgnoreMeta.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockIgnoreMeta extends BptBlock { + + public BptBlockIgnoreMeta(int blockId) { + super(blockId); + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(slot.blockId, 1, 0)); + } + + @Override + public boolean isValid(BptSlotInfo slot, IBptContext context) { + return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z); + } +} diff --git a/common/buildcraft/api/bptblocks/BptBlockInventory.java b/common/buildcraft/api/bptblocks/BptBlockInventory.java new file mode 100644 index 00000000..0cebe58f --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockInventory.java @@ -0,0 +1,28 @@ +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import net.minecraft.inventory.IInventory; + +@Deprecated +public class BptBlockInventory extends BptBlock { + + public BptBlockInventory(int blockId) { + super(blockId); + + } + + @Override + public void buildBlock(BptSlotInfo slot, IBptContext context) { + super.buildBlock(slot, context); + + IInventory inv = (IInventory) context.world().getBlockTileEntity(slot.x, slot.y, slot.z); + + for (int i = 0; i < inv.getSizeInventory(); ++i) { + inv.setInventorySlotContents(i, null); + } + + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockLever.java b/common/buildcraft/api/bptblocks/BptBlockLever.java new file mode 100644 index 00000000..b9a8e1c4 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockLever.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockLever extends BptBlockWallSide { + + public BptBlockLever(int blockId) { + super(blockId); + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(slot.blockId, 1, 0)); + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + int status = slot.meta - (slot.meta & 7); + + slot.meta -= status; + super.rotateLeft(slot, context); + slot.meta += status; + + } +} diff --git a/common/buildcraft/api/bptblocks/BptBlockPiston.java b/common/buildcraft/api/bptblocks/BptBlockPiston.java new file mode 100644 index 00000000..b12693bd --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockPiston.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; + +@Deprecated +public class BptBlockPiston extends BptBlockRotateMeta { + + public BptBlockPiston(int blockId) { + super(blockId, new int[] { 2, 5, 3, 4 }, true); + } + + @Override + public void buildBlock(BptSlotInfo slot, IBptContext context) { + int meta = slot.meta & 7; + + context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, meta,1); + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockPumpkin.java b/common/buildcraft/api/bptblocks/BptBlockPumpkin.java new file mode 100644 index 00000000..16049346 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockPumpkin.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockPumpkin extends BptBlock { + + public BptBlockPumpkin(int blockId) { + super(blockId); + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(slot.blockId, 1, 0)); + } + + @Override + public boolean isValid(BptSlotInfo slot, IBptContext context) { + return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z); + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + switch (slot.meta) { + case 0: + slot.meta = 1; + break; + case 1: + slot.meta = 2; + break; + case 2: + slot.meta = 3; + break; + case 3: + slot.meta = 0; + break; + } + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockRedstoneRepeater.java b/common/buildcraft/api/bptblocks/BptBlockRedstoneRepeater.java new file mode 100644 index 00000000..8ac4f023 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockRedstoneRepeater.java @@ -0,0 +1,50 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockRedstoneRepeater extends BptBlock { + + public BptBlockRedstoneRepeater(int blockId) { + super(blockId); + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(Item.redstoneRepeater)); + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + int step = slot.meta - (slot.meta & 3); + + switch (slot.meta - step) { + case 0: + slot.meta = 1 + step; + break; + case 1: + slot.meta = 2 + step; + break; + case 2: + slot.meta = 3 + step; + break; + case 3: + slot.meta = 0 + step; + break; + } + } +} diff --git a/common/buildcraft/api/bptblocks/BptBlockRotateInventory.java b/common/buildcraft/api/bptblocks/BptBlockRotateInventory.java new file mode 100644 index 00000000..6fcc30a8 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockRotateInventory.java @@ -0,0 +1,27 @@ +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import net.minecraft.inventory.IInventory; + +@Deprecated +public class BptBlockRotateInventory extends BptBlockRotateMeta { + + public BptBlockRotateInventory(int blockId, int[] rotations, boolean rotateForward) { + super(blockId, rotations, rotateForward); + + } + + @Override + public void buildBlock(BptSlotInfo slot, IBptContext context) { + super.buildBlock(slot, context); + + IInventory inv = (IInventory) context.world().getBlockTileEntity(slot.x, slot.y, slot.z); + + for (int i = 0; i < inv.getSizeInventory(); ++i) { + inv.setInventorySlotContents(i, null); + } + + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockRotateMeta.java b/common/buildcraft/api/bptblocks/BptBlockRotateMeta.java new file mode 100644 index 00000000..4352b660 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockRotateMeta.java @@ -0,0 +1,84 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockRotateMeta extends BptBlock { + + int[] rot; + boolean rotateForward; + + int infoMask = 0; + + public BptBlockRotateMeta(int blockId, int[] rotations, boolean rotateForward) { + super(blockId); + + rot = rotations; + + for (int i = 0; i < rot.length; ++i) { + if (rot[i] < 4) { + infoMask = (infoMask < 3 ? 3 : infoMask); + } else if (rot[i] < 8) { + infoMask = (infoMask < 7 ? 7 : infoMask); + } else if (rot[i] < 16) { + infoMask = (infoMask < 15 ? 15 : infoMask); + } + } + + this.rotateForward = rotateForward; + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(slot.blockId, 1, 0)); + } + + @Override + public boolean isValid(BptSlotInfo slot, IBptContext context) { + return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z); + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + int pos = slot.meta & infoMask; + int others = slot.meta - pos; + + if (rotateForward) { + if (pos == rot[0]) { + pos = rot[1]; + } else if (pos == rot[1]) { + pos = rot[2]; + } else if (pos == rot[2]) { + pos = rot[3]; + } else if (pos == rot[3]) { + pos = rot[0]; + } + } else { + if (pos == rot[0]) { + pos = rot[3]; + } else if (pos == rot[1]) { + pos = rot[2]; + } else if (pos == rot[2]) { + pos = rot[0]; + } else if (pos == rot[3]) { + pos = rot[1]; + } + } + + slot.meta = pos + others; + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockSign.java b/common/buildcraft/api/bptblocks/BptBlockSign.java new file mode 100644 index 00000000..f7bd1338 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockSign.java @@ -0,0 +1,64 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BlockSignature; +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockSign extends BptBlock { + + boolean isWall; + + public BptBlockSign(int blockId, boolean isWall) { + super(blockId); + + this.isWall = isWall; + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(Item.sign)); + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + if (!isWall) { + double angle = ((slot.meta) * 360.0) / 16.0; + angle += 90.0; + if (angle >= 360) { + angle -= 360; + } + slot.meta = (int) (angle / 360.0 * 16.0); + } else { + // slot.meta = ForgeDirection.values()[slot.meta].rotateLeft().ordinal(); + } + } + + @Override + public BlockSignature getSignature(Block block) { + BlockSignature sig = super.getSignature(block); + + if (isWall) { + sig.customField = "wall"; + } else { + sig.customField = "floor"; + } + + return sig; + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockStairs.java b/common/buildcraft/api/bptblocks/BptBlockStairs.java new file mode 100644 index 00000000..4dc061a4 --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockStairs.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockStairs extends BptBlock { + + public BptBlockStairs(int blockId) { + super(blockId); + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(slot.blockId, 1, 0)); + } + + @Override + public boolean isValid(BptSlotInfo slot, IBptContext context) { + return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z); + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + switch (slot.meta) { + case 0: + slot.meta = 2; + break; + case 1: + slot.meta = 3; + break; + case 2: + slot.meta = 1; + break; + case 3: + slot.meta = 0; + break; + } + } + +} diff --git a/common/buildcraft/api/bptblocks/BptBlockWallSide.java b/common/buildcraft/api/bptblocks/BptBlockWallSide.java new file mode 100644 index 00000000..74ff3f0f --- /dev/null +++ b/common/buildcraft/api/bptblocks/BptBlockWallSide.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.bptblocks; + +import buildcraft.api.blueprints.BptBlock; +import buildcraft.api.blueprints.BptSlotInfo; +import buildcraft.api.blueprints.IBptContext; +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +@Deprecated +public class BptBlockWallSide extends BptBlock { + + public BptBlockWallSide(int blockId) { + super(blockId); + } + + @Override + public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) { + requirements.add(new ItemStack(slot.blockId, 1, 0)); + } + + @Override + public void rotateLeft(BptSlotInfo slot, IBptContext context) { + final int XPos = 2; + final int XNeg = 1; + final int ZPos = 4; + final int ZNeg = 3; + + switch (slot.meta) { + case XPos: + slot.meta = ZPos; + break; + case ZNeg: + slot.meta = XPos; + break; + case XNeg: + slot.meta = ZNeg; + break; + case ZPos: + slot.meta = XNeg; + break; + } + } +} diff --git a/common/buildcraft/api/core/BuildCraftAPI.java b/common/buildcraft/api/core/BuildCraftAPI.java new file mode 100644 index 00000000..87c45fdf --- /dev/null +++ b/common/buildcraft/api/core/BuildCraftAPI.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.core; + +import net.minecraft.block.Block; + +public class BuildCraftAPI { + + public static final int LAST_ORIGINAL_BLOCK = 122; + public static final int LAST_ORIGINAL_ITEM = 126; + + public static final boolean[] softBlocks = new boolean[Block.blocksList.length]; +} diff --git a/common/buildcraft/api/core/IAreaProvider.java b/common/buildcraft/api/core/IAreaProvider.java new file mode 100644 index 00000000..fa905d2c --- /dev/null +++ b/common/buildcraft/api/core/IAreaProvider.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.core; + +/** + * To be implemented by TileEntities able to provide a square area on the world, typically BuildCraft markers. + */ +public interface IAreaProvider { + + public int xMin(); + + public int yMin(); + + public int zMin(); + + public int xMax(); + + public int yMax(); + + public int zMax(); + + /** + * Remove from the world all objects used to define the area. + */ + public void removeFromWorld(); + +} diff --git a/common/buildcraft/api/core/IBox.java b/common/buildcraft/api/core/IBox.java new file mode 100644 index 00000000..6337a96c --- /dev/null +++ b/common/buildcraft/api/core/IBox.java @@ -0,0 +1,30 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.core; + +import net.minecraft.world.World; + +public interface IBox { + + public void expand(int amount); + + public void contract(int amount); + + public boolean contains(int x, int y, int z); + + public Position pMin(); + + public Position pMax(); + + public void createLasers(World world, LaserKind kind); + + public void deleteLasers(); + +} diff --git a/common/buildcraft/api/core/IIconProvider.java b/common/buildcraft/api/core/IIconProvider.java new file mode 100644 index 00000000..666d32e3 --- /dev/null +++ b/common/buildcraft/api/core/IIconProvider.java @@ -0,0 +1,24 @@ +package buildcraft.api.core; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.util.Icon; + +public interface IIconProvider { + + /** + * @param iconIndex + * @return + */ + @SideOnly(Side.CLIENT) + public Icon getIcon(int iconIndex); + + /** + * A call for the provider to register its Icons. This may be called multiple times but should only be executed once per provider + * @param iconRegister + */ + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister iconRegister); + +} diff --git a/common/buildcraft/api/core/LaserKind.java b/common/buildcraft/api/core/LaserKind.java new file mode 100644 index 00000000..24e66dba --- /dev/null +++ b/common/buildcraft/api/core/LaserKind.java @@ -0,0 +1,14 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.core; + +public enum LaserKind { + Red, Blue, Stripes +} diff --git a/common/buildcraft/api/core/Position.java b/common/buildcraft/api/core/Position.java new file mode 100644 index 00000000..5cdddbc8 --- /dev/null +++ b/common/buildcraft/api/core/Position.java @@ -0,0 +1,142 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.core; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.ForgeDirection; + +public class Position { + + public double x, y, z; + public ForgeDirection orientation; + + public Position(double ci, double cj, double ck) { + x = ci; + y = cj; + z = ck; + orientation = ForgeDirection.UNKNOWN; + } + + public Position(double ci, double cj, double ck, ForgeDirection corientation) { + x = ci; + y = cj; + z = ck; + orientation = corientation; + } + + public Position(Position p) { + x = p.x; + y = p.y; + z = p.z; + orientation = p.orientation; + } + + public Position(NBTTagCompound nbttagcompound) { + x = nbttagcompound.getDouble("i"); + y = nbttagcompound.getDouble("j"); + z = nbttagcompound.getDouble("k"); + + orientation = ForgeDirection.UNKNOWN; + } + + public Position(TileEntity tile) { + x = tile.xCoord; + y = tile.yCoord; + z = tile.zCoord; + } + + public void moveRight(double step) { + switch (orientation) { + case SOUTH: + x = x - step; + break; + case NORTH: + x = x + step; + break; + case EAST: + z = z + step; + break; + case WEST: + z = z - step; + break; + default: + } + } + + public void moveLeft(double step) { + moveRight(-step); + } + + public void moveForwards(double step) { + switch (orientation) { + case UP: + y = y + step; + break; + case DOWN: + y = y - step; + break; + case SOUTH: + z = z + step; + break; + case NORTH: + z = z - step; + break; + case EAST: + x = x + step; + break; + case WEST: + x = x - step; + break; + default: + } + } + + public void moveBackwards(double step) { + moveForwards(-step); + } + + public void moveUp(double step) { + switch (orientation) { + case SOUTH: + case NORTH: + case EAST: + case WEST: + y = y + step; + break; + default: + } + + } + + public void moveDown(double step) { + moveUp(-step); + } + + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setDouble("i", x); + nbttagcompound.setDouble("j", y); + nbttagcompound.setDouble("k", z); + } + + @Override + public String toString() { + return "{" + x + ", " + y + ", " + z + "}"; + } + + public Position min(Position p) { + return new Position(p.x > x ? x : p.x, p.y > y ? y : p.y, p.z > z ? z : p.z); + } + + public Position max(Position p) { + return new Position(p.x < x ? x : p.x, p.y < y ? y : p.y, p.z < z ? z : p.z); + } + +} diff --git a/common/buildcraft/api/core/SafeTimeTracker.java b/common/buildcraft/api/core/SafeTimeTracker.java new file mode 100644 index 00000000..44e1531e --- /dev/null +++ b/common/buildcraft/api/core/SafeTimeTracker.java @@ -0,0 +1,46 @@ +/** + * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public License + * 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.core; + +import net.minecraft.world.World; + +public class SafeTimeTracker { + + private long lastMark = Long.MIN_VALUE; + private long duration = -1; + + /** + * Return true if a given delay has passed since last time marked was called + * successfully. + */ + public boolean markTimeIfDelay(World world, long delay) { + if (world == null) + return false; + + long currentTime = world.getTotalWorldTime(); + + if (currentTime < lastMark) { + lastMark = currentTime; + return false; + } else if (lastMark + delay <= currentTime) { + duration = currentTime - lastMark; + lastMark = currentTime; + return true; + } else + return false; + + } + + public long durationOfLastDelay() { + return duration > 0 ? duration : 0; + } + + public void markTime(World world) { + lastMark = world.getTotalWorldTime(); + } +} diff --git a/common/buildcraft/api/core/StackWrapper.java b/common/buildcraft/api/core/StackWrapper.java new file mode 100644 index 00000000..f46652c4 --- /dev/null +++ b/common/buildcraft/api/core/StackWrapper.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) SpaceToad, 2011-2012 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.core; + +import net.minecraft.item.ItemStack; + +/** + * + * @author CovertJaguar + */ +public class StackWrapper { + + public final ItemStack stack; + + public StackWrapper(ItemStack stack) { + this.stack = stack; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 67 * hash + stack.itemID; + hash = 67 * hash + stack.getItemDamage(); + if (stack.stackTagCompound != null) + hash = 67 * hash + stack.stackTagCompound.hashCode(); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final StackWrapper other = (StackWrapper) obj; + if (stack.itemID != other.stack.itemID) + return false; + if (stack.getHasSubtypes() && stack.getItemDamage() != other.stack.getItemDamage()) + return false; + if (stack.stackTagCompound != null && !stack.stackTagCompound.equals(other.stack.stackTagCompound)) + return false; + return true; + } +} diff --git a/common/buildcraft/api/filler/FillerManager.java b/common/buildcraft/api/filler/FillerManager.java new file mode 100644 index 00000000..ae104c59 --- /dev/null +++ b/common/buildcraft/api/filler/FillerManager.java @@ -0,0 +1,7 @@ +package buildcraft.api.filler; + +public class FillerManager { + + public static IFillerRegistry registry; + +} diff --git a/common/buildcraft/api/filler/IFillerPattern.java b/common/buildcraft/api/filler/IFillerPattern.java new file mode 100644 index 00000000..dd5862bb --- /dev/null +++ b/common/buildcraft/api/filler/IFillerPattern.java @@ -0,0 +1,23 @@ +package buildcraft.api.filler; + +import buildcraft.api.core.IBox; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; + +public interface IFillerPattern { + + public int getId(); + + public void setId(int id); + + public boolean iteratePattern(TileEntity tile, IBox box, ItemStack stackToPlace); + + @SideOnly(Side.CLIENT) + public Icon getTexture(); + + public String getName(); + +} diff --git a/common/buildcraft/api/filler/IFillerRegistry.java b/common/buildcraft/api/filler/IFillerRegistry.java new file mode 100644 index 00000000..12bf9799 --- /dev/null +++ b/common/buildcraft/api/filler/IFillerRegistry.java @@ -0,0 +1,15 @@ +package buildcraft.api.filler; + +import net.minecraft.inventory.IInventory; + +public interface IFillerRegistry { + + public void addRecipe(IFillerPattern pattern, Object aobj[]); + + public IFillerPattern findMatchingRecipe(IInventory inventorycrafting); + + public int getPatternNumber(IFillerPattern pattern); + + public IFillerPattern getPattern(int n); + +} diff --git a/common/buildcraft/api/fuels/IronEngineCoolant.java b/common/buildcraft/api/fuels/IronEngineCoolant.java new file mode 100644 index 00000000..347fabd7 --- /dev/null +++ b/common/buildcraft/api/fuels/IronEngineCoolant.java @@ -0,0 +1,83 @@ +/** + * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public License + * 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.fuels; + +import buildcraft.api.core.StackWrapper; +import java.util.HashMap; +import java.util.Map; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +public final class IronEngineCoolant { + + public static Map liquidCoolants = new HashMap(); + public static Map solidCoolants = new HashMap(); + + public static FluidStack getFluidCoolant(ItemStack stack) { + return solidCoolants.get(new StackWrapper(stack)); + } + + public static Coolant getCoolant(ItemStack stack) { + return getCoolant(getFluidCoolant(stack)); + } + + public static Coolant getCoolant(FluidStack fluidStack) { + return fluidStack != null ? liquidCoolants.get(fluidStack.getFluid().getName()) : null; + } + + private IronEngineCoolant() { + } + + public static interface Coolant { + + float getDegreesCoolingPerMB(float currentHeat); + } + + public static void addCoolant(final Fluid fluid, final float degreesCoolingPerMB) { + if (fluid != null) { + liquidCoolants.put(fluid.getName(), new Coolant() { + @Override + public float getDegreesCoolingPerMB(float currentHeat) { + return degreesCoolingPerMB; + } + }); + } + } + + /** + * Adds a solid coolant like Ice Blocks. The FluidStack must contain a registered + * Coolant Fluid or nothing will happen. You do not need to call this for + * Fluid Containers. + * + * @param stack + * @param coolant + */ + public static void addCoolant(final ItemStack stack, final FluidStack coolant) { + if (stack != null && Item.itemsList[stack.itemID] != null && coolant != null) { + solidCoolants.put(new StackWrapper(stack), coolant); + } + } + + /** + * Adds a solid coolant like Ice Blocks. The FluidStack must contain a registered + * Coolant Fluid or nothing will happen. You do not need to call this for + * Fluid Containers. + * + * @param stack + * @param coolant + */ + public static void addCoolant(final int itemId, final int metadata, final FluidStack coolant) { + addCoolant(new ItemStack(itemId, 1, metadata), coolant); + } + + public static boolean isCoolant(Fluid fluid) { + return liquidCoolants.containsKey(fluid.getName()); + } +} diff --git a/common/buildcraft/api/fuels/IronEngineFuel.java b/common/buildcraft/api/fuels/IronEngineFuel.java new file mode 100644 index 00000000..3ab5ca2a --- /dev/null +++ b/common/buildcraft/api/fuels/IronEngineFuel.java @@ -0,0 +1,50 @@ +/** + * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public License + * 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.fuels; + +import java.util.HashMap; +import java.util.Map; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; + +public class IronEngineFuel { + + public static Map fuels = new HashMap(); + + public static Fuel getFuelForFluid(Fluid liquid) { + return liquid == null ? null : fuels.get(liquid.getName()); + } + + private IronEngineFuel() { + } + + public static class Fuel { + + public final Fluid liquid; + public final float powerPerCycle; + public final int totalBurningTime; + + private Fuel(String fluidName, float powerPerCycle, int totalBurningTime) { + this(FluidRegistry.getFluid(fluidName), powerPerCycle, totalBurningTime); + } + + private Fuel(Fluid liquid, float powerPerCycle, int totalBurningTime) { + this.liquid = liquid; + this.powerPerCycle = powerPerCycle; + this.totalBurningTime = totalBurningTime; + } + } + + public static void addFuel(Fluid fluid, float powerPerCycle, int totalBurningTime) { + fuels.put(fluid.getName(), new Fuel(fluid, powerPerCycle, totalBurningTime)); + } + + public static void addFuel(String fluidName, float powerPerCycle, int totalBurningTime) { + fuels.put(fluidName, new Fuel(fluidName, powerPerCycle, totalBurningTime)); + } +} diff --git a/common/buildcraft/api/gates/ActionManager.java b/common/buildcraft/api/gates/ActionManager.java new file mode 100644 index 00000000..26cfd2c7 --- /dev/null +++ b/common/buildcraft/api/gates/ActionManager.java @@ -0,0 +1,106 @@ +package buildcraft.api.gates; + +import buildcraft.api.transport.IPipe; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import net.minecraft.block.Block; +import net.minecraft.tileentity.TileEntity; + +public class ActionManager { + + public static Map triggers = new HashMap(); + public static Map actions = new HashMap(); + private static LinkedList triggerProviders = new LinkedList(); + private static LinkedList actionProviders = new LinkedList(); + + public static void registerTriggerProvider(ITriggerProvider provider) { + if (provider != null && !triggerProviders.contains(provider)) { + triggerProviders.add(provider); + } + } + + public static void registerTrigger(ITrigger trigger){ + triggers.put(trigger.getUniqueTag(), trigger); + } + + public static void registerAction(IAction action){ + actions.put(action.getUniqueTag(), action); + } + + public static LinkedList getNeighborTriggers(Block block, TileEntity entity) { + LinkedList triggers = new LinkedList(); + + for (ITriggerProvider provider : triggerProviders) { + LinkedList toAdd = provider.getNeighborTriggers(block, entity); + + if (toAdd != null) { + for (ITrigger t : toAdd) { + if (!triggers.contains(t)) { + triggers.add(t); + } + } + } + } + + return triggers; + } + + public static void registerActionProvider(IActionProvider provider) { + if (provider != null && !actionProviders.contains(provider)) { + actionProviders.add(provider); + } + } + + public static LinkedList getNeighborActions(Block block, TileEntity entity) { + LinkedList actions = new LinkedList(); + + for (IActionProvider provider : actionProviders) { + LinkedList toAdd = provider.getNeighborActions(block, entity); + + if (toAdd != null) { + for (IAction t : toAdd) { + if (!actions.contains(t)) { + actions.add(t); + } + } + } + } + + return actions; + } + + public static LinkedList getPipeTriggers(IPipe pipe) { + LinkedList triggers = new LinkedList(); + + for (ITriggerProvider provider : triggerProviders) { + LinkedList toAdd = provider.getPipeTriggers(pipe); + + if (toAdd != null) { + for (ITrigger t : toAdd) { + if (!triggers.contains(t)) { + triggers.add(t); + } + } + } + } + + return triggers; + } + + public static ITrigger getTriggerFromLegacyId(int legacyId){ + for(ITrigger trigger : triggers.values()){ + if(trigger.getLegacyId() == legacyId) + return trigger; + } + return null; + } + + public static IAction getActionFromLegacyId(int legacyId){ + for(IAction action : actions.values()){ + if(action.getLegacyId() == legacyId) + return action; + } + return null; + } +} diff --git a/common/buildcraft/api/gates/IAction.java b/common/buildcraft/api/gates/IAction.java new file mode 100644 index 00000000..90547d58 --- /dev/null +++ b/common/buildcraft/api/gates/IAction.java @@ -0,0 +1,27 @@ +package buildcraft.api.gates; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.util.Icon; + +public interface IAction { + + /** + * Return your ID from the old API here, this is only used to convert old + * saves to the new format. + */ + int getLegacyId(); + + String getUniqueTag(); + + @SideOnly(Side.CLIENT) + Icon getIcon(); + + @SideOnly(Side.CLIENT) + void registerIcons(IconRegister iconRegister); + + boolean hasParameter(); + + String getDescription(); +} diff --git a/common/buildcraft/api/gates/IActionProvider.java b/common/buildcraft/api/gates/IActionProvider.java new file mode 100644 index 00000000..6c64b57e --- /dev/null +++ b/common/buildcraft/api/gates/IActionProvider.java @@ -0,0 +1,23 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.gates; + +import java.util.LinkedList; +import net.minecraft.block.Block; +import net.minecraft.tileentity.TileEntity; + +public interface IActionProvider { + + /** + * Returns the list of actions available to a gate next to the given block. + */ + public abstract LinkedList getNeighborActions(Block block, TileEntity tile); + +} diff --git a/common/buildcraft/api/gates/IActionReceptor.java b/common/buildcraft/api/gates/IActionReceptor.java new file mode 100644 index 00000000..c4637adc --- /dev/null +++ b/common/buildcraft/api/gates/IActionReceptor.java @@ -0,0 +1,16 @@ +/** + * Copyright (c) SpaceToad, 2012 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.gates; + +public interface IActionReceptor { + + public void actionActivated(IAction action); + +} diff --git a/common/buildcraft/api/gates/IOverrideDefaultTriggers.java b/common/buildcraft/api/gates/IOverrideDefaultTriggers.java new file mode 100644 index 00000000..8a2e47c6 --- /dev/null +++ b/common/buildcraft/api/gates/IOverrideDefaultTriggers.java @@ -0,0 +1,21 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.gates; + +import java.util.LinkedList; + +/** + * This interface has to be implemented by a TileEntity or a Pipe that wants to provide triggers different from the ones installed by default with BuildCraft. + */ +public interface IOverrideDefaultTriggers { + + LinkedList getTriggers(); + +} diff --git a/common/buildcraft/api/gates/ITrigger.java b/common/buildcraft/api/gates/ITrigger.java new file mode 100644 index 00000000..ab59616b --- /dev/null +++ b/common/buildcraft/api/gates/ITrigger.java @@ -0,0 +1,47 @@ +package buildcraft.api.gates; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraftforge.common.ForgeDirection; + +public interface ITrigger { + + /** + * Return your ID from the old API here, this is only used to convert old + * saves to the new format. + */ + int getLegacyId(); + + String getUniqueTag(); + + @SideOnly(Side.CLIENT) + Icon getIcon(); + + @SideOnly(Side.CLIENT) + void registerIcons(IconRegister iconRegister); + + /** + * Return true if this trigger can accept parameters + */ + boolean hasParameter(); + + /** + * Return the trigger description in the UI + */ + String getDescription(); + + /** + * Return true if the tile given in parameter activates the trigger, given + * the parameters. + */ + boolean isTriggerActive(ForgeDirection side, TileEntity tile, ITriggerParameter parameter); + + /** + * Create parameters for the trigger. As for now, there is only one kind of + * trigger parameter available so this subprogram is final. + */ + ITriggerParameter createParameter(); +} diff --git a/common/buildcraft/api/gates/ITriggerParameter.java b/common/buildcraft/api/gates/ITriggerParameter.java new file mode 100644 index 00000000..cef436a6 --- /dev/null +++ b/common/buildcraft/api/gates/ITriggerParameter.java @@ -0,0 +1,18 @@ +package buildcraft.api.gates; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public interface ITriggerParameter { + + public abstract ItemStack getItemStack(); + + public abstract void set(ItemStack stack); + + public abstract void writeToNBT(NBTTagCompound compound); + + public abstract void readFromNBT(NBTTagCompound compound); + + public abstract ItemStack getItem(); + +} diff --git a/common/buildcraft/api/gates/ITriggerProvider.java b/common/buildcraft/api/gates/ITriggerProvider.java new file mode 100644 index 00000000..fe2271e0 --- /dev/null +++ b/common/buildcraft/api/gates/ITriggerProvider.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.gates; + +import buildcraft.api.transport.IPipe; +import java.util.LinkedList; +import net.minecraft.block.Block; +import net.minecraft.tileentity.TileEntity; + +public interface ITriggerProvider { + + /** + * Returns the list of triggers that are available from the pipe holding the gate. + */ + public abstract LinkedList getPipeTriggers(IPipe pipe); + + /** + * Returns the list of triggers available to a gate next to the given block. + */ + public abstract LinkedList getNeighborTriggers(Block block, TileEntity tile); + +} diff --git a/common/buildcraft/api/gates/TriggerParameter.java b/common/buildcraft/api/gates/TriggerParameter.java new file mode 100644 index 00000000..c76ce99a --- /dev/null +++ b/common/buildcraft/api/gates/TriggerParameter.java @@ -0,0 +1,79 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.gates; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public class TriggerParameter implements ITriggerParameter { + + protected ItemStack stack; + + /* + * (non-Javadoc) + * + * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#getItemStack() + */ + @Override + public ItemStack getItemStack() { + return stack; + } + + /* + * (non-Javadoc) + * + * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#set(net.minecraft.src.ItemStack) + */ + @Override + public void set(ItemStack stack) { + if (stack != null) { + this.stack = stack.copy(); + this.stack.stackSize = 1; + } + } + + /* + * (non-Javadoc) + * + * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#writeToNBT(net.minecraft.src.NBTTagCompound) + */ + @Override + public void writeToNBT(NBTTagCompound compound) { + if (stack != null) { + compound.setInteger("itemID", stack.itemID); + compound.setInteger("itemDMG", stack.getItemDamage()); + } + } + + /* + * (non-Javadoc) + * + * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#readFromNBT(net.minecraft.src.NBTTagCompound) + */ + @Override + public void readFromNBT(NBTTagCompound compound) { + int itemID = compound.getInteger("itemID"); + + if (itemID != 0) { + stack = new ItemStack(itemID, 1, compound.getInteger("itemDMG")); + } + } + + /* + * (non-Javadoc) + * + * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#getItem() + */ + @Override + public ItemStack getItem() { + return stack; + } + +} diff --git a/common/buildcraft/api/inventory/ISecuredInventory.java b/common/buildcraft/api/inventory/ISecuredInventory.java new file mode 100644 index 00000000..6ebb99b6 --- /dev/null +++ b/common/buildcraft/api/inventory/ISecuredInventory.java @@ -0,0 +1,23 @@ +package buildcraft.api.inventory; + +import net.minecraftforge.common.ForgeDirection; + +public interface ISecuredInventory { + + /** + * @param name + * @return true if the user/player with the given name has access permissions on this machine. + */ + boolean canAccess(String name); + + /** + * Informs the inventory with whose permissions the next item or liquid transaction will be performed. It is up to the inventory to determine the effect. + * + * @param orientation + * Orientation the transaction will be performed from. + * @param name + * Name of the user/player who owns the transaction. + */ + void prepareTransaction(ForgeDirection orientation, String name); + +} diff --git a/common/buildcraft/api/inventory/ISelectiveInventory.java b/common/buildcraft/api/inventory/ISelectiveInventory.java new file mode 100644 index 00000000..0e4d7045 --- /dev/null +++ b/common/buildcraft/api/inventory/ISelectiveInventory.java @@ -0,0 +1,23 @@ +package buildcraft.api.inventory; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.ForgeDirection; + +public interface ISelectiveInventory extends ISpecialInventory { + /** + * Requests specified items to be extracted from the inventory + * + * @param desired + * Array which can contain ItemStacks, Items, or classes describing the type of item accepted or excluded. + * @param exclusion + * If true desired items are not eligible for returning. + * @param doRemove + * If false no actual extraction may occur. + * @param from + * Orientation the ItemStack is requested from. + * @param maxItemCount + * Maximum amount of items to extract (spread over all returned item stacks) + * @return Array of item stacks extracted from the inventory + */ + ItemStack[] extractItem(Object[] desired, boolean exclusion, boolean doRemove, ForgeDirection from, int maxItemCount); +} diff --git a/common/buildcraft/api/inventory/ISpecialInventory.java b/common/buildcraft/api/inventory/ISpecialInventory.java new file mode 100644 index 00000000..27b735d4 --- /dev/null +++ b/common/buildcraft/api/inventory/ISpecialInventory.java @@ -0,0 +1,36 @@ +package buildcraft.api.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.ForgeDirection; + +public interface ISpecialInventory extends IInventory { + + /** + * Offers an ItemStack for addition to the inventory. + * + * @param stack + * ItemStack offered for addition. Do not manipulate this! + * @param doAdd + * If false no actual addition should take place. Implementors should simulate. + * @param from + * Orientation the ItemStack is offered from. + * @return Amount of items used from the passed stack. + */ + int addItem(ItemStack stack, boolean doAdd, ForgeDirection from); + + /** + * Requests items to be extracted from the inventory + * + * @param doRemove + * If false no actual extraction may occur. Implementors should simulate. + * Can be used to "peek" at what the result would be + * @param from + * Orientation the ItemStack is requested from. + * @param maxItemCount + * Maximum amount of items to extract (spread over all returned item stacks) + * @return Array of item stacks that were/would be extracted from the inventory + */ + ItemStack[] extractItem(boolean doRemove, ForgeDirection from, int maxItemCount); + +} diff --git a/common/buildcraft/api/power/IPowerEmitter.java b/common/buildcraft/api/power/IPowerEmitter.java new file mode 100644 index 00000000..7ccf62b9 --- /dev/null +++ b/common/buildcraft/api/power/IPowerEmitter.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) SpaceToad, 2011-2012 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.power; + +import net.minecraftforge.common.ForgeDirection; + +/** + * Essentially only used for Wooden Power Pipe connection rules. + * + * This Tile Entity interface allows you to indicate that a block can emit power + * from a specific side. + * + * @author CovertJaguar + */ +public interface IPowerEmitter { + + public boolean canEmitPowerFrom(ForgeDirection side); +} diff --git a/common/buildcraft/api/power/IPowerReceptor.java b/common/buildcraft/api/power/IPowerReceptor.java new file mode 100644 index 00000000..a7f6c421 --- /dev/null +++ b/common/buildcraft/api/power/IPowerReceptor.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public License + * 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.power; + +import buildcraft.api.power.PowerHandler.PowerReceiver; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; + +/** + * This interface should be implemented by any Tile Entity that wishes to be + * able to receive power. + * + * @author CovertJaguar + */ +public interface IPowerReceptor { + + /** + * Get the PowerReceiver for this side of the block. You can return the same + * PowerReceiver for all sides or one for each side. + * + * You should NOT return null to this method unless you mean to NEVER + * receive power from that side. Returning null, after previous returning a + * PowerReceiver, will most likely cause pipe connections to derp out and + * engines to eventually explode. + * + * @param side + * @return + */ + public PowerReceiver getPowerReceiver(ForgeDirection side); + + /** + * Call back from the PowerHandler that is called when the stored power + * exceeds the activation power. + * + * It can be triggered by update() calls or power modification calls. + * + * @param workProvider + */ + public void doWork(PowerHandler workProvider); + + public World getWorld(); +} diff --git a/common/buildcraft/api/power/PowerHandler.java b/common/buildcraft/api/power/PowerHandler.java new file mode 100644 index 00000000..0751065b --- /dev/null +++ b/common/buildcraft/api/power/PowerHandler.java @@ -0,0 +1,389 @@ +/** + * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public License + * 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.power; + +import buildcraft.api.core.SafeTimeTracker; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.ForgeDirection; + +public final class PowerHandler { + + public static enum Type { + + ENGINE, GATE, MACHINE, PIPE, STORAGE; + + public boolean canReceiveFromPipes() { + switch (this) { + case MACHINE: + case STORAGE: + return true; + default: + return false; + } + } + + public boolean eatsEngineExcess() { + switch (this) { + case MACHINE: + case STORAGE: + return true; + default: + return false; + } + } + } + + public static class PerditionCalculator { + + public static final float DEFAULT_POWERLOSS = 1F; + public static final float MIN_POWERLOSS = 0.01F; + private final float powerLoss; + + public PerditionCalculator() { + powerLoss = DEFAULT_POWERLOSS; + } + + public PerditionCalculator(float powerLoss) { + if (powerLoss < MIN_POWERLOSS) { + powerLoss = MIN_POWERLOSS; + } + this.powerLoss = powerLoss; + } + + /** + * Apply the perdition algorithm to the current stored energy. This + * function can only be called once per tick, but it might not be called + * every tick. It is triggered by any manipulation of the stored energy. + * + * @param powerHandler the PowerHandler requesting the perdition update + * @param current the current stored energy + * @param ticksPassed ticks since the last time this function was called + * @return + */ + public float applyPerdition(PowerHandler powerHandler, float current, long ticksPassed) { + current -= powerLoss * ticksPassed; + if (current < 0) { + current = 0; + } + return current; + } + } + public static final PerditionCalculator DEFAULT_PERDITION = new PerditionCalculator(); + private float minEnergyReceived; + private float maxEnergyReceived; + private float maxEnergyStored; + private float activationEnergy; + private float energyStored = 0; + private final SafeTimeTracker doWorkTracker = new SafeTimeTracker(); + private final SafeTimeTracker sourcesTracker = new SafeTimeTracker(); + private final SafeTimeTracker perditionTracker = new SafeTimeTracker(); + public final int[] powerSources = new int[6]; + public final IPowerReceptor receptor; + private PerditionCalculator perdition; + private final PowerReceiver receiver; + private final Type type; + + public PowerHandler(IPowerReceptor receptor, Type type) { + this.receptor = receptor; + this.type = type; + this.receiver = new PowerReceiver(); + this.perdition = DEFAULT_PERDITION; + } + + public PowerReceiver getPowerReceiver() { + return receiver; + } + + public float getMinEnergyReceived() { + return minEnergyReceived; + } + + public float getMaxEnergyReceived() { + return maxEnergyReceived; + } + + public float getMaxEnergyStored() { + return maxEnergyStored; + } + + public float getActivationEnergy() { + return activationEnergy; + } + + public float getEnergyStored() { + return energyStored; + } + + /** + * Setup your PowerHandler's settings. + * + * @param minEnergyReceived This is the minimum about of power that will be + * accepted by the PowerHandler. This should generally be greater than the + * activationEnergy if you plan to use the doWork() callback. Anything + * greater than 1 will prevent Redstone Engines from powering this Provider. + * @param maxEnergyReceived The maximum amount of power accepted by the + * PowerHandler. This should generally be less than 500. Too low and larger + * engines will overheat while trying to power the machine. Too high, and + * the engines will never warm up. Greater values also place greater strain + * on the power net. + * @param activationEnergy If the stored energy is greater than this value, + * the doWork() callback is called (once per tick). + * @param maxStoredEnergy The maximum amount of power this PowerHandler can + * store. Values tend to range between 100 and 5000. With 1000 and 1500 + * being common. + */ + public void configure(float minEnergyReceived, float maxEnergyReceived, float activationEnergy, float maxStoredEnergy) { + if (minEnergyReceived > maxEnergyReceived) { + maxEnergyReceived = minEnergyReceived; + } + this.minEnergyReceived = minEnergyReceived; + this.maxEnergyReceived = maxEnergyReceived; + this.maxEnergyStored = maxStoredEnergy; + this.activationEnergy = activationEnergy; + } + + public void configurePowerPerdition(int powerLoss, int powerLossRegularity) { + if (powerLoss == 0 || powerLossRegularity == 0) { + perdition = new PerditionCalculator(0); + return; + } + perdition = new PerditionCalculator((float) powerLoss / (float) powerLossRegularity); + } + + /** + * Allows you to define a new PerditionCalculator class to handler perdition + * calculations. + * + * For example if you want exponentially increasing loss based on amount + * stored. + * + * @param perdition + */ + public void setPerdition(PerditionCalculator perdition) { + if (perdition == null) + perdition = DEFAULT_PERDITION; + this.perdition = perdition; + } + + public PerditionCalculator getPerdition() { + if (perdition == null) + return DEFAULT_PERDITION; + return perdition; + } + + /** + * Ticks the power handler. You should call this if you can, but its not + * required. + * + * If you don't call it, the possibility exists for some weirdness with the + * perdition algorithm and work callback as its possible they will not be + * called on every tick they otherwise would be. You should be able to + * design around this though if you are aware of the limitations. + */ + public void update() { + applyPerdition(); + applyWork(); + validateEnergy(); + } + + private void applyPerdition() { + if (perditionTracker.markTimeIfDelay(receptor.getWorld(), 1) && energyStored > 0) { + float newEnergy = getPerdition().applyPerdition(this, energyStored, perditionTracker.durationOfLastDelay()); + if (newEnergy == 0 || newEnergy < energyStored) + energyStored = newEnergy; + else + energyStored = DEFAULT_PERDITION.applyPerdition(this, energyStored, perditionTracker.durationOfLastDelay()); + validateEnergy(); + } + } + + private void applyWork() { + if (energyStored >= activationEnergy) { + if (doWorkTracker.markTimeIfDelay(receptor.getWorld(), 1)) { + receptor.doWork(this); + } + } + } + + private void updateSources(ForgeDirection source) { + if (sourcesTracker.markTimeIfDelay(receptor.getWorld(), 1)) { + for (int i = 0; i < 6; ++i) { + powerSources[i] -= sourcesTracker.durationOfLastDelay(); + if (powerSources[i] < 0) { + powerSources[i] = 0; + } + } + } + + if (source != null) + powerSources[source.ordinal()] = 10; + } + + /** + * Extract energy from the PowerHandler. You must call this even if doWork() + * triggers. + * + * @param min + * @param max + * @param doUse + * @return amount used + */ + public float useEnergy(float min, float max, boolean doUse) { + applyPerdition(); + + float result = 0; + + if (energyStored >= min) { + if (energyStored <= max) { + result = energyStored; + if (doUse) { + energyStored = 0; + } + } else { + result = max; + if (doUse) { + energyStored -= max; + } + } + } + + validateEnergy(); + + return result; + } + + public void readFromNBT(NBTTagCompound data) { + readFromNBT(data, "powerProvider"); + } + + public void readFromNBT(NBTTagCompound data, String tag) { + NBTTagCompound nbt = data.getCompoundTag(tag); + energyStored = nbt.getFloat("storedEnergy"); + } + + public void writeToNBT(NBTTagCompound data) { + writeToNBT(data, "powerProvider"); + } + + public void writeToNBT(NBTTagCompound data, String tag) { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setFloat("storedEnergy", energyStored); + data.setCompoundTag(tag, nbt); + } + + public final class PowerReceiver { + + private PowerReceiver() { + } + + public float getMinEnergyReceived() { + return minEnergyReceived; + } + + public float getMaxEnergyReceived() { + return maxEnergyReceived; + } + + public float getMaxEnergyStored() { + return maxEnergyStored; + } + + public float getActivationEnergy() { + return activationEnergy; + } + + public float getEnergyStored() { + return energyStored; + } + + public Type getType() { + return type; + } + + public void update() { + PowerHandler.this.update(); + } + + /** + * The amount of power that this PowerHandler currently needs. + * + * @return + */ + public float powerRequest() { + return Math.min(maxEnergyReceived, maxEnergyStored - energyStored); + } + + /** + * Add power to the PowerReceiver from an external source. + * + * @param quantity + * @param from + * @return the amount of power used + */ + public float receiveEnergy(Type source, final float quantity, ForgeDirection from) { + float used = quantity; + if (source == Type.ENGINE) { + if (used < minEnergyReceived) { + return 0; + } else if (used > maxEnergyReceived) { + used = maxEnergyReceived; + } + } + + updateSources(from); + + used = addEnergy(used); + + applyWork(); + + if (source == Type.ENGINE && type.eatsEngineExcess()) { + return Math.min(quantity, maxEnergyReceived); + } + + return used; + } + } + + /** + * + * @return the amount the power changed by + */ + public float addEnergy(float quantity) { + energyStored += quantity; + + if (energyStored > maxEnergyStored) { + quantity -= energyStored - maxEnergyStored; + energyStored = maxEnergyStored; + } else if (energyStored < 0) { + quantity -= energyStored; + energyStored = 0; + } + + applyPerdition(); + + return quantity; + } + + public void setEnergy(float quantity) { + this.energyStored = quantity; + validateEnergy(); + } + + public boolean isPowerSource(ForgeDirection from) { + return powerSources[from.ordinal()] != 0; + } + + private void validateEnergy() { + if (energyStored < 0) { + energyStored = 0; + } + if (energyStored > maxEnergyStored) { + energyStored = maxEnergyStored; + } + } +} diff --git a/common/buildcraft/api/recipes/AssemblyRecipe.java b/common/buildcraft/api/recipes/AssemblyRecipe.java new file mode 100644 index 00000000..573db282 --- /dev/null +++ b/common/buildcraft/api/recipes/AssemblyRecipe.java @@ -0,0 +1,48 @@ +package buildcraft.api.recipes; + +import java.util.LinkedList; +import net.minecraft.item.ItemStack; + +public class AssemblyRecipe { + + public static LinkedList assemblyRecipes = new LinkedList(); + + public final ItemStack[] input; + public final ItemStack output; + public final float energy; + + public AssemblyRecipe(ItemStack[] input, int energy, ItemStack output) { + this.input = input; + this.output = output; + this.energy = energy; + } + + public boolean canBeDone(ItemStack[] items) { + + for (ItemStack in : input) { + + if (in == null) { + continue; + } + + int found = 0; // Amount of ingredient found in inventory + + for (ItemStack item : items) { + if (item == null) { + continue; + } + + if (item.isItemEqual(in)) { + found += item.stackSize; // Adds quantity of stack to amount + // found + } + } + + if (found < in.stackSize) + return false; // Return false if the amount of ingredient found + // is not enough + } + + return true; + } +} diff --git a/common/buildcraft/api/recipes/RefineryRecipes.java b/common/buildcraft/api/recipes/RefineryRecipes.java new file mode 100644 index 00000000..64985bf7 --- /dev/null +++ b/common/buildcraft/api/recipes/RefineryRecipes.java @@ -0,0 +1,126 @@ +/** + * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public License + * 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.recipes; + +import com.google.common.base.Objects; +import java.util.Collections; +import java.util.SortedSet; +import java.util.TreeSet; +import net.minecraftforge.fluids.FluidStack; + +public final class RefineryRecipes { + + private static SortedSet recipes = new TreeSet(); + + public static void addRecipe(FluidStack ingredient, FluidStack result, int energy, int delay) { + addRecipe(ingredient, null, result, energy, delay); + } + + public static void addRecipe(FluidStack ingredient1, FluidStack ingredient2, FluidStack result, int energy, int delay) { + Recipe recipe = new Recipe(ingredient1, ingredient2, result, energy, delay); + recipes.add(recipe); + } + + public static SortedSet getRecipes() { + return Collections.unmodifiableSortedSet(recipes); + } + + public static Recipe findRefineryRecipe(FluidStack liquid1, FluidStack liquid2) { + for (Recipe recipe : recipes) { + if (recipe.matches(liquid1, liquid2)) + return recipe; + } + + return null; + } + + private RefineryRecipes() { + } + + public static final class Recipe implements Comparable { + + public final FluidStack ingredient1; + public final FluidStack ingredient2; + public final FluidStack result; + public final int energy; + public final int delay; + + private Recipe(FluidStack ingredient1, FluidStack ingredient2, FluidStack result, int energy, int delay) { + if (ingredient1 == null) + throw new IllegalArgumentException("First Ingredient cannot be null!"); + this.ingredient1 = ingredient1; + this.ingredient2 = ingredient2; + this.result = result; + this.energy = energy; + this.delay = delay; + } + + public boolean matches(FluidStack liquid1, FluidStack liquid2) { + + // No inputs, return. + if (liquid1 == null && liquid2 == null) + return false; + + // Return if two ingredients are required but only one was supplied. + if ((ingredient1 != null && ingredient2 != null) && (liquid1 == null || liquid2 == null)) + return false; + + if (liquid1 != null && liquid2 != null) { + if (liquid1.containsFluid(ingredient1) && liquid1.containsFluid(ingredient2)) + return true; + if (liquid1.containsFluid(ingredient2) && liquid1.containsFluid(ingredient1)) + return true; + } + + if (liquid1 != null) + return liquid1.containsFluid(ingredient1) || liquid1.containsFluid(ingredient2); + + if (liquid2 != null) + return liquid2.containsFluid(ingredient1) || liquid2.containsFluid(ingredient2); + + return false; + } + + // Compares to only the types of source materials. + // We consider non-null < null in order that one-ingredient recipe is checked after + // the failure of matching two-ingredient recipes which include that liquid. + @Override + public int compareTo(Recipe other) { + if (other == null) + return -1; + else if (ingredient1.getFluid() != other.ingredient1.getFluid()) + return ingredient1.getFluid().getName().compareTo(other.ingredient1.getFluid().getName()); + else if (ingredient1.amount != other.ingredient1.amount) + return other.ingredient1.amount - ingredient1.amount; + else if (ingredient2 == null) + return other.ingredient2 == null ? 0 : 1; + else if (other.ingredient2 == null) + return -1; + else if (ingredient2.getFluid() != other.ingredient2.getFluid()) + return ingredient2.getFluid().getName().compareTo(other.ingredient2.getFluid().getName()); + else if (ingredient2.amount != other.ingredient2.amount) + return other.ingredient2.amount - ingredient2.amount; + + return 0; + } + + // equals() should be consistent with compareTo(). + @Override + public boolean equals(Object obj) { + return obj instanceof Recipe + && Objects.equal(ingredient1, ((Recipe) obj).ingredient1) + && Objects.equal(ingredient2, ((Recipe) obj).ingredient2); + } + + // hashCode() should be overridden because equals() was overridden. + @Override + public int hashCode() { + return Objects.hashCode(ingredient1, ingredient2); + } + } +} diff --git a/common/buildcraft/api/tools/IToolPipette.java b/common/buildcraft/api/tools/IToolPipette.java new file mode 100644 index 00000000..d636523d --- /dev/null +++ b/common/buildcraft/api/tools/IToolPipette.java @@ -0,0 +1,40 @@ +package buildcraft.api.tools; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public interface IToolPipette { + + /** + * @param pipette + * ItemStack of the pipette. + * @return Capacity of the pipette. + */ + int getCapacity(ItemStack pipette); + + /** + * @param pipette + * @return true if the pipette can pipette. + */ + boolean canPipette(ItemStack pipette); + + /** + * Fills the pipette with the given liquid stack. + * + * @param pipette + * @param liquid + * @param doFill + * @return Amount of liquid used in filling the pipette. + */ + int fill(ItemStack pipette, FluidStack liquid, boolean doFill); + + /** + * Drains liquid from the pipette + * + * @param pipette + * @param maxDrain + * @param doDrain + * @return Fluid stack representing the liquid and amount drained from the pipette. + */ + FluidStack drain(ItemStack pipette, int maxDrain, boolean doDrain); +} diff --git a/common/buildcraft/api/tools/IToolWrench.java b/common/buildcraft/api/tools/IToolWrench.java new file mode 100644 index 00000000..bd0c3c59 --- /dev/null +++ b/common/buildcraft/api/tools/IToolWrench.java @@ -0,0 +1,32 @@ +package buildcraft.api.tools; + +import net.minecraft.entity.player.EntityPlayer; + +/*** + * Implement this interface on subclasses of Item to have that item work as a wrench for buildcraft + */ +public interface IToolWrench { + + /*** + * Called to ensure that the wrench can be used. To get the ItemStack that is used, check player.inventory.getCurrentItem() + * + * @param player + * - The player doing the wrenching + * @param x + * ,y,z - The coordinates for the block being wrenched + * + * @return true if wrenching is allowed, false if not + */ + public boolean canWrench(EntityPlayer player, int x, int y, int z); + + /*** + * Callback after the wrench has been used. This can be used to decrease durability or for other purposes. To get the ItemStack that was used, check + * player.inventory.getCurrentItem() + * + * @param player + * - The player doing the wrenching + * @param x + * ,y,z - The coordinates of the block being wrenched + */ + public void wrenchUsed(EntityPlayer player, int x, int y, int z); +} diff --git a/common/buildcraft/api/transport/FacadeManager.java b/common/buildcraft/api/transport/FacadeManager.java new file mode 100644 index 00000000..28cbdd1a --- /dev/null +++ b/common/buildcraft/api/transport/FacadeManager.java @@ -0,0 +1,25 @@ +package buildcraft.api.transport; + +import java.lang.reflect.Method; +import net.minecraft.item.ItemStack; + +/** + * You can use this if you wish, but FML InterModComms are recommended. + * + * SYNTAX: add-facade:id@meta + */ +public class FacadeManager { + private static Method addFacade; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static void addFacade(ItemStack is) { + try { + if (addFacade == null) { + Class facade = Class.forName("buildcraft.transport.ItemFacade"); + addFacade = facade.getMethod("addFacade", ItemStack.class); + } + addFacade.invoke(null, is); + } catch (Exception ex) { + } + } +} diff --git a/common/buildcraft/api/transport/IExtractionHandler.java b/common/buildcraft/api/transport/IExtractionHandler.java new file mode 100644 index 00000000..e912f65b --- /dev/null +++ b/common/buildcraft/api/transport/IExtractionHandler.java @@ -0,0 +1,21 @@ +package buildcraft.api.transport; + +import net.minecraft.world.World; + +/** + * Implement and register with the PipeManager if you want to suppress connections from wooden pipes. + */ +public interface IExtractionHandler { + + /** + * Can this pipe extract items from the block located at these coordinates? + * param extractor can be null + */ + boolean canExtractItems(Object extractor, World world, int i, int j, int k); + + /** + * Can this pipe extract liquids from the block located at these coordinates? + * param extractor can be null + */ + boolean canExtractFluids(Object extractor, World world, int i, int j, int k); +} diff --git a/common/buildcraft/api/transport/IPipe.java b/common/buildcraft/api/transport/IPipe.java new file mode 100644 index 00000000..20096b76 --- /dev/null +++ b/common/buildcraft/api/transport/IPipe.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.transport; + +import net.minecraft.tileentity.TileEntity; + +public interface IPipe { + + enum DrawingState { + DrawingPipe, DrawingRedWire, DrawingBlueWire, DrawingGreenWire, DrawingYellowWire, DrawingGate + } + + enum WireColor { + Red, Blue, Green, Yellow; + + public WireColor reverse() { + switch (this) { + case Red: + return Yellow; + case Blue: + return Green; + case Green: + return Blue; + default: + return Red; + } + } + } + + public boolean isWired(WireColor color); + + public boolean hasGate(); + + public TileEntity getContainer(); + + public boolean isWireConnectedTo(TileEntity tile, WireColor color); + +} diff --git a/common/buildcraft/api/transport/IPipeConnection.java b/common/buildcraft/api/transport/IPipeConnection.java new file mode 100644 index 00000000..cbb1d003 --- /dev/null +++ b/common/buildcraft/api/transport/IPipeConnection.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public License + * 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.transport; + +import buildcraft.api.transport.IPipeTile.PipeType; +import net.minecraftforge.common.ForgeDirection; + +public interface IPipeConnection { + + enum ConnectOverride { + + CONNECT, DISCONNECT, DEFAULT + }; + + /** + * Allows you to override pipe connection logic. + * + * @param type + * @param with + * @return CONNECT to force a connection, DISCONNECT to force no connection, + * and DEFAULT to let the pipe decide. + */ + public ConnectOverride overridePipeConnection(PipeType type, ForgeDirection with); +} diff --git a/common/buildcraft/api/transport/IPipeTile.java b/common/buildcraft/api/transport/IPipeTile.java new file mode 100644 index 00000000..13aa8d76 --- /dev/null +++ b/common/buildcraft/api/transport/IPipeTile.java @@ -0,0 +1,39 @@ +/** + * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public License + * 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.transport; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.IFluidHandler; + +public interface IPipeTile extends ISolidSideTile, IFluidHandler { + + public enum PipeType { + + ITEM, FLUID, POWER, STRUCTURE; + } + + @Deprecated + IPipe getPipe(); + + PipeType getPipeType(); + + /** + * Offers an ItemStack for addition to the pipe. Will be rejected if the + * pipe doesn't accept items from that side. + * + * @param stack ItemStack offered for addition. Do not manipulate this! + * @param doAdd If false no actual addition should take place. Implementors + * should simulate. + * @param from Orientation the ItemStack is offered from. + * @return Amount of items used from the passed stack. + */ + int injectItem(ItemStack stack, boolean doAdd, ForgeDirection from); + + boolean isPipeConnected(ForgeDirection with); +} diff --git a/common/buildcraft/api/transport/ISolidSideTile.java b/common/buildcraft/api/transport/ISolidSideTile.java new file mode 100644 index 00000000..627b0d88 --- /dev/null +++ b/common/buildcraft/api/transport/ISolidSideTile.java @@ -0,0 +1,7 @@ +package buildcraft.api.transport; + +import net.minecraftforge.common.ForgeDirection; + +public interface ISolidSideTile { + public boolean isSolidOnSide(ForgeDirection side); +} diff --git a/common/buildcraft/api/transport/PipeManager.java b/common/buildcraft/api/transport/PipeManager.java new file mode 100644 index 00000000..c78c86e2 --- /dev/null +++ b/common/buildcraft/api/transport/PipeManager.java @@ -0,0 +1,36 @@ +package buildcraft.api.transport; + +import java.util.ArrayList; +import java.util.List; +import net.minecraft.world.World; + +public abstract class PipeManager { + + public static List extractionHandlers = new ArrayList(); + + public static void registerExtractionHandler(IExtractionHandler handler) { + extractionHandlers.add(handler); + } + + /** + * param extractor can be null + */ + public static boolean canExtractItems(Object extractor, World world, int i, int j, int k) { + for (IExtractionHandler handler : extractionHandlers) + if (!handler.canExtractItems(extractor, world, i, j, k)) + return false; + + return true; + } + + /** + * param extractor can be null + */ + public static boolean canExtractFluids(Object extractor, World world, int i, int j, int k) { + for (IExtractionHandler handler : extractionHandlers) + if (!handler.canExtractFluids(extractor, world, i, j, k)) + return false; + + return true; + } +} diff --git a/common/crazypants/enderio/ClientProxy.java b/common/crazypants/enderio/ClientProxy.java new file mode 100644 index 00000000..f08a6a63 --- /dev/null +++ b/common/crazypants/enderio/ClientProxy.java @@ -0,0 +1,120 @@ +package crazypants.enderio; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; +import net.minecraftforge.client.MinecraftForgeClient; +import cpw.mods.fml.client.FMLClientHandler; +import cpw.mods.fml.client.registry.ClientRegistry; +import cpw.mods.fml.client.registry.RenderingRegistry; +import crazypants.enderio.conduit.BlockConduitBundle; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.TileConduitBundle; +import crazypants.enderio.conduit.facade.FacadeRenderer; +import crazypants.enderio.conduit.liquid.LiquidConduitRenderer; +import crazypants.enderio.conduit.redstone.RedstoneSwitchRenderer; +import crazypants.enderio.conduit.render.ConduitBundleRenderer; +import crazypants.enderio.conduit.render.ConduitRenderer; +import crazypants.enderio.conduit.render.DefaultConduitRenderer; +import crazypants.enderio.conduit.render.ItemConduitRenderer; +import crazypants.enderio.enderface.EnderIoRenderer; +import crazypants.enderio.enderface.TileEnderIO; +import crazypants.enderio.machine.painter.BlockCustomFenceGate; +import crazypants.enderio.machine.painter.BlockCustomFenceGateRenderer; +import crazypants.enderio.machine.painter.PaintedItemRenderer; +import crazypants.enderio.machine.reservoir.ReservoirRenderer; +import crazypants.enderio.machine.reservoir.TileReservoir; +import crazypants.enderio.material.BlockFusedQuartz; +import crazypants.enderio.material.FusedQuartzFrameRenderer; +import crazypants.enderio.material.FusedQuartzRenderer; + + +public class ClientProxy extends CommonProxy { + + //@formatter:off + public static int[][] sideAndFacingToSpriteOffset = new int[][] { + + { 3, 2, 0, 0, 0, 0 }, + { 2, 3, 1, 1, 1, 1 }, + { 1, 1, 3, 2, 5, 4 }, + { 0, 0, 2, 3, 4, 5 }, + { 4, 5, 4, 5, 3, 2 }, + { 5, 4, 5, 4, 2, 3 } }; +//@formatter:on + + + private List conduitRenderers = new ArrayList(); + + private DefaultConduitRenderer dcr = new DefaultConduitRenderer(); + + @Override + public World getClientWorld() { + return FMLClientHandler.instance().getClient().theWorld; + } + + @Override + public EntityPlayer getClientPlayer() { + return Minecraft.getMinecraft().thePlayer; + } + + @Override + public void load() { + super.load(); + + //Renderers + + ConduitBundleRenderer cbr = new ConduitBundleRenderer(); + BlockConduitBundle.rendererId = RenderingRegistry.getNextAvailableRenderId(); + RenderingRegistry.registerBlockHandler(cbr); + + BlockCustomFenceGateRenderer bcfgr = new BlockCustomFenceGateRenderer(); + BlockCustomFenceGate.renderId = RenderingRegistry.getNextAvailableRenderId();; + RenderingRegistry.registerBlockHandler(bcfgr); + + FusedQuartzRenderer fqr = new FusedQuartzRenderer(); + BlockFusedQuartz.renderId = RenderingRegistry.getNextAvailableRenderId();; + RenderingRegistry.registerBlockHandler(fqr); + + FusedQuartzFrameRenderer fqfr = new FusedQuartzFrameRenderer(); + MinecraftForgeClient.registerItemRenderer(EnderIO.itemFusedQuartzFrame.itemID, fqfr); + + ItemConduitRenderer itemConRenderer = new ItemConduitRenderer(); + MinecraftForgeClient.registerItemRenderer(EnderIO.itemLiquidConduit.itemID, itemConRenderer); + MinecraftForgeClient.registerItemRenderer(EnderIO.itemPowerConduit.itemID, itemConRenderer); + MinecraftForgeClient.registerItemRenderer(EnderIO.itemRedstoneConduit.itemID, itemConRenderer); + + + PaintedItemRenderer pir = new PaintedItemRenderer(); + MinecraftForgeClient.registerItemRenderer(EnderIO.blockCustomFence.blockID, pir); + MinecraftForgeClient.registerItemRenderer(EnderIO.blockCustomFenceGate.blockID, pir); + MinecraftForgeClient.registerItemRenderer(EnderIO.blockCustomWall.blockID, pir); + MinecraftForgeClient.registerItemRenderer(EnderIO.blockCustomStair.blockID, pir); + + MinecraftForgeClient.registerItemRenderer(EnderIO.itemConduitFacade.itemID, new FacadeRenderer()); + + ClientRegistry.bindTileEntitySpecialRenderer(TileConduitBundle.class, cbr); + conduitRenderers.add(RedstoneSwitchRenderer.instance); + conduitRenderers.add(new LiquidConduitRenderer()); + + EnderIoRenderer eior = new EnderIoRenderer(); + ClientRegistry.bindTileEntitySpecialRenderer(TileEnderIO.class, eior); + MinecraftForgeClient.registerItemRenderer(EnderIO.blockEnderIo.blockID, eior); + + ClientRegistry.bindTileEntitySpecialRenderer(TileReservoir.class, new ReservoirRenderer(EnderIO.blockReservoir)); + + } + + @Override + public ConduitRenderer getRendererForConduit(IConduit conduit) { + for(ConduitRenderer renderer : conduitRenderers) { + if(renderer.isRendererForConduit(conduit)) { + return renderer; + } + } + return dcr; + } + +} diff --git a/common/crazypants/enderio/ClientTickHandler.java b/common/crazypants/enderio/ClientTickHandler.java new file mode 100644 index 00000000..91fc614c --- /dev/null +++ b/common/crazypants/enderio/ClientTickHandler.java @@ -0,0 +1,60 @@ +package crazypants.enderio; + +import java.util.EnumSet; +import java.util.List; + +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import cpw.mods.fml.client.FMLClientHandler; +import cpw.mods.fml.common.ITickHandler; +import cpw.mods.fml.common.TickType; +import crazypants.enderio.conduit.ConduitUtil; + +public class ClientTickHandler implements ITickHandler { + + private boolean hidingConduits = false; + private boolean first = true; + + @Override + public void tickStart(EnumSet type, Object... tickData) { + EntityPlayer player = (EntityPlayer) tickData[0]; + boolean curVal = ConduitUtil.isToolEquipped(player) || ConduitUtil.isConduitEquipped(player); + if(first) { + hidingConduits = curVal; + first = false; + } + if(curVal != hidingConduits) { + hidingConduits = curVal; + WorldClient world = FMLClientHandler.instance().getClient().theWorld; + + @SuppressWarnings("unchecked") + List checkList = world.loadedTileEntityList; + for(TileEntity o : checkList) { + if(o.blockType != null && o.blockType.blockID == EnderIO.blockConduitBundle.blockID) { + if(o.getDistanceFrom(player.posX, player.posY, player.posZ) < o.getMaxRenderDistanceSquared()) { + world.markBlockForRenderUpdate(o.xCoord, o.yCoord, o.zCoord); + } + } + } + } + + + } + + @Override + public void tickEnd(EnumSet type, Object... tickData) { + } + + @Override + public EnumSet ticks() { + return EnumSet.of(TickType.PLAYER); + } + + @Override + public String getLabel() { + return "EnderIO Client Tick Handler"; + } + + +} diff --git a/common/crazypants/enderio/CommonProxy.java b/common/crazypants/enderio/CommonProxy.java new file mode 100644 index 00000000..a741a2b2 --- /dev/null +++ b/common/crazypants/enderio/CommonProxy.java @@ -0,0 +1,38 @@ +package crazypants.enderio; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; +import cpw.mods.fml.common.registry.TickRegistry; +import cpw.mods.fml.relauncher.Side; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.render.ConduitRenderer; + +public class CommonProxy { + + private final ServerTickHandler serverTickHandler = new ServerTickHandler(); + + public World getClientWorld() { + return null; + } + + public EntityPlayer getClientPlayer() { + return null; + } + + public void load() { + TickRegistry.registerTickHandler(serverTickHandler, Side.SERVER); + } + + public ConduitRenderer getRendererForConduit(IConduit conduit) { + return null; + } + + public ServerTickHandler getServerTickHandler() { + return serverTickHandler; + } + + public void serverStopped() { + serverTickHandler.serverStopped(); + } + +} diff --git a/common/crazypants/enderio/Config.java b/common/crazypants/enderio/Config.java new file mode 100644 index 00000000..3d44f4b4 --- /dev/null +++ b/common/crazypants/enderio/Config.java @@ -0,0 +1,19 @@ +package crazypants.enderio; + +import net.minecraftforge.common.Configuration; + +public final class Config { + + static int BID = 700; + static int IID = 8524; + + public static void load(Configuration config) { + for (ModObject e : ModObject.values()) { + e.load(config); + } + } + + private Config() { + } + +} diff --git a/common/crazypants/enderio/EnderIO.java b/common/crazypants/enderio/EnderIO.java new file mode 100644 index 00000000..e2ae2ca1 --- /dev/null +++ b/common/crazypants/enderio/EnderIO.java @@ -0,0 +1,172 @@ +package crazypants.enderio; + +import java.util.logging.Level; + +import net.minecraftforge.common.Configuration; +import net.minecraftforge.common.MinecraftForge; +import cpw.mods.fml.common.FMLLog; +import cpw.mods.fml.common.Mod; +import cpw.mods.fml.common.Mod.Init; +import cpw.mods.fml.common.Mod.Instance; +import cpw.mods.fml.common.Mod.PostInit; +import cpw.mods.fml.common.Mod.PreInit; +import cpw.mods.fml.common.Mod.ServerStopped; +import cpw.mods.fml.common.SidedProxy; +import cpw.mods.fml.common.event.FMLInitializationEvent; +import cpw.mods.fml.common.event.FMLPostInitializationEvent; +import cpw.mods.fml.common.event.FMLPreInitializationEvent; +import cpw.mods.fml.common.event.FMLServerStoppedEvent; +import cpw.mods.fml.common.network.NetworkMod; +import cpw.mods.fml.common.network.NetworkRegistry; +import cpw.mods.fml.common.registry.TickRegistry; +import cpw.mods.fml.relauncher.Side; +import crazypants.enderio.conduit.BlockConduitBundle; +import crazypants.enderio.conduit.ConduitRecipes; +import crazypants.enderio.conduit.facade.BlockConduitFacade; +import crazypants.enderio.conduit.facade.ItemConduitFacade; +import crazypants.enderio.conduit.liquid.ItemLiquidConduit; +import crazypants.enderio.conduit.power.ItemPowerConduit; +import crazypants.enderio.conduit.redstone.ItemRedstoneConduit; +import crazypants.enderio.enderface.BlockEnderIO; +import crazypants.enderio.enderface.ItemEnderface; +import crazypants.enderio.machine.BlockElectricLight; +import crazypants.enderio.machine.MachineRecipes; +import crazypants.enderio.machine.alloy.BlockAlloySmelter; +import crazypants.enderio.machine.generator.BlockStirlingGenerator; +import crazypants.enderio.machine.painter.BlockCustomFence; +import crazypants.enderio.machine.painter.BlockCustomFenceGate; +import crazypants.enderio.machine.painter.BlockCustomStair; +import crazypants.enderio.machine.painter.BlockCustomWall; +import crazypants.enderio.machine.painter.BlockPainter; +import crazypants.enderio.machine.reservoir.BlockReservoir; +import crazypants.enderio.machine.solor.BlockSolarPanel; +import crazypants.enderio.material.BlockFusedQuartz; +import crazypants.enderio.material.ItemAlloy; +import crazypants.enderio.material.ItemCapacitor; +import crazypants.enderio.material.ItemFusedQuartzFrame; +import crazypants.enderio.material.ItemIndustrialBinder; +import crazypants.enderio.material.ItemYetaWrench; +import crazypants.enderio.material.MaterialRecipes; + +@Mod(name = "EnderIO", modid = "EnderIO", version = "0.1.0", dependencies = "required-after:Forge@[7.1,);required-after:FML@[5.0.5,)") +@NetworkMod(clientSideRequired = true, serverSideRequired = true, channels = { "EnderIO" }, packetHandler = PacketHandler.class) +public class EnderIO { + + @Instance("EnderIO") + public static EnderIO instance; + + @SidedProxy(clientSide = "crazypants.enderio.ClientProxy", serverSide = "crazypants.enderio.CommonProxy") + public static CommonProxy proxy; + + public static GuiHandler guiHandler = new GuiHandler(); + + //Materials + public static ItemIndustrialBinder itemIndustrialBinder; + public static ItemCapacitor itemBasicCapacitor; + public static ItemAlloy itemAlloy; + public static BlockFusedQuartz blockFusedQuartz; + public static ItemFusedQuartzFrame itemFusedQuartzFrame; + + // Enderface + public static BlockEnderIO blockEnderIo; + public static ItemEnderface itemEnderface; + + // Painter + public static BlockPainter blockPainter; + public static BlockCustomFence blockCustomFence; + public static BlockCustomFenceGate blockCustomFenceGate; + public static BlockCustomWall blockCustomWall; + public static BlockCustomStair blockCustomStair; + + // Conduits + public static BlockConduitBundle blockConduitBundle; + public static BlockConduitFacade blockConduitFacade; + public static ItemConduitFacade itemConduitFacade; + public static ItemRedstoneConduit itemRedstoneConduit; + public static ItemPowerConduit itemPowerConduit; + public static ItemLiquidConduit itemLiquidConduit; + + //Machines + public static BlockStirlingGenerator blockStirlingGenerator; + public static BlockSolarPanel blockSolarPanel; + public static BlockElectricLight blockElectricLight; + public static BlockReservoir blockReservoir; + public static BlockAlloySmelter blockAlloySmelter; + + public static ItemYetaWrench itemYetaWench; + + @PreInit + public void preInit(FMLPreInitializationEvent event) { + Configuration cfg = new Configuration(event.getSuggestedConfigurationFile()); + try { + cfg.load(); + Config.load(cfg); + } catch (Exception e) { + FMLLog.log(Level.SEVERE, e, "EnderIO has a problem loading it's configuration"); + } finally { + if (cfg.hasChanged()) { + cfg.save(); + } + } + + itemIndustrialBinder= ItemIndustrialBinder.create(); + itemBasicCapacitor = ItemCapacitor.create(); + itemAlloy = ItemAlloy.create(); + blockFusedQuartz = BlockFusedQuartz.create(); + itemFusedQuartzFrame = ItemFusedQuartzFrame.create(); + + blockEnderIo = BlockEnderIO.create(); + itemEnderface = ItemEnderface.create(); + + blockPainter = BlockPainter.create(); + blockCustomFence = BlockCustomFence.create(); + blockCustomFenceGate = BlockCustomFenceGate.create(); + blockCustomWall = BlockCustomWall.create(); + blockCustomStair = BlockCustomStair.create(); + + blockStirlingGenerator = BlockStirlingGenerator.create(); + blockSolarPanel = BlockSolarPanel.create(); + blockReservoir = BlockReservoir.create(); + blockAlloySmelter = BlockAlloySmelter.create(); + + + blockConduitBundle = BlockConduitBundle.create(); + blockConduitFacade = BlockConduitFacade.create(); + itemConduitFacade = ItemConduitFacade.create(); + + itemRedstoneConduit = ItemRedstoneConduit.create(); + itemPowerConduit = ItemPowerConduit.create(); + itemLiquidConduit = ItemLiquidConduit.create(); + + //blockElectricLight = BlockElectricLight.create(); + + itemYetaWench = ItemYetaWrench.create(); + } + + + @Init + public void load(FMLInitializationEvent event) { + + instance = this; + + NetworkRegistry.instance().registerGuiHandler(this, guiHandler); + MinecraftForge.EVENT_BUS.register(this); + + MaterialRecipes.addRecipes(); + ConduitRecipes.addRecipes(); + MachineRecipes.addRecipes(); + + proxy.load(); + } + + @PostInit + public void postInit(FMLPostInitializationEvent event) { + TickRegistry.registerTickHandler(new ClientTickHandler(), Side.CLIENT); + } + + @ServerStopped + public void serverStopped(FMLServerStoppedEvent event) { + proxy.serverStopped(); + } + +} diff --git a/common/crazypants/enderio/EnderIOTab.java b/common/crazypants/enderio/EnderIOTab.java new file mode 100644 index 00000000..0640fb35 --- /dev/null +++ b/common/crazypants/enderio/EnderIOTab.java @@ -0,0 +1,36 @@ +package crazypants.enderio; + +import net.minecraft.creativetab.CreativeTabs; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +public class EnderIOTab extends CreativeTabs { + + + public static final CreativeTabs tabEnderIO = new EnderIOTab(); + + public EnderIOTab() { + super("EnderIO"); + } + + /** + * the itemID for the item to be displayed on the tab + */ + @Override + public int getTabIconItemIndex() { + return EnderIO.itemEnderface.itemID; + } + + @Override + @SideOnly(Side.CLIENT) + public String getTabLabel() { + return "EnderIO"; + } + + @Override + @SideOnly(Side.CLIENT) + public String getTranslatedTabLabel() { + return "EnderIO"; + } + +} diff --git a/common/crazypants/enderio/GuiHandler.java b/common/crazypants/enderio/GuiHandler.java new file mode 100644 index 00000000..312b7e7b --- /dev/null +++ b/common/crazypants/enderio/GuiHandler.java @@ -0,0 +1,41 @@ +package crazypants.enderio; + +import java.util.HashMap; +import java.util.Map; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; +import cpw.mods.fml.common.network.IGuiHandler; + +public class GuiHandler implements IGuiHandler { + + public static final int GUI_ID_ENDERFACE = 1; + public static final int GUI_ID_PAINTER = 2; + public static final int GUI_ID_STIRLING_GEN = 3; + public static final int GUI_ID_ALLOY_SMELTER = 4; + + protected final Map guiHandlers = new HashMap(); + + public void registerGuiHandler(int id, IGuiHandler handler) { + guiHandlers.put(id, handler); + } + + @Override + public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) { + IGuiHandler handler = guiHandlers.get(id); + if(handler != null) { + return handler.getServerGuiElement(id, player, world, x, y, z); + } + return null; + } + + @Override + public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) { + IGuiHandler handler = guiHandlers.get(id); + if(handler != null) { + return handler.getClientGuiElement(id, player, world, x, y, z); + } + return null; + } + +} diff --git a/common/crazypants/enderio/ModObject.java b/common/crazypants/enderio/ModObject.java new file mode 100644 index 00000000..997e84cb --- /dev/null +++ b/common/crazypants/enderio/ModObject.java @@ -0,0 +1,80 @@ +package crazypants.enderio; + +import static net.minecraftforge.common.Configuration.CATEGORY_BLOCK; +import static net.minecraftforge.common.Configuration.CATEGORY_ITEM; +import net.minecraftforge.common.Configuration; + +public enum ModObject { + // Enderface + blockEnderIo(++Config.BID, CATEGORY_BLOCK, "Ender IO"), + itemEnderface(++Config.IID, CATEGORY_ITEM, "Enderface"), + + // Conduits + blockConduitBundle(++Config.BID, CATEGORY_BLOCK, "Conduit Bundle"), + blockConduitFacade(++Config.BID, CATEGORY_BLOCK, "Conduit Facade"), + itemConduitFacade(++Config.IID, CATEGORY_ITEM, "Conduit Facade"), + itemRedstoneConduit(++Config.IID, CATEGORY_ITEM, "Redstone Conduit"), + + // Power + itemPowerConduit(++Config.IID, CATEGORY_ITEM, "Power Conduit"), + + // Liquid + itemLiquidConduit(++Config.IID, CATEGORY_ITEM, "Liquid Conduit"), + + // Materials + itemIndustrialBinder(++Config.IID, CATEGORY_ITEM, "Industrial Binder"), + itemBasicCapacitor(++Config.IID, CATEGORY_ITEM, "Basic Capacitor"), + itemAlloy(++Config.IID, CATEGORY_ITEM, "Alloy"), + blockFusedQuartz(++Config.BID, CATEGORY_BLOCK, "Fused Quartz"), + + // Stirling Gen + blockStirlingGenerator(++Config.BID, CATEGORY_BLOCK, "Strirling Generator"), + blockReservoir(++Config.BID, CATEGORY_BLOCK, "Reservoir"), + blockAlloySmelter(++Config.BID, CATEGORY_BLOCK, "Alloy Smelter"), + + // Painter + blockPainter(++Config.BID, CATEGORY_BLOCK, "Painter"), + blockCustomFence(++Config.BID, CATEGORY_BLOCK, "Fence"), + blockCustomFenceGate(++Config.BID, CATEGORY_BLOCK, "Gate"), + blockCustomWall(++Config.BID, CATEGORY_BLOCK, "Wall"), + blockCustomStair(++Config.BID, CATEGORY_BLOCK, "Stair"), + itemFusedQuartzFrame(++Config.IID, CATEGORY_ITEM, "Fused Quartz Frame"), + + // Solar Panel + blockSolarPanel(++Config.BID, CATEGORY_BLOCK, "Photovoltaic Panel"), + + blockElectricLight(++Config.BID, CATEGORY_BLOCK, "Electric Light"), + + itemYetaWrench(++Config.IID, CATEGORY_ITEM, "Yeta Wrench"); + + public final String unlocalisedName; + public final String name; + public final int defaultId; + public final String category; + public int id; + public int actualId; + + private ModObject(int defaultId, String category, String name) { + this.unlocalisedName = "enderIO:" + toString(); + this.defaultId = defaultId; + this.name = name; + this.category = category; + id = -1; + actualId = -1; + } + + void load(Configuration config) { + if (CATEGORY_ITEM.equals(category)) { + id = config.getItem(unlocalisedName, defaultId).getInt(); + } else if (CATEGORY_BLOCK.equals(category)) { + id = config.getBlock(unlocalisedName, defaultId).getInt(); + } else { + throw new RuntimeException("Unknown category " + category); + } + actualId = id; + if (CATEGORY_ITEM.equals(category)) { + actualId += 256; + } + } + +} \ No newline at end of file diff --git a/common/crazypants/enderio/PacketHandler.java b/common/crazypants/enderio/PacketHandler.java new file mode 100644 index 00000000..3bf27911 --- /dev/null +++ b/common/crazypants/enderio/PacketHandler.java @@ -0,0 +1,264 @@ +package crazypants.enderio; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Set; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.ContainerBeacon; +import net.minecraft.inventory.ContainerRepair; +import net.minecraft.item.ItemInWorldManager; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.INetworkManager; +import net.minecraft.network.packet.Packet; +import net.minecraft.network.packet.Packet100OpenWindow; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.tileentity.TileEntityBeacon; +import net.minecraft.world.World; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.network.IPacketHandler; +import cpw.mods.fml.common.network.Player; +import crazypants.enderio.enderface.ContainerWrapper; +import crazypants.enderio.machine.AbstractMachineEntity; +import crazypants.enderio.machine.RedstoneControlMode; +import crazypants.util.PacketUtil; + +public class PacketHandler implements IPacketHandler { + + public static int ID_ENDERFACE = 1; + private static final int ID_TILE_ENTITY = 4; + private static final int ID_MACHINE_REDSTONE_PACKET = 2; + + private static final String CHANNEL = "EnderIO"; + + + @Override + public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player) { + if (packet.data != null && packet.data.length <= 0) { + return; + } + + DataInputStream data = new DataInputStream(new ByteArrayInputStream(packet.data)); + try { + int id = data.readInt(); + if (id == ID_ENDERFACE) { + handleEnderfacePacket(data, manager, player); + } else if(id == ID_TILE_ENTITY) { + PacketUtil.handleTileEntityPacket(false, data); + } else if(id == ID_MACHINE_REDSTONE_PACKET) { + handleRedstoneControlPacket(data, manager, player); + } else { + System.out.println("PacketHandler.onPacketData: Recieved packet of unknown type: " + id); + } + } catch (IOException ex) { + FMLCommonHandler.instance().raiseException(ex, "PacketHandler.onPacketData", true); + } + } + + + + public static Packet getPacket(TileEntity te) { + return PacketUtil.createTileEntityPacket(CHANNEL, ID_TILE_ENTITY, te); + } + + // ---------------- Redstone Control -------------------------------------------------------- + + private void handleRedstoneControlPacket(DataInputStream data, INetworkManager manager, Player player) throws IOException { + int x = data.readInt(); + int y = data.readInt(); + int z = data.readInt(); + short ordinal = data.readShort(); + EntityPlayerMP p = (EntityPlayerMP) player; + TileEntity te = p.worldObj.getBlockTileEntity(x, y, z); + if(te instanceof AbstractMachineEntity) { + AbstractMachineEntity me = (AbstractMachineEntity)te; + me.setRedstoneControlMode(RedstoneControlMode.values()[ordinal]); + p.worldObj.markBlockForUpdate(x, y, z); + } + + } + + public static Packet getRedstoneControlPacket(AbstractMachineEntity te) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(140); + DataOutputStream dos = new DataOutputStream(bos); + try { + dos.writeInt(ID_MACHINE_REDSTONE_PACKET); + dos.writeInt(te.xCoord); + dos.writeInt(te.yCoord); + dos.writeInt(te.zCoord); + dos.writeShort((short)te.getRedstoneControlMode().ordinal()); + } catch (IOException e) { + // never thrown + } + + Packet250CustomPayload pkt = new Packet250CustomPayload(); + pkt.channel = CHANNEL; + pkt.data = bos.toByteArray(); + pkt.length = bos.size(); + pkt.isChunkDataPacket = true; + return pkt; + + } + + + // ---------------- Enderface + // ------------------------------------------------------------ + + public static Packet250CustomPayload getPacketEnderface(int x, int y, int z) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(16); + DataOutputStream dos = new DataOutputStream(bos); + try { + dos.writeInt(ID_ENDERFACE); + dos.writeInt(x); + dos.writeInt(y); + dos.writeInt(z); + } catch (IOException e) { + // never thrown + } + Packet250CustomPayload pkt = new Packet250CustomPayload(); + pkt.channel = CHANNEL; + pkt.data = bos.toByteArray(); + pkt.length = bos.size(); + pkt.isChunkDataPacket = true; + return pkt; + } + + private void handleEnderfacePacket(DataInputStream data, INetworkManager manager, Player p) throws IOException { + if (!(p instanceof EntityPlayerMP)) { + System.out.println("kitchenbench.PacketHandler.handleEnderfacePacket: Not an EntityPlayerMP"); + return; + } + int x = data.readInt(); + int y = data.readInt(); + int z = data.readInt(); + + EntityPlayerMP player = (EntityPlayerMP) p; + EntityPlayerMP proxy = createPlayerProxy(player); + player.theItemInWorldManager.activateBlockOrUseItem(proxy, player.worldObj, null, x, y, z, 0, 0, 0, 0); + player.theItemInWorldManager.thisPlayerMP = player; + + } + + public static T createPlayerProxy(EntityPlayerMP player) { + Enhancer e = new Enhancer(); + e.setCallback(new PlayerProxy(player)); + + e.setSuperclass(player.getClass()); + Class[] argTypes = new Class[] { MinecraftServer.class, World.class, String.class, ItemInWorldManager.class }; + Object[] args = new Object[] { player.mcServer, player.worldObj, player.username, player.theItemInWorldManager }; + + e.setInterceptDuringConstruction(false); + @SuppressWarnings("unchecked") + T proxifiedObj = (T) e.create(argTypes, args); + + return proxifiedObj; + } + + public static class PlayerProxy implements MethodInterceptor { + + private EntityPlayerMP realObj; + + private Set interceptNames = new HashSet(); + + private Set beaconNames = new HashSet(); + private Set anvilNames = new HashSet(); + + public PlayerProxy(EntityPlayerMP obj) { + // TODO: Move to config? + this.realObj = obj; + interceptNames.add("openGui"); + + interceptNames.add("displayGUIBrewingStand"); + interceptNames.add("func_71017_a"); + + interceptNames.add("displayGUIChest"); + interceptNames.add("func_71007_a"); + + interceptNames.add("displayGUIDispenser"); + interceptNames.add("func_71006_a"); + + interceptNames.add("displayGUIEnchantment"); + interceptNames.add("func_71002_c"); + + interceptNames.add("displayGUIFurnace"); + interceptNames.add("func_71042_a"); + + interceptNames.add("displayGUIWorkbench"); + interceptNames.add("func_71058_b"); + + interceptNames.add("displayGuiHopper"); // for when its added + interceptNames.add("func_94064_a"); // displayGuiHopper + + interceptNames.add("displayGUIHopper"); + + beaconNames.add("displayGUIBeacon"); + beaconNames.add("func_82240_a"); + + anvilNames.add("displayGUIAnvil"); + anvilNames.add("func_82244_d"); + + + } + + @Override + public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { + if (interceptNames.contains(method.getName())) { + + Object res = method.invoke(realObj, objects); + if (realObj.openContainer != null) { + realObj.openContainer = new ContainerWrapper(realObj.openContainer); + } + return res; + + } else if (beaconNames.contains(method.getName())) { + + // Beacon needs to be done manually for some reason to work properly + TileEntityBeacon par1TileEntityBeacon = (TileEntityBeacon) objects[0]; + realObj.incrementWindowID(); + realObj.playerNetServerHandler.sendPacketToPlayer(new Packet100OpenWindow(realObj.currentWindowId, 7, par1TileEntityBeacon.getInvName(), + par1TileEntityBeacon.getSizeInventory(), par1TileEntityBeacon.isInvNameLocalized())); + realObj.openContainer = new ContainerBeacon(realObj.inventory, par1TileEntityBeacon) { + @Override + public boolean canInteractWith(EntityPlayer par1EntityPlayer) { + return true; + } + }; + realObj.openContainer.windowId = realObj.currentWindowId; + realObj.openContainer.addCraftingToCrafters(realObj); + return null; + + } else if (anvilNames.contains(method.getName())) { + + realObj.incrementWindowID(); + realObj.playerNetServerHandler.sendPacketToPlayer(new Packet100OpenWindow(realObj.currentWindowId, 8, "Repairing", 9, true)); + realObj.openContainer = new ContainerRepair(realObj.inventory, realObj.worldObj, ((Integer)objects[0]).intValue(), ((Integer)objects[1]).intValue(), ((Integer)objects[2]).intValue(), realObj) { + @Override + public boolean canInteractWith(EntityPlayer par1EntityPlayer) { + return true; + } + }; + realObj.openContainer.windowId = realObj.currentWindowId; + realObj.openContainer.addCraftingToCrafters(realObj); + return null; + + } else if(method.getName().equals("getDistanceSq")) { //for forestry + return 6; + } + method.setAccessible(true); + return method.invoke(realObj, objects); + } + + } + +} diff --git a/common/crazypants/enderio/ServerTickHandler.java b/common/crazypants/enderio/ServerTickHandler.java new file mode 100644 index 00000000..9494caff --- /dev/null +++ b/common/crazypants/enderio/ServerTickHandler.java @@ -0,0 +1,81 @@ +package crazypants.enderio; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import cpw.mods.fml.common.ITickHandler; +import cpw.mods.fml.common.TickType; + +public class ServerTickHandler implements ITickHandler { + + private static final EnumSet TICKS = EnumSet.of(TickType.SERVER); + + private final List> listeners = new CopyOnWriteArrayList>(); + + public void addListener(TickListener listener) { + listeners.add(new WeakReference(listener)); + } + + public void removeListener(TickListener listener) { + WeakReference toRemove = null; + for(WeakReference ref : listeners) { + if(ref.get() == listener) { + toRemove = ref; + break; + } + } + if(toRemove != null) { + listeners.remove(toRemove); + } + } + + + @Override + public void tickStart(EnumSet type, Object... tickData) { + List lists = processListeners(); + for(TickListener listener : lists) { + listener.tickStart(type, tickData); + } + } + + @Override + public void tickEnd(EnumSet type, Object... tickData) { + List lists = processListeners(); + for(TickListener listener : lists) { + listener.tickEnd(type, tickData); + } + } + + private List processListeners() { + List result = new ArrayList(listeners.size()); + List> toRemove = new ArrayList>(); + for(WeakReference ref : listeners) { + TickListener l = ref.get(); + if(l == null) { + toRemove.add(ref); + } else { + result.add(l); + } + } + return result; + } + + public void serverStopped() { + listeners.clear(); + } + + @Override + public EnumSet ticks() { + return TICKS; + } + + @Override + public String getLabel() { + return "EnderIO Server Tick Handler"; + } + + +} diff --git a/common/crazypants/enderio/TickListener.java b/common/crazypants/enderio/TickListener.java new file mode 100644 index 00000000..3f40b8c0 --- /dev/null +++ b/common/crazypants/enderio/TickListener.java @@ -0,0 +1,13 @@ +package crazypants.enderio; + +import java.util.EnumSet; + +import cpw.mods.fml.common.TickType; + +public interface TickListener { + + void tickStart(EnumSet type, Object... tickData); + + void tickEnd(EnumSet type, Object... tickData); + +} diff --git a/common/crazypants/enderio/Tst.java b/common/crazypants/enderio/Tst.java new file mode 100644 index 00000000..35b49ba6 --- /dev/null +++ b/common/crazypants/enderio/Tst.java @@ -0,0 +1,22 @@ +package crazypants.enderio; + +import crazypants.vecmath.Matrix4d; +import crazypants.vecmath.VecmathUtil; +import crazypants.vecmath.Vector3d; + + +public class Tst { + + + /** + * @param args + */ + public static void main(String[] args) { + } + + + + + + +} diff --git a/common/crazypants/enderio/conduit/AbstractConduit.java b/common/crazypants/enderio/conduit/AbstractConduit.java new file mode 100644 index 00000000..974c2ef4 --- /dev/null +++ b/common/crazypants/enderio/conduit/AbstractConduit.java @@ -0,0 +1,368 @@ +package crazypants.enderio.conduit; + +import java.util.*; + +import crazypants.enderio.EnderIO; +import crazypants.enderio.conduit.geom.*; +import crazypants.enderio.conduit.geom.CollidableCache.CacheKey; +import crazypants.util.BlockCoord; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; + +public abstract class AbstractConduit implements IConduit { + + protected final Set conduitConnections = new HashSet(); + + protected final Set externalConnections = new HashSet(); + + public static final float STUB_WIDTH = 0.2f; + + public static final float STUB_HEIGHT = 0.2f; + + public static final float TRANSMISSION_SCALE = 0.3f; + + // NB: This is a transient field controlled by the owning bundle. It is not + // written to the NBT etc + protected IConduitBundle bundle; + + protected boolean active; + + protected List collidables; + + protected boolean collidablesDirty = true; + + private boolean clientStateDirty = true; + + private boolean dodgyChangeSinceLastCallFlagForBundle = true; + + protected AbstractConduit() { + } + + private int lastNumConections = -1; + + @Override + public boolean haveCollidablesChangedSinceLastCall() { + if(dodgyChangeSinceLastCallFlagForBundle) { + dodgyChangeSinceLastCallFlagForBundle = false; + return true; + } + return false; + } + + @Override + public BlockCoord getLocation() { + if (bundle == null) { + return null; + } + TileEntity te = bundle.getEntity(); + if (te == null) { + return null; + } + return new BlockCoord(te.xCoord, te.yCoord, te.zCoord); + } + + @Override + public void setBundle(IConduitBundle tileConduitBundle) { + bundle = tileConduitBundle; + } + + @Override + public IConduitBundle getBundle() { + return bundle; + } + + // Connections + @Override + public Set getConduitConnections() { + return conduitConnections; + } + + @Override + public boolean containsConduitConnection(ForgeDirection dir) { + return conduitConnections.contains(dir); + } + + @Override + public void conduitConnectionAdded(ForgeDirection fromDirection) { + conduitConnections.add(fromDirection); + connectionsChanged(); + } + + @Override + public void conduitConnectionRemoved(ForgeDirection fromDirection) { + conduitConnections.remove(fromDirection); + connectionsChanged(); + } + + @Override + public boolean canConnectToConduit(ForgeDirection direction, IConduit conduit) { + return true; + } + + @Override + public boolean canConnectToExternal(ForgeDirection direction) { + return false; + } + + @Override + public Set getExternalConnections() { + return externalConnections; + } + + @Override + public boolean containsExternalConnection(ForgeDirection dir) { + return externalConnections.contains(dir); + } + + @Override + public void externalConnectionAdded(ForgeDirection fromDirection) { + externalConnections.add(fromDirection); + connectionsChanged(); + } + + @Override + public void externalConnectionRemoved(ForgeDirection fromDirection) { + externalConnections.remove(fromDirection); + connectionsChanged(); + } + + @Override + public boolean isConnectedTo(ForgeDirection dir) { + return containsConduitConnection(dir) || containsExternalConnection(dir); + } + + @Override + public boolean isActive() { + return active; + } + + @Override + public void setActive(boolean active) { + if(active != this.active) { + clientStateDirty = true; + } + this.active = active; + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + int[] dirs = new int[conduitConnections.size()]; + Iterator cons = conduitConnections.iterator(); + for (int i = 0; i < dirs.length; i++) { + dirs[i] = cons.next().ordinal(); + } + nbtRoot.setIntArray("connections", dirs); + + dirs = new int[externalConnections.size()]; + cons = externalConnections.iterator(); + for (int i = 0; i < dirs.length; i++) { + dirs[i] = cons.next().ordinal(); + } + nbtRoot.setIntArray("externalConnections", dirs); + nbtRoot.setBoolean("signalActive", active); + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + conduitConnections.clear(); + int[] dirs = nbtRoot.getIntArray("connections"); + for (int i = 0; i < dirs.length; i++) { + conduitConnections.add(ForgeDirection.values()[dirs[i]]); + } + + externalConnections.clear(); + dirs = nbtRoot.getIntArray("externalConnections"); + for (int i = 0; i < dirs.length; i++) { + externalConnections.add(ForgeDirection.values()[dirs[i]]); + } + active = nbtRoot.getBoolean("signalActive"); + //collidablesDirty = true; + } + + @Override + public int getLightValue() { + return 0; + } + + @Override + public boolean onBlockActivated(EntityPlayer player, RaytraceResult res) { + return false; + } + + @Override + public float getSelfIlluminationForState(CollidableComponent component) { + return isActive() ? 1 : 0; + } + + @Override + public float getTransmitionGeometryScale() { + return TRANSMISSION_SCALE; + } + + @Override + public void onChunkUnload(World worldObj) { + AbstractConduitNetwork network = getNetwork(); + if (network != null) { + System.out.println("AbstractConduit.onChunkUnload: Destroyed network on chunk unload."); + network.destroyNetwork(); + } + } + + @Override + public void updateEntity(World world) { + if (world.isRemote) { + return; + } + updateNetwork(world); + + if(clientStateDirty) { + getBundle().dirty(); + clientStateDirty = false; + } + } + + + protected void connectionsChanged() { + collidablesDirty = true; + clientStateDirty = true; + dodgyChangeSinceLastCallFlagForBundle = true; + } + + protected void updateNetwork(World world) { + if (getNetwork() == null) { + ConduitUtil.ensureValidNetwork(this); + } + getNetwork().onUpdateEntity(this); + } + + @Override + public void onAddedToBundle() { + + TileEntity te = bundle.getEntity(); + World world = te.worldObj; + + conduitConnections.clear(); + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + IConduit neighbour = ConduitUtil.getConduit(world, te, dir, getBaseConduitType()); + if (neighbour != null && neighbour.canConnectToConduit(dir.getOpposite(), this)) { + conduitConnections.add(dir); + neighbour.conduitConnectionAdded(dir.getOpposite()); + } + } + + externalConnections.clear(); + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (!containsConduitConnection(dir) && canConnectToExternal(dir)) { + externalConnectionAdded(dir); + } + } + + connectionsChanged(); + } + + @Override + public void onRemovedFromBundle() { + TileEntity te = bundle.getEntity(); + World world = te.worldObj; + + for (ForgeDirection dir : conduitConnections) { + IConduit neighbour = ConduitUtil.getConduit(world, te, dir, getBaseConduitType()); + if (neighbour != null) { + neighbour.conduitConnectionRemoved(dir.getOpposite()); + } + } + conduitConnections.clear(); + + if (!externalConnections.isEmpty()) { + world.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord, te.zCoord, EnderIO.blockConduitBundle.blockID); + } + externalConnections.clear(); + + AbstractConduitNetwork network = getNetwork(); + if (network != null) { + network.destroyNetwork(); + } + connectionsChanged(); + } + + @Override + public boolean onNeighborBlockChange(int blockId) { + // Check for changes to external connections, connections to conduits are + // handled by the bundle + + //NB: No need to check externals if the neighbour that changed was a conduit bundle as this + //can't effect external connections. + if(blockId == EnderIO.blockConduitBundle.blockID) { + return false; + } + + boolean externalConnectionsChanged = false; + List copy = new ArrayList(externalConnections); + // remove any no longer valid connections + for (ForgeDirection dir : copy) { + if (!canConnectToExternal(dir)) { + externalConnectionRemoved(dir); + externalConnectionsChanged = true; + } + } + + // then check for new ones + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (!conduitConnections.contains(dir) && !externalConnections.contains(dir)) { + if (canConnectToExternal(dir)) { + externalConnectionAdded(dir); + externalConnectionsChanged = true; + } + } + } + if (externalConnectionsChanged) { + connectionsChanged(); + } + return externalConnectionsChanged; + } + + @Override + public Collection createCollidables(CacheKey key) { + return Collections.singletonList(new CollidableComponent(getBaseConduitType(),ConduitGeometryUtil.instance.getBoundingBox(getBaseConduitType(), key.dir, key.isStub, key.offset),key.dir,null)); + } + + @Override + public List getCollidableComponents() { + + if (collidables != null && !collidablesDirty) { + return collidables; + } + + List result = new ArrayList(); + CollidableCache cc = CollidableCache.instance; + + for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + Collection col = getCollidables(dir); + if(col != null) { + result.addAll(col); + } + } + collidables = result; + + collidablesDirty = false; + + return result; + } + + + private Collection getCollidables(ForgeDirection dir) { + CollidableCache cc = CollidableCache.instance; + Class type = getBaseConduitType(); + + if (isConnectedTo(dir)) { + return cc.getCollidables(cc.createKey(type, getBundle().getOffset(type, dir), dir, false), this); + } + return null; + } + + +} diff --git a/common/crazypants/enderio/conduit/AbstractConduitNetwork.java b/common/crazypants/enderio/conduit/AbstractConduitNetwork.java new file mode 100644 index 00000000..2f3b89c3 --- /dev/null +++ b/common/crazypants/enderio/conduit/AbstractConduitNetwork.java @@ -0,0 +1,84 @@ +package crazypants.enderio.conduit; + +import java.util.*; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + +public abstract class AbstractConduitNetwork { + + protected final List conduits = new ArrayList(); + + protected AbstractConduitNetwork() { + } + + public void init(IConduitBundle tile, Collection connections, World world) { + + if (world.isRemote) { + throw new UnsupportedOperationException(); + } + + // Destroy all existing redstone networks around this block + for (T con : connections) { + AbstractConduitNetwork network = con.getNetwork(); + if (network != null) { + network.destroyNetwork(); + } + } + setNetwork(world, tile); + notifyNetworkOfUpdate(); + } + + public abstract Class getBaseConduitType(); + + protected void setNetwork(World world, IConduitBundle tile) { + + T conduit = tile.getConduit(getBaseConduitType()); + if (conduit.setNetwork(this)) { + addConduit(conduit); + TileEntity te = tile.getEntity(); + Collection connections = ConduitUtil.getConnectedConduits(world, te.xCoord, te.yCoord, te.zCoord, getBaseConduitType()); + for (T con : connections) { + if (con.getNetwork() == null) { + setNetwork(world, con.getBundle()); + } + } + } + } + + public void addConduit(T con) { + conduits.add(con); + } + + public void destroyNetwork() { + for (T con : conduits) { + con.setNetwork(null); + } + conduits.clear(); + } + + public List getConduits() { + return conduits; + } + + public void notifyNetworkOfUpdate() { + for (T con : conduits) { + TileEntity te = con.getBundle().getEntity(); + te.worldObj.markBlockForUpdate(te.xCoord, te.yCoord, te.zCoord); + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (IConduit con : conduits) { + sb.append(con.getLocation()); + sb.append(", "); + } + return "AbstractConduitNetwork [conduits=" + sb.toString() + "]"; + } + + public void onUpdateEntity(IConduit conduit) { + } + +} diff --git a/common/crazypants/enderio/conduit/AbstractItemConduit.java b/common/crazypants/enderio/conduit/AbstractItemConduit.java new file mode 100644 index 00000000..1e23d2fa --- /dev/null +++ b/common/crazypants/enderio/conduit/AbstractItemConduit.java @@ -0,0 +1,121 @@ +package crazypants.enderio.conduit; + +import java.util.List; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.*; +import net.minecraft.util.Icon; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import cpw.mods.fml.common.registry.*; +import crazypants.enderio.*; +import crazypants.enderio.material.Alloy; + +public abstract class AbstractItemConduit extends Item implements IConduitItem { + + protected ModObject modObj; + + protected ItemConduitSubtype[] subtypes; + + protected Icon[] icons; + + protected AbstractItemConduit(ModObject modObj) { + super(modObj.id); + this.modObj = modObj; + setCreativeTab(EnderIOTab.tabEnderIO); + setUnlocalizedName(modObj.unlocalisedName); + setMaxStackSize(64); + setHasSubtypes(true); + } + + protected void init(ItemConduitSubtype[] subtypes) { + this.subtypes = subtypes; + icons = new Icon[subtypes.length]; + + LanguageRegistry.addName(this, modObj.name); + GameRegistry.registerItem(this, modObj.unlocalisedName); + for(ItemConduitSubtype subtype : subtypes) { + LanguageRegistry.instance().addStringLocalization(getUnlocalizedName() + "." + subtype.unlocalisedName + ".name", subtype.uiName); + } + + } + + @Override + public void registerIcons(IconRegister iconRegister) { + int index = 0; + for(ItemConduitSubtype subtype : subtypes) { + icons[index] = iconRegister.registerIcon(subtype.iconKey); + index++; + } + } + + @Override + public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { + + ForgeDirection dir = ForgeDirection.values()[side]; + int placeX = x + dir.offsetX; + int placeY = y + dir.offsetY; + int placeZ = z + dir.offsetZ; + + int blockID = world.getBlockId(placeX, placeY, placeZ); + if (blockID == 0) { + if(!world.isRemote) { + if(world.setBlock(placeX, placeY, placeZ, ModObject.blockConduitBundle.actualId,0,1)) { + IConduitBundle bundle = (IConduitBundle) world.getBlockTileEntity(placeX, placeY, placeZ); + bundle.addConduit(createConduit(stack)); + } + } + if (!player.capabilities.isCreativeMode) { + stack.stackSize--; + } + return true; + } else if(blockID == ModObject.blockConduitBundle.actualId) { + + IConduitBundle bundle = (TileConduitBundle)world.getBlockTileEntity(placeX, placeY, placeZ); + if(bundle == null) { + System.out.println("AbstractItemConduit.onItemUse: Bunle null"); + return false; + } + IConduit con = createConduit(stack); + if(con == null) { + System.out.println("AbstractItemConduit.onItemUse: Conduit null."); + return false; + } + if(bundle.getConduit(con.getBaseConduitType()) == null) { + if(!world.isRemote) { + bundle.addConduit(con); + } + return true; + } + } + + return false; + } + + + @Override + public Icon getIconFromDamage(int damage) { + damage = MathHelper.clamp_int(damage, 0, subtypes.length); + return icons[damage]; + } + + + @Override + public String getUnlocalizedName(ItemStack par1ItemStack) { + int i = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, subtypes.length); + return super.getUnlocalizedName() + "." + subtypes[i].unlocalisedName; + + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List) { + for (int j = 0; j < subtypes.length; ++j) { + par3List.add(new ItemStack(par1, 1, j)); + } + } + +} diff --git a/common/crazypants/enderio/conduit/BlockConduitBundle.java b/common/crazypants/enderio/conduit/BlockConduitBundle.java new file mode 100644 index 00000000..94ebb740 --- /dev/null +++ b/common/crazypants/enderio/conduit/BlockConduitBundle.java @@ -0,0 +1,601 @@ +package crazypants.enderio.conduit; + +import static net.minecraftforge.common.ForgeDirection.getOrientation; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Random; + +import net.minecraft.block.Block; +import net.minecraft.block.ITileEntityProvider; +import net.minecraft.block.material.Material; +import net.minecraft.client.Minecraft; +import net.minecraft.client.particle.EffectRenderer; +import net.minecraft.client.particle.EntityDiggingFX; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.Icon; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.tools.IToolWrench; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.EnderIO; +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.conduit.geom.ConduitConnectorType; +import crazypants.enderio.conduit.liquid.LiquidConduit; +import crazypants.enderio.conduit.power.PowerConduit; +import crazypants.enderio.conduit.redstone.IRedstoneConduit; +import crazypants.enderio.conduit.redstone.RedstoneConduit; +import crazypants.enderio.conduit.redstone.RedstoneSwitch; +import crazypants.enderio.machine.painter.PainterUtil; +import crazypants.render.BoundingBox; + +public class BlockConduitBundle extends Block implements ITileEntityProvider { + + // private static final String KEY_BLOCK_ICON = "enderio:conduitBundle"; + + private static final String KEY_CONNECTOR_ICON = "enderIO:conduitConnector"; + + public static BlockConduitBundle create() { + BlockConduitBundle result = new BlockConduitBundle(); + result.init(); + return result; + } + + public static int rendererId = -1; + + private Icon connectorIcon; + + private Icon lastRemovedComponetIcon = null; + + private Random rand = new Random(); + + protected BlockConduitBundle() { + super(ModObject.blockConduitBundle.id, Material.ground); + setHardness(0.5F); + setBlockBounds(0.334f, 0.334f, 0.334f, 0.667f, 0.667f, 0.667f); + setStepSound(Block.soundStoneFootstep); + setUnlocalizedName(ModObject.blockConduitBundle.unlocalisedName); + setCreativeTab(null); + + RedstoneConduit.initIcons(); + RedstoneSwitch.initIcons(); + PowerConduit.initIcons(); + LiquidConduit.initIcons(); + + } + + // public float getPlayerRelativeBlockHardness(EntityPlayer par1EntityPlayer, + // World par2World, int par3, int par4, int par5) + + @Override + public boolean addBlockHitEffects(World world, MovingObjectPosition target, EffectRenderer effectRenderer) { + Icon tex = null; + + TileConduitBundle cb = (TileConduitBundle) world.getBlockTileEntity(target.blockX, target.blockY, target.blockZ); + if (ConduitUtil.renderFacade(cb, Minecraft.getMinecraft().thePlayer)) { + if (cb.getFacadeId() > 0) { + tex = Block.blocksList[cb.getFacadeId()].getIcon(target.sideHit, cb.getFacadeMetadata()); + } + } else if (target.hitInfo instanceof CollidableComponent) { + CollidableComponent cc = (CollidableComponent) target.hitInfo; + IConduit con = cb.getConduit(cc.conduitType); + if (con != null) { + tex = con.getTextureForState(cc); + } + } + if (tex == null) { + tex = blockIcon; + } + lastRemovedComponetIcon = tex; + addBlockHitEffects(world, effectRenderer, target.blockX, target.blockY, target.blockZ, target.sideHit, tex); + return true; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean addBlockDestroyEffects(World world, int x, int y, int z, int meta, EffectRenderer effectRenderer) { + Icon tex = lastRemovedComponetIcon; + byte b0 = 4; + for (int j1 = 0; j1 < b0; ++j1) { + for (int k1 = 0; k1 < b0; ++k1) { + for (int l1 = 0; l1 < b0; ++l1) { + double d0 = x + (j1 + 0.5D) / b0; + double d1 = y + (k1 + 0.5D) / b0; + double d2 = z + (l1 + 0.5D) / b0; + int i2 = this.rand.nextInt(6); + EntityDiggingFX fx = new EntityDiggingFX(world, d0, d1, d2, d0 - x - 0.5D, d1 - y - 0.5D, d2 - z - 0.5D, this, i2, 0).applyColourMultiplier(x, y, z); + fx.func_110125_a(tex); + effectRenderer.addEffect(fx); + } + } + } + return true; + + } + + @SideOnly(Side.CLIENT) + private void addBlockHitEffects(World world, EffectRenderer effectRenderer, int x, int y, int z, int side, Icon tex) { + float f = 0.1F; + double d0 = x + rand.nextDouble() * (getBlockBoundsMaxX() - getBlockBoundsMinX() - f * 2.0F) + f + getBlockBoundsMinX(); + double d1 = y + rand.nextDouble() * (getBlockBoundsMaxY() - getBlockBoundsMinY() - f * 2.0F) + f + getBlockBoundsMinY(); + double d2 = z + rand.nextDouble() * (getBlockBoundsMaxZ() - getBlockBoundsMinZ() - f * 2.0F) + f + getBlockBoundsMinZ(); + if (side == 0) { + d1 = y + getBlockBoundsMinY() - f; + } else if (side == 1) { + d1 = y + getBlockBoundsMaxY() + f; + } else if (side == 2) { + d2 = z + getBlockBoundsMinZ() - f; + } else if (side == 3) { + d2 = z + getBlockBoundsMaxZ() + f; + } else if (side == 4) { + d0 = x + getBlockBoundsMinX() - f; + } else if (side == 5) { + d0 = x + getBlockBoundsMaxX() + f; + } + EntityDiggingFX digFX = new EntityDiggingFX(world, d0, d1, d2, 0.0D, 0.0D, 0.0D, this, side, 0); + digFX.applyColourMultiplier(x, y, z).multiplyVelocity(0.2F).multipleParticleScaleBy(0.6F); + digFX.func_110125_a(tex); + effectRenderer.addEffect(digFX); + } + + private void init() { + LanguageRegistry.addName(this, ModObject.blockConduitBundle.name); + GameRegistry.registerBlock(this, ModObject.blockConduitBundle.unlocalisedName); + GameRegistry.registerTileEntity(TileConduitBundle.class, ModObject.blockConduitBundle.unlocalisedName + "TileEntity"); + } + + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + if (target != null && target.hitInfo instanceof CollidableComponent) { + CollidableComponent cc = (CollidableComponent) target.hitInfo; + TileConduitBundle bundle = (TileConduitBundle) world.getBlockTileEntity(x, y, z); + IConduit conduit = bundle.getConduit(cc.conduitType); + if (conduit != null) { + return conduit.createItem(); + } else if(cc.conduitType == null && bundle.getFacadeId() > 0) { + //use the facde + ItemStack fac = new ItemStack(ModObject.itemConduitFacade.actualId, 1, 0); + PainterUtil.setSourceBlock(fac, bundle.getFacadeId(), bundle.getFacadeMetadata()); + return fac; + } + } + return null; + } + + @Override + public int getDamageValue(World world, int x, int y, int z) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return 0; + } + IConduitBundle bun = (IConduitBundle) te; + return bun.getFacadeId() > 0 ? bun.getFacadeMetadata() : 0; + } + + + @Override + public int idDropped(int par1, Random par2Random, int par3) { + return 0; + } + + @Override + public int quantityDropped(Random r) { + return 0; + } + + public Icon getConnectorIcon() { + return connectorIcon; + } + + @Override + public void registerIcons(IconRegister iconRegister) { + connectorIcon = iconRegister.registerIcon(KEY_CONNECTOR_ICON); + blockIcon = connectorIcon; + } + + @Override + public boolean isBlockSolidOnSide(World world, int x, int y, int z, ForgeDirection side) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return false; + } + IConduitBundle con = (IConduitBundle) te; + if (con.getFacadeId() > 0) { + return true; + } + return false; + } + + @Override + public boolean isOpaqueCube() { + return false; + } + + @Override + public int getRenderType() { + return rendererId; + } + + @Override + public boolean renderAsNormalBlock() { + return false; + } + + @Override + public TileEntity createNewTileEntity(World world) { + return null; + } + + @Override + public TileEntity createTileEntity(World world, int metadata) { + return new TileConduitBundle(); + } + + @Override + public int getLightValue(IBlockAccess world, int x, int y, int z) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return super.getLightValue(world, x, y, z); + } + IConduitBundle con = (IConduitBundle) te; + if (con.getFacadeId() > 0) { + return 0; + } + Collection conduits = con.getConduits(); + int result = 0; + for (IConduit conduit : conduits) { + result += conduit.getLightValue(); + } + return result; + } + + @Override + public int isProvidingStrongPower(IBlockAccess world, int x, int y, int z, int par5) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return 0; + } + IConduitBundle bundle = (IConduitBundle) te; + IRedstoneConduit con = bundle.getConduit(IRedstoneConduit.class); + if (con == null) { + return 0; + } + return con.isProvidingStrongPower(getOrientation(par5)); + } + + @Override + public int isProvidingWeakPower(IBlockAccess world, int x, int y, int z, int par5) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return 0; + } + IConduitBundle bundle = (IConduitBundle) te; + IRedstoneConduit con = bundle.getConduit(IRedstoneConduit.class); + if (con == null) { + return 0; + } + return con.isProvidingWeakPower(getOrientation(par5)); + } + + @Override + public boolean canProvidePower() { + return true; + } + @Override + public boolean removeBlockByPlayer(World world, EntityPlayer player, int x, int y, int z) { + IConduitBundle te = (IConduitBundle) world.getBlockTileEntity(x, y, z); + if (te == null) { + return true; + } + + boolean breakBlock = true; + List drop = new ArrayList(); + if (ConduitUtil.renderFacade(te, player)) { + breakBlock = false; + ItemStack fac = new ItemStack(ModObject.itemConduitFacade.actualId, 1, 0); + PainterUtil.setSourceBlock(fac, te.getFacadeId(), te.getFacadeMetadata()); + drop.add(fac); + te.setFacadeId(-1); + te.setFacadeMetadata(0); + } + + if (breakBlock) { + RaytraceResult rt = doRayTrace(world, x, y, z, player); + if (rt != null && rt.component != null) { + Class type = rt.component.conduitType; + if (type == null) { + // broke a conector so drop any conduits with no connections as there + // is no other way to remove these + List cons = new ArrayList(te.getConduits()); + boolean droppedUnconected = false; + for (IConduit con : cons) { + if (con.getConduitConnections().isEmpty() && con.getExternalConnections().isEmpty()) { + te.removeConduit(con); + drop.add(con.createItem()); + droppedUnconected = true; + } + } + // If there isn't, then drop em all + if (!droppedUnconected) { + for (IConduit con : cons) { + te.removeConduit(con); + drop.add(con.createItem()); + } + } + } else { + IConduit con = te.getConduit(type); + te.removeConduit(con); + drop.add(con.createItem()); + + } + } + } + + breakBlock = te.getConduits().isEmpty() && !te.hasFacade(); + + if (!world.isRemote && !player.capabilities.isCreativeMode) { + for (ItemStack st : drop) { + ConduitUtil.dropItems(world, st, x, y, z); + } + } + + if (!breakBlock) { + world.markBlockForUpdate(x, y, z); + return false; + } + world.setBlockToAir(x, y, z); + return true; + } + + @Override + public void breakBlock(World world, int x, int y, int z, int par5, int par6) { + IConduitBundle te = (IConduitBundle) world.getBlockTileEntity(x, y, z); + if (te != null) { + te.onBlockRemoved(); + } + world.removeBlockTileEntity(x, y, z); + } + + @Override + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) { + + IConduitBundle bundle = (IConduitBundle) world.getBlockTileEntity(x, y, z); + if (bundle == null) { + return false; + } + + ItemStack stack = player.getCurrentEquippedItem(); + if (stack != null && stack.itemID == ModObject.itemConduitFacade.actualId && !bundle.hasFacade()) { + // Add facade + if (player.isSneaking()) { + return false; + } + + bundle.setFacadeId(PainterUtil.getSourceBlockId(player.getCurrentEquippedItem())); + bundle.setFacadeMetadata(PainterUtil.getSourceBlockMetadata(player.getCurrentEquippedItem())); + if (!player.capabilities.isCreativeMode) { + stack.stackSize--; + } + world.markBlockForUpdate(x, y, z); + world.updateTileEntityChunkAndDoNothing(x, y, z, bundle.getEntity()); + return true; + + } else if (ConduitUtil.isConduitEquipped(player)) { + // Add conduit + if (player.isSneaking()) { + return false; + } + + IConduitItem equipped = (IConduitItem) stack.getItem(); + if (!bundle.hasType(equipped.getBaseConduitType())) { + bundle.addConduit(equipped.createConduit(stack)); + if (!player.capabilities.isCreativeMode) { + player.getCurrentEquippedItem().stackSize--; + } + return true; + } + + } + + // Break conduit with tool + if (ConduitUtil.isToolEquipped(player) && player.isSneaking()) { + if (!world.isRemote) { + removeBlockByPlayer(world, player, x, y, z); + if (player.getCurrentEquippedItem().getItem() instanceof IToolWrench) { + ((IToolWrench) player.getCurrentEquippedItem().getItem()).wrenchUsed(player, x, y, z); + } + } + return true; + } + + // Check conduit defined actions + RaytraceResult res = doRayTrace(world, x, y, z, player); + + if(res != null && res.component != null && res.component.data instanceof ConduitConnectorType) { + //if its a connector pass the event on to all conduits + for(IConduit con : bundle.getConduits()) { + if(con.onBlockActivated(player, res)) { + world.updateTileEntityChunkAndDoNothing(x, y, z, bundle.getEntity()); + return true; + } + + } + return false; + } + + if (res == null || res.component == null || res.component.conduitType == null) { + // Nothing of interest hit + return false; + } + + // Conduit specific actions + if (bundle.getConduit(res.component.conduitType).onBlockActivated(player, res)) { + world.updateTileEntityChunkAndDoNothing(x, y, z, bundle.getEntity()); + return true; + } + return false; + + } + + @Override + public void onNeighborBlockChange(World world, int x, int y, int z, int blockId) { + TileEntity tile = world.getBlockTileEntity(x, y, z); + if ((tile instanceof IConduitBundle)) { + ((IConduitBundle) tile).onNeighborBlockChange(blockId); + } + } + + @Override + public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB axisalignedbb, @SuppressWarnings("rawtypes") List arraylist, + Entity par7Entity) { + + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return; + } + IConduitBundle con = (IConduitBundle) te; + if (con.getFacadeId() > 0) { + setBlockBounds(0, 0, 0, 1, 1, 1); + super.addCollisionBoxesToList(world, x, y, z, axisalignedbb, arraylist, par7Entity); + } else { + + Collection bounds = con.getCollidableComponents(); + for (CollidableComponent bnd : bounds) { + setBlockBounds(bnd.bound.minX, bnd.bound.minY, bnd.bound.minZ, bnd.bound.maxX, bnd.bound.maxY, bnd.bound.maxZ); + super.addCollisionBoxesToList(world, x, y, z, axisalignedbb, arraylist, par7Entity); + } + + if (con.getConduits().isEmpty()) { // just in case + setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + super.addCollisionBoxesToList(world, x, y, z, axisalignedbb, arraylist, par7Entity); + } + } + + setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + + } + + @Override + public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z) { + + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return null; + } + IConduitBundle con = (IConduitBundle) te; + + BoundingBox minBB = new BoundingBox(1, 1, 1, 0, 0, 0); + if (!ConduitUtil.renderFacade(con, EnderIO.proxy.getClientPlayer())) { + + Collection bounds = con.getCollidableComponents(); + for (CollidableComponent bnd : bounds) { + minBB = minBB.expandBy(bnd.bound); + } + + } else { + minBB = new BoundingBox(0, 0, 0, 1, 1, 1); + } + + if (!minBB.isValid()) { + minBB = new BoundingBox(0, 0, 0, 1, 1, 1); + } + + return AxisAlignedBB.getBoundingBox(x + minBB.minX, y + minBB.minY, + z + minBB.minZ, x + minBB.maxX, y + minBB.maxY, z + + minBB.maxZ); + } + + @Override + public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 origin, Vec3 direction) { + RaytraceResult raytraceResult = doRayTrace(world, x, y, z, origin, direction, null); + if (raytraceResult == null) { + return null; + } + + if (raytraceResult.movingObjectPosition != null) { + raytraceResult.movingObjectPosition.hitInfo = raytraceResult.component; + + } + return raytraceResult.movingObjectPosition; + } + + public RaytraceResult doRayTrace(World world, int x, int y, int z, EntityPlayer entityPlayer) { + double pitch = Math.toRadians(entityPlayer.rotationPitch); + double yaw = Math.toRadians(entityPlayer.rotationYaw); + + double dirX = -Math.sin(yaw) * Math.cos(pitch); + double dirY = -Math.sin(pitch); + double dirZ = Math.cos(yaw) * Math.cos(pitch); + + double reachDistance = 5; + + if (entityPlayer instanceof EntityPlayerMP) { + reachDistance = ((EntityPlayerMP) entityPlayer).theItemInWorldManager.getBlockReachDistance(); + } + + double posY = entityPlayer.posY + 1.62 - entityPlayer.yOffset; + if (!world.isRemote && entityPlayer.isSneaking()) { + posY -= 0.08; + } + Vec3 origin = Vec3.fakePool.getVecFromPool(entityPlayer.posX, posY, entityPlayer.posZ); + Vec3 direction = origin.addVector(dirX * reachDistance, dirY * reachDistance, dirZ * reachDistance); + RaytraceResult res = doRayTrace(world, x, y, z, origin, direction, entityPlayer); + return res; + } + + protected RaytraceResult doRayTrace(World world, int x, int y, int z, Vec3 origin, Vec3 direction, EntityPlayer player) { + + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return null; + } + IConduitBundle bundle = (IConduitBundle) te; + List hits = new ArrayList(); + + if (ConduitUtil.renderFacade(bundle, player)) { + setBlockBounds(0, 0, 0, 1, 1, 1); + MovingObjectPosition hitPos = super.collisionRayTrace(world, x, y, z, origin, direction); + if (hitPos != null) { + hits.add(new RaytraceResult(new CollidableComponent(null, BoundingBox.UNIT_CUBE, ForgeDirection.UNKNOWN, null), hitPos)); + } + } else { + + Collection components = bundle.getCollidableComponents(); + for (CollidableComponent component : components) { + setBlockBounds(component.bound.minX, component.bound.minY, component.bound.minZ, component.bound.maxX, component.bound.maxY, component.bound.maxZ); + MovingObjectPosition hitPos = super.collisionRayTrace(world, x, y, z, origin, direction); + if (hitPos != null) { + hits.add(new RaytraceResult(component, hitPos)); + } + } + + // safety to prevent unbreakable empty bundles in case of a bug + if (bundle.getConduits().isEmpty() && !ConduitUtil.isFacadeHidden(bundle, player)) { + setBlockBounds(0, 0, 0, 1, 1, 1); + MovingObjectPosition hitPos = super.collisionRayTrace(world, x, y, z, origin, direction); + if (hitPos != null) { + hits.add(new RaytraceResult(null, hitPos)); + } + } + } + + setBlockBounds(0, 0, 0, 1, 1, 1); + + return RaytraceResult.getClosestHit(origin, hits); + } + +} diff --git a/common/crazypants/enderio/conduit/ConduitRecipes.java b/common/crazypants/enderio/conduit/ConduitRecipes.java new file mode 100644 index 00000000..166009a2 --- /dev/null +++ b/common/crazypants/enderio/conduit/ConduitRecipes.java @@ -0,0 +1,41 @@ +package crazypants.enderio.conduit; + +import static crazypants.enderio.ModObject.*; +import net.minecraft.block.Block; +import net.minecraft.item.*; +import cpw.mods.fml.common.registry.GameRegistry; +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.facade.ItemConduitFacade.FacadePainterRecipe; +import crazypants.enderio.machine.MachineRecipeRegistry; +import crazypants.enderio.material.Alloy; + +public class ConduitRecipes { + + public static void addRecipes() { + ItemStack industialBinder = new ItemStack(itemIndustrialBinder.actualId, 1, 0); + //ItemStack glassPane = new ItemStack(Block.thinGlass, 1, 0); + ItemStack fusedQuartz = new ItemStack(ModObject.blockFusedQuartz.actualId, 1, 0); + + //Facade + GameRegistry.addShapedRecipe(new ItemStack(itemConduitFacade.actualId,1,0), "bbb", "b b", "bbb", 'b', industialBinder); + MachineRecipeRegistry.instance.registerRecipe(blockPainter.unlocalisedName, new FacadePainterRecipe()); + + //Liquids + GameRegistry.addShapedRecipe(new ItemStack(itemLiquidConduit.actualId,4,0), "bgb", "g g", "bgb", 'b', industialBinder, 'g', fusedQuartz); + + //Power + GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId,4,0), " b ", "bib", " b ", 'b', industialBinder, 'i', new ItemStack(Item.ingotIron)); + ItemStack activatedIron = new ItemStack(ModObject.itemAlloy.actualId,1,Alloy.ACTIVATED_IRON.ordinal()); + GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId,4,1), " b ", "bib", " b ", 'b', industialBinder, 'i', activatedIron); + GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId,4,2), " b ", "bib", " b ", 'b', industialBinder, 'i', new ItemStack(ModObject.itemAlloy.actualId,1,Alloy.ENDER_IRON.ordinal())); + + + //Redstone + ItemStack redstoneConduit = new ItemStack(itemRedstoneConduit.actualId,1,0); + GameRegistry.addShapedRecipe(redstoneConduit , " b ", "brb", " b ", 'b', industialBinder, 'r', new ItemStack(Item.redstone)); + GameRegistry.addShapedRecipe(new ItemStack(itemRedstoneConduit.actualId,1,1), " l ", "lcl", " l ", 'c', redstoneConduit, 'l', Block.lever); + + + } + +} diff --git a/common/crazypants/enderio/conduit/ConduitUtil.java b/common/crazypants/enderio/conduit/ConduitUtil.java new file mode 100644 index 00000000..b924b762 --- /dev/null +++ b/common/crazypants/enderio/conduit/ConduitUtil.java @@ -0,0 +1,196 @@ +package crazypants.enderio.conduit; + +import java.util.*; + +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.*; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.tools.IToolWrench; +import cpw.mods.fml.common.FMLCommonHandler; +import crazypants.enderio.EnderIO; +import crazypants.enderio.conduit.liquid.*; +import crazypants.enderio.conduit.power.*; +import crazypants.enderio.conduit.redstone.*; + +public class ConduitUtil { + + + public static final Random RANDOM = new Random(); + + + public static AbstractConduitNetwork createNetworkForType(Class type) { + if(IRedstoneConduit.class.isAssignableFrom(type)) { + return new RedstoneConduitNetwork(); + } else if(IPowerConduit.class.isAssignableFrom(type)) { + return new PowerConduitNetwork(); + } else if(ILiquidConduit.class.isAssignableFrom(type)) { + return new LiquidConduitNetwork(); + } + FMLCommonHandler.instance().raiseException(new Exception("Could not determine network type for class " + type), "ConduitUtil.createNetworkForType", false); + return null; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static void ensureValidNetwork(IConduit conduit) { + TileEntity te = conduit.getBundle().getEntity(); + World world = te.worldObj; + Collection connections = ConduitUtil.getConnectedConduits(world, te.xCoord, te.yCoord, te.zCoord, conduit.getBaseConduitType()); + + if (reuseNetwork(conduit, connections, world)) { + return; + } + + AbstractConduitNetwork res = createNetworkForType(conduit.getBaseConduitType()); + res.init(conduit.getBundle(), connections, world); + return; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static boolean reuseNetwork(IConduit con, Collection connections, World world) { + AbstractConduitNetwork network = null; + for (IConduit conduit : connections) { + if (network == null) { + network = conduit.getNetwork(); + } else if (network != conduit.getNetwork()) { + return false; + } + } + if (network == null) { + return false; + } + con.setNetwork(network); + network.addConduit(con); + network.notifyNetworkOfUpdate(); + return true; + } + + public static void dropConduit(World world, IConduit conduit, int x, int y, int z) { + dropItems(world, conduit.createItem(), x, y, z); + } + + public static void dropItems(World world, ItemStack stack, int x, int y, int z) { + if (stack.stackSize <= 0) { + return; + } + + 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); + } + + public static void dropItems(World world, IInventory inventory, int x, int y, int z) { + 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); + } + } + } + + public static boolean renderFacade(IConduitBundle bundle, EntityPlayer player) { + return bundle.getFacadeId() > 0 && !isFacadeHidden(bundle, player); + } + + public static boolean isFacadeHidden(IConduitBundle bundle, EntityPlayer player) { + return bundle.getFacadeId() > 0 && (isToolEquipped(player) || isConduitEquipped(player)); + } + + public static boolean isConduitEquipped(EntityPlayer player) { + player = player == null ? EnderIO.proxy.getClientPlayer() : player; + if(player == null) { + return false; + } + ItemStack equipped = player.getCurrentEquippedItem(); + if (equipped == null) { + return false; + } + return equipped.getItem() instanceof IConduitItem ; + } + + public static boolean isToolEquipped(EntityPlayer player) { + player = player == null ? EnderIO.proxy.getClientPlayer() : player; + if(player == null) { + return false; + } + ItemStack equipped = player.getCurrentEquippedItem(); + if (equipped == null) { + return false; + } + return /*equipped.itemID == Block.stone.blockID ||*/ equipped.getItem() instanceof IToolWrench; + } + + public static T getConduit(IBlockAccess world, int x, int y, int z, Class type) { + if(world == null) { + return null; + } + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof IConduitBundle) { + IConduitBundle con = (IConduitBundle) te; + return con.getConduit(type); + } + return null; + } + + public static T getConduit(IBlockAccess world, TileEntity te, ForgeDirection dir, Class type) { + return ConduitUtil.getConduit(world, te.xCoord + dir.offsetX, te.yCoord + dir.offsetY, te.zCoord + dir.offsetZ, type); + } + + public static Collection getConnectedConduits(IBlockAccess world, int x, int y, int z, Class type) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return Collections.emptyList(); + } + List result = new ArrayList(); + IConduitBundle root = (IConduitBundle) te; + for (ForgeDirection dir : root.getAllConnections()) { + T con = getConduit(world, root.getEntity(), dir, type); + if (con != null) { + result.add(con); + } + } + return result; + } + + public static void writeToNBT(IConduit conduit, NBTTagCompound conduitRoot) { + if (conduit == null) { + return; + } + + NBTTagCompound conduitBody = new NBTTagCompound(); + conduit.writeToNBT(conduitBody); + + conduitRoot.setString("conduitType", conduit.getClass().getCanonicalName()); + conduitRoot.setCompoundTag("conduit", conduitBody); + } + + public static IConduit readConduitFromNBT(NBTTagCompound conduitRoot) { + String typeName = conduitRoot.getString("conduitType"); + NBTTagCompound conduitBody = conduitRoot.getCompoundTag("conduit"); + if(typeName == null || conduitBody == null) { + return null; + } + IConduit result; + try { + result = (IConduit) Class.forName(typeName).newInstance(); + } catch (Exception e) { + throw new RuntimeException("Could not create an instance of the conduit with name: " + typeName, e); + } + result.readFromNBT(conduitBody); + return result; + + } + + + +} diff --git a/common/crazypants/enderio/conduit/IConduit.java b/common/crazypants/enderio/conduit/IConduit.java new file mode 100644 index 00000000..7163eeee --- /dev/null +++ b/common/crazypants/enderio/conduit/IConduit.java @@ -0,0 +1,103 @@ +package crazypants.enderio.conduit; + +import java.util.*; + +import crazypants.enderio.conduit.geom.*; +import crazypants.enderio.conduit.geom.CollidableCache.CacheKey; +import crazypants.util.BlockCoord; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Icon; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; + +public interface IConduit { + + // Base functionality + Class getBaseConduitType(); + + ItemStack createItem(); + + int getLightValue(); + + boolean isActive(); + + void setActive(boolean active); + + void writeToNBT(NBTTagCompound conduitBody); + + void readFromNBT(NBTTagCompound conduitBody); + + // Container + + void setBundle(IConduitBundle tileConduitBundle); + + IConduitBundle getBundle(); + + void onAddedToBundle(); + + void onRemovedFromBundle(); + + BlockCoord getLocation(); + + // Conduit Connections + + boolean canConnectToConduit(ForgeDirection direction, IConduit conduit); + + Set getConduitConnections(); + + boolean containsConduitConnection(ForgeDirection dir); + + void conduitConnectionAdded(ForgeDirection fromDirection); + + void conduitConnectionRemoved(ForgeDirection fromDirection); + + AbstractConduitNetwork getNetwork(); + + boolean setNetwork(AbstractConduitNetwork network); + + // External Connections + + boolean canConnectToExternal(ForgeDirection direction); + + Set getExternalConnections(); + + boolean containsExternalConnection(ForgeDirection dir); + + void externalConnectionAdded(ForgeDirection fromDirection); + + void externalConnectionRemoved(ForgeDirection fromDirection); + + boolean isConnectedTo(ForgeDirection dir); + + // rendering, only needed us default rendering is used + + Icon getTextureForState(CollidableComponent component); + + Icon getTransmitionTextureForState(CollidableComponent component); + + float getTransmitionGeometryScale(); + + float getSelfIlluminationForState(CollidableComponent component); + + // geometry + + boolean haveCollidablesChangedSinceLastCall(); + + Collection getCollidableComponents(); + + Collection createCollidables(CacheKey key); + + // Actions + + boolean onBlockActivated(EntityPlayer player, RaytraceResult res); + + void onChunkUnload(World worldObj); + + void updateEntity(World worldObj); + + boolean onNeighborBlockChange(int blockId); + +} diff --git a/common/crazypants/enderio/conduit/IConduitBundle.java b/common/crazypants/enderio/conduit/IConduitBundle.java new file mode 100644 index 00000000..32f270ca --- /dev/null +++ b/common/crazypants/enderio/conduit/IConduitBundle.java @@ -0,0 +1,68 @@ +package crazypants.enderio.conduit; + +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.conduit.geom.Offset; +import crazypants.enderio.power.IInternalPowerReceptor; + +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.IFluidHandler; +import buildcraft.api.power.IPowerReceptor; + +public interface IConduitBundle extends IInternalPowerReceptor, IFluidHandler { + + TileEntity getEntity(); + + //conduits + + boolean hasType(Class type); + + T getConduit(Class type); + + void addConduit(IConduit conduit); + + void removeConduit(IConduit conduit); + + Collection getConduits(); + + Offset getOffset(Class type, ForgeDirection dir); + + // connections + + Set getConnections(Class type); + + boolean containsConnection(Class type, ForgeDirection west); + + Set getAllConnections(); + + boolean containsConnection(ForgeDirection dir); + + // events + + void onNeighborBlockChange(int blockId); + + void onBlockRemoved(); + + // Facade + + boolean hasFacade(); + + void setFacadeId(int blockID); + + int getFacadeId(); + + void setFacadeMetadata(int meta); + + int getFacadeMetadata(); + + List getCollidableComponents(); + + List getConnectors(); + + void dirty(); + +} diff --git a/common/crazypants/enderio/conduit/IConduitItem.java b/common/crazypants/enderio/conduit/IConduitItem.java new file mode 100644 index 00000000..b36514da --- /dev/null +++ b/common/crazypants/enderio/conduit/IConduitItem.java @@ -0,0 +1,11 @@ +package crazypants.enderio.conduit; + +import net.minecraft.item.ItemStack; + +public interface IConduitItem { + + Class getBaseConduitType(); + + IConduit createConduit(ItemStack item); + +} diff --git a/common/crazypants/enderio/conduit/ItemConduitSubtype.java b/common/crazypants/enderio/conduit/ItemConduitSubtype.java new file mode 100644 index 00000000..6332c66e --- /dev/null +++ b/common/crazypants/enderio/conduit/ItemConduitSubtype.java @@ -0,0 +1,18 @@ +package crazypants.enderio.conduit; + +public class ItemConduitSubtype { + + public final String unlocalisedName; + + public final String uiName; + + public final String iconKey; + + public ItemConduitSubtype(String unlocalisedName, String uiName, String iconKey) { + super(); + this.unlocalisedName = unlocalisedName; + this.uiName = uiName; + this.iconKey = iconKey; + } + +} diff --git a/common/crazypants/enderio/conduit/RaytraceResult.java b/common/crazypants/enderio/conduit/RaytraceResult.java new file mode 100644 index 00000000..80c0a1e7 --- /dev/null +++ b/common/crazypants/enderio/conduit/RaytraceResult.java @@ -0,0 +1,38 @@ +package crazypants.enderio.conduit; + +import java.util.Collection; + +import crazypants.enderio.conduit.geom.CollidableComponent; + + +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; + +public class RaytraceResult { + + public static RaytraceResult getClosestHit(Vec3 origin, Collection candidates) { + double minLengthSquared = Double.POSITIVE_INFINITY; + RaytraceResult closest = null; + + for (RaytraceResult candidate : candidates) { + MovingObjectPosition hit = candidate.movingObjectPosition; + if (hit != null) { + double lengthSquared = hit.hitVec.squareDistanceTo(origin); + if (lengthSquared < minLengthSquared) { + minLengthSquared = lengthSquared; + closest = candidate; + } + } + } + return closest; + } + + public final CollidableComponent component; + public final MovingObjectPosition movingObjectPosition; + + public RaytraceResult(CollidableComponent component, MovingObjectPosition movingObjectPosition) { + this.component = component; + this.movingObjectPosition = movingObjectPosition; + } + +} diff --git a/common/crazypants/enderio/conduit/TileConduitBundle.java b/common/crazypants/enderio/conduit/TileConduitBundle.java new file mode 100644 index 00000000..c6528cb2 --- /dev/null +++ b/common/crazypants/enderio/conduit/TileConduitBundle.java @@ -0,0 +1,517 @@ +package crazypants.enderio.conduit; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import crazypants.enderio.EnderIO; +import crazypants.enderio.PacketHandler; +import crazypants.enderio.conduit.geom.CollidableCache; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.conduit.geom.ConduitConnectorType; +import crazypants.enderio.conduit.geom.ConduitGeometryUtil; +import crazypants.enderio.conduit.geom.Offset; +import crazypants.enderio.conduit.geom.Offsets; +import crazypants.enderio.conduit.liquid.ILiquidConduit; +import crazypants.enderio.conduit.power.IPowerConduit; +import crazypants.util.BlockCoord; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.network.packet.Packet; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import buildcraft.api.power.PowerHandler; +import buildcraft.api.power.PowerHandler.PowerReceiver; + +public class TileConduitBundle extends TileEntity implements IConduitBundle { + + + private final List conduits = new ArrayList(); + + private int facadeId = -1; + private int facadeMeta = 0; + + private boolean facadeChanged; + + private final List cachedCollidables = new ArrayList(); + + private boolean conduitsDirty = true; + private boolean collidablesDirty = true; + + public TileConduitBundle() { + blockType = EnderIO.blockConduitBundle; + } + + @Override + public void dirty() { + conduitsDirty = true; + collidablesDirty = true; + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + + NBTTagList conduitTags = new NBTTagList(); + for (IConduit conduit : conduits) { + NBTTagCompound conduitRoot = new NBTTagCompound(); + ConduitUtil.writeToNBT(conduit, conduitRoot); + conduitTags.appendTag(conduitRoot); + } + nbtRoot.setTag("conduits", conduitTags); + nbtRoot.setInteger("facadeId", facadeId); + nbtRoot.setInteger("facadeMeta", facadeMeta); + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + super.readFromNBT(nbtRoot); + + conduits.clear(); + NBTTagList conduitTags = nbtRoot.getTagList("conduits"); + for (int i = 0; i < conduitTags.tagCount(); i++) { + NBTTagCompound conduitTag = (NBTTagCompound) conduitTags.tagAt(i); + IConduit conduit = ConduitUtil.readConduitFromNBT(conduitTag); + if (conduit != null) { + conduit.setBundle(this); + conduits.add(conduit); + } + } + facadeId = nbtRoot.getInteger("facadeId"); + facadeMeta = nbtRoot.getInteger("facadeMeta"); + + } + + @Override + public boolean hasFacade() { + return facadeId > 0; + } + + @Override + public void setFacadeId(int blockID) { + this.facadeId = blockID; + facadeChanged = true; + } + + @Override + public int getFacadeId() { + return facadeId; + } + + @Override + public void setFacadeMetadata(int meta) { + facadeMeta = meta; + } + + @Override + public int getFacadeMetadata() { + return facadeMeta; + } + + @Override + public Packet getDescriptionPacket() { + return PacketHandler.getPacket(this); + } + + @Override + public void onChunkUnload() { + for (IConduit conduit : conduits) { + conduit.onChunkUnload(worldObj); + } + } + + @Override + public void updateEntity() { + for (IConduit conduit : conduits) { + conduit.updateEntity(worldObj); + } + + if(worldObj != null && !worldObj.isRemote && conduitsDirty) { + worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); + conduitsDirty = false; + } + + if(worldObj != null && facadeChanged) { + worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord); + facadeChanged = false; + } + } + + public BlockCoord getLocation() { + return new BlockCoord(xCoord, yCoord, zCoord); + } + + @Override + public void onNeighborBlockChange(int blockId) { + boolean needsUpdate = false; + for (IConduit conduit : conduits) { + needsUpdate |= conduit.onNeighborBlockChange(blockId); + } + if (needsUpdate) { + dirty(); + } + } + + @Override + public TileConduitBundle getEntity() { + return this; + } + + @Override + public boolean hasType(Class type) { + return getConduit(type) != null; + } + + @SuppressWarnings("unchecked") + @Override + public T getConduit(Class type) { + if (type == null) { + return null; + } + for (IConduit conduit : conduits) { + if (type.isInstance(conduit)) { + return (T) conduit; + } + } + return null; + } + + @Override + public void addConduit(IConduit conduit) { + if (worldObj.isRemote) { + return; + } + conduits.add(conduit); + conduit.setBundle(this); + conduit.onAddedToBundle(); + dirty(); + } + + @Override + public void removeConduit(IConduit conduit) { + if(conduit != null) { + removeConduit(conduit, true); + } + } + + public void removeConduit(IConduit conduit, boolean notify) { + if (worldObj.isRemote) { + return; + } + conduit.onRemovedFromBundle(); + conduits.remove(conduit); + conduit.setBundle(null); + if (notify) { + dirty(); + } + } + + @Override + public void onBlockRemoved() { + if (worldObj.isRemote) { + return; + } + List copy = new ArrayList(conduits); + for (IConduit con : copy) { + removeConduit(con, false); + } + dirty(); + } + + @Override + public Collection getConduits() { + return conduits; + } + + @Override + public Set getConnections(Class type) { + IConduit con = getConduit(type); + if (con != null) { + return con.getConduitConnections(); + } + return null; + } + + @Override + public boolean containsConnection(Class type, ForgeDirection dir) { + IConduit con = getConduit(type); + if (con != null) { + return con.containsConduitConnection(dir); + } + return false; + } + + @Override + public boolean containsConnection(ForgeDirection dir) { + for (IConduit con : conduits) { + if (con.containsConduitConnection(dir)) { + return true; + } + } + return false; + } + + @Override + public Set getAllConnections() { + Set result = new HashSet(); + for (IConduit con : conduits) { + result.addAll(con.getConduitConnections()); + } + return result; + } + + // Geometry + + @Override + public Offset getOffset(Class type, ForgeDirection dir) { + + if (getConnectionCount(dir) < 2) { + return Offset.NONE; + } + + if (dir == ForgeDirection.UNKNOWN) { + if (containsOnlySingleVerticalConnections()) { + return Offsets.get(type, true, false); + } + if (containsOnlySingleHorizontalConnections()) { + return Offsets.get(type, false, true); + } + return Offsets.get(type, true, true); + } + + boolean isVertical = dir == ForgeDirection.UP || dir == ForgeDirection.DOWN; + if (isVertical) { + return Offsets.get(type, false, true); + } + return Offsets.get(type, true, false); + } + + @Override + public List getCollidableComponents() { + + for(IConduit con : conduits) { + collidablesDirty = collidablesDirty || con.haveCollidablesChangedSinceLastCall(); + } + if(!collidablesDirty && !cachedCollidables.isEmpty()) { + return cachedCollidables; + } + cachedCollidables.clear(); + for (IConduit conduit : conduits) { + cachedCollidables.addAll(conduit.getCollidableComponents()); + } + + addConnectors(cachedCollidables); + + collidablesDirty = false; + + return cachedCollidables; + } + + @Override + public List getConnectors() { + List result = new ArrayList(); + addConnectors(result); + return result; + } + + private void addConnectors(List result) { + if (conduits.isEmpty()) { + return; + } + CollidableCache cc = CollidableCache.instance; + if (conduits.size() == 1) { + + IConduit con = conduits.get(0); + result.addAll(cc.getCollidables(cc.createKey(con.getBaseConduitType(), Offset.NONE, ForgeDirection.UNKNOWN, false), con)); + + } else if (containsOnlySingleVerticalConnections()) { + + if (allDirectionsHaveSameConnectionCount()) { + for (IConduit con : conduits) { + Class type = con.getBaseConduitType(); + result.addAll(cc.getCollidables(cc.createKey(type, getOffset(type, ForgeDirection.UNKNOWN), ForgeDirection.UNKNOWN, false), con)); + } + } else { + // vertical box + result.add(new CollidableComponent(null, ConduitGeometryUtil.instance.getBoundingBox(ConduitConnectorType.VERTICAL), ForgeDirection.UNKNOWN, ConduitConnectorType.VERTICAL)); + } + + } else if (containsOnlySingleHorizontalConnections()) { + + if (allDirectionsHaveSameConnectionCount()) { + for (IConduit con : conduits) { + Class type = con.getBaseConduitType(); + result.addAll(cc.getCollidables(cc.createKey(type, getOffset(type, ForgeDirection.UNKNOWN), ForgeDirection.UNKNOWN, false), con)); + } + + } else { + // vertical box + result + .add(new CollidableComponent(null, ConduitGeometryUtil.instance.getBoundingBox(ConduitConnectorType.HORIZONTAL), ForgeDirection.UNKNOWN, ConduitConnectorType.HORIZONTAL)); + } + } else { + result.add(new CollidableComponent(null, ConduitGeometryUtil.instance.getBoundingBox(ConduitConnectorType.BOTH), ForgeDirection.UNKNOWN, ConduitConnectorType.BOTH)); + } + + } + + private boolean containsOnlySingleVerticalConnections() { + return getConnectionCount(ForgeDirection.UP) < 2 && getConnectionCount(ForgeDirection.DOWN) < 2; + } + + private boolean containsOnlySingleHorizontalConnections() { + return getConnectionCount(ForgeDirection.WEST) < 2 && getConnectionCount(ForgeDirection.EAST) < 2 && + getConnectionCount(ForgeDirection.NORTH) < 2 && getConnectionCount(ForgeDirection.SOUTH) < 2; + } + + private boolean allDirectionsHaveSameConnectionCount() { + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + boolean hasCon = conduits.get(0).isConnectedTo(dir); + for (int i = 1; i < conduits.size(); i++) { + if (hasCon != conduits.get(i).isConnectedTo(dir)) { + return false; + } + } + } + return true; + } + + private boolean containsOnlyHorizontalConnections() { + for (IConduit con : conduits) { + for (ForgeDirection dir : con.getConduitConnections()) { + if (dir == ForgeDirection.UP || dir == ForgeDirection.DOWN) { + return false; + } + } + for (ForgeDirection dir : con.getExternalConnections()) { + if (dir == ForgeDirection.UP || dir == ForgeDirection.DOWN) { + return false; + } + } + } + return true; + } + + private int getConnectionCount(ForgeDirection dir) { + if(dir == ForgeDirection.UNKNOWN) { + return conduits.size(); + } + int result = 0; + for (IConduit con : conduits) { + if (con.containsConduitConnection(dir) || con.containsExternalConnection(dir)) { + result++; + } + } + return result; + } + + // ------------ Power ----------------------------- + + @Override + public void doWork(PowerHandler workProvider) { + IPowerConduit pc = getConduit(IPowerConduit.class); + if (pc != null) { + pc.doWork(workProvider); + } + } + + @Override + public PowerReceiver getPowerReceiver(ForgeDirection side) { + IPowerConduit pc = getConduit(IPowerConduit.class); + if (pc != null) { + return pc.getPowerReceiver(side); + } + return null; + } + + @Override + public PowerHandler getPowerHandler() { + IPowerConduit pc = getConduit(IPowerConduit.class); + if (pc != null) { + return pc.getPowerHandler(); + } + return null; + } + + @Override + public void applyPerdition() { + IPowerConduit pc = getConduit(IPowerConduit.class); + if (pc != null) { + pc.applyPerdition(); + } + + } + + @Override + public World getWorld() { + return worldObj; + } + + + + //------- Liquids ----------------------------- + + + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + ILiquidConduit lc = getConduit(ILiquidConduit.class); + if (lc != null) { + return lc.fill(from, resource, doFill); + } + return 0; + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + ILiquidConduit lc = getConduit(ILiquidConduit.class); + if (lc != null) { + return lc.drain(from, resource, doDrain); + } + return null; + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + ILiquidConduit lc = getConduit(ILiquidConduit.class); + if (lc != null) { + return lc.drain(from, maxDrain, doDrain); + } + return null; + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + ILiquidConduit lc = getConduit(ILiquidConduit.class); + if (lc != null) { + return lc.canFill(from, fluid); + } + return false; + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + ILiquidConduit lc = getConduit(ILiquidConduit.class); + if (lc != null) { + return lc.canDrain(from, fluid); + } + return false; + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + ILiquidConduit lc = getConduit(ILiquidConduit.class); + if (lc != null) { + return lc.getTankInfo(from); + } + return null; + } + + +} diff --git a/common/crazypants/enderio/conduit/facade/BlockConduitFacade.java b/common/crazypants/enderio/conduit/facade/BlockConduitFacade.java new file mode 100644 index 00000000..935dfcac --- /dev/null +++ b/common/crazypants/enderio/conduit/facade/BlockConduitFacade.java @@ -0,0 +1,100 @@ +package crazypants.enderio.conduit.facade; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.IConduitBundle; + +public class BlockConduitFacade extends Block { + + public static BlockConduitFacade create() { + BlockConduitFacade result = new BlockConduitFacade(); + result.init(); + return result; + } + + private BlockConduitFacade() { + super(ModObject.blockConduitFacade.id, Material.rock); + setHardness(0.5F); + setStepSound(Block.soundStoneFootstep); + setUnlocalizedName(ModObject.blockConduitFacade.unlocalisedName); + setCreativeTab(null); + } + + private void init() { + LanguageRegistry.addName(this, "Utility for Rendering DO NOT USE"); + GameRegistry.registerBlock(this, ModObject.blockConduitFacade.unlocalisedName); + } + + @Override + public void registerIcons(IconRegister iconRegister) { + blockIcon = iconRegister.registerIcon("enderio:conduitFacade"); + } + + @Override + @SideOnly(Side.CLIENT) + public Icon getBlockTexture(IBlockAccess ba, int x, int y, int z, int side) { + TileEntity te = ba.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + return blockIcon; + } + IConduitBundle cb = (IConduitBundle) te; + int id = cb.getFacadeId(); + int meta = cb.getFacadeMetadata(); + if (id <= 0 || id == blockID) { + return blockIcon; + } + return Block.blocksList[id].getIcon(side, meta); + } + + + @Override + public int getDamageValue(World par1World, int x, int y, int z) { + Mimic m = getMimic(par1World, x, y, z); + if (m != null) { + return m.meta; + } + return 0; + } + + private Mimic getMimic(IBlockAccess ba, int x, int y, int z) { + TileEntity te = ba.getBlockTileEntity(x, y, z); + if (!(te instanceof IConduitBundle)) { + // System.out.println("BlockConduitFacade.getMimic: Not a conduit bundle"); + return null; + } + IConduitBundle cb = (IConduitBundle) te; + int id = cb.getFacadeId(); + int meta = cb.getFacadeMetadata(); + + if(id <= 0) { + return null; + } + + return new Mimic(id, meta); + } + + class Mimic { + int id; + int meta; + Block block; + + private Mimic(int id, int meta) { + super(); + this.id = id; + this.meta = meta; + this.block = Block.blocksList[id]; + } + + } + +} diff --git a/common/crazypants/enderio/conduit/facade/FacadeRenderer.java b/common/crazypants/enderio/conduit/facade/FacadeRenderer.java new file mode 100644 index 00000000..de9333b0 --- /dev/null +++ b/common/crazypants/enderio/conduit/facade/FacadeRenderer.java @@ -0,0 +1,93 @@ +package crazypants.enderio.conduit.facade; + +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.item.ItemStack; +import net.minecraftforge.client.IItemRenderer; + +import org.lwjgl.opengl.GL11; + +import crazypants.enderio.EnderIO; +import crazypants.enderio.machine.painter.PainterUtil; +import crazypants.render.RenderUtil; + + +public class FacadeRenderer implements IItemRenderer { + + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED_FIRST_PERSON; + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + if (type == ItemRenderType.INVENTORY) { + RenderBlocks renderBlocks = (RenderBlocks) data[0]; + renderToInventory(item, renderBlocks); + } else if (type == ItemRenderType.EQUIPPED || type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + renderEquipped(item, (RenderBlocks) data[0]); + } else if (type == ItemRenderType.ENTITY) { + renderEntity(item, (RenderBlocks) data[0]); + } else { + System.out.println("FacadeRenderer.renderItem: Unsupported render type"); + } + } + + private void renderEntity(ItemStack item, RenderBlocks renderBlocks) { + GL11.glPushMatrix(); + GL11.glScalef(0.5f, 0.5f, 0.5f); + renderToInventory(item, renderBlocks); + GL11.glPopMatrix(); + } + + private void renderEquipped(ItemStack item, RenderBlocks renderBlocks) { + renderToInventory(item, renderBlocks); + } + + private void renderToInventory(ItemStack item, RenderBlocks renderBlocks) { + + Block block = PainterUtil.getSourceBlock(item); + if (block != null ) { + //Render the facade block + + RenderUtil.bindBlockTexture(); + renderBlocks.renderBlockAsItem(block, PainterUtil.getSourceBlockMetadata(item), 1.0F); + + //then the 'overlay' that marks it as a facade + //GL11.glDepthFunc(GL11.GL_ALWAYS); + GL11.glDepthFunc(GL11.GL_LEQUAL); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDepthMask(false); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL); + GL11.glPolygonOffset(-1.0f, -1.0f); + + + RenderUtil.bindItemTexture(); + renderBlocks.setOverrideBlockTexture(EnderIO.itemConduitFacade.getOverlayIcon()); + renderBlocks.renderBlockAsItem(block, item.getItemDamage(), 1.0F); + + GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL); + + renderBlocks.clearOverrideBlockTexture(); + GL11.glDisable(GL11.GL_BLEND); + GL11.glDepthMask(true); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDepthFunc(GL11.GL_LEQUAL); + + } else { + renderBlocks.setOverrideBlockTexture(EnderIO.itemConduitFacade.getIconFromDamage(0)); + renderBlocks.renderBlockAsItem(Block.stone, 0, 1.0F); + renderBlocks.clearOverrideBlockTexture(); + } + + } + +} diff --git a/common/crazypants/enderio/conduit/facade/ItemConduitFacade.java b/common/crazypants/enderio/conduit/facade/ItemConduitFacade.java new file mode 100644 index 00000000..e3721359 --- /dev/null +++ b/common/crazypants/enderio/conduit/facade/ItemConduitFacade.java @@ -0,0 +1,106 @@ +package crazypants.enderio.conduit.facade; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.*; +import net.minecraft.util.Icon; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import cpw.mods.fml.common.registry.*; +import cpw.mods.fml.relauncher.*; +import crazypants.enderio.*; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.machine.painter.*; + +public class ItemConduitFacade extends Item { + + public static ItemConduitFacade create() { + ItemConduitFacade result = new ItemConduitFacade(); + result.init(); + return result; + } + + protected Icon overlayIcon; + + protected ItemConduitFacade() { + super(ModObject.itemConduitFacade.id); + setCreativeTab(EnderIOTab.tabEnderIO); + setUnlocalizedName(ModObject.itemConduitFacade.unlocalisedName); + setMaxStackSize(64); + } + + protected void init() { + LanguageRegistry.addName(this, ModObject.itemConduitFacade.name); + GameRegistry.registerItem(this, ModObject.itemConduitFacade.unlocalisedName); + } + + @Override + public void registerIcons(IconRegister iconRegister) { + itemIcon = iconRegister.registerIcon("enderio:ConduitFacade"); + overlayIcon = iconRegister.registerIcon("enderio:conduitFacadeOverlay"); + } + + public Icon getOverlayIcon() { + return overlayIcon; + } + + @Override + public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float par8, + float par9, float par10) { + + if (world.isRemote) { + return true; + } + + ForgeDirection dir = ForgeDirection.values()[side]; + int placeX = x + dir.offsetX; + int placeY = y + dir.offsetY; + int placeZ = z + dir.offsetZ; + + if (player.canPlayerEdit(placeX, placeY, placeZ, side, itemStack) && world.isAirBlock(placeX, placeY, placeZ) + && PainterUtil.getSourceBlockId(itemStack) > 0) { + + world.setBlock(placeX, placeY, placeZ, EnderIO.blockConduitBundle.blockID); + IConduitBundle bundle = (IConduitBundle) world.getBlockTileEntity(placeX, placeY, placeZ); + bundle.setFacadeId(PainterUtil.getSourceBlockId(itemStack)); + bundle.setFacadeMetadata(PainterUtil.getSourceBlockMetadata(itemStack)); + if (!player.capabilities.isCreativeMode) { + itemStack.stackSize--; + } + return true; + } + + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean isFull3D() { + return true; + } + + @Override + public void onCreated(ItemStack itemStack, World world, EntityPlayer player) { + if (PainterUtil.getSourceBlock(itemStack) == null) { + PainterUtil.setSourceBlock(itemStack, ModObject.blockConduitFacade.id, 0); + } + } + + public ItemStack createItemStackForSourceBlock(int id, int itemDamage) { + if (id < 1) { + id = ModObject.blockConduitFacade.id; + } + ItemStack result = new ItemStack(itemID, 1, 0); + PainterUtil.setSourceBlock(result, id, itemDamage); + return result; + } + + public static final class FacadePainterRecipe extends BasicPainterTemplate { + + public FacadePainterRecipe() { + super(ModObject.itemConduitFacade.actualId); + } + + } + +} diff --git a/common/crazypants/enderio/conduit/geom/CollidableCache.java b/common/crazypants/enderio/conduit/geom/CollidableCache.java new file mode 100644 index 00000000..54fa6638 --- /dev/null +++ b/common/crazypants/enderio/conduit/geom/CollidableCache.java @@ -0,0 +1,83 @@ +package crazypants.enderio.conduit.geom; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import crazypants.enderio.conduit.IConduit; + +import net.minecraftforge.common.ForgeDirection; + +public class CollidableCache { + + public static final CollidableCache instance = new CollidableCache(); + + private final Map> cache = new HashMap>(); + + public CacheKey createKey(Class baseType, Offset offset, ForgeDirection dir, boolean isStub) { + return new CacheKey(baseType, offset, dir, isStub); + } + + public Collection getCollidables(CacheKey key, IConduit conduit) { + Collection result = cache.get(key); + if(result == null) { + result = conduit.createCollidables(key); + cache.put(key, result); + } + return result; + } + + + public static class CacheKey { + + public final Class baseType; + public final String className; //used to generate reliable equals / hashcode + public final Offset offset; + public final ForgeDirection dir; + public final boolean isStub; + + public CacheKey(Class baseType, Offset offset, ForgeDirection dir, boolean isStub) { + this.baseType = baseType; + className = baseType.getCanonicalName(); + this.offset = offset; + this.dir = dir; + this.isStub = isStub; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((className == null) ? 0 : className.hashCode()); + result = prime * result + ((dir == null) ? 0 : dir.hashCode()); + result = prime * result + (isStub ? 1231 : 1237); + result = prime * result + ((offset == null) ? 0 : offset.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CacheKey other = (CacheKey) obj; + if (className == null) { + if (other.className != null) + return false; + } else if (!className.equals(other.className)) + return false; + if (dir != other.dir) + return false; + if (isStub != other.isStub) + return false; + if (offset != other.offset) + return false; + return true; + } + + } + +} diff --git a/common/crazypants/enderio/conduit/geom/CollidableComponent.java b/common/crazypants/enderio/conduit/geom/CollidableComponent.java new file mode 100644 index 00000000..a97ee06a --- /dev/null +++ b/common/crazypants/enderio/conduit/geom/CollidableComponent.java @@ -0,0 +1,28 @@ +package crazypants.enderio.conduit.geom; + +import crazypants.enderio.conduit.IConduit; +import crazypants.render.BoundingBox; +import net.minecraftforge.common.ForgeDirection; + +public class CollidableComponent { + + public final Class conduitType; + public final BoundingBox bound; + public final ForgeDirection dir; + public final Object data; + + public CollidableComponent(Class conduitType, BoundingBox bound, ForgeDirection id,Object data) { + this.conduitType = conduitType; + this.bound = bound; + this.dir = id; + this.data = data; + } + + @Override + public String toString() { + return "CollidableComponent [conduitType=" + conduitType + ", bound=" + bound + ", id=" + dir + "]"; + } + + + +} diff --git a/common/crazypants/enderio/conduit/geom/ConduitConnectorType.java b/common/crazypants/enderio/conduit/geom/ConduitConnectorType.java new file mode 100644 index 00000000..002c5ed4 --- /dev/null +++ b/common/crazypants/enderio/conduit/geom/ConduitConnectorType.java @@ -0,0 +1,9 @@ +package crazypants.enderio.conduit.geom; + +public enum ConduitConnectorType { + + VERTICAL, + HORIZONTAL, + BOTH + +} diff --git a/common/crazypants/enderio/conduit/geom/ConduitGeometryUtil.java b/common/crazypants/enderio/conduit/geom/ConduitGeometryUtil.java new file mode 100644 index 00000000..0bf49d8b --- /dev/null +++ b/common/crazypants/enderio/conduit/geom/ConduitGeometryUtil.java @@ -0,0 +1,131 @@ +package crazypants.enderio.conduit.geom; + +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; + +import crazypants.enderio.conduit.IConduit; +import crazypants.render.BoundingBox; +import crazypants.vecmath.VecmathUtil; +import crazypants.vecmath.Vector3d; + +import net.minecraftforge.common.ForgeDirection; + +public class ConduitGeometryUtil { + + public static final ConduitGeometryUtil instance = new ConduitGeometryUtil(); + + public static final float STUB_WIDTH = 0.2f; + public static final float STUB_HEIGHT = 0.2f; + + public static final float WIDTH = 0.075f; + public static final float HEIGHT = 0.075f; + + public static final float HWIDTH = WIDTH / 2; + public static final float HHEIGHT = HEIGHT / 2; + + // All values are for a single conduit core + public static final Vector3d CORE_MIN = new Vector3d(0.5f - HWIDTH, 0.5 - HHEIGHT, 0.5 - HWIDTH); + public static final Vector3d CORE_MAX = new Vector3d(CORE_MIN.x + WIDTH, CORE_MIN.y + HEIGHT, CORE_MIN.z + WIDTH); + public static final BoundingBox CORE_BOUNDS = new BoundingBox(CORE_MIN, CORE_MAX); + + private Map boundsCache = new HashMap(); + + private EnumMap connectorBounds = new EnumMap(ConduitConnectorType.class); + + private ConduitGeometryUtil() { + + } + + public BoundingBox getBoundingBox(ConduitConnectorType type) { + BoundingBox result = connectorBounds.get(type); + if (result == null) { + result = createConnector(type); + result = result.scale(1.2f, 1.2f, 1.2f); + connectorBounds.put(type, result); + } + return result; + } + + private BoundingBox createConnector(ConduitConnectorType type) { + float distance = WIDTH + HWIDTH; + switch (type) { + case VERTICAL: + return new BoundingBox(0.5 - HWIDTH, 0.5 - distance, 0.5 - HWIDTH, 0.5 + HWIDTH, 0.5 + distance, 0.5 + HWIDTH); + case HORIZONTAL: + return new BoundingBox(0.5 - distance, 0.5 - HWIDTH, 0.5 - HWIDTH, 0.5 + distance, 0.5 + HWIDTH, 0.5 + HWIDTH); + case BOTH: + return createConnector(ConduitConnectorType.VERTICAL).expandBy(createConnector(ConduitConnectorType.HORIZONTAL)); + default: + return CORE_BOUNDS; + } + + } + + public BoundingBox getBoundingBox(Class type, ForgeDirection dir, boolean isStub, Offset offset) { + GeometryKey key = new GeometryKey(dir, isStub, offset, type); + BoundingBox result = boundsCache.get(key); + if (result == null) { + result = createConduitBounds(type, key); + boundsCache.put(key, result); + } + return result; + } + + public Vector3d getTranslation(ForgeDirection dir, Offset offset) { + Vector3d result = new Vector3d(offset.xOffset, offset.yOffset,0); + result.scale(WIDTH); + return result; + } + + private BoundingBox createConduitBounds(Class type, GeometryKey key) { + return createConduitBounds(type, key.dir, key.isStub, key.offset); + } + + private BoundingBox createConduitBounds(Class type, ForgeDirection dir, boolean isStub, Offset offset) { + BoundingBox bb = CORE_BOUNDS; +// if(type == IRedstoneConduit.class) { +// bb = bb.scale(0.5f, 0.5f, 0.5f); +// } + Vector3d min = bb.getMin(); + Vector3d max = bb.getMax(); + + switch (dir) { + case WEST: + min.x = isStub ? Math.max(0, bb.minX - STUB_WIDTH) : 0; + max.x = bb.minX; + break; + case EAST: + min.x = bb.maxX; + max.x = isStub ? Math.min(1, bb.maxX + STUB_WIDTH) : 1; + break; + case DOWN: + min.y = isStub ? Math.max(0, bb.minY - STUB_HEIGHT) : 0; + max.y = bb.minY; + break; + case UP: + max.y = isStub ? Math.min(1, bb.maxY + STUB_HEIGHT) : 1; + min.y = bb.maxY; + break; + case NORTH: + min.z = isStub ? Math.max(0.0F, bb.minZ - STUB_WIDTH) : 0; + max.z = bb.minZ; + break; + case SOUTH: + max.z = isStub ? Math.min(1F, bb.maxZ + STUB_WIDTH) : 1; + min.z = bb.maxZ; + break; + default: + break; + } + + Vector3d trans = getTranslation(dir, offset); + min.add(trans); + max.add(trans); + bb = new BoundingBox(VecmathUtil.clamp(min,0,1), VecmathUtil.clamp(max,0,1)); + return bb; + } + + + +} diff --git a/common/crazypants/enderio/conduit/geom/GeometryKey.java b/common/crazypants/enderio/conduit/geom/GeometryKey.java new file mode 100644 index 00000000..b3aaa151 --- /dev/null +++ b/common/crazypants/enderio/conduit/geom/GeometryKey.java @@ -0,0 +1,60 @@ +package crazypants.enderio.conduit.geom; + +import crazypants.enderio.conduit.IConduit; +import net.minecraftforge.common.ForgeDirection; + +public final class GeometryKey { + + public final ForgeDirection dir; + public final boolean isStub; + public final Offset offset; + public final String className; + + public GeometryKey(ForgeDirection dir, boolean isStub, Offset offset,Class type) { + this.dir = dir; + this.isStub = isStub; + this.offset = offset; + className = type != null ? type.getName() : null; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((className == null) ? 0 : className.hashCode()); + result = prime * result + ((dir == null) ? 0 : dir.hashCode()); + result = prime * result + (isStub ? 1231 : 1237); + result = prime * result + ((offset == null) ? 0 : offset.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + GeometryKey other = (GeometryKey) obj; + if (className == null) { + if (other.className != null) + return false; + } else if (!className.equals(other.className)) + return false; + if (dir != other.dir) + return false; + if (isStub != other.isStub) + return false; + if (offset != other.offset) + return false; + return true; + } + + + + + + + +} diff --git a/common/crazypants/enderio/conduit/geom/Offset.java b/common/crazypants/enderio/conduit/geom/Offset.java new file mode 100644 index 00000000..bc3e609c --- /dev/null +++ b/common/crazypants/enderio/conduit/geom/Offset.java @@ -0,0 +1,31 @@ +package crazypants.enderio.conduit.geom; + + + +/** + * Offset vectors are based on Y up. + * @author brad + */ +public enum Offset { + + NONE(0,0), + TOP(0,1), + BOTTOM(0,-1), + LEFT(-1,0), + RIGHT(1,0), + TL(-1,1), + TR(1,1), + BL(-1,-1), + BR(1,-1); + + public final int xOffset; + public final int yOffset; + + private Offset(int xOffset, int yOffset) { + this.xOffset = xOffset; + this.yOffset = yOffset; + } + +} + + diff --git a/common/crazypants/enderio/conduit/geom/Offsets.java b/common/crazypants/enderio/conduit/geom/Offsets.java new file mode 100644 index 00000000..735dc6ab --- /dev/null +++ b/common/crazypants/enderio/conduit/geom/Offsets.java @@ -0,0 +1,84 @@ +package crazypants.enderio.conduit.geom; + +import java.util.*; + +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.liquid.ILiquidConduit; +import crazypants.enderio.conduit.power.IPowerConduit; +import crazypants.enderio.conduit.redstone.IRedstoneConduit; + + +public class Offsets { + + private static Map OFFSETS = new HashMap(); + + static { + OFFSETS.put(key(IRedstoneConduit.class, true, false), Offset.BOTTOM); + OFFSETS.put(key(IPowerConduit.class, true, false), Offset.TOP); + OFFSETS.put(key(ILiquidConduit.class, true, false), Offset.NONE); + + OFFSETS.put(key(IRedstoneConduit.class, false, true), Offset.LEFT); + OFFSETS.put(key(IPowerConduit.class, false, true), Offset.RIGHT); + OFFSETS.put(key(ILiquidConduit.class, false, true), Offset.NONE); + + OFFSETS.put(key(IRedstoneConduit.class, true, true), Offset.BL); + OFFSETS.put(key(IPowerConduit.class, true, true), Offset.TR); + OFFSETS.put(key(ILiquidConduit.class, true, true), Offset.NONE); + } + + public static Offset get(Class type, boolean horizontal, boolean vertical) { + return OFFSETS.get(key(type,horizontal,vertical)); + } + + public static OffsetKey key(Class type, boolean horizontal, boolean vertical) { + return new OffsetKey(type, horizontal, vertical); + } + + public static class OffsetKey { + + String typeName; + boolean horizontal; + boolean vertical; + + private OffsetKey(Class type, boolean horizontal, boolean vertical) { + this.typeName = type.getCanonicalName(); + this.horizontal = horizontal; + this.vertical = vertical; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (horizontal ? 1231 : 1237); + result = prime * result + ((typeName == null) ? 0 : typeName.hashCode()); + result = prime * result + (vertical ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OffsetKey other = (OffsetKey) obj; + if (horizontal != other.horizontal) + return false; + if (typeName == null) { + if (other.typeName != null) + return false; + } else if (!typeName.equals(other.typeName)) + return false; + if (vertical != other.vertical) + return false; + return true; + } + + } + + + +} diff --git a/common/crazypants/enderio/conduit/liquid/ConduitTank.java b/common/crazypants/enderio/conduit/liquid/ConduitTank.java new file mode 100644 index 00000000..613ef186 --- /dev/null +++ b/common/crazypants/enderio/conduit/liquid/ConduitTank.java @@ -0,0 +1,183 @@ +package crazypants.enderio.conduit.liquid; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidTank; + +public class ConduitTank implements IFluidTank { + + private FluidStack fluid; + private int capacity; + private int tankPressure = 0; + + ConduitTank(int capacity) { + this.capacity = capacity; + } + + public int getFluidAmount() { + return fluid == null ? 0 : fluid.amount; + } + + public float getFilledRatio() { + if(getFluidAmount() <= 0) { + return 0; + } + if(getCapacity() <= 0) { + return -1; + } + return (float) getFluidAmount() / getCapacity(); + } + + public boolean isFull() { + return getFluidAmount() >= getCapacity(); + } + + public void setAmount(int amount) { + if(fluid != null) { + fluid.amount = amount; + } + } + + public int getAvailableSpace() { + return getCapacity() - getFluidAmount(); + } + + public void addAmount(int amount) { + setAmount(getFluidAmount() + amount); + } + + @Override + public FluidTankInfo getInfo() { + return new FluidTankInfo(this); + } + + + @Override + public FluidStack getFluid() { + return this.fluid; + } + + @Override + public int getCapacity() { + return this.capacity; + } + + public void setLiquid(FluidStack liquid) { + this.fluid = liquid; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + if (getFluidAmount() > capacity) { + setAmount(capacity); + } + } + + @Override + public int fill(FluidStack resource, boolean doFill) { + if (resource == null || resource.fluidID <= 0) { + return 0; + } + + if (fluid == null || fluid.fluidID <= 0) { + if (resource.amount <= capacity) { + if (doFill) { + fluid = resource.copy(); + } + return resource.amount; + } else { + if (doFill) { + fluid = resource.copy(); + fluid.amount = capacity; + } + return capacity; + } + } + + if (!fluid.isFluidEqual(resource)) { + return 0; + } + + int space = capacity - fluid.amount; + if (resource.amount <= space) { + if (doFill) { + fluid.amount += resource.amount; + } + return resource.amount; + } else { + if (doFill) { + fluid.amount = capacity; + } + return space; + } + + } + + @Override + public FluidStack drain(int maxDrain, boolean doDrain) { + if (fluid == null || fluid.fluidID <= 0) { + return null; + } + if (fluid.amount <= 0) { + return null; + } + + int used = maxDrain; + if (fluid.amount < used) { + used = fluid.amount; + } + + if (doDrain) { + fluid.amount -= used; + } + + FluidStack drained = new FluidStack(fluid.fluidID, used); + + if (fluid.amount < 0) { + fluid.amount = 0; + } + return drained; + } + + public void setTankPressure(int pressure) { + this.tankPressure = pressure; + } + + public String getLiquidName() { + return fluid != null ? FluidRegistry.getFluidName(fluid) : null; + } + + public boolean containsValidLiquid() { + return fluid != null && FluidRegistry.getFluidName(fluid) != null; + } + + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + if (containsValidLiquid()) { + fluid.writeToNBT(nbt); + } else { + nbt.setString("emptyTank", ""); + } + return nbt; + } + + public IFluidTank readFromNBT(NBTTagCompound nbt) { + if (!nbt.hasKey("emptyTank")) { + FluidStack liquid = FluidStack.loadFluidStackFromNBT(nbt); + if (liquid != null) { + setLiquid(liquid); + } + } + return this; + } + + public void remove(int amount) { + if(fluid == null) { + return; + } + fluid.amount -= amount; + fluid.amount = Math.max(0, fluid.amount); + } + +} diff --git a/common/crazypants/enderio/conduit/liquid/ILiquidConduit.java b/common/crazypants/enderio/conduit/liquid/ILiquidConduit.java new file mode 100644 index 00000000..edba3e0c --- /dev/null +++ b/common/crazypants/enderio/conduit/liquid/ILiquidConduit.java @@ -0,0 +1,31 @@ +package crazypants.enderio.conduit.liquid; + +import crazypants.enderio.conduit.IConduit; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidHandler; + +public interface ILiquidConduit extends IConduit, IFluidHandler { + + static final int VOLUME_PER_CONNECTION = FluidContainerRegistry.BUCKET_VOLUME/4; + + public static final String ICON_KEY ="enderio:liquidConduit"; + public static final String ICON_CORE_KEY ="enderio:liquidConduitCore"; + public static final String ICON_EXTRACT_KEY ="enderio:liquidConduitExtract"; + + void setFluidType(FluidStack fluidType); + + FluidStack getFluidType(); + + ConduitTank getTank(); + + IFluidHandler getExternalHandler(ForgeDirection direction); + + boolean canOutputToDir(ForgeDirection dir); + + boolean isExtractingFromDir(ForgeDirection dir); + + void setExtractingFromDir(ForgeDirection dir, boolean extracting); + +} diff --git a/common/crazypants/enderio/conduit/liquid/ItemLiquidConduit.java b/common/crazypants/enderio/conduit/liquid/ItemLiquidConduit.java new file mode 100644 index 00000000..4e4a0a30 --- /dev/null +++ b/common/crazypants/enderio/conduit/liquid/ItemLiquidConduit.java @@ -0,0 +1,36 @@ +package crazypants.enderio.conduit.liquid; + +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.AbstractItemConduit; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.ItemConduitSubtype; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.item.ItemStack; + +public class ItemLiquidConduit extends AbstractItemConduit { + + private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] { + new ItemConduitSubtype(ModObject.itemLiquidConduit.unlocalisedName, ModObject.itemLiquidConduit.name, "enderio:ItemLiquidConduit"), + }; + + public static ItemLiquidConduit create() { + ItemLiquidConduit result = new ItemLiquidConduit(); + result.init(subtypes); + return result; + } + + protected ItemLiquidConduit() { + super(ModObject.itemLiquidConduit); + } + + @Override + public Class getBaseConduitType() { + return ILiquidConduit.class; + } + + @Override + public IConduit createConduit(ItemStack stack) { + return new LiquidConduit(); + } + +} diff --git a/common/crazypants/enderio/conduit/liquid/LiquidConduit.java b/common/crazypants/enderio/conduit/liquid/LiquidConduit.java new file mode 100644 index 00000000..af10dedb --- /dev/null +++ b/common/crazypants/enderio/conduit/liquid/LiquidConduit.java @@ -0,0 +1,548 @@ +package crazypants.enderio.conduit.liquid; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.AbstractConduit; +import crazypants.enderio.conduit.AbstractConduitNetwork; +import crazypants.enderio.conduit.ConduitUtil; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.conduit.RaytraceResult; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.machine.reservoir.TileReservoir; +import crazypants.render.IconUtil; +import crazypants.util.BlockCoord; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChatMessageComponent; +import net.minecraft.util.Icon; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; + +public class LiquidConduit extends AbstractConduit implements ILiquidConduit { + + static final Map ICONS = new HashMap(); + + public static void initIcons() { + IconUtil.addIconProvider(new IconUtil.IIconProvider() { + + @Override + public void registerIcons(IconRegister register) { + ICONS.put(ICON_KEY, register.registerIcon(ICON_KEY)); + ICONS.put(ICON_CORE_KEY, register.registerIcon(ICON_CORE_KEY)); + ICONS.put(ICON_EXTRACT_KEY, register.registerIcon(ICON_EXTRACT_KEY)); + } + + @Override + public int getTextureType() { + return 0; + } + + }); + } + + private LiquidConduitNetwork network; + + private ConduitTank tank = new ConduitTank(0); + + private float lastSyncRatio = -99; + + private boolean pushing = false; + + private final Set extractDirs = new HashSet(); + + // ----------------------------- + + private long lastEmptyTick = 0; + private int numEmptyEvents = 0; + + private boolean stateDirty = false; + + private int maxDrainPerTick = 50; + + @Override + public boolean onBlockActivated(EntityPlayer player, RaytraceResult res) { + if (player.getCurrentEquippedItem() == null) { + return false; + } + if (ConduitUtil.isToolEquipped(player)) { + + if (!getBundle().getEntity().worldObj.isRemote) { + ForgeDirection faceHit = ForgeDirection.getOrientation(res.movingObjectPosition.sideHit); + if (res.component != null) { + ForgeDirection connDir = (ForgeDirection) res.component.dir; + + if (connDir == ForgeDirection.UNKNOWN || connDir == faceHit) { + // Attempt to join networls + ILiquidConduit neighbour = getFluidConduit(faceHit); + if (neighbour != null && LiquidConduitNetwork.areFluidsCompatable(getFluidType(), neighbour.getFluidType())) { + // kill the networks so a new one is formed combining then + if (neighbour.getNetwork() != null) { + neighbour.getNetwork().destroyNetwork(); + } + if (getNetwork() != null) { + getNetwork().destroyNetwork(); + } + // and join'm'up + neighbour.conduitConnectionAdded(faceHit.getOpposite()); + conduitConnectionAdded(faceHit); + } + } else if (containsExternalConnection(connDir)) { + // Toggle extraction mode + setExtractingFromDir(connDir, !isExtractingFromDir(connDir)); + } + } + + } else { + String str = player.worldObj.isRemote ? "[Client]" : "[Server]"; + System.out.println(str + + " LiquidConduit.onBlockActivated: Tank volume is: " + + tank.getCapacity() + " tank contains: " + tank.getFluidAmount() + + " filled ratio is: " + tank.getFilledRatio()); + } + return true; + + } else if (player.getCurrentEquippedItem().itemID == Item.bucketEmpty.itemID) { + + if (!getBundle().getEntity().worldObj.isRemote) { + long curTick = getBundle().getEntity().worldObj.getWorldTime(); + if (curTick - lastEmptyTick < 20) { + numEmptyEvents++; + } else { + numEmptyEvents = 1; + } + lastEmptyTick = curTick; + + if (numEmptyEvents < 2) { + tank.setAmount(0); + } else if (network != null) { + network.setFluidType(null); + numEmptyEvents = 0; + } + } + + return true; + } else { + + FluidStack fluid = FluidContainerRegistry.getFluidForFilledItem(player.getCurrentEquippedItem()); + if (fluid != null) { + if (!getBundle().getEntity().worldObj.isRemote) { + if (network != null && (network.getFluidType() == null || network.getTotalVolume() < 500)) { + network.setFluidType(fluid); + ChatMessageComponent c = ChatMessageComponent.func_111066_d("Fluid type set to " + FluidRegistry.getFluidName(fluid)); + player.sendChatToPlayer(c); + } + } + return true; + } + } + + return false; + } + + @Override + public void updateEntity(World world) { + super.updateEntity(world); + if (world.isRemote) { + return; + } + doExtract(); + // Limit these updates to prevent spamming during flow + if (stateDirty || (lastSyncRatio != tank.getFilledRatio() && world.getTotalWorldTime() % 2 == 0)) { + lastSyncRatio = tank.getFilledRatio(); + setActive(lastSyncRatio > 0); + getBundle().dirty(); + stateDirty = false; + } + } + + private void doExtract() { + + BlockCoord loc = getLocation(); + if (!getBundle().getEntity().worldObj.isBlockIndirectlyGettingPowered(loc.x, loc.y, loc.z)) { + return; + } + + for (ForgeDirection dir : extractDirs) { + IFluidHandler extTank = getTankContainer(getLocation().getLocation(dir)); + + int maxPush = tank.getFluidAmount(); + int couldPush = pushLiquid(dir, maxPush, false); + int targetExtract = Math.min(maxDrainPerTick, tank.getAvailableSpace() + couldPush); + FluidStack couldDrain = extTank.drain(dir.getOpposite(), targetExtract, false); + if (couldDrain != null && network != null && network.canAcceptLiquid(couldDrain)) { + couldDrain = extTank.drain(dir.getOpposite(), targetExtract, true); + if (couldDrain != null) { + FluidStack drained = couldDrain.copy(); + + int totalVolume = tank.getFluidAmount() + drained.amount; + int pushed = pushLiquid(dir, Math.min(drained.amount, maxPush), true); + // System.out.println("LiquidConduit.doExtract: Drained: " + + // drained.amount + " pushed = " + pushed + " contains volume " + + // tank.getAmount()); + drained.amount = totalVolume - pushed; + tank.setLiquid(drained); + } + } + } + + } + + @Override + public boolean canOutputToDir(ForgeDirection dir) { + // TODO: In/Out control on externals + if (conduitConnections.contains(dir)) { + return true; + } + if (!externalConnections.contains(dir)) { + return false; + } + if (isExtractingFromDir(dir)) { + return false; + } + IFluidHandler ext = getExternalHandler(dir); + if (ext instanceof TileReservoir) { // dont push to an auto ejecting + // resevoir or we loop + TileReservoir tr = (TileReservoir) ext; + return !tr.isMultiblock() || !tr.isAutoEject(); + } + return true; + } + + @Override + public boolean isExtractingFromDir(ForgeDirection dir) { + return extractDirs.contains(dir); + } + + @Override + public void setExtractingFromDir(ForgeDirection dir, boolean extracting) { + if (isExtractingFromDir(dir) == extracting) { + return; + } + if (!extracting) { + extractDirs.remove(dir); + } else { + extractDirs.add(dir); + } + stateDirty = true; + } + + @Override + public void externalConnectionRemoved(ForgeDirection fromDirection) { + super.externalConnectionRemoved(fromDirection); + setExtractingFromDir(fromDirection, false); + } + + @Override + public void setFluidType(FluidStack liquidType) { + if (tank.getFluid() != null && tank.getFluid().isFluidEqual(liquidType)) { + return; + } + if (liquidType != null) { + liquidType = liquidType.copy(); + } + tank.setLiquid(liquidType); + } + + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + if (network == null) { + return 0; + } + if (network.canAcceptLiquid(resource)) { + network.setFluidType(resource); + } else { + return 0; + } + int recieveAmount = resource == null ? 0 : resource.amount; + if (recieveAmount <= 0) { + return 0; + } + // int maxPush = Math.min(recieveAmount, tank.getFluidAmount()); + int maxPush = Math.max(0, recieveAmount + tank.getFluidAmount() - tank.getCapacity()); + + int pushedVolume = pushLiquid(from, maxPush, doFill); + if (doFill) { + tank.drain(pushedVolume, doFill); + return tank.fill(resource, doFill); + } else { + int amount = tank.getFluidAmount(); + tank.drain(pushedVolume, true); + int res = tank.fill(resource, false); + tank.setAmount(amount); + return res; + } + } + + private int pushLiquid(ForgeDirection from, int amount, boolean doPush) { + if (pushing || amount <= 0 || tank.getFluid() == null) { // avoid circular + // pushing + return 0; + } + + pushing = true; + int pushed = 0; + + try { + + Set cons = new HashSet(getConduitConnections()); + cons.addAll(getExternalConnections()); + cons.remove(from); + + if (cons.size() == 0) { + return pushed; + } + + int numToPushTo; + int amountPerCon; + List toRemove = new ArrayList(cons.size()); + FluidStack toPush = tank.getFluid().copy(); + do { + numToPushTo = cons.size(); + amountPerCon = amount / numToPushTo; + amountPerCon = Math.max(1, amountPerCon); + toPush.amount = amountPerCon; + for (ForgeDirection dir : cons) { + IFluidHandler con = getTankContainer(getLocation().getLocation(dir)); + // NB: Dont push liquid into a conduit that is fuller than yourself + ILiquidConduit conduitCon = getFluidConduit(dir); + if (con == null || !canOutputToDir(dir) || (conduitCon != null && conduitCon.getTank().getFilledRatio() > tank.getFilledRatio())) { + toRemove.add(dir); + } else { + int filled = con.fill(dir.getOpposite(), toPush, doPush); + if (filled < amountPerCon) { + toRemove.add(dir); + } + pushed += filled; + + } + toPush.amount = amountPerCon; + if (pushed >= amount) { + return amount; + } + } + for (ForgeDirection dir : toRemove) { + cons.remove(dir); + } + + } while (!cons.isEmpty() && pushed < amount); + + } finally { + pushing = false; + } + + return pushed; + } + + private ILiquidConduit getFluidConduit(ForgeDirection dir) { + TileEntity ent = getBundle().getEntity(); + return ConduitUtil.getConduit(ent.worldObj, ent, dir, ILiquidConduit.class); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tank.drain(maxDrain, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + if (resource != null && !resource.isFluidEqual(tank.getFluid())) { + return null; + } + return drain(from, resource.amount, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + if (tank.getFluid() == null) { + return true; + } + if (fluid != null && fluid.getID() == tank.getFluid().fluidID) { + return true; + } + return false; + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + if (tank.getFluid() == null || fluid == null) { + return false; + } + return tank.getFluid().getFluid().getID() == fluid.getID(); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return new FluidTankInfo[] { tank.getInfo() }; + } + + // ----------------------------- + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + if (tank.containsValidLiquid()) { + nbtRoot.setTag("tank", tank.getFluid().writeToNBT(new NBTTagCompound())); + } + + int[] dirs = new int[extractDirs.size()]; + Iterator cons = extractDirs.iterator(); + for (int i = 0; i < dirs.length; i++) { + dirs[i] = cons.next().ordinal(); + } + nbtRoot.setIntArray("extractDirs", dirs); + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + super.readFromNBT(nbtRoot); + updateTanksCapacity(); + FluidStack liquid = FluidStack.loadFluidStackFromNBT(nbtRoot.getCompoundTag("tank")); + tank.setLiquid(liquid); + + extractDirs.clear(); + int[] dirs = nbtRoot.getIntArray("extractDirs"); + for (int i = 0; i < dirs.length; i++) { + extractDirs.add(ForgeDirection.values()[dirs[i]]); + } + } + + @Override + protected void connectionsChanged() { + super.connectionsChanged(); + updateTanksCapacity(); + } + + @Override + public ConduitTank getTank() { + return tank; + } + + @Override + public Class getBaseConduitType() { + return ILiquidConduit.class; + } + + @Override + public ItemStack createItem() { + return new ItemStack(ModObject.itemLiquidConduit.actualId, 1, 0); + } + + @Override + public AbstractConduitNetwork getNetwork() { + return network; + } + + @Override + public boolean setNetwork(AbstractConduitNetwork network) { + if (network == null) { + this.network = null; + return true; + } + + LiquidConduitNetwork n = (LiquidConduitNetwork) network; + if (tank.getFluid() == null) { + tank.setLiquid(n.getFluidType() == null ? null : n.getFluidType().copy()); + } else if (n.getFluidType() == null) { + n.setFluidType(tank.getFluid()); + } else if (!tank.getFluid().isFluidEqual(n.getFluidType())) { + return false; + } + this.network = (LiquidConduitNetwork) network; + return true; + } + + @Override + public boolean canConnectToExternal(ForgeDirection direction) { + return getExternalHandler(direction) != null; + } + + @Override + public IFluidHandler getExternalHandler(ForgeDirection direction) { + IFluidHandler con = getTankContainer(getLocation().getLocation(direction)); + return (con != null && !(con instanceof IConduitBundle)) ? con : null; + } + + @Override + public boolean canConnectToConduit(ForgeDirection direction, IConduit con) { + if (!(con instanceof ILiquidConduit)) { + return false; + } + if (getFluidType() != null && ((ILiquidConduit) con).getFluidType() == null) { + return false; + } + return LiquidConduitNetwork.areFluidsCompatable(getFluidType(), ((ILiquidConduit) con).getFluidType()); + } + + @Override + public net.minecraftforge.fluids.FluidStack getFluidType() { + FluidStack result = null; + if (network != null) { + result = network.getFluidType(); + } + if (result == null) { + result = tank.getFluid(); + } + return result; + } + + @Override + public Icon getTextureForState(CollidableComponent component) { + if (component.dir == ForgeDirection.UNKNOWN) { + return ICONS.get(ICON_CORE_KEY); + } + if (isExtractingFromDir((ForgeDirection) component.dir)) { + return ICONS.get(ICON_EXTRACT_KEY); + } + return ICONS.get(ICON_KEY); + } + + @Override + public Icon getTransmitionTextureForState(CollidableComponent component) { + if (active && tank.getFluid() != null) { + return tank.getFluid().getFluid().getStillIcon(); + } + return null; + } + + @Override + public float getTransmitionGeometryScale() { + return tank.getFilledRatio(); + } + + private IFluidHandler getTankContainer(BlockCoord bc) { + return getTankContainer(bc.x, bc.y, bc.z); + } + + private IFluidHandler getTankContainer(int x, int y, int z) { + TileEntity te = getBundle().getEntity().worldObj.getBlockTileEntity(x, y, z); + if (te instanceof IFluidHandler) { + return (IFluidHandler) te; + } + return null; + } + + private void updateTanksCapacity() { + int totalConnections = getConduitConnections().size() + getExternalConnections().size(); + tank.setCapacity(totalConnections * VOLUME_PER_CONNECTION); + } + +} diff --git a/common/crazypants/enderio/conduit/liquid/LiquidConduitNetwork.java b/common/crazypants/enderio/conduit/liquid/LiquidConduitNetwork.java new file mode 100644 index 00000000..31ab6d09 --- /dev/null +++ b/common/crazypants/enderio/conduit/liquid/LiquidConduitNetwork.java @@ -0,0 +1,285 @@ +package crazypants.enderio.conduit.liquid; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import crazypants.enderio.conduit.AbstractConduitNetwork; +import crazypants.enderio.conduit.ConduitUtil; +import crazypants.enderio.conduit.IConduit; +import crazypants.util.BlockCoord; + +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidHandler; + +public class LiquidConduitNetwork extends AbstractConduitNetwork { + + private FluidStack liquidType; + private long timeAtLastApply; + + private int maxFlowsPerTick = 10; + private int lastFlowIndex = 0; + + private boolean printFlowTiming = false; + + @Override + public Class getBaseConduitType() { + return ILiquidConduit.class; + } + + public FluidStack getFluidType() { + return liquidType; + } + + @Override + public void addConduit(ILiquidConduit con) { + super.addConduit(con); + con.setFluidType(liquidType); + } + + public void setFluidType(FluidStack newType) { + if (liquidType != null && liquidType.isFluidEqual(newType)) { + return; + } + if (newType != null) { + liquidType = newType.copy(); + liquidType.amount = 0; + } else { + liquidType = null; + } + for (ILiquidConduit conduit : conduits) { + conduit.setFluidType(liquidType); + } + } + + public boolean canAcceptLiquid(FluidStack acceptable) { + return areFluidsCompatable(liquidType, acceptable); + } + + public static boolean areFluidsCompatable(FluidStack a, FluidStack b) { + if (a == null || b == null) { + return true; + } + return a.isFluidEqual(b); + } + + public int getTotalVolume() { + int totalVolume = 0; + for (ILiquidConduit con : conduits) { + totalVolume += con.getTank().getFluidAmount(); + } + return totalVolume; + } + + @Override + public void onUpdateEntity(IConduit conduit) { + World world = conduit.getBundle().getEntity().worldObj; + if (world == null) { + return; + } + if (world.isRemote || liquidType == null) { + return; + } + + long curTime = world.getTotalWorldTime(); + if (curTime != timeAtLastApply) { + timeAtLastApply = curTime; + // 1000 water, 6000 lava + if (liquidType != null && liquidType.getFluid() != null) { + int visc = liquidType.getFluid().getViscosity(); + if (curTime % (visc / 500) == 0) { + long start = System.nanoTime(); + if (doFlow() && printFlowTiming) { + long took = System.nanoTime() - start; + double secs = took / 1000000000.0; + System.out.println("LiquidConduitNetwork.onUpdateEntity: took " + secs + " secs, " + (secs * 1000) + " millis"); + } + } + } + } + } + + private boolean doFlow() { + + // int preVol = 0; + // for (ILiquidConduit con : conduits) { + // preVol += con.getTank().getAmount(); + // } + + List actions = new ArrayList(); + for (int i = 0; i < Math.min(maxFlowsPerTick, conduits.size()); i++) { + + if (lastFlowIndex >= conduits.size()) { + lastFlowIndex = 0; + } + flowFrom(conduits.get(lastFlowIndex), actions); + ++lastFlowIndex; + + } + for (FlowAction action : actions) { + action.apply(); + } + + // int postVol = 0; + // for (ILiquidConduit con : conduits) { + // postVol += con.getTank().getAmount(); + // } + // if (preVol != postVol) { + // System.out.println("LiquidConduitNetwork.doFlow: net change of: " + + // (postVol - preVol)); + // } + + return !actions.isEmpty(); + } + + private void flowFrom(ILiquidConduit con, List actions) { + + ConduitTank tank = con.getTank(); + int totalAmount = tank.getFluidAmount(); + if (totalAmount <= 0) { + return; + } + + int maxFlowVolume = 20; + + // First flow all we can down, then balance the rest + if (con.getConduitConnections().contains(ForgeDirection.DOWN)) { + BlockCoord loc = con.getLocation().getLocation(ForgeDirection.DOWN); + ILiquidConduit downCon = ConduitUtil.getConduit(con.getBundle().getEntity().worldObj, loc.x, loc.y, loc.z, ILiquidConduit.class); + int filled = downCon.fill(ForgeDirection.UP, tank.getFluid().copy(), false); + tank.addAmount(-filled); + downCon.getTank().addAmount(filled); + } + + totalAmount = tank.getFluidAmount(); + if (totalAmount <= 0) { + return; + } + FluidStack available = tank.getFluid(); + int totalRequested = 0; + int numRequests = 0; + // Then to external connections + for (ForgeDirection dir : con.getExternalConnections()) { + if (con.canOutputToDir(dir)) { + IFluidHandler extCon = con.getExternalHandler(dir); + if (extCon != null) { + int amount = extCon.fill(dir.getOpposite(), available.copy(), false); + if (amount > 0) { + totalRequested += amount; + numRequests++; + } + } + } + } + + if (numRequests > 0) { + int amountPerRequest = Math.min(totalAmount, totalRequested) / numRequests; + + // ----- + amountPerRequest = Math.min(maxFlowVolume, amountPerRequest); + // ---- + + FluidStack requestSource = available.copy(); + requestSource.amount = amountPerRequest; + for (ForgeDirection dir : con.getExternalConnections()) { + if (con.canOutputToDir(dir)) { + IFluidHandler extCon = con.getExternalHandler(dir); + if (extCon != null) { + int amount = extCon.fill(dir.getOpposite(), requestSource.copy(), true); + if (amount > 0) { + tank.addAmount(-amount); + } + } + } + } + } + + // TODO: Liquid can currently flow upwards from a down connection + + totalAmount = tank.getFluidAmount(); + if (totalAmount <= 0) { + return; + } + int totalCapacity = tank.getCapacity(); + + BlockCoord loc = con.getLocation(); + Collection connections = + ConduitUtil.getConnectedConduits(con.getBundle().getEntity().worldObj, + loc.x, loc.y, loc.z, ILiquidConduit.class); + int numTargets = 0; + for (ILiquidConduit neighbour : connections) { + if (canFlowTo(con, neighbour)) { // can only flow within same network + totalAmount += neighbour.getTank().getFluidAmount(); + totalCapacity += neighbour.getTank().getCapacity(); + numTargets++; + } + } + + float targetRatio = (float) totalAmount / totalCapacity; + int netChange = 0; + int flowVolume = Math.round((targetRatio - tank.getFilledRatio()) * tank.getCapacity()); + + // ----- + flowVolume = Math.min(maxFlowVolume, flowVolume); + // ---- + + if (Math.abs(flowVolume) < 2) { + return; // dont bother with transfers of less than a thousands of a bucket + } + + netChange += flowVolume; + actions.add(new FlowAction(con, flowVolume)); + for (ILiquidConduit neigbour : connections) { + if (canFlowTo(con, neigbour)) { // can only flow within same network + flowVolume = Math.round((targetRatio - neigbour.getTank().getFilledRatio()) * neigbour.getTank().getCapacity()); + if (flowVolume != 0) { + actions.add(new FlowAction(neigbour, flowVolume)); + netChange += flowVolume; + } + } + } + + if (netChange != 0) { + actions.add(new FlowAction(con, -netChange)); + } + } + + private boolean canFlowTo(ILiquidConduit con, ILiquidConduit neighbour) { + if (neighbour.getNetwork() != this) { + return false; + } + if (neighbour.getLocation().y > con.getLocation().y) { + return false; + } + float nr = neighbour.getTank().getFilledRatio(); + if (nr >= con.getTank().getFilledRatio()) { + return false; + } + return true; + } + + static class FlowAction { + ILiquidConduit con; + int amount; + + FlowAction(ILiquidConduit con, int amount) { + this.con = con; + this.amount = amount; + } + + void apply() { + if (amount != 0) { + // int preFlow = con.getTank().getAmount(); + con.getTank().addAmount(amount); + // System.out.println("LiquidConduitNetwork.FlowAction.apply: Con " + + // con.getLocation() + " went from " + preFlow + " to " + + // con.getTank().getAmount() + // + " with transfer amount " + amount); + } + } + + } + +} diff --git a/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java b/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java new file mode 100644 index 00000000..96641769 --- /dev/null +++ b/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java @@ -0,0 +1,118 @@ +package crazypants.enderio.conduit.liquid; + +import static crazypants.render.CubeRenderer.setupVertices; +import crazypants.enderio.conduit.*; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.conduit.render.*; +import crazypants.render.BoundingBox; +import crazypants.vecmath.Vector3d; + +import net.minecraft.util.Icon; +import net.minecraftforge.common.ForgeDirection; + +public class LiquidConduitRenderer extends DefaultConduitRenderer { + + private float downRatio; + + private float flatRatio; + + private float upRatio; + + @Override + public boolean isRendererForConduit(IConduit conduit) { + if (conduit instanceof ILiquidConduit) { + return true; + } + return false; + } + + @Override + public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x, double y, double z, float partialTick, + float worldLight) { + calculateRatios((ILiquidConduit) conduit); + super.renderEntity(conduitBundleRenderer, te, conduit, x, y, z, partialTick, worldLight); + } + + protected void renderConduit(Icon tex, CollidableComponent component) { + if (isNSEWUP(component.dir)) { + BoundingBox[] cubes = toCubes(component.bound); + for (BoundingBox cube : cubes) { + drawSection(cube, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, false); + } + } else { + drawSection(component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true); + } + } + + protected void renderTransmission(Icon tex, CollidableComponent component) { + BoundingBox[] cubes = toCubes(component.bound); + for (BoundingBox cube : cubes) { + drawSection(cube, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true); + } + } + + @Override + protected void setVerticesForTransmission(BoundingBox bound, ForgeDirection id) { + + float yScale = getRatioForConnection(id); + + float xs = ((ForgeDirection) id).offsetX == 0 ? 0.9f : 1; + float ys = ((ForgeDirection) id).offsetY == 0 ? Math.min(yScale, 0.9f) : yScale; + float zs = ((ForgeDirection) id).offsetZ == 0 ? 0.9f : 1; + + float sizeY = bound.sizeY(); + bound = bound.scale(xs, ys, zs); + float transY = (bound.sizeY() - sizeY) / 2; + + Vector3d translation = new Vector3d(0, transY, 0); + setupVertices(bound.translate(translation)); + } + + private void calculateRatios(ILiquidConduit conduit) { + ConduitTank tank = conduit.getTank(); + int totalAmount = tank.getFluidAmount(); + + int upCapacity = 0; + if (conduit.containsConduitConnection(ForgeDirection.UP) || conduit.containsExternalConnection(ForgeDirection.UP)) { + upCapacity = ILiquidConduit.VOLUME_PER_CONNECTION; + } + int downCapacity = 0; + if (conduit.containsConduitConnection(ForgeDirection.DOWN) || conduit.containsExternalConnection(ForgeDirection.DOWN)) { + downCapacity = ILiquidConduit.VOLUME_PER_CONNECTION; + } + + int flatCapacity = tank.getCapacity() - upCapacity - downCapacity; + + int usedCapacity = 0; + if (downCapacity > 0) { + int inDown = Math.min(totalAmount, downCapacity); + usedCapacity += inDown; + downRatio = (float) inDown / downCapacity; + } + if (flatCapacity > 0 && usedCapacity < totalAmount) { + int inFlat = Math.min(flatCapacity, totalAmount - usedCapacity); + usedCapacity += inFlat; + flatRatio = (float) inFlat / flatCapacity; + } else { + flatRatio = 0; + } + if (upCapacity > 0 && usedCapacity < totalAmount) { + int inUp = Math.min(upCapacity, totalAmount - usedCapacity); + upRatio = (float) inUp / upCapacity; + } else { + upRatio = 0; + } + + } + + private float getRatioForConnection(ForgeDirection id) { + if (id == ForgeDirection.UP) { + return upRatio; + } + if (id == ForgeDirection.DOWN) { + return downRatio; + } + return flatRatio; + } + +} diff --git a/common/crazypants/enderio/conduit/power/IPowerConduit.java b/common/crazypants/enderio/conduit/power/IPowerConduit.java new file mode 100644 index 00000000..7c65d48a --- /dev/null +++ b/common/crazypants/enderio/conduit/power/IPowerConduit.java @@ -0,0 +1,23 @@ +package crazypants.enderio.conduit.power; + +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.power.ICapacitor; +import crazypants.enderio.power.IInternalPowerReceptor; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.power.IPowerReceptor; + +public interface IPowerConduit extends IConduit, IInternalPowerReceptor { + + public static final String ICON_KEY ="enderio:powerConduit"; + public static final String ICON_CORE_KEY ="enderio:powerConduitCore"; + public static final String ICON_TRANSMISSION_KEY = "enderio:powerConduitTransmission"; + + IPowerReceptor getExternalPowerReceptor(ForgeDirection direction); + + ICapacitor getCapacitor(); + + float getEnergyStored(); + + void setEnergyStored(float energyStored); + +} diff --git a/common/crazypants/enderio/conduit/power/ItemPowerConduit.java b/common/crazypants/enderio/conduit/power/ItemPowerConduit.java new file mode 100644 index 00000000..0fd02d5c --- /dev/null +++ b/common/crazypants/enderio/conduit/power/ItemPowerConduit.java @@ -0,0 +1,53 @@ +package crazypants.enderio.conduit.power; + +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.AbstractItemConduit; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.ItemConduitSubtype; +import crazypants.enderio.power.ICapacitor; + +public class ItemPowerConduit extends AbstractItemConduit { + + static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] { + new ItemConduitSubtype(ModObject.itemPowerConduit.unlocalisedName, ModObject.itemPowerConduit.name, "enderio:itemPowerConduit"), + new ItemConduitSubtype(ModObject.itemPowerConduit.unlocalisedName + "Enhanced", "Enhanced " + ModObject.itemPowerConduit.name, "enderio:itemPowerConduitEnhanced"), + new ItemConduitSubtype(ModObject.itemPowerConduit.unlocalisedName + "Ender", "Ender " + ModObject.itemPowerConduit.name, "enderio:itemPowerConduitEnder") + }; + + public static ItemPowerConduit create() { + ItemPowerConduit result = new ItemPowerConduit(); + result.init(subtypes); + return result; + } + + protected ItemPowerConduit() { + super(ModObject.itemPowerConduit); + } + + @Override + public Class getBaseConduitType() { + return IPowerConduit.class; + } + + @Override + public IConduit createConduit(ItemStack stack) { + return new PowerConduit(stack.getItemDamage()); + } + + @Override + @SideOnly(Side.CLIENT) + public void addInformation(ItemStack itemStack, EntityPlayer par2EntityPlayer, List list, boolean par4) { + super.addInformation(itemStack, par2EntityPlayer, list, par4); + ICapacitor cap = PowerConduit.CAPACITORS[itemStack.getItemDamage()]; + list.add(String.format("I/O %d MJ/t", cap.getMaxEnergyExtracted())); + list.add(String.format("Storage %d MJ", cap.getMaxEnergyStored())); + } + + +} diff --git a/common/crazypants/enderio/conduit/power/NetworkPowerManager.java b/common/crazypants/enderio/conduit/power/NetworkPowerManager.java new file mode 100644 index 00000000..eea92f16 --- /dev/null +++ b/common/crazypants/enderio/conduit/power/NetworkPowerManager.java @@ -0,0 +1,251 @@ +package crazypants.enderio.conduit.power; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + +import crazypants.enderio.conduit.power.PowerConduitNetwork.ReceptorEntry; +import crazypants.enderio.power.IInternalPowerReceptor; +import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.util.BlockCoord; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; + +public class NetworkPowerManager { + + private PowerConduitNetwork network; + + private int maxEnergyStored; + private float energyStored; + private float reserved; + + private int updateRenderTicks = 10; + private int inactiveTicks = 100; + + private final List receptors = new ArrayList(); + private ListIterator receptorIterator = receptors.listIterator(); + + private boolean lastActiveValue = false; + private int ticksWithNoPower = 0; + + private final Map starveBuffers = new HashMap(); + + public NetworkPowerManager(PowerConduitNetwork netowrk, World world) { + this.network = netowrk; + maxEnergyStored = 64; + } + + + public float addEnergy(float quantity) { + float used = quantity; + energyStored += quantity; + if (energyStored > maxEnergyStored) { + used -= energyStored - maxEnergyStored; + energyStored = maxEnergyStored; + } else if (energyStored < 0) { + used -= energyStored; + energyStored = 0; + } + updateConduitStorage(); + return used; + } + + public void applyRecievedPower() { + + updateStorage(); + + float extracted = extractRecievedEnergy(); + addEnergy(extracted); + checkReserves(); + float quantity = energyStored; + boolean active; + if (quantity > 0) { + ticksWithNoPower = 0; + active = true; + } else { + ticksWithNoPower++; + active = false; + } + + boolean doRender = active != lastActiveValue && (active || (!active && ticksWithNoPower > updateRenderTicks)); + + if (doRender) { + lastActiveValue = active; + for (IPowerConduit con : network.getConduits()) { + con.setActive(active); + } + } + + if (quantity <= 0 || receptors.isEmpty()) { + return; + } + + + int appliedCount = 0; + int numReceptors = receptors.size(); + int numEngines = 0; + while (quantity > 0 && appliedCount < numReceptors) { + + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { + receptorIterator = receptors.listIterator(); + } + + ReceptorEntry r = receptorIterator.next(); + float reservedForEntry = removeReservedEnergy(r); + + for (ForgeDirection dir : r.directions) { + + PowerReceiver pp = r.powerReceptor.getPowerReceiver(dir); + if(pp != null) { + if(pp.getType() != Type.ENGINE) { + + float used = 0; + float nonReservedPower = quantity - reserved; + float available = nonReservedPower + reservedForEntry; + float canOffer = Math.min(r.emmiter.getCapacitor().getMaxEnergyExtracted(),available); + float requested = pp.powerRequest(); + + //If it is possible to supply the minimum amount of energy + if(pp.getMinEnergyReceived() <= r.emmiter.getCapacitor().getMaxEnergyExtracted()) { + //Buffer energy if we can't meet it now + if(pp.getMinEnergyReceived() > canOffer && requested > 0) { + reserveEnergy(r, canOffer); + used += canOffer; + } else if (r.powerReceptor instanceof IInternalPowerReceptor) { + used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) r.powerReceptor, pp, canOffer, Type.PIPE, dir); + } else { + used = pp.receiveEnergy(Type.PIPE, Math.min(requested, canOffer), dir); + } + + } + quantity -= used; + + } else if(pp.getType() == Type.ENGINE && !(r.powerReceptor instanceof IInternalPowerReceptor)) { + numEngines++; + } + + if(quantity <= 0) { + break; + } + + } + } + appliedCount++; + } + float leaveForBlowingUpEngines = numEngines * 8; + if(leaveForBlowingUpEngines > maxEnergyStored) { + leaveForBlowingUpEngines = maxEnergyStored; + } + energyStored = Math.min(quantity, maxEnergyStored - leaveForBlowingUpEngines); + updateConduitStorage(); + } + + private float removeReservedEnergy(ReceptorEntry r) { + StarveBuffer starveBuf = starveBuffers.remove(r.coord); + if(starveBuf == null) { + return 0; + } + float result = starveBuf.stored; + reserved -= result; + return result; + } + + private void reserveEnergy(ReceptorEntry r, float amount) { + starveBuffers.put(r.coord, new StarveBuffer(amount)); + reserved += amount; + } + + private void checkReserves() { + if(reserved > maxEnergyStored * 0.9) { + starveBuffers.clear(); + reserved = 0; + } + } + + + private void updateConduitStorage() { + float energyLeft = energyStored; + for(IPowerConduit con : network.getConduits()) { + float give = con.getCapacitor().getMaxEnergyStored(); + if(give > energyLeft) { + give = energyLeft; + } + con.setEnergyStored(give); + energyLeft -= give; + } + } + + + boolean isActive() { + return energyStored > 0; + } + + private void updateStorage() { + maxEnergyStored = 0; + energyStored = 0; + for(IPowerConduit con : network.getConduits()) { + maxEnergyStored += con.getCapacitor().getMaxEnergyStored(); + energyStored += con.getEnergyStored(); + } + if(energyStored > maxEnergyStored) { + energyStored = maxEnergyStored; + } + + } + + private float extractRecievedEnergy() { + float extracted = 0; + for(IPowerConduit conduit : network.getConduits()) { + PowerHandler ph = conduit.getPowerHandler(); + extracted += ph.getEnergyStored(); + ph.update(); + ph.setEnergy(0); + } + return extracted; + } + + public void receptorsChanged() { + receptors.clear(); + receptors.addAll(network.getPowerReceptors()); + receptorIterator = receptors.listIterator(); + } + + + void onNetworkDestroyed() { + //Pass out all the stored energy to the conduits + for(IPowerConduit con : network.getConduits()) { + PowerHandler ph = con.getPowerHandler(); + float give = ph.getMaxEnergyStored() - ph.getEnergyStored(); + give = Math.min(give, energyStored); + ph.setEnergy(ph.getEnergyStored() + give); + energyStored -= give; + if(energyStored <= 0) { + return; + } + } + + } + + private static class StarveBuffer { + + float stored; + + public StarveBuffer(float stored) { + this.stored = stored; + } + + void addToStore(float val) { + stored += val; + } + + } + +} diff --git a/common/crazypants/enderio/conduit/power/PowerConduit.java b/common/crazypants/enderio/conduit/power/PowerConduit.java new file mode 100644 index 00000000..e299bdf5 --- /dev/null +++ b/common/crazypants/enderio/conduit/power/PowerConduit.java @@ -0,0 +1,234 @@ +package crazypants.enderio.conduit.power; + +import java.util.HashMap; +import java.util.Map; + +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.AbstractConduit; +import crazypants.enderio.conduit.AbstractConduitNetwork; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.power.BasicCapacitor; +import crazypants.enderio.power.ICapacitor; +import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.render.BoundingBox; +import crazypants.render.IconUtil; +import crazypants.vecmath.Vector3d; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.power.IPowerEmitter; +import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; + +public class PowerConduit extends AbstractConduit implements IPowerConduit { + + static final Map ICONS = new HashMap(); + + static final ICapacitor[] CAPACITORS = new BasicCapacitor[] { + new BasicCapacitor(0, 64, 64, 0, 0, 0, 64), + new BasicCapacitor(0, 128, 128, 0, 0, 0, 128), + new BasicCapacitor(0, 1024, 1024, 0, 0, 0, 1024) + }; + + static final String[] POSTFIX = new String[] { "", "Enhanced", "Ender" }; + + static ItemStack createItemStackForSubtype(int subtype) { + ItemStack result = new ItemStack(ModObject.itemPowerConduit.actualId, 1, subtype); + return result; + + } + + public static void initIcons() { + IconUtil.addIconProvider(new IconUtil.IIconProvider() { + + @Override + public void registerIcons(IconRegister register) { + for (String pf : POSTFIX) { + ICONS.put(ICON_KEY + pf, register.registerIcon(ICON_KEY + pf)); + ICONS.put(ICON_CORE_KEY + pf, register.registerIcon(ICON_CORE_KEY + pf)); + } + ICONS.put(ICON_TRANSMISSION_KEY, register.registerIcon(ICON_TRANSMISSION_KEY)); + } + + @Override + public int getTextureType() { + return 0; + } + + }); + } + + public static final float WIDTH = 0.075f; + public static final float HEIGHT = 0.075f; + + public static final Vector3d MIN = new Vector3d(0.5f - WIDTH, 0.5 - HEIGHT, 0.5 - WIDTH); + public static final Vector3d MAX = new Vector3d(MIN.x + WIDTH, MIN.y + HEIGHT, MIN.z + WIDTH); + + public static final BoundingBox BOUNDS = new BoundingBox(MIN, MAX); + + protected PowerConduitNetwork network; + private PowerHandler powerHandler; + + private int subtype; + + private float energyStored; + + public PowerConduit() { + } + + public PowerConduit(int meta) { + this.subtype = meta; + powerHandler = createPowerHandlerForType(); + } + + @Override + public ICapacitor getCapacitor() { + return CAPACITORS[subtype]; + } + + private PowerHandler createPowerHandlerForType() { + return PowerHandlerUtil.createHandler(CAPACITORS[subtype], this, Type.PIPE); + } + + public float getEnergyStored() { + return energyStored; + } + + public void setEnergyStored(float energyStored) { + this.energyStored = energyStored; + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + nbtRoot.setShort("subtype", (short) subtype); + nbtRoot.setFloat("energyStored", energyStored); + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + super.readFromNBT(nbtRoot); + subtype = nbtRoot.getShort("subtype"); + if (powerHandler == null) { + powerHandler = createPowerHandlerForType(); + } + energyStored = nbtRoot.getFloat("energyStored"); + if(energyStored < 0) { + energyStored = 0; + } + } + + @Override + public PowerReceiver getPowerReceiver(ForgeDirection side) { + return powerHandler.getPowerReceiver(); + } + + @Override + public PowerHandler getPowerHandler() { + return powerHandler; + } + + @Override + public void applyPerdition() { + } + + @Override + public void doWork(PowerHandler workProvider) { + } + + @Override + public World getWorld() { + return getBundle().getEntity().worldObj; + } + + @Override + public AbstractConduitNetwork getNetwork() { + return network; + } + + @Override + public boolean setNetwork(AbstractConduitNetwork network) { + this.network = (PowerConduitNetwork) network; + return true; + } + + @Override + public boolean canConnectToExternal(ForgeDirection direction) { + IPowerReceptor rec = getExternalPowerReceptor(direction); + if(rec instanceof IPowerEmitter) { + return ((IPowerEmitter)rec).canEmitPowerFrom(direction.getOpposite()); + } + return rec != null; + } + + @Override + public void externalConnectionAdded(ForgeDirection direction) { + super.externalConnectionAdded(direction); + if (network != null) { + TileEntity te = bundle.getEntity(); + network.powerReceptorAdded(this, direction, te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ, + getExternalPowerReceptor(direction)); + } + } + + @Override + public void externalConnectionRemoved(ForgeDirection direction) { + super.externalConnectionRemoved(direction); + if (network != null) { + TileEntity te = bundle.getEntity(); + network.powerReceptorRemoved(te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ); + } + } + + @Override + public IPowerReceptor getExternalPowerReceptor(ForgeDirection direction) { + TileEntity te = bundle.getEntity(); + World world = te.worldObj; + if (world == null) { + return null; + } + TileEntity test = world.getBlockTileEntity(te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ); + if (test instanceof IConduitBundle) { + return null; + } + if (test instanceof IPowerReceptor) { + return (IPowerReceptor) test; + } + return null; + } + + @Override + public ItemStack createItem() { + return createItemStackForSubtype(subtype); + } + + @Override + public Class getBaseConduitType() { + return IPowerConduit.class; + } + + // Rendering + @Override + public Icon getTextureForState(CollidableComponent component) { + if (component.dir == ForgeDirection.UNKNOWN) { + return ICONS.get(ICON_CORE_KEY + POSTFIX[subtype]); + } + return ICONS.get(ICON_KEY + POSTFIX[subtype]); + } + + @Override + public Icon getTransmitionTextureForState(CollidableComponent component) { + //return ICONS.get(ICON_TRANSMISSION_KEY); + return null; + } + +} diff --git a/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java b/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java new file mode 100644 index 00000000..3e53478b --- /dev/null +++ b/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java @@ -0,0 +1,136 @@ +package crazypants.enderio.conduit.power; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import crazypants.enderio.conduit.AbstractConduitNetwork; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.util.BlockCoord; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; + +public class PowerConduitNetwork extends AbstractConduitNetwork { + + // ---------------------------------------------------------------------- + + NetworkPowerManager powerManager; + + + private Map powerReceptors = new HashMap(); + + private long timeAtLastApply = -1; + + public PowerConduitNetwork() { + } + + @Override + public void init(IConduitBundle tile, Collection connections, World world) { + super.init(tile, connections, world); + powerManager = new NetworkPowerManager(this, world); + powerManager.receptorsChanged(); + } + + @Override + public void destroyNetwork() { + for (IPowerConduit con : conduits) { + con.setActive(false); + } + powerManager.onNetworkDestroyed(); + super.destroyNetwork(); + } + + public NetworkPowerManager getPowerManager() { + return powerManager; + } + + @Override + public void addConduit(IPowerConduit con) { + super.addConduit(con); + Set externalDirs = con.getExternalConnections(); + for (ForgeDirection dir : externalDirs) { + IPowerReceptor pr = con.getExternalPowerReceptor(dir); + if (pr != null) { + TileEntity te = con.getBundle().getEntity(); + powerReceptorAdded(con, dir, te.xCoord + dir.offsetX, te.yCoord + dir.offsetY, te.zCoord + dir.offsetZ, pr); + } + } + if(powerManager != null) { + con.setActive(powerManager.isActive()); + } + } + + @Override + public Class getBaseConduitType() { + return IPowerConduit.class; + } + + public void powerReceptorAdded(IPowerConduit powerConduit, ForgeDirection direction, int x, int y, int z, IPowerReceptor powerReceptor) { + if(powerReceptor == null) { + return; + } + BlockCoord key = new BlockCoord(x, y, z); + ReceptorEntry re = powerReceptors.get(key); + if(re == null) { + re = new ReceptorEntry(powerReceptor, key, powerConduit); + powerReceptors.put(key, re); + } + re.directions.add(direction); + if(powerManager != null) { + powerManager.receptorsChanged(); + } + } + + public void powerReceptorRemoved(int x, int y, int z) { + powerReceptors.remove(new BlockCoord(x, y, z)); + powerManager.receptorsChanged(); + } + + public Collection getPowerReceptors() { + return powerReceptors.values(); + } + + @Override + public void onUpdateEntity(IConduit conduit) { + World world = conduit.getBundle().getEntity().worldObj; + if(world == null) { + return; + } + if(world.isRemote) { + return; + } + long curTime = world.getTotalWorldTime(); + if(curTime != timeAtLastApply) { + timeAtLastApply = curTime; + powerManager.applyRecievedPower(); + } + } + + + public static class ReceptorEntry { + + IPowerConduit emmiter; + IPowerReceptor powerReceptor; + BlockCoord coord; + //The different directions that we connect to the sucker + Set directions = new HashSet(); + + public ReceptorEntry(IPowerReceptor powerReceptor, BlockCoord coord,IPowerConduit emmiter) { + this.powerReceptor = powerReceptor; + this.coord = coord; + this.emmiter = emmiter; + } + + } + + +} diff --git a/common/crazypants/enderio/conduit/redstone/IRedstoneConduit.java b/common/crazypants/enderio/conduit/redstone/IRedstoneConduit.java new file mode 100644 index 00000000..1cc11cac --- /dev/null +++ b/common/crazypants/enderio/conduit/redstone/IRedstoneConduit.java @@ -0,0 +1,39 @@ +package crazypants.enderio.conduit.redstone; + +import java.util.Set; + +import crazypants.enderio.conduit.IConduit; + +import net.minecraftforge.common.ForgeDirection; + +public interface IRedstoneConduit extends IConduit { + + public static final String KEY_CONDUIT_ICON ="enderio:redstoneConduit"; + public static final String KEY_TRANSMISSION_ICON ="enderio:redstoneConduitTransmission"; + public static final String KEY_CORE_OFF_ICON ="enderio:redstoneConduitCoreOff"; + public static final String KEY_CORE_ON_ICON ="enderio:redstoneConduitCoreOn"; + + enum SignalColor { + RED + } + + //External redstone interface + + int isProvidingStrongPower(ForgeDirection toDirection); + + int isProvidingWeakPower(ForgeDirection toDirection); + + //signals + + //--- Server Side Only + Set getNetworkInputs(); + + Set getNetworkOutputs(ForgeDirection side); + + //--- Set on server side, used on client side for rendering + + + boolean isReplaceableByControl(Class replacenebtType); + + +} diff --git a/common/crazypants/enderio/conduit/redstone/ItemRedstoneConduit.java b/common/crazypants/enderio/conduit/redstone/ItemRedstoneConduit.java new file mode 100644 index 00000000..10697f17 --- /dev/null +++ b/common/crazypants/enderio/conduit/redstone/ItemRedstoneConduit.java @@ -0,0 +1,41 @@ +package crazypants.enderio.conduit.redstone; + +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.*; +import crazypants.enderio.conduit.facade.ItemConduitFacade; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.item.ItemStack; + +public class ItemRedstoneConduit extends AbstractItemConduit { + + private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] { + new ItemConduitSubtype(ModObject.itemRedstoneConduit.unlocalisedName, ModObject.itemRedstoneConduit.name, "enderio:itemRedstoneConduit"), + new ItemConduitSubtype(ModObject.itemRedstoneConduit.unlocalisedName + "switch", "Conduit Switch", "enderio:itemRedstoneSwitch") + + }; + + public static ItemRedstoneConduit create() { + ItemRedstoneConduit result = new ItemRedstoneConduit(); + result.init(subtypes); + return result; + } + + protected ItemRedstoneConduit() { + super(ModObject.itemRedstoneConduit); + } + + @Override + public Class getBaseConduitType() { + return IRedstoneConduit.class; + } + + @Override + public IConduit createConduit(ItemStack stack) { + if(stack.getItemDamage() == 1) { + return new RedstoneSwitch(); + } else { + return new RedstoneConduit(); + } + } + +} diff --git a/common/crazypants/enderio/conduit/redstone/RedstoneConduit.java b/common/crazypants/enderio/conduit/redstone/RedstoneConduit.java new file mode 100644 index 00000000..337d0b20 --- /dev/null +++ b/common/crazypants/enderio/conduit/redstone/RedstoneConduit.java @@ -0,0 +1,221 @@ +package crazypants.enderio.conduit.redstone; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import crazypants.enderio.EnderIO; +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.AbstractConduit; +import crazypants.enderio.conduit.AbstractConduitNetwork; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.render.IconUtil; +import crazypants.util.BlockCoord; + +import net.minecraft.block.Block; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; + +public class RedstoneConduit extends AbstractConduit implements IRedstoneConduit { + + + static final Map ICONS = new HashMap(); + + + public static void initIcons() { + IconUtil.addIconProvider(new IconUtil.IIconProvider() { + + @Override + public void registerIcons(IconRegister register) { + ICONS.put(KEY_CORE_OFF_ICON, register.registerIcon(KEY_CORE_OFF_ICON)); + ICONS.put(KEY_CORE_ON_ICON, register.registerIcon(KEY_CORE_ON_ICON)); + ICONS.put(KEY_CONDUIT_ICON, register.registerIcon(KEY_CONDUIT_ICON)); + ICONS.put(KEY_TRANSMISSION_ICON, register.registerIcon(KEY_TRANSMISSION_ICON)); + } + + @Override + public int getTextureType() { + return 0; + } + + }); + } + + protected RedstoneConduitNetwork network; + + protected final Set externalSignals = new HashSet(); + + public RedstoneConduit() { + } + + @Override + public boolean isReplaceableByControl(Class replacenebtType) { + return true; + } + + @Override + public ItemStack createItem() { + return new ItemStack(ModObject.itemRedstoneConduit.actualId,1,0); + } + + @Override + public Class getBaseConduitType() { + return IRedstoneConduit.class; + } + + @Override + public AbstractConduitNetwork getNetwork() { + return network; + } + + @Override + public boolean setNetwork(AbstractConduitNetwork network) { + this.network = (RedstoneConduitNetwork) network; + return true; + } + + @Override + public boolean canConnectToExternal(ForgeDirection direction) { + TileEntity te = bundle.getEntity(); + World world = te.worldObj; + if (world == null) { + return false; + } + int id = world.getBlockId(te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ); + if (id > 0 && id != EnderIO.blockConduitBundle.blockID) { + + //We can connect to a block if it can provide power or it is receiving a string signal (not emitted by us) + + BlockCoord loc = getLocation().getLocation(direction); + + boolean toggleNetwork = network != null && network.isNetworkEnabled(); + if(toggleNetwork ) { + network.setNetworkEnabled(false); + } + boolean gettingStrongPower = world.getBlockPowerInput(loc.x, loc.y, loc.z) == 15; + if(toggleNetwork) { + network.setNetworkEnabled(true); + } + + + //We can get an input from the block when: + return + Block.blocksList[id].canProvidePower() || //The block can provide power + //Or its getting a strong signal that we are not providing + gettingStrongPower; + //( world.getBlockPowerInput(loc.x, loc.y, loc.z) == 15 && isProvidingStrongPower(direction) != 15 ); + } + return false; + } + + @Override + public Set getNetworkInputs() { + Set res = new HashSet(); + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (canConnectToExternal(dir)) { + int input = getExternalPowerLevel(dir); + if (input > 1) { //need to degrade external signals by one as they enter + BlockCoord loc = getLocation().getLocation(dir); + Signal signal = new Signal(loc.x, loc.y, loc.z, input - 1, SignalColor.RED); + res.add(signal); + } + } + } + return res; + } + + @Override + public Set getNetworkOutputs(ForgeDirection side) { + if (network == null) { + return Collections.emptySet(); + } + return network.getSignals(); + } + + @Override + public boolean onNeighborBlockChange(int blockId) { + World world = getBundle().getEntity().worldObj; + if (world.isRemote) { + return false; + } + if (blockId == EnderIO.blockConduitBundle.blockID) { + return false; + } + boolean res = super.onNeighborBlockChange(blockId); + + if (network == null || network.updatingNetwork) { + return false; + } + + if(blockId > 0 && Block.blocksList[blockId].canProvidePower() && network != null) { + //TODO: Just recalculate the signals, no need for a full rebuild + network.destroyNetwork(); + return false; + } + return res; + } + + private int getExternalPowerLevel(ForgeDirection dir) { + if (network != null) { + network.setNetworkEnabled(false); + } + World world = getBundle().getEntity().worldObj; + BlockCoord loc = getLocation(); + int result = world.getStrongestIndirectPower(loc.x, loc.y, loc.z); + + if (network != null) { + network.setNetworkEnabled(true); + } + return result; + + } + + @Override + public int isProvidingStrongPower(ForgeDirection toDirection) { + return 0; + } + + @Override + public int isProvidingWeakPower(ForgeDirection toDirection) { + if (network == null || !network.isNetworkEnabled()) { + return 0; + } + int result = 0; + for (Signal signal : network.getSignals()) { + result = Math.max(result, signal.strength); + } + return result; + } + + @Override + public Icon getTextureForState(CollidableComponent component) { + if (component.dir == ForgeDirection.UNKNOWN) { + return isActive() ? ICONS.get(KEY_CORE_ON_ICON) : ICONS.get(KEY_CORE_OFF_ICON); + } + //return ICONS.get(KEY_CONDUIT_ICON); + return isActive() ? ICONS.get(KEY_TRANSMISSION_ICON) : ICONS.get(KEY_CONDUIT_ICON); + } + + @Override + public Icon getTransmitionTextureForState(CollidableComponent component) { +// if (component.id == ForgeDirection.UNKNOWN) { +// return null; +// } +// return isActive() ? ICONS.get(KEY_TRANSMISSION_ICON) : null; + return null; + + } + + @Override + public String toString() { + return "RedstoneConduit [network=" + network + " connections=" + conduitConnections + " active=" + active + "]"; + } + +} diff --git a/common/crazypants/enderio/conduit/redstone/RedstoneConduitNetwork.java b/common/crazypants/enderio/conduit/redstone/RedstoneConduitNetwork.java new file mode 100644 index 00000000..3321a150 --- /dev/null +++ b/common/crazypants/enderio/conduit/redstone/RedstoneConduitNetwork.java @@ -0,0 +1,185 @@ +package crazypants.enderio.conduit.redstone; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import crazypants.enderio.conduit.AbstractConduitNetwork; +import crazypants.enderio.conduit.IConduitBundle; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + +public class RedstoneConduitNetwork extends AbstractConduitNetwork { + + private final Set signals = new HashSet(); + + boolean updatingNetwork = false; + + private boolean networkEnabled = true; + + public RedstoneConduitNetwork() { + } + + @Override + public Class getBaseConduitType() { + return IRedstoneConduit.class; + } + + @Override + public void init(IConduitBundle tile, Collection connections, World world) { + super.init(tile, connections, world); + updatingNetwork = true; + notifyNeigborsOfSignals(); + updatingNetwork = false; + } + + @Override + public void destroyNetwork() { + updatingNetwork = true; + for (IRedstoneConduit con : conduits) { + con.setActive(false); + } + //Notify neighbours that all signals have been lost + List copy = new ArrayList(signals); + signals.clear(); + for(Signal s : copy) { + notifyNeigborsOfSignalUpdate(s); + } + updatingNetwork = false; + super.destroyNetwork(); + } + + @Override + public void addConduit(IRedstoneConduit con) { + updatingNetwork = true; + super.addConduit(con); + Set newInputs = con.getNetworkInputs(); + signals.addAll(newInputs); + //Notify existing nodes of new signals + for (Signal signal : newInputs) { + notifyNeigborsOfSignalUpdate(signal); + } + //and new nodes neighbours of all signals + for (Signal signal : signals) { + notifyConduitNeighbours(con, signal); + } + updatingNetwork = false; + } + + public Set getSignals() { + if(networkEnabled) { + return signals; + } else { + return Collections.emptySet(); + } + } + + //Need to disable the network when determining the strength of external signals + //to avoid feed back looops + void setNetworkEnabled(boolean enabled) { + networkEnabled = enabled; + } + + public boolean isNetworkEnabled() { + return networkEnabled; + } + + public void addSignal(Signal signal) { + updatingNetwork = true; + signals.add(signal); + notifyNetworkOfUpdate(); + notifyNeigborsOfSignalUpdate(signal); + updatingNetwork = false; + + } + + public void removeSignal(Signal signal) { + updatingNetwork = true; + signals.remove(signal); + notifyNetworkOfUpdate(); + notifyNeigborsOfSignalUpdate(signal); + updatingNetwork = false; + } + + public void replaceSignal(Signal oldSig, Signal newSig) { + updatingNetwork = true; + signals.remove(oldSig); + signals.add(newSig); + notifyNetworkOfUpdate(); + notifyNeigborsOfSignalUpdate(newSig); + updatingNetwork = false; + } + + @Override + public void notifyNetworkOfUpdate() { + for (IRedstoneConduit con : conduits) { + con.setActive(!getSignals().isEmpty()); + } + super.notifyNetworkOfUpdate(); + } + + @Override + public String toString() { + return "RedstoneConduitNetwork [signals=" + signalsString() + ", conduits=" + conduitsString() + "]"; + } + + private String conduitsString() { + StringBuilder sb = new StringBuilder(); + for (IRedstoneConduit con : conduits) { + TileEntity te = con.getBundle().getEntity(); + sb.append("<"); + sb.append(te.xCoord + "," + te.yCoord + "," + te.zCoord); + sb.append(">"); + } + return sb.toString(); + } + + String signalsString() { + StringBuilder sb = new StringBuilder(); + for (Signal s : signals) { + sb.append("<"); + sb.append(s); + sb.append(">"); + + } + return sb.toString(); + } + + private void notifyNeigborsOfSignals() { + for(Signal signal : signals) { + notifyNeigborsOfSignalUpdate(signal); + } + } + + private void notifyNeigborsOfSignalUpdate(Signal signal) { + for (IRedstoneConduit con : conduits) { + notifyConduitNeighbours(con, signal); + } + } + + private void notifyConduitNeighbours(IRedstoneConduit con, Signal signal) { + if (con.getBundle() == null) { + System.out.println("RedstoneConduitNetwork.notifyNeigborsOfSignalUpdate: NULL BUNDLE!!!!"); + return; + } + TileEntity te = con.getBundle().getEntity(); + + te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord, te.zCoord, te.worldObj.getBlockId(te.xCoord, te.yCoord, te.zCoord)); + // Need to notify neighbours neighbours for changes to string signals + if (signal != null && signal.strength >= 15 && signal.x == te.xCoord && signal.y == te.yCoord && signal.z == te.zCoord) { + + te.worldObj.notifyBlocksOfNeighborChange(te.xCoord + 1, te.yCoord, te.zCoord, te.worldObj.getBlockId(te.xCoord + 1, te.yCoord, te.zCoord)); + te.worldObj.notifyBlocksOfNeighborChange(te.xCoord - 1, te.yCoord, te.zCoord, te.worldObj.getBlockId(te.xCoord - 1, te.yCoord, te.zCoord)); + te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord + 1, te.zCoord, te.worldObj.getBlockId(te.xCoord, te.yCoord + 1, te.zCoord)); + te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord - 1, te.zCoord, te.worldObj.getBlockId(te.xCoord, te.yCoord - 1, te.zCoord)); + te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord, te.zCoord + 1, te.worldObj.getBlockId(te.xCoord, te.yCoord, te.zCoord + 1)); + te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord, te.zCoord - 1, te.worldObj.getBlockId(te.xCoord, te.yCoord, te.zCoord - 1)); + + } + } + +} diff --git a/common/crazypants/enderio/conduit/redstone/RedstoneSwitch.java b/common/crazypants/enderio/conduit/redstone/RedstoneSwitch.java new file mode 100644 index 00000000..82d0c830 --- /dev/null +++ b/common/crazypants/enderio/conduit/redstone/RedstoneSwitch.java @@ -0,0 +1,145 @@ +package crazypants.enderio.conduit.redstone; + +import java.util.List; +import java.util.Set; + +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.RaytraceResult; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.conduit.geom.ConduitGeometryUtil; +import crazypants.enderio.conduit.geom.Offset; +import crazypants.render.BoundingBox; +import crazypants.render.IconUtil; +import crazypants.util.BlockCoord; +import crazypants.vecmath.Vector3d; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraftforge.common.ForgeDirection; + +public class RedstoneSwitch extends RedstoneConduit { + + static final String SWITCH_TAG = "switch"; + public static final String SWITHC_ICON_OFF_KEY = "enderio:redstoneConduitSwitchOff"; + public static final String SWITCH_ICON_ON_KEY = "enderio:redstoneConduitSwitchOn"; + + private boolean isOn; + + public static void initIcons() { + IconUtil.addIconProvider(new IconUtil.IIconProvider() { + + @Override + public void registerIcons(IconRegister register) { + ICONS.put(RedstoneSwitch.SWITHC_ICON_OFF_KEY, register.registerIcon(SWITHC_ICON_OFF_KEY)); + ICONS.put(RedstoneSwitch.SWITCH_ICON_ON_KEY, register.registerIcon(SWITCH_ICON_ON_KEY)); + } + + @Override + public int getTextureType() { + return 0; + } + + }); + } + + @Override + public boolean isReplaceableByControl(Class replacenebtType) { + return false; + } + + @Override + public ItemStack createItem() { + return new ItemStack(ModObject.itemRedstoneConduit.actualId,1,1); + } + + @Override + public int isProvidingStrongPower(ForgeDirection toDirection) { + if (network == null || !network.isNetworkEnabled()) { + return 0; + } + return isOn ? 15 : 0; + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + nbtRoot.setBoolean("switchOn", isOn); + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + super.readFromNBT(nbtRoot); + isOn = nbtRoot.getBoolean("switchOn"); + } + + Icon getSwitchIcon() { + return isOn ? ICONS.get(SWITCH_ICON_ON_KEY) : ICONS.get(SWITHC_ICON_OFF_KEY); + } + + @Override + public Icon getTextureForState(CollidableComponent component) { + if (SWITCH_TAG.equals(component.data)) { + return isOn ? ICONS.get(SWITCH_ICON_ON_KEY) : ICONS.get(SWITHC_ICON_OFF_KEY); + } + return super.getTextureForState(component); + } + + + @Override + public List getCollidableComponents() { + if (collidables != null && !collidablesDirty) { + return collidables; + } + + Offset o = getBundle().getOffset(getBaseConduitType(), ForgeDirection.UNKNOWN); + Vector3d trans = ConduitGeometryUtil.instance.getTranslation(ForgeDirection.UNKNOWN, o); + + List result = super.getCollidableComponents(); + BoundingBox[] aabb = RedstoneSwitchRenderer.instance.getAABB(); + + for (BoundingBox bb : aabb) { + result.add(new CollidableComponent(IRedstoneConduit.class, bb.translate(trans), ForgeDirection.UNKNOWN, SWITCH_TAG)); + } + + return result; + } + + @Override + public boolean onBlockActivated(EntityPlayer player, RaytraceResult res) { + if (res.component.data != null && res.component.data.equals(SWITCH_TAG)) { + toggleSwitch(); + return true; + } + return false; + } + + private void toggleSwitch() { + isOn = !isOn; + if (network == null) { + return; + } + TileEntity te = bundle.getEntity(); + Signal signal = new Signal(te.xCoord, te.yCoord, te.zCoord, 15, SignalColor.RED); + if (isOn) { + network.addSignal(signal); + } else { + network.removeSignal(signal); + } + } + + @Override + public Set getNetworkInputs() { + Set res = super.getNetworkInputs(); + if (isOn) { + BlockCoord loc = getLocation(); + Signal signal = new Signal(loc.x, loc.y, loc.z, 15, SignalColor.RED); + res.add(signal); + } + return res; + } + +} diff --git a/common/crazypants/enderio/conduit/redstone/RedstoneSwitchRenderer.java b/common/crazypants/enderio/conduit/redstone/RedstoneSwitchRenderer.java new file mode 100644 index 00000000..adcf4f36 --- /dev/null +++ b/common/crazypants/enderio/conduit/redstone/RedstoneSwitchRenderer.java @@ -0,0 +1,112 @@ +package crazypants.enderio.conduit.redstone; + +import crazypants.enderio.EnderIO; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.conduit.geom.ConduitGeometryUtil; +import crazypants.enderio.conduit.render.ConduitBundleRenderer; +import crazypants.enderio.conduit.render.DefaultConduitRenderer; +import crazypants.render.BoundingBox; +import crazypants.render.CubeRenderer; +import crazypants.render.VertexRotation; +import crazypants.render.VertexTransform; +import crazypants.vecmath.Vector3d; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.Icon; +import net.minecraftforge.common.ForgeDirection; + +public class RedstoneSwitchRenderer extends DefaultConduitRenderer { + + public static RedstoneSwitchRenderer instance = new RedstoneSwitchRenderer(); + + private static final float SIZE = 0.2f; + private static final float HW = SIZE/3; + private static final float HH = SIZE/2; + private static final float DEPTH = 0.05f; + private static final float HD = DEPTH/2; + + private static final float DIST = 0.25f; + + private static final float CON_HW = 0.015f; + + + private final VertexTransform[] xForms; + private final BoundingBox switchBounds; + private final BoundingBox connectorBounds; + + private final BoundingBox[] aabb; + + private RedstoneSwitchRenderer() { + BoundingBox bb = new BoundingBox(0.5- HW, 0.5- HH, 0.5- HD, 0.5+ HW, 0.5+ HH, 0.5 + HD); + switchBounds = bb.translate(0, 0, DIST); + + connectorBounds = new BoundingBox(0.5- CON_HW, 0.5- CON_HW, 0.5- CON_HW, 0.5+ CON_HW, 0.5+ CON_HW, 0.5 + DIST); + + Vector3d axis = new Vector3d(0,1,0); + Vector3d p = new Vector3d(0.5,0.5,0.5); + xForms = new VertexTransform[4]; + double angle = Math.toRadians(45); + for(int i=0; i < xForms.length; i++) { + //TODO + //xForms[i] = new Rotation(angle, axis, p); + xForms[i] = new VertexRotation(angle, axis, p); + angle += Math.toRadians(90); + } + + aabb = new BoundingBox[xForms.length]; + for(int i=0; i < xForms.length; i++) { + aabb[i] = switchBounds.transform(xForms[i]); + } + + } + + public BoundingBox[] getAABB() { + return aabb; + } + + @Override + public boolean isRendererForConduit(IConduit conduit) { + return conduit.getClass() == RedstoneSwitch.class; + } + + @Override + public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle bundle, IConduit conduit, double x, double y, double z, float partialTick, + float worldLight) { + + super.renderEntity(conduitBundleRenderer, bundle, conduit, x, y, z, partialTick, worldLight); + + RedstoneSwitch sw = (RedstoneSwitch)conduit; + + Tessellator tessellator = Tessellator.instance; + float selfIllum = Math.max(worldLight, conduit.getSelfIlluminationForState(null)); + tessellator.setColorOpaque_F(selfIllum, selfIllum, selfIllum); + + Icon[] icons = new Icon[6]; + for(int i=0;i sources) { + // Each source is 5 ints + int[] result = new int[sources.size() * 5]; + int i = 0; + for (SignalSource ss : sources) { + result[i] = ss.signal.x; + i++; + result[i] = ss.signal.y; + i++; + result[i] = ss.signal.z; + i++; + result[i] = ss.signal.strength; + i++; + result[i] = ss.signal.color.ordinal(); + i++; + result[i] = ss.fromDirection.ordinal(); + i++; + } + return result; + } + + public static Set fromIntArray(int[] enc) { + Set result = new HashSet(); + for(int i=0; i < enc.length; i+=5) { + Signal sig = new Signal(enc[i], enc[i+1], enc[i+2], enc[i+3], SignalColor.values()[enc[i+4]]); + result.add(new SignalSource(sig, ForgeDirection.values()[enc[i+4]])); + } + return result; + } + +} diff --git a/common/crazypants/enderio/conduit/render/ConduitBundleRenderer.java b/common/crazypants/enderio/conduit/render/ConduitBundleRenderer.java new file mode 100644 index 00000000..2015ebf3 --- /dev/null +++ b/common/crazypants/enderio/conduit/render/ConduitBundleRenderer.java @@ -0,0 +1,212 @@ +package crazypants.enderio.conduit.render; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.IBlockAccess; +import net.minecraftforge.common.ForgeDirection; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; +import crazypants.enderio.EnderIO; +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.BlockConduitBundle; +import crazypants.enderio.conduit.ConduitUtil; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.conduit.facade.BlockConduitFacade; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.render.BoundingBox; +import crazypants.render.CubeRenderer; +import crazypants.render.RenderUtil; + +public class ConduitBundleRenderer extends TileEntitySpecialRenderer implements ISimpleBlockRenderingHandler { + + private static final float CONNECTOR_DEPTH = 0.05f; + private static final float CONNECTOR_WIDTH = 0.3f; + + private Map connectorBounds = new HashMap(); + + public ConduitBundleRenderer() { + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + connectorBounds.put(dir, createConnector(dir)); + } + } + + @Override + public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTick) { + IConduitBundle bundle = (IConduitBundle) te; + EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; + if (ConduitUtil.renderFacade(bundle, player)) { + return; + } + + // Lighting calcuations to allow for self illumination + float val = RenderUtil.claculateTotalBrightnessForLocation(te.worldObj, te.xCoord, te.yCoord, te.zCoord); + renderTileEntityAt(bundle, x, y, z, partialTick, val); + } + + + public void renderTileEntityAt(IConduitBundle bundle, double x, double y, double z, float partialTick, float brightness) { + + RenderUtil.bindBlockTexture(); + Minecraft.getMinecraft().entityRenderer.disableLightmap(0); + + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); + //GL11.glPushAttrib(GL11.GL_POLYGON_BIT); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glShadeModel(GL11.GL_SMOOTH); + //GL11.glDisable (GL11.GL_CULL_FACE); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + + // Conduits + Set externals = new HashSet(); + for (IConduit con : bundle.getConduits()) { + ConduitRenderer renderer = EnderIO.proxy.getRendererForConduit(con); + renderer.renderEntity(this, bundle, con, x, y, z, partialTick, brightness); + externals.addAll(con.getExternalConnections()); + } + + // Internal conectors between conduits + List connectors = bundle.getConnectors(); + for (CollidableComponent component : connectors) { + if (component.conduitType != null) { + IConduit con = bundle.getConduit(component.conduitType); + float selfIllum = Math.max(brightness, con.getSelfIlluminationForState(component)); + tessellator.setColorRGBA_F(selfIllum, selfIllum, selfIllum, 1); + CubeRenderer.render(component.bound, con.getTextureForState(component)); + } else { + Icon tex = EnderIO.blockConduitBundle.getConnectorIcon(); + CubeRenderer.render(component.bound, tex); + } + } + + // External connection terminations + for (ForgeDirection dir : externals) { + renderExternalConnection(dir); + } + + tessellator.draw(); + GL11.glPopMatrix(); + GL11.glPopAttrib(); + GL11.glPopAttrib(); + //GL11.glPopAttrib(); + + } + + private void renderExternalConnection(ForgeDirection dir) { + Icon tex = EnderIO.blockConduitBundle.getConnectorIcon(); + BoundingBox[] bbs = connectorBounds.get(dir); + for (BoundingBox bb : bbs) { + CubeRenderer.render(bb, tex); + } + } + + private static BoundingBox[] createConnector(ForgeDirection dir) { + + BoundingBox[] res = new BoundingBox[2]; + + float cMin = 0.5f - CONNECTOR_WIDTH / 2; + float cMax = 0.5f + CONNECTOR_WIDTH / 2; + float dMin = 1 - CONNECTOR_DEPTH / 2; + float dMax = 1; + + res[0] = createConnectorComponent(dir, cMin, cMax, dMin, dMax); + + cMin = 0.5f - CONNECTOR_WIDTH / 3; + cMax = 0.5f + CONNECTOR_WIDTH / 3; + dMin = 1 - CONNECTOR_DEPTH; + dMax = 1 - CONNECTOR_DEPTH / 2; + + res[1] = createConnectorComponent(dir, cMin, cMax, dMin, dMax); + + return res; + } + + private static BoundingBox createConnectorComponent(ForgeDirection dir, float cornerMin, float cornerMax, float depthMin, float depthMax) { + float minX = (1 - Math.abs(dir.offsetX)) * cornerMin + dir.offsetX * depthMin; + float minY = (1 - Math.abs(dir.offsetY)) * cornerMin + dir.offsetY * depthMin; + float minZ = (1 - Math.abs(dir.offsetZ)) * cornerMin + dir.offsetZ * depthMin; + + float maxX = (1 - Math.abs(dir.offsetX)) * cornerMax + (dir.offsetX * depthMax); + float maxY = (1 - Math.abs(dir.offsetY)) * cornerMax + (dir.offsetY * depthMax); + float maxZ = (1 - Math.abs(dir.offsetZ)) * cornerMax + (dir.offsetZ * depthMax); + + minX = fix(minX); + minY = fix(minY); + minZ = fix(minZ); + maxX = fix(maxX); + maxY = fix(maxY); + maxZ = fix(maxZ); + + BoundingBox bb = new BoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + bb = bb.fixMinMax(); + + return bb; + } + + private static float fix(float val) { + return val < 0 ? 1 + val : val; + } + + @Override + public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks rb) { + + IConduitBundle bundle = (IConduitBundle) world.getBlockTileEntity(x, y, z); + EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; + + if (bundle.hasFacade()) { + + int facadeId = bundle.getFacadeId(); + if (ConduitUtil.isFacadeHidden(bundle, player)) { + bundle.setFacadeId(0); + } + + BlockConduitFacade facb = (BlockConduitFacade) Block.blocksList[ModObject.blockConduitFacade.actualId]; + facb.setBlockBounds(0, 0, 0, 1, 1, 1); + rb.setRenderBoundsFromBlock(facb); + rb.renderStandardBlock(facb, x, y, z); + + bundle.setFacadeId(facadeId); + + } + + return true; + } + + @Override + public boolean shouldRender3DInInventory() { + return false; + } + + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { + } + + @Override + public int getRenderId() { + return BlockConduitBundle.rendererId; + } + +} diff --git a/common/crazypants/enderio/conduit/render/ConduitRenderer.java b/common/crazypants/enderio/conduit/render/ConduitRenderer.java new file mode 100644 index 00000000..4e1a4665 --- /dev/null +++ b/common/crazypants/enderio/conduit/render/ConduitRenderer.java @@ -0,0 +1,12 @@ +package crazypants.enderio.conduit.render; + +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IConduitBundle; + +public interface ConduitRenderer { + + boolean isRendererForConduit(IConduit conduit); + + void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit con, double x, double y, double z, float partialTick, float worldLight); + +} diff --git a/common/crazypants/enderio/conduit/render/DefaultConduitRenderer.java b/common/crazypants/enderio/conduit/render/DefaultConduitRenderer.java new file mode 100644 index 00000000..ca58ac0a --- /dev/null +++ b/common/crazypants/enderio/conduit/render/DefaultConduitRenderer.java @@ -0,0 +1,296 @@ +package crazypants.enderio.conduit.render; + +import static crazypants.render.CubeRenderer.*; +import static net.minecraftforge.common.ForgeDirection.*; + +import java.util.Collection; + +import crazypants.enderio.conduit.*; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.render.BoundingBox; + +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.Icon; +import net.minecraftforge.common.ForgeDirection; + +public class DefaultConduitRenderer implements ConduitRenderer { + + protected float transmissionScaleFactor; + + @Override + public boolean isRendererForConduit(IConduit conduit) { + return true; + } + + @Override + public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x, double y, double z, float partialTick, + float worldLight) { + + Collection components = conduit.getCollidableComponents(); + Tessellator tessellator = Tessellator.instance; + + transmissionScaleFactor = conduit.getTransmitionGeometryScale(); + + Icon tex; + boolean active = conduit.isActive(); + for (CollidableComponent component : components) { + if (renderComponent(component)) { + float selfIllum = Math.max(worldLight, conduit.getSelfIlluminationForState(component)); + if (active && isNSEWUP(component.dir) && + conduit.getTransmitionTextureForState(component) != null) { + tessellator.setColorRGBA_F(selfIllum + 0.1f, selfIllum + 0.1f, + selfIllum + 0.1f, 0.75f); + tex = conduit.getTransmitionTextureForState(component); + renderTransmission(tex, component); + } + + tex = conduit.getTextureForState(component); + tessellator.setColorOpaque_F(selfIllum, selfIllum, selfIllum); + renderConduit(tex, component); + } + + } + + } + + protected void renderConduit(Icon tex, CollidableComponent component) { + if (isNSEWUP(component.dir)) { + RoundedSegmentRenderer.renderSegment(component.dir, component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV()); + } else { + drawSection(component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true); + } + } + + protected void renderTransmission(Icon tex, CollidableComponent component) { + RoundedSegmentRenderer.renderSegment(component.dir, component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV()); + } + + // @Override + public void renderEntity2(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x, double y, double z, float partialTick, + float worldLight) { + + Collection components = conduit.getCollidableComponents(); + Tessellator tessellator = Tessellator.instance; + + transmissionScaleFactor = conduit.getTransmitionGeometryScale(); + + Icon tex; + boolean active = conduit.isActive(); + for (CollidableComponent component : components) { + if (renderComponent(component)) { + float selfIllum = Math.max(worldLight, conduit.getSelfIlluminationForState(component)); + if (active && isNSEWUP(component.dir) && conduit.getTransmitionTextureForState(component) != null) { + tessellator.setColorRGBA_F(selfIllum + 0.1f, selfIllum + 0.1f, selfIllum + 0.1f, 0.75f); + tex = conduit.getTransmitionTextureForState(component); + drawSection(component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true); + } + + tex = conduit.getTextureForState(component); + tessellator.setColorOpaque_F(selfIllum, selfIllum, selfIllum); + BoundingBox[] cubes = toCubes(component.bound); + for (BoundingBox cube : cubes) { + drawSection(cube, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, false); + } + } + + } + + } + + protected boolean renderComponent(CollidableComponent component) { + return true; + } + + protected boolean isNSEWUP(ForgeDirection dir) { + return dir == NORTH || dir == SOUTH || dir == EAST || dir == WEST || dir == UP || dir == DOWN; + } + + protected void drawSection(BoundingBox bound, float minU, float maxU, float minV, float maxV, ForgeDirection dir, boolean isTransmission) { + + setupVertices(bound); + + Tessellator tessellator = Tessellator.instance; + + if (isTransmission) { + setVerticesForTransmission(bound, dir); + } + + if (dir == NORTH || dir == UP || dir == EAST) { // maintain consistent texture + // dir relative to the cneter + // of the conduit + float tmp = minU; + minU = maxU; + maxU = tmp; + } + + boolean rotateSides = dir == UP || dir == DOWN; + boolean rotateTopBottom = dir == NORTH || dir == SOUTH; + + if (dir != NORTH && dir != SOUTH) { + tessellator.setNormal(0, 0, -1); + if (rotateSides) { + addVecWithUV(verts[1], maxU, maxV); + addVecWithUV(verts[0], maxU, minV); + addVecWithUV(verts[3], minU, minV); + addVecWithUV(verts[2], minU, maxV); + } else { + addVecWithUV(verts[1], minU, minV); + addVecWithUV(verts[0], maxU, minV); + addVecWithUV(verts[3], maxU, maxV); + addVecWithUV(verts[2], minU, maxV); + } + if (dir == WEST || dir == EAST) { + float tmp = minU; + minU = maxU; + maxU = tmp; + } + tessellator.setNormal(0, 0, 1); + if (rotateSides) { + addVecWithUV(verts[4], maxU, maxV); + addVecWithUV(verts[5], maxU, minV); + addVecWithUV(verts[6], minU, minV); + addVecWithUV(verts[7], minU, maxV); + } else { + addVecWithUV(verts[4], minU, minV); + addVecWithUV(verts[5], maxU, minV); + addVecWithUV(verts[6], maxU, maxV); + addVecWithUV(verts[7], minU, maxV); + } + if (dir == WEST || dir == EAST) { + float tmp = minU; + minU = maxU; + maxU = tmp; + } + } + + if (dir != UP && dir != DOWN) { + + tessellator.setNormal(0, 1, 0); + if (rotateTopBottom) { + addVecWithUV(verts[6], maxU, maxV); + addVecWithUV(verts[2], minU, maxV); + addVecWithUV(verts[3], minU, minV); + addVecWithUV(verts[7], maxU, minV); + } else { + 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 (rotateTopBottom) { + addVecWithUV(verts[0], minU, minV); + addVecWithUV(verts[1], minU, maxV); + addVecWithUV(verts[5], maxU, maxV); + addVecWithUV(verts[4], maxU, minV); + } else { + addVecWithUV(verts[0], maxU, maxV); + addVecWithUV(verts[1], minU, maxV); + addVecWithUV(verts[5], minU, minV); + addVecWithUV(verts[4], maxU, minV); + } + } + + if (dir != EAST && dir != WEST) { + + // if(id == NORTH) { + // float tmp = minU; + // minU = maxU; + // maxU = tmp; + // } + + tessellator.setNormal(1, 0, 0); + if (rotateSides) { + addVecWithUV(verts[2], minU, maxV); + addVecWithUV(verts[6], minU, minV); + addVecWithUV(verts[5], maxU, minV); + addVecWithUV(verts[1], maxU, maxV); + } else { + 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 (rotateSides) { + addVecWithUV(verts[0], maxU, maxV); + addVecWithUV(verts[4], maxU, minV); + addVecWithUV(verts[7], minU, minV); + addVecWithUV(verts[3], minU, maxV); + } else { + addVecWithUV(verts[0], minU, minV); + addVecWithUV(verts[4], maxU, minV); + addVecWithUV(verts[7], maxU, maxV); + addVecWithUV(verts[3], minU, maxV); + } + } + } + + protected void setVerticesForTransmission(BoundingBox bound, ForgeDirection dir) { + float xs = dir.offsetX == 0 ? transmissionScaleFactor : 1; + float ys = dir.offsetY == 0 ? transmissionScaleFactor : 1; + float zs = dir.offsetZ == 0 ? transmissionScaleFactor : 1; + setupVertices(bound.scale(xs, ys, zs)); + } + + // TODO: This is a really hacky, imprecise and slow way to do this + public BoundingBox[] toCubes(BoundingBox bb) { + + // NB This on handles the really simple conduit case! + + float width = bb.maxX - bb.minX; + float height = bb.maxY - bb.minY; + float depth = bb.maxZ - bb.minZ; + + if (width > 0 && height > 0 && depth > 0) { + if (width / depth > 1.5f || depth / width > 1.5f) { + // split horizontally + if (width > depth) { + int numSplits = Math.round(width / depth); + float newWidth = width / numSplits; + BoundingBox[] result = new BoundingBox[numSplits]; + float lastMax = bb.minX; + for (int i = 0; i < numSplits; i++) { + float max = lastMax + newWidth; + result[i] = new BoundingBox(lastMax, bb.minY, bb.minZ, max, bb.maxY, bb.maxZ); + lastMax = max; + } + return result; + + } else { + + int numSplits = Math.round(depth / width); + float newWidth = depth / numSplits; + BoundingBox[] result = new BoundingBox[numSplits]; + float lastMax = bb.minZ; + for (int i = 0; i < numSplits; i++) { + float max = lastMax + newWidth; + result[i] = new BoundingBox(bb.minX, bb.minY, lastMax, bb.maxX, bb.maxY, max); + lastMax = max; + } + return result; + + } + + } else if (height / width > 1.5) { + + int numSplits = Math.round(height / width); + float newWidth = height / numSplits; + BoundingBox[] result = new BoundingBox[numSplits]; + float lastMax = bb.minY; + for (int i = 0; i < numSplits; i++) { + float max = lastMax + newWidth; + result[i] = new BoundingBox(bb.minX, lastMax, bb.minZ, bb.maxX, max, bb.maxZ); + lastMax = max; + } + return result; + + } + } + + return new BoundingBox[] { bb }; + } + +} diff --git a/common/crazypants/enderio/conduit/render/ItemConduitRenderer.java b/common/crazypants/enderio/conduit/render/ItemConduitRenderer.java new file mode 100644 index 00000000..d935006c --- /dev/null +++ b/common/crazypants/enderio/conduit/render/ItemConduitRenderer.java @@ -0,0 +1,68 @@ +package crazypants.enderio.conduit.render; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.item.ItemStack; +import net.minecraftforge.client.IItemRenderer; + +import org.lwjgl.opengl.GL11; + +import crazypants.render.BoundingBox; +import crazypants.render.CubeRenderer; + + +public class ItemConduitRenderer implements IItemRenderer { + + private final BoundingBox bb; + + public ItemConduitRenderer() { + float scale = 0.8f; + bb = BoundingBox.UNIT_CUBE.scale(scale,scale,scale); + } + + + + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED_FIRST_PERSON; + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + RenderBlocks renderBlocks = (RenderBlocks) data[0]; + if (type == ItemRenderType.INVENTORY) { + renderToInventory(item, renderBlocks); + } else if (type == ItemRenderType.EQUIPPED) { + renderEquipped(item, renderBlocks); + } else if (type == ItemRenderType.ENTITY) { + renderEntity(item, renderBlocks); + } else if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + renderEntity(item, renderBlocks); + } else { + System.out.println("FacadeRenderer.renderItem: Unsupported render type"); + } + } + + private void renderEntity(ItemStack item, RenderBlocks renderBlocks) { + GL11.glPushMatrix(); + GL11.glScalef(0.5f, 0.5f, 0.5f); + renderToInventory(item, renderBlocks); + GL11.glPopMatrix(); + } + + private void renderEquipped(ItemStack item, RenderBlocks renderBlocks) { + renderToInventory(item, renderBlocks); + } + + private void renderToInventory(ItemStack item, RenderBlocks renderBlocks) { + Tessellator.instance.startDrawingQuads(); + CubeRenderer.render(bb, item.getItem().getIconFromDamage(item.getItemDamage())); + Tessellator.instance.draw(); + } + +} diff --git a/common/crazypants/enderio/conduit/render/RoundedSegmentRenderer.java b/common/crazypants/enderio/conduit/render/RoundedSegmentRenderer.java new file mode 100644 index 00000000..86a583b4 --- /dev/null +++ b/common/crazypants/enderio/conduit/render/RoundedSegmentRenderer.java @@ -0,0 +1,186 @@ +package crazypants.enderio.conduit.render; + +import static crazypants.util.ForgeDirectionOffsets.offsetScaled; +import static net.minecraftforge.common.ForgeDirection.SOUTH; + +import java.util.ArrayList; +import java.util.List; + +import crazypants.enderio.conduit.geom.ConduitGeometryUtil; +import crazypants.render.BoundingBox; +import crazypants.util.ForgeDirectionOffsets; +import crazypants.vecmath.Matrix4d; +import crazypants.vecmath.Vector2d; +import crazypants.vecmath.Vector3d; +import crazypants.vecmath.Vector3f; + + +import net.minecraft.client.renderer.Tessellator; +import net.minecraftforge.common.ForgeDirection; + +public class RoundedSegmentRenderer { + + private static Coord[][] DIR_COORDS = new Coord[ForgeDirection.VALID_DIRECTIONS.length][]; + + private static final Vector3d REF_TRANS = new Vector3d(0.5, 0.5, 0.5); + + static { + double circ = ConduitGeometryUtil.WIDTH * 0.7; + + Coord[] refCoords = createUnitSectionQuads(16, -0.25, 0.25); + + for (Coord coord : refCoords) { + coord.xyz.x = coord.xyz.x * circ; + coord.xyz.y = coord.xyz.y * circ; + } + Matrix4d rotMat = new Matrix4d(); + rotMat.setIdentity(); + rotMat.setTranslation(REF_TRANS); + + DIR_COORDS[SOUTH.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.SOUTH, 0.25)); + + rotMat.makeRotationY(Math.PI); + rotMat.setTranslation(REF_TRANS); + DIR_COORDS[ForgeDirection.NORTH.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.NORTH, 0.25)); + + rotMat.makeRotationY(Math.PI / 2); + rotMat.setTranslation(REF_TRANS); + DIR_COORDS[ForgeDirection.EAST.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.EAST, 0.25)); + + rotMat.makeRotationY(-Math.PI / 2); + rotMat.setTranslation(REF_TRANS); + DIR_COORDS[ForgeDirection.WEST.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.WEST, 0.25)); + + rotMat.makeRotationX(-Math.PI / 2); + rotMat.setTranslation(REF_TRANS); + DIR_COORDS[ForgeDirection.UP.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.UP, 0.25)); + + rotMat.makeRotationX(Math.PI / 2); + rotMat.setTranslation(REF_TRANS); + DIR_COORDS[ForgeDirection.DOWN.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.DOWN, 0.25)); + + } + + + private static Coord[] xformCoords(Coord[] refCoords, Matrix4d rotMat, Vector3d trans) { + Coord[] res = new Coord[refCoords.length]; + for (int i = 0; i < res.length; i++) { + res[i] = new Coord(refCoords[i]); + rotMat.transform(res[i].xyz); + rotMat.transformNormal(res[i].normal); + res[i].xyz.add(trans); + } + return res; + } + + private static Coord[] xformCoords(List refCoords, Matrix4d rotMat, Vector3d trans) { + Coord[] res = new Coord[refCoords.size()]; + for (int i = 0; i < res.length; i++) { + res[i] = new Coord(refCoords.get(i)); + rotMat.transform(res[i].xyz); + rotMat.transformNormal(res[i].normal); + res[i].xyz.add(trans); + } + return res; + } + + public static Coord[] createUnitCrossSection(double xOffset, double yOffset, double zOffset, int numCoords, int u) { + + Coord[] crossSection = new Coord[numCoords]; + + double angle = 0; + double inc = (Math.PI * 2) / (crossSection.length - 1); + for (int i = 0; i < crossSection.length; i++) { + double x = Math.cos(angle) * 0.5; + double y = Math.sin(angle) * 0.5; + angle += inc; + crossSection[i] = new Coord(); + crossSection[i].setXYZ(xOffset + x, yOffset + y, zOffset); + crossSection[i].setNormal(x, y, 0); + crossSection[i].setUV(u, y + 0.5); + } + return crossSection; + + } + + public static void renderSegment(ForgeDirection dir, BoundingBox bounds, float minU, float maxU, float minV, float maxV) { + float uScale = maxU - minU; + float vScale = maxV - minV; + + Vector3d offset = calcOffset(dir, bounds); + + Tessellator tes = Tessellator.instance; + Coord[] coords = DIR_COORDS[dir.ordinal()]; + for (Coord coord : coords) { + double u = minU + (coord.uv.x * uScale); + double v = minV + (coord.uv.y * vScale); + tes.setNormal(coord.normal.x, coord.normal.y, coord.normal.z); + tes.addVertexWithUV(offset.x + coord.xyz.x, offset.y + coord.xyz.y, offset.z + coord.xyz.z, u, v); + } + } + + + private static Vector3d calcOffset(ForgeDirection dir, BoundingBox bounds) { + Vector3d res = new Vector3d(); + Vector3d center = bounds.getCenter(); + if(dir != ForgeDirection.UP && dir != ForgeDirection.DOWN) { + res.set(0, center.y - REF_TRANS.y,0); + } else { + res.set(center.x - REF_TRANS.x, 0,0); + } + return res; + } + + public static Coord[] createUnitSectionQuads(int numCoords, double minZ, double maxZ) { + + Coord[] z0 = createUnitCrossSection(0, 0, minZ, numCoords + 1, 0); + Coord[] z1 = createUnitCrossSection(0, 0, maxZ, numCoords + 1, 1); + + Coord[] result = new Coord[numCoords * 4]; + for (int i = 0; i < numCoords; i++) { + int index = i * 4; + result[index] = new Coord(z0[i]); + result[index + 1] = new Coord(z0[i + 1]); + result[index + 2] = new Coord(z1[i + 1]); + result[index + 3] = new Coord(z1[i]); + } + return result; + + } + + public static class Coord { + + Vector3d xyz = new Vector3d(); + Vector2d uv = new Vector2d(); + Vector3f normal = new Vector3f(); + + Coord() { + } + + Coord(Coord other) { + xyz.set(other.xyz); + uv.set(other.uv); + normal.set(other.normal); + } + + void setXYZ(double x, double y, double z) { + xyz.set(x, y, z); + } + + void setUV(double u, double v) { + uv.set(u, v); + } + + void setNormal(double x, double y, double z) { + normal.set((float)x,(float)y,(float)z); + normal.normalize(); + } + + @Override + public String toString() { + return "Coord [xyz=" + xyz + ", uv=" + uv + "]"; + } + + } + +} diff --git a/common/crazypants/enderio/enderface/BlockEnderIO.java b/common/crazypants/enderio/enderface/BlockEnderIO.java new file mode 100644 index 00000000..8fa7d2ea --- /dev/null +++ b/common/crazypants/enderio/enderface/BlockEnderIO.java @@ -0,0 +1,113 @@ +package crazypants.enderio.enderface; + +import net.minecraft.block.Block; +import net.minecraft.block.ITileEntityProvider; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChatMessageComponent; +import net.minecraft.util.Icon; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import crazypants.enderio.EnderIO; +import crazypants.enderio.EnderIOTab; +import crazypants.enderio.ModObject; + +public class BlockEnderIO extends Block implements ITileEntityProvider { + + public static BlockEnderIO create() { + BlockEnderIO result = new BlockEnderIO(); + result.init(); + return result; + } + + Icon frameIcon; + + private BlockEnderIO() { + super(ModObject.blockEnderIo.id, Material.rock); + setHardness(0.5F); + setStepSound(Block.soundStoneFootstep); + setUnlocalizedName(ModObject.blockEnderIo.unlocalisedName); + setCreativeTab(EnderIOTab.tabEnderIO); + } + + private void init() { + LanguageRegistry.addName(this, ModObject.blockEnderIo.name); + GameRegistry.registerBlock(this, ModObject.blockEnderIo.unlocalisedName); + GameRegistry.registerTileEntity(TileEnderIO.class, ModObject.blockEnderIo.unlocalisedName + "TileEntity"); + GameRegistry.addRecipe(new ItemStack(this), "zxz", "xyx", "zxz", 'x', new ItemStack(Item.eyeOfEnder), 'y', new ItemStack(Block.enderChest), 'z', + new ItemStack(Item.diamond)); + } + + @Override + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int par6, float par7, float par8, float par9) { + if (entityPlayer.isSneaking()) { + return false; + } + if (entityPlayer.getCurrentEquippedItem() != null && entityPlayer.getCurrentEquippedItem().itemID == EnderIO.itemEnderface.itemID) { + ItemStack enderFaceStack = entityPlayer.getCurrentEquippedItem(); + NBTTagCompound nbttagcompound = enderFaceStack.getTagCompound(); + if (nbttagcompound == null) { + nbttagcompound = new NBTTagCompound(); + } + nbttagcompound.setBoolean(ItemEnderface.KEY_IO_SET, true); + nbttagcompound.setInteger(ItemEnderface.KEY_IO_X, x); + nbttagcompound.setInteger(ItemEnderface.KEY_IO_Y, y); + nbttagcompound.setInteger(ItemEnderface.KEY_IO_Z, z); + nbttagcompound.setInteger(ItemEnderface.KEY_DIMENSION, world.provider.dimensionId); + enderFaceStack.setTagCompound(nbttagcompound); + + entityPlayer.setCurrentItemOrArmor(0, enderFaceStack); + + if (world.isRemote) { + ChatMessageComponent c = ChatMessageComponent.func_111066_d("EnderIO Interface Selected"); + entityPlayer.sendChatToPlayer(c); + } + + } + return true; + } + + @Override + public boolean renderAsNormalBlock() { + return false; + } + + @Override + public boolean isOpaqueCube() { + return false; + } + + @Override + public int getRenderType() { + return -1; + } + + @Override + public int getLightValue(IBlockAccess world, int x, int y, int z) { + return 13; + } + + @Override + public int getLightOpacity(World world, int x, int y, int z) { + return 100; + } + + @Override + public void registerIcons(IconRegister iconRegister) { + blockIcon = iconRegister.registerIcon("enderio:enderIO"); + frameIcon = iconRegister.registerIcon("enderio:enderIOFrame"); + } + + @Override + public TileEntity createNewTileEntity(World world) { + return new TileEnderIO(); + } + +} diff --git a/common/crazypants/enderio/enderface/ContainerWrapper.java b/common/crazypants/enderio/enderface/ContainerWrapper.java new file mode 100644 index 00000000..e0d3238b --- /dev/null +++ b/common/crazypants/enderio/enderface/ContainerWrapper.java @@ -0,0 +1,114 @@ +package crazypants.enderio.enderface; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +public class ContainerWrapper extends net.minecraft.inventory.Container { + + public net.minecraft.inventory.Container wrapped; + + public ContainerWrapper(net.minecraft.inventory.Container wrapped) { + this.wrapped = wrapped; + this.inventoryItemStacks = wrapped.inventoryItemStacks; + this.inventorySlots = wrapped.inventorySlots; + this.windowId = wrapped.windowId; + } + + @Override + public boolean canDragIntoSlot(Slot par1Slot) { + return wrapped.canDragIntoSlot(par1Slot); + } + + @Override + public boolean canInteractWith(net.minecraft.entity.player.EntityPlayer arg0) { + return true; + } + + @Override + public net.minecraft.inventory.Slot getSlot(int arg0) { + return wrapped.getSlot(arg0); + } + + @SuppressWarnings("rawtypes") + @Override + public java.util.List getInventory() { + return wrapped.getInventory(); + } + + @Override + public boolean enchantItem(net.minecraft.entity.player.EntityPlayer arg0, int arg1) { + return wrapped.enchantItem(arg0, arg1); + } + + @Override + public net.minecraft.item.ItemStack slotClick(int arg0, int arg1, int arg2, net.minecraft.entity.player.EntityPlayer arg3) { + return wrapped.slotClick(arg0, arg1, arg2, arg3); + } + + @Override + public boolean func_94530_a(net.minecraft.item.ItemStack arg0, net.minecraft.inventory.Slot arg1) { + return wrapped.func_94530_a(arg0, arg1); + } + + @Override + public void addCraftingToCrafters(net.minecraft.inventory.ICrafting arg0) { + wrapped.addCraftingToCrafters(arg0); + } + + @Override + public void detectAndSendChanges() { + wrapped.detectAndSendChanges(); + } + + @Override + public void removeCraftingFromCrafters(net.minecraft.inventory.ICrafting arg0) { + wrapped.removeCraftingFromCrafters(arg0); + } + + @Override + public net.minecraft.inventory.Slot getSlotFromInventory(net.minecraft.inventory.IInventory arg0, int arg1) { + return wrapped.getSlotFromInventory(arg0, arg1); + } + + @Override + public net.minecraft.item.ItemStack transferStackInSlot(net.minecraft.entity.player.EntityPlayer arg0, int arg1) { + return wrapped.transferStackInSlot(arg0, arg1); + } + + @Override + public void onCraftMatrixChanged(net.minecraft.inventory.IInventory arg0) { + wrapped.onCraftMatrixChanged(arg0); + } + + @Override + public void putStackInSlot(int arg0, net.minecraft.item.ItemStack arg1) { + wrapped.putStackInSlot(arg0, arg1); + } + + @Override + public void putStacksInSlots(net.minecraft.item.ItemStack[] arg0) { + wrapped.putStacksInSlots(arg0); + } + + @Override + public void updateProgressBar(int arg0, int arg1) { + wrapped.updateProgressBar(arg0, arg1); + } + + @Override + public short getNextTransactionID(net.minecraft.entity.player.InventoryPlayer arg0) { + return wrapped.getNextTransactionID(arg0); + } + + @Override + public boolean isPlayerNotUsingContainer(net.minecraft.entity.player.EntityPlayer arg0) { + return wrapped.isPlayerNotUsingContainer(arg0); + } + + @Override + public void setPlayerIsPresent(net.minecraft.entity.player.EntityPlayer arg0, boolean arg1) { + wrapped.setPlayerIsPresent(arg0, arg1); + } + +} diff --git a/common/crazypants/enderio/enderface/EnderIoRenderer.java b/common/crazypants/enderio/enderface/EnderIoRenderer.java new file mode 100644 index 00000000..0e830940 --- /dev/null +++ b/common/crazypants/enderio/enderface/EnderIoRenderer.java @@ -0,0 +1,157 @@ +package crazypants.enderio.enderface; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraftforge.client.IItemRenderer; + +import org.lwjgl.opengl.GL11; + +import crazypants.enderio.EnderIO; +import crazypants.render.BoundingBox; +import crazypants.render.CubeRenderer; +import crazypants.render.RenderUtil; +import crazypants.vecmath.Matrix4d; +import crazypants.vecmath.VecmathUtil; +import crazypants.vecmath.Vector3d; + + +public class EnderIoRenderer extends TileEntitySpecialRenderer implements IItemRenderer { + + @Override + public void renderTileEntityAt(TileEntity te, double x, double y, double z, float f) { + EntityLivingBase entityPlayer = tileEntityRenderer.entityLivingPlayer; + + Vector3d playerEye = new Vector3d(entityPlayer.posX, entityPlayer.posY + 1.62 - entityPlayer.yOffset, entityPlayer.posZ); + Vector3d blockOrigin = new Vector3d(te.xCoord + 0.5, te.yCoord + 0.5, te.zCoord + 0.5); + Matrix4d lookMat = VecmathUtil.createMatrixAsLookAt(blockOrigin, playerEye, RenderUtil.UP_V); + lookMat.setTranslation(new Vector3d()); + lookMat.invert(); + + int brightness = RenderUtil.setTesselatorBrightness(tileEntityRenderer.worldObj, te.xCoord, te.yCoord, te.zCoord); + render(x, y, z, lookMat, brightness); + } + + public void render(double x, double y, double z, Matrix4d lookMat, int brightness) { + + + GL11.glPushMatrix(); + GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); + + Icon tex = Item.eyeOfEnder.getIconFromDamage(0); + RenderUtil.bindItemTexture(); + float minU = tex.getMinU(); + float maxU = tex.getMaxU(); + float minV = tex.getMinV(); + float maxV = tex.getMaxV(); + + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glColor3f(1, 1, 1); + renderBillboard(lookMat, minU, maxU, minV, maxV, 0.8, brightness); + + // Glint + float maxUV = 32; + GL11.glDepthFunc(GL11.GL_EQUAL); + GL11.glDisable(GL11.GL_LIGHTING); + RenderUtil.bindGlintTexture(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); + float blendFactor = 1F; + GL11.glColor4f(0.5F * blendFactor, 0.25F * blendFactor, 0.8F * blendFactor, 1.0F); + + GL11.glMatrixMode(GL11.GL_TEXTURE); + GL11.glPushMatrix(); + float scale = 0.125F; + GL11.glScalef(scale, scale, scale); + float tans = Minecraft.getSystemTime() % 3000L / 3000.0F * 8.0F; + GL11.glTranslatef(tans, 0.0F, 0.0F); + GL11.glRotatef(-50.0F, 0.0F, 0.0F, 1.0F); + renderBillboard(lookMat, 0, maxUV, 0, maxUV, 0.8, brightness); + GL11.glPopMatrix(); + + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, scale); + tans = Minecraft.getSystemTime() % 4873L / 4873.0F * 8.0F; + GL11.glTranslatef(-tans, 0.0F, 0.0F); + GL11.glRotatef(10.0F, 0.0F, 0.0F, 1.0F); + renderBillboard(lookMat, 0, maxUV, 0, maxUV, 0.8,brightness); + GL11.glPopMatrix(); + + GL11.glMatrixMode(GL11.GL_MODELVIEW); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDepthFunc(GL11.GL_LEQUAL); + + + + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glPopMatrix(); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + + RenderUtil.bindBlockTexture(); + Tessellator.instance.startDrawingQuads(); + Tessellator.instance.setBrightness(brightness); + + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + CubeRenderer.render(BoundingBox.UNIT_CUBE, EnderIO.blockEnderIo.frameIcon); + Tessellator.instance.draw(); + GL11.glPopMatrix(); + + GL11.glDisable(GL11.GL_BLEND); + + } + + private 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(); + } + + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return true; + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + Matrix4d lookMat = new Matrix4d(); + lookMat.setIdentity(); + + lookMat = VecmathUtil.createMatrixAsLookAt(RenderUtil.ZERO_V, new Vector3d(1, 0, 0), RenderUtil.UP_V); + + render(0, 0, 0, lookMat, 0xF000F0); + + } + +} diff --git a/common/crazypants/enderio/enderface/GuiEnderface.java b/common/crazypants/enderio/enderface/GuiEnderface.java new file mode 100644 index 00000000..6d5be227 --- /dev/null +++ b/common/crazypants/enderio/enderface/GuiEnderface.java @@ -0,0 +1,507 @@ +package crazypants.enderio.enderface; + +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.tileentity.TileEntityRenderer; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; + +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import cpw.mods.fml.common.network.PacketDispatcher; +import crazypants.enderio.ModObject; +import crazypants.enderio.PacketHandler; +import crazypants.render.RenderUtil; +import crazypants.util.BlockCoord; +import crazypants.vecmath.Camera; +import crazypants.vecmath.Matrix4d; +import crazypants.vecmath.VecmathUtil; +import crazypants.vecmath.Vector3d; + +public class GuiEnderface extends GuiScreen { + + protected static final RenderBlocks RB = new RenderBlocks(); + + private float pitch = -45; + private float yaw = 45; + + private final EntityPlayer player; + private final World world; + private final int ioX; + private final int ioY; + private final int ioZ; + private boolean chunkLoaded; + + private List blocks = new ArrayList(); + + private int gw; + private int gh; + private int guiLeft; + private int guiTop; + private int finalGw; + private int finalGh; + // private boolean animateInX = true; + private boolean animateInX = false; + private boolean animateInY = false; + // private boolean animating = true; + float animationDuration = 180; + + private final Vector3d origin = new Vector3d(); + private final Vector3d eye = new Vector3d(); + private final Camera camera = new Camera(); + private final Matrix4d pitchRot = new Matrix4d(); + private final Matrix4d yawRot = new Matrix4d(); + + private float scaleAnimX; + + private int range; + + boolean dragging = false; + + private double distance; + + private long initTime; + + public GuiEnderface(EntityPlayer player, World world, int ioX, int ioY, int ioZ) { + this.player = player; + this.world = world; + this.ioX = ioX; + this.ioY = ioY; + this.ioZ = ioZ; + + distance = 10 + (range * 2); + + origin.set(ioX + 0.5, ioY + 0.5, ioZ + 0.5); + pitchRot.setIdentity(); + yawRot.setIdentity(); + + Chunk c = world.getChunkFromBlockCoords(ioX, ioZ); + chunkLoaded = c != null && c.isChunkLoaded; + RB.blockAccess = world; + + blocks.add(new ViewableBlocks(ioX, ioY, ioZ, ModObject.blockEnderIo.id)); + range = 3; + for (int x = ioX - range; x <= ioX + range; x++) { + for (int y = ioY - range; y <= ioY + range; y++) { + for (int z = ioZ - range; z <= ioZ + range; z++) { + int blockId = world.getBlockId(x, y, z); + if (blockId > 0 && blockId < Block.blocksList.length) { + blocks.add(new ViewableBlocks(x, y, z, blockId)); + } + } + } + } + } + + /** + * Adds the buttons (and other controls) to the screen in question. + */ + @Override + public void initGui() { + + finalGw = width * 1; + finalGh = height * 1; + // gw = finalGw - 1; + // gh = finalGh - 1; + gw = finalGw; + gh = finalGh; + // gw = 0; + // gh = 0; + guiLeft = (width - gw) / 2; + guiTop = (height - gh) / 2; + + initTime = world.getTotalWorldTime(); + } + + @Override + public boolean doesGuiPauseGame() { + return false; + } + + /** + * Handles mouse input. + */ + @Override + public void handleMouseInput() { + super.handleMouseInput(); + + if (Mouse.getEventButton() == 0) { + dragging = Mouse.getEventButtonState(); + } + + if (dragging) { + yaw -= (Mouse.getEventDX() / (double) mc.displayWidth) * 180; + pitch += (Mouse.getEventDY() / (double) mc.displayHeight) * 180; + pitch = (float) VecmathUtil.clamp(pitch, -80, 80); + } + + distance -= Mouse.getDWheel() * 0.01; + distance = VecmathUtil.clamp(distance, 0.1, 20); + + long elapsed = world.getTotalWorldTime() - initTime; + + if (Mouse.getEventButton() == 1 && !Mouse.getEventButtonState() && camera.isValid() && elapsed > 10) { + + int x = Mouse.getEventX(); + int y = Mouse.getEventY(); + Vector3d start = new Vector3d(); + Vector3d end = new Vector3d(); + if (camera.getRayForPixel(x, y, start, end)) { + end.scale(distance * 2); + end.add(start); + doSelection(start, end); + } + + } + + } + + private void doSelection(Vector3d start, Vector3d end) { + start.add(origin); + end.add(origin); + List hits = new ArrayList(); + for (ViewableBlocks ug : blocks) { + if (!ug.bc.equals(new BlockCoord(ioX, ioY, ioZ))) { + MovingObjectPosition res = Block.blocksList[ug.blockId].collisionRayTrace(world, ug.bc.x, ug.bc.y, ug.bc.z, + Vec3.createVectorHelper(start.x, start.y, start.z), Vec3.createVectorHelper(end.x, end.y, end.z)); + if (res != null) { + hits.add(res); + } + } + } + MovingObjectPosition hit = getClosestHit(Vec3.createVectorHelper(start.x, start.y, start.z), hits); + if (hit != null) { + int id = world.getBlockId(hit.blockX, hit.blockY, hit.blockZ); + openInterface(hit.blockX, hit.blockY, hit.blockZ); + } + + } + + public static MovingObjectPosition getClosestHit(Vec3 origin, Collection candidates) { + double minLengthSquared = Double.POSITIVE_INFINITY; + MovingObjectPosition closest = null; + + for (MovingObjectPosition hit : candidates) { + if (hit != null) { + double lengthSquared = hit.hitVec.squareDistanceTo(origin); + if (lengthSquared < minLengthSquared) { + minLengthSquared = lengthSquared; + closest = hit; + } + } + } + return closest; + } + + /** + * Draws the screen and all the components in it. + */ + @Override + public void drawScreen(int par1, int par2, float partialTick) { + + animateBackground(partialTick); + drawDefaultBackground(); + + RenderHelper.disableStandardItemLighting(); + RenderHelper.enableGUIStandardItemLighting(); + drawEnderfaceBackground(); + + if (!updateCamera(partialTick)) { + return; + } + applyCamera(partialTick); + + if (!animateInX && !animateInY) { + + if (chunkLoaded) { + + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + + RenderHelper.disableStandardItemLighting(); + mc.entityRenderer.enableLightmap(0); + RenderUtil.bindBlockTexture(); + + Vector3d trans = new Vector3d((-origin.x) + eye.x, (-origin.y) + eye.y, (-origin.z) + eye.z); + Tessellator.instance.startDrawingQuads(); + Tessellator.instance.setTranslation(trans.x, trans.y, trans.z); + for (ViewableBlocks ug : blocks) { + RB.setRenderBounds(0, 0, 0, 1, 1, 1); + RB.renderBlockByRenderType(Block.blocksList[ug.blockId], ug.bc.x, ug.bc.y, ug.bc.z); + } + Tessellator.instance.draw(); + Tessellator.instance.setTranslation(0, 0, 0); + + RenderHelper.enableStandardItemLighting(); + TileEntityRenderer.instance.playerX = origin.x - eye.x; + TileEntityRenderer.instance.playerY = origin.y - eye.y; + TileEntityRenderer.instance.playerZ = origin.z - eye.z; + TileEntityRenderer.staticPlayerX = origin.x - eye.x; + TileEntityRenderer.staticPlayerY = origin.y - eye.y; + TileEntityRenderer.staticPlayerZ = origin.z - eye.z; + for (ViewableBlocks ug : blocks) { + TileEntity tile = world.getBlockTileEntity(ug.bc.x, ug.bc.y, ug.bc.z); + if (tile != null) { + TileEntityRenderer.instance.renderTileEntity(tile, partialTick); + } + } + + // mc.entityRenderer.disableLightmap(0); + } else { + drawCenteredString(fontRenderer, "EnderIO chunk not loaded.", width / 2, height / 2 - 32, 0xFFFFFFFF); + } + } + drawEffectOverlay(partialTick); + } + + private boolean updateCamera(float partialTick) { + ScaledResolution scaledresolution = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight); + int vpx = guiLeft * scaledresolution.getScaleFactor(); + int vpy = guiTop * scaledresolution.getScaleFactor(); + int vpw = (int) ((float) gw / width * mc.displayWidth); + int vph = (int) ((float) gh / height * mc.displayHeight); + if (vpw <= 0 || vph <= 0) { + return false; + } + + camera.setViewport(vpx, vpy, vpw, vph); + camera.setProjectionMatrixAsPerspective(30, 0.05, 50, vpw, vph); + + eye.set(0, 0, distance); + pitchRot.makeRotationX(Math.toRadians(pitch)); + yawRot.makeRotationY(Math.toRadians(yaw)); + pitchRot.transform(eye); + yawRot.transform(eye); + camera.setViewMatrixAsLookAt(eye, RenderUtil.ZERO_V, RenderUtil.UP_V); + return camera.isValid(); + } + + private void applyCamera(float partialTick) { + Rectangle vp = camera.getViewport(); + GL11.glViewport(vp.x, vp.y, vp.width, vp.height); + GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); + GL11.glMatrixMode(GL11.GL_PROJECTION); + RenderUtil.loadMatrix(camera.getTransposeProjectionMatrix()); + GL11.glMatrixMode(GL11.GL_MODELVIEW); + RenderUtil.loadMatrix(camera.getTransposeViewMatrix()); + + scaleAnimX += (partialTick * 0.25); + float v = 0.4f; + float sf = 1.0F * (1 + v / 32); + GL11.glRotatef((scaleAnimX + partialTick) * 7, 0.0F, 1.0F, 1.0F); + GL11.glScalef(sf, 1.0F, 1.0f); + GL11.glRotatef(-(scaleAnimX + partialTick) * 7, 0.0F, 1.0F, 1.0F); + + GL11.glTranslatef(-(float) eye.x, -(float) eye.y, -(float) eye.z); + } + + private float portalFade = 1; + + private void drawEffectOverlay(float partialTick) { + ScaledResolution scaledresolution = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); + GL11.glMatrixMode(GL11.GL_PROJECTION); + GL11.glLoadIdentity(); + GL11.glOrtho(0.0D, scaledresolution.getScaledWidth_double(), scaledresolution.getScaledHeight_double(), 0.0D, 1000.0D, 3000.0D); + GL11.glMatrixMode(GL11.GL_MODELVIEW); + GL11.glLoadIdentity(); + GL11.glTranslatef(0.0F, 0.0F, -2000.0F); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glDepthMask(false); + + RenderHelper.disableStandardItemLighting(); + RenderHelper.enableGUIStandardItemLighting(); + + GL11.glDisable(GL11.GL_LIGHTING); + mc.entityRenderer.disableLightmap(0); + + portalFade -= (partialTick * (1f / animationDuration)); + portalFade = Math.max(0, portalFade); + if (portalFade >= 0) { + drawRect(scaledresolution.getScaledWidth(), scaledresolution.getScaledHeight(), 0, 0.3f, 0.16f, Math.max(0.3f, portalFade)); + } + + GL11.glEnable(GL11.GL_LIGHTING); + mc.entityRenderer.enableLightmap(0); + + renderPortalOverlay(0.9f - (0.1f * (1 - portalFade)), scaledresolution.getScaledWidth(), scaledresolution.getScaledHeight()); + + GL11.glDepthMask(true); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + } + + /** + * Renders the portal overlay. Args: portalStrength, width, height + */ + protected void renderPortalOverlay(float par1, int par2, int par3) { + if (par1 < 1.0F) { + par1 *= par1; + par1 *= par1; + par1 = par1 * 0.8F + 0.2F; + } + GL11.glColor4f(1.0F, 1.0F, 1.0F, par1); + RenderUtil.bindBlockTexture(); + Icon icon = Block.portal.getBlockTextureFromSide(1); + float f1 = icon.getMinU(); + float f2 = icon.getMinV(); + float f3 = icon.getMaxU(); + float f4 = icon.getMaxV(); + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV(0.0D, par3, -90.0D, f1, f4); + tessellator.addVertexWithUV(par2, par3, -90.0D, f3, f4); + tessellator.addVertexWithUV(par2, 0.0D, -90.0D, f3, f2); + tessellator.addVertexWithUV(0.0D, 0.0D, -90.0D, f1, f2); + tessellator.draw(); + } + + private boolean animating() { + return gw < finalGw || gh < finalGh; + } + + private void drawRect(int width, int height, float r, float g, + float b, float a) { + Tessellator tessellator = Tessellator.instance; + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(r, g, b, a); + tessellator.startDrawingQuads(); + tessellator.addVertex(0.0D, height, 0.0D); + tessellator.addVertex(width, height, 0.0D); + tessellator.addVertex(width, 0.0D, 0.0D); + tessellator.addVertex(0.0D, 0.0D, 0.0D); + tessellator.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } + + private void animateBackground(float partialTick) { + + if (!animating()) { + return; + } + + // if (animateInX) { + // animationDuration *= 0.8; + // } + int mag = (int) ((width / (animationDuration * 0.5f)) * partialTick); + int mag2 = mag * 2; + + int ymag = (int) ((height / (animationDuration * 0.5f)) * partialTick); + // int ymag = mag; + int ymag2 = ymag * 2; + + if (animateInX) { + gw -= mag2; + guiLeft += mag; + if (gw <= 0) { + animateInX = false; + // animateInY = false; + } + } else { + gw += mag2; + guiLeft -= mag; + } + + if (animateInY) { + gh -= ymag2; + guiTop += ymag; + if (gh <= 0) { + animateInY = false; + // animateInX= false; + } + } else { + gh += ymag2; + guiTop -= ymag; + } + + gw = Math.min(gw, finalGw); + gh = Math.min(gh, finalGh); + guiLeft = Math.max((width - finalGw) / 2, guiLeft); + guiTop = Math.max((height - finalGh) / 2, guiTop); + + } + + private void drawEnderfaceBackground() { + + int w = this.gw; + int h = this.gh; + int left = this.guiLeft; + int top = this.guiTop; + int cx = left + w / 2; + int cy = top + h / 2; + + // black outline + drawRect(left, top, left + w, top + h, 0xFF000000); + left += 1; + top += 1; + w -= 2; + h -= 2; + + // border + int topH = 0xFFFFFFFF; + int botH = 0xFF555555; + int rightH = 0xFF555555; + int leftH = 0xFFFFFFFF; + if (animateInX) { + leftH = 0xFF555555; + rightH = 0xFFFFFFFF; + } + if (animateInY) { + topH = 0xFF555555; + botH = 0xFFFFFFFF; + } + + // drawRect(left, top, left + w, top + 1, topH); + // drawRect(left, top, left + 1, top + h, leftH); + // drawRect(left + w - 1, top + 1, left + w, top + h, rightH); + // drawRect(left + 1, top + h - 1, left + w, top + h, botH); + + left += 1; + top += 1; + w -= 2; + h -= 2; + // green background + // drawRect(left, top, left + w, top + h, 0xFF004C2A); + drawRect(left, top, left + w, top + h, 0xFF00331C); + + } + + void openInterface(int targetX, int targetY, int targetZ) { + Packet250CustomPayload pkt = PacketHandler.getPacketEnderface(targetX, targetY, targetZ); + PacketDispatcher.sendPacketToServer(pkt); + } + + static class ViewableBlocks { + BlockCoord bc; + int blockId; + + private ViewableBlocks(int x, int y, int z, int blockId) { + super(); + this.bc = new BlockCoord(x, y, z); + this.blockId = blockId; + } + + } + +} diff --git a/common/crazypants/enderio/enderface/ItemEnderface.java b/common/crazypants/enderio/enderface/ItemEnderface.java new file mode 100644 index 00000000..63c12741 --- /dev/null +++ b/common/crazypants/enderio/enderface/ItemEnderface.java @@ -0,0 +1,122 @@ +package crazypants.enderio.enderface; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChatMessageComponent; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import cpw.mods.fml.common.network.IGuiHandler; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import crazypants.enderio.EnderIO; +import crazypants.enderio.EnderIOTab; +import crazypants.enderio.GuiHandler; +import crazypants.enderio.ModObject; + +public class ItemEnderface extends Item implements IGuiHandler { + + public static final String KEY_IO_SET = "enderFaceIoSet"; + public static final String KEY_IO_X = "enderFaceIoX"; + public static final String KEY_IO_Y = "enderFaceIoY"; + public static final String KEY_IO_Z = "enderFaceIoZ"; + public static final String KEY_DIMENSION = "enderFaceDimension"; + + public static ItemEnderface create() { + ItemEnderface result = new ItemEnderface(); + result.init(); + return result; + } + + protected ItemEnderface() { + super(ModObject.itemEnderface.id); + setCreativeTab(EnderIOTab.tabEnderIO); + setUnlocalizedName(ModObject.itemEnderface.unlocalisedName); + setMaxStackSize(1); + } + + protected void init() { + LanguageRegistry.addName(this, ModObject.itemEnderface.name); + GameRegistry.addRecipe(new ItemStack(this), " x ", "xyx", " x ", 'x', new ItemStack(Item.diamond), 'y', new ItemStack(Item.eyeOfEnder)); + GameRegistry.registerItem(this, ModObject.itemEnderface.unlocalisedName); + EnderIO.guiHandler.registerGuiHandler(GuiHandler.GUI_ID_ENDERFACE, this); + } + + @Override + public void registerIcons(IconRegister iconRegister) { + itemIcon = iconRegister.registerIcon("enderio:enderface"); + } + + @Override + public boolean hasEffect(ItemStack par1ItemStack, int pass) { + return true; + } + + @Override + public void onCreated(ItemStack itemStack, World world, EntityPlayer entityPlayer) { + super.onCreated(itemStack, world, entityPlayer); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setBoolean(KEY_IO_SET, false); + nbttagcompound.setInteger(KEY_IO_X, -1); + nbttagcompound.setInteger(KEY_IO_Y, -1); + nbttagcompound.setInteger(KEY_IO_Z, -1); + nbttagcompound.setInteger(KEY_DIMENSION, -1); + itemStack.setTagCompound(nbttagcompound); + } + + @Override + public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + return null; + } + + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + return new GuiEnderface(player, world, x, y, z); + } + + @Override + public ItemStack onItemRightClick(ItemStack itemStack, World world, final EntityPlayer entityPlayer) { + + if (!world.isRemote) { + return itemStack; + } + + NBTTagCompound tag = itemStack.getTagCompound(); + boolean tagsSet = tag != null && tag.getBoolean(KEY_IO_SET); + + if (tag != null && tag.getBoolean(KEY_IO_SET)) { + + int x = tag.getInteger(KEY_IO_X); + int y = tag.getInteger(KEY_IO_Y); + int z = tag.getInteger(KEY_IO_Z); + int dimension = tag.getInteger(KEY_DIMENSION); + + if(world.provider.dimensionId != dimension) { + ChatMessageComponent c = ChatMessageComponent.func_111066_d("EnderIO block is in a different dimension."); + entityPlayer.sendChatToPlayer(c); + return itemStack; + } + + Chunk c = world.getChunkFromBlockCoords(x, z); + if(c == null || !c.isChunkLoaded) { + ChatMessageComponent cm = ChatMessageComponent.func_111066_d("EnderIO block's chunk is not loaded."); + entityPlayer.sendChatToPlayer(cm); + return itemStack; + } + int blockId = world.getBlockId(x, y, z); + if (blockId != EnderIO.blockEnderIo.blockID) { + ChatMessageComponent cm = ChatMessageComponent.func_111066_d("EnderIO block has been destroyed."); + entityPlayer.sendChatToPlayer(cm); + return itemStack; + } + entityPlayer.openGui(EnderIO.instance, GuiHandler.GUI_ID_ENDERFACE, world, x, y, z); + return itemStack; + } + ChatMessageComponent cm = ChatMessageComponent.func_111066_d(" Enderface not synchronized with EnderIO."); + entityPlayer.sendChatToPlayer(cm); + return itemStack; + } + +} diff --git a/common/crazypants/enderio/enderface/TileEnderIO.java b/common/crazypants/enderio/enderface/TileEnderIO.java new file mode 100644 index 00000000..68d314f0 --- /dev/null +++ b/common/crazypants/enderio/enderface/TileEnderIO.java @@ -0,0 +1,7 @@ +package crazypants.enderio.enderface; + +import net.minecraft.tileentity.TileEntity; + +public class TileEnderIO extends TileEntity { + +} diff --git a/common/crazypants/enderio/machine/AbstractMachineBlock.java b/common/crazypants/enderio/machine/AbstractMachineBlock.java new file mode 100644 index 00000000..79fab59e --- /dev/null +++ b/common/crazypants/enderio/machine/AbstractMachineBlock.java @@ -0,0 +1,246 @@ +package crazypants.enderio.machine; + +import java.util.Random; + +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.MapColor; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.util.MathHelper; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.network.IGuiHandler; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.ClientProxy; +import crazypants.enderio.EnderIO; +import crazypants.enderio.EnderIOTab; +import crazypants.enderio.ModObject; +import crazypants.render.IconUtil; + +public abstract class AbstractMachineBlock extends BlockContainer implements IGuiHandler { + + public static final Icon[] REDSTONE_CONTROL_ICONS = new Icon[RedstoneControlMode.values().length]; + + static { + IconUtil.addIconProvider(new IconUtil.IIconProvider() { + + @Override + public void registerIcons(IconRegister iconRegister) { + REDSTONE_CONTROL_ICONS[RedstoneControlMode.IGNORE.ordinal()] = iconRegister.registerIcon("enderio:iconRedstoneIgnore"); + REDSTONE_CONTROL_ICONS[RedstoneControlMode.ON.ordinal()] = iconRegister.registerIcon("enderio:iconRedstoneOn"); + REDSTONE_CONTROL_ICONS[RedstoneControlMode.OFF.ordinal()] = iconRegister.registerIcon("enderio:iconRedstoneOff"); + } + + @Override + public int getTextureType() { + return 0; + } + + }); + } + + @SideOnly(Side.CLIENT) + public static Icon getRedstoneControlIcon(RedstoneControlMode mode) { + return REDSTONE_CONTROL_ICONS[mode.ordinal()]; + } + + @SideOnly(Side.CLIENT) + protected Icon[][] iconBuffer; + + protected final Random random; + + protected final ModObject modObject; + + protected final Class teClass; + + protected AbstractMachineBlock(ModObject mo, Class teClass) { + super(mo.id, new Material(MapColor.ironColor)); + modObject = mo; + this.teClass = teClass; + setHardness(2.0F); + setStepSound(soundMetalFootstep); + setUnlocalizedName(mo.unlocalisedName); + setCreativeTab(EnderIOTab.tabEnderIO); + random = new Random(); + + } + + protected void init() { + LanguageRegistry.addName(this, modObject.name); + GameRegistry.registerBlock(this, modObject.unlocalisedName); + GameRegistry.registerTileEntity(teClass, modObject.unlocalisedName + "TileEntity"); + EnderIO.guiHandler.registerGuiHandler(getGuiId(), this); + } + + @Override + public TileEntity createNewTileEntity(World world) { + return null; + } + + @Override + public TileEntity createTileEntity(World world, int metadata) { + try { + return teClass.newInstance(); + } catch (Exception e) { + FMLCommonHandler.instance().raiseException(e, "Could not create tile entity from class " + teClass, true); + return null; + } + } + + @Override + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int par6, float par7, float par8, float par9) { + if (entityPlayer.isSneaking()) { + return false; + } + entityPlayer.openGui(EnderIO.instance, getGuiId(), world, x, y, z); + return true; + } + + @Override + public void registerIcons(IconRegister iconRegister) { + + iconBuffer = new Icon[1][12]; + // first the 6 sides in OFF state + iconBuffer[0][0] = iconRegister.registerIcon("enderio:machineSide"); + iconBuffer[0][1] = iconRegister.registerIcon("enderio:machineSide"); + iconBuffer[0][2] = iconRegister.registerIcon("enderio:machineSide"); + iconBuffer[0][3] = iconRegister.registerIcon(getMachineFrontIconKey(false)); + iconBuffer[0][4] = iconRegister.registerIcon("enderio:machineSide"); + iconBuffer[0][5] = iconRegister.registerIcon("enderio:machineSide"); + + iconBuffer[0][6] = iconRegister.registerIcon("enderio:machineSide"); + iconBuffer[0][7] = iconRegister.registerIcon("enderio:machineSide"); + iconBuffer[0][8] = iconRegister.registerIcon("enderio:machineSide"); + iconBuffer[0][9] = iconRegister.registerIcon(getMachineFrontIconKey(true)); + iconBuffer[0][10] = iconRegister.registerIcon("enderio:machineSide"); + iconBuffer[0][11] = iconRegister.registerIcon("enderio:machineSide"); + + } + + @Override + public Icon getBlockTexture(IBlockAccess world, int x, int y, int z, int blockSide) { + // used to render the block in the world + TileEntity te = world.getBlockTileEntity(x, y, z); + int facing = 0; + if (te instanceof AbstractMachineEntity) { + AbstractMachineEntity me = (AbstractMachineEntity) te; + facing = me.facing; + } + if (isActive(world, x, y, z)) { + return iconBuffer[0][ClientProxy.sideAndFacingToSpriteOffset[blockSide][facing] + 6]; + } else { + return iconBuffer[0][ClientProxy.sideAndFacingToSpriteOffset[blockSide][facing]]; + } + } + + @Override + public Icon getIcon(int blockSide, int blockMeta) { + // This is used to render the block as an item + return iconBuffer[0][blockSide]; + } + + @Override + public void breakBlock(World world, int x, int y, int z, int par5, int par6) { + @SuppressWarnings("unchecked") + T te = (T) world.getBlockTileEntity(x, y, z); + if (te != null) { + dropContent(0, te, world, te.xCoord, te.yCoord, te.zCoord); + } + super.breakBlock(world, x, y, z, par5, par6); + } + + public void dropContent(int newSize, T inventory, World world, int xCoord, int yCoord, int zCoord) { + for (int i = newSize; i < inventory.getSizeInventory(); i++) { + ItemStack itemstack = inventory.getStackInSlot(i); + if (itemstack == null) { + continue; + } + float f = random.nextFloat() * 0.8F + 0.1F; + float f1 = random.nextFloat() * 0.8F + 0.1F; + float f2 = random.nextFloat() * 0.8F + 0.1F; + + EntityItem entityitem = new EntityItem(world, xCoord + f, (float) yCoord + (newSize > 0 ? 1 : 0) + f1, zCoord + f2, new ItemStack( + itemstack.itemID, itemstack.stackSize, itemstack.getItemDamage())); + float f3 = 0.05F; + entityitem.motionX = (float) random.nextGaussian() * f3; + entityitem.motionY = (float) random.nextGaussian() * f3 + 0.2F; + entityitem.motionZ = (float) random.nextGaussian() * f3; + if (itemstack.hasTagCompound()) { + entityitem.getEntityItem().setTagCompound((NBTTagCompound) itemstack.getTagCompound().copy()); + } + world.spawnEntityInWorld(entityitem); + } + } + + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack) { + super.onBlockPlacedBy(world, x, y, z, player, stack); + int heading = MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; + AbstractMachineEntity te = (AbstractMachineEntity) world.getBlockTileEntity(x, y, z); + switch (heading) { + case 0: + te.setFacing((short) 2); + break; + case 1: + te.setFacing((short) 5); + break; + case 2: + te.setFacing((short) 3); + break; + case 3: + te.setFacing((short) 4); + break; + default: + break; + } + world.markBlockForUpdate(x, y, z); + } + + @Override + public void onBlockAdded(World world, int x, int y, int z) { + super.onBlockAdded(world, x, y, z); + world.markBlockForUpdate(x, y, z); + } + + @Override + public void onNeighborBlockChange(World world, int x, int y, int z, int blockId) { + AbstractMachineEntity te = (AbstractMachineEntity) world.getBlockTileEntity(x, y, z); + te.onNeighborBlockChange(blockId); + } + + @Override + public void randomDisplayTick(World world, int x, int y, int z, Random rand) { + // If active, randomly throw some smoke around + if (isActive(world, x, y, z)) { + float startX = x + 1.0F; + float startY = y + 1.0F; + float startZ = z + 1.0F; + for (int i = 0; i < 4; i++) { + float xOffset = -0.2F - rand.nextFloat() * 0.6F; + float yOffset = -0.1F + rand.nextFloat() * 0.2F; + float zOffset = -0.2F - rand.nextFloat() * 0.6F; + world.spawnParticle("smoke", startX + xOffset, startY + yOffset, startZ + zOffset, 0.0D, 0.0D, 0.0D); + } + } + } + + protected abstract int getGuiId(); + + protected abstract String getMachineFrontIconKey(boolean active); + + private boolean isActive(IBlockAccess blockAccess, int x, int y, int z) { + return ((AbstractMachineEntity) blockAccess.getBlockTileEntity(x, y, z)).isActive(); + } + +} diff --git a/common/crazypants/enderio/machine/AbstractMachineEntity.java b/common/crazypants/enderio/machine/AbstractMachineEntity.java new file mode 100644 index 00000000..e969c257 --- /dev/null +++ b/common/crazypants/enderio/machine/AbstractMachineEntity.java @@ -0,0 +1,353 @@ +package crazypants.enderio.machine; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.PacketHandler; +import crazypants.enderio.power.*; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.*; +import net.minecraft.network.packet.Packet; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.power.*; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; + +public abstract class AbstractMachineEntity extends TileEntity implements IInventory, IInternalPowerReceptor, IMachine { + + public short facing; + + // Client sync monitoring + protected int ticksSinceSync = -1; + protected boolean firstUpdate = true; + protected boolean lastActive; + protected float lastSyncPowerStored = -1; + + // Power + protected ICapacitor capacitor; + + // Used on the client as the power provided isn't sinked + private float storedEnergy; + + + protected ItemStack[] inventory; + protected final int inventorySize; + + protected PowerHandler powerHandler; + + protected RedstoneControlMode redstoneControlMode; + + protected boolean redstoneCheckPassed; + + public AbstractMachineEntity(int inventorySize, Type powerType) { + this.inventorySize = inventorySize; + facing = 3; + capacitor = new BasicCapacitor(); + powerHandler = PowerHandlerUtil.createHandler(capacitor, this, powerType); + + inventory = new ItemStack[inventorySize]; + + redstoneControlMode = RedstoneControlMode.IGNORE; + } + + public AbstractMachineEntity(int inventorySize) { + this(inventorySize, Type.MACHINE); + } + + public RedstoneControlMode getRedstoneControlMode() { + return redstoneControlMode; + } + + public void setRedstoneControlMode(RedstoneControlMode redstoneControlMode) { + this.redstoneControlMode = redstoneControlMode; + } + + @Override + public PowerHandler getPowerHandler() { + return powerHandler; + } + + @Override + public void applyPerdition() { + // TODO Apply values derived capcitor + + } + + public short getFacing() { + return facing; + } + + public void setFacing(short facing) { + this.facing = facing; + } + + public abstract boolean isActive(); + + public abstract float getProgress(); + + public int getProgressScaled(int scale) { + int result = (int) (getProgress() * scale); + return result; + } + + // --- Power + // -------------------------------------------------------------------------------------- + + public boolean hasPower() { + boolean hasPower = powerHandler.getEnergyStored() > 0; + return hasPower; + } + + public ICapacitor getCapacitor() { + return capacitor; + } + + public int getEnergyStoredScaled(int scale) { + // NB: called on the client so can't use the power provider + return (int) (scale * (storedEnergy / capacitor.getMaxEnergyStored())); + } + + public float getEnergyStored() { + return storedEnergy; + } + + // Needs NBT support for this + // public void setCapacitor(ICapacitor capacitor) { + // this.capacitor = capacitor; + // powerProvider.setCapacitor(capacitor); + // } + + @Override + public void doWork(PowerHandler workProvider) { + } + + @Override + public PowerReceiver getPowerReceiver(ForgeDirection side) { + return powerHandler.getPowerReceiver(); + } + + @Override + public World getWorld() { + return worldObj; + } + + protected float getPowerUsePerTick() { + return capacitor.getMaxEnergyExtracted(); + } + + // --- Process Loop + // -------------------------------------------------------------------------- + + @Override + public void updateEntity() { + + if (worldObj == null) { // sanity check + return; + } + + if (worldObj.isRemote) { + // check if the block on the client needs to update its texture + if (isActive() != lastActive) { + worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord); + } + lastActive = isActive(); + return; + + } // else is server, do all logic only on the server + + float stored = powerHandler.getEnergyStored(); + powerHandler.update(); + powerHandler.setEnergy(stored); + + boolean requiresClientSync = false; + if (firstUpdate) { + // First update, send state to client + firstUpdate = false; + requiresClientSync = true; + } + + redstoneCheckPassed = true; + if(redstoneControlMode == RedstoneControlMode.ON) { + int powerLevel = worldObj.getStrongestIndirectPower(xCoord, yCoord, zCoord); + if(powerLevel < 1) { + redstoneCheckPassed = false; + } + } else if(redstoneControlMode == RedstoneControlMode.OFF) { + int powerLevel = worldObj.getStrongestIndirectPower(xCoord, yCoord, zCoord); + if(powerLevel > 0) { + redstoneCheckPassed = false; + } + } + + + requiresClientSync |= processTasks(redstoneCheckPassed); + + + // Update if our power has changed by more than 1% + requiresClientSync |= Math.abs(lastSyncPowerStored - powerHandler.getEnergyStored()) > powerHandler.getMaxEnergyStored() / 100; + + if (requiresClientSync) { + lastSyncPowerStored = powerHandler.getEnergyStored(); + // this will cause 'getPacketDescription()' to be called and its result + // will be sent to the PacketHandler on the other end of + // client/server connection + worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); + // And this will make sure our current tile entity state is saved + worldObj.updateTileEntityChunkAndDoNothing(xCoord, yCoord, zCoord, this); + } + + } + + protected abstract boolean processTasks(boolean redstoneCheckPassed); + + + // ---- Tile Entity + // ------------------------------------------------------------------------------ + + + + @Override + public Packet getDescriptionPacket() { + return PacketHandler.getPacket(this); + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + super.readFromNBT(nbtRoot); + + facing = nbtRoot.getShort("facing"); + + float storedEnergy = nbtRoot.getFloat("storedEnergy"); + powerHandler.setEnergy(storedEnergy); + // For the client as provider is not saved to NBT + this.storedEnergy = storedEnergy; + + // read in the inventories contents + inventory = new ItemStack[inventorySize]; + NBTTagList itemList = nbtRoot.getTagList("Items"); + + for (int i = 0; i < itemList.tagCount(); i++) { + NBTTagCompound itemStack = (NBTTagCompound) itemList.tagAt(i); + byte slot = itemStack.getByte("Slot"); + if (slot >= 0 && slot < inventory.length) { + inventory[slot] = ItemStack.loadItemStackFromNBT(itemStack); + } + } + + int rsContr = nbtRoot.getInteger("redstoneControlMode"); + if(rsContr < 0 || rsContr >= RedstoneControlMode.values().length) { + rsContr = 0; + } + redstoneControlMode = RedstoneControlMode.values()[rsContr]; + + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + nbtRoot.setShort("facing", facing); + nbtRoot.setFloat("storedEnergy", powerHandler.getEnergyStored()); + + // write inventory list + NBTTagList itemList = new NBTTagList(); + for (int i = 0; i < inventory.length; i++) { + if (inventory[i] != null) { + NBTTagCompound itemStackNBT = new NBTTagCompound(); + itemStackNBT.setByte("Slot", (byte) i); + inventory[i].writeToNBT(itemStackNBT); + itemList.appendTag(itemStackNBT); + } + } + nbtRoot.setTag("Items", itemList); + + nbtRoot.setInteger("redstoneControlMode", redstoneControlMode.ordinal()); + } + + // ---- Inventory + // ------------------------------------------------------------------------------ + + @Override + public boolean isInvNameLocalized() { + return false; + } + + @Override + public boolean isUseableByPlayer(EntityPlayer player) { + if (worldObj == null) { + return true; + } + if (worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this) { + return false; + } + return player.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64D; + } + + @Override + public int getSizeInventory() { + return inventorySize; + } + + @Override + public int getInventoryStackLimit() { + return 64; + } + + @Override + public ItemStack getStackInSlot(int slot) { + return inventory[slot]; + } + + @Override + public ItemStack decrStackSize(int fromSlot, int amount) { + ItemStack fromStack = inventory[fromSlot]; + if (fromStack == null) { + return null; + } + if (fromStack.stackSize <= amount) { + inventory[fromSlot] = null; + return fromStack; + } + ItemStack result = new ItemStack(fromStack.itemID, amount, fromStack.getItemDamage()); + if (fromStack.stackTagCompound != null) { + result.stackTagCompound = (NBTTagCompound) fromStack.stackTagCompound.copy(); + } + fromStack.stackSize -= amount; + return result; + } + + @Override + public void setInventorySlotContents(int slot, ItemStack contents) { + if (contents == null) { + inventory[slot] = contents; + } else { + inventory[slot] = contents.copy(); + } + + if (contents != null && contents.stackSize > getInventoryStackLimit()) { + contents.stackSize = getInventoryStackLimit(); + } + } + + @Override + public ItemStack getStackInSlotOnClosing(int i) { + return null; + } + + @Override + public void openChest() { + } + + @Override + public void closeChest() { + } + + public void onNeighborBlockChange(int blockId) { + } + + + +} diff --git a/common/crazypants/enderio/machine/AbstractPoweredTaskEntity.java b/common/crazypants/enderio/machine/AbstractPoweredTaskEntity.java new file mode 100644 index 00000000..2158b289 --- /dev/null +++ b/common/crazypants/enderio/machine/AbstractPoweredTaskEntity.java @@ -0,0 +1,189 @@ +package crazypants.enderio.machine; + +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public abstract class AbstractPoweredTaskEntity extends AbstractMachineEntity implements ISidedInventory { + + protected PoweredTask currentTask = null; + + public AbstractPoweredTaskEntity(int inventorySize) { + super(inventorySize); + } + + @Override + public int[] getAccessibleSlotsFromSide(int var1) { + int[] res = new int[inventory.length]; + for(int i=0;i maxInputIndex) { + return false; + } + if (!isItemValidForSlot(i, itemstack)) { + return false; + } + if (inventory[i] == null) { + return true; + } + if (inventory[i].stackSize + itemstack.stackSize > inventory[i].getMaxStackSize()) { + return false; + } + return inventory[i].isItemEqual(itemstack); + } + + @Override + public boolean canExtractItem(int i, ItemStack itemstack, int j) { + int outputIndex = inventory.length - 1; + if (outputIndex != 2) { + return false; + } + if (inventory[outputIndex] == null || inventory[outputIndex].stackSize < itemstack.stackSize) { + return false; + } + return itemstack.itemID == inventory[outputIndex].itemID; + } + + @Override + public boolean isActive() { + return currentTask == null ? false : currentTask.getProgress() > 0 && hasPower() && redstoneCheckPassed; + } + + @Override + public float getProgress() { + return currentTask == null ? 0 : currentTask.getProgress(); + } + + @Override + protected boolean processTasks(boolean redstoneChecksPassed) { + + if(!redstoneChecksPassed) { + return false; + } + + boolean requiresClientSync = false; + // Process any current items + requiresClientSync |= checkProgress(); + + // Then see if we need to start a new one + IMachineRecipe nextRecipe = canStartNextTask(); + if (nextRecipe != null) { + requiresClientSync |= startNextTask(nextRecipe); + } + return requiresClientSync; + } + + protected boolean checkProgress() { + if (currentTask == null || !hasPower()) { + return false; + } + float used = powerHandler.useEnergy(0, getPowerUsePerTick(), true); + currentTask.update(used); + // then check if we are done + if (currentTask.isComplete()) { + taskComplete(); + } + return true; + } + + protected void taskComplete() { + int outputIndex = inventory.length - 1; + if (currentTask != null) { + ItemStack result = currentTask.getCompletedResult()[0]; + if (inventory[outputIndex] == null) { + inventory[outputIndex] = result.copy(); + } else { + int newStackSize = inventory[outputIndex].stackSize += result.stackSize; + inventory[outputIndex] = result.copy(); + inventory[outputIndex].stackSize = newStackSize; + } + } + currentTask = null; + } + + protected RecipeInput[] getInputs() { + RecipeInput[] res = new RecipeInput[inventorySize - 1]; + for(int i=0;i < res.length;i++) { + res[i] = new RecipeInput(i, inventory[i]); + } + return res; + } + + protected IMachineRecipe canStartNextTask() { + if (currentTask != null) { + return null; // already cooking something + } + if (!hasPower()) { + return null; // no heat to cook + } + + IMachineRecipe nextRecipe = MachineRecipeRegistry.instance.getRecipeForInputs(getMachineName(), getInputs()); + if (nextRecipe == null) { + return null; // no template + } + + int outputIndex = inventory.length - 1; + // make sure we can merge the recipe output with our result + if (inventory[outputIndex] == null) { + return nextRecipe; + } + ItemStack nextResult = nextRecipe.getCompletedResult(getInputs())[0]; + if (inventory[outputIndex].stackSize + nextResult.stackSize > inventory[outputIndex].getMaxStackSize()) { + return null; // no room for output + } + + if(!canMergeWithCurrentOuput(nextResult)) { + return null; + } + + return nextRecipe; + } + + protected boolean canMergeWithCurrentOuput(ItemStack nextResult) { + if (!nextResult.isItemEqual(inventory[inventory.length - 1])) { + // next result is a different item type + return false; + } + return true; + } + + protected boolean startNextTask(IMachineRecipe nextRecipe) { + if (hasPower() && nextRecipe.isRecipe(getInputs())) { + // then get our recipe and take away the source items + currentTask = new PoweredTask(nextRecipe, getInputs()); + for(RecipeInput input : getInputs()) { + int consumed = nextRecipe.getQuantityConsumed(input); + decrStackSize(input.slotNumber, consumed); + } + return true; + } + return false; + } + + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + super.readFromNBT(nbtRoot); + currentTask = PoweredTask.readFromNBT(nbtRoot.getCompoundTag("currentTask")); + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + if (currentTask != null) { + NBTTagCompound currentTaskNBT = new NBTTagCompound(); + currentTask.writeToNBT(currentTaskNBT); + nbtRoot.setCompoundTag("currentTask", currentTaskNBT); + } + } + + + +} diff --git a/common/crazypants/enderio/machine/BlockElectricLight.java b/common/crazypants/enderio/machine/BlockElectricLight.java new file mode 100644 index 00000000..79f75c15 --- /dev/null +++ b/common/crazypants/enderio/machine/BlockElectricLight.java @@ -0,0 +1,95 @@ +package crazypants.enderio.machine; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.util.Icon; +import net.minecraft.world.*; +import net.minecraftforge.common.ForgeDirection; +import cpw.mods.fml.common.registry.*; +import cpw.mods.fml.relauncher.*; +import crazypants.enderio.ModObject; + +public class BlockElectricLight extends Block { + + + public static BlockElectricLight create() { + BlockElectricLight result = new BlockElectricLight(); + result.init(); + return result; + } + + public BlockElectricLight() { + super(ModObject.blockElectricLight.id, Material.rock); + setHardness(2.0F); + setStepSound(soundGlassFootstep); + setUnlocalizedName(ModObject.blockElectricLight.unlocalisedName); + //setCreativeTab(EnderIOTab.tabEnderIO); + setLightOpacity(0); + setLightValue(1); + } + + + private void init() { + LanguageRegistry.addName(this, ModObject.blockElectricLight.name); + GameRegistry.registerBlock(this, ModObject.blockElectricLight.unlocalisedName); + //GameRegistry.addRecipe(new ItemStack(this), "zxz", "xyx", "zxz", 'x', new ItemStack(Item.eyeOfEnder), 'y', new ItemStack(Block.enderChest),'z', new ItemStack(Item.diamond)); + } + + @Override + public void registerIcons(IconRegister iconRegister) { + blockIcon = iconRegister.registerIcon("enderio:blockElectricLightFace"); + } + + @Override + public boolean renderAsNormalBlock() { + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public Icon getBlockTexture(IBlockAccess par1iBlockAccess, int par2, int par3, int par4, int par5) { + // TODO Auto-generated method stub + return super.getBlockTexture(par1iBlockAccess, par2, par3, par4, par5); + } + + @Override + @SideOnly(Side.CLIENT) + public Icon getIcon(int par1, int par2) { + // TODO Auto-generated method stub + return super.getIcon(par1, par2); + } + + @Override + public boolean isOpaqueCube() { + return false; + } + + @Override + public void onNeighborBlockChange(World par1World, int par2, int par3, int par4, int par5) { + super.onNeighborBlockChange(par1World, par2, par3, par4, par5); + } + + @Override + public boolean canPlaceBlockOnSide(World par1World, int x, int y, int z, int side) { + ForgeDirection dir = ForgeDirection.getOrientation(side); + ForgeDirection op = dir.getOpposite(); + return par1World.isBlockSolidOnSide(x + op.offsetX, y + op.offsetY, z + op.offsetZ, dir); +// ForgeDirection dir = ForgeDirection.getOrientation(side); +// return (dir == DOWN && par1World.isBlockSolidOnSide(x, y + 1, z, DOWN )) || +// (dir == UP && par1World.isBlockSolidOnSide(x, y - 1, z, UP )) || +// (dir == NORTH && par1World.isBlockSolidOnSide(x, y, z + 1, NORTH)) || +// (dir == SOUTH && par1World.isBlockSolidOnSide(x, y, z - 1, SOUTH)) || +// (dir == WEST && par1World.isBlockSolidOnSide(x + 1, y, z, WEST )) || +// (dir == EAST && par1World.isBlockSolidOnSide(x - 1, y, z, EAST )); + } + + + @Override + public boolean canPlaceTorchOnTop(World world, int x, int y, int z) { + return false; + } + + + +} diff --git a/common/crazypants/enderio/machine/GuiMachineBase.java b/common/crazypants/enderio/machine/GuiMachineBase.java new file mode 100644 index 00000000..18b7c9bf --- /dev/null +++ b/common/crazypants/enderio/machine/GuiMachineBase.java @@ -0,0 +1,129 @@ +package crazypants.enderio.machine; + +import java.awt.Rectangle; +import java.util.Iterator; + +import org.lwjgl.opengl.GL11; + +import cpw.mods.fml.common.network.PacketDispatcher; +import crazypants.enderio.PacketHandler; +import crazypants.enderio.machine.painter.PainterContainer; +import crazypants.render.GuiContainerBase; +import crazypants.render.GuiToolTip; +import crazypants.render.IconButton; +import crazypants.render.ItemButton; +import crazypants.render.RenderUtil; + +import net.minecraft.block.Block; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.item.Item; +import net.minecraft.network.packet.Packet; + +public abstract class GuiMachineBase extends GuiContainerBase { + + + protected static final int POWER_Y = 13; + protected final int POWER_X = 15; + protected static final int POWER_WIDTH = 11; + protected static final int POWER_HEIGHT = 53; + protected static final int BOTTOM_POWER_Y = POWER_Y + POWER_HEIGHT; + + protected static final int BUTTON_SIZE = 16; + protected static final int REDSTONE_BUTTON_ID = 99; + + + private AbstractMachineEntity tileEntity; + + private IconButton redstoneButton; + + public GuiMachineBase(AbstractMachineEntity machine, Container container) { + super(container); + tileEntity = machine; + addToolTip(new GuiToolTip(new Rectangle(POWER_X, POWER_Y, POWER_WIDTH, POWER_HEIGHT),"") { + + @Override + protected void updateText() { + text.clear(); + text.add(Math.round(tileEntity.getEnergyStored()) + "/" + tileEntity.getCapacitor().getMaxEnergyStored() + " MJ"); + } + + }); + addToolTip(new GuiToolTip(new Rectangle(0, 0, 0, 0),"") { + + @Override + protected void updateText() { + text.clear(); + switch(tileEntity.getRedstoneControlMode()) { + case ON: + text.add("Active when"); + text.add("recieving a"); + text.add("redstone signal."); + break; + case OFF: + text.add("Active when not"); + text.add("recieving a"); + text.add("redstone signal."); + break; + case IGNORE: + default: + text.add("Allways active."); + } + + } + + @Override + public void onTick(int mouseX, int mouseY) { + bounds.setBounds(xSize - 5 - BUTTON_SIZE, 5, BUTTON_SIZE, BUTTON_SIZE); + super.onTick(mouseX, mouseY); + } + + }); + + } + + @Override + protected void actionPerformed(GuiButton par1GuiButton) { + if(par1GuiButton.id == REDSTONE_BUTTON_ID) { + int ordinal = tileEntity.getRedstoneControlMode().ordinal(); + ordinal++; + if(ordinal >= RedstoneControlMode.values().length) { + ordinal = 0; + } + tileEntity.setRedstoneControlMode(RedstoneControlMode.values()[ordinal]); + redstoneButton.setIcon(AbstractMachineBlock.getRedstoneControlIcon(tileEntity.getRedstoneControlMode())); + Packet pkt = PacketHandler.getRedstoneControlPacket(tileEntity); + PacketDispatcher.sendPacketToServer(pkt); + } + } + + @Override + public void initGui() { + super.initGui(); + int x = guiLeft + xSize - 5 - BUTTON_SIZE; + int y = guiTop + 5; + + redstoneButton = new IconButton(fontRenderer, REDSTONE_BUTTON_ID, x, y, AbstractMachineBlock.getRedstoneControlIcon(tileEntity.getRedstoneControlMode()), RenderUtil.BLOCK_TEX); + redstoneButton.setSize(BUTTON_SIZE, BUTTON_SIZE); + + buttonList.add(redstoneButton); + } + + + + protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + int k = (width - xSize) / 2; + int l = (height - ySize) / 2; + int i1 = tileEntity.getEnergyStoredScaled(POWER_HEIGHT); + drawTexturedModalRect(k + POWER_X, l + BOTTOM_POWER_Y - i1, 176, 31, 11, i1); + + for (int i = 0; i < buttonList.size(); ++i) { + GuiButton guibutton = (GuiButton)this.buttonList.get(i); + guibutton.drawButton(this.mc, 0, 0); + } + + } + +} diff --git a/common/crazypants/enderio/machine/IMachine.java b/common/crazypants/enderio/machine/IMachine.java new file mode 100644 index 00000000..7be23d52 --- /dev/null +++ b/common/crazypants/enderio/machine/IMachine.java @@ -0,0 +1,8 @@ +package crazypants.enderio.machine; + +public interface IMachine { + + + String getMachineName(); + +} diff --git a/common/crazypants/enderio/machine/IMachineRecipe.java b/common/crazypants/enderio/machine/IMachineRecipe.java new file mode 100644 index 00000000..fbc7a90a --- /dev/null +++ b/common/crazypants/enderio/machine/IMachineRecipe.java @@ -0,0 +1,21 @@ +package crazypants.enderio.machine; + +import net.minecraft.item.ItemStack; + +public interface IMachineRecipe { + + String getUid(); + + float getEnergyRequired(RecipeInput... inputs); + + public boolean isRecipe(RecipeInput... inputs); + + ItemStack[] getCompletedResult(RecipeInput... inputs); + + boolean isValidInput(int slotNumber, ItemStack item); + + String getMachineName(); + + int getQuantityConsumed(RecipeInput input); + +} diff --git a/common/crazypants/enderio/machine/MachineRecipeRegistry.java b/common/crazypants/enderio/machine/MachineRecipeRegistry.java new file mode 100644 index 00000000..f463521f --- /dev/null +++ b/common/crazypants/enderio/machine/MachineRecipeRegistry.java @@ -0,0 +1,62 @@ +package crazypants.enderio.machine; + +import java.util.*; + +public class MachineRecipeRegistry { + + public static final MachineRecipeRegistry instance = new MachineRecipeRegistry(); + + private final Map> machineRecipes = new HashMap>(); + + public void registerRecipe(String machine, IMachineRecipe recipe) { + getRecipesForMachine(machine).put(recipe.getUid(), recipe); + } + + public Map getRecipesForMachine(String machineName) { + Map res = machineRecipes.get(machineName); + if(res == null) { + res = new HashMap(); + machineRecipes.put(machineName, res); + } + return res; + } + + public IMachineRecipe getRecipeForUid(String uid) { + for(Map recipes : machineRecipes.values()) { + for(IMachineRecipe recipe : recipes.values()) { + if(uid.equals(recipe.getUid())) { + return recipe; + } + } + } + return null; + } + + public IMachineRecipe getRecipeForInputs(String machineName, RecipeInput... inputs) { + Map recipes = getRecipesForMachine(machineName); + if(recipes == null) { + return null; + } + for(IMachineRecipe recipe : recipes.values()) { + if(recipe.isRecipe(inputs)) { + return recipe; + } + } + return null; + } + + public List getRecipesForInput(String machineName, RecipeInput input) { + if(input == null) { + return Collections.emptyList(); + } + List result = new ArrayList(); + Map recipes = getRecipesForMachine(machineName); + for(IMachineRecipe recipe : recipes.values()) { + if(recipe.isValidInput(input.slotNumber, input.item)) { + result.add(recipe); + } + } + return result; + } + +} diff --git a/common/crazypants/enderio/machine/MachineRecipes.java b/common/crazypants/enderio/machine/MachineRecipes.java new file mode 100644 index 00000000..e21e75b1 --- /dev/null +++ b/common/crazypants/enderio/machine/MachineRecipes.java @@ -0,0 +1,40 @@ +package crazypants.enderio.machine; + +import static crazypants.enderio.ModObject.*; +import net.minecraft.block.Block; +import net.minecraft.item.*; +import cpw.mods.fml.common.registry.GameRegistry; +import crazypants.enderio.ModObject; +import crazypants.enderio.material.Alloy; + +public class MachineRecipes { + + public static void addRecipes() { + ItemStack industialBinder = new ItemStack(itemIndustrialBinder.actualId, 1, 0); + ItemStack capacitor = new ItemStack(itemBasicCapacitor.actualId, 1, 0); + + ItemStack stirlingGen = new ItemStack(blockStirlingGenerator.actualId, 1, 0); + GameRegistry.addShapedRecipe(stirlingGen, "bbb", "bfb", "bcb", 'b', industialBinder, 'f', Block.furnaceIdle, 'c', capacitor); + + ItemStack painter = new ItemStack(blockPainter.actualId, 1, 0); + ItemStack red = new ItemStack(Item.dyePowder, 1, 1); + ItemStack green = new ItemStack(Item.dyePowder, 1, 2); + ItemStack blue = new ItemStack(Item.dyePowder, 1, 4); + GameRegistry.addShapedRecipe(painter, "bbb", "RGB", "bcb", 'b', industialBinder, 'R', red, 'G', green, 'B', blue, 'c', capacitor); + + ItemStack reservoir = new ItemStack(blockReservoir.actualId, 1, 0); + ItemStack glassPane = new ItemStack(Block.thinGlass, 1, 0); + GameRegistry.addShapedRecipe(reservoir, "bgb", "gBg", "bgb", 'b', industialBinder, 'g', glassPane, 'B', Item.bucketEmpty); + + ItemStack alloySmelter = new ItemStack(blockAlloySmelter.actualId, 1, 0); + GameRegistry.addShapedRecipe(alloySmelter, "bbb", "CfC", "bcb", 'b', industialBinder, 'f', Block.furnaceIdle, 'c', capacitor, 'C', Item.cauldron); + + ItemStack solarPanel = new ItemStack(blockSolarPanel.actualId,1,0); + ItemStack activatedIron = new ItemStack(ModObject.itemAlloy.actualId,1,Alloy.ACTIVATED_IRON.ordinal()); + ItemStack activatedGold = new ItemStack(ModObject.itemAlloy.actualId,1,Alloy.ACTIVATED_GOLD.ordinal()); + ItemStack fusedQuartz = new ItemStack(ModObject.blockFusedQuartz.actualId, 1, 0); + + GameRegistry.addShapedRecipe(solarPanel, "qqq", "gig", "bcb", 'q', fusedQuartz, 'g', activatedGold, 'i', activatedIron, 'b', industialBinder,'c', capacitor); + } + +} diff --git a/common/crazypants/enderio/machine/PoweredTask.java b/common/crazypants/enderio/machine/PoweredTask.java new file mode 100644 index 00000000..c23c70a8 --- /dev/null +++ b/common/crazypants/enderio/machine/PoweredTask.java @@ -0,0 +1,119 @@ +package crazypants.enderio.machine; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.*; +import net.minecraft.util.MathHelper; + +public class PoweredTask { + + public static final String KEY_INPUTS_SLOTS = "inputsSlots"; + public static final String KEY_INPUTS_STACKS = "inputsStacks"; + public static final String KEY_RECIPE = "recipeUid"; + public static final String KEY_USED_ENERGY = "usedEnergy"; + + private float usedEnergy = 0; + + private RecipeInput[] inputs; + + private float requiredEnergy; + + private IMachineRecipe recipe; + + public PoweredTask(IMachineRecipe recipe, RecipeInput... inputs) { + this(recipe, 0, inputs); + } + + public PoweredTask(IMachineRecipe recipe, float usedEnergy, RecipeInput... inputsIn) { + this.inputs = inputsIn; + int numInputs = 0; + for (int i = 0; i < inputsIn.length; i++) { + if (inputsIn[i] != null && inputsIn[i].item != null) { + numInputs++; + } + } + + inputs = new RecipeInput[numInputs]; + int index = 0; + for (int i = 0; i < inputsIn.length; i++) { + if (inputsIn[i] != null && inputsIn[i].item != null) { + inputs[index] = inputsIn[i]; + index++; + } + } + + this.recipe = recipe; + this.usedEnergy = usedEnergy; + requiredEnergy = recipe.getEnergyRequired(inputsIn); + } + + public void update(float availableEnergy) { + usedEnergy += availableEnergy; + } + + public boolean isComplete() { + return usedEnergy >= requiredEnergy; + } + + public float getProgress() { + return MathHelper.clamp_float(usedEnergy / requiredEnergy, 0, 1); + } + + public ItemStack[] getCompletedResult() { + return recipe.getCompletedResult(inputs); + } + + public void writeToNBT(NBTTagCompound nbtRoot) { + NBTTagCompound stackRoot; + + int[] inputSlots = new int[inputs.length]; + for (int i = 0; i < inputSlots.length; i++) { + inputSlots[i] = inputs[i].slotNumber; + } + nbtRoot.setIntArray(KEY_INPUTS_SLOTS, inputSlots); + + NBTTagList inputItems = new NBTTagList(); + for (RecipeInput ri : inputs) { + stackRoot = new NBTTagCompound(); + ri.item.writeToNBT(stackRoot); + inputItems.appendTag(stackRoot); + } + nbtRoot.setTag(KEY_INPUTS_STACKS, inputItems); + + nbtRoot.setString(KEY_RECIPE, recipe.getUid()); + nbtRoot.setFloat(KEY_USED_ENERGY, usedEnergy); + } + + public static PoweredTask readFromNBT(NBTTagCompound nbtRoot) { + if (nbtRoot == null) { + return null; + } + + IMachineRecipe recipe; + + float usedEnergy = nbtRoot.getFloat(KEY_USED_ENERGY); + + int[] inputSlots = nbtRoot.getIntArray(KEY_INPUTS_SLOTS); + if (inputSlots == null || inputSlots.length <= 0) { + return null; + } + NBTTagList inputItems = nbtRoot.getTagList(KEY_INPUTS_STACKS); + if (inputItems == null || inputItems.tagCount() != inputSlots.length) { + return null; + } + + RecipeInput[] inputs = new RecipeInput[inputSlots.length]; + for (int i = 0; i < inputSlots.length; i++) { + NBTBase stackTag = inputItems.tagAt(i); + ItemStack item = ItemStack.loadItemStackFromNBT((NBTTagCompound) stackTag); + inputs[i] = new RecipeInput(inputSlots[i], item); + } + + String uid = nbtRoot.getString(KEY_RECIPE); + recipe = MachineRecipeRegistry.instance.getRecipeForUid(uid); + if (recipe != null) { + return new PoweredTask(recipe, usedEnergy, inputs); + } + return null; + + } +} diff --git a/common/crazypants/enderio/machine/RecipeInput.java b/common/crazypants/enderio/machine/RecipeInput.java new file mode 100644 index 00000000..fbcfc9fa --- /dev/null +++ b/common/crazypants/enderio/machine/RecipeInput.java @@ -0,0 +1,30 @@ +package crazypants.enderio.machine; + +import net.minecraft.item.ItemStack; + +public class RecipeInput { + + public static ItemStack getInputForSlot(int slot, RecipeInput... inputs) { + for(RecipeInput ri: inputs) { + if(ri.slotNumber == slot) { + return ri.item; + } + } + return null; + } + + public static RecipeInput create(int slotNumber, ItemStack item) { + return new RecipeInput(slotNumber, item); + } + + public final int slotNumber; + public final ItemStack item; + + public RecipeInput(int slotNumber, ItemStack item) { + super(); + this.slotNumber = slotNumber; + this.item = item; + } + + +} \ No newline at end of file diff --git a/common/crazypants/enderio/machine/RedstoneControlMode.java b/common/crazypants/enderio/machine/RedstoneControlMode.java new file mode 100644 index 00000000..ecfb902f --- /dev/null +++ b/common/crazypants/enderio/machine/RedstoneControlMode.java @@ -0,0 +1,9 @@ +package crazypants.enderio.machine; + +public enum RedstoneControlMode { + + IGNORE, + ON, + OFF + +} diff --git a/common/crazypants/enderio/machine/alloy/BasicAlloyRecipe.java b/common/crazypants/enderio/machine/alloy/BasicAlloyRecipe.java new file mode 100644 index 00000000..23a51a2e --- /dev/null +++ b/common/crazypants/enderio/machine/alloy/BasicAlloyRecipe.java @@ -0,0 +1,104 @@ +package crazypants.enderio.machine.alloy; + +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; +import net.minecraft.item.ItemStack; + +public class BasicAlloyRecipe implements IMachineRecipe { + + public static final int DEFAULT_ENERGY_USE = 1600; + + private final String uid; + + private float energyRequired = DEFAULT_ENERGY_USE; + + private ItemStack[] inputs; + + private ItemStack output; + + public BasicAlloyRecipe(ItemStack output, String uid, ItemStack... recipeInputs) { + this.output = output.copy(); + this.uid = uid; + inputs = new ItemStack[recipeInputs.length]; + for(int i=0;i input.item.stackSize) { + return false; + } + } + return true; + } + + private RecipeInput[] getNonNullInputs(RecipeInput[] checking) { + int numNonNulls = 0; + for(int i=0;i { + + public static BlockAlloySmelter create() { + BlockAlloySmelter ppainter = new BlockAlloySmelter(); + ppainter.init(); + return ppainter; + } + + private BlockAlloySmelter() { + super(ModObject.blockAlloySmelter, TileAlloySmelter.class); + } + + @Override + protected void init() { + super.init(); + + // GameRegistry.addRecipe(new ItemStack(this), "bbb", "iri", "bbb", 'i', new ItemStack(Item.ingotIron), 'r', new ItemStack(Item.redstone), 'b', new ItemStack( +// ModObject.itemIndustrialBinder.id, 1, 0)); + IMachineRecipe recipe; + recipe = new BasicAlloyRecipe(new ItemStack(Item.axeDiamond), "Diamond Axe", new ItemStack(Item.diamond,3,0), new ItemStack(Item.stick,2,0)); + MachineRecipeRegistry.instance.registerRecipe(ModObject.blockAlloySmelter.unlocalisedName, recipe); + + recipe = new BasicAlloyRecipe(new ItemStack(Item.blazeRod), "Blazedy Blaze", new ItemStack(Item.ingotIron,1,0), new ItemStack(Item.ingotGold,1,0),new ItemStack(Item.diamond,1,0)); + MachineRecipeRegistry.instance.registerRecipe(ModObject.blockAlloySmelter.unlocalisedName, recipe); + } + + @Override + public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + // The server needs the container as it manages the adding and removing of + // items, which are then sent to the client for display + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileAlloySmelter) { + return new ContainerAlloySmelter(player.inventory, (TileAlloySmelter) te); + } + return null; + } + + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + TileEntity te = world.getBlockTileEntity(x, y, z); + return new GuiAlloySmelter(player.inventory, (TileAlloySmelter) te); + } + + @Override + protected int getGuiId() { + return GuiHandler.GUI_ID_ALLOY_SMELTER; + } + + @Override + protected String getMachineFrontIconKey(boolean active) { + if(active) { + return "enderio:alloySmelterFrontOn"; + } + return "enderio:alloySmelterFront"; + } + +} diff --git a/common/crazypants/enderio/machine/alloy/ContainerAlloySmelter.java b/common/crazypants/enderio/machine/alloy/ContainerAlloySmelter.java new file mode 100644 index 00000000..3010acf4 --- /dev/null +++ b/common/crazypants/enderio/machine/alloy/ContainerAlloySmelter.java @@ -0,0 +1,115 @@ +package crazypants.enderio.machine.alloy; + +import net.minecraft.entity.player.*; +import net.minecraft.inventory.*; +import net.minecraft.item.ItemStack; + +public class ContainerAlloySmelter extends Container { + + final TileAlloySmelter tileEntity; + private int progress = 0; + + public ContainerAlloySmelter(InventoryPlayer playerInv, TileAlloySmelter te) { + + this.tileEntity = te; + + addSlotToContainer(new Slot(tileEntity, 0, 54, 17) { + @Override + public boolean isItemValid(ItemStack itemStack) { + return tileEntity.isItemValidForSlot(0, itemStack); + } + }); + addSlotToContainer(new Slot(tileEntity, 1, 78, 7) { + @Override + public boolean isItemValid(ItemStack itemStack) { + return tileEntity.isItemValidForSlot(1, itemStack); + } + }); + addSlotToContainer(new Slot(tileEntity, 2, 103, 17) { + @Override + public boolean isItemValid(ItemStack itemStack) { + return tileEntity.isItemValidForSlot(2, itemStack); + } + }); + addSlotToContainer(new Slot(tileEntity, 3, 79, 57) { + @Override + public boolean isItemValid(ItemStack par1ItemStack) { + return false; + } + }); + + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (int i = 0; i < 9; ++i) { + addSlotToContainer(new Slot(playerInv, i, 8 + i * 18, 142)); + } + + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return tileEntity.isUseableByPlayer(entityplayer); + } + + + @Override + public ItemStack transferStackInSlot(EntityPlayer entityPlayer, int slotIndex) { + ItemStack itemstack = null; + Slot slot = (Slot) inventorySlots.get(slotIndex); + if (slot != null && slot.getHasStack()) { + ItemStack origStack = slot.getStack(); + itemstack = origStack.copy(); + + if (slotIndex == 3) { + + if (!mergeItemStack(origStack, 4, 39, true)) { + return null; + } + slot.onSlotChange(origStack, itemstack); + + } else if (slotIndex != 1 && slotIndex != 0 && slotIndex != 2) { + + boolean merged = false; + + if (tileEntity.isItemValidForSlot(0, origStack)) { + merged = mergeItemStack(origStack, 0, 1, false); + } + if (!merged && tileEntity.isItemValidForSlot(1, origStack)) { + merged = mergeItemStack(origStack, 1, 2, false); + } + if (!merged && tileEntity.isItemValidForSlot(2, origStack)) { + merged = mergeItemStack(origStack, 2, 3, false); + } else if (!merged && slotIndex >= 4 && slotIndex < 30) { + if (!this.mergeItemStack(origStack, 31, 40, false)) { + return null; + } + } else if (!merged && slotIndex >= 31 && slotIndex < 40 && !this.mergeItemStack(origStack, 4, 31, false)) { + return null; + } + + } else if (!mergeItemStack(origStack, 4, 39, false)) { + return null; + } + + if (origStack.stackSize == 0) { + slot.putStack((ItemStack) null); + } + slot.onSlotChanged(); + + if (origStack.stackSize == itemstack.stackSize) { + return null; + } + + slot.onPickupFromSlot(entityPlayer, origStack); + } + + return itemstack; + } + + + +} diff --git a/common/crazypants/enderio/machine/alloy/GuiAlloySmelter.java b/common/crazypants/enderio/machine/alloy/GuiAlloySmelter.java new file mode 100644 index 00000000..ae157e41 --- /dev/null +++ b/common/crazypants/enderio/machine/alloy/GuiAlloySmelter.java @@ -0,0 +1,46 @@ +package crazypants.enderio.machine.alloy; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.util.StatCollector; + +import org.lwjgl.opengl.GL11; + +import crazypants.enderio.machine.GuiMachineBase; +import crazypants.render.RenderUtil; + + +public class GuiAlloySmelter extends GuiMachineBase { + + private TileAlloySmelter tileEntity; + + public GuiAlloySmelter(InventoryPlayer par1InventoryPlayer, TileAlloySmelter furnaceInventory) { + super(furnaceInventory, new ContainerAlloySmelter(par1InventoryPlayer, furnaceInventory)); + this.tileEntity = furnaceInventory; + } + + + /** + * Draw the background layer for the GuiContainer (everything behind the + * items) + */ + @Override + protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + RenderUtil.bindTexture("enderio:textures/gui/alloySmelter.png"); + int sx = (width - xSize) / 2; + int sy = (height - ySize) / 2; + + drawTexturedModalRect(sx, sy, 0, 0, this.xSize, this.ySize); + + int scaled; + + if(tileEntity.getProgress() < 1 && tileEntity.getProgress() > 0) { + scaled = tileEntity.getProgressScaled(12); + drawTexturedModalRect(sx + 55, sy + 48 - scaled, 176, 12 - scaled, 14, scaled + 2); + drawTexturedModalRect(sx + 103, sy + 48 - scaled, 176, 12 - scaled, 14, scaled + 2); + } + + super.drawGuiContainerBackgroundLayer(par1, par2, par3); + } +} diff --git a/common/crazypants/enderio/machine/alloy/TileAlloySmelter.java b/common/crazypants/enderio/machine/alloy/TileAlloySmelter.java new file mode 100644 index 00000000..e4a7fc70 --- /dev/null +++ b/common/crazypants/enderio/machine/alloy/TileAlloySmelter.java @@ -0,0 +1,31 @@ +package crazypants.enderio.machine.alloy; + +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; +import net.minecraft.item.ItemStack; + +public class TileAlloySmelter extends AbstractPoweredTaskEntity { + + public TileAlloySmelter() { + super(4); + } + + @Override + public String getInvName() { + return "Alloy Smelter"; + } + + @Override + public String getMachineName() { + return ModObject.blockAlloySmelter.unlocalisedName; + } + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + if(i >= 3) { + return false; + } + return !MachineRecipeRegistry.instance.getRecipesForInput(getMachineName(), RecipeInput.create(i, itemstack)).isEmpty(); + } + +} diff --git a/common/crazypants/enderio/machine/generator/BlockStirlingGenerator.java b/common/crazypants/enderio/machine/generator/BlockStirlingGenerator.java new file mode 100644 index 00000000..24bb4cb4 --- /dev/null +++ b/common/crazypants/enderio/machine/generator/BlockStirlingGenerator.java @@ -0,0 +1,45 @@ +package crazypants.enderio.machine.generator; + +import crazypants.enderio.*; +import crazypants.enderio.machine.AbstractMachineBlock; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; + +public class BlockStirlingGenerator extends AbstractMachineBlock { + + public static BlockStirlingGenerator create() { + BlockStirlingGenerator gen = new BlockStirlingGenerator(); + gen.init(); + return gen; + } + + protected BlockStirlingGenerator() { + super(ModObject.blockStirlingGenerator, TileEntityStirlingGenerator.class); + } + + @Override + public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + return new StirlingGeneratorContainer(player.inventory, (TileEntityStirlingGenerator) world.getBlockTileEntity(x, y, z)); + } + + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + return new GuiStirlingGenerator(player.inventory, (TileEntityStirlingGenerator) world.getBlockTileEntity(x, y, z)); + } + + @Override + protected int getGuiId() { + return GuiHandler.GUI_ID_STIRLING_GEN; + } + + @Override + protected String getMachineFrontIconKey(boolean active) { + if(active) { + return "enderio:stirlingGenFrontOn"; + } + return "enderio:stirlingGenFrontOff"; + } + + + +} diff --git a/common/crazypants/enderio/machine/generator/GuiStirlingGenerator.java b/common/crazypants/enderio/machine/generator/GuiStirlingGenerator.java new file mode 100644 index 00000000..9cbba15f --- /dev/null +++ b/common/crazypants/enderio/machine/generator/GuiStirlingGenerator.java @@ -0,0 +1,59 @@ +package crazypants.enderio.machine.generator; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.util.StatCollector; + +import org.lwjgl.opengl.GL11; + + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.machine.GuiMachineBase; +import crazypants.render.RenderUtil; + +@SideOnly(Side.CLIENT) +public class GuiStirlingGenerator extends GuiMachineBase { + + private TileEntityStirlingGenerator entity; + + public GuiStirlingGenerator(InventoryPlayer par1InventoryPlayer, TileEntityStirlingGenerator te) { + super(te, new StirlingGeneratorContainer(par1InventoryPlayer, te)); + this.entity = te; + } + + /** + * Draw the foreground layer for the GuiContainer (everything in front of the + * items) + */ + @Override + protected void drawForegroundImpl(int par1, int par2) { + String s = this.entity.isInvNameLocalized() ? this.entity.getInvName() : StatCollector.translateToLocal(this.entity.getInvName()); + this.fontRenderer.drawString(s, this.xSize / 2 - this.fontRenderer.getStringWidth(s) / 2, 6, 4210752); + this.fontRenderer.drawString(StatCollector.translateToLocal("container.inventory"), 8, this.ySize - 94, 4210752); + } + + /** + * Draw the background layer for the GuiContainer (everything behind the + * items) + */ + @Override + protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + RenderUtil.bindTexture("enderio:textures/gui/stirlingGenerator.png"); + int sx = (width - xSize) / 2; + int sy = (height - ySize) / 2; + + drawTexturedModalRect(sx, sy, 0, 0, this.xSize, this.ySize); + int scaled; + + if(entity.getProgress() < 1 && entity.getProgress() > 0) { + scaled = entity.getProgressScaled(12); + drawTexturedModalRect(sx + 80, sy + 65 - scaled, 176, 12 - scaled, 14, scaled + 2); + } + + super.drawGuiContainerBackgroundLayer(par1, par2, par3); + + } +} + diff --git a/common/crazypants/enderio/machine/generator/StirlingGeneratorContainer.java b/common/crazypants/enderio/machine/generator/StirlingGeneratorContainer.java new file mode 100644 index 00000000..5b32581f --- /dev/null +++ b/common/crazypants/enderio/machine/generator/StirlingGeneratorContainer.java @@ -0,0 +1,81 @@ +package crazypants.enderio.machine.generator; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +public class StirlingGeneratorContainer extends Container { + + final TileEntityStirlingGenerator tileEntity; + private int progress = 0; + + public StirlingGeneratorContainer(InventoryPlayer playerInv, TileEntityStirlingGenerator te) { + + this.tileEntity = te; + + addSlotToContainer(new Slot(tileEntity, 0, 80, 34) { + @Override + public boolean isItemValid(ItemStack itemStack) { + return tileEntity.isItemValidForSlot(0, itemStack); + } + }); + + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (int i = 0; i < 9; ++i) { + addSlotToContainer(new Slot(playerInv, i, 8 + i * 18, 142)); + } + + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return tileEntity.isUseableByPlayer(entityplayer); + } + + + @Override + public ItemStack transferStackInSlot(EntityPlayer entityPlayer, int slotIndex) { + ItemStack itemstack = null; + Slot slot = (Slot) inventorySlots.get(slotIndex); + if (slot != null && slot.getHasStack()) { + ItemStack origStack = slot.getStack(); + itemstack = origStack.copy(); + + if (slotIndex != 0) { + if (tileEntity.isItemValidForSlot(0, origStack)) { + if (!this.mergeItemStack(origStack, 0, 1, false)) { + return null; + } + } else if (slotIndex >= 30 && slotIndex < 39 && !this.mergeItemStack(origStack, 1, 28, false)) { + return null; + } + + } else if (!mergeItemStack(origStack, 1, 37, false)) { + return null; + } + + if (origStack.stackSize == 0) { + slot.putStack((ItemStack) null); + } else { + slot.onSlotChanged(); + } + + if (origStack.stackSize == itemstack.stackSize) { + return null; + } + + slot.onPickupFromSlot(entityPlayer, origStack); + } + + return itemstack; + } + + +} diff --git a/common/crazypants/enderio/machine/generator/TileEntityStirlingGenerator.java b/common/crazypants/enderio/machine/generator/TileEntityStirlingGenerator.java new file mode 100644 index 00000000..b72a6695 --- /dev/null +++ b/common/crazypants/enderio/machine/generator/TileEntityStirlingGenerator.java @@ -0,0 +1,225 @@ +package crazypants.enderio.machine.generator; + +import java.util.*; + +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.conduit.power.PowerConduitNetwork.ReceptorEntry; +import crazypants.enderio.machine.AbstractMachineEntity; +import crazypants.enderio.power.IInternalPowerReceptor; +import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.util.BlockCoord; + +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.*; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.power.IPowerEmitter; +import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; + +public class TileEntityStirlingGenerator extends AbstractMachineEntity implements ISidedInventory, IPowerEmitter { + + public static final float ENERGY_PER_TICK = 1; + + /** How many ticks left until the item is burnt. */ + private int burnTime = 0; + private int totalBurnTime; + + private final List receptors = new ArrayList(); + private ListIterator receptorIterator = receptors.listIterator(); + private boolean receptorsDirty = true; + + public TileEntityStirlingGenerator() { + super(1, Type.ENGINE); + } + + @Override + public boolean canEmitPowerFrom(ForgeDirection side) { + return true; + } + + @Override + public String getMachineName() { + return ModObject.blockStirlingGenerator.unlocalisedName; + } + + @Override + public String getInvName() { + return "Stirling Generator"; + } + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return TileEntityFurnace.isItemFuel(itemstack); + } + + @Override + public int[] getAccessibleSlotsFromSide(int var1) { + return new int[] { 0 }; + } + + @Override + public boolean canInsertItem(int i, ItemStack itemstack, int j) { + return isItemValidForSlot(i, itemstack); + } + + @Override + public boolean canExtractItem(int i, ItemStack itemstack, int j) { + return false; + } + + @Override + public boolean isActive() { + return burnTime > 0; + } + + @Override + public float getProgress() { + if (totalBurnTime <= 0) { + return 0; + } + return (float) burnTime / (float) totalBurnTime; + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + super.readFromNBT(nbtRoot); + burnTime = nbtRoot.getInteger("burnTime"); + totalBurnTime = nbtRoot.getInteger("totalBurnTime"); + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + nbtRoot.setInteger("burnTime", burnTime); + nbtRoot.setInteger("totalBurnTime", totalBurnTime); + } + + @Override + public void onNeighborBlockChange(int blockId) { + receptorsDirty = true; + } + + @Override + protected boolean processTasks(boolean redstoneCheckPassed) { + boolean needsUpdate = false; + + if (burnTime > 0) { + // powerProvider.getPowerReceiver().receiveEnergy(Type.ENGINE, + // ENERGY_PER_TICK, ForgeDirection.DOWN); + powerHandler.setEnergy(powerHandler.getEnergyStored() + ENERGY_PER_TICK); + burnTime--; + needsUpdate = true; + } + + needsUpdate |= transmitEnergy(); + + if (burnTime <= 0 && powerHandler.getEnergyStored() < powerHandler.getMaxEnergyStored() && redstoneCheckPassed) { + if (inventory[0] != null && inventory[0].stackSize > 0) { + burnTime = TileEntityFurnace.getItemBurnTime(inventory[0]); + if (burnTime > 0) { + totalBurnTime = burnTime; + decrStackSize(0, 1); + } + needsUpdate = true; + } + } + + return needsUpdate; + } + + private boolean transmitEnergy() { + + if (powerHandler.getEnergyStored() <= 0) { + powerHandler.update(); + return false; + } + float canTransmit = Math.min(powerHandler.getEnergyStored(), capacitor.getMaxEnergyExtracted()); + float transmitted = 0; + + float stored = powerHandler.getEnergyStored(); + powerHandler.update(); + float storedAfter = powerHandler.getEnergyStored(); + + + checkReceptors(); + + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { + receptorIterator = receptors.listIterator(); + } + + int appliedCount = 0; + int numReceptors = receptors.size(); + while (receptorIterator.hasNext() && canTransmit > 0 && appliedCount < numReceptors) { + + Receptor receptor = receptorIterator.next(); + PowerReceiver pp = receptor.receptor.getPowerReceiver(receptor.fromDir); + if (pp != null && pp.getMinEnergyReceived() <= canTransmit && pp.getType() != Type.ENGINE) { + float used; + if (receptor.receptor instanceof IInternalPowerReceptor) { + //System.out.println("TileEntityStirlingGenerator.transmitEnergy: Sending " + canTransmit + " to internal."); + used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) receptor.receptor, pp, canTransmit,Type.ENGINE,receptor.fromDir); + } else { + //System.out.println("TileEntityStirlingGenerator.transmitEnergy: Sending " + canTransmit + " to EXTERNAL. Receptor is: " + receptor.receptor); + used = pp.receiveEnergy(Type.ENGINE, canTransmit, receptor.fromDir); + } + transmitted += used; +// if (used > 0) { +// System.out.println("TileEntityStirlingGenerator.transmitEnergy: Trasnmitted energy " + used + " to " + receptor.receptor); +// } + canTransmit -= used; + } + if (canTransmit <= 0) { + break; + } + + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { + receptorIterator = receptors.listIterator(); + } + appliedCount++; + } + + powerHandler.setEnergy(powerHandler.getEnergyStored() - transmitted); + + return transmitted > 0; + + } + + private void checkReceptors() { + if (!receptorsDirty) { + return; + } + receptors.clear(); + + BlockCoord bc = new BlockCoord(xCoord, yCoord, zCoord); + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + BlockCoord checkLoc = bc.getLocation(dir); + TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); + if (te instanceof IPowerReceptor) { + IPowerReceptor rec = (IPowerReceptor) te; + PowerReceiver reciever = rec.getPowerReceiver(dir.getOpposite()); + receptors.add(new Receptor((IPowerReceptor) te, dir.getOpposite())); + } + } + receptorIterator = receptors.listIterator(); + receptorsDirty = false; + + } + + static class Receptor { + IPowerReceptor receptor; + ForgeDirection fromDir; + + private Receptor(IPowerReceptor rec, ForgeDirection fromDir) { + super(); + this.receptor = rec; + this.fromDir = fromDir; + } + } + +} diff --git a/common/crazypants/enderio/machine/painter/BasicPainterTemplate.java b/common/crazypants/enderio/machine/painter/BasicPainterTemplate.java new file mode 100644 index 00000000..e711b51c --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BasicPainterTemplate.java @@ -0,0 +1,119 @@ +package crazypants.enderio.machine.painter; + +import static crazypants.enderio.machine.RecipeInput.getInputForSlot; +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; +import crazypants.util.Util; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; + +public class BasicPainterTemplate implements IMachineRecipe { + + public static float DEFAULT_ENERGY_PER_TASK = 200; //5 seconds at the default energy use of 2 mj per tick. + + public static boolean isValidSourceDefault(ItemStack paintSource) { + if(paintSource == null) { + return false; + } + Block block = Util.getBlockFromItemId(paintSource.itemID); + if(block == null) { + return false; + } + return Block.isNormalCube(block.blockID) || block.blockID == Block.glass.blockID; + } + + protected final int[] validIds; + + protected BasicPainterTemplate(int... validTargetBlocksIds) { + this.validIds = validTargetBlocksIds; + } + + @Override + public float getEnergyRequired(RecipeInput... inputs) { + return DEFAULT_ENERGY_PER_TASK; + } + + @Override + public boolean isRecipe(RecipeInput... inputs) { + return isValidTarget(getTarget(inputs)) && isValidPaintSource(getPaintSource(inputs)); + } + + @Override + public ItemStack[] getCompletedResult(RecipeInput... inputs) { + ItemStack target = getTarget(inputs); + ItemStack paintSource = getPaintSource(inputs); + if(target == null || paintSource == null) { + return null; + } + ItemStack result = new ItemStack(getResultId(target), 1, target.getItemDamage()); + PainterUtil.setSourceBlock(result, paintSource.itemID, paintSource.getItemDamage()); + return new ItemStack[] {result}; + } + + public ItemStack getTarget(RecipeInput... inputs) { + return getInputForSlot(0, inputs); + } + + public ItemStack getPaintSource(RecipeInput... inputs) { + return getInputForSlot(1, inputs); + } + + @Override + public boolean isValidInput(int slotNumber, ItemStack item) { + if(slotNumber == 0) { + return isValidTarget(item); + } + if(slotNumber == 1) { + return isValidPaintSource(item); + } + return false; + } + + @Override + public String getMachineName() { + return ModObject.blockPainter.unlocalisedName; + } + + public boolean isValidPaintSource(ItemStack paintSource) { + return isValidSourceDefault(paintSource); + } + + public boolean isValidTarget(ItemStack target) { + //first check for exact matches, then check for item blocks + if(target == null) { + return false; + } + + for(int i=0; i < validIds.length; i++) { + if(validIds[i] == target.itemID) { + return true; + } + } + + Block blk = Util.getBlockFromItemId(target.itemID); + if(blk == null) { + return false; + } + for(int i=0; i < validIds.length; i++) { + if(validIds[i] == blk.blockID) { + return true; + } + } + return false; + } + + @Override + public String getUid() { + return getClass().getCanonicalName(); + } + + protected int getResultId(ItemStack target) { + return target.itemID; + } + + @Override + public int getQuantityConsumed(RecipeInput input) { + return input.slotNumber == 0 ? 1 : 0; + } + +} diff --git a/common/crazypants/enderio/machine/painter/BlockCustomFence.java b/common/crazypants/enderio/machine/painter/BlockCustomFence.java new file mode 100644 index 00000000..1a2fb7e8 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockCustomFence.java @@ -0,0 +1,190 @@ +package crazypants.enderio.machine.painter; + +import java.util.Random; + +import net.minecraft.block.*; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.EntityLiving; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.*; +import cpw.mods.fml.common.registry.*; +import cpw.mods.fml.relauncher.*; +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; + +public class BlockCustomFence extends BlockFence implements ITileEntityProvider { + + public static BlockCustomFence create() { + BlockCustomFence result = new BlockCustomFence(); + result.init(); + return result; + } + + public BlockCustomFence() { + super(ModObject.blockCustomFence.id, ModObject.blockCustomFence.unlocalisedName, Material.wood); + setUnlocalizedName(ModObject.blockCustomFence.unlocalisedName); + setHardness(2.0F); + setResistance(5.0F); + setStepSound(soundWoodFootstep); + setCreativeTab(null); + } + + private void init() { + LanguageRegistry.addName(this, ModObject.blockCustomFence.name); + GameRegistry.registerBlock(this, BlockItemCustomFence.class, ModObject.blockCustomFence.unlocalisedName); + GameRegistry.registerTileEntity(TileEntityCustomBlock.class, ModObject.blockCustomFence.unlocalisedName + "TileEntity"); + MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPainter.unlocalisedName, new PainterTemplate()); + } + + public static ItemStack createItemStackForSourceBlock(int id, int damage) { + ItemStack result = new ItemStack(ModObject.blockCustomFence.id, 1, damage); + PainterUtil.setSourceBlock(result, id, damage); + return result; + } + + @Override + public int getLightOpacity(World world, int x, int y, int z) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + if(tef.getSourceBlockId() > 0) { + return Math.min(super.getLightOpacity(world, x, y, z), Block.lightOpacity[tef.getSourceBlockId()]); + } + } + return super.getLightOpacity(world, x, y, z); + } + + @Override + public boolean canPlaceTorchOnTop(World world, int x, int y, int z) { + int id = world.getBlockId(x, y, z); + if (id == this.blockID) { + return true; + } + return super.canPlaceTorchOnTop(world, x, y, z); + } + + + @Override + public boolean canConnectFenceTo(IBlockAccess par1IBlockAccess, int par2, int par3, int par4) { + int l = par1IBlockAccess.getBlockId(par2, par3, par4); + if(l == ModObject.blockCustomFenceGate.id) { + return true; + } + return super.canConnectFenceTo(par1IBlockAccess, par2, par3, par4); + } + + @Override + public Icon getBlockTexture(IBlockAccess world, int x, int y, int z, int blockSide) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + if (tef.getSourceBlockId() > 0 && tef.getSourceBlockId() < Block.blocksList.length) { + return blocksList[tef.getSourceBlockId()].getIcon(blockSide, tef.getSourceBlockMetadata()); + } + } else { + System.out.println("BlockCustFence: No tile entity."); + } + return blocksList[Block.anvil.blockID].getBlockTexture(world, x, y, z, blockSide); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister par1IconRegister) { + this.blockIcon = par1IconRegister.registerIcon("enderio:conduitConnector"); + } + + @Override + public TileEntity createNewTileEntity(World world) { + return null; + } + + @Override + public TileEntity createTileEntity(World world, int metadata) { + return new TileEntityCustomBlock(); + } + + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack) { + int id = -1; + Block b = PainterUtil.getSourceBlock(stack); + if (b != null) { + id = b.blockID; + } + + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + tef.setSourceBlockId(id); + tef.setSourceBlockMetadata(PainterUtil.getSourceBlockMetadata(stack)); + } + world.markBlockForUpdate(x, y, z); + } + + /** + * Remove the tile entity too. + */ + @Override + public void breakBlock(World world, int x, int y, int z, int par5, int par6) { + + if (!world.isRemote && world.getGameRules().getGameRuleBooleanValue("doTileDrops")) { + TileEntity te = world.getBlockTileEntity(x, y, z); + + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + + ItemStack itemStack = createItemStackForSourceBlock(tef.getSourceBlockId(), tef.getSourceBlockMetadata()); + + float f = 0.7F; + double d0 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d1 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + EntityItem entityitem = new EntityItem(world, x + d0, y + d1, z + d2, itemStack); + entityitem.delayBeforeCanPickup = 10; + world.spawnEntityInWorld(entityitem); + + } else { + System.out.println("dropBlockAsItem_do: No tile entity."); + } + + } + + world.removeBlockTileEntity(x, y, z); + } + + @Override + public int quantityDropped(Random par1Random) { + return 0; // need to do custom dropping to maintain source metadata + } + + /** + * Called when the block receives a BlockEvent - see World.addBlockEvent. By + * default, passes it on to the tile entity at this location. Args: world, x, + * y, z, blockID, EventID, event parameter + */ + @Override + public boolean onBlockEventReceived(World par1World, int par2, int par3, int par4, int par5, int par6) { + super.onBlockEventReceived(par1World, par2, par3, par4, par5, par6); + TileEntity tileentity = par1World.getBlockTileEntity(par2, par3, par4); + return tileentity != null ? tileentity.receiveClientEvent(par5, par6) : false; + } + + public static final class PainterTemplate extends BasicPainterTemplate { + + public PainterTemplate() { + super(Block.fence.blockID/* , Block.netherFence.blockID */); + } + + @Override + public ItemStack[] getCompletedResult(RecipeInput... inputs) { + ItemStack paintSource = RecipeInput.getInputForSlot(1, inputs); + return new ItemStack[] {createItemStackForSourceBlock(paintSource.itemID, paintSource.getItemDamage())}; + } + + } + +} diff --git a/common/crazypants/enderio/machine/painter/BlockCustomFenceGate.java b/common/crazypants/enderio/machine/painter/BlockCustomFenceGate.java new file mode 100644 index 00000000..36feb5fe --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockCustomFenceGate.java @@ -0,0 +1,164 @@ +package crazypants.enderio.machine.painter; + +import java.util.Random; + +import net.minecraft.block.*; +import net.minecraft.entity.EntityLiving; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.*; +import net.minecraft.world.*; +import cpw.mods.fml.common.registry.*; +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; + +public class BlockCustomFenceGate extends BlockFenceGate implements ITileEntityProvider{ + + + public static int renderId; + + public static BlockCustomFenceGate create() { + BlockCustomFenceGate result = new BlockCustomFenceGate(); + result.init(); + return result; + } + + public BlockCustomFenceGate() { + super(ModObject.blockCustomFenceGate.id); + setCreativeTab(null); + setUnlocalizedName(ModObject.blockCustomFenceGate.unlocalisedName); + setHardness(2.0F); + setResistance(5.0F); + setStepSound(soundWoodFootstep); + } + + private void init() { + LanguageRegistry.addName(this, ModObject.blockCustomFenceGate.name); + GameRegistry.registerBlock(this, BlockItemCustomFenceGate.class, ModObject.blockCustomFenceGate.unlocalisedName); + GameRegistry.registerTileEntity(TileEntityCustomBlock.class, ModObject.blockCustomFenceGate.unlocalisedName + "TileEntity"); + MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPainter.unlocalisedName, new PainterTemplate()); + } + + @Override + public int getRenderType() { + return renderId; + } + + @Override + public TileEntity createNewTileEntity(World world) { + return null; + } + + + @Override + public int getLightOpacity(World world, int x, int y, int z) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + if(tef.getSourceBlockId() > 0) { + return Math.min(super.getLightOpacity(world, x, y, z), Block.lightOpacity[tef.getSourceBlockId()]); + } + + } + return super.getLightOpacity(world, x, y, z); + } + + @Override + public TileEntity createTileEntity(World world, int metadata) { + return new TileEntityCustomBlock(); + } + + @Override + public Icon getBlockTexture(IBlockAccess world, int x, int y, int z, int blockSide) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + if (tef.getSourceBlockId() > 0 && tef.getSourceBlockId() < Block.blocksList.length) { + return blocksList[tef.getSourceBlockId()].getIcon(blockSide, tef.getSourceBlockMetadata()); + } + } else { + System.out.println("BlockCustFence: No tile entity."); + } + return blocksList[Block.anvil.blockID].getBlockTexture(world, x, y, z, blockSide); + } + + + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack) { + int id = -1; + Block b = PainterUtil.getSourceBlock(stack); + if (b != null) { + id = b.blockID; + } + + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + tef.setSourceBlockId(id); + tef.setSourceBlockMetadata(PainterUtil.getSourceBlockMetadata(stack)); + } + //world.markBlockForUpdate(x, y, z); + + int l = (MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3) % 4; + world.setBlockMetadataWithNotify(x, y, z, l, 2); + } + + + public static ItemStack createItemStackForSourceBlock(int id, int damage) { + ItemStack result = new ItemStack(ModObject.blockCustomFenceGate.actualId, 1, damage); + PainterUtil.setSourceBlock(result, id, damage); + return result; + } + + /** + * Remove the tile entity too. + */ + @Override + public void breakBlock(World world, int x, int y, int z, int par5, int par6) { + + if (!world.isRemote && world.getGameRules().getGameRuleBooleanValue("doTileDrops")) { + TileEntity te = world.getBlockTileEntity(x, y, z); + + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + + ItemStack itemStack = createItemStackForSourceBlock(tef.getSourceBlockId(), tef.getSourceBlockMetadata()); + + float f = 0.7F; + double d0 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d1 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + EntityItem entityitem = new EntityItem(world, x + d0, y + d1, z + d2, itemStack); + entityitem.delayBeforeCanPickup = 10; + world.spawnEntityInWorld(entityitem); + + } + + } + + world.removeBlockTileEntity(x, y, z); + } + + @Override + public int quantityDropped(Random par1Random) { + return 0; // need to do custom dropping to maintain source metadata + } + + + public static final class PainterTemplate extends BasicPainterTemplate { + + public PainterTemplate() { + super(Block.fenceGate.blockID/*, Block.netherFence.blockID*/); + } + + @Override + public ItemStack[] getCompletedResult(RecipeInput... inputs) { + ItemStack paintSource = RecipeInput.getInputForSlot(1, inputs); + return new ItemStack[] {createItemStackForSourceBlock(paintSource.itemID, paintSource.getItemDamage())}; + } + + } + +} diff --git a/common/crazypants/enderio/machine/painter/BlockCustomFenceGateRenderer.java b/common/crazypants/enderio/machine/painter/BlockCustomFenceGateRenderer.java new file mode 100644 index 00000000..a68b2de1 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockCustomFenceGateRenderer.java @@ -0,0 +1,221 @@ +package crazypants.enderio.machine.painter; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockDirectional; +import net.minecraft.block.BlockFenceGate; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.world.IBlockAccess; +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; +import crazypants.enderio.ModObject; + +public class BlockCustomFenceGateRenderer implements ISimpleBlockRenderingHandler { + + + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { + renderer.renderBlockAsItem(Block.fenceGate, metadata, 1); + } + + @Override + public boolean shouldRender3DInInventory() { + return true; + } + + @Override + public int getRenderId() { + return BlockCustomFenceGate.renderId; + } + + @Override + public boolean renderWorldBlock(IBlockAccess blockAccess, int par2, int par3, int par4, Block block, int modelId, RenderBlocks rb) { + + BlockFenceGate par1BlockFenceGate = (BlockFenceGate)block; + + boolean flag = true; + int l = rb.blockAccess.getBlockMetadata(par2, par3, par4); + boolean flag1 = BlockFenceGate.isFenceGateOpen(l); + int i1 = BlockDirectional.getDirection(l); + float f = 0.375F; + float f1 = 0.5625F; + float f2 = 0.75F; + float f3 = 0.9375F; + float f4 = 0.3125F; + float f5 = 1.0F; + + if ((i1 == 2 || i1 == 0) && rb.blockAccess.getBlockId(par2 - 1, par3, par4) == Block.cobblestoneWall.blockID && rb.blockAccess.getBlockId(par2 + 1, par3, par4) == Block.cobblestoneWall.blockID || + (i1 == 3 || i1 == 1) && rb.blockAccess.getBlockId(par2, par3, par4 - 1) == Block.cobblestoneWall.blockID && rb.blockAccess.getBlockId(par2, par3, par4 + 1) == Block.cobblestoneWall.blockID || + (i1 == 2 || i1 == 0) && rb.blockAccess.getBlockId(par2 - 1, par3, par4) == ModObject.blockCustomWall.id && rb.blockAccess.getBlockId(par2 + 1, par3, par4) == ModObject.blockCustomWall.id || + (i1 == 3 || i1 == 1) && rb.blockAccess.getBlockId(par2, par3, par4 - 1) == ModObject.blockCustomWall.id && rb.blockAccess.getBlockId(par2, par3, par4 + 1) == ModObject.blockCustomWall.id) + { + f -= 0.1875F; + f1 -= 0.1875F; + f2 -= 0.1875F; + f3 -= 0.1875F; + f4 -= 0.1875F; + f5 -= 0.1875F; + } + + rb.renderAllFaces = true; + float f6; + float f7; + float f8; + float f9; + + if (i1 != 3 && i1 != 1) + { + f6 = 0.0F; + f8 = 0.125F; + f7 = 0.4375F; + f9 = 0.5625F; + rb.setRenderBounds(f6, f4, f7, f8, f5, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + f6 = 0.875F; + f8 = 1.0F; + rb.setRenderBounds(f6, f4, f7, f8, f5, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + } + else + { + rb.uvRotateTop = 1; + f6 = 0.4375F; + f8 = 0.5625F; + f7 = 0.0F; + f9 = 0.125F; + rb.setRenderBounds(f6, f4, f7, f8, f5, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + f7 = 0.875F; + f9 = 1.0F; + rb.setRenderBounds(f6, f4, f7, f8, f5, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.uvRotateTop = 0; + } + + if (flag1) + { + if (i1 == 2 || i1 == 0) + { + rb.uvRotateTop = 1; + } + + if (i1 == 3) + { + rb.setRenderBounds(0.8125D, f, 0.0D, 0.9375D, f3, 0.125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.8125D, f, 0.875D, 0.9375D, f3, 1.0D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.5625D, f, 0.0D, 0.8125D, f1, 0.125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.5625D, f, 0.875D, 0.8125D, f1, 1.0D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.5625D, f2, 0.0D, 0.8125D, f3, 0.125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.5625D, f2, 0.875D, 0.8125D, f3, 1.0D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + } + else if (i1 == 1) + { + rb.setRenderBounds(0.0625D, f, 0.0D, 0.1875D, f3, 0.125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.0625D, f, 0.875D, 0.1875D, f3, 1.0D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.1875D, f, 0.0D, 0.4375D, f1, 0.125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.1875D, f, 0.875D, 0.4375D, f1, 1.0D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.1875D, f2, 0.0D, 0.4375D, f3, 0.125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.1875D, f2, 0.875D, 0.4375D, f3, 1.0D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + } + else if (i1 == 0) + { + rb.setRenderBounds(0.0D, f, 0.8125D, 0.125D, f3, 0.9375D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.875D, f, 0.8125D, 1.0D, f3, 0.9375D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.0D, f, 0.5625D, 0.125D, f1, 0.8125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.875D, f, 0.5625D, 1.0D, f1, 0.8125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.0D, f2, 0.5625D, 0.125D, f3, 0.8125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.875D, f2, 0.5625D, 1.0D, f3, 0.8125D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + } + else if (i1 == 2) + { + rb.setRenderBounds(0.0D, f, 0.0625D, 0.125D, f3, 0.1875D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.875D, f, 0.0625D, 1.0D, f3, 0.1875D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.0D, f, 0.1875D, 0.125D, f1, 0.4375D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.875D, f, 0.1875D, 1.0D, f1, 0.4375D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.0D, f2, 0.1875D, 0.125D, f3, 0.4375D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(0.875D, f2, 0.1875D, 1.0D, f3, 0.4375D); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + } + } + else if (i1 != 3 && i1 != 1) + { + f6 = 0.375F; + f8 = 0.5F; + f7 = 0.4375F; + f9 = 0.5625F; + rb.setRenderBounds(f6, f, f7, f8, f3, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + f6 = 0.5F; + f8 = 0.625F; + rb.setRenderBounds(f6, f, f7, f8, f3, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + f6 = 0.625F; + f8 = 0.875F; + rb.setRenderBounds(f6, f, f7, f8, f1, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(f6, f2, f7, f8, f3, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + f6 = 0.125F; + f8 = 0.375F; + rb.setRenderBounds(f6, f, f7, f8, f1, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(f6, f2, f7, f8, f3, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + } + else + { + rb.uvRotateTop = 1; + f6 = 0.4375F; + f8 = 0.5625F; + f7 = 0.375F; + f9 = 0.5F; + rb.setRenderBounds(f6, f, f7, f8, f3, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + f7 = 0.5F; + f9 = 0.625F; + rb.setRenderBounds(f6, f, f7, f8, f3, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + f7 = 0.625F; + f9 = 0.875F; + rb.setRenderBounds(f6, f, f7, f8, f1, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(f6, f2, f7, f8, f3, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + f7 = 0.125F; + f9 = 0.375F; + rb.setRenderBounds(f6, f, f7, f8, f1, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + rb.setRenderBounds(f6, f2, f7, f8, f3, f9); + rb.renderStandardBlock(par1BlockFenceGate, par2, par3, par4); + } + + rb.renderAllFaces = false; + rb.uvRotateTop = 0; + rb.setRenderBounds(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D); + return flag; + } + + + +} diff --git a/common/crazypants/enderio/machine/painter/BlockCustomStair.java b/common/crazypants/enderio/machine/painter/BlockCustomStair.java new file mode 100644 index 00000000..2c3b4ef0 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockCustomStair.java @@ -0,0 +1,168 @@ +package crazypants.enderio.machine.painter; + +import java.util.Random; + +import net.minecraft.block.*; +import net.minecraft.entity.EntityLiving; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.*; +import net.minecraftforge.common.ForgeDirection; +import cpw.mods.fml.common.registry.*; +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; +import crazypants.util.Util; + +public class BlockCustomStair extends BlockStairs implements ITileEntityProvider { + + public static BlockCustomStair create() { + BlockCustomStair result = new BlockCustomStair(); + result.init(); + return result; + } + + protected BlockCustomStair() { + super(ModObject.blockCustomStair.actualId, Block.brick, 0); + setCreativeTab(null); + setUnlocalizedName(ModObject.blockCustomStair.unlocalisedName); + } + + + private void init() { + LanguageRegistry.addName(this, ModObject.blockCustomStair.name); + GameRegistry.registerBlock(this, BlockItemCustomStair.class, ModObject.blockCustomStair.unlocalisedName); + GameRegistry.registerTileEntity(TileEntityCustomBlock.class, ModObject.blockCustomStair.unlocalisedName + "TileEntity"); + MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPainter.unlocalisedName, new PainterTemplate()); + } + + + public static ItemStack createItemStackForSourceBlock(int id, int damage) { + ItemStack result = new ItemStack(ModObject.blockCustomStair.id, 1, damage); + PainterUtil.setSourceBlock(result, id, damage); + return result; + } + + @Override + public boolean isBlockSolidOnSide(World world, int x, int y, int z, ForgeDirection side) { + int meta = world.getBlockMetadata(x, y, z); + boolean flipped = ((meta & 4) != 0); + return ((meta & 3) + side.ordinal() == 5) || (side == ForgeDirection.UP && flipped); + } + + @Override + public Icon getBlockTexture(IBlockAccess world, int x, int y, int z, int blockSide) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + if (tef.getSourceBlockId() > 0 && tef.getSourceBlockId() < Block.blocksList.length) { + return blocksList[tef.getSourceBlockId()].getIcon(blockSide, tef.getSourceBlockMetadata()); + } + } + return blocksList[Block.anvil.blockID].getBlockTexture(world, x, y, z, blockSide); + } + + + @Override + public TileEntity createNewTileEntity(World world) { + return null; + } + + @Override + public TileEntity createTileEntity(World world, int metadata) { + return new TileEntityCustomBlock(); + } + + @Override + public int getLightOpacity(World world, int x, int y, int z) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + if(tef.getSourceBlockId() > 0) { + return Math.min(super.getLightOpacity(world, x, y, z), Block.lightOpacity[tef.getSourceBlockId()]); + } + + } + return super.getLightOpacity(world, x, y, z); + } + + + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack) { + int id = -1; + Block b = PainterUtil.getSourceBlock(stack); + if (b != null) { + id = b.blockID; + } + + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + tef.setSourceBlockId(id); + tef.setSourceBlockMetadata(PainterUtil.getSourceBlockMetadata(stack)); + } + world.markBlockForUpdate(x, y, z); + super.onBlockPlacedBy(world, x, y, z, player, stack); + } + + /** + * Remove the tile entity too. + */ + @Override + public void breakBlock(World world, int x, int y, int z, int par5, int par6) { + + if (!world.isRemote && world.getGameRules().getGameRuleBooleanValue("doTileDrops")) { + TileEntity te = world.getBlockTileEntity(x, y, z); + + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + + ItemStack itemStack = createItemStackForSourceBlock(tef.getSourceBlockId(), tef.getSourceBlockMetadata()); + + float f = 0.7F; + double d0 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d1 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + EntityItem entityitem = new EntityItem(world, x + d0, y + d1, z + d2, itemStack); + entityitem.delayBeforeCanPickup = 10; + world.spawnEntityInWorld(entityitem); + + } else { + System.out.println("dropBlockAsItem_do: No tile entity."); + } + + } + + world.removeBlockTileEntity(x, y, z); + } + + @Override + public int quantityDropped(Random par1Random) { + return 0; // need to do custom dropping to maintain source metadata + } + + public static final class PainterTemplate extends BasicPainterTemplate { + + public PainterTemplate() { + } + + @Override + public ItemStack[] getCompletedResult(RecipeInput... inputs) { + ItemStack paintSource = RecipeInput.getInputForSlot(1, inputs); + return new ItemStack[] {createItemStackForSourceBlock(paintSource.itemID, paintSource.getItemDamage())}; + } + + @Override + public boolean isValidTarget(ItemStack target) { + if(target == null) { + return false; + } + Block blk = Util.getBlockFromItemId(target.itemID); + return blk instanceof BlockStairs; + } + } + + +} diff --git a/common/crazypants/enderio/machine/painter/BlockCustomWall.java b/common/crazypants/enderio/machine/painter/BlockCustomWall.java new file mode 100644 index 00000000..e71b326d --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockCustomWall.java @@ -0,0 +1,168 @@ +package crazypants.enderio.machine.painter; + +import java.util.Random; + +import net.minecraft.block.*; +import net.minecraft.entity.EntityLiving; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.*; +import cpw.mods.fml.common.registry.*; +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; + +public class BlockCustomWall extends BlockWall implements ITileEntityProvider { + + + public static BlockCustomWall create() { + BlockCustomWall result = new BlockCustomWall(); + result.init(); + return result; + } + + public BlockCustomWall() { + super(ModObject.blockCustomWall.id, Block.cobblestone); + setCreativeTab(null); + setUnlocalizedName(ModObject.blockCustomWall.unlocalisedName); + } + + + private void init() { + LanguageRegistry.addName(this, ModObject.blockCustomWall.name); + GameRegistry.registerBlock(this, BlockItemCustomWall.class, ModObject.blockCustomWall.unlocalisedName); + GameRegistry.registerTileEntity(TileEntityCustomBlock.class, ModObject.blockCustomWall.unlocalisedName + "TileEntity"); + MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPainter.unlocalisedName, new PainterTemplate()); + } + + + public static ItemStack createItemStackForSourceBlock(int id, int damage) { + ItemStack result = new ItemStack(ModObject.blockCustomWall.id, 1, damage); + PainterUtil.setSourceBlock(result, id, damage); + return result; + } + + @Override + public int getLightOpacity(World world, int x, int y, int z) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + if(tef.getSourceBlockId() > 0) { + return Math.min(super.getLightOpacity(world, x, y, z), Block.lightOpacity[tef.getSourceBlockId()]); + } + } + return super.getLightOpacity(world, x, y, z); + } + + @Override + public boolean canPlaceTorchOnTop(World world, int x, int y, int z) { + int id = world.getBlockId(x, y, z); + if (id == this.blockID) { + return true; + } + return super.canPlaceTorchOnTop(world, x, y, z); + } + + + @Override + public boolean canConnectWallTo(IBlockAccess par1IBlockAccess, int par2, int par3, int par4) { + int l = par1IBlockAccess.getBlockId(par2, par3, par4); + if(l == ModObject.blockCustomFenceGate.id) { + return true; + } + return super.canConnectWallTo(par1IBlockAccess, par2, par3, par4); + } + + @Override + public Icon getBlockTexture(IBlockAccess world, int x, int y, int z, int blockSide) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + if (tef.getSourceBlockId() > 0 && tef.getSourceBlockId() < Block.blocksList.length) { + return blocksList[tef.getSourceBlockId()].getIcon(blockSide, tef.getSourceBlockMetadata()); + } + } + return blocksList[Block.anvil.blockID].getBlockTexture(world, x, y, z, blockSide); + } + + + @Override + public TileEntity createNewTileEntity(World world) { + return null; + } + + @Override + public TileEntity createTileEntity(World world, int metadata) { + return new TileEntityCustomBlock(); + } + + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack) { + int id = -1; + Block b = PainterUtil.getSourceBlock(stack); + if (b != null) { + id = b.blockID; + } + + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + tef.setSourceBlockId(id); + tef.setSourceBlockMetadata(PainterUtil.getSourceBlockMetadata(stack)); + } + world.markBlockForUpdate(x, y, z); + } + + /** + * Remove the tile entity too. + */ + @Override + public void breakBlock(World world, int x, int y, int z, int par5, int par6) { + + if (!world.isRemote && world.getGameRules().getGameRuleBooleanValue("doTileDrops")) { + TileEntity te = world.getBlockTileEntity(x, y, z); + + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + + ItemStack itemStack = createItemStackForSourceBlock(tef.getSourceBlockId(), tef.getSourceBlockMetadata()); + + float f = 0.7F; + double d0 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d1 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + EntityItem entityitem = new EntityItem(world, x + d0, y + d1, z + d2, itemStack); + entityitem.delayBeforeCanPickup = 10; + world.spawnEntityInWorld(entityitem); + + } else { + System.out.println("dropBlockAsItem_do: No tile entity."); + } + + } + + world.removeBlockTileEntity(x, y, z); + } + + @Override + public int quantityDropped(Random par1Random) { + return 0; // need to do custom dropping to maintain source metadata + } + + public static final class PainterTemplate extends BasicPainterTemplate { + + public PainterTemplate() { + super(Block.cobblestoneWall.blockID); + } + + @Override + public ItemStack[] getCompletedResult(RecipeInput... inputs) { + ItemStack paintSource = RecipeInput.getInputForSlot(1, inputs); + return new ItemStack[] {createItemStackForSourceBlock(paintSource.itemID, paintSource.getItemDamage())}; + } + } + + +} diff --git a/common/crazypants/enderio/machine/painter/BlockItemCustomFence.java b/common/crazypants/enderio/machine/painter/BlockItemCustomFence.java new file mode 100644 index 00000000..3c891e92 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockItemCustomFence.java @@ -0,0 +1,21 @@ +package crazypants.enderio.machine.painter; + +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +public class BlockItemCustomFence extends ItemBlock { + + public BlockItemCustomFence(int id) { + super(id); + setHasSubtypes(true); + } + + public int getMetadata(int par1) { + return par1; + } + +} diff --git a/common/crazypants/enderio/machine/painter/BlockItemCustomFenceGate.java b/common/crazypants/enderio/machine/painter/BlockItemCustomFenceGate.java new file mode 100644 index 00000000..cc913073 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockItemCustomFenceGate.java @@ -0,0 +1,17 @@ +package crazypants.enderio.machine.painter; + +import net.minecraft.item.ItemBlock; + +public class BlockItemCustomFenceGate extends ItemBlock { + + public BlockItemCustomFenceGate(int id) { + super(id); + setHasSubtypes(true); + } + + @Override + public int getMetadata(int par1) { + return par1; + } + +} diff --git a/common/crazypants/enderio/machine/painter/BlockItemCustomStair.java b/common/crazypants/enderio/machine/painter/BlockItemCustomStair.java new file mode 100644 index 00000000..6ef7cfd6 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockItemCustomStair.java @@ -0,0 +1,16 @@ +package crazypants.enderio.machine.painter; + +import net.minecraft.item.ItemBlock; + +public class BlockItemCustomStair extends ItemBlock { + + public BlockItemCustomStair(int id) { + super(id); + setHasSubtypes(true); + } + + @Override + public int getMetadata(int par1) { + return par1; + } +} diff --git a/common/crazypants/enderio/machine/painter/BlockItemCustomWall.java b/common/crazypants/enderio/machine/painter/BlockItemCustomWall.java new file mode 100644 index 00000000..d4014674 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockItemCustomWall.java @@ -0,0 +1,16 @@ +package crazypants.enderio.machine.painter; + +import net.minecraft.item.ItemBlock; + +public class BlockItemCustomWall extends ItemBlock { + + public BlockItemCustomWall(int id) { + super(id); + setHasSubtypes(true); + } + + @Override + public int getMetadata(int par1) { + return par1; + } +} diff --git a/common/crazypants/enderio/machine/painter/BlockPainter.java b/common/crazypants/enderio/machine/painter/BlockPainter.java new file mode 100644 index 00000000..3ef2a48b --- /dev/null +++ b/common/crazypants/enderio/machine/painter/BlockPainter.java @@ -0,0 +1,65 @@ +package crazypants.enderio.machine.painter; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import cpw.mods.fml.common.registry.GameRegistry; +import crazypants.enderio.GuiHandler; +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; + +public class BlockPainter extends AbstractMachineBlock { + + public static final String KEY_SOURCE_BLOCK_ID = "sourceBlockId"; + public static final String KEY_SOURCE_BLOCK_META = "sourceBlockMeta"; + + public static BlockPainter create() { + BlockPainter ppainter = new BlockPainter(); + ppainter.init(); + return ppainter; + } + + private BlockPainter() { + super(ModObject.blockPainter, TileEntityPainter.class); + } + + @Override + protected void init() { + super.init(); + GameRegistry.addRecipe(new ItemStack(this), "bbb", "iri", "bbb", 'i', new ItemStack(Item.ingotIron), 'r', new ItemStack(Item.redstone), 'b', new ItemStack( + ModObject.itemIndustrialBinder.id, 1, 0)); + } + + @Override + public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + // The server needs the container as it manages the adding and removing of + // items, which are then sent to the client for display + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te instanceof TileEntityPainter) { + return new PainterContainer(player.inventory, (AbstractMachineEntity) te); + } + return null; + } + + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + TileEntity te = world.getBlockTileEntity(x, y, z); + return new GuiPainter(player.inventory, (AbstractMachineEntity) te); + } + + @Override + protected int getGuiId() { + return GuiHandler.GUI_ID_PAINTER; + } + + @Override + protected String getMachineFrontIconKey(boolean active) { + if(active) { + return "enderio:painterFrontOn"; + } + return "enderio:painterFrontOff"; + } + +} diff --git a/common/crazypants/enderio/machine/painter/GuiPainter.java b/common/crazypants/enderio/machine/painter/GuiPainter.java new file mode 100644 index 00000000..2e67ab29 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/GuiPainter.java @@ -0,0 +1,48 @@ +package crazypants.enderio.machine.painter; + +import java.awt.Rectangle; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.util.StatCollector; + +import org.lwjgl.opengl.GL11; + +import cpw.mods.fml.relauncher.*; +import crazypants.enderio.machine.AbstractMachineEntity; +import crazypants.enderio.machine.GuiMachineBase; +import crazypants.render.GuiContainerBase; +import crazypants.render.GuiToolTip; +import crazypants.render.RenderUtil; + +@SideOnly(Side.CLIENT) +public class GuiPainter extends GuiMachineBase { + + private AbstractMachineEntity tileEntity; + + public GuiPainter(InventoryPlayer par1InventoryPlayer, AbstractMachineEntity furnaceInventory) { + super(furnaceInventory, new PainterContainer(par1InventoryPlayer, furnaceInventory)); + tileEntity = furnaceInventory; + } + + /** + * Draw the background layer for the GuiContainer (everything behind the + * items) + */ + @Override + protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + RenderUtil.bindTexture("enderio:textures/gui/painter.png"); + int k = (width - xSize) / 2; + int l = (height - ySize) / 2; + + drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize); + int i1; + + i1 = tileEntity.getProgressScaled(24); + drawTexturedModalRect(k + 88, l + 34, 176, 14, i1 + 1, 16); + + super.drawGuiContainerBackgroundLayer(par1, par2, par3); + } +} + diff --git a/common/crazypants/enderio/machine/painter/PaintedItemRenderer.java b/common/crazypants/enderio/machine/painter/PaintedItemRenderer.java new file mode 100644 index 00000000..e0ba2426 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/PaintedItemRenderer.java @@ -0,0 +1,70 @@ +package crazypants.enderio.machine.painter; + +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.entity.EntityLiving; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.item.ItemStack; +import net.minecraftforge.client.IItemRenderer; + +import org.lwjgl.opengl.GL11; + +public class PaintedItemRenderer implements IItemRenderer { + + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED_FIRST_PERSON; + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return type == ItemRenderType.INVENTORY || type == ItemRenderType.ENTITY; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + + if (type == ItemRenderType.INVENTORY) { + RenderBlocks renderBlocks = (RenderBlocks) data[0]; + renderToInventory(item, renderBlocks); + } else if (type == ItemRenderType.EQUIPPED) { + renderEquipped(item, (RenderBlocks) data[0]); + } else if (type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + renderEntity(item, (RenderBlocks) data[0]); + } else { + System.out.println("CustomFenceRenderer.renderItem: Unsupported render type"); + } + + } + + public void renderEntity(ItemStack item, RenderBlocks renderBlocks) { + Block block = PainterUtil.getSourceBlock(item); + if (block != null) { + renderBlocks.setOverrideBlockTexture(renderBlocks.getBlockIconFromSideAndMetadata(block, 2, item.getItemDamage())); + } + renderBlocks.renderBlockAsItem(Block.blocksList[item.itemID], item.getItemDamage(), 1.0f); + renderBlocks.clearOverrideBlockTexture(); + } + + public void renderEquipped(ItemStack item, RenderBlocks renderBlocks) { + Block block = PainterUtil.getSourceBlock(item); + if (block != null) { + renderBlocks.setOverrideBlockTexture(renderBlocks.getBlockIconFromSideAndMetadata(block, 2, item.getItemDamage())); + } + GL11.glPushMatrix(); + GL11.glTranslatef(0.75F, 0.0F, 0.0F); + renderBlocks.renderBlockAsItem(Block.blocksList[item.itemID], item.getItemDamage(), 1.0f); + GL11.glPopMatrix(); + renderBlocks.clearOverrideBlockTexture(); + } + + public void renderToInventory(ItemStack item, RenderBlocks renderBlocks) { + Block block = PainterUtil.getSourceBlock(item); + if (block != null) { + renderBlocks.setOverrideBlockTexture(renderBlocks.getBlockIconFromSideAndMetadata(block, 2, item.getItemDamage())); + } + renderBlocks.renderBlockAsItem(Block.blocksList[item.itemID], item.getItemDamage(), 1.0f); + renderBlocks.clearOverrideBlockTexture(); + } + +} diff --git a/common/crazypants/enderio/machine/painter/PainterContainer.java b/common/crazypants/enderio/machine/painter/PainterContainer.java new file mode 100644 index 00000000..8bcc39ed --- /dev/null +++ b/common/crazypants/enderio/machine/painter/PainterContainer.java @@ -0,0 +1,110 @@ +package crazypants.enderio.machine.painter; + +import crazypants.enderio.machine.AbstractMachineEntity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +public class PainterContainer extends Container { + + final AbstractMachineEntity tileEntity; + private int progress = 0; + + public PainterContainer(InventoryPlayer playerInv, AbstractMachineEntity te) { + + this.tileEntity = te; + + addSlotToContainer(new Slot(tileEntity, 0, 67, 34) { + @Override + public boolean isItemValid(ItemStack itemStack) { + return tileEntity.isItemValidForSlot(0, itemStack); + } + }); + addSlotToContainer(new Slot(tileEntity, 1, 37, 34) { + @Override + public boolean isItemValid(ItemStack itemStack) { + return tileEntity.isItemValidForSlot(1, itemStack); + } + }); + addSlotToContainer(new Slot(tileEntity, 2, 121, 34) { + @Override + public boolean isItemValid(ItemStack par1ItemStack) { + return false; + } + }); + + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (int i = 0; i < 9; ++i) { + addSlotToContainer(new Slot(playerInv, i, 8 + i * 18, 142)); + } + + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return tileEntity.isUseableByPlayer(entityplayer); + } + + + @Override + public ItemStack transferStackInSlot(EntityPlayer entityPlayer, int slotIndex) { + ItemStack itemstack = null; + Slot slot = (Slot) inventorySlots.get(slotIndex); + if (slot != null && slot.getHasStack()) { + ItemStack origStack = slot.getStack(); + itemstack = origStack.copy(); + + if (slotIndex == 2) { + + if (!mergeItemStack(origStack, 3, 39, true)) { + return null; + } + slot.onSlotChange(origStack, itemstack); + + } else if (slotIndex != 1 && slotIndex != 0) { + + if (tileEntity.isItemValidForSlot(0, origStack)) { + if (!this.mergeItemStack(origStack, 0, 1, false)) { + return null; + } + } else if (tileEntity.isItemValidForSlot(1, origStack)) { + if (!this.mergeItemStack(origStack, 1, 2, false)) { + return null; + } + } else if (slotIndex >= 3 && slotIndex < 30) { + if (!this.mergeItemStack(origStack, 30, 39, false)) { + return null; + } + } else if (slotIndex >= 30 && slotIndex < 39 && !this.mergeItemStack(origStack, 3, 30, false)) { + return null; + } + + } else if (!mergeItemStack(origStack, 3, 39, false)) { + return null; + } + + if (origStack.stackSize == 0) { + slot.putStack((ItemStack) null); + } else { + slot.onSlotChanged(); + } + + if (origStack.stackSize == itemstack.stackSize) { + return null; + } + + slot.onPickupFromSlot(entityPlayer, origStack); + } + + return itemstack; + } + + +} diff --git a/common/crazypants/enderio/machine/painter/PainterUtil.java b/common/crazypants/enderio/machine/painter/PainterUtil.java new file mode 100644 index 00000000..785003f7 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/PainterUtil.java @@ -0,0 +1,77 @@ +package crazypants.enderio.machine.painter; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import net.minecraft.util.StringTranslate; + +public final class PainterUtil { + + + private PainterUtil() { + } + + public static boolean isMetadataEquivelent(ItemStack one, ItemStack two) { + if(one == null || two == null) { + return false; + } + return PainterUtil.getSourceBlockId(one) == PainterUtil.getSourceBlockId(two) && PainterUtil.getSourceBlockMetadata(one) == PainterUtil.getSourceBlockMetadata(two); + } + + public static Block getSourceBlock(ItemStack item) { + NBTTagCompound tag = item.getTagCompound(); + if (tag != null) { + int blockId = tag.getInteger(BlockPainter.KEY_SOURCE_BLOCK_ID); + if (blockId >= 0 && blockId < Block.blocksList.length) { + return Block.blocksList[blockId]; + } + } + return null; + } + + public static int getSourceBlockId(ItemStack item) { + NBTTagCompound tag = item.getTagCompound(); + if (tag != null) { + int blockId = tag.getInteger(BlockPainter.KEY_SOURCE_BLOCK_ID); + if (blockId >= 0 && blockId < Block.blocksList.length) { + return blockId; + } + } + return -1; + } + + public static int getSourceBlockMetadata(ItemStack item) { + NBTTagCompound tag = item.getTagCompound(); + if (tag != null) { + return tag.getInteger(BlockPainter.KEY_SOURCE_BLOCK_META); + } + return 0; + } + + public static void setSourceBlock(ItemStack item, int sourceId, int meta) { + NBTTagCompound tag = item.getTagCompound(); + if (tag == null) { + tag = new NBTTagCompound(); + item.setTagCompound(tag); + } + tag.setInteger(BlockPainter.KEY_SOURCE_BLOCK_ID, sourceId); + tag.setInteger(BlockPainter.KEY_SOURCE_BLOCK_META, meta); + + String sourceName = ""; + if (sourceId > 0) { + sourceName = Item.itemsList[sourceId].getUnlocalizedName(new ItemStack(sourceId, 1, meta)); + sourceName = StatCollector.translateToLocal(sourceName + ".name"); + } + String typeName; + typeName = Item.itemsList[item.itemID].getUnlocalizedName(item); + typeName = StatCollector.translateToLocal(typeName + ".name"); + + NBTTagCompound displayTags = new NBTTagCompound(); + displayTags.setString("Name", "Painted " + sourceName + " " + typeName); + tag.setCompoundTag("display", displayTags); + + } + +} diff --git a/common/crazypants/enderio/machine/painter/TileEntityCustomBlock.java b/common/crazypants/enderio/machine/painter/TileEntityCustomBlock.java new file mode 100644 index 00000000..00154bb4 --- /dev/null +++ b/common/crazypants/enderio/machine/painter/TileEntityCustomBlock.java @@ -0,0 +1,67 @@ +package crazypants.enderio.machine.painter; + +import crazypants.enderio.PacketHandler; +import net.minecraft.block.Block; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.packet.Packet; +import net.minecraft.tileentity.TileEntity; + +public class TileEntityCustomBlock extends TileEntity { + + private static final String KEY_SOURCE_BLOCK_ID = "sourceBlockId"; + private static final String KEY_SOURCE_BLOCK_META = "sourceBlockMeta"; + private int sourceBlockId; + private int sourceBlockMetadata; + + public TileEntityCustomBlock() { + this.sourceBlockId = -1; + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + super.readFromNBT(nbtRoot); + sourceBlockId = nbtRoot.getInteger(KEY_SOURCE_BLOCK_ID); + sourceBlockMetadata = nbtRoot.getInteger(KEY_SOURCE_BLOCK_META); + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + nbtRoot.setInteger(KEY_SOURCE_BLOCK_ID, sourceBlockId); + nbtRoot.setInteger(KEY_SOURCE_BLOCK_META, sourceBlockMetadata); + } + + public int getSourceBlockId() { + return sourceBlockId; + } + + public void setSourceBlockId(int sourceBlockId) { + this.sourceBlockId = sourceBlockId; + } + + public int getSourceBlockMetadata() { + return sourceBlockMetadata; + } + + public void setSourceBlockMetadata(int sourceBlockMetadata) { + this.sourceBlockMetadata = sourceBlockMetadata; + } + + public Block getSourceBlock() { + if(sourceBlockId <= 0) { + return null; + } + return Block.blocksList[sourceBlockId]; + } + + @Override + public Packet getDescriptionPacket() { + return PacketHandler.getPacket(this); + } + + @Override + public boolean canUpdate() { + return false; + } + +} diff --git a/common/crazypants/enderio/machine/painter/TileEntityPainter.java b/common/crazypants/enderio/machine/painter/TileEntityPainter.java new file mode 100644 index 00000000..11277f5f --- /dev/null +++ b/common/crazypants/enderio/machine/painter/TileEntityPainter.java @@ -0,0 +1,70 @@ +package crazypants.enderio.machine.painter; + +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; + +public class TileEntityPainter extends AbstractPoweredTaskEntity implements ISidedInventory { + + private static final short MAX_POWER_USE_PER_TICK = 6; + + public TileEntityPainter() { + // 0 = input slot, 1 = paint source, 2 = output slot + super(3); + } + + @Override + public boolean canExtractItem(int i, ItemStack itemstack, int j) { + return super.canExtractItem(i, itemstack, j) && PainterUtil.isMetadataEquivelent(itemstack, inventory[2]); + } + + @Override + public String getInvName() { + return "Auto Painter"; + } + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + if (i > 1) { + return false; + } + if (i == 0) { + return !MachineRecipeRegistry.instance.getRecipesForInput(getMachineName(), RecipeInput.create(i, itemStack)).isEmpty(); + } + if (inventory[0] == null) { + return BasicPainterTemplate.isValidSourceDefault(itemStack); + } + return MachineRecipeRegistry.instance.getRecipeForInputs(getMachineName(), targetInput(), paintSource()) != null; + } + + @Override + public String getMachineName() { + return ModObject.blockPainter.unlocalisedName; + } + + private RecipeInput targetInput() { + return RecipeInput.create(0, inventory[0]); + } + + private RecipeInput paintSource() { + return RecipeInput.create(1, inventory[1]); + } + + @Override + protected boolean canMergeWithCurrentOuput(ItemStack nextResult) { + if (!nextResult.isItemEqual(inventory[2])) { + // next result is a different item type + return false; + } + + int cookedId = nextResult.getTagCompound().getInteger(BlockPainter.KEY_SOURCE_BLOCK_ID); + int invId = inventory[2].getTagCompound().getInteger(BlockPainter.KEY_SOURCE_BLOCK_ID); + if (cookedId != invId) { + // next result has a different source item than the current one + return false; + } + return true; + } + +} diff --git a/common/crazypants/enderio/machine/reservoir/BlockReservoir.java b/common/crazypants/enderio/machine/reservoir/BlockReservoir.java new file mode 100644 index 00000000..b8357223 --- /dev/null +++ b/common/crazypants/enderio/machine/reservoir/BlockReservoir.java @@ -0,0 +1,283 @@ +package crazypants.enderio.machine.reservoir; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.Icon; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidStack; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.EnderIOTab; +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.ConduitUtil; +import crazypants.enderio.machine.reservoir.TileReservoir.Pos; +import crazypants.util.BlockCoord; +import crazypants.util.Util; +import crazypants.vecmath.Vector3d; + +public class BlockReservoir extends BlockContainer { + + public static BlockReservoir create() { + BlockReservoir result = new BlockReservoir(); + result.init(); + return result; + } + + private static enum MbFace { + TL("reservoirMbTl"), + TR("reservoirMbTr"), + BL("reservoirMbBl"), + BR("reservoirMbBr"), + T("reservoirMbT"), + B("reservoirMbB"), + L("reservoirMbL"), + R("reservoirMbR"); + + String iconName; + + private MbFace(String iconName) { + this.iconName = iconName; + } + + } + + private Icon[] mbIcons = new Icon[8]; + Icon switchIcon; + + private BlockReservoir() { + super(ModObject.blockReservoir.id, Material.rock); + setHardness(0.5F); + setStepSound(Block.soundStoneFootstep); + setUnlocalizedName(ModObject.blockReservoir.unlocalisedName); + setCreativeTab(EnderIOTab.tabEnderIO); + } + + private void init() { + LanguageRegistry.addName(this, ModObject.blockReservoir.name); + GameRegistry.registerBlock(this, ModObject.blockReservoir.unlocalisedName); + GameRegistry.registerTileEntity(TileReservoir.class, ModObject.blockReservoir.unlocalisedName + "TileEntity"); + } + + @Override + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int par6, float par7, float par8, float par9) { + + ItemStack current = entityPlayer.inventory.getCurrentItem(); + if (current != null) { + + TileReservoir tank = (TileReservoir) world.getBlockTileEntity(x, y, z); + + // LiquidStack liquid = + // LiquidContainerRegistry.getLiquidForFilledItem(current); + FluidStack liquid = FluidContainerRegistry.getFluidForFilledItem(current); + + if (liquid != null) { + // Handle filled containers + int qty = tank.getController().doFill(ForgeDirection.UNKNOWN, liquid, true); + + if (qty != 0 && !entityPlayer.capabilities.isCreativeMode) { + entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, Util.consumeItem(current)); + } + return true; + + } else { + // Handle empty containers + + FluidStack available = tank.getTankInfo(ForgeDirection.UNKNOWN)[0].fluid; + if (available != null) { + ItemStack filled = FluidContainerRegistry.fillFluidContainer(available, current); + + liquid = FluidContainerRegistry.getFluidForFilledItem(filled); + + if (liquid != null) { + if (!entityPlayer.capabilities.isCreativeMode) { + if (current.stackSize > 1) { + if (!entityPlayer.inventory.addItemStackToInventory(filled)) + return false; + else { + entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, Util.consumeItem(current)); + } + } else { + entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, Util.consumeItem(current)); + entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, filled); + } + } + tank.drain(ForgeDirection.UNKNOWN, liquid.amount, true); + return true; + + } else if (ConduitUtil.isToolEquipped(entityPlayer) && tank.isMultiblock()) { + tank.setAutoEject(!tank.isAutoEject()); + for (BlockCoord bc : tank.multiblock) { + world.markBlockForUpdate(bc.x, bc.y, bc.z); + } + + } + + } + } + } + + return false; + + } + + @Override + @SideOnly(Side.CLIENT) + public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof TileReservoir)) { + return super.getSelectedBoundingBoxFromPool(world, x, y, z); + } + TileReservoir tr = (TileReservoir) te; + if (!tr.isMultiblock()) { + return super.getSelectedBoundingBoxFromPool(world, x, y, z); + } + + Vector3d min = new Vector3d(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE); + Vector3d max = new Vector3d(-Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE); + for (BlockCoord bc : tr.multiblock) { + min.x = Math.min(min.x, bc.x); + max.x = Math.max(max.x, bc.x + 1); + min.y = Math.min(min.y, bc.y); + max.y = Math.max(max.y, bc.y + 1); + min.z = Math.min(min.z, bc.z); + max.z = Math.max(max.z, bc.z + 1); + } + return AxisAlignedBB.getAABBPool().getAABB(min.x, min.y, min.z, max.x, max.y, max.z); + + } + + @Override + public boolean renderAsNormalBlock() { + return false; + } + + @Override + public boolean isOpaqueCube() { + return false; + } + + @Override + public TileEntity createNewTileEntity(World world) { + return null; + } + + @Override + public TileEntity createTileEntity(World world, int metadata) { + return new TileReservoir(); + } + + @Override + public void onBlockAdded(World world, int x, int y, int z) { + if (world.isRemote) { + return; + } + TileReservoir tr = (TileReservoir) world.getBlockTileEntity(x, y, z); + boolean res = tr.onBlockAdded(); + + } + + @Override + public void onNeighborBlockChange(World world, int x, int y, int z, int blockId) { + if (world.isRemote) { + return; + } + TileReservoir te = (TileReservoir) world.getBlockTileEntity(x, y, z); + te.onNeighborBlockChange(blockId); + } + + @Override + public void registerIcons(IconRegister iconRegister) { + blockIcon = iconRegister.registerIcon("enderio:reservoir"); + for (MbFace face : MbFace.values()) { + mbIcons[face.ordinal()] = iconRegister.registerIcon("enderio:" + face.iconName); + } + switchIcon = iconRegister.registerIcon("enderio:reservoirSwitch"); + } + + @Override + @SideOnly(Side.CLIENT) + public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int blockSide) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if (!(te instanceof TileReservoir)) { + return true; + } + TileReservoir tr = (TileReservoir) te; + if (!tr.isMultiblock()) { + return true; + } + return false; + } + + @Override + public Icon getBlockTexture(IBlockAccess world, int x, int y, int z, int blockSide) { + // used to render the block in the world + TileEntity te = world.getBlockTileEntity(x, y, z); + + if (!(te instanceof TileReservoir)) { + return blockIcon; + } + TileReservoir tr = (TileReservoir) te; + if (!tr.isMultiblock()) { + return blockIcon; + } + + ForgeDirection side = ForgeDirection.getOrientation(blockSide); + Pos pos = tr.pos; + + if (tr.front == side || tr.front == side.getOpposite()) { // 2x2 area + + boolean isRight; + if (tr.isVertical()) { // to to flip right and left for back faces of + // vertical multiblocks + isRight = (pos.isRight && tr.front != side.getOpposite()) || (!pos.isRight && tr.front == side.getOpposite()); + } else { + isRight = pos.isRight; + } + if (pos.isTop) { + return isRight ? mbIcons[MbFace.TR.ordinal()] : mbIcons[MbFace.TL.ordinal()]; + } else { + return isRight ? mbIcons[MbFace.BR.ordinal()] : mbIcons[MbFace.BL.ordinal()]; + } + + } + if (tr.up == side || tr.up == side.getOpposite()) { // up or down face + if (tr.isVertical()) { + if (tr.right.offsetX != 0) { + return pos.isRight ? mbIcons[MbFace.L.ordinal()] : mbIcons[MbFace.R.ordinal()]; + } else { + return pos.isRight ? mbIcons[MbFace.T.ordinal()] : mbIcons[MbFace.B.ordinal()]; + } + } else { + if (tr.up == side) { + return pos.isRight ? mbIcons[MbFace.L.ordinal()] : mbIcons[MbFace.R.ordinal()]; + } else { + return pos.isRight ? mbIcons[MbFace.R.ordinal()] : mbIcons[MbFace.L.ordinal()]; + } + } + + } else { + if (tr.isVertical()) { + return pos.isTop ? mbIcons[MbFace.T.ordinal()] : mbIcons[MbFace.B.ordinal()]; + } else { + if (tr.right != side) { + return pos.isTop ? mbIcons[MbFace.L.ordinal()] : mbIcons[MbFace.R.ordinal()]; + } else { + return pos.isTop ? mbIcons[MbFace.R.ordinal()] : mbIcons[MbFace.L.ordinal()]; + } + } + } + + } + +} diff --git a/common/crazypants/enderio/machine/reservoir/ReservoirRenderer.java b/common/crazypants/enderio/machine/reservoir/ReservoirRenderer.java new file mode 100644 index 00000000..c4a72b89 --- /dev/null +++ b/common/crazypants/enderio/machine/reservoir/ReservoirRenderer.java @@ -0,0 +1,169 @@ +package crazypants.enderio.machine.reservoir; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.common.ForgeDirection; + +import org.lwjgl.opengl.GL11; + +import crazypants.render.BoundingBox; +import crazypants.render.CubeRenderer; +import crazypants.render.RenderUtil; +import crazypants.vecmath.Vector3d; + + +public class ReservoirRenderer extends TileEntitySpecialRenderer { + + private ResourceLocation texName = null; + private Icon tex = null; + private float switchSize = 0.25f; + private float switchHSize = switchSize / 2f; + private BoundingBox switchBB = new BoundingBox(0.5 - switchHSize, 0.5 - switchHSize, 0.5 - switchHSize, 0.5 + switchHSize, 0.5 + switchHSize, + 0.5 + switchHSize); + + private final BlockReservoir block; + + public ReservoirRenderer(BlockReservoir res) { + block = res; + } + + @Override + public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) { + + TileReservoir res = (TileReservoir) tileentity; + + float fullness = res.getFilledRatio(); + if ((res.isMultiblock() && !res.isMaster() && (fullness >= 0 || res.isAutoEject())) || (!res.isMultiblock() && + fullness <= 0) ) { + return; + } + + float val = RenderUtil.claculateTotalBrightnessForLocation(tileentity.worldObj, tileentity.xCoord, tileentity.yCoord, tileentity.zCoord); + Minecraft.getMinecraft().entityRenderer.disableLightmap(0); + + + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glDisable(GL11.GL_LIGHTING); + + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + GL11.glTranslatef((float) x, (float) y, (float) z); + + BoundingBox bb = res.getLiquidRenderBounds(); + + if (res.isMultiblock() && res.isAutoEject()) { + + // switch + RenderUtil.bindBlockTexture(); + + Tessellator.instance.startDrawingQuads(); + Tessellator.instance.setColorRGBA_F(val, val, val, 1); + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + drawSwitch(dir, bb); + } + Tessellator.instance.draw(); + } + + if (fullness > 0) { + RenderUtil.bindTexture(getLiquidSheet()); + + float margin = 0.01f; + + Icon tex = getLiquidTexture(); + float maxV = tex.getMinV() + ((tex.getMaxV() - tex.getMinV()) * fullness); + + Tessellator.instance.startDrawingQuads(); + Tessellator.instance.setColorRGBA_F(val, val, val, 1); + CubeRenderer.render( + new BoundingBox(bb.minX + margin, bb.minY + margin, bb.minZ + margin, bb.maxX - margin, + bb.minY + (fullness * (Math.abs(bb.maxY - bb.minY))) - margin, bb.maxZ - margin), tex.getMinU(), tex.getMaxU(), tex.getMinV(), maxV); + Tessellator.instance.draw(); + } + + GL11.glPopAttrib(); + GL11.glPopMatrix(); + + } + + private Vector3d forward = new Vector3d(); + private Vector3d left = new Vector3d(); + private Vector3d up = new Vector3d(); + private Vector3d offset = new Vector3d(); + + private void drawSwitch(ForgeDirection dir, BoundingBox bb) { + Tessellator tes = Tessellator.instance; + + Vector3d cent = bb.getCenter(); + offset.set(cent); + + boolean isUp = dir.offsetY != 0; + + if(dir == ForgeDirection.UP) { + int i = 0; + } + + forward.set(dir.offsetX, dir.offsetY, dir.offsetZ); + forward.scale(0.5); + forward.x *= bb.sizeX(); + forward.y *= bb.sizeY(); + forward.z *= bb.sizeZ(); + + offset.add(forward); + + if(dir.offsetY == 0) { + offset.y += bb.sizeY() * 0.25; + } + if(dir.offsetX == 0) { + offset.x -= (isUp ? dir.offsetY : dir.offsetZ) * bb.sizeX() * 0.25; + } + if(dir.offsetZ == 0) { + offset.z += (isUp ? -dir.offsetY : dir.offsetX) * bb.sizeZ() * 0.25; + } + + left.set(isUp ? -dir.offsetY : -dir.offsetZ, 0, dir.offsetX); + + if (isUp) { + up.set(0, 0, -1); + } else { + up.set(0, 1, 0); + } + + forward.scale(0.5); + left.scale(0.125); + up.scale(0.125); + + Icon icon = block.switchIcon; + + tes.addVertexWithUV(offset.x + left.x - up.x, offset.y + left.y - up.y, + offset.z + left.z - up.z, icon.getMinU(), icon.getMaxV()); + tes.addVertexWithUV(offset.x - left.x - up.x, offset.y - left.y - up.y, + offset.z - left.z - up.z, icon.getMaxU(), icon.getMaxV()); + tes.addVertexWithUV(offset.x - left.x + up.x, offset.y - left.y + up.y, + offset.z - left.z + up.z, icon.getMaxU(), icon.getMinV()); + tes.addVertexWithUV(offset.x + left.x + up.x, offset.y + left.y + up.y, + offset.z + left.z + up.z, icon.getMinU(), icon.getMinV()); + + } + + private ResourceLocation getLiquidSheet() { + if (texName == null) { + texName = TextureMap.field_110575_b; + } + return texName; + } + + private Icon getLiquidTexture() { + if (tex == null) { + tex = ReservoirTank.WATER.getFluid().getStillIcon(); + } + return tex; + } +} diff --git a/common/crazypants/enderio/machine/reservoir/ReservoirTank.java b/common/crazypants/enderio/machine/reservoir/ReservoirTank.java new file mode 100644 index 00000000..3bef26c9 --- /dev/null +++ b/common/crazypants/enderio/machine/reservoir/ReservoirTank.java @@ -0,0 +1,66 @@ +package crazypants.enderio.machine.reservoir; + +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; + +public class ReservoirTank extends FluidTank { + + static final FluidStack WATER = FluidRegistry.getFluidStack("water", 0); + + ReservoirTank(int quantity, int capacity) { + super(WATER.getFluid(), quantity, capacity); + } + + ReservoirTank(int capacity) { + this(0, capacity); + } + + ReservoirTank(FluidStack liquid, int capacity) { + super(liquid, capacity); + } + + public int getAmount() { + return getFluid().amount; + } + + public float getFilledRatio() { + return (float) getAmount() / getCapacity(); + } + + public boolean isFull() { + return getAmount() >= getCapacity(); + } + + public void setAmount(int amount) { + FluidStack newLiquid = WATER.copy(); + newLiquid.amount = Math.min(getCapacity(), amount); + setFluid(newLiquid); + } + + @Override + public FluidStack getFluid() { + FluidStack l = super.getFluid(); + if (l == null) { + l = WATER.copy(); + setFluid(l); + } + return l; + } + + public int getAvailableSpace() { + return getCapacity() - getAmount(); + } + + public void addAmount(int amount) { + setAmount(getAmount() + amount); + } + + @Override + public void setCapacity(int capacity) { + super.setCapacity(capacity); + if (getAmount() > capacity) { + setAmount(capacity); + } + } +} diff --git a/common/crazypants/enderio/machine/reservoir/TankNeighbour.java b/common/crazypants/enderio/machine/reservoir/TankNeighbour.java new file mode 100644 index 00000000..81874456 --- /dev/null +++ b/common/crazypants/enderio/machine/reservoir/TankNeighbour.java @@ -0,0 +1,18 @@ +package crazypants.enderio.machine.reservoir; + +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.IFluidHandler; + +class TankNeighbour { + + final IFluidHandler container; + final ForgeDirection fillFromDir; + + TankNeighbour(IFluidHandler container, ForgeDirection fillFromDir) { + this.container = container; + this.fillFromDir = fillFromDir; + } + + + +} diff --git a/common/crazypants/enderio/machine/reservoir/TileReservoir.java b/common/crazypants/enderio/machine/reservoir/TileReservoir.java new file mode 100644 index 00000000..000f3f08 --- /dev/null +++ b/common/crazypants/enderio/machine/reservoir/TileReservoir.java @@ -0,0 +1,630 @@ +package crazypants.enderio.machine.reservoir; + +import static net.minecraftforge.common.ForgeDirection.EAST; +import static net.minecraftforge.common.ForgeDirection.NORTH; +import static net.minecraftforge.common.ForgeDirection.UNKNOWN; +import static net.minecraftforge.common.ForgeDirection.UP; +import static net.minecraftforge.common.ForgeDirection.WEST; +import static net.minecraftforge.fluids.FluidContainerRegistry.BUCKET_VOLUME; + +import java.util.ArrayList; + +import crazypants.enderio.ModObject; +import crazypants.enderio.PacketHandler; +import crazypants.render.BoundingBox; +import crazypants.util.BlockCoord; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.packet.Packet; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; + +public class TileReservoir extends TileEntity implements IFluidHandler { + + enum Pos { + TL(true, false), + TR(true, true), + BL(false, false), + BR(false, true), + UNKNOWN(false, false); + + boolean isTop; + boolean isRight; + + private Pos(boolean isTop, boolean isRight) { + this.isTop = isTop; + this.isRight = isRight; + } + } + + static final FluidStack WATER_BUCKET = FluidRegistry.getFluidStack("water", BUCKET_VOLUME); + + BlockCoord[] multiblock = null; + + // Orientation of multibock + ForgeDirection front = UNKNOWN; + ForgeDirection up = UNKNOWN; + ForgeDirection right = UNKNOWN; + + // Position within multiblock + Pos pos = Pos.UNKNOWN; + + ReservoirTank tank = new ReservoirTank(BUCKET_VOLUME); + + ReservoirTank regenTank = null; + + boolean autoEject; + + private boolean tankDirty = false; + + private boolean neighboursDirty = false; + + private long ticksSinceFill = 0; + + private BoundingBox liquidRenderBounds = null; + + private ArrayList tankNeighbours; + + @Override + public void updateEntity() { + if (worldObj == null || worldObj.isRemote) { + return; + } + if (isMaster()) { + if (regenTank.isFull() && !tank.isFull()) { + ++ticksSinceFill; + if (ticksSinceFill >= 20) { + ticksSinceFill = 0; + tank.fill(WATER_BUCKET, true); + tankDirty = true; + } + } + if(autoEject && neighboursDirty) { + doUpdateTankNeighbours(); + } + if(autoEject && tankNeighbours != null && !tankNeighbours.isEmpty() && tank.getAmount() > 0) { + int ejectable = tank.getAmount(); + int amountPerNeighbour = ejectable / tankNeighbours.size(); + FluidStack source = WATER_BUCKET.copy(); + int used = 0; + for(TankNeighbour tc : tankNeighbours) { + source.amount = amountPerNeighbour; + used += tc.container.fill(tc.fillFromDir, source, true); + } + tank.drain(used, true); + tankDirty = true; + } + } + if (tankDirty) { + worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); + tankDirty = false; + } + } + + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + if(isMultiblock()) { + return 0; + } + return getController().doFill(from, resource, doFill); + } + + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return getController().doDrain(from, maxDrain, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + if (resource != null && !resource.isFluidEqual(tank.getFluid())) { + return null; + } + return drain(from, resource.amount, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + if(tank.getFluid() == null) { + return true; + } + if(fluid != null && fluid.getID() == tank.getFluid().fluidID) { + return true; + } + return false; + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + if(tank.getFluid() == null || fluid == null) { + return false; + } + return tank.getFluid().getFluid().getID() == fluid.getID(); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return getController().doGetTankInfo(from); + } + + private FluidTankInfo[] doGetTankInfo(ForgeDirection from) { + return new FluidTankInfo[]{tank.getInfo()}; + } + + @Override + public Packet getDescriptionPacket() { + return PacketHandler.getPacket(this); + } + + public void setAutoEject(boolean autoEject) { + TileReservoir c = getController(); + if (c != null) { + c.doSetAutoEject(autoEject); + } else { + doSetAutoEject(autoEject); + } + } + + private void doSetAutoEject(boolean newVal) { + if (newVal && !autoEject) { + updateTankNeighbours(); + } + this.autoEject = newVal; + } + + public boolean isAutoEject() { + TileReservoir c = getController(); + if (c != null) { + return c.doIsAutoEject(); + } else { + return doIsAutoEject(); + } + } + + private boolean doIsAutoEject() { + return autoEject; + } + + private void updateTankNeighbours() { + TileReservoir c = getController(); + if (c != null) { + c.neighboursDirty = true; + } + } + + + private void doUpdateTankNeighbours() { + if (tankNeighbours == null) { + tankNeighbours = new ArrayList(); + } + tankNeighbours.clear(); + for (BlockCoord bc : multiblock) { + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + BlockCoord check = bc.getLocation(dir); + if (!inMultiblock(check)) { + IFluidHandler tc = getTankContainer(check); + if (tc != null) { + tankNeighbours.add(new TankNeighbour(tc, dir.getOpposite())); + } + } + } + } + neighboursDirty = false; + } + + private boolean inMultiblock(BlockCoord check) { + for (BlockCoord bc : multiblock) { + if (check.equals(bc)) { + return true; + } + } + return false; + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot) { + super.readFromNBT(nbtRoot); + front = ForgeDirection.getOrientation(nbtRoot.getShort("front")); + up = ForgeDirection.getOrientation(nbtRoot.getShort("up")); + right = ForgeDirection.getOrientation(nbtRoot.getShort("right")); + pos = Pos.values()[nbtRoot.getShort("pos")]; + + autoEject = nbtRoot.getBoolean("autoEject"); + + FluidStack liquid = FluidStack.loadFluidStackFromNBT(nbtRoot.getCompoundTag("tank")); + FluidStack regenLiquid = FluidStack.loadFluidStackFromNBT(nbtRoot.getCompoundTag("regenTank")); + + tank.setCapacity(regenLiquid == null ? BUCKET_VOLUME : BUCKET_VOLUME * 2); + if (liquid != null) { + tank.setFluid(liquid); + } else { + tank.setAmount(0); + } + + if (regenLiquid == null) { + regenTank = null; + } else { + regenTank = new ReservoirTank(regenLiquid, BUCKET_VOLUME * 2); + } + + boolean wasMulti = isMultiblock(); + + if (nbtRoot.getBoolean("isMultiblock")) { + int[] coords = nbtRoot.getIntArray("multiblock"); + multiblock = new BlockCoord[4]; + int c = 0; + for (int i = 0; i < 4; i++) { + multiblock[i] = new BlockCoord(coords[c++], coords[c++], coords[c++]); + } + + if (isMaster() && autoEject) { + updateTankNeighbours(); + } + + } else { + multiblock = null; + } + + if (wasMulti != isMultiblock()) { + liquidRenderBounds = null; + } + + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + nbtRoot.setShort("front", (short) front.ordinal()); + nbtRoot.setShort("up", (short) up.ordinal()); + nbtRoot.setShort("right", (short) right.ordinal()); + nbtRoot.setShort("pos", (short) pos.ordinal()); + + nbtRoot.setBoolean("autoEject", autoEject); + + if (tank.getFluid() != null) { + nbtRoot.setTag("tank", tank.getFluid().writeToNBT(new NBTTagCompound())); + } + if (regenTank != null) { + nbtRoot.setTag("regenTank", regenTank.getFluid().writeToNBT(new NBTTagCompound())); + } + + nbtRoot.setBoolean("isMultiblock", isMultiblock()); + if (isMultiblock()) { + int[] vals = new int[12]; + int i = 0; + for (BlockCoord bc : multiblock) { + vals[i++] = bc.x; + vals[i++] = bc.y; + vals[i++] = bc.z; + } + nbtRoot.setIntArray("multiblock", vals); + } + } + + public boolean onBlockAdded() { + boolean res = formMultiblock(); + return res; + } + + public boolean onNeighborBlockChange(int blockId) { + if (blockId == ModObject.blockReservoir.actualId) { + + if (!isCurrentMultiblockValid()) { + // if its not, try and form a new one + TileReservoir controller = getController(); + if (controller != null) { + controller.clearCurrentMultiblock(); + controller.formMultiblock(); + } else { + clearCurrentMultiblock(); + formMultiblock(); + } + return true; + } + } else if (isMultiblock() && isAutoEject()) { + updateTankNeighbours(); + } + return false; + } + + boolean isVertical() { + return up == UP; + } + + boolean isMaster() { + if (multiblock != null) { + return multiblock[0].equals(xCoord, yCoord, zCoord); + } + return false; + } + + float getFilledRatio() { + return getController().doGetFilledRatio(); + } + + public boolean isMultiblock() { + return multiblock != null; + } + + BoundingBox getLiquidRenderBounds() { + if (liquidRenderBounds == null) { + if (!isMultiblock()) { + return BoundingBox.UNIT_CUBE; + } + BoundingBox bounds = new BoundingBox(multiblock[0]); + for (int i = 1; i < multiblock.length; i++) { + bounds = bounds.expandBy(new BoundingBox(multiblock[i])); + } + liquidRenderBounds = bounds.translate(-multiblock[0].x, -multiblock[0].y, -multiblock[0].z); + } + return liquidRenderBounds; + } + + protected float doGetFilledRatio() { + float result = tank.getFilledRatio(); + if (isMaster()) { + result = regenTank.getFilledRatio() * 0.5f + result * 0.5f; + } + return result; + } + + int doFill(ForgeDirection from, FluidStack resource, boolean doFill) { + if (!WATER_BUCKET.isFluidEqual(resource)) { + return 0; + } + + int ret = 0; + // fill buffer first + if (resource != null && isMaster()) { + resource = resource.copy(); + int filled = regenTank.fill(resource, doFill); + resource.amount -= filled; + ret += filled; + } + ret += tank.fill(resource, doFill); + tankDirty = doFill; + return ret; + } + + protected FluidStack doDrain(ForgeDirection from, int maxDrain, boolean doDrain) { + FluidStack ret = tank.drain(maxDrain, doDrain); + tankDirty = doDrain; + return ret; + } + + private void setMultiblock(BlockCoord[] mb) { + multiblock = mb; + updatePosition(); + + if (isMaster()) { + + regenTank = new ReservoirTank(BUCKET_VOLUME * 2); + tank.setCapacity(BUCKET_VOLUME * 2); + for (BlockCoord bc : multiblock) { + TileReservoir res = getReservoir(bc); + if (res != null) { + FluidStack drained = res.doDrain(ForgeDirection.UNKNOWN, regenTank.getAvailableSpace(), true); + if (drained != null) { + regenTank.addAmount(drained.amount); + } + // incase regen tank is full, add to normal tank + drained = res.doDrain(ForgeDirection.UNKNOWN, tank.getAvailableSpace(), true); + if (drained != null) { + tank.addAmount(drained.amount); + } + } + } + + if (doIsAutoEject()) { + updateTankNeighbours(); + } + + } else { + regenTank = null; + tank.setCapacity(BUCKET_VOLUME); + } + tankDirty = true; + + liquidRenderBounds = null; + + // Forces an update + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, isMultiblock() ? 1 : 0, 2); + } + + TileReservoir getController() { + if (isMaster() || !isMultiblock()) { + return this; + } + TileReservoir res = getReservoir(multiblock[0]); + return res != null ? res : this; + } + + private void updatePosition() { + if (multiblock == null) { + front = UNKNOWN; + up = UNKNOWN; + right = UNKNOWN; + return; + } + + boolean isVertical = false; + for (BlockCoord bc : multiblock) { + if (bc.y != yCoord) { + isVertical = true; + break; + } + } + if (isVertical) { + up = ForgeDirection.UP; + boolean isWestEast = false; + for (BlockCoord bc : multiblock) { + if (bc.x != xCoord) { + isWestEast = true; + break; + } + } + front = isWestEast ? NORTH : EAST; + right = isWestEast ? WEST : NORTH; + } else { + front = UP; + right = EAST; + up = NORTH; + } + + boolean isRight = false; + BlockCoord myCoord = new BlockCoord(this); + for (BlockCoord bc : multiblock) { + if (isInDir(myCoord, right, bc)) { + isRight = true; + } + } + boolean isTop = false; + for (BlockCoord bc : multiblock) { + if (isInDir(myCoord, up, bc)) { + isTop = true; + } + } + if (isTop) { + pos = isRight ? Pos.TR : Pos.TL; + } else { + pos = isRight ? Pos.BR : Pos.BL; + } + + } + + private boolean isInDir(BlockCoord from, ForgeDirection inDir, BlockCoord to) { + if (inDir.offsetX != 0) { + return from.x - inDir.offsetX == to.x; + } else if (inDir.offsetY != 0) { + return from.y - inDir.offsetY == to.y; + } else if (inDir.offsetZ != 0) { + return from.z - inDir.offsetZ == to.z; + } + return false; + } + + private void clearCurrentMultiblock() { + if (multiblock == null) { + return; + } + boolean fillTanks = false; + if (isMaster()) { + fillTanks = regenTank.isFull(); + regenTank = null; + } + + for (BlockCoord bc : multiblock) { + TileReservoir res = getReservoir(bc); + if (res != null) { + res.setMultiblock(null); + if (fillTanks) { + res.tank.fill(WATER_BUCKET, true); + } else { + res.tank.drain(BUCKET_VOLUME, true); + } + } + } + multiblock = null; + tankDirty = true; + } + + private boolean isCurrentMultiblockValid() { + if (multiblock == null) { + return false; + } + for (BlockCoord bc : multiblock) { + TileReservoir res = getReservoir(bc); + if (res == null || !res.isMultiblock()) { + return false; + } + } + return true; + } + + private boolean formMultiblock() { + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (isNonMultiReservoir(dir)) { + ForgeDirection[] cans = candidates(dir); + for (ForgeDirection neighbor : cans) { + if (isNonMultiReservoir(neighbor)) { + if (isNonMultiReservoir(dir.offsetX + neighbor.offsetX, dir.offsetY + neighbor.offsetY, dir.offsetZ + neighbor.offsetZ)) { + BlockCoord[] mb = new BlockCoord[4]; + mb[0] = inDirection(dir); + mb[1] = inDirection(neighbor); + mb[2] = inDirection(dir.offsetX + neighbor.offsetX, dir.offsetY + neighbor.offsetY, dir.offsetZ + neighbor.offsetZ); + mb[3] = new BlockCoord(xCoord, yCoord, zCoord); + for (BlockCoord bc : mb) { + TileReservoir res = getReservoir(bc); + res.setMultiblock(mb); + } + return true; + } + } + } + } + } + return false; + } + + private BlockCoord inDirection(int offsetX, int offsetY, int offsetZ) { + return new BlockCoord(xCoord + offsetX, yCoord + offsetY, zCoord + offsetZ); + } + + private BlockCoord inDirection(ForgeDirection dir) { + return inDirection(dir.offsetX, dir.offsetY, dir.offsetZ); + } + + private IFluidHandler getTankContainer(BlockCoord bc) { + return getTankContainer(bc.x, bc.y, bc.z); + } + + private IFluidHandler getTankContainer(int x, int y, int z) { + if(worldObj == null) { + return null; + } + TileEntity te = worldObj.getBlockTileEntity(x, y, z); + if (te instanceof IFluidHandler) { + return (IFluidHandler) te; + } + return null; + } + + private TileReservoir getReservoir(BlockCoord bc) { + return getReservoir(bc.x, bc.y, bc.z); + } + + private TileReservoir getReservoir(int x, int y, int z) { + TileEntity te = worldObj.getBlockTileEntity(x, y, z); + if (te instanceof TileReservoir) { + return (TileReservoir) te; + } + return null; + } + + private boolean isNonMultiReservoir(int offsetX, int offsetY, int offsetZ) { + TileReservoir res = getReservoir(xCoord + offsetX, yCoord + offsetY, zCoord + offsetZ); + if (res == null) { + return false; + } + return !res.isMultiblock(); + } + + private boolean isNonMultiReservoir(ForgeDirection dir) { + return isNonMultiReservoir(dir.offsetX, dir.offsetY, dir.offsetZ); + } + + private ForgeDirection[] candidates(ForgeDirection matchDir) { + ForgeDirection[] res = new ForgeDirection[4]; + res[0] = matchDir.getRotation(matchDir.offsetY == 0 ? ForgeDirection.UP : ForgeDirection.NORTH); + res[1] = res[0].getOpposite(); + res[2] = matchDir.getRotation(matchDir.offsetX == 0 ? ForgeDirection.EAST : ForgeDirection.NORTH); + res[3] = res[2].getOpposite(); + return res; + } + +} diff --git a/common/crazypants/enderio/machine/solor/BlockSolarPanel.java b/common/crazypants/enderio/machine/solor/BlockSolarPanel.java new file mode 100644 index 00000000..8120a170 --- /dev/null +++ b/common/crazypants/enderio/machine/solor/BlockSolarPanel.java @@ -0,0 +1,105 @@ +package crazypants.enderio.machine.solor; + +import java.util.List; + +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import crazypants.enderio.EnderIOTab; +import crazypants.enderio.ModObject; +import crazypants.enderio.enderface.BlockEnderIO; +import crazypants.enderio.enderface.TileEnderIO; +import crazypants.enderio.machine.AbstractMachineBlock; +import net.minecraft.block.Block; +import net.minecraft.block.ITileEntityProvider; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.Entity; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.Icon; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; + +public class BlockSolarPanel extends Block implements ITileEntityProvider { + + public static BlockSolarPanel create() { + BlockSolarPanel result = new BlockSolarPanel(); + result.init(); + return result; + } + + private static final float BLOCK_HEIGHT = 0.15f; + + Icon sideIcon; + + private BlockSolarPanel() { + super(ModObject.blockSolarPanel.id, Material.ground); + setHardness(0.5F); + setStepSound(Block.soundStoneFootstep); + setUnlocalizedName(ModObject.blockSolarPanel.unlocalisedName); + setCreativeTab(EnderIOTab.tabEnderIO); + setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, BLOCK_HEIGHT, 1.0F); + } + + private void init() { + LanguageRegistry.addName(this, ModObject.blockSolarPanel.name); + GameRegistry.registerBlock(this, ModObject.blockSolarPanel.unlocalisedName); + GameRegistry.registerTileEntity(TileEntitySolorPanel.class, ModObject.blockSolarPanel.unlocalisedName + "TileEntity"); + } + + @Override + public boolean renderAsNormalBlock() { + return false; + } + + @Override + public boolean isOpaqueCube() { + return false; + } + + @Override + public TileEntity createNewTileEntity(World world) { + return new TileEntitySolorPanel(); + } + + public Icon getIcon(int side, int meta) { + if(side == ForgeDirection.UP.ordinal()) { + return blockIcon; + } + return sideIcon; + } + + @Override + public void onNeighborBlockChange(World world, int x, int y, int z, int par5) { + TileEntity te = world.getBlockTileEntity(x, y, z); + if(te instanceof TileEntitySolorPanel) { + ((TileEntitySolorPanel)te).onNeighborBlockChange(); + } + } + + @Override + public void registerIcons(IconRegister iconRegister) { + blockIcon = iconRegister.registerIcon("enderio:solarPanelTop"); + sideIcon = iconRegister.registerIcon("enderio:solarPanelSide"); + } + + @Override + public void setBlockBoundsBasedOnState(IBlockAccess par1IBlockAccess, int par2, int par3, int par4) { + setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, BLOCK_HEIGHT, 1.0F); + } + + @Override + public void setBlockBoundsForItemRender() { + setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, BLOCK_HEIGHT, 1.0F); + } + + @Override + public void addCollisionBoxesToList(World par1World, int par2, int par3, int par4, AxisAlignedBB par5AxisAlignedBB, List par6List, Entity par7Entity) { + setBlockBoundsBasedOnState(par1World, par2, par3, par4); + super.addCollisionBoxesToList(par1World, par2, par3, par4, par5AxisAlignedBB, par6List, par7Entity); + } + +} diff --git a/common/crazypants/enderio/machine/solor/TileEntitySolorPanel.java b/common/crazypants/enderio/machine/solor/TileEntitySolorPanel.java new file mode 100644 index 00000000..27a5a41d --- /dev/null +++ b/common/crazypants/enderio/machine/solor/TileEntitySolorPanel.java @@ -0,0 +1,188 @@ +package crazypants.enderio.machine.solor; + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + +import crazypants.enderio.power.BasicCapacitor; +import crazypants.enderio.power.IInternalPowerReceptor; +import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.util.BlockCoord; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.power.IPowerEmitter; +import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; + +public class TileEntitySolorPanel extends TileEntity implements IInternalPowerReceptor, IPowerEmitter { + + protected PowerHandler powerHandler; + private BasicCapacitor capacitor; + + private final List receptors = new ArrayList(); + private ListIterator receptorIterator = receptors.listIterator(); + private boolean receptorsDirty = true; + + private float energyPerTick = 1; + + public TileEntitySolorPanel() { + // TODO: + capacitor = new BasicCapacitor(); + powerHandler = PowerHandlerUtil.createHandler(capacitor, this, Type.ENGINE); + } + + @Override + public boolean canEmitPowerFrom(ForgeDirection side) { + return side == ForgeDirection.DOWN; + } + + @Override + public void doWork(PowerHandler workProvider) { + } + + @Override + public World getWorld() { + return worldObj; + } + + @Override + public PowerReceiver getPowerReceiver(ForgeDirection side) { + return powerHandler.getPowerReceiver(); + } + + public void onNeighborBlockChange() { + receptorsDirty = true; + } + + @Override + public void applyPerdition() { + } + + @Override + public PowerHandler getPowerHandler() { + return powerHandler; + } + + @Override + public void updateEntity() { + if (worldObj == null || worldObj.isRemote) { + return; + } + collectEnergy(); + transmitEnergy(); + } + + private void collectEnergy() { + if(!worldObj.canBlockSeeTheSky(xCoord, yCoord, zCoord)) { + return; + } + float fromSun = worldObj.getSunBrightness(1); + float collected = energyPerTick * fromSun; + powerHandler.setEnergy(Math.min(powerHandler.getMaxEnergyStored(), powerHandler.getEnergyStored() + collected)); + + } + + private boolean transmitEnergy() { + + if (powerHandler.getEnergyStored() <= 0) { + powerHandler.update(); + return false; + } + + // Mandatory power handler update + float stored = powerHandler.getEnergyStored(); + powerHandler.update(); + powerHandler.setEnergy(stored); + + float canTransmit = Math.min(powerHandler.getEnergyStored(), capacitor.getMaxEnergyExtracted()); + float transmitted = 0; + + checkReceptors(); + + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { + receptorIterator = receptors.listIterator(); + } + + int appliedCount = 0; + int numReceptors = receptors.size(); + while (receptorIterator.hasNext() && canTransmit > 0 && appliedCount < numReceptors) { + + Receptor receptor = receptorIterator.next(); + PowerReceiver pp = receptor.receptor.getPowerReceiver(receptor.fromDir); + if (pp != null && pp.getMinEnergyReceived() <= canTransmit && pp.getType() != Type.ENGINE) { + float used; + if (receptor.receptor instanceof IInternalPowerReceptor) { + used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) receptor.receptor, pp, canTransmit, Type.ENGINE, receptor.fromDir); + } else { + used = pp.receiveEnergy(Type.ENGINE, canTransmit, receptor.fromDir); + } + transmitted += used; + canTransmit -= used; + } + if (canTransmit <= 0) { + break; + } + + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { + receptorIterator = receptors.listIterator(); + } + appliedCount++; + } + + powerHandler.setEnergy(powerHandler.getEnergyStored() - transmitted); + + return transmitted > 0; + + } + + private void checkReceptors() { + if (!receptorsDirty) { + return; + } + receptors.clear(); + + BlockCoord bc = new BlockCoord(xCoord, yCoord, zCoord); + ForgeDirection dir = ForgeDirection.DOWN; + BlockCoord checkLoc = bc.getLocation(dir); + TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); + if (te instanceof IPowerReceptor) { + IPowerReceptor rec = (IPowerReceptor) te; + PowerReceiver reciever = rec.getPowerReceiver(dir.getOpposite()); + if(reciever != null) { + receptors.add(new Receptor((IPowerReceptor) te, dir.getOpposite())); + } + } + + //NB: This is to supports connections from any direction +// BlockCoord bc = new BlockCoord(xCoord, yCoord, zCoord); +// for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { +// BlockCoord checkLoc = bc.getLocation(dir); +// TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); +// if (te instanceof IPowerReceptor) { +// IPowerReceptor rec = (IPowerReceptor) te; +// PowerReceiver reciever = rec.getPowerReceiver(dir.getOpposite()); +// receptors.add(new Receptor((IPowerReceptor) te, dir.getOpposite())); +// } +// } + receptorIterator = receptors.listIterator(); + receptorsDirty = false; + + } + + static class Receptor { + IPowerReceptor receptor; + ForgeDirection fromDir; + + private Receptor(IPowerReceptor rec, ForgeDirection fromDir) { + super(); + this.receptor = rec; + this.fromDir = fromDir; + } + } + + +} diff --git a/common/crazypants/enderio/material/Alloy.java b/common/crazypants/enderio/material/Alloy.java new file mode 100644 index 00000000..17f9a6b8 --- /dev/null +++ b/common/crazypants/enderio/material/Alloy.java @@ -0,0 +1,28 @@ +package crazypants.enderio.material; + +import net.minecraft.block.Block; +import net.minecraft.item.*; + +//public static final String[] alloyNames = new String[] {"Activated Iron", "Activated Gold", "Ender Iron", "Ender Gold"}; + +public enum Alloy { + + ACTIVATED_IRON("Activated Iron", "activatedIron", new ItemStack(Item.ingotIron), new ItemStack(Item.redstone), new ItemStack(Item.glowstone)), + ACTIVATED_GOLD("Activated Gold", "activatedGold", new ItemStack(Item.ingotGold), new ItemStack(Item.redstone), new ItemStack(Item.glowstone)), + ENDER_IRON("Ender Iron", "enderIron", new ItemStack(Item.ingotIron), new ItemStack(Item.enderPearl), new ItemStack(Item.glowstone)), + ENDER_GOLD("Ender Gold", "enderGold", new ItemStack(Item.ingotGold), new ItemStack(Item.enderPearl), new ItemStack(Item.glowstone)), + BLUE_STEEL("Blue Steel", "blueSteel", new ItemStack(Item.ingotIron), new ItemStack(Item.dyePowder,1,4), new ItemStack(Block.obsidian)); + + public final String unlocalisedName; + public final String uiName; + public final String iconKey; + public final ItemStack[] ingrediants; + + private Alloy(String uiName, String iconKey, ItemStack... ingrediants) { + this.unlocalisedName = name(); + this.uiName = uiName; + this.iconKey = "enderio:" + iconKey; + this.ingrediants = ingrediants; + } + +} diff --git a/common/crazypants/enderio/material/BlockFusedQuartz.java b/common/crazypants/enderio/material/BlockFusedQuartz.java new file mode 100644 index 00000000..348dad71 --- /dev/null +++ b/common/crazypants/enderio/material/BlockFusedQuartz.java @@ -0,0 +1,146 @@ +package crazypants.enderio.material; + +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.EnderIO; +import crazypants.enderio.EnderIOTab; +import crazypants.enderio.ModObject; +import crazypants.enderio.enderface.BlockEnderIO; +import crazypants.enderio.enderface.ItemEnderface; +import crazypants.enderio.enderface.TileEnderIO; +import crazypants.enderio.machine.painter.PainterUtil; +import crazypants.enderio.machine.painter.TileEntityCustomBlock; +import net.minecraft.block.Block; +import net.minecraft.block.ITileEntityProvider; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChatMessageComponent; +import net.minecraft.util.Icon; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +public class BlockFusedQuartz extends Block implements ITileEntityProvider { + + public static int renderId; + + public static BlockFusedQuartz create() { + BlockFusedQuartz result = new BlockFusedQuartz(); + result.init(); + return result; + } + + Icon itemIcon; + + private BlockFusedQuartz() { + super(ModObject.blockFusedQuartz.id, Material.glass); + setHardness(0.5F); + setStepSound(Block.soundGlassFootstep); + setUnlocalizedName(ModObject.blockFusedQuartz.unlocalisedName); + setCreativeTab(EnderIOTab.tabEnderIO); + } + + private void init() { + LanguageRegistry.addName(this, ModObject.blockFusedQuartz.name); + GameRegistry.registerBlock(this, ModObject.blockFusedQuartz.unlocalisedName); + } + + @Override + public boolean renderAsNormalBlock() { + return false; + } + + @Override + public boolean isOpaqueCube() { + return false; + } + + @Override + public int getRenderType() { + return renderId; + } + + @Override + @SideOnly(Side.CLIENT) + public int getRenderBlockPass() { + return 1; + } + + @Override + public boolean canRenderInPass(int pass) { + FusedQuartzRenderer.renderPass = pass; + return true; + } + + @Override + public int getLightOpacity(World world, int x, int y, int z) { + return 0; + } + + public boolean shouldSideBeRendered(IBlockAccess par1IBlockAccess, int par2, int par3, int par4, int par5) { + int i1 = par1IBlockAccess.getBlockId(par2, par3, par4); + return i1 == this.blockID ? false : super.shouldSideBeRendered(par1IBlockAccess, par2, par3, par4, par5); + } + + @Override + public void registerIcons(IconRegister iconRegister) { + blockIcon = iconRegister.registerIcon("enderio:fusedQuartz"); + itemIcon = iconRegister.registerIcon("enderio:fusedQuartzItem"); + } + + @Override + public TileEntity createNewTileEntity(World world) { + return null; + } + + @Override + public TileEntity createTileEntity(World world, int metadata) { + return new TileEntityCustomBlock(); + } + + /** + * Remove the tile entity too. + */ + @Override + public void breakBlock(World world, int x, int y, int z, int par5, int par6) { + + if (!world.isRemote && world.getGameRules().getGameRuleBooleanValue("doTileDrops")) { + TileEntity te = world.getBlockTileEntity(x, y, z); + + if (te instanceof TileEntityCustomBlock) { + TileEntityCustomBlock tef = (TileEntityCustomBlock) te; + + ItemStack itemStack = createItemStackForSourceBlock(tef.getSourceBlockId(), tef.getSourceBlockMetadata()); + if (itemStack != null) { + float f = 0.7F; + double d0 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d1 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + EntityItem entityitem = new EntityItem(world, x + d0, y + d1, z + d2, itemStack); + entityitem.delayBeforeCanPickup = 10; + world.spawnEntityInWorld(entityitem); + } + } + + } + + super.breakBlock(world, x, y, z, par5, par6); + } + + private ItemStack createItemStackForSourceBlock(int sourceBlockId, int sourceBlockMetadata) { + if(sourceBlockId <= 0) { + return null; + } + ItemStack result = new ItemStack(ModObject.itemFusedQuartzFrame.actualId,1,0); + PainterUtil.setSourceBlock(result, sourceBlockId, sourceBlockMetadata); + return result; + } + +} diff --git a/common/crazypants/enderio/material/FusedQuartzFrameRenderer.java b/common/crazypants/enderio/material/FusedQuartzFrameRenderer.java new file mode 100644 index 00000000..66b8ed75 --- /dev/null +++ b/common/crazypants/enderio/material/FusedQuartzFrameRenderer.java @@ -0,0 +1,67 @@ +package crazypants.enderio.material; + +import org.lwjgl.opengl.GL11; + +import crazypants.enderio.EnderIO; +import crazypants.enderio.machine.painter.PainterUtil; + +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.item.ItemStack; +import net.minecraft.util.Icon; +import net.minecraftforge.client.IItemRenderer; +import net.minecraftforge.client.IItemRenderer.ItemRenderType; +import net.minecraftforge.client.IItemRenderer.ItemRendererHelper; +import net.minecraftforge.common.ForgeDirection; + +public class FusedQuartzFrameRenderer implements IItemRenderer { + + + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED_FIRST_PERSON; + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + RenderBlocks renderBlocks = (RenderBlocks) data[0]; + if (type == ItemRenderType.INVENTORY) { + renderToInventory(item, renderBlocks); + } else if (type == ItemRenderType.EQUIPPED) { + renderEquipped(item, renderBlocks); + } else if (type == ItemRenderType.ENTITY) { + renderEntity(item, renderBlocks); + } else if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + renderEntity(item, renderBlocks); + } + } + + private void renderEntity(ItemStack item, RenderBlocks renderBlocks) { + renderToInventory(item, renderBlocks); + } + + private void renderEquipped(ItemStack item, RenderBlocks renderBlocks) { + renderToInventory(item, renderBlocks); + } + + private void renderToInventory(ItemStack item, RenderBlocks renderBlocks) { + renderFrame(item); + } + + private void renderFrame(ItemStack item) { + GL11.glDisable(GL11.GL_LIGHTING); + FusedQuartzRenderer r = new FusedQuartzRenderer(); + r.renderFrameItem(item); + GL11.glEnable(GL11.GL_LIGHTING); + } + + + +} diff --git a/common/crazypants/enderio/material/FusedQuartzRenderer.java b/common/crazypants/enderio/material/FusedQuartzRenderer.java new file mode 100644 index 00000000..eefc7975 --- /dev/null +++ b/common/crazypants/enderio/material/FusedQuartzRenderer.java @@ -0,0 +1,268 @@ +package crazypants.enderio.material; + +import static net.minecraftforge.common.ForgeDirection.DOWN; +import static net.minecraftforge.common.ForgeDirection.EAST; +import static net.minecraftforge.common.ForgeDirection.NORTH; +import static net.minecraftforge.common.ForgeDirection.SOUTH; +import static net.minecraftforge.common.ForgeDirection.UP; +import static net.minecraftforge.common.ForgeDirection.WEST; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.IBlockAccess; +import net.minecraftforge.common.ForgeDirection; +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; +import crazypants.enderio.EnderIO; +import crazypants.enderio.machine.painter.PainterUtil; +import crazypants.enderio.machine.painter.TileEntityCustomBlock; +import crazypants.render.RenderUtil; +import crazypants.util.BlockCoord; +import crazypants.util.ForgeDirectionOffsets; +import crazypants.vecmath.VecmathUtil; +import crazypants.vecmath.Vector2d; +import crazypants.vecmath.Vector3d; +import crazypants.vecmath.Vector4d; + +public class FusedQuartzRenderer implements ISimpleBlockRenderingHandler { + + static int renderPass; + + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { + renderer.setOverrideBlockTexture(EnderIO.blockFusedQuartz.itemIcon); + renderer.renderBlockAsItem(Block.glass, 0, 1); + renderer.clearOverrideBlockTexture(); + } + + @Override + public boolean shouldRender3DInInventory() { + return true; + } + + @Override + public int getRenderId() { + return BlockFusedQuartz.renderId; + } + + @Override + public boolean renderWorldBlock(IBlockAccess blockAccess, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { + if (renderPass == 0) { + + RenderUtil.setTesselatorBrightness(blockAccess, x, y, z); + TileEntityCustomBlock tecb = null; + TileEntity te = blockAccess.getBlockTileEntity(x, y, z); + if(te instanceof TileEntityCustomBlock) { + tecb = (TileEntityCustomBlock)te; + } + + renderFrame(blockAccess, x, y, z, tecb, false); + + } else { + renderer.renderStandardBlock(block, x, y, z); + } + return true; + } + + public void renderFrameItem(ItemStack stack) { + RenderUtil.bindBlockTexture(); + Tessellator.instance.startDrawingQuads(); + TileEntityCustomBlock tecb = new TileEntityCustomBlock(); + tecb.setSourceBlockId(PainterUtil.getSourceBlockId(stack)); + tecb.setSourceBlockMetadata(PainterUtil.getSourceBlockMetadata(stack)); + renderFrame(null,0,0,0,tecb,true); + Tessellator.instance.draw(); + + } + + private void renderFrame(IBlockAccess blockAccess, int x, int y, int z, TileEntityCustomBlock tecb, boolean forceAllEdges) { + Icon texture = EnderIO.blockFusedQuartz.itemIcon; + + for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) { + + if(tecb != null && tecb.getSourceBlockId() > 0) { + texture = tecb.getSourceBlock().getIcon(face.ordinal(), tecb.getSourceBlockMetadata()); + } + renderFrame(blockAccess, x, y, z, tecb, face, texture, forceAllEdges); + } + } + + private void renderFrame(IBlockAccess blockAccess, int x, int y, int z, TileEntityCustomBlock tecb, ForgeDirection face, Icon texture, boolean forceAllEdges) { + + if (!forceAllEdges && !EnderIO.blockFusedQuartz.shouldSideBeRendered(blockAccess, x + face.offsetX, y + face.offsetY, z + face.offsetZ, + face.ordinal())) { + return; + } + + BlockCoord bc = new BlockCoord(x, y, z); + + List edges = new ArrayList(4); + if (face.offsetY != 0) { + edges.add(new Edge(bc, EAST)); + edges.add(new Edge(bc, WEST)); + edges.add(new Edge(bc, NORTH)); + edges.add(new Edge(bc, SOUTH)); + } else if (face.offsetX != 0) { + edges.add(new Edge(bc, DOWN)); + edges.add(new Edge(bc, UP)); + edges.add(new Edge(bc, SOUTH)); + edges.add(new Edge(bc, NORTH)); + } else { + edges.add(new Edge(bc, UP)); + edges.add(new Edge(bc, DOWN)); + edges.add(new Edge(bc, WEST)); + edges.add(new Edge(bc, EAST)); + } + + Tessellator tes = Tessellator.instance; + float cm = RenderUtil.getColorMultiplierForFace(face); + tes.setColorOpaque_F(cm, cm, cm); + + Vector2d uv = new Vector2d(); + int index = 0; + boolean invertWinding; + for (Edge edge : edges) { + + if (forceAllEdges || blockAccess.getBlockId(edge.bc.x, edge.bc.y, edge.bc.z) != EnderIO.blockFusedQuartz.blockID) { + + invertWinding = ForgeDirectionOffsets.isPositiveOffset(face); + + Vector3d edgeCenter = new Vector3d(x + 0.5, y + 0.5, z + 0.5); + edgeCenter.add(ForgeDirectionOffsets.offsetScaled(edge.dir, 0.5)); + edgeCenter.add(ForgeDirectionOffsets.offsetScaled(face, 0.5)); + + Vector3d edgeUp = new Vector3d(); + edgeUp.x = face.offsetX == 0 && edge.dir.offsetX == 0 ? 0.5 : 0; + edgeUp.y = face.offsetY == 0 && edge.dir.offsetY == 0 ? 0.5 : 0; + edgeUp.z = face.offsetZ == 0 && edge.dir.offsetZ == 0 ? 0.5 : 0; + + Vector3d in = ForgeDirectionOffsets.offsetScaled(edge.dir, -1 / 16d); + Vector3d corner = new Vector3d(); + if ((invertWinding && index % 2 == 0) || (!invertWinding && index % 2 != 0)) { + + corner.set(edgeCenter); + corner.add(edgeUp); + getUvForCorner(uv, corner,x,y,z,face,texture); + tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); + + corner.set(edgeCenter); + corner.sub(edgeUp); + getUvForCorner(uv, corner,x,y,z,face,texture); + tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); + + corner.set(edgeCenter); + corner.sub(edgeUp); + corner.add(in); + getUvForCorner(uv, corner,x,y,z,face,texture); + tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); + + corner.set(edgeCenter); + corner.add(edgeUp); + corner.add(in); + getUvForCorner(uv, corner,x,y,z,face,texture); + tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); + + } else { //reverse winding + + corner.set(edgeCenter); + corner.add(edgeUp); + corner.add(in); + getUvForCorner(uv, corner,x,y,z,face,texture); + tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); + + corner.set(edgeCenter); + corner.sub(edgeUp); + corner.add(in); + getUvForCorner(uv, corner,x,y,z,face,texture); + tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); + + corner.set(edgeCenter); + corner.sub(edgeUp); + getUvForCorner(uv, corner,x,y,z,face,texture); + tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); + + corner.set(edgeCenter); + corner.add(edgeUp); + getUvForCorner(uv, corner,x,y,z,face,texture); + tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); + } + + } + index++; + } + } + + + private void getUvForCorner(Vector2d uv, Vector3d corner, int x, int y, int z, ForgeDirection face, Icon icon) { + Vector3d p = new Vector3d(corner); + p.x -= x; + p.y -= y; + p.z -= z; + + float uWidth = icon.getMaxU() - icon.getMinU(); + float vWidth = icon.getMaxV() - icon.getMinV(); + + uv.x = VecmathUtil.distanceFromPointToPlane(getUPlaneForFace(face), p); + uv.y = VecmathUtil.distanceFromPointToPlane(getVPlaneForFace(face), p); + + uv.x = icon.getMinU() + (uv.x * uWidth); + uv.y = icon.getMinV() + (uv.y * vWidth); + + } + + private 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; + } + + private 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; + } + + + private static class Edge { + final ForgeDirection dir; + final BlockCoord bc; + + public Edge(BlockCoord bc, ForgeDirection dir) { + this.dir = dir; + this.bc = bc.getLocation(dir); + } + + } + +} diff --git a/common/crazypants/enderio/material/ItemAlloy.java b/common/crazypants/enderio/material/ItemAlloy.java new file mode 100644 index 00000000..5065b6f6 --- /dev/null +++ b/common/crazypants/enderio/material/ItemAlloy.java @@ -0,0 +1,80 @@ +package crazypants.enderio.material; + +import java.util.List; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.*; +import net.minecraft.util.*; +import cpw.mods.fml.common.registry.*; +import crazypants.enderio.*; + +public class ItemAlloy extends Item { + + private final Icon[] icons; + + public static ItemAlloy create() { + ItemAlloy alloy = new ItemAlloy(); + alloy.init(); + return alloy; + } + + private ItemAlloy() { + super(ModObject.itemAlloy.id); + setHasSubtypes(true); + setMaxDamage(0); + setCreativeTab(EnderIOTab.tabEnderIO); + setUnlocalizedName(ModObject.itemAlloy.unlocalisedName); + + + icons = new Icon[Alloy.values().length * 2]; + } + + private void init() { + LanguageRegistry.addName(this, ModObject.itemAlloy.name); + GameRegistry.registerItem(this, ModObject.itemAlloy.unlocalisedName); + for (int i = 0; i < Alloy.values().length; i++) { + LanguageRegistry.instance().addStringLocalization(getUnlocalizedName() + "." + Alloy.values()[i].unlocalisedName + ".name", Alloy.values()[i].uiName); + } + for (int i = 0; i < Alloy.values().length; i++) { + LanguageRegistry.instance().addStringLocalization(getUnlocalizedName() + "." + Alloy.values()[i].unlocalisedName + "Nugget" + ".name", Alloy.values()[i].uiName + " Nugget"); + } + } + + @Override + public Icon getIconFromDamage(int damage) { + damage = MathHelper.clamp_int(damage, 0, Alloy.values().length * 2); + return icons[damage]; + } + + @Override + public void registerIcons(IconRegister iconRegister) { + int numAlloys = Alloy.values().length; + for (int i = 0; i < numAlloys ; i++) { + icons[i] = iconRegister.registerIcon(Alloy.values()[i].iconKey); + } + for (int i = 0; i < numAlloys ; i++) { + icons[i + numAlloys] = iconRegister.registerIcon(Alloy.values()[i].iconKey + "Nugget"); + } + } + + + @Override + public String getUnlocalizedName(ItemStack par1ItemStack) { + int i = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, Alloy.values().length * 2); + if(i < Alloy.values().length) { + return super.getUnlocalizedName() + "." + Alloy.values()[i].unlocalisedName; + } else { + return super.getUnlocalizedName() + "." + Alloy.values()[i - Alloy.values().length].unlocalisedName + "Nugget"; + } + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List) { + for (int j = 0; j < Alloy.values().length * 2; ++j) { + par3List.add(new ItemStack(par1, 1, j)); + } + } + +} diff --git a/common/crazypants/enderio/material/ItemCapacitor.java b/common/crazypants/enderio/material/ItemCapacitor.java new file mode 100644 index 00000000..2fcf9b57 --- /dev/null +++ b/common/crazypants/enderio/material/ItemCapacitor.java @@ -0,0 +1,43 @@ +package crazypants.enderio.material; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.item.Item; +import cpw.mods.fml.common.registry.*; +import cpw.mods.fml.relauncher.*; +import crazypants.enderio.*; +import crazypants.enderio.power.*; + +public class ItemCapacitor extends Item implements ICapacitorItem { + + private static final BasicCapacitor CAP = new BasicCapacitor(); + + public static ItemCapacitor create() { + ItemCapacitor result = new ItemCapacitor(); + result.init(); + return result; + } + + protected ItemCapacitor() { + super(ModObject.itemBasicCapacitor.id); + setCreativeTab(EnderIOTab.tabEnderIO); + setUnlocalizedName(ModObject.itemBasicCapacitor.unlocalisedName); + setMaxStackSize(64); + } + + protected void init() { + LanguageRegistry.addName(this, ModObject.itemBasicCapacitor.name); + GameRegistry.registerItem(this, ModObject.itemBasicCapacitor.unlocalisedName); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister iconRegister) { + itemIcon = iconRegister.registerIcon("enderio:basicCapacitor"); + } + + @Override + public ICapacitor getCapacitor() { + return CAP; + } + +} diff --git a/common/crazypants/enderio/material/ItemFusedQuartzFrame.java b/common/crazypants/enderio/material/ItemFusedQuartzFrame.java new file mode 100644 index 00000000..edf95f62 --- /dev/null +++ b/common/crazypants/enderio/material/ItemFusedQuartzFrame.java @@ -0,0 +1,91 @@ +package crazypants.enderio.material; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.Icon; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.EnderIO; +import crazypants.enderio.EnderIOTab; +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.conduit.facade.ItemConduitFacade; +import crazypants.enderio.machine.MachineRecipeRegistry; +import crazypants.enderio.machine.painter.BasicPainterTemplate; +import crazypants.enderio.machine.painter.PainterUtil; +import crazypants.enderio.machine.painter.TileEntityCustomBlock; +import crazypants.enderio.machine.painter.BlockCustomWall.PainterTemplate; + +public class ItemFusedQuartzFrame extends Item { + + public static ItemFusedQuartzFrame create() { + ItemFusedQuartzFrame result = new ItemFusedQuartzFrame(); + result.init(); + return result; + } + + protected ItemFusedQuartzFrame() { + super(ModObject.itemFusedQuartzFrame.id); + setCreativeTab(EnderIOTab.tabEnderIO); + setUnlocalizedName(ModObject.itemFusedQuartzFrame.unlocalisedName); + setMaxStackSize(64); + } + + protected void init() { + LanguageRegistry.addName(this, ModObject.itemFusedQuartzFrame.name); + GameRegistry.registerItem(this, ModObject.itemFusedQuartzFrame.unlocalisedName); + MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPainter.unlocalisedName, new FramePainterRecipe()); + } + + @Override + public void registerIcons(IconRegister iconRegister) { + itemIcon = iconRegister.registerIcon("enderio:fusedQuartzFrame"); + } + + + @Override + public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float par8, + float par9, float par10) { + + if(world.getBlockId(x, y, z) == ModObject.blockFusedQuartz.actualId) { + TileEntityCustomBlock tecb = (TileEntityCustomBlock)world.getBlockTileEntity(x, y, z); + if(tecb == null) { + return false; + } + //if(!world.isRemote) { + tecb.setSourceBlockId(PainterUtil.getSourceBlockId(itemStack)); + tecb.setSourceBlockMetadata(PainterUtil.getSourceBlockMetadata(itemStack)); + world.markBlockForUpdate(x, y, z); + world.markBlockForRenderUpdate(x, y, z); + //} + if(!world.isRemote) { + if (!player.capabilities.isCreativeMode) { + itemStack.stackSize--; + } + } + return true; + } else { + return false; + } + } + + @Override + @SideOnly(Side.CLIENT) + public boolean isFull3D() { + return true; + } + + public static final class FramePainterRecipe extends BasicPainterTemplate { + + public FramePainterRecipe() { + super(ModObject.itemFusedQuartzFrame.actualId); + } + + } +} diff --git a/common/crazypants/enderio/material/ItemIndustrialBinder.java b/common/crazypants/enderio/material/ItemIndustrialBinder.java new file mode 100644 index 00000000..653af419 --- /dev/null +++ b/common/crazypants/enderio/material/ItemIndustrialBinder.java @@ -0,0 +1,37 @@ +package crazypants.enderio.material; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.item.Item; +import cpw.mods.fml.common.registry.*; +import cpw.mods.fml.relauncher.*; +import crazypants.enderio.*; + +public class ItemIndustrialBinder extends Item { + + + public static ItemIndustrialBinder create() { + ItemIndustrialBinder result = new ItemIndustrialBinder(); + result.init(); + return result; + } + + protected ItemIndustrialBinder() { + super(ModObject.itemIndustrialBinder.id); + setCreativeTab(EnderIOTab.tabEnderIO); + setUnlocalizedName(ModObject.itemIndustrialBinder.unlocalisedName); + setMaxStackSize(64); + } + + protected void init() { + LanguageRegistry.addName(this, ModObject.itemIndustrialBinder.name); + GameRegistry.registerItem(this, ModObject.itemIndustrialBinder.unlocalisedName); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister iconRegister) { + itemIcon = iconRegister.registerIcon("enderio:industrialBinder"); + } + + +} diff --git a/common/crazypants/enderio/material/ItemYetaWrench.java b/common/crazypants/enderio/material/ItemYetaWrench.java new file mode 100644 index 00000000..6a4a1ee1 --- /dev/null +++ b/common/crazypants/enderio/material/ItemYetaWrench.java @@ -0,0 +1,72 @@ +package crazypants.enderio.material; + +import net.minecraft.block.Block; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.tools.IToolWrench; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.EnderIOTab; +import crazypants.enderio.ModObject; + +public class ItemYetaWrench extends Item implements IToolWrench { + + + public static ItemYetaWrench create() { + ItemYetaWrench result = new ItemYetaWrench(); + result.init(); + return result; + } + + protected ItemYetaWrench() { + super(ModObject.itemYetaWrench.id); + setCreativeTab(EnderIOTab.tabEnderIO); + setUnlocalizedName(ModObject.itemYetaWrench.unlocalisedName); + setMaxStackSize(1); + } + + protected void init() { + LanguageRegistry.addName(this, ModObject.itemYetaWrench.name); + GameRegistry.registerItem(this, ModObject.itemYetaWrench.unlocalisedName); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister iconRegister) { + itemIcon = iconRegister.registerIcon("enderio:yetaWrench"); + } + + @Override + public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { + int blockId = world.getBlockId(x, y, z); + Block block = Block.blocksList[blockId]; + if (block != null && block.rotateBlock(world, x, y, z, ForgeDirection.getOrientation(side))) { + player.swingItem(); + return !world.isRemote; + } + return false; + } + + @Override + public boolean canWrench(EntityPlayer player, int x, int y, int z) { + return true; + } + + @Override + public void wrenchUsed(EntityPlayer player, int x, int y, int z) { + player.swingItem(); + } + + @Override + public boolean shouldPassSneakingClickToBlock(World par2World, int par4, int par5, int par6) { + return true; + } + + +} diff --git a/common/crazypants/enderio/material/MaterialRecipes.java b/common/crazypants/enderio/material/MaterialRecipes.java new file mode 100644 index 00000000..76e88fde --- /dev/null +++ b/common/crazypants/enderio/material/MaterialRecipes.java @@ -0,0 +1,43 @@ +package crazypants.enderio.material; + +import static crazypants.enderio.ModObject.*; +import net.minecraft.block.Block; +import net.minecraft.item.*; +import cpw.mods.fml.common.registry.GameRegistry; +import crazypants.enderio.ModObject; +import crazypants.enderio.machine.*; +import crazypants.enderio.machine.alloy.BasicAlloyRecipe; + +public class MaterialRecipes { + + public static void addRecipes() { + + ItemStack industialBinder = new ItemStack(itemIndustrialBinder.actualId, 8, 0); + GameRegistry.addSmelting(Block.gravel.blockID, industialBinder, 0); + + industialBinder = new ItemStack(itemIndustrialBinder.actualId, 1, 0); + ItemStack basicCapacitor = new ItemStack(itemBasicCapacitor.actualId, 1, 0); + GameRegistry.addShapedRecipe(basicCapacitor, " ", "gwi", "RbR", 'b', industialBinder, 'g', new ItemStack(Item.ingotGold), 'i', new ItemStack( + Item.ingotIron), 'R', new ItemStack(Item.redstoneRepeater), 'w', Block.cloth); + + int meta = 0; + for(Alloy alloy : Alloy.values()) { + ItemStack ingot = new ItemStack(ModObject.itemAlloy.actualId, 1, meta); + ItemStack nugget = new ItemStack(ModObject.itemAlloy.actualId, 9, meta + Alloy.values().length); + IMachineRecipe recipe = new BasicAlloyRecipe(ingot, alloy.unlocalisedName, alloy.ingrediants); + GameRegistry.addShapelessRecipe(nugget, ingot); + MachineRecipeRegistry.instance.registerRecipe(ModObject.blockAlloySmelter.unlocalisedName, recipe); + meta++; + } + + ItemStack fusedQuartz = new ItemStack(ModObject.blockFusedQuartz.actualId, 1, 0); + IMachineRecipe recipe = new BasicAlloyRecipe(fusedQuartz, ModObject.blockFusedQuartz.unlocalisedName, new ItemStack(Item.netherQuartz,4,0)); + MachineRecipeRegistry.instance.registerRecipe(ModObject.blockAlloySmelter.unlocalisedName, recipe); + + ItemStack fusedQuartzFrame = new ItemStack(ModObject.itemFusedQuartzFrame.actualId,1,0); + + GameRegistry.addShapedRecipe(fusedQuartzFrame, "bsb", "s s", "bsb", 'b', industialBinder, 's', new ItemStack(Item.stick)); + + } + +} diff --git a/common/crazypants/enderio/power/BasicCapacitor.java b/common/crazypants/enderio/power/BasicCapacitor.java new file mode 100644 index 00000000..2e343d9a --- /dev/null +++ b/common/crazypants/enderio/power/BasicCapacitor.java @@ -0,0 +1,94 @@ +package crazypants.enderio.power; + +public class BasicCapacitor implements ICapacitor { + + private int minEnergyReceived = 0; + private int maxEnergyReceived = 2; + private int maxEnergyStored = 5000; + private int minActivationEnergy = 0; + + private int powerLoss = 1; + private int powerLossRegularity = 200; + + private int maxEnergyExtracted = 2; + + public BasicCapacitor() { + } + + public BasicCapacitor(int minEnergyReceived, int maxEnergyReceived, int maxEnergyStored, int minActivationEnergy, int powerLoss, int powerLossRegularity, + int maxEnergyExtracted) { + configure(minEnergyReceived, maxEnergyReceived, maxEnergyStored, minActivationEnergy, powerLoss, powerLossRegularity, maxEnergyExtracted); + } + + protected void configure(int minEnergyReceived, int maxEnergyReceived, int maxEnergyStored, int minActivationEnergy, int powerLoss, int powerLossRegularity, + int maxEnergyExtracted) { + this.minEnergyReceived = minEnergyReceived; + this.maxEnergyReceived = maxEnergyReceived; + this.maxEnergyStored = maxEnergyStored; + this.minActivationEnergy = minActivationEnergy; + this.powerLoss = powerLoss; + this.powerLossRegularity = powerLossRegularity; + this.maxEnergyExtracted = maxEnergyExtracted; + + } + + @Override + public int getMinEnergyReceived() { + return minEnergyReceived; + } + + protected void setMinEnergyReceived(int minEnergyReceived) { + this.minEnergyReceived = minEnergyReceived; + } + + @Override + public int getMaxEnergyReceived() { + return maxEnergyReceived; + } + + protected void setMaxEnergyReceived(int maxEnergyReceived) { + this.maxEnergyReceived = maxEnergyReceived; + } + + @Override + public int getMaxEnergyStored() { + return maxEnergyStored; + } + + protected void setMaxEnergyStored(int maxEnergyStored) { + this.maxEnergyStored = maxEnergyStored; + } + + @Override + public int getMinActivationEnergy() { + return minActivationEnergy; + } + + protected void setMinActivationEnergy(int minActivationEnergy) { + this.minActivationEnergy = minActivationEnergy; + } + + @Override + public int getPowerLoss() { + return powerLoss; + } + + protected void setPowerLoss(int powerLoss) { + this.powerLoss = powerLoss; + } + + @Override + public int getPowerLossRegularity() { + return powerLossRegularity; + } + + protected void setPowerLossRegularity(int powerLossRegularity) { + this.powerLossRegularity = powerLossRegularity; + } + + @Override + public int getMaxEnergyExtracted() { + return maxEnergyExtracted; + } + +} diff --git a/common/crazypants/enderio/power/ICapacitor.java b/common/crazypants/enderio/power/ICapacitor.java new file mode 100644 index 00000000..88c35a90 --- /dev/null +++ b/common/crazypants/enderio/power/ICapacitor.java @@ -0,0 +1,16 @@ +package crazypants.enderio.power; + +public interface ICapacitor { + + int getMinEnergyReceived(); + int getMaxEnergyReceived(); + + int getMaxEnergyStored(); + int getMinActivationEnergy(); + + int getPowerLoss(); + int getPowerLossRegularity(); + + int getMaxEnergyExtracted(); + +} diff --git a/common/crazypants/enderio/power/ICapacitorItem.java b/common/crazypants/enderio/power/ICapacitorItem.java new file mode 100644 index 00000000..33ff5916 --- /dev/null +++ b/common/crazypants/enderio/power/ICapacitorItem.java @@ -0,0 +1,7 @@ +package crazypants.enderio.power; + +public interface ICapacitorItem { + + ICapacitor getCapacitor(); + +} diff --git a/common/crazypants/enderio/power/IInternalPowerReceptor.java b/common/crazypants/enderio/power/IInternalPowerReceptor.java new file mode 100644 index 00000000..e1fa09d6 --- /dev/null +++ b/common/crazypants/enderio/power/IInternalPowerReceptor.java @@ -0,0 +1,12 @@ +package crazypants.enderio.power; + +import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler; + +public interface IInternalPowerReceptor extends IPowerReceptor { + + PowerHandler getPowerHandler(); + + void applyPerdition(); + +} diff --git a/common/crazypants/enderio/power/PowerHandlerUtil.java b/common/crazypants/enderio/power/PowerHandlerUtil.java new file mode 100644 index 00000000..60c9eac3 --- /dev/null +++ b/common/crazypants/enderio/power/PowerHandlerUtil.java @@ -0,0 +1,98 @@ +package crazypants.enderio.power; + +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.conduit.power.IPowerConduit; +import crazypants.enderio.conduit.power.NetworkPowerManager; +import crazypants.enderio.conduit.power.PowerConduitNetwork; +import net.minecraftforge.common.ForgeDirection; +import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler; +import buildcraft.api.power.PowerHandler.PerditionCalculator; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; + +public class PowerHandlerUtil { + + public static PowerHandler createHandler(ICapacitor capacitor, IPowerReceptor pr, Type type) { + PowerHandler ph = new PowerHandler(pr, type); + ph.configure(capacitor.getMinEnergyReceived(),capacitor.getMaxEnergyReceived(),capacitor.getMinActivationEnergy(),capacitor.getMaxEnergyStored()); + ph.configurePowerPerdition(0, 0); + ph.setPerdition(new NullPerditionCalculator()); + return ph; + } + + public static float transmitInternal(IInternalPowerReceptor receptor, PowerReceiver pp, float quantity, Type type, ForgeDirection from) { + float used = quantity; + + if(receptor instanceof IConduitBundle) { + return transferToPowerNetwork((IConduitBundle)receptor, pp, quantity); + } + + PowerHandler ph = receptor.getPowerHandler(); + if(ph == null) { + return 0; + } + + float maxEnergyStored = pp.getMaxEnergyStored(); + float maxEnergyRecieved = pp.getMaxEnergyReceived(); + float energyStored = pp.getEnergyStored(); + + //Do all required functions except: + //- We will handle perd'n ourselves and there is not need to drain excess from our engines as they are self regulating + //- Also not making use of the doWork calls. + pp.receiveEnergy(type, quantity, from); + + ph.setEnergy(energyStored); + + if (used < pp.getMinEnergyReceived()) { + return 0; + } + + if (used > maxEnergyRecieved) { + used = maxEnergyRecieved; + } + + energyStored += used; + + if (energyStored > maxEnergyStored) { + used -= energyStored - maxEnergyStored; + energyStored = maxEnergyStored; + } else if (energyStored < 0) { + used -= energyStored; + energyStored = 0; + } + + + ph.setEnergy(energyStored); + + receptor.applyPerdition(); + + return used; + + } + + public static float transferToPowerNetwork(IConduitBundle bundle, PowerReceiver pp, float quantity) { + IPowerConduit receptor = bundle.getConduit(IPowerConduit.class); + if(receptor.getNetwork() == null) { + return 0; + } + NetworkPowerManager network = ((PowerConduitNetwork)receptor.getNetwork()).getPowerManager(); + float used = network.addEnergy(quantity); + return used; + } + + private static class NullPerditionCalculator extends PerditionCalculator { + + public float applyPerdition(PowerHandler powerHandler, float current, long ticksPassed) { + if(current <= 0) { + return 0; + } + float res = current - 0.001f; + if(res >= current) { + System.out.println("PowerHandlerUtil.NullPerditionCalculator.applyPerdition: Fail! current is: " + current + " res is:" + res); + } + return res; + } + } + +} diff --git a/common/crazypants/render/BoundingBox.java b/common/crazypants/render/BoundingBox.java new file mode 100644 index 00000000..53803178 --- /dev/null +++ b/common/crazypants/render/BoundingBox.java @@ -0,0 +1,149 @@ +package crazypants.render; + +import crazypants.util.BlockCoord; +import crazypants.vecmath.Vector3d; + +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(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 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 isValid() { + return minX < maxX && minY < maxY && minZ < maxZ; + } + + 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 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)); + + } + + 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); + } + + @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); + } + + + + +} diff --git a/common/crazypants/render/CubeRenderer.java b/common/crazypants/render/CubeRenderer.java new file mode 100644 index 00000000..08c7c226 --- /dev/null +++ b/common/crazypants/render/CubeRenderer.java @@ -0,0 +1,183 @@ +package crazypants.render; + +import crazypants.vecmath.Vector3d; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.Icon; + +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(BoundingBox bb, Icon tex) { + render(bb, tex, null); + } + + public static void render(BoundingBox bb, Icon tex, VertexTransform xForm) { + render(bb, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), xForm); + } + + public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV) { + render(bb, minU,maxU,minV,maxV,null); + } + + public static void render(BoundingBox bb, float minU, float maxU, float minV, float maxV, VertexTransform xForm) { + setupVertices(bb, xForm); + + float tmp = minV; + minV = maxV; + maxV = tmp; + + Tessellator tessellator = Tessellator.instance; + + tessellator.setNormal(0, 0, -1); + + 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); + + 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); + + 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); + + 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); + 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); + 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, Icon[] faceTextures, VertexTransform xForm) { + setupVertices(bb, xForm); + float minU; + float maxU; + float minV; + float maxV; + Icon tex; + + Tessellator tessellator = Tessellator.instance; + + tessellator.setNormal(0, 0, -1); + tex = faceTextures[0]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + 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); + tex = faceTextures[1]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + 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); + tex = faceTextures[2]; + 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); + tex = faceTextures[3]; + 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); + tex = faceTextures[4]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + 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); + tex = faceTextures[5]; + minU = tex.getMinU(); + maxU = tex.getMaxU(); + minV = tex.getMinV(); + maxV = tex.getMaxV(); + addVecWithUV(verts[0], minU, minV); + addVecWithUV(verts[4], maxU, minV); + addVecWithUV(verts[7], maxU, maxV); + addVecWithUV(verts[3], minU, maxV); + } + + 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/common/crazypants/render/EmptySlot.java b/common/crazypants/render/EmptySlot.java new file mode 100644 index 00000000..45ee4855 --- /dev/null +++ b/common/crazypants/render/EmptySlot.java @@ -0,0 +1,43 @@ +package crazypants.render; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.util.ResourceLocation; + +import org.lwjgl.opengl.GL11; + + +class EmptySlot { + + 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 EmptySlot(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/common/crazypants/render/GuiContainerBase.java b/common/crazypants/render/GuiContainerBase.java new file mode 100644 index 00000000..1a80d691 --- /dev/null +++ b/common/crazypants/render/GuiContainerBase.java @@ -0,0 +1,60 @@ +package crazypants.render; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.lwjgl.opengl.GL11; + +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; + +public abstract class GuiContainerBase extends GuiContainer { + + private List toolTips = new ArrayList(); + + protected GuiContainerBase(Container par1Container) { + super(par1Container); + } + + protected void addToolTip(GuiToolTip toolTip) { + toolTips.add(toolTip); + } + + @Override + protected final void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + + drawForegroundImpl(mouseX, mouseY); + for (GuiToolTip toolTip : toolTips) { + toolTip.onTick(mouseX - guiLeft, mouseY - guiTop); + if (toolTip.shouldDraw()) { + drawTooltip(toolTip, mouseX - guiLeft, mouseY - guiTop); + } + } + } + + protected void drawForegroundImpl(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + } + + protected void drawTooltip(GuiToolTip toolTip, int mouseX, int mouseY) { + List list = toolTip.getToolTipText(); + if(mouseX > (xSize/2)) { + int maxWidth = 0; + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + String s = (String) iterator.next(); + int w = fontRenderer.getStringWidth(s); + if (w > maxWidth) { + maxWidth = w; + } + } + mouseX -= (maxWidth + 18); + } + drawHoveringText(list, mouseX, mouseY, fontRenderer); + } + +} diff --git a/common/crazypants/render/GuiToolTip.java b/common/crazypants/render/GuiToolTip.java new file mode 100644 index 00000000..dc489445 --- /dev/null +++ b/common/crazypants/render/GuiToolTip.java @@ -0,0 +1,74 @@ +package crazypants.render; + +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.List; + +public class GuiToolTip { + + private static final long DELAY = 500; + + protected Rectangle bounds; + + private long mouseOverStart; + + protected final List text; + + private int lastMouseX = -1; + + private int lastMouseY = -1; + + 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 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() { + updateText(); + if (mouseOverStart == 0) { + return false; + } + return System.currentTimeMillis() - mouseOverStart >= DELAY; + } + + protected void updateText() { + } + + public List getToolTipText() { + return text; + } + +} diff --git a/common/crazypants/render/IconButton.java b/common/crazypants/render/IconButton.java new file mode 100644 index 00000000..a9225b47 --- /dev/null +++ b/common/crazypants/render/IconButton.java @@ -0,0 +1,107 @@ +package crazypants.render; + +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.ItemStack; +import net.minecraft.util.Icon; +import net.minecraft.util.ResourceLocation; + +import org.lwjgl.opengl.GL11; + +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 Icon icon; + protected ResourceLocation texture; + + + public IconButton(FontRenderer fr, int id, int x, int y, Icon 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 Icon getIcon() { + return icon; + } + + public void setIcon(Icon 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 (drawButton) { + + RenderUtil.bindTexture("textures/gui/widgets.png"); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.field_82253_i = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + width + && par3 < this.yPosition + height; + int hoverState = this.getHoverState(this.field_82253_i); + + // 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_82253_i) { + l = 16777120; + } + + 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/common/crazypants/render/IconUtil.java b/common/crazypants/render/IconUtil.java new file mode 100644 index 00000000..c789a08d --- /dev/null +++ b/common/crazypants/render/IconUtil.java @@ -0,0 +1,39 @@ +package crazypants.render; + +import java.util.ArrayList; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraftforge.client.event.TextureStitchEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.ForgeSubscribe; + +public class IconUtil { + + public static interface IIconProvider { + + public void registerIcons(IconRegister register); + + /** 0 = terrain.png, 1 = items.png */ + public int getTextureType(); + } + + static { + MinecraftForge.EVENT_BUS.register(new IconUtil()); + } + + private static ArrayList iconProviders = new ArrayList(); + + public static void addIconProvider(IIconProvider registrar) { + iconProviders.add(registrar); + } + + @ForgeSubscribe + public void onIconLoad(TextureStitchEvent.Pre event) { + for (IIconProvider reg : iconProviders) { + if (reg.getTextureType() == event.map.textureType) { + reg.registerIcons(event.map); + } + } + } + +} diff --git a/common/crazypants/render/ItemButton.java b/common/crazypants/render/ItemButton.java new file mode 100644 index 00000000..e93f4dec --- /dev/null +++ b/common/crazypants/render/ItemButton.java @@ -0,0 +1,84 @@ +package crazypants.render; + +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.ItemStack; +import net.minecraft.util.ResourceLocation; + +import org.lwjgl.opengl.GL11; + + +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, int itemId) { + super(id, x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, ""); + this.fr = fr; + item = new ItemStack(itemId, 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 (drawButton) { + + RenderUtil.bindTexture("textures/gui/widgets.png"); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.field_82253_i = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + width + && par3 < this.yPosition + height; + int hoverState = this.getHoverState(this.field_82253_i); + + // 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_82253_i) { + 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/common/crazypants/render/RenderUtil.java b/common/crazypants/render/RenderUtil.java new file mode 100644 index 00000000..b487bcf2 --- /dev/null +++ b/common/crazypants/render/RenderUtil.java @@ -0,0 +1,124 @@ +package crazypants.render; + +import java.nio.FloatBuffer; + +import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.*; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.item.ItemStack; +import net.minecraft.util.MathHelper; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; + +import org.lwjgl.opengl.GL11; + +import crazypants.vecmath.Matrix4d; +import crazypants.vecmath.Vector3d; + + +public class RenderUtil { + + 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 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); + } + + public static TextureManager engine() { + return Minecraft.getMinecraft().renderEngine; + } + + public static final ResourceLocation BLOCK_TEX = TextureMap.field_110575_b; + public static final ResourceLocation ITEM_TEX = TextureMap.field_110576_c; + public static final ResourceLocation GLINT_TEX = new ResourceLocation("textures/misc/enchanted_item_glint.png"); + + public static void bindItemTexture(ItemStack stack) { + engine().func_110577_a(stack.getItemSpriteNumber() == 0 ? BLOCK_TEX : ITEM_TEX); + } + + public static void bindItemTexture() { + engine().func_110577_a(ITEM_TEX); + } + + public static void bindBlockTexture() { + engine().func_110577_a(BLOCK_TEX); + } + + public static void bindGlintTexture() { + engine().func_110577_a(BLOCK_TEX); + } + + public static void bindTexture(String string) { + engine().func_110577_a(new ResourceLocation(string)); + } + + public static void bindTexture(ResourceLocation tex) { + engine().func_110577_a(tex); + } + + public static FontRenderer fontRenderer() { + return Minecraft.getMinecraft().fontRenderer; + } + + public static float claculateTotalBrightnessForLocation(World worldObj, int xCoord, int yCoord, int zCoord) { + int i = worldObj.getLightBrightnessForSkyBlocks(xCoord, yCoord, zCoord, 0); + int j = i % 65536; + float fromSun = worldObj.getSunBrightness(1); + float fromLights = j / 255f; + int k = i / 65536; + float recievedPercent = worldObj.getLightBrightness(xCoord, yCoord, zCoord); + + float val = (fromSun + fromLights) * recievedPercent; + val = MathHelper.clamp_float(val, 0, 1); + return val; + } + + 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 = Block.blocksList[world.getBlockId(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; + } + +} diff --git a/common/crazypants/render/VertexRotation.java b/common/crazypants/render/VertexRotation.java new file mode 100644 index 00000000..3fa1d323 --- /dev/null +++ b/common/crazypants/render/VertexRotation.java @@ -0,0 +1,23 @@ +package crazypants.render; + +import crazypants.vecmath.Quat4d; +import crazypants.vecmath.Vector3d; + +public class VertexRotation implements VertexTransform { + + private final Vector3d center; + private final Quat4d quat; + + public VertexRotation(double angle, Vector3d axis, Vector3d center) { + this.center = center; + quat = Quat4d.makeRotate(angle, axis); + } + + @Override + public void apply(Vector3d vec) { + vec.sub(center); + quat.rotate(vec); + vec.add(center); + } + +} diff --git a/common/crazypants/render/VertexTransform.java b/common/crazypants/render/VertexTransform.java new file mode 100644 index 00000000..bdb848aa --- /dev/null +++ b/common/crazypants/render/VertexTransform.java @@ -0,0 +1,10 @@ +package crazypants.render; + +import crazypants.vecmath.Vector3d; + +public interface VertexTransform { + + public abstract void apply(Vector3d vec); + + +} diff --git a/common/crazypants/util/BlockCoord.java b/common/crazypants/util/BlockCoord.java new file mode 100644 index 00000000..d4c1f521 --- /dev/null +++ b/common/crazypants/util/BlockCoord.java @@ -0,0 +1,63 @@ +package crazypants.util; + +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.ForgeDirection; + +public final class BlockCoord { + + public final int x; + public final int y; + public final int z; + + public BlockCoord(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + public BlockCoord(TileEntity tile) { + this(tile.xCoord,tile.yCoord,tile.zCoord); + } + + public BlockCoord getLocation(ForgeDirection dir) { + return new BlockCoord(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + x; + result = prime * result + y; + result = prime * result + z; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BlockCoord other = (BlockCoord) obj; + if (x != other.x) + return false; + if (y != other.y) + return false; + if (z != other.z) + return false; + return true; + } + + @Override + public String toString() { + return "BlockCoord [x=" + x + ", y=" + y + ", z=" + z + "]"; + } + + public boolean equals(int xCoord, int yCoord, int zCoord) { + return x == xCoord && y == yCoord && z == zCoord; + } + +} diff --git a/common/crazypants/util/ForgeDirectionOffsets.java b/common/crazypants/util/ForgeDirectionOffsets.java new file mode 100644 index 00000000..b67800f7 --- /dev/null +++ b/common/crazypants/util/ForgeDirectionOffsets.java @@ -0,0 +1,37 @@ +package crazypants.util; + +import crazypants.vecmath.Vector3d; +import net.minecraftforge.common.ForgeDirection; + +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; + } + + private ForgeDirectionOffsets() { + } + + public static boolean isPositiveOffset(ForgeDirection dir) { + return dir == ForgeDirection.SOUTH || dir == ForgeDirection.EAST || dir == ForgeDirection.UP; + } + +} diff --git a/common/crazypants/util/MetadataUtil.java b/common/crazypants/util/MetadataUtil.java new file mode 100644 index 00000000..c90dc6e9 --- /dev/null +++ b/common/crazypants/util/MetadataUtil.java @@ -0,0 +1,44 @@ +package crazypants.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/common/crazypants/util/PacketUtil.java b/common/crazypants/util/PacketUtil.java new file mode 100644 index 00000000..023292ec --- /dev/null +++ b/common/crazypants/util/PacketUtil.java @@ -0,0 +1,139 @@ +package crazypants.util; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.packet.Packet; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import cpw.mods.fml.common.FMLCommonHandler; +import crazypants.enderio.EnderIO; + +public class PacketUtil { + + public static Packet createTileEntityPacket(String channel, int id, TileEntity te) { + + ByteArrayOutputStream bos = new ByteArrayOutputStream(140); + DataOutputStream dos = new DataOutputStream(bos); + try { + dos.writeInt(id); + dos.writeInt(te.xCoord); + dos.writeInt(te.yCoord); + dos.writeInt(te.zCoord); + NBTTagCompound root = new NBTTagCompound(); + te.writeToNBT(root); + writeNBTTagCompound(root, dos); + + } catch (IOException e) { + // never thrown + } + + Packet250CustomPayload pkt = new Packet250CustomPayload(); + pkt.channel = channel; + pkt.data = bos.toByteArray(); + pkt.length = bos.size(); + pkt.isChunkDataPacket = true; + return pkt; + + } + + public static TileEntity handleTileEntityPacket(boolean readId, DataInputStream dis) { + int x; + int y; + int z; + try { + if (readId) { + int id = dis.readInt(); + } + x = dis.readInt(); + y = dis.readInt(); + z = dis.readInt(); + } catch (IOException e) { + FMLCommonHandler.instance().raiseException(e, "PacketUtil.readTileEntityPacket", false); + return null; + } + NBTTagCompound tags = readNBTTagCompound(dis); + + World world = EnderIO.proxy.getClientWorld(); + if (world == null) { + FMLCommonHandler.instance().raiseException(new Exception("World was null"), "PacketUtil.readTileEntityPacket", true); + return null; + } + TileEntity te = world.getBlockTileEntity(x, y, z); + if (te == null) { + FMLCommonHandler.instance().raiseException(new Exception("TileEntity was null"), "PacketUtil.readTileEntityPacket", true); + return null; + } + te.readFromNBT(tags); + return te; + } + + public static ItemStack readItemStack(DataInputStream dataIn) throws IOException { + ItemStack var2 = null; + short itemID = dataIn.readShort(); + + if (itemID >= 0) { + byte stackSize = dataIn.readByte(); + short damage = dataIn.readShort(); + var2 = new ItemStack(itemID, stackSize, damage); + var2.stackTagCompound = readNBTTagCompound(dataIn); + } + + return var2; + } + + public static byte[] readByteArray(int length, DataInputStream dataIn) throws IOException { + + byte[] barray = new byte[length]; + dataIn.readFully(barray, 0, length); + return barray; + + } + + public static void writeItemStack(ItemStack spawnstack, DataOutputStream dataout) throws IOException { + if (spawnstack == null) { + dataout.writeShort(-1); + } else { + dataout.writeShort(spawnstack.itemID); + dataout.writeByte(spawnstack.stackSize); + dataout.writeShort(spawnstack.getItemDamage()); + writeNBTTagCompound(spawnstack.stackTagCompound, dataout); + } + } + + public static NBTTagCompound readNBTTagCompound(DataInputStream dataIn) { + try { + short var2 = dataIn.readShort(); + if (var2 < 0) { + return null; + } else { + byte[] var3 = readByteArray(var2, dataIn); + return CompressedStreamTools.decompress(var3); + } + } catch (IOException e) { + FMLCommonHandler.instance().raiseException(e, "Custom Packet", true); + return null; + } + } + + public static void writeNBTTagCompound(NBTTagCompound compound, DataOutputStream dataout) { + try { + if (compound == null) { + dataout.writeShort(-1); + } else { + byte[] var3 = CompressedStreamTools.compress(compound); + dataout.writeShort((short) var3.length); + dataout.write(var3); + } + } catch (IOException e) { + FMLCommonHandler.instance().raiseException(e, "PacketUtil.readTileEntityPacket.writeNBTTagCompound", true); + } + } + +} diff --git a/common/crazypants/util/Util.java b/common/crazypants/util/Util.java new file mode 100644 index 00000000..52be6dd8 --- /dev/null +++ b/common/crazypants/util/Util.java @@ -0,0 +1,49 @@ +package crazypants.util; + +import net.minecraft.block.Block; +import net.minecraft.item.*; + +public class Util { + + public static Block getBlock(int blockId) { + if (blockId <= 0) { + return null; + } + if (blockId > Block.blocksList.length) { + return null; + } + return Block.blocksList[blockId]; + } + + public static Item getItem(int itemId) { + if (itemId <= 0) { + return null; + } + if (itemId > Item.itemsList.length) { + return null; + } + return Item.itemsList[itemId]; + } + + public static Block getBlockFromItemId(int itemId) { + Item item = getItem(itemId); + if (item instanceof ItemBlock) { + return getBlock(((ItemBlock) item).getBlockID()); + } + return null; + } + + public static ItemStack consumeItem(ItemStack stack) { + if (stack.stackSize == 1) { + if (stack.getItem().hasContainerItem()) { + return stack.getItem().getContainerItemStack(stack); + } else { + return null; + } + } else { + stack.splitStack(1); + return stack; + } + } + +} diff --git a/common/crazypants/vecmath/Camera.java b/common/crazypants/vecmath/Camera.java new file mode 100644 index 00000000..873d98f7 --- /dev/null +++ b/common/crazypants/vecmath/Camera.java @@ -0,0 +1,146 @@ +package crazypants.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/common/crazypants/vecmath/Matrix4d.java b/common/crazypants/vecmath/Matrix4d.java new file mode 100644 index 00000000..f14757d8 --- /dev/null +++ b/common/crazypants/vecmath/Matrix4d.java @@ -0,0 +1,525 @@ +package crazypants.vecmath; + +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(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 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/common/crazypants/vecmath/Quat4d.java b/common/crazypants/vecmath/Quat4d.java new file mode 100644 index 00000000..1e408bc1 --- /dev/null +++ b/common/crazypants/vecmath/Quat4d.java @@ -0,0 +1,48 @@ +package crazypants.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; + } + +} diff --git a/common/crazypants/vecmath/VecmathUtil.java b/common/crazypants/vecmath/VecmathUtil.java new file mode 100644 index 00000000..f09082c8 --- /dev/null +++ b/common/crazypants/vecmath/VecmathUtil.java @@ -0,0 +1,633 @@ +package crazypants.vecmath; + +import java.awt.Rectangle; + +import net.minecraft.util.MathHelper; + +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); + } + + /** + * 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 camera + * the camera. + * @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/common/crazypants/vecmath/Vector2d.java b/common/crazypants/vecmath/Vector2d.java new file mode 100644 index 00000000..f30033ba --- /dev/null +++ b/common/crazypants/vecmath/Vector2d.java @@ -0,0 +1,82 @@ +package crazypants.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(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 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/common/crazypants/vecmath/Vector3d.java b/common/crazypants/vecmath/Vector3d.java new file mode 100644 index 00000000..19b13270 --- /dev/null +++ b/common/crazypants/vecmath/Vector3d.java @@ -0,0 +1,101 @@ +package crazypants.vecmath; + +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 void set(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public void set(Vector3d vec) { + x = vec.x; + y = vec.y; + z = vec.z; + } + + public void add(Vector3d vec) { + x += vec.x; + y += vec.y; + z += vec.z; + } + + public void sub(Vector3d vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + } + + public void negate() { + x = -x; + y = -y; + z = -z; + } + + public void scale(double s) { + x *= s; + y *= s; + z *= s; + } + + 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 + ")"; + } + +} diff --git a/common/crazypants/vecmath/Vector3f.java b/common/crazypants/vecmath/Vector3f.java new file mode 100644 index 00000000..32a784f9 --- /dev/null +++ b/common/crazypants/vecmath/Vector3f.java @@ -0,0 +1,94 @@ +package crazypants.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 = (float)x; + this.y = (float)y; + this.z = (float)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 sub(Vector3f 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 + ")"; + } +} diff --git a/common/crazypants/vecmath/Vector4d.java b/common/crazypants/vecmath/Vector4d.java new file mode 100644 index 00000000..33ca21cb --- /dev/null +++ b/common/crazypants/vecmath/Vector4d.java @@ -0,0 +1,92 @@ +package crazypants.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/common/crazypants/vecmath/ViewFrustum.java b/common/crazypants/vecmath/ViewFrustum.java new file mode 100644 index 00000000..afb03c22 --- /dev/null +++ b/common/crazypants/vecmath/ViewFrustum.java @@ -0,0 +1,172 @@ +package crazypants.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]; + } + +} diff --git a/lib/cglib-nodep-2.2.3.jar b/lib/cglib-nodep-2.2.3.jar new file mode 100644 index 00000000..35d6d7c3 Binary files /dev/null and b/lib/cglib-nodep-2.2.3.jar differ diff --git a/resources/CGLibLiscence.txt b/resources/CGLibLiscence.txt new file mode 100644 index 00000000..3d332846 --- /dev/null +++ b/resources/CGLibLiscence.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/resources/assets/enderio/textures/blocks/CutterFrontOff.pdn b/resources/assets/enderio/textures/blocks/CutterFrontOff.pdn new file mode 100644 index 00000000..439543b4 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/CutterFrontOff.pdn differ diff --git a/resources/assets/enderio/textures/blocks/CutterFrontOff.png b/resources/assets/enderio/textures/blocks/CutterFrontOff.png new file mode 100644 index 00000000..d7f6109e Binary files /dev/null and b/resources/assets/enderio/textures/blocks/CutterFrontOff.png differ diff --git a/resources/assets/enderio/textures/blocks/CutterFrontOn.pdn b/resources/assets/enderio/textures/blocks/CutterFrontOn.pdn new file mode 100644 index 00000000..03963318 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/CutterFrontOn.pdn differ diff --git a/resources/assets/enderio/textures/blocks/CutterFrontOn.png b/resources/assets/enderio/textures/blocks/CutterFrontOn.png new file mode 100644 index 00000000..49e2cb68 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/CutterFrontOn.png differ diff --git a/resources/assets/enderio/textures/blocks/activatedIronNugget.png b/resources/assets/enderio/textures/blocks/activatedIronNugget.png new file mode 100644 index 00000000..c9967fa5 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/activatedIronNugget.png differ diff --git a/resources/assets/enderio/textures/blocks/alloySmelterFront.pdn b/resources/assets/enderio/textures/blocks/alloySmelterFront.pdn new file mode 100644 index 00000000..613776d6 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/alloySmelterFront.pdn differ diff --git a/resources/assets/enderio/textures/blocks/alloySmelterFront.png b/resources/assets/enderio/textures/blocks/alloySmelterFront.png new file mode 100644 index 00000000..057d8096 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/alloySmelterFront.png differ diff --git a/resources/assets/enderio/textures/blocks/alloySmelterFrontOn.png b/resources/assets/enderio/textures/blocks/alloySmelterFrontOn.png new file mode 100644 index 00000000..70eede12 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/alloySmelterFrontOn.png differ diff --git a/resources/assets/enderio/textures/blocks/blockElectricLightFace.png b/resources/assets/enderio/textures/blocks/blockElectricLightFace.png new file mode 100644 index 00000000..ec64eb0f Binary files /dev/null and b/resources/assets/enderio/textures/blocks/blockElectricLightFace.png differ diff --git a/resources/assets/enderio/textures/blocks/conduitBundle.png b/resources/assets/enderio/textures/blocks/conduitBundle.png new file mode 100644 index 00000000..8916b298 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/conduitBundle.png differ diff --git a/resources/assets/enderio/textures/blocks/conduitConnector.png b/resources/assets/enderio/textures/blocks/conduitConnector.png new file mode 100644 index 00000000..ac56f926 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/conduitConnector.png differ diff --git a/resources/assets/enderio/textures/blocks/conduitFacade.png b/resources/assets/enderio/textures/blocks/conduitFacade.png new file mode 100644 index 00000000..f4941978 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/conduitFacade.png differ diff --git a/resources/assets/enderio/textures/blocks/enderIO.pdn b/resources/assets/enderio/textures/blocks/enderIO.pdn new file mode 100644 index 00000000..df676ea9 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/enderIO.pdn differ diff --git a/resources/assets/enderio/textures/blocks/enderIO.png b/resources/assets/enderio/textures/blocks/enderIO.png new file mode 100644 index 00000000..78f4af49 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/enderIO.png differ diff --git a/resources/assets/enderio/textures/blocks/enderIOFrame.pdn b/resources/assets/enderio/textures/blocks/enderIOFrame.pdn new file mode 100644 index 00000000..81f6f171 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/enderIOFrame.pdn differ diff --git a/resources/assets/enderio/textures/blocks/enderIOFrame.png b/resources/assets/enderio/textures/blocks/enderIOFrame.png new file mode 100644 index 00000000..e9a69b56 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/enderIOFrame.png differ diff --git a/resources/assets/enderio/textures/blocks/enderIronNugget.png b/resources/assets/enderio/textures/blocks/enderIronNugget.png new file mode 100644 index 00000000..44743146 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/enderIronNugget.png differ diff --git a/resources/assets/enderio/textures/blocks/fusedQuartz.pdn b/resources/assets/enderio/textures/blocks/fusedQuartz.pdn new file mode 100644 index 00000000..a28e483f Binary files /dev/null and b/resources/assets/enderio/textures/blocks/fusedQuartz.pdn differ diff --git a/resources/assets/enderio/textures/blocks/fusedQuartz.png b/resources/assets/enderio/textures/blocks/fusedQuartz.png new file mode 100644 index 00000000..3b020a6e Binary files /dev/null and b/resources/assets/enderio/textures/blocks/fusedQuartz.png differ diff --git a/resources/assets/enderio/textures/blocks/fusedQuartzItem.png b/resources/assets/enderio/textures/blocks/fusedQuartzItem.png new file mode 100644 index 00000000..87965e80 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/fusedQuartzItem.png differ diff --git a/resources/assets/enderio/textures/blocks/iconRedstoneControls.pdn b/resources/assets/enderio/textures/blocks/iconRedstoneControls.pdn new file mode 100644 index 00000000..4ee2c2cd Binary files /dev/null and b/resources/assets/enderio/textures/blocks/iconRedstoneControls.pdn differ diff --git a/resources/assets/enderio/textures/blocks/iconRedstoneIgnore.png b/resources/assets/enderio/textures/blocks/iconRedstoneIgnore.png new file mode 100644 index 00000000..66fb3019 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/iconRedstoneIgnore.png differ diff --git a/resources/assets/enderio/textures/blocks/iconRedstoneOff.png b/resources/assets/enderio/textures/blocks/iconRedstoneOff.png new file mode 100644 index 00000000..0ffb2f7c Binary files /dev/null and b/resources/assets/enderio/textures/blocks/iconRedstoneOff.png differ diff --git a/resources/assets/enderio/textures/blocks/iconRedstoneOn.png b/resources/assets/enderio/textures/blocks/iconRedstoneOn.png new file mode 100644 index 00000000..6ba64f47 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/iconRedstoneOn.png differ diff --git a/resources/assets/enderio/textures/blocks/liquidConduit.pdn b/resources/assets/enderio/textures/blocks/liquidConduit.pdn new file mode 100644 index 00000000..bc4e8d31 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/liquidConduit.pdn differ diff --git a/resources/assets/enderio/textures/blocks/liquidConduit.png b/resources/assets/enderio/textures/blocks/liquidConduit.png new file mode 100644 index 00000000..7104cd9a Binary files /dev/null and b/resources/assets/enderio/textures/blocks/liquidConduit.png differ diff --git a/resources/assets/enderio/textures/blocks/liquidConduitCore.pdn b/resources/assets/enderio/textures/blocks/liquidConduitCore.pdn new file mode 100644 index 00000000..4ab97d48 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/liquidConduitCore.pdn differ diff --git a/resources/assets/enderio/textures/blocks/liquidConduitCore.png b/resources/assets/enderio/textures/blocks/liquidConduitCore.png new file mode 100644 index 00000000..d8c1a1e1 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/liquidConduitCore.png differ diff --git a/resources/assets/enderio/textures/blocks/liquidConduitExtract.pdn b/resources/assets/enderio/textures/blocks/liquidConduitExtract.pdn new file mode 100644 index 00000000..2af3c67b Binary files /dev/null and b/resources/assets/enderio/textures/blocks/liquidConduitExtract.pdn differ diff --git a/resources/assets/enderio/textures/blocks/liquidConduitExtract.png b/resources/assets/enderio/textures/blocks/liquidConduitExtract.png new file mode 100644 index 00000000..ac4830d5 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/liquidConduitExtract.png differ diff --git a/resources/assets/enderio/textures/blocks/machineSide.pdn b/resources/assets/enderio/textures/blocks/machineSide.pdn new file mode 100644 index 00000000..8f06b299 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/machineSide.pdn differ diff --git a/resources/assets/enderio/textures/blocks/machineSide.png b/resources/assets/enderio/textures/blocks/machineSide.png new file mode 100644 index 00000000..2a081f86 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/machineSide.png differ diff --git a/resources/assets/enderio/textures/blocks/painterFront.pdn b/resources/assets/enderio/textures/blocks/painterFront.pdn new file mode 100644 index 00000000..654803e4 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/painterFront.pdn differ diff --git a/resources/assets/enderio/textures/blocks/painterFrontOff.png b/resources/assets/enderio/textures/blocks/painterFrontOff.png new file mode 100644 index 00000000..a0a95c5a Binary files /dev/null and b/resources/assets/enderio/textures/blocks/painterFrontOff.png differ diff --git a/resources/assets/enderio/textures/blocks/painterFrontOn.png b/resources/assets/enderio/textures/blocks/painterFrontOn.png new file mode 100644 index 00000000..7d1faea2 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/painterFrontOn.png differ diff --git a/resources/assets/enderio/textures/blocks/powerConduit.png b/resources/assets/enderio/textures/blocks/powerConduit.png new file mode 100644 index 00000000..dd7b511c Binary files /dev/null and b/resources/assets/enderio/textures/blocks/powerConduit.png differ diff --git a/resources/assets/enderio/textures/blocks/powerConduitCore.pdn b/resources/assets/enderio/textures/blocks/powerConduitCore.pdn new file mode 100644 index 00000000..fa5e6f2c Binary files /dev/null and b/resources/assets/enderio/textures/blocks/powerConduitCore.pdn differ diff --git a/resources/assets/enderio/textures/blocks/powerConduitCore.png b/resources/assets/enderio/textures/blocks/powerConduitCore.png new file mode 100644 index 00000000..59b15adf Binary files /dev/null and b/resources/assets/enderio/textures/blocks/powerConduitCore.png differ diff --git a/resources/assets/enderio/textures/blocks/powerConduitCoreEnder.png b/resources/assets/enderio/textures/blocks/powerConduitCoreEnder.png new file mode 100644 index 00000000..f0e422b8 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/powerConduitCoreEnder.png differ diff --git a/resources/assets/enderio/textures/blocks/powerConduitCoreEnhanced.png b/resources/assets/enderio/textures/blocks/powerConduitCoreEnhanced.png new file mode 100644 index 00000000..3d5e8c69 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/powerConduitCoreEnhanced.png differ diff --git a/resources/assets/enderio/textures/blocks/powerConduitEnder.png b/resources/assets/enderio/textures/blocks/powerConduitEnder.png new file mode 100644 index 00000000..839809e9 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/powerConduitEnder.png differ diff --git a/resources/assets/enderio/textures/blocks/powerConduitEnhanced.png b/resources/assets/enderio/textures/blocks/powerConduitEnhanced.png new file mode 100644 index 00000000..567c562a Binary files /dev/null and b/resources/assets/enderio/textures/blocks/powerConduitEnhanced.png differ diff --git a/resources/assets/enderio/textures/blocks/powerConduitTransmission.png b/resources/assets/enderio/textures/blocks/powerConduitTransmission.png new file mode 100644 index 00000000..e9c432c8 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/powerConduitTransmission.png differ diff --git a/resources/assets/enderio/textures/blocks/redstoneConduit.png b/resources/assets/enderio/textures/blocks/redstoneConduit.png new file mode 100644 index 00000000..025a7cca Binary files /dev/null and b/resources/assets/enderio/textures/blocks/redstoneConduit.png differ diff --git a/resources/assets/enderio/textures/blocks/redstoneConduitCoreOff.pdn b/resources/assets/enderio/textures/blocks/redstoneConduitCoreOff.pdn new file mode 100644 index 00000000..06d6734f Binary files /dev/null and b/resources/assets/enderio/textures/blocks/redstoneConduitCoreOff.pdn differ diff --git a/resources/assets/enderio/textures/blocks/redstoneConduitCoreOff.png b/resources/assets/enderio/textures/blocks/redstoneConduitCoreOff.png new file mode 100644 index 00000000..43b4e0cc Binary files /dev/null and b/resources/assets/enderio/textures/blocks/redstoneConduitCoreOff.png differ diff --git a/resources/assets/enderio/textures/blocks/redstoneConduitCoreOn.pdn b/resources/assets/enderio/textures/blocks/redstoneConduitCoreOn.pdn new file mode 100644 index 00000000..e4ca7df8 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/redstoneConduitCoreOn.pdn differ diff --git a/resources/assets/enderio/textures/blocks/redstoneConduitCoreOn.png b/resources/assets/enderio/textures/blocks/redstoneConduitCoreOn.png new file mode 100644 index 00000000..df9bce29 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/redstoneConduitCoreOn.png differ diff --git a/resources/assets/enderio/textures/blocks/redstoneConduitSwitch.pdn b/resources/assets/enderio/textures/blocks/redstoneConduitSwitch.pdn new file mode 100644 index 00000000..873879de Binary files /dev/null and b/resources/assets/enderio/textures/blocks/redstoneConduitSwitch.pdn differ diff --git a/resources/assets/enderio/textures/blocks/redstoneConduitSwitchOff.png b/resources/assets/enderio/textures/blocks/redstoneConduitSwitchOff.png new file mode 100644 index 00000000..708c9115 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/redstoneConduitSwitchOff.png differ diff --git a/resources/assets/enderio/textures/blocks/redstoneConduitSwitchOn.png b/resources/assets/enderio/textures/blocks/redstoneConduitSwitchOn.png new file mode 100644 index 00000000..13b3be3c Binary files /dev/null and b/resources/assets/enderio/textures/blocks/redstoneConduitSwitchOn.png differ diff --git a/resources/assets/enderio/textures/blocks/redstoneConduitTransmission.png b/resources/assets/enderio/textures/blocks/redstoneConduitTransmission.png new file mode 100644 index 00000000..04396d7a Binary files /dev/null and b/resources/assets/enderio/textures/blocks/redstoneConduitTransmission.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoir.pdn b/resources/assets/enderio/textures/blocks/reservoir.pdn new file mode 100644 index 00000000..f233bf56 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoir.pdn differ diff --git a/resources/assets/enderio/textures/blocks/reservoir.png b/resources/assets/enderio/textures/blocks/reservoir.png new file mode 100644 index 00000000..91227ee6 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoir.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoirFront.pdn b/resources/assets/enderio/textures/blocks/reservoirFront.pdn new file mode 100644 index 00000000..d42f5cae Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirFront.pdn differ diff --git a/resources/assets/enderio/textures/blocks/reservoirMbB.png b/resources/assets/enderio/textures/blocks/reservoirMbB.png new file mode 100644 index 00000000..311e3b6e Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirMbB.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoirMbBl.png b/resources/assets/enderio/textures/blocks/reservoirMbBl.png new file mode 100644 index 00000000..06941d80 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirMbBl.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoirMbBr.png b/resources/assets/enderio/textures/blocks/reservoirMbBr.png new file mode 100644 index 00000000..8f4b19d3 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirMbBr.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoirMbL.png b/resources/assets/enderio/textures/blocks/reservoirMbL.png new file mode 100644 index 00000000..0e18ea45 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirMbL.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoirMbR.png b/resources/assets/enderio/textures/blocks/reservoirMbR.png new file mode 100644 index 00000000..ad76c6e4 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirMbR.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoirMbT.png b/resources/assets/enderio/textures/blocks/reservoirMbT.png new file mode 100644 index 00000000..4e1d9e17 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirMbT.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoirMbTl.png b/resources/assets/enderio/textures/blocks/reservoirMbTl.png new file mode 100644 index 00000000..480149fc Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirMbTl.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoirMbTr.png b/resources/assets/enderio/textures/blocks/reservoirMbTr.png new file mode 100644 index 00000000..0763ab6b Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirMbTr.png differ diff --git a/resources/assets/enderio/textures/blocks/reservoirSideHorizontal.pdn b/resources/assets/enderio/textures/blocks/reservoirSideHorizontal.pdn new file mode 100644 index 00000000..2b95b389 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirSideHorizontal.pdn differ diff --git a/resources/assets/enderio/textures/blocks/reservoirSideVertical.pdn b/resources/assets/enderio/textures/blocks/reservoirSideVertical.pdn new file mode 100644 index 00000000..32daa67d Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirSideVertical.pdn differ diff --git a/resources/assets/enderio/textures/blocks/reservoirSwitch.png b/resources/assets/enderio/textures/blocks/reservoirSwitch.png new file mode 100644 index 00000000..135dcad6 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/reservoirSwitch.png differ diff --git a/resources/assets/enderio/textures/blocks/solarPanelSide.png b/resources/assets/enderio/textures/blocks/solarPanelSide.png new file mode 100644 index 00000000..af36bd89 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/solarPanelSide.png differ diff --git a/resources/assets/enderio/textures/blocks/solarPanelTop.png b/resources/assets/enderio/textures/blocks/solarPanelTop.png new file mode 100644 index 00000000..15bae1f7 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/solarPanelTop.png differ diff --git a/resources/assets/enderio/textures/blocks/stirlingGenFront.pdn b/resources/assets/enderio/textures/blocks/stirlingGenFront.pdn new file mode 100644 index 00000000..dbcf4560 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/stirlingGenFront.pdn differ diff --git a/resources/assets/enderio/textures/blocks/stirlingGenFrontOff.png b/resources/assets/enderio/textures/blocks/stirlingGenFrontOff.png new file mode 100644 index 00000000..76124997 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/stirlingGenFrontOff.png differ diff --git a/resources/assets/enderio/textures/blocks/stirlingGenFrontOn.png b/resources/assets/enderio/textures/blocks/stirlingGenFrontOn.png new file mode 100644 index 00000000..528152dc Binary files /dev/null and b/resources/assets/enderio/textures/blocks/stirlingGenFrontOn.png differ diff --git a/resources/assets/enderio/textures/gui/alloySmelter.png b/resources/assets/enderio/textures/gui/alloySmelter.png new file mode 100644 index 00000000..ab3e5214 Binary files /dev/null and b/resources/assets/enderio/textures/gui/alloySmelter.png differ diff --git a/resources/assets/enderio/textures/gui/painter.pdn b/resources/assets/enderio/textures/gui/painter.pdn new file mode 100644 index 00000000..924479b4 Binary files /dev/null and b/resources/assets/enderio/textures/gui/painter.pdn differ diff --git a/resources/assets/enderio/textures/gui/painter.png b/resources/assets/enderio/textures/gui/painter.png new file mode 100644 index 00000000..a879d639 Binary files /dev/null and b/resources/assets/enderio/textures/gui/painter.png differ diff --git a/resources/assets/enderio/textures/gui/stirlingGenerator.pdn b/resources/assets/enderio/textures/gui/stirlingGenerator.pdn new file mode 100644 index 00000000..67de5dad Binary files /dev/null and b/resources/assets/enderio/textures/gui/stirlingGenerator.pdn differ diff --git a/resources/assets/enderio/textures/gui/stirlingGenerator.png b/resources/assets/enderio/textures/gui/stirlingGenerator.png new file mode 100644 index 00000000..58f6df7f Binary files /dev/null and b/resources/assets/enderio/textures/gui/stirlingGenerator.png differ diff --git a/resources/assets/enderio/textures/items/ConduitFacade.png b/resources/assets/enderio/textures/items/ConduitFacade.png new file mode 100644 index 00000000..568a98bf Binary files /dev/null and b/resources/assets/enderio/textures/items/ConduitFacade.png differ diff --git a/resources/assets/enderio/textures/items/ItemLiquidConduit.png b/resources/assets/enderio/textures/items/ItemLiquidConduit.png new file mode 100644 index 00000000..d8c1a1e1 Binary files /dev/null and b/resources/assets/enderio/textures/items/ItemLiquidConduit.png differ diff --git a/resources/assets/enderio/textures/items/ItemPowerConduit.png b/resources/assets/enderio/textures/items/ItemPowerConduit.png new file mode 100644 index 00000000..59b15adf Binary files /dev/null and b/resources/assets/enderio/textures/items/ItemPowerConduit.png differ diff --git a/resources/assets/enderio/textures/items/ItemRedstoneConduit.png b/resources/assets/enderio/textures/items/ItemRedstoneConduit.png new file mode 100644 index 00000000..43b4e0cc Binary files /dev/null and b/resources/assets/enderio/textures/items/ItemRedstoneConduit.png differ diff --git a/resources/assets/enderio/textures/items/activatedGold.png b/resources/assets/enderio/textures/items/activatedGold.png new file mode 100644 index 00000000..2f40fdc9 Binary files /dev/null and b/resources/assets/enderio/textures/items/activatedGold.png differ diff --git a/resources/assets/enderio/textures/items/activatedGoldNugget.png b/resources/assets/enderio/textures/items/activatedGoldNugget.png new file mode 100644 index 00000000..8768434b Binary files /dev/null and b/resources/assets/enderio/textures/items/activatedGoldNugget.png differ diff --git a/resources/assets/enderio/textures/items/activatedIron.pdn b/resources/assets/enderio/textures/items/activatedIron.pdn new file mode 100644 index 00000000..17af8aad Binary files /dev/null and b/resources/assets/enderio/textures/items/activatedIron.pdn differ diff --git a/resources/assets/enderio/textures/items/activatedIron.png b/resources/assets/enderio/textures/items/activatedIron.png new file mode 100644 index 00000000..919381ce Binary files /dev/null and b/resources/assets/enderio/textures/items/activatedIron.png differ diff --git a/resources/assets/enderio/textures/items/activatedIronNugget.png b/resources/assets/enderio/textures/items/activatedIronNugget.png new file mode 100644 index 00000000..2dc9699b Binary files /dev/null and b/resources/assets/enderio/textures/items/activatedIronNugget.png differ diff --git a/resources/assets/enderio/textures/items/basicCapacitor.pdn b/resources/assets/enderio/textures/items/basicCapacitor.pdn new file mode 100644 index 00000000..a9c2c46f Binary files /dev/null and b/resources/assets/enderio/textures/items/basicCapacitor.pdn differ diff --git a/resources/assets/enderio/textures/items/basicCapacitor.png b/resources/assets/enderio/textures/items/basicCapacitor.png new file mode 100644 index 00000000..c9308a49 Binary files /dev/null and b/resources/assets/enderio/textures/items/basicCapacitor.png differ diff --git a/resources/assets/enderio/textures/items/blueSteel.png b/resources/assets/enderio/textures/items/blueSteel.png new file mode 100644 index 00000000..f7f72a49 Binary files /dev/null and b/resources/assets/enderio/textures/items/blueSteel.png differ diff --git a/resources/assets/enderio/textures/items/blueSteelNugget.pdn b/resources/assets/enderio/textures/items/blueSteelNugget.pdn new file mode 100644 index 00000000..008b1936 Binary files /dev/null and b/resources/assets/enderio/textures/items/blueSteelNugget.pdn differ diff --git a/resources/assets/enderio/textures/items/blueSteelNugget.png b/resources/assets/enderio/textures/items/blueSteelNugget.png new file mode 100644 index 00000000..ef44ad7d Binary files /dev/null and b/resources/assets/enderio/textures/items/blueSteelNugget.png differ diff --git a/resources/assets/enderio/textures/items/conduitFacade.pdn b/resources/assets/enderio/textures/items/conduitFacade.pdn new file mode 100644 index 00000000..6de25e95 Binary files /dev/null and b/resources/assets/enderio/textures/items/conduitFacade.pdn differ diff --git a/resources/assets/enderio/textures/items/conduitFacadeOverlay.png b/resources/assets/enderio/textures/items/conduitFacadeOverlay.png new file mode 100644 index 00000000..15e679b9 Binary files /dev/null and b/resources/assets/enderio/textures/items/conduitFacadeOverlay.png differ diff --git a/resources/assets/enderio/textures/items/enderGold.png b/resources/assets/enderio/textures/items/enderGold.png new file mode 100644 index 00000000..cb5ccfcc Binary files /dev/null and b/resources/assets/enderio/textures/items/enderGold.png differ diff --git a/resources/assets/enderio/textures/items/enderGoldNugget.png b/resources/assets/enderio/textures/items/enderGoldNugget.png new file mode 100644 index 00000000..37120ede Binary files /dev/null and b/resources/assets/enderio/textures/items/enderGoldNugget.png differ diff --git a/resources/assets/enderio/textures/items/enderIron.png b/resources/assets/enderio/textures/items/enderIron.png new file mode 100644 index 00000000..df86a15f Binary files /dev/null and b/resources/assets/enderio/textures/items/enderIron.png differ diff --git a/resources/assets/enderio/textures/items/enderIronNugget.pdn b/resources/assets/enderio/textures/items/enderIronNugget.pdn new file mode 100644 index 00000000..a200b8ee Binary files /dev/null and b/resources/assets/enderio/textures/items/enderIronNugget.pdn differ diff --git a/resources/assets/enderio/textures/items/enderIronNugget.png b/resources/assets/enderio/textures/items/enderIronNugget.png new file mode 100644 index 00000000..7e3a1911 Binary files /dev/null and b/resources/assets/enderio/textures/items/enderIronNugget.png differ diff --git a/resources/assets/enderio/textures/items/enderface.pdn b/resources/assets/enderio/textures/items/enderface.pdn new file mode 100644 index 00000000..62d50332 Binary files /dev/null and b/resources/assets/enderio/textures/items/enderface.pdn differ diff --git a/resources/assets/enderio/textures/items/enderface.png b/resources/assets/enderio/textures/items/enderface.png new file mode 100644 index 00000000..b005c295 Binary files /dev/null and b/resources/assets/enderio/textures/items/enderface.png differ diff --git a/resources/assets/enderio/textures/items/industrialBinder.pdn b/resources/assets/enderio/textures/items/industrialBinder.pdn new file mode 100644 index 00000000..8c5860aa Binary files /dev/null and b/resources/assets/enderio/textures/items/industrialBinder.pdn differ diff --git a/resources/assets/enderio/textures/items/industrialBinder.png b/resources/assets/enderio/textures/items/industrialBinder.png new file mode 100644 index 00000000..a2adc58f Binary files /dev/null and b/resources/assets/enderio/textures/items/industrialBinder.png differ diff --git a/resources/assets/enderio/textures/items/itemPowerConduitEnder.png b/resources/assets/enderio/textures/items/itemPowerConduitEnder.png new file mode 100644 index 00000000..f0e422b8 Binary files /dev/null and b/resources/assets/enderio/textures/items/itemPowerConduitEnder.png differ diff --git a/resources/assets/enderio/textures/items/itemPowerConduitEnhanced.png b/resources/assets/enderio/textures/items/itemPowerConduitEnhanced.png new file mode 100644 index 00000000..3d5e8c69 Binary files /dev/null and b/resources/assets/enderio/textures/items/itemPowerConduitEnhanced.png differ diff --git a/resources/assets/enderio/textures/items/itemRedstoneSwitch.png b/resources/assets/enderio/textures/items/itemRedstoneSwitch.png new file mode 100644 index 00000000..708c9115 Binary files /dev/null and b/resources/assets/enderio/textures/items/itemRedstoneSwitch.png differ diff --git a/resources/assets/enderio/textures/items/nugget.pdn b/resources/assets/enderio/textures/items/nugget.pdn new file mode 100644 index 00000000..676bd07d Binary files /dev/null and b/resources/assets/enderio/textures/items/nugget.pdn differ diff --git a/resources/assets/enderio/textures/items/yetaWrench.png b/resources/assets/enderio/textures/items/yetaWrench.png new file mode 100644 index 00000000..1a6d2113 Binary files /dev/null and b/resources/assets/enderio/textures/items/yetaWrench.png differ diff --git a/resources/mcmod.info b/resources/mcmod.info new file mode 100644 index 00000000..e8bd080c --- /dev/null +++ b/resources/mcmod.info @@ -0,0 +1,21 @@ +[ +{ + "modid": "EnderIO", + "name": "Ender IO", + "description": "Compact conduits, painted things and access to your stuff through an eye of ender.", + "version": "0.1.0", + "mcversion": "1.6.2", + "url": "", + "updateUrl": "", + "authors": [ + "crazypants" + ], + "credits": "By crazypants, using the buildcraft API, and the cglib library.", + "logoFile": "", + "screenshots": [ + ], + "parent":"", + "dependencies": [ + ] +} +] \ No newline at end of file