Initial code dump.

This commit is contained in:
brad-c committed 2013-08-12 16:22:59 +08:00
1 parent 07253c55ae
commit 0e893e449f
327 files changed
+21597

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="common"/>
<classpathentry kind="src" path="resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry exported="true" kind="lib" path="lib/cglib-nodep-2.2.3.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Minecraft"/>
<classpathentry kind="output" path="bin"/>
</classpath>
+3
View File
@@ -0,0 +1,3 @@
/bin
/build
/download
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>EnderIO</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
+4
View File
@@ -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.
+170
View File
@@ -0,0 +1,170 @@
<project name="EnderIO" default="main">
<property environment="env"/>
<!-- Properties -->
<property name="build.dir" value="build"/>
<property name="src.dir" value="."/>
<property name="resources.dir" value="resources"/>
<property name="lib.dir" value="lib"/>
<property name="download.dir" value="download"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="bin"/>
<property name="forge.dir" value="${build.dir}/forge"/>
<property name="mcp.dir" value="${forge.dir}/mcp"/>
<property name="mcpsrc.dir" value="${mcp.dir}/src"/>
<property name="mc.version" value="1.6.2"/>
<property name="forge.version" value="9.10.0.800"/>
<property name="project.version" value="0.1.0"/>
<property name="forge.name" value="minecraftforge-src-${mc.version}-${forge.version}.zip"/>
<available property="forge-exists" file="${download.dir}/${forge.name}"/>
<condition property="out-of-date">
<not>
<and>
<available file="${download.dir}/${forge.name}"/>
<available file="${mcpsrc.dir}"/>
</and>
</not>
</condition>
<mkdir dir="${download.dir}"/>
<!-- Targets -->
<!-- Clear build directory -->
<target name="clean">
<delete dir="${build.dir}"/>
</target>
<!-- Set full version -->
<target name="initialize-version" depends="version-provided,version-not-provided">
<property name="project.version.full" value="${project.version}.${build.number}"/>
</target>
<!-- Set unknown build number -->
<target name="version-not-provided" unless="env.BUILD_NUMBER">
<!-- property name="build.number" value="unknown"/ -->
<property name="build.number" value="0"/>
</target>
<!-- Set build number from environment -->
<target name="version-provided" if="env.BUILD_NUMBER">
<property name="build.number" value="${env.BUILD_NUMBER}"/>
</target>
<!-- Download necessary files -->
<target name="download-files" depends="download-forge"/>
<!-- Download forge (if it doesn't exist) -->
<target name="download-forge" unless="forge-exists">
<get src="http://files.minecraftforge.net/${forge.name}" dest="${download.dir}" usetimestamp="True"/>
</target>
<!-- Setup mcp and forge -->
<target name="setup" depends="download-files" if="out-of-date">
<delete dir="${forge.dir}" failonerror="false"/>
<unzip dest="${forge.dir}/.." src="${download.dir}/${forge.name}"/>
<!-- Fix executable permissions -->
<chmod dir="${forge.dir}" perm="ugo+rx" includes="**.sh"/>
<!-- Install forge -->
<exec dir="${forge.dir}" executable="cmd" osfamily="windows">
<arg line="/c install.cmd"/>
</exec>
<exec dir="${forge.dir}" executable="sh" osfamily="unix">
<arg value="install.sh"/>
</exec>
</target>
<target name="compile" depends="initialize-version,setup">
<delete dir="${classes.dir}"/>
<mkdir dir="${classes.dir}"/>
<!-- Copy sources -->
<copy todir="${mcpsrc.dir}/minecraft">
<fileset dir="${src.dir}/common"/>
<filterset>
<filter token="VERSION" value="${project.version.full}" />
<filter token="BUILD_NUMBER" value="${build.number}" />
</filterset>
</copy>
<copy todir="${mcp.dir}/lib">
<fileset dir="${src.dir}/lib"/>
</copy>
<!-- Recompile -->
<exec dir="${mcp.dir}" executable="cmd" osfamily="windows">
<arg line="/c recompile.bat"/>
</exec>
<exec dir="${mcp.dir}" executable="sh" osfamily="unix">
<arg value="recompile.sh"/>
</exec>
<!-- Check for failure -->
<fail message="MCP failed to build">
<condition>
<resourcecontains resource="${mcp.dir}/logs/client_compile.log" substring="error:"/>
</condition>
</fail>
<!-- Reobfuscate -->
<exec dir="${mcp.dir}" executable="cmd" osfamily="windows">
<arg line="/c reobfuscate.bat"/>
</exec>
<exec dir="${mcp.dir}" executable="sh" osfamily="unix">
<arg value="reobfuscate.sh"/>
</exec>
<!-- Copy classes -->
<copy todir="${classes.dir}">
<fileset dir="${mcp.dir}/reobf/minecraft"/>
</copy>
<!-- Copy resources -->
<copy todir="${classes.dir}">
<fileset dir="${resources.dir}">
<exclude name="build.xml"/>
<exclude name="**/*.pdn"/>
</fileset>
</copy>
<!-- Reset src dir to post-forge-install state -->
<delete dir="${mcpsrc.dir}/minecraft/crazypants"/>
</target>
<!-- Package the compiled files -->
<target name="package" depends="compile">
<delete dir="${jar.dir}"/>
<mkdir dir="${jar.dir}"/>
<jar destfile="${jar.dir}/${ant.project.name}-${mc.version}-${project.version.full}.jar" basedir="${classes.dir}"/>
<jar destfile="${jar.dir}/${ant.project.name}-${mc.version}-${project.version.full}.jar">
<fileset dir="${classes.dir}"/>
<zipfileset includes="**/*.class" src="${lib.dir}/cglib-nodep-2.2.3.jar"/>
</jar>
</target>
<!-- Default target to run -->
<target name="main" depends="package"/>
</project>
@@ -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 = "*";
}
}
}
@@ -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);
}
}
}
@@ -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<ItemStack> 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<ItemStack> 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);
}
}
@@ -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<ItemStack> 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);
}
}
@@ -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<ItemStack> storedRequirements = new LinkedList<ItemStack>();
/**
* 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;
}
}
@@ -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();
}
@@ -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 = "*";
}
}
}
@@ -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<ItemStack> 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;
}
}
@@ -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<ItemStack> requirements) {
requirements.add(customStack.copy());
}
}
@@ -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<ItemStack> 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);
}
}
}
@@ -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<ItemStack> 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;
}
}
@@ -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<ItemStack> 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);
}
}
@@ -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<ItemStack> 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);
}
}
}
@@ -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<ItemStack> 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;
}
}
@@ -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<ItemStack> 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);
}
}
@@ -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);
}
}
}
@@ -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<ItemStack> 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;
}
}
@@ -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);
}
}
@@ -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<ItemStack> 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;
}
}
}
@@ -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<ItemStack> 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;
}
}
}
@@ -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);
}
}
}
@@ -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<ItemStack> 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;
}
}
@@ -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<ItemStack> 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;
}
}
@@ -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<ItemStack> 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;
}
}
}
@@ -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<ItemStack> 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;
}
}
}
@@ -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];
}
@@ -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();
}
+30
View File
@@ -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();
}
@@ -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);
}
+14
View File
@@ -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
}
+142
View File
@@ -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);
}
}
@@ -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();
}
}
@@ -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 <http://www.railcraft.info/>
*/
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;
}
}
@@ -0,0 +1,7 @@
package buildcraft.api.filler;
public class FillerManager {
public static IFillerRegistry registry;
}
@@ -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();
}
@@ -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);
}
@@ -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<String, Coolant> liquidCoolants = new HashMap<String, Coolant>();
public static Map<StackWrapper, FluidStack> solidCoolants = new HashMap<StackWrapper, FluidStack>();
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());
}
}
@@ -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<String, Fuel> fuels = new HashMap<String, Fuel>();
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));
}
}
@@ -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<String, ITrigger> triggers = new HashMap<String, ITrigger>();
public static Map<String, IAction> actions = new HashMap<String, IAction>();
private static LinkedList<ITriggerProvider> triggerProviders = new LinkedList<ITriggerProvider>();
private static LinkedList<IActionProvider> actionProviders = new LinkedList<IActionProvider>();
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<ITrigger> getNeighborTriggers(Block block, TileEntity entity) {
LinkedList<ITrigger> triggers = new LinkedList<ITrigger>();
for (ITriggerProvider provider : triggerProviders) {
LinkedList<ITrigger> 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<IAction> getNeighborActions(Block block, TileEntity entity) {
LinkedList<IAction> actions = new LinkedList<IAction>();
for (IActionProvider provider : actionProviders) {
LinkedList<IAction> toAdd = provider.getNeighborActions(block, entity);
if (toAdd != null) {
for (IAction t : toAdd) {
if (!actions.contains(t)) {
actions.add(t);
}
}
}
}
return actions;
}
public static LinkedList<ITrigger> getPipeTriggers(IPipe pipe) {
LinkedList<ITrigger> triggers = new LinkedList<ITrigger>();
for (ITriggerProvider provider : triggerProviders) {
LinkedList<ITrigger> 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;
}
}
+27
View File
@@ -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();
}
@@ -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<IAction> getNeighborActions(Block block, TileEntity tile);
}
@@ -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);
}
@@ -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<ITrigger> getTriggers();
}
+47
View File
@@ -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();
}
@@ -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();
}
@@ -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<ITrigger> getPipeTriggers(IPipe pipe);
/**
* Returns the list of triggers available to a gate next to the given block.
*/
public abstract LinkedList<ITrigger> getNeighborTriggers(Block block, TileEntity tile);
}
@@ -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;
}
}
@@ -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);
}
@@ -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);
}
@@ -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);
}
@@ -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 <http://www.railcraft.info/>
*/
public interface IPowerEmitter {
public boolean canEmitPowerFrom(ForgeDirection side);
}
@@ -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 <http://www.railcraft.info/>
*/
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();
}
@@ -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;
}
}
}
@@ -0,0 +1,48 @@
package buildcraft.api.recipes;
import java.util.LinkedList;
import net.minecraft.item.ItemStack;
public class AssemblyRecipe {
public static LinkedList<AssemblyRecipe> assemblyRecipes = new LinkedList<AssemblyRecipe>();
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;
}
}
@@ -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<Recipe> recipes = new TreeSet<Recipe>();
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<Recipe> 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<Recipe> {
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);
}
}
}
@@ -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);
}
@@ -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);
}
@@ -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) {
}
}
}
@@ -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);
}
@@ -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);
}
@@ -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);
}
@@ -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);
}
@@ -0,0 +1,7 @@
package buildcraft.api.transport;
import net.minecraftforge.common.ForgeDirection;
public interface ISolidSideTile {
public boolean isSolidOnSide(ForgeDirection side);
}
@@ -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<IExtractionHandler> extractionHandlers = new ArrayList<IExtractionHandler>();
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;
}
}
+120
View File
@@ -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<ConduitRenderer> conduitRenderers = new ArrayList<ConduitRenderer>();
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;
}
}
@@ -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<TickType> 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<TileEntity> 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<TickType> type, Object... tickData) {
}
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.PLAYER);
}
@Override
public String getLabel() {
return "EnderIO Client Tick Handler";
}
}
@@ -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();
}
}
+19
View File
@@ -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() {
}
}
+172
View File
@@ -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();
}
}
+36
View File
@@ -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";
}
}
+41
View File
@@ -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<Integer, IGuiHandler> guiHandlers = new HashMap<Integer, IGuiHandler>();
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;
}
}
+80
View File
@@ -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;
}
}
}
@@ -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: <ERROR> 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> 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<String> interceptNames = new HashSet<String>();
private Set<String> beaconNames = new HashSet<String>();
private Set<String> anvilNames = new HashSet<String>();
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);
}
}
}
@@ -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<TickType> TICKS = EnumSet.of(TickType.SERVER);
private final List<WeakReference<TickListener>> listeners = new CopyOnWriteArrayList<WeakReference<TickListener>>();
public void addListener(TickListener listener) {
listeners.add(new WeakReference<TickListener>(listener));
}
public void removeListener(TickListener listener) {
WeakReference<TickListener> toRemove = null;
for(WeakReference<TickListener> ref : listeners) {
if(ref.get() == listener) {
toRemove = ref;
break;
}
}
if(toRemove != null) {
listeners.remove(toRemove);
}
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
List<TickListener> lists = processListeners();
for(TickListener listener : lists) {
listener.tickStart(type, tickData);
}
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
List<TickListener> lists = processListeners();
for(TickListener listener : lists) {
listener.tickEnd(type, tickData);
}
}
private List<TickListener> processListeners() {
List<TickListener> result = new ArrayList<TickListener>(listeners.size());
List<WeakReference<TickListener>> toRemove = new ArrayList<WeakReference<TickListener>>();
for(WeakReference<TickListener> 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<TickType> ticks() {
return TICKS;
}
@Override
public String getLabel() {
return "EnderIO Server Tick Handler";
}
}
@@ -0,0 +1,13 @@
package crazypants.enderio;
import java.util.EnumSet;
import cpw.mods.fml.common.TickType;
public interface TickListener {
void tickStart(EnumSet<TickType> type, Object... tickData);
void tickEnd(EnumSet<TickType> type, Object... tickData);
}
+22
View File
@@ -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) {
}
}
@@ -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<ForgeDirection> conduitConnections = new HashSet<ForgeDirection>();
protected final Set<ForgeDirection> externalConnections = new HashSet<ForgeDirection>();
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<CollidableComponent> 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<ForgeDirection> 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<ForgeDirection> 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<ForgeDirection> 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<ForgeDirection> copy = new ArrayList<ForgeDirection>(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<CollidableComponent> 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<CollidableComponent> getCollidableComponents() {
if (collidables != null && !collidablesDirty) {
return collidables;
}
List<CollidableComponent> result = new ArrayList<CollidableComponent>();
CollidableCache cc = CollidableCache.instance;
for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
Collection<CollidableComponent> col = getCollidables(dir);
if(col != null) {
result.addAll(col);
}
}
collidables = result;
collidablesDirty = false;
return result;
}
private Collection<CollidableComponent> getCollidables(ForgeDirection dir) {
CollidableCache cc = CollidableCache.instance;
Class<? extends IConduit> type = getBaseConduitType();
if (isConnectedTo(dir)) {
return cc.getCollidables(cc.createKey(type, getBundle().getOffset(type, dir), dir, false), this);
}
return null;
}
}
@@ -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<T extends IConduit> {
protected final List<T> conduits = new ArrayList<T>();
protected AbstractConduitNetwork() {
}
public void init(IConduitBundle tile, Collection<T> 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<? extends T> getBaseConduitType();
protected void setNetwork(World world, IConduitBundle tile) {
T conduit = tile.getConduit(getBaseConduitType());
if (conduit.setNetwork(this)) {
addConduit(conduit);
TileEntity te = tile.getEntity();
Collection<? extends T> 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<T> 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) {
}
}
@@ -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));
}
}
}
@@ -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<IConduit> 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<ItemStack> drop = new ArrayList<ItemStack>();
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<? extends IConduit> 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<IConduit> cons = new ArrayList<IConduit>(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<CollidableComponent> 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<CollidableComponent> 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<RaytraceResult> hits = new ArrayList<RaytraceResult>();
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<CollidableComponent> 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);
}
}
@@ -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);
}
}
@@ -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<? extends IConduit> 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<? extends IConduit> 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<? extends IConduit> 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 extends IConduit> T getConduit(IBlockAccess world, int x, int y, int z, Class<T> 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 extends IConduit> T getConduit(IBlockAccess world, TileEntity te, ForgeDirection dir, Class<T> type) {
return ConduitUtil.getConduit(world, te.xCoord + dir.offsetX, te.yCoord + dir.offsetY, te.zCoord + dir.offsetZ, type);
}
public static <T extends IConduit> Collection<T> getConnectedConduits(IBlockAccess world, int x, int y, int z, Class<T> type) {
TileEntity te = world.getBlockTileEntity(x, y, z);
if (!(te instanceof IConduitBundle)) {
return Collections.emptyList();
}
List<T> result = new ArrayList<T>();
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;
}
}
@@ -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<? extends IConduit> 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<ForgeDirection> 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<ForgeDirection> 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<CollidableComponent> getCollidableComponents();
Collection<CollidableComponent> createCollidables(CacheKey key);
// Actions
boolean onBlockActivated(EntityPlayer player, RaytraceResult res);
void onChunkUnload(World worldObj);
void updateEntity(World worldObj);
boolean onNeighborBlockChange(int blockId);
}
@@ -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<? extends IConduit> type);
<T extends IConduit> T getConduit(Class<T> type);
void addConduit(IConduit conduit);
void removeConduit(IConduit conduit);
Collection<IConduit> getConduits();
Offset getOffset(Class<? extends IConduit> type, ForgeDirection dir);
// connections
Set<ForgeDirection> getConnections(Class<? extends IConduit> type);
boolean containsConnection(Class<? extends IConduit> type, ForgeDirection west);
Set<ForgeDirection> 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<CollidableComponent> getCollidableComponents();
List<CollidableComponent> getConnectors();
void dirty();
}
@@ -0,0 +1,11 @@
package crazypants.enderio.conduit;
import net.minecraft.item.ItemStack;
public interface IConduitItem {
Class<? extends IConduit> getBaseConduitType();
IConduit createConduit(ItemStack item);
}
@@ -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;
}
}
@@ -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<RaytraceResult> 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;
}
}
@@ -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<IConduit> conduits = new ArrayList<IConduit>();
private int facadeId = -1;
private int facadeMeta = 0;
private boolean facadeChanged;
private final List<CollidableComponent> cachedCollidables = new ArrayList<CollidableComponent>();
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<? extends IConduit> type) {
return getConduit(type) != null;
}
@SuppressWarnings("unchecked")
@Override
public <T extends IConduit> T getConduit(Class<T> 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<IConduit> copy = new ArrayList<IConduit>(conduits);
for (IConduit con : copy) {
removeConduit(con, false);
}
dirty();
}
@Override
public Collection<IConduit> getConduits() {
return conduits;
}
@Override
public Set<ForgeDirection> getConnections(Class<? extends IConduit> type) {
IConduit con = getConduit(type);
if (con != null) {
return con.getConduitConnections();
}
return null;
}
@Override
public boolean containsConnection(Class<? extends IConduit> 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<ForgeDirection> getAllConnections() {
Set<ForgeDirection> result = new HashSet<ForgeDirection>();
for (IConduit con : conduits) {
result.addAll(con.getConduitConnections());
}
return result;
}
// Geometry
@Override
public Offset getOffset(Class<? extends IConduit> 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<CollidableComponent> 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<CollidableComponent> getConnectors() {
List<CollidableComponent> result = new ArrayList<CollidableComponent>();
addConnectors(result);
return result;
}
private void addConnectors(List<CollidableComponent> 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<? extends IConduit> 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<? extends IConduit> 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;
}
}
@@ -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];
}
}
}
@@ -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();
}
}
}
@@ -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);
}
}
}
@@ -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<CacheKey, Collection<CollidableComponent>> cache = new HashMap<CollidableCache.CacheKey, Collection<CollidableComponent>>();
public CacheKey createKey(Class<? extends IConduit> baseType, Offset offset, ForgeDirection dir, boolean isStub) {
return new CacheKey(baseType, offset, dir, isStub);
}
public Collection<CollidableComponent> getCollidables(CacheKey key, IConduit conduit) {
Collection<CollidableComponent> result = cache.get(key);
if(result == null) {
result = conduit.createCollidables(key);
cache.put(key, result);
}
return result;
}
public static class CacheKey {
public final Class<? extends IConduit> 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<? extends IConduit> 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;
}
}
}
@@ -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<? extends IConduit> conduitType;
public final BoundingBox bound;
public final ForgeDirection dir;
public final Object data;
public CollidableComponent(Class<? extends IConduit> 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 + "]";
}
}
@@ -0,0 +1,9 @@
package crazypants.enderio.conduit.geom;
public enum ConduitConnectorType {
VERTICAL,
HORIZONTAL,
BOTH
}
@@ -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<GeometryKey, BoundingBox> boundsCache = new HashMap<GeometryKey, BoundingBox>();
private EnumMap<ConduitConnectorType, BoundingBox> connectorBounds = new EnumMap<ConduitConnectorType, BoundingBox>(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<? extends IConduit> 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<? extends IConduit> type, GeometryKey key) {
return createConduitBounds(type, key.dir, key.isStub, key.offset);
}
private BoundingBox createConduitBounds(Class<? extends IConduit> 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;
}
}
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more