diff --git a/common/cofh/api/block/IDismantleable.java b/common/cofh/api/block/IDismantleable.java new file mode 100644 index 00000000..fd794378 --- /dev/null +++ b/common/cofh/api/block/IDismantleable.java @@ -0,0 +1,25 @@ +package cofh.api.block; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +/** + * Implemented on Blocks which have some method of being instantly dismantled. + * + * @author King Lemming + * + */ +public interface IDismantleable { + + /** + * Dismantles the block. If returnBlock is true, the drop(s) should be placed into the player's inventory. + */ + public ItemStack dismantleBlock(EntityPlayer player, World world, int x, int y, int z, boolean returnBlock); + + /** + * Return true if the block can be dismantled. The criteria for this is entirely up to the block. + */ + public boolean canDismantle(EntityPlayer player, World world, int x, int y, int z); + +} diff --git a/common/cofh/api/core/IInitializer.java b/common/cofh/api/core/IInitializer.java new file mode 100644 index 00000000..b507e6bc --- /dev/null +++ b/common/cofh/api/core/IInitializer.java @@ -0,0 +1,17 @@ +package cofh.api.core; + +/** + * Interface which can be put on just about anything to allow for iteration during initialization. + * + * @author King Lemming + * + */ +public interface IInitializer { + + public boolean preInit(); + + public boolean initialize(); + + public boolean postInit(); + +} diff --git a/common/cofh/api/core/ISimpleRegistry.java b/common/cofh/api/core/ISimpleRegistry.java new file mode 100644 index 00000000..1ffe2cb7 --- /dev/null +++ b/common/cofh/api/core/ISimpleRegistry.java @@ -0,0 +1,22 @@ +package cofh.api.core; + +/** + * Basic interface for the Cape and Skin Registries. + * + * @author Zeldo Kavira + * + */ +public interface ISimpleRegistry { + + /** + * Register a new entry. + * + * @param playerName + * The player to register. + * @param URL + * Location of the cape/skin. + * @return True if registration was successful. + */ + public boolean register(String playerName, String URL); + +} diff --git a/common/cofh/api/core/NullSimpleRegistry.java b/common/cofh/api/core/NullSimpleRegistry.java new file mode 100644 index 00000000..df95dae5 --- /dev/null +++ b/common/cofh/api/core/NullSimpleRegistry.java @@ -0,0 +1,17 @@ +package cofh.api.core; + +/** + * Dummy class used to initialize Cape and Skin Registries to prevent accidental NPEs. + * + * @author Zeldo Kavira + * + */ +public class NullSimpleRegistry implements ISimpleRegistry { + + @Override + public boolean register(String playerName, String URL) { + + return false; + } + +} diff --git a/common/cofh/api/core/RegistryAccess.java b/common/cofh/api/core/RegistryAccess.java new file mode 100644 index 00000000..c1c04957 --- /dev/null +++ b/common/cofh/api/core/RegistryAccess.java @@ -0,0 +1,14 @@ +package cofh.api.core; + +/** + * Access to the Cape and Skin Registries of CoFH Core. + * + * @author Zeldo Kavira + * + */ +public class RegistryAccess { + + public static ISimpleRegistry capeRegistry = new NullSimpleRegistry(); + public static ISimpleRegistry skinRegistry = new NullSimpleRegistry(); + +} diff --git a/common/cofh/api/energy/EnergyStorage.java b/common/cofh/api/energy/EnergyStorage.java new file mode 100644 index 00000000..e7aef31d --- /dev/null +++ b/common/cofh/api/energy/EnergyStorage.java @@ -0,0 +1,152 @@ +package cofh.api.energy; + +import net.minecraft.nbt.NBTTagCompound; +import cofh.util.MathHelper; + +/** + * Reference implementation of {@link IEnergyStorage}. Use/extend this or implement your own. + * + * @author King Lemming + * + */ +public class EnergyStorage implements IEnergyStorage { + + protected int energy; + protected int capacity; + protected int maxReceive; + protected int maxExtract; + + public EnergyStorage(int capacity) { + + this(capacity, capacity, capacity); + } + + public EnergyStorage(int capacity, int maxTransfer) { + + this(capacity, maxTransfer, maxTransfer); + } + + public EnergyStorage(int capacity, int maxReceive, int maxExtract) { + + this.capacity = capacity; + this.maxReceive = maxReceive; + this.maxExtract = maxExtract; + } + + public EnergyStorage readFromNBT(NBTTagCompound nbt) { + + this.energy = nbt.getInteger("Energy"); + return this; + } + + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + + nbt.setInteger("Energy", energy); + return nbt; + } + + public void setCapacity(int capacity) { + + this.capacity = capacity; + + if (energy > capacity) { + energy = capacity; + } + } + + public void setMaxTransfer(int maxTransfer) { + + setMaxReceive(maxTransfer); + setMaxExtract(maxTransfer); + } + + public void setMaxReceive(int maxReceive) { + + this.maxReceive = maxReceive; + } + + public void setMaxExtract(int maxExtract) { + + this.maxExtract = maxExtract; + } + + public int getMaxReceive() { + + return maxReceive; + } + + public int getMaxExtract() { + + return maxExtract; + } + + /** + * This function is included to allow for server -> client sync. Do not call this externally to the containing Tile Entity, as not all IEnergyHandlers are + * guaranteed to have it. + * + * @param energy + */ + public void setEnergyStored(int energy) { + + this.energy = energy; + + if (this.energy > capacity) { + this.energy = capacity; + } else if (this.energy < 0) { + this.energy = 0; + } + } + + /** + * This function is included to allow the containing tile to directly and efficiently modify the energy contained in the EnergyStorage. Do not rely on this + * externally, as not all IEnergyHandlers are guaranteed to have it. + * + * @param energy + */ + public void modifyEnergyStored(int energy) { + + this.energy += energy; + + if (this.energy > capacity) { + this.energy = capacity; + } else if (this.energy < 0) { + this.energy = 0; + } + } + + /* IEnergyStorage */ + @Override + public int receiveEnergy(int maxReceive, boolean simulate) { + + int energyReceived = MathHelper.minI(capacity - energy, MathHelper.minI(this.maxReceive, maxReceive)); + + if (!simulate) { + energy += energyReceived; + } + return energyReceived; + } + + @Override + public int extractEnergy(int maxExtract, boolean simulate) { + + int energyExtracted = MathHelper.minI(energy, MathHelper.minI(this.maxExtract, maxExtract)); + + if (!simulate) { + energy -= energyExtracted; + } + return energyExtracted; + } + + @Override + public int getEnergyStored() { + + return energy; + } + + @Override + public int getMaxEnergyStored() { + + return capacity; + } + +} diff --git a/common/cofh/api/energy/IEnergyContainerItem.java b/common/cofh/api/energy/IEnergyContainerItem.java new file mode 100644 index 00000000..e01be6e4 --- /dev/null +++ b/common/cofh/api/energy/IEnergyContainerItem.java @@ -0,0 +1,51 @@ +package cofh.api.energy; + +import net.minecraft.item.ItemStack; + +/** + * Implement this interface on Item classes that support external manipulation of their internal energy storages. + * + * A reference implementation is provided {@link ItemEnergyContainer}. + * + * @author King Lemming + * + */ +public interface IEnergyContainerItem { + + /** + * Adds energy to an item. Returns the quantity of energy that was accepted. This should always return 0 if the item cannot be externally charged. + * + * @param container + * ItemStack to be charged. + * @param maxReceive + * Maximum amount of energy to be sent into the item. + * @param simulate + * If TRUE, the charge will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) received by the item. + */ + int receiveEnergy(ItemStack container, int maxReceive, boolean simulate); + + /** + * Removes energy from an item. Returns the quantity of energy that was removed. This should always return 0 if the item cannot be externally discharged. + * + * @param container + * ItemStack to be discharged. + * @param maxExtract + * Maximum amount of energy to be extracted from the item. + * @param simulate + * If TRUE, the discharge will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) extracted from the item. + */ + int extractEnergy(ItemStack container, int maxExtract, boolean simulate); + + /** + * Get the amount of energy currently stored in the item. + */ + int getEnergyStored(ItemStack container); + + /** + * Get the max amount of energy that can be stored in the item. + */ + int getMaxEnergyStored(ItemStack container); + +} diff --git a/common/cofh/api/energy/IEnergyHandler.java b/common/cofh/api/energy/IEnergyHandler.java new file mode 100644 index 00000000..67171609 --- /dev/null +++ b/common/cofh/api/energy/IEnergyHandler.java @@ -0,0 +1,56 @@ +package cofh.api.energy; + +import net.minecraftforge.common.ForgeDirection; + +/** + * Implement this interface on TileEntities which should handle energy, generally storing it in one or more internal {@link IEnergyStorage} objects. + * + * A reference implementation is provided {@link TileEnergyHandler}. + * + * @author King Lemming + * + */ +public interface IEnergyHandler { + + /** + * Add energy to an IEnergyHandler, internal distribution is left entirely to the IEnergyHandler. + * + * @param from + * Orientation the energy is received from. + * @param maxReceive + * Maximum amount of energy to received. + * @param simulate + * If TRUE, the charge will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) received. + */ + int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate); + + /** + * Remove energy from an IEnergyHandler, internal distribution is left entirely to the IEnergyHandler. + * + * @param from + * Orientation the energy is extracted to. + * @param maxExtract + * Maximum amount of energy to extract. + * @param simulate + * If TRUE, the discharge will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) extracted. + */ + int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate); + + /** + * Returns true if the Handler functions on a given side - if a Tile Entity can receive and/or send energy from a given side, this should return true. + */ + boolean canInterface(ForgeDirection from); + + /** + * Returns the amount of energy currently stored. + */ + int getEnergyStored(ForgeDirection from); + + /** + * Returns the maximum amount of energy that can be stored. + */ + int getMaxEnergyStored(ForgeDirection from); + +} diff --git a/common/cofh/api/energy/IEnergyStorage.java b/common/cofh/api/energy/IEnergyStorage.java new file mode 100644 index 00000000..1e84bc22 --- /dev/null +++ b/common/cofh/api/energy/IEnergyStorage.java @@ -0,0 +1,45 @@ +package cofh.api.energy; + +/** + * An energy storage is the unit of interaction with Energy inventories. + * + * A reference implementation can be found at {@link EnergyStorage}. + * + * @author King Lemming + * + */ +public interface IEnergyStorage { + + /** + * Adds energy to the storage. Returns quantity of energy that was accepted. + * + * @param maxReceive + * Maximum amount of energy to be inserted. + * @param simulate + * If TRUE, the insertion will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) accepted by the storage. + */ + int receiveEnergy(int maxReceive, boolean simulate); + + /** + * Removes energy from the storage. Returns quantity of energy that was removed. + * + * @param maxExtract + * Maximum amount of energy to be extracted. + * @param simulate + * If TRUE, the extraction will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) extracted from the storage. + */ + int extractEnergy(int maxExtract, boolean simulate); + + /** + * Returns the amount of energy currently stored. + */ + int getEnergyStored(); + + /** + * Returns the maximum amount of energy that can be stored. + */ + int getMaxEnergyStored(); + +} diff --git a/common/cofh/api/energy/ItemEnergyContainer.java b/common/cofh/api/energy/ItemEnergyContainer.java new file mode 100644 index 00000000..f502b7ed --- /dev/null +++ b/common/cofh/api/energy/ItemEnergyContainer.java @@ -0,0 +1,113 @@ +package cofh.api.energy; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import cofh.util.MathHelper; + +/** + * Reference implementation of {@link IEnergyContainerItem}. Use/extend this or implement your own. + * + * @author King Lemming + * + */ +public class ItemEnergyContainer extends Item implements IEnergyContainerItem { + + protected int capacity; + protected int maxReceive; + protected int maxExtract; + + public ItemEnergyContainer(int itemID) { + + super(itemID); + } + + public ItemEnergyContainer(int itemID, int capacity) { + + this(itemID, capacity, capacity, capacity); + } + + public ItemEnergyContainer(int itemID, int capacity, int maxTransfer) { + + this(itemID, capacity, maxTransfer, maxTransfer); + } + + public ItemEnergyContainer(int itemID, int capacity, int maxReceive, int maxExtract) { + + super(itemID); + this.capacity = capacity; + this.maxReceive = maxReceive; + this.maxExtract = maxExtract; + } + + public ItemEnergyContainer setCapacity(int capacity) { + + this.capacity = capacity; + return this; + } + + public void setMaxTransfer(int maxTransfer) { + + setMaxReceive(maxTransfer); + setMaxExtract(maxTransfer); + } + + public void setMaxReceive(int maxReceive) { + + this.maxReceive = maxReceive; + } + + public void setMaxExtract(int maxExtract) { + + this.maxExtract = maxExtract; + } + + /* IEnergyContainerItem */ + @Override + public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) { + + if (container.stackTagCompound == null) { + container.stackTagCompound = new NBTTagCompound(); + } + int energy = container.stackTagCompound.getInteger("Energy"); + int energyReceived = MathHelper.minI(capacity - energy, MathHelper.minI(this.maxReceive, maxReceive)); + + if (!simulate) { + energy += energyReceived; + container.stackTagCompound.setInteger("Energy", energy); + } + return energyReceived; + } + + @Override + public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) { + + if (container.stackTagCompound == null || !container.stackTagCompound.hasKey("Energy")) { + return 0; + } + int energy = container.stackTagCompound.getInteger("Energy"); + int energyExtracted = MathHelper.minI(energy, MathHelper.minI(this.maxExtract, maxExtract)); + + if (!simulate) { + energy -= energyExtracted; + container.stackTagCompound.setInteger("Energy", energy); + } + return energyExtracted; + } + + @Override + public int getEnergyStored(ItemStack container) { + + if (container.stackTagCompound == null || !container.stackTagCompound.hasKey("Energy")) { + return 0; + } + return container.stackTagCompound.getInteger("Energy"); + } + + @Override + public int getMaxEnergyStored(ItemStack container) { + + return capacity; + } + +} diff --git a/common/cofh/api/energy/TileEnergyHandler.java b/common/cofh/api/energy/TileEnergyHandler.java new file mode 100644 index 00000000..4eb49fd8 --- /dev/null +++ b/common/cofh/api/energy/TileEnergyHandler.java @@ -0,0 +1,62 @@ +package cofh.api.energy; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.ForgeDirection; + +/** + * Reference implementation of {@link IEnergyHandler}. Use/extend this or implement your own. + * + * @author King Lemming + * + */ +public class TileEnergyHandler extends TileEntity implements IEnergyHandler { + + protected EnergyStorage storage = new EnergyStorage(32000); + + @Override + public void readFromNBT(NBTTagCompound nbt) { + + super.readFromNBT(nbt); + storage.readFromNBT(nbt); + } + + @Override + public void writeToNBT(NBTTagCompound nbt) { + + super.writeToNBT(nbt); + storage.writeToNBT(nbt); + } + + /* IEnergyHandler */ + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + + return storage.receiveEnergy(maxReceive, simulate); + } + + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + + return storage.extractEnergy(maxExtract, simulate); + } + + @Override + public boolean canInterface(ForgeDirection from) { + + return true; + } + + @Override + public int getEnergyStored(ForgeDirection from) { + + return storage.getEnergyStored(); + } + + @Override + public int getMaxEnergyStored(ForgeDirection from) { + + return storage.getMaxEnergyStored(); + } + +} diff --git a/common/cofh/api/item/IInventoryContainerItem.java b/common/cofh/api/item/IInventoryContainerItem.java new file mode 100644 index 00000000..73263a95 --- /dev/null +++ b/common/cofh/api/item/IInventoryContainerItem.java @@ -0,0 +1,20 @@ +package cofh.api.item; + +import net.minecraft.item.ItemStack; + +/** + * Implement this interface on Item classes that are themselves inventories. + * + * There's no real interaction here - the point of this is to correctly identify these items and prevent nesting. + * + * @author King Lemming + * + */ +public interface IInventoryContainerItem { + + /** + * Get the size of this inventory. + */ + int getSizeInventory(ItemStack stack); + +} diff --git a/common/cofh/api/tileentity/IEnergyInfo.java b/common/cofh/api/tileentity/IEnergyInfo.java new file mode 100644 index 00000000..c3018183 --- /dev/null +++ b/common/cofh/api/tileentity/IEnergyInfo.java @@ -0,0 +1,19 @@ +package cofh.api.tileentity; + +/** + * Implement this interface on Tile Entities which can report information about their energy usage. + * + * @author King Lemming + * + */ +public interface IEnergyInfo { + + public int getEnergyPerTick(); + + public int getMaxEnergyPerTick(); + + public int getEnergy(); + + public int getMaxEnergy(); + +} diff --git a/common/cofh/api/tileentity/IReconfigurableFacing.java b/common/cofh/api/tileentity/IReconfigurableFacing.java new file mode 100644 index 00000000..df981096 --- /dev/null +++ b/common/cofh/api/tileentity/IReconfigurableFacing.java @@ -0,0 +1,39 @@ +package cofh.api.tileentity; + +/** + * Implement this interface on Tile Entities which allow for reconfiguration of their facing. + * + * Coordination with the containing block is required. + * + * @author King Lemming + * + */ +public interface IReconfigurableFacing { + + /** + * Returns the current facing of the block. + */ + public int getFacing(); + + /** + * Returns whether or not the block's face can be aligned with the Y Axis. + */ + public boolean allowYAxisFacing(); + + /** + * Attempt to rotate the block. Arbitrary based on implementation. + * + * @return True if rotation was successful, false otherwise. + */ + public boolean rotateBlock(); + + /** + * Set the facing of the block. + * + * @param side + * The side to set the facing to. + * @return True if the facing was set, false otherwise. + */ + public boolean setFacing(int side); + +} diff --git a/common/cofh/api/tileentity/IReconfigurableSides.java b/common/cofh/api/tileentity/IReconfigurableSides.java new file mode 100644 index 00000000..354d58db --- /dev/null +++ b/common/cofh/api/tileentity/IReconfigurableSides.java @@ -0,0 +1,54 @@ +package cofh.api.tileentity; + +/** + * Implement this interface on Tile Entities which allow for reconfiguration of their sides. + * + * Coordination with the containing block is required. + * + * @author King Lemming + * + */ +public interface IReconfigurableSides { + + /** + * Decrement the config for a given side. + * + * @param side + * The side to decrement. + * @return True if config was changed, false otherwise. + */ + public boolean decrSide(int side); + + /** + * Increment the config for a given side. + * + * @param side + * The side to decrement. + * @return True if config was changed, false otherwise. + */ + public boolean incrSide(int side); + + /** + * Set the config for a given side. + * + * @param side + * The side to set. + * @param config + * The config value to use. + * @return True of config was set, false otherwise. + */ + public boolean setSide(int side, int config); + + /** + * Reset configs on all sides to their base values. + * + * @return True if reset was successful, false otherwise. + */ + public boolean resetSides(); + + /** + * Returns the number of possible config settings for a given side. + */ + public int getNumConfig(int side); + +} diff --git a/common/cofh/api/tileentity/IRedstoneControl.java b/common/cofh/api/tileentity/IRedstoneControl.java new file mode 100644 index 00000000..0fd0014f --- /dev/null +++ b/common/cofh/api/tileentity/IRedstoneControl.java @@ -0,0 +1,21 @@ +package cofh.api.tileentity; + +/** + * Implement this interface on Tile Entities which have redstone control functionality. + * + * @author King Lemming + * + */ +public interface IRedstoneControl { + + public boolean getControlDisable(); + + public boolean getControlSetting(); + + public boolean setControlDisable(boolean disable); + + public boolean setControlSetting(boolean state); + + public boolean setRedstoneConfig(boolean disable, boolean state); + +} diff --git a/common/cofh/api/tileentity/ISecureTile.java b/common/cofh/api/tileentity/ISecureTile.java new file mode 100644 index 00000000..e5659ecc --- /dev/null +++ b/common/cofh/api/tileentity/ISecureTile.java @@ -0,0 +1,44 @@ +package cofh.api.tileentity; + +public interface ISecureTile { + + public static enum AccessMode { + PUBLIC, RESTRICTED, PRIVATE; + + public boolean isPublic() { + + return this == PUBLIC; + } + + public boolean isRestricted() { + + return this == RESTRICTED; + } + + public boolean isPrivate() { + + return this == PRIVATE; + } + + public static AccessMode stepForward(AccessMode curAccess) { + + return curAccess == AccessMode.PUBLIC ? AccessMode.RESTRICTED : curAccess == AccessMode.PRIVATE ? AccessMode.PUBLIC : AccessMode.PRIVATE; + } + + public static AccessMode stepBackward(AccessMode curAccess) { + + return curAccess == AccessMode.PUBLIC ? AccessMode.PRIVATE : curAccess == AccessMode.PRIVATE ? AccessMode.RESTRICTED : AccessMode.PUBLIC; + } + } + + public boolean setAccess(AccessMode access); + + public AccessMode getAccess(); + + public boolean setOwnerName(String name); + + public String getOwnerName(); + + public boolean canPlayerAccess(String name); + +} diff --git a/common/cofh/api/tileentity/ISidedBlockTexture.java b/common/cofh/api/tileentity/ISidedBlockTexture.java new file mode 100644 index 00000000..7f5d4d97 --- /dev/null +++ b/common/cofh/api/tileentity/ISidedBlockTexture.java @@ -0,0 +1,16 @@ +package cofh.api.tileentity; + +import net.minecraft.util.Icon; + +/** + * Implement this interface on Tile Entities which can change their block's texture based on the current render pass. The block must defer the call to its Tile + * Entity. + * + * @author Zeldo Kavira + * + */ +public interface ISidedBlockTexture { + + public Icon getBlockTexture(int side, int pass); + +} diff --git a/common/cofh/api/tileentity/ITileInfo.java b/common/cofh/api/tileentity/ITileInfo.java new file mode 100644 index 00000000..379b8fd7 --- /dev/null +++ b/common/cofh/api/tileentity/ITileInfo.java @@ -0,0 +1,19 @@ +package cofh.api.tileentity; + +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; + +/** + * Implement this interface on Tile Entities which can send state information through chat. + * + * @author Zeldo Kavira + * + */ +public interface ITileInfo { + + public List getTileInfo(); + + public void sendTileInfoToPlayer(EntityPlayer player); + +} diff --git a/common/cofh/api/transport/IItemConduit.java b/common/cofh/api/transport/IItemConduit.java new file mode 100644 index 00000000..36785493 --- /dev/null +++ b/common/cofh/api/transport/IItemConduit.java @@ -0,0 +1,19 @@ +package cofh.api.transport; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.ForgeDirection; + +/** + * This interface is implemented on Item Conduits. Use it to attempt to eject items into an entry point. + * + * @author Zeldo Kavira + * + */ +public interface IItemConduit { + + /** + * Insert items into the conduit. Returns the ItemStack left (null if fully routed). Will only accept items if they have an valid destination. + */ + public ItemStack sendItems(ItemStack item, ForgeDirection side); + +} diff --git a/common/cofh/api/transport/IItemConduitConnection.java b/common/cofh/api/transport/IItemConduitConnection.java new file mode 100644 index 00000000..150598b6 --- /dev/null +++ b/common/cofh/api/transport/IItemConduitConnection.java @@ -0,0 +1,15 @@ +package cofh.api.transport; + +import net.minecraftforge.common.ForgeDirection; + +/** + * Implement this interface to explicitly control sided Item Conduit connections for a Tile Entity. + * + * @author Zeldo Kavira + * + */ +public interface IItemConduitConnection { + + public boolean canConduitConnect(ForgeDirection side); + +} diff --git a/common/cofh/api/world/IFeatureGenerator.java b/common/cofh/api/world/IFeatureGenerator.java new file mode 100644 index 00000000..f0d732f3 --- /dev/null +++ b/common/cofh/api/world/IFeatureGenerator.java @@ -0,0 +1,39 @@ +package cofh.api.world; + +import java.util.Random; + +import net.minecraft.world.World; +import net.minecraft.world.gen.feature.WorldGenerator; + +/** + * This interface should be implemented on classes which define a world feature to be generated in a {@link IFeatureHandler}. It is essentially a more robust + * version of {@link WorldGenerator}, and may include one or more WorldGenerators should you wish. + * + * @author King Lemming + * + */ +public interface IFeatureGenerator { + + /** + * Returns the name of the feature, used for displaying in the World.cfg file. + */ + public String getFeatureName(); + + /** + * Generates the world feature. + * + * @param random + * Random derived from the world seed. + * @param chunkX + * Minimum X chunk-coordinate of the chunk. (x16 for block coordinate) + * @param chunkZ + * Minimum Z chunk-coordinate of the chunk. (x16 for block coordinate) + * @param world + * The world to generate in. + * @param newGen + * True on initial generation, false on retrogen. + * @return True if generation happened, false otherwise. + */ + public boolean generateFeature(Random random, int chunkX, int chunkZ, World world, boolean newGen); + +} diff --git a/common/cofh/api/world/IFeatureHandler.java b/common/cofh/api/world/IFeatureHandler.java new file mode 100644 index 00000000..eea078ce --- /dev/null +++ b/common/cofh/api/world/IFeatureHandler.java @@ -0,0 +1,22 @@ +package cofh.api.world; + +/** + * Provides an interface to allow for the addition of Features to world generation. + * + * See {@link IFeatureGenerator}. + * + * @author King Lemming + * + */ +public interface IFeatureHandler { + + /** + * Register a feature with an IFeatureHandler. + * + * @param feature + * The feature to register. + * @return True if the registration was successful, false if a feature with that name existed. + */ + public boolean registerFeature(IFeatureGenerator feature); + +} diff --git a/common/cofh/api/world/WeightedRandomBlock.java b/common/cofh/api/world/WeightedRandomBlock.java new file mode 100644 index 00000000..b841494e --- /dev/null +++ b/common/cofh/api/world/WeightedRandomBlock.java @@ -0,0 +1,31 @@ +package cofh.api.world; + +import net.minecraft.item.ItemStack; +import net.minecraft.util.WeightedRandomItem; + +/** + * This class essentially allows for ores to be generated in clusters, with Features randomly choosing one or more blocks from a weighted list. + * + * @author King Lemming + * + */ +public final class WeightedRandomBlock extends WeightedRandomItem { + + public final int blockId; + public final int metadata; + + public WeightedRandomBlock(ItemStack ore) { + + super(100); + this.blockId = ore.itemID; + this.metadata = ore.getItemDamage(); + } + + public WeightedRandomBlock(ItemStack ore, int weight) { + + super(weight); + this.blockId = ore.itemID; + this.metadata = ore.getItemDamage(); + } + +} diff --git a/common/cofh/util/MathHelper.java b/common/cofh/util/MathHelper.java new file mode 100644 index 00000000..a442353b --- /dev/null +++ b/common/cofh/util/MathHelper.java @@ -0,0 +1,183 @@ +package cofh.util; + +/** + * Contains various math-related helper functions. Often faster than conventional implementations. + * + * @author King Lemming + * + */ +public final class MathHelper { + + private MathHelper() { + + } + + public static final double PHI = 1.618034; + public static final double[] SIN_TABLE = new double[65536]; + + static { + for (int i = 0; i < 65536; i++) { + SIN_TABLE[i] = Math.sin(i / 65536D * 2 * Math.PI); + } + SIN_TABLE[0] = 0; + SIN_TABLE[16384] = 1; + SIN_TABLE[32768] = 0; + SIN_TABLE[49152] = 1; + } + + public static double sin(double d) { + + return SIN_TABLE[(int) ((float) d * 10430.378F) & 65535]; + } + + public static double cos(double d) { + + return SIN_TABLE[(int) ((float) d * 10430.378F + 16384.0F) & 65535]; + } + + public static float approachLinear(float a, float b, float max) { + + return a > b ? a - b < max ? b : a - max : b - a < max ? b : a + max; + } + + public static double approachLinear(double a, double b, double max) { + + return a > b ? a - b < max ? b : a - max : b - a < max ? b : a + max; + } + + public static float interpolate(float a, float b, float d) { + + return a + (b - a) * d; + } + + public static double interpolate(double a, double b, double d) { + + return a + (b - a) * d; + } + + public static double approachExp(double a, double b, double ratio) { + + return a + (b - a) * ratio; + } + + public static double approachExp(double a, double b, double ratio, double cap) { + + double d = (b - a) * ratio; + + if (Math.abs(d) > cap) { + d = Math.signum(d) * cap; + } + return a + d; + } + + public static double retreatExp(double a, double b, double c, double ratio, double kick) { + + double d = (Math.abs(c - a) + kick) * ratio; + + if (d > Math.abs(b - a)) { + return b; + } + return a + Math.signum(b - a) * d; + } + + public static double clip(double value, double min, double max) { + + if (value > max) { + value = max; + } else if (value < min) { + value = min; + } + return value; + } + + public static boolean between(double a, double x, double b) { + + return a <= x && x <= b; + } + + public static int approachExpI(int a, int b, double ratio) { + + int r = (int) Math.round(approachExp(a, b, ratio)); + return r == a ? b : r; + } + + public static int retreatExpI(int a, int b, int c, double ratio, int kick) { + + int r = (int) Math.round(retreatExp(a, b, c, ratio, kick)); + return r == a ? b : r; + } + + public static int floor_double(double d) { + + return net.minecraft.util.MathHelper.floor_double(d); + } + + /** + * Unchecked implementation to round a number. Parameter should be known to be valid in advance. + */ + public static int round(double d) { + + return (int) (d + 0.5D); + } + + /** + * Unchecked implementation to round a number up. Parameter should be known to be valid in advance. + */ + public static int ceil(double d) { + + return (int) (d + 0.9999D); + } + + /** + * Unchecked implementation to determine the smaller of two Floats. Parameters should be known to be valid in advance. + */ + public static float minF(float a, float b) { + + return a < b ? a : b; + } + + public static float minF(int a, float b) { + + return a < b ? a : b; + } + + public static float minF(float a, int b) { + + return a < b ? a : b; + } + + /** + * Unchecked implementation to determine the larger of two Floats. Parameters should be known to be valid in advance. + */ + public static float maxF(float a, float b) { + + return a > b ? a : b; + } + + public static float maxF(int a, float b) { + + return a > b ? a : b; + } + + public static float maxF(float a, int b) { + + return a > b ? a : b; + } + + /** + * Unchecked implementation to determine the smaller of two Integers. Parameters should be known to be valid in advance. + */ + public static int minI(int a, int b) { + + return a < b ? a : b; + } + + /** + * Unchecked implementation to determine the larger of two Integers. Parameters should be known to be valid in advance. + */ + public static int maxI(int a, int b) { + + return a > b ? a : b; + } + +} diff --git a/common/crazypants/enderio/conduit/TileConduitBundle.java b/common/crazypants/enderio/conduit/TileConduitBundle.java index 94578fde..01b07b32 100644 --- a/common/crazypants/enderio/conduit/TileConduitBundle.java +++ b/common/crazypants/enderio/conduit/TileConduitBundle.java @@ -543,6 +543,51 @@ public class TileConduitBundle extends TileEntity implements IConduitBundle { public World getWorld() { return worldObj; } + + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + IPowerConduit pc = getConduit(IPowerConduit.class); + if(pc != null) { + return pc.receiveEnergy(from, maxReceive, simulate); + } + return 0; + } + + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + IPowerConduit pc = getConduit(IPowerConduit.class); + if(pc != null) { + return pc.extractEnergy(from, maxExtract, simulate); + } + return 0; + } + + @Override + public boolean canInterface(ForgeDirection from) { + IPowerConduit pc = getConduit(IPowerConduit.class); + if(pc != null) { + return pc.canInterface(from); + } + return false; + } + + @Override + public int getEnergyStored(ForgeDirection from) { + IPowerConduit pc = getConduit(IPowerConduit.class); + if(pc != null) { + return pc.getEnergyStored(from); + } + return 0; + } + + @Override + public int getMaxEnergyStored(ForgeDirection from) { + IPowerConduit pc = getConduit(IPowerConduit.class); + if(pc != null) { + return pc.getMaxEnergyStored(from); + } + return 0; + } // ------- Liquids ----------------------------- diff --git a/common/crazypants/enderio/conduit/power/IPowerConduit.java b/common/crazypants/enderio/conduit/power/IPowerConduit.java index b9d233e8..f1d7bd20 100644 --- a/common/crazypants/enderio/conduit/power/IPowerConduit.java +++ b/common/crazypants/enderio/conduit/power/IPowerConduit.java @@ -6,6 +6,7 @@ import buildcraft.api.power.IPowerReceptor; import crazypants.enderio.conduit.IConduit; import crazypants.enderio.power.ICapacitor; import crazypants.enderio.power.IInternalPowerReceptor; +import crazypants.enderio.power.PowerInterface; public interface IPowerConduit extends IConduit, IInternalPowerReceptor { @@ -15,7 +16,7 @@ public interface IPowerConduit extends IConduit, IInternalPowerReceptor { public static final String ICON_CORE_KEY = "enderio:powerConduitCore"; public static final String ICON_TRANSMISSION_KEY = "enderio:powerConduitTransmission"; - IPowerReceptor getExternalPowerReceptor(ForgeDirection direction); + PowerInterface getExternalPowerReceptor(ForgeDirection direction); ICapacitor getCapacitor(); diff --git a/common/crazypants/enderio/conduit/power/NetworkPowerManager.java b/common/crazypants/enderio/conduit/power/NetworkPowerManager.java index 89e962e7..2ce82772 100644 --- a/common/crazypants/enderio/conduit/power/NetworkPowerManager.java +++ b/common/crazypants/enderio/conduit/power/NetworkPowerManager.java @@ -18,6 +18,7 @@ import crazypants.enderio.conduit.power.PowerConduitNetwork.ReceptorEntry; import crazypants.enderio.machine.power.TileCapacitorBank; import crazypants.enderio.power.IInternalPowerReceptor; import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.enderio.power.PowerInterface; import crazypants.util.BlockCoord; public class NetworkPowerManager { @@ -69,14 +70,14 @@ public class NetworkPowerManager { } public float getPowerInCapacitorBanks() { - if(capSupply == null) { + if (capSupply == null) { return 0; } return capSupply.stored; } public float getMaxPowerInCapacitorBanks() { - if(capSupply == null) { + if (capSupply == null) { return 0; } return capSupply.maxCap; @@ -84,19 +85,12 @@ public class NetworkPowerManager { public float getPowerInReceptors() { float result = 0; - Set done = new HashSet(); + Set done = new HashSet(); for (ReceptorEntry re : receptors) { - IPowerReceptor powerReceptor = re.powerReceptor; - if(!done.contains(powerReceptor)) { + PowerInterface powerReceptor = re.powerInterface; + if (!done.contains(powerReceptor)) { done.add(powerReceptor); - if(powerReceptor instanceof IInternalPowerReceptor) { - result += ((IInternalPowerReceptor) powerReceptor).getPowerHandler().getEnergyStored(); - } else { - PowerReceiver pr = powerReceptor.getPowerReceiver(re.direction); - if(pr != null) { - result += pr.getEnergyStored(); - } - } + result += powerReceptor.getEnergyStored(re.direction); } } return result; @@ -104,21 +98,12 @@ public class NetworkPowerManager { public float getMaxPowerInReceptors() { float result = 0; - Set done = new HashSet(); + Set done = new HashSet(); for (ReceptorEntry re : receptors) { - IPowerReceptor powerReceptor = re.powerReceptor; - if(!done.contains(powerReceptor)) { + PowerInterface powerReceptor = re.powerInterface; + if (!done.contains(powerReceptor)) { done.add(powerReceptor); - if(!(powerReceptor instanceof IPowerEmitter)) { - if(powerReceptor instanceof IInternalPowerReceptor) { - result += ((IInternalPowerReceptor) powerReceptor).getPowerHandler().getMaxEnergyStored(); - } else { - PowerReceiver pr = powerReceptor.getPowerReceiver(re.direction); - if(pr != null) { - result += pr.getMaxEnergyStored(); - } - } - } + result += powerReceptor.getMaxEnergyStored(re.direction); } } return result; @@ -141,21 +126,21 @@ public class NetworkPowerManager { float available = energyStored + capSupply.canExtract; float wasAvailable = available; - if(available <= 0 || (receptors.isEmpty() && storageReceptors.isEmpty())) { + if (available <= 0 || (receptors.isEmpty() && storageReceptors.isEmpty())) { trackerEndTick(); return; } while (available > 0 && appliedCount < numReceptors) { - if(!receptors.isEmpty() && !receptorIterator.hasNext()) { + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = receptors.listIterator(); } ReceptorEntry r = receptorIterator.next(); - if(r.emmiter.getPowerHandler().isPowerSource(r.direction)) { + if (r.emmiter.getPowerHandler().isPowerSource(r.direction)) { - //do a summy recieve or recieve energy counter will never tick down + // do a summy recieve or recieve energy counter will never tick down float es = r.emmiter.getPowerHandler().getEnergyStored(); PowerReceiver pr = r.emmiter.getPowerReceiver(r.direction.getOpposite()); pr.receiveEnergy(Type.STORAGE, 0, null); @@ -163,36 +148,29 @@ public class NetworkPowerManager { } else { - PowerReceiver pp = r.powerReceptor.getPowerReceiver(r.direction); - if(pp != null) { - if(pp.getType() != Type.ENGINE) { + PowerInterface pp = r.powerInterface; + if (pp != null) { - float used = 0; - float reservedForEntry = removeReservedEnergy(r); - available += reservedForEntry; - float canOffer = Math.min(r.emmiter.getMaxEnergyExtracted(r.direction), available); - float requested = pp.powerRequest(); - - // If it is possible to supply the minimum amount of energy - if(pp.getMinEnergyReceived() <= r.emmiter.getMaxEnergyExtracted(r.direction)) { - // Buffer energy if we can't meet it now - if(pp.getMinEnergyReceived() > canOffer && requested > 0) { - reserveEnergy(r, canOffer); - used += canOffer; - } else if(r.powerReceptor instanceof IInternalPowerReceptor) { - used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) r.powerReceptor, pp, canOffer, Type.PIPE, r.direction.getOpposite()); - trackerSend(r.emmiter, used, false); - } else { - float offer = Math.min(requested, canOffer); - used = pp.receiveEnergy(Type.PIPE, offer, r.direction.getOpposite()); - trackerSend(r.emmiter, used, false); - } + float used = 0; + float reservedForEntry = removeReservedEnergy(r); + available += reservedForEntry; + float canOffer = Math.min(r.emmiter.getMaxEnergyExtracted(r.direction), available); + float requested = pp.getPowerRequest(r.direction.getOpposite()); + // If it is possible to supply the minimum amount of energy + if (pp.getMinEnergyReceived(r.direction) <= r.emmiter.getMaxEnergyExtracted(r.direction)) { + // Buffer energy if we can't meet it now + if (pp.getMinEnergyReceived(r.direction) > canOffer && requested > 0) { + reserveEnergy(r, canOffer); + used += canOffer; + } else { + used = pp.recieveEnergy(r.direction.getOpposite(), canOffer); + trackerSend(r.emmiter, used, false); } available -= used; - } - if(available <= 0) { + + if (available <= 0) { break; } } @@ -206,19 +184,19 @@ public class NetworkPowerManager { energyStored -= used; float capBankChange = 0; - if(energyStored < 0) { + if (energyStored < 0) { // not enough so get the rest from the capacitor bank capBankChange = energyStored; energyStored = 0; - } else if(energyStored > 0) { + } else if (energyStored > 0) { // push as much as we can back to the cap banks capBankChange = Math.min(energyStored, capSupply.canFill); energyStored -= capBankChange; } - if(capBankChange < 0) { + if (capBankChange < 0) { capSupply.remove(Math.abs(capBankChange)); - } else if(capBankChange > 0) { + } else if (capBankChange > 0) { capSupply.add(capBankChange); } @@ -233,11 +211,11 @@ public class NetworkPowerManager { private void trackerStartTick() { - if(!Config.detailedPowerTrackingEnabled) { + if (!Config.detailedPowerTrackingEnabled) { return; } for (IPowerConduit con : network.getConduits()) { - if(con.hasExternalConnections()) { + if (con.hasExternalConnections()) { PowerTracker tracker = getOrCreateTracker(con); tracker.tickStart(con.getPowerHandler().getEnergyStored()); } @@ -245,31 +223,31 @@ public class NetworkPowerManager { } private void trackerSend(IPowerConduit con, float sent, boolean fromBank) { - if(!fromBank) { + if (!fromBank) { networkPowerTracker.powerSent(sent); } - if(!Config.detailedPowerTrackingEnabled) { + if (!Config.detailedPowerTrackingEnabled) { return; } getOrCreateTracker(con).powerSent(sent); } private void trackerRecieve(IPowerConduit con, float recieved, boolean fromBank) { - if(!fromBank) { + if (!fromBank) { networkPowerTracker.powerRecieved(recieved); } - if(!Config.detailedPowerTrackingEnabled) { + if (!Config.detailedPowerTrackingEnabled) { return; } getOrCreateTracker(con).powerRecieved(recieved); } private void trackerEndTick() { - if(!Config.detailedPowerTrackingEnabled) { + if (!Config.detailedPowerTrackingEnabled) { return; } for (IPowerConduit con : network.getConduits()) { - if(con.hasExternalConnections()) { + if (con.hasExternalConnections()) { PowerTracker tracker = getOrCreateTracker(con); tracker.tickEnd(con.getPowerHandler().getEnergyStored()); } @@ -278,7 +256,7 @@ public class NetworkPowerManager { private PowerTracker getOrCreateTracker(IPowerConduit con) { PowerTracker result = powerTrackers.get(con); - if(result == null) { + if (result == null) { result = new PowerTracker(); powerTrackers.put(con, result); } @@ -287,7 +265,7 @@ public class NetworkPowerManager { private void updateActiveState() { boolean active; - if(energyStored > 0) { + if (energyStored > 0) { ticksWithNoPower = 0; active = true; } else { @@ -296,7 +274,7 @@ public class NetworkPowerManager { } boolean doRender = active != lastActiveValue && (active || (!active && ticksWithNoPower > updateRenderTicks)); - if(doRender) { + if (doRender) { lastActiveValue = active; for (IPowerConduit con : network.getConduits()) { con.setActive(active); @@ -306,7 +284,7 @@ public class NetworkPowerManager { private float removeReservedEnergy(ReceptorEntry r) { StarveBuffer starveBuf = starveBuffers.remove(r.coord); - if(starveBuf == null) { + if (starveBuf == null) { return 0; } float result = starveBuf.stored; @@ -320,20 +298,20 @@ public class NetworkPowerManager { } private void checkReserves() { - if(reserved > maxEnergyStored * 0.9) { + if (reserved > maxEnergyStored * 0.9) { starveBuffers.clear(); reserved = 0; } } private void distributeStorageToConduits() { - if(maxEnergyStored <= 0 || energyStored <= 0) { + if (maxEnergyStored <= 0 || energyStored <= 0) { for (IPowerConduit con : network.getConduits()) { con.getPowerHandler().setEnergy(0); } return; } - if(energyStored > maxEnergyStored) { + if (energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } @@ -341,8 +319,9 @@ public class NetworkPowerManager { float energyLeft = energyStored; float given = 0; for (IPowerConduit con : network.getConduits()) { - if(energyLeft >= 0) { - // NB: use ceil to ensure we dont through away any energy due to rounding + if (energyLeft >= 0) { + // NB: use ceil to ensure we dont through away any energy due to + // rounding // errors float give = (float) Math.ceil(con.getCapacitor().getMaxEnergyStored() * filledRatio); give = Math.min(give, con.getCapacitor().getMaxEnergyStored()); @@ -368,7 +347,7 @@ public class NetworkPowerManager { energyStored += con.getPowerHandler().getEnergyStored(); } - if(energyStored > maxEnergyStored) { + if (energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } @@ -378,7 +357,7 @@ public class NetworkPowerManager { receptors.clear(); storageReceptors.clear(); for (ReceptorEntry rec : network.getPowerReceptors()) { - if(rec.powerReceptor instanceof TileCapacitorBank) { + if (rec.powerInterface.getDelegate() instanceof TileCapacitorBank) { storageReceptors.add(rec); } else { receptors.add(rec); @@ -405,7 +384,7 @@ public class NetworkPowerManager { } private float minAbs(float amount, float limit) { - if(amount < 0) { + if (amount < 0) { return Math.max(amount, -limit); } else { return Math.min(amount, limit); @@ -436,22 +415,22 @@ public class NetworkPowerManager { maxCap = 0; enteries = new ArrayList(); for (ReceptorEntry rec : storageReceptors) { - TileCapacitorBank cb = (TileCapacitorBank) rec.powerReceptor; + TileCapacitorBank cb = (TileCapacitorBank) rec.powerInterface.getDelegate(); - if(!capBanks.contains(cb)) { + if (!capBanks.contains(cb)) { stored += cb.getEnergyStored(); maxCap += cb.getMaxEnergyStored(); capBanks.add(cb); } float canGet = 0; - if(cb.isOutputEnabled()) { + if (cb.isOutputEnabled()) { canGet = Math.min(cb.getEnergyStored(), cb.getMaxOutput()); canGet = Math.min(canGet, rec.emmiter.getMaxEnergyRecieved(rec.direction)); canExtract += canGet; } float canFill = 0; - if(cb.isInputEnabled()) { + if (cb.isInputEnabled()) { canFill = Math.min(cb.getMaxEnergyStored() - cb.getEnergyStored(), cb.getMaxInput()); canFill = Math.min(canFill, rec.emmiter.getMaxEnergyExtracted(rec.direction)); this.canFill += canFill; @@ -461,13 +440,13 @@ public class NetworkPowerManager { } filledRatio = 0; - if(maxCap > 0) { + if (maxCap > 0) { filledRatio = stored / maxCap; } } void balance() { - if(enteries.size() < 2) { + if (enteries.size() < 2) { return; } init(); @@ -475,7 +454,7 @@ public class NetworkPowerManager { int canAdd = 0; for (CapBankSupplyEntry entry : enteries) { entry.calcToBalance(filledRatio); - if(entry.toBalance < 0) { + if (entry.toBalance < 0) { canRemove += -entry.toBalance; } else { canAdd += entry.toBalance; @@ -494,7 +473,7 @@ public class NetworkPowerManager { for (int j = i + 1; j < enteries.size() && toTranfser > 0; j++) { CapBankSupplyEntry to = enteries.get(j); - if(Math.signum(amount) != Math.signum(to.toBalance)) { + if (Math.signum(amount) != Math.signum(to.toBalance)) { float toAmount = Math.min(toTranfser, Math.abs(to.toBalance)); to.capBank.addEnergy(toAmount * Math.signum(to.toBalance)); toTranfser -= toAmount; @@ -506,7 +485,7 @@ public class NetworkPowerManager { } void remove(float amount) { - if(canExtract <= 0 || amount <= 0) { + if (canExtract <= 0 || amount <= 0) { return; } float ratio = amount / canExtract; @@ -518,14 +497,14 @@ public class NetworkPowerManager { entry.capBank.addEnergy(-(float) use); trackerRecieve(entry.emmiter, (float) use, true); amount -= use; - if(amount == 0) { + if (amount == 0) { return; } } } void add(float amount) { - if(canFill <= 0 || amount <= 0) { + if (canFill <= 0 || amount <= 0) { return; } float ratio = amount / canFill; @@ -537,7 +516,7 @@ public class NetworkPowerManager { entry.capBank.addEnergy((float) add); trackerSend(entry.emmiter, (float) add, true); amount -= add; - if(amount == 0) { + if (amount == 0) { return; } } @@ -562,7 +541,7 @@ public class NetworkPowerManager { void calcToBalance(float targetRatio) { float targetAmount = capBank.getMaxEnergyStored() * targetRatio; toBalance = targetAmount - capBank.getEnergyStored(); - if(toBalance < 0) { + if (toBalance < 0) { toBalance = Math.max(toBalance, -canExtract); } else { toBalance = Math.min(toBalance, canFill); diff --git a/common/crazypants/enderio/conduit/power/PowerConduit.java b/common/crazypants/enderio/conduit/power/PowerConduit.java index 5ea27d59..bb50de40 100644 --- a/common/crazypants/enderio/conduit/power/PowerConduit.java +++ b/common/crazypants/enderio/conduit/power/PowerConduit.java @@ -4,6 +4,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import cofh.api.energy.IEnergyHandler; + import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -29,6 +31,7 @@ import crazypants.enderio.conduit.geom.CollidableComponent; import crazypants.enderio.power.BasicCapacitor; import crazypants.enderio.power.ICapacitor; import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.enderio.power.PowerInterface; import crazypants.render.BoundingBox; import crazypants.render.IconUtil; import crazypants.util.BlockCoord; @@ -212,6 +215,34 @@ public class PowerConduit extends AbstractConduit implements IPowerConduit { return getBundle().getEntity().worldObj; } + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + if(getMaxEnergyRecieved(from) == 0) { + return 0; + } + return PowerHandlerUtil.recieveRedstoneFlux(from, powerHandler, maxReceive, simulate); + } + + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + return 0; + } + + @Override + public boolean canInterface(ForgeDirection from) { + return true; + } + + @Override + public int getEnergyStored(ForgeDirection from) { + return (int)(powerHandler.getEnergyStored() * 10); + } + + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return (int)(powerHandler.getMaxEnergyStored() * 10); + } + @Override public AbstractConduitNetwork getNetwork() { return network; @@ -225,11 +256,8 @@ public class PowerConduit extends AbstractConduit implements IPowerConduit { @Override public boolean canConnectToExternal(ForgeDirection direction) { - IPowerReceptor rec = getExternalPowerReceptor(direction); - if(rec instanceof IPowerEmitter) { - return ((IPowerEmitter) rec).canEmitPowerFrom(direction.getOpposite()); - } - return rec != null && PowerHandlerUtil.canConnectRecievePower(rec); + PowerInterface rec = getExternalPowerReceptor(direction); + return rec != null && rec.canConduitConnect(direction); } @Override @@ -252,20 +280,20 @@ public class PowerConduit extends AbstractConduit implements IPowerConduit { } @Override - public IPowerReceptor getExternalPowerReceptor(ForgeDirection direction) { + public PowerInterface getExternalPowerReceptor(ForgeDirection direction) { TileEntity te = bundle.getEntity(); World world = te.worldObj; if(world == null) { return null; } TileEntity test = world.getBlockTileEntity(te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ); + if(test == null) { + return null; + } if(test instanceof IConduitBundle) { return null; - } - if(test instanceof IPowerReceptor) { - return (IPowerReceptor) test; - } - return null; + } + return PowerInterface.create(test); } @Override diff --git a/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java b/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java index 49a06a56..cf8d552d 100644 --- a/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java +++ b/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java @@ -7,6 +7,8 @@ import java.util.List; import java.util.Map; import java.util.Set; +import cofh.api.energy.IEnergyHandler; + import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; @@ -14,6 +16,8 @@ import buildcraft.api.power.IPowerReceptor; import crazypants.enderio.conduit.AbstractConduitNetwork; import crazypants.enderio.conduit.IConduit; import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.machine.power.TileCapacitorBank; +import crazypants.enderio.power.PowerInterface; import crazypants.util.BlockCoord; public class PowerConduitNetwork extends AbstractConduitNetwork { @@ -54,7 +58,7 @@ public class PowerConduitNetwork extends AbstractConduitNetwork { super.addConduit(con); Set externalDirs = con.getExternalConnections(); for (ForgeDirection dir : externalDirs) { - IPowerReceptor pr = con.getExternalPowerReceptor(dir); + PowerInterface pr = con.getExternalPowerReceptor(dir); if(pr != null) { TileEntity te = con.getBundle().getEntity(); powerReceptorAdded(con, dir, te.xCoord + dir.offsetX, te.yCoord + dir.offsetY, te.zCoord + dir.offsetZ, pr); @@ -70,7 +74,7 @@ public class PowerConduitNetwork extends AbstractConduitNetwork { return IPowerConduit.class; } - public void powerReceptorAdded(IPowerConduit powerConduit, ForgeDirection direction, int x, int y, int z, IPowerReceptor powerReceptor) { + public void powerReceptorAdded(IPowerConduit powerConduit, ForgeDirection direction, int x, int y, int z, PowerInterface powerReceptor) { if(powerReceptor == null) { return; } @@ -123,12 +127,13 @@ public class PowerConduitNetwork extends AbstractConduitNetwork { public static class ReceptorEntry { IPowerConduit emmiter; - IPowerReceptor powerReceptor; BlockCoord coord; ForgeDirection direction; + + PowerInterface powerInterface; - public ReceptorEntry(IPowerReceptor powerReceptor, BlockCoord coord, IPowerConduit emmiter, ForgeDirection direction) { - this.powerReceptor = powerReceptor; + public ReceptorEntry(PowerInterface powerReceptor, BlockCoord coord, IPowerConduit emmiter, ForgeDirection direction) { + powerInterface =powerReceptor; this.coord = coord; this.emmiter = emmiter; this.direction = direction; diff --git a/common/crazypants/enderio/machine/AbstractMachineEntity.java b/common/crazypants/enderio/machine/AbstractMachineEntity.java index a309014d..1f243e39 100644 --- a/common/crazypants/enderio/machine/AbstractMachineEntity.java +++ b/common/crazypants/enderio/machine/AbstractMachineEntity.java @@ -183,6 +183,34 @@ public abstract class AbstractMachineEntity extends TileEntity implements IInven protected float getPowerUsePerTick() { return capacitorType.capacitor.getMaxEnergyExtracted(); } + + // RF Power + + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + return PowerHandlerUtil.recieveRedstoneFlux(from, powerHandler, maxReceive, simulate); + } + + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + return 0; + } + + @Override + public boolean canInterface(ForgeDirection from) { + return true; + } + + @Override + public int getEnergyStored(ForgeDirection from) { + return (int)(powerHandler.getEnergyStored() * 10); + } + + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return (int)(powerHandler.getMaxEnergyStored() * 10); + } + // --- Process Loop // -------------------------------------------------------------------------- diff --git a/common/crazypants/enderio/machine/generator/TileEntityStirlingGenerator.java b/common/crazypants/enderio/machine/generator/TileEntityStirlingGenerator.java index c64f3173..fdd88ad0 100644 --- a/common/crazypants/enderio/machine/generator/TileEntityStirlingGenerator.java +++ b/common/crazypants/enderio/machine/generator/TileEntityStirlingGenerator.java @@ -12,15 +12,12 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraftforge.common.ForgeDirection; import buildcraft.api.power.IPowerEmitter; -import buildcraft.api.power.IPowerReceptor; -import buildcraft.api.power.PowerHandler.PowerReceiver; import buildcraft.api.power.PowerHandler.Type; import crazypants.enderio.ModObject; import crazypants.enderio.machine.AbstractMachineEntity; import crazypants.enderio.machine.SlotDefinition; import crazypants.enderio.power.Capacitors; -import crazypants.enderio.power.IInternalPowerReceptor; -import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.enderio.power.PowerInterface; import crazypants.util.BlockCoord; public class TileEntityStirlingGenerator extends AbstractMachineEntity implements ISidedInventory, IPowerEmitter { @@ -171,19 +168,13 @@ public class TileEntityStirlingGenerator extends AbstractMachineEntity implement int appliedCount = 0; int numReceptors = receptors.size(); while (receptorIterator.hasNext() && canTransmit > 0 && appliedCount < numReceptors) { - Receptor receptor = receptorIterator.next(); - PowerReceiver pp = receptor.receptor.getPowerReceiver(receptor.fromDir.getOpposite()); - if(pp != null && pp.getMinEnergyReceived() <= canTransmit && pp.getType() != Type.ENGINE) { - float used; - if(receptor.receptor instanceof IInternalPowerReceptor) { - used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) receptor.receptor, pp, canTransmit, Type.ENGINE, receptor.fromDir.getOpposite()); - } else { - used = pp.receiveEnergy(Type.ENGINE, canTransmit, receptor.fromDir.getOpposite()); - } + PowerInterface pp = receptor.receptor; + if (pp != null && pp.getMinEnergyReceived(receptor.fromDir.getOpposite()) <= canTransmit) { + float used = pp.recieveEnergy(receptor.fromDir.getOpposite(), canTransmit); transmitted += used; canTransmit -= used; - } + } if(canTransmit <= 0) { break; } @@ -210,10 +201,10 @@ public class TileEntityStirlingGenerator extends AbstractMachineEntity implement for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { BlockCoord checkLoc = bc.getLocation(dir); TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); - if(te instanceof IPowerReceptor) { - IPowerReceptor rec = (IPowerReceptor) te; - receptors.add(new Receptor((IPowerReceptor) te, dir)); - } + PowerInterface pi = PowerInterface.create(te); + if(pi != null) { + receptors.add(new Receptor(pi, dir)); + } } receptorIterator = receptors.listIterator(); receptorsDirty = false; @@ -221,11 +212,10 @@ public class TileEntityStirlingGenerator extends AbstractMachineEntity implement } static class Receptor { - IPowerReceptor receptor; + PowerInterface receptor; ForgeDirection fromDir; - private Receptor(IPowerReceptor rec, ForgeDirection fromDir) { - super(); + private Receptor(PowerInterface rec, ForgeDirection fromDir) { this.receptor = rec; this.fromDir = fromDir; } diff --git a/common/crazypants/enderio/machine/hypercube/TileHyperCube.java b/common/crazypants/enderio/machine/hypercube/TileHyperCube.java index d64dcba0..5ff88f02 100644 --- a/common/crazypants/enderio/machine/hypercube/TileHyperCube.java +++ b/common/crazypants/enderio/machine/hypercube/TileHyperCube.java @@ -14,7 +14,6 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; -import buildcraft.api.power.IPowerReceptor; import buildcraft.api.power.PowerHandler; import buildcraft.api.power.PowerHandler.PowerReceiver; import buildcraft.api.power.PowerHandler.Type; @@ -24,6 +23,7 @@ import crazypants.enderio.machine.RedstoneControlMode; import crazypants.enderio.power.BasicCapacitor; import crazypants.enderio.power.IInternalPowerReceptor; import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.enderio.power.PowerInterface; import crazypants.util.BlockCoord; import crazypants.vecmath.VecmathUtil; @@ -111,7 +111,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, } private boolean isConnected() { - if(channel == null || HyperCubeRegister.instance == null) { + if (channel == null || HyperCubeRegister.instance == null) { return false; } List cons = HyperCubeRegister.instance.getCubesForChannel(channel); @@ -121,7 +121,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, private void balanceCubeNetworkEnergy() { List cubes = HyperCubeRegister.instance.getCubesForChannel(channel); - if(cubes == null || cubes.isEmpty()) { + if (cubes == null || cubes.isEmpty()) { return; } float totalEnergy = 0; @@ -132,7 +132,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, float energyPerNode = totalEnergy / cubes.size(); float totalToTranfer = 0; for (TileHyperCube cube : cubes) { - if(cube.powerHandler.getEnergyStored() < energyPerNode) { + if (cube.powerHandler.getEnergyStored() < energyPerNode) { totalToTranfer += (energyPerNode - cube.powerHandler.getEnergyStored()); } } @@ -145,7 +145,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, for (TileHyperCube cube : cubes) { boolean wasConnected = cube.isConnected(); cube.powerHandler.setEnergy(energyPerNode); - if(wasConnected != cube.isConnected()) { + if (wasConnected != cube.isConnected()) { cube.fluidHandlersDirty = true; } } @@ -154,7 +154,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, @Override public void onChunkUnload() { - if(HyperCubeRegister.instance != null) { + if (HyperCubeRegister.instance != null) { HyperCubeRegister.instance.deregister(this); } } @@ -166,10 +166,10 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, @Override public void updateEntity() { - if(worldObj == null) { // sanity check + if (worldObj == null) { // sanity check return; } - if(worldObj.isRemote) { + if (worldObj.isRemote) { return; } // else is server, do all logic only on the server @@ -183,12 +183,12 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, boolean wasConnected = isConnected(); - //Pay upkeep cost + // Pay upkeep cost stored -= ENERGY_UPKEEP; - //Pay fluid transmission cost + // Pay fluid transmission cost stored -= (MILLIBUCKET_TRANSMISSION_COST * milliBucketsTransfered); - //update power status + // update power status stored = Math.max(stored, 0); powerHandler.setEnergy(stored); @@ -197,21 +197,22 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, powerInputEnabled = RedstoneControlMode.isConditionMet(inputControlMode, this); powerOutputEnabled = RedstoneControlMode.isConditionMet(outputControlMode, this); - if(powerOutputEnabled) { + if (powerOutputEnabled) { transmitEnergy(); } balanceCubeNetworkEnergy(); - //check we are still connected (i.e. we haven't run out of power or started receiving power) + // check we are still connected (i.e. we haven't run out of power or started + // receiving power) boolean stillConnected = isConnected(); - if(wasConnected != stillConnected) { + if (wasConnected != stillConnected) { fluidHandlersDirty = true; } updateFluidHandlers(); - if(registeredChannel == null ? channel != null : !registeredChannel.equals(channel)) { - if(registeredChannel != null) { + if (registeredChannel == null ? channel != null : !registeredChannel.equals(channel)) { + if (registeredChannel != null) { HyperCubeRegister.instance.deregister(this, registeredChannel); } HyperCubeRegister.instance.register(this); @@ -224,7 +225,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, // Update if our power has changed by more than 0.5% requiresClientSync |= lastSyncPowerStored != storedEnergy && worldObj.getTotalWorldTime() % 21 == 0; - if(requiresClientSync) { + if (requiresClientSync) { lastSyncPowerStored = storedEnergy; // this will cause 'getPacketDescription()' to be called and its result // will be sent to the PacketHandler on the other end of @@ -238,7 +239,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, private boolean transmitEnergy() { - if(powerHandler.getEnergyStored() <= 0) { + if (powerHandler.getEnergyStored() <= 0) { return false; } float canTransmit = Math.min(powerHandler.getEnergyStored(), internalCapacitor.getMaxEnergyExtracted()); @@ -246,35 +247,25 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, checkReceptors(); - if(!receptors.isEmpty() && !receptorIterator.hasNext()) { + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = receptors.listIterator(); } int appliedCount = 0; int numReceptors = receptors.size(); while (receptorIterator.hasNext() && canTransmit > 0 && appliedCount < numReceptors) { - Receptor receptor = receptorIterator.next(); - PowerReceiver pp = receptor.receptor.getPowerReceiver(receptor.fromDir.getOpposite()); - if(pp != null && pp.getMinEnergyReceived() <= canTransmit && pp.getType() != Type.ENGINE && !powerHandler.isPowerSource(receptor.fromDir)) { - float used; - float boundCanTransmit = Math.min(canTransmit, pp.getMaxEnergyReceived()); - if(boundCanTransmit > 0) { - if(receptor.receptor instanceof IInternalPowerReceptor) { - used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) receptor.receptor, pp, boundCanTransmit, Type.STORAGE, - receptor.fromDir.getOpposite()); - } else { - used = pp.receiveEnergy(Type.STORAGE, boundCanTransmit, receptor.fromDir.getOpposite()); - } - transmitted += used; - canTransmit -= used; - } + PowerInterface pp = receptor.receptor; + if (pp != null && pp.getMinEnergyReceived(receptor.fromDir.getOpposite()) <= canTransmit) { + float used = pp.recieveEnergy(receptor.fromDir.getOpposite(), canTransmit); + transmitted += used; + canTransmit -= used; } - if(canTransmit <= 0) { + if (canTransmit <= 0) { break; } - if(!receptors.isEmpty() && !receptorIterator.hasNext()) { + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = receptors.listIterator(); } appliedCount++; @@ -297,7 +288,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, @Override public PowerHandler getPowerHandler() { - if(powerInputEnabled) { + if (powerInputEnabled) { return powerHandler; } return getDisabledPowerHandler(); @@ -308,12 +299,42 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, } private PowerHandler getDisabledPowerHandler() { - if(disabledPowerHandler == null) { + if (disabledPowerHandler == null) { disabledPowerHandler = PowerHandlerUtil.createHandler(new BasicCapacitor(0, 0), this, Type.STORAGE); } return disabledPowerHandler; } + // RF Power + + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + if(powerInputEnabled) { + return PowerHandlerUtil.recieveRedstoneFlux(from, powerHandler, maxReceive, simulate); + } + return 0; + } + + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + return 0; + } + + @Override + public boolean canInterface(ForgeDirection from) { + return true; + } + + @Override + public int getEnergyStored(ForgeDirection from) { + return (int) (powerHandler.getEnergyStored() * 10); + } + + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return (int) (powerHandler.getMaxEnergyStored() * 10); + } + @Override public void doWork(PowerHandler workProvider) { } @@ -323,7 +344,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, } private void checkReceptors() { - if(!receptorsDirty) { + if (!receptorsDirty) { return; } receptors.clear(); @@ -331,9 +352,9 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { BlockCoord checkLoc = myLoc.getLocation(dir); TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); - if(te instanceof IPowerReceptor) { - IPowerReceptor rec = (IPowerReceptor) te; - receptors.add(new Receptor((IPowerReceptor) te, dir)); + PowerInterface pi = PowerInterface.create(te); + if(pi != null) { + receptors.add(new Receptor(pi, dir)); } } @@ -343,19 +364,19 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - if(!powerInputEnabled) { + if (!powerInputEnabled) { return 0; } FluidStack in = resource.copy(); int result = 0; for (NetworkFluidHandler h : getNetworkHandlers()) { - if(h.node.powerOutputEnabled && h.handler.canFill(h.dirOp, in.getFluid())) { + if (h.node.powerOutputEnabled && h.handler.canFill(h.dirOp, in.getFluid())) { int filled = h.handler.fill(h.dirOp, in, doFill); in.amount -= filled; result += filled; } } - if(doFill) { + if (doFill) { milliBucketsTransfered += result; } return result; @@ -363,25 +384,25 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, @Override public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - if(!powerOutputEnabled || resource == null) { + if (!powerOutputEnabled || resource == null) { return null; } FluidStack in = resource.copy(); FluidStack result = null; for (NetworkFluidHandler h : getNetworkHandlers()) { - if(h.node.powerInputEnabled && h.handler.canDrain(h.dirOp, in.getFluid())) { + if (h.node.powerInputEnabled && h.handler.canDrain(h.dirOp, in.getFluid())) { FluidStack res = h.handler.drain(h.dirOp, in, false); - if(res != null) { - if(result == null) { + if (res != null) { + if (result == null) { result = res.copy(); - if(doDrain) { + if (doDrain) { h.handler.drain(h.dirOp, in, true); } - } else if(result.isFluidEqual(res)) { + } else if (result.isFluidEqual(res)) { result.amount += res.amount; - if(doDrain) { + if (doDrain) { h.handler.drain(h.dirOp, in, true); } in.amount -= res.amount; @@ -394,24 +415,24 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, @Override public FluidStack drain(ForgeDirection from, int maxDrainIn, boolean doDrain) { - if(!powerOutputEnabled) { + if (!powerOutputEnabled) { return null; } int maxDrain = maxDrainIn; FluidStack result = null; for (NetworkFluidHandler h : getNetworkHandlers()) { - if(h.node.powerInputEnabled) { + if (h.node.powerInputEnabled) { FluidStack res = h.handler.drain(h.dirOp, maxDrain, false); - if(res != null) { - if(result == null) { + if (res != null) { + if (result == null) { result = res.copy(); - if(doDrain) { + if (doDrain) { h.handler.drain(h.dirOp, maxDrain, true); } maxDrain -= res.amount; - } else if(result.isFluidEqual(res)) { + } else if (result.isFluidEqual(res)) { result.amount += res.amount; - if(doDrain) { + if (doDrain) { h.handler.drain(h.dirOp, maxDrain, true); } maxDrain -= res.amount; @@ -424,12 +445,12 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, @Override public boolean canFill(ForgeDirection from, Fluid fluid) { - if(!powerInputEnabled) { + if (!powerInputEnabled) { return false; } for (NetworkFluidHandler h : getNetworkHandlers()) { - if(h.node.powerOutputEnabled) { - if(h.handler.canFill(h.dirOp, fluid)) { + if (h.node.powerOutputEnabled) { + if (h.handler.canFill(h.dirOp, fluid)) { return true; } } @@ -439,12 +460,12 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, @Override public boolean canDrain(ForgeDirection from, Fluid fluid) { - if(!powerOutputEnabled) { + if (!powerOutputEnabled) { return false; } for (NetworkFluidHandler h : getNetworkHandlers()) { - if(h.node.powerInputEnabled) { - if(h.handler.canDrain(h.dirOp, fluid)) { + if (h.node.powerInputEnabled) { + if (h.handler.canDrain(h.dirOp, fluid)) { return true; } } @@ -457,9 +478,9 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, List res = new ArrayList(); for (NetworkFluidHandler h : getNetworkHandlers()) { FluidTankInfo[] ti = h.handler.getTankInfo(h.dirOp); - if(ti != null) { + if (ti != null) { for (FluidTankInfo t : ti) { - if(t != null) { + if (t != null) { res.add(t); } } @@ -469,18 +490,18 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, } private List getNetworkHandlers() { - if(HyperCubeRegister.instance == null) { + if (HyperCubeRegister.instance == null) { return Collections.emptyList(); } List cubes = HyperCubeRegister.instance.getCubesForChannel(channel); - if(cubes == null || cubes.isEmpty()) { + if (cubes == null || cubes.isEmpty()) { return Collections.emptyList(); } List result = new ArrayList(); for (TileHyperCube cube : cubes) { - if(cube != this && cube != null) { + if (cube != this && cube != null) { List handlers = cube.fluidHandlers; - if(handlers != null && !handlers.isEmpty()) { + if (handlers != null && !handlers.isEmpty()) { result.addAll(handlers); } } @@ -490,16 +511,16 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, } private void updateFluidHandlers() { - if(!fluidHandlersDirty) { + if (!fluidHandlersDirty) { return; } fluidHandlers.clear(); - if(isConnected()) { + if (isConnected()) { BlockCoord myLoc = new BlockCoord(this); for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { BlockCoord checkLoc = myLoc.getLocation(dir); TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); - if(te instanceof IFluidHandler) { + if (te instanceof IFluidHandler) { IFluidHandler fh = (IFluidHandler) te; fluidHandlers.add(new NetworkFluidHandler(this, fh, dir)); } @@ -517,7 +538,7 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, String channelName = nbtRoot.getString("channelName"); String channelUser = nbtRoot.getString("channelUser"); - if(channelName != null && !channelName.isEmpty()) { + if (channelName != null && !channelName.isEmpty()) { channel = new Channel(channelName, channelUser == null || channelUser.isEmpty() ? null : channelUser); } else { channel = null; @@ -532,13 +553,13 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, nbtRoot.setFloat("storedEnergy", powerHandler.getEnergyStored()); nbtRoot.setShort("inputControlMode", (short) inputControlMode.ordinal()); nbtRoot.setShort("outputControlMode", (short) outputControlMode.ordinal()); - if(channel != null) { + if (channel != null) { nbtRoot.setString("channelName", channel.name); - if(channel.user != null) { + if (channel.user != null) { nbtRoot.setString("channelUser", channel.user); } } - if(owner != null && !(owner.isEmpty())) { + if (owner != null && !(owner.isEmpty())) { nbtRoot.setString("owner", owner); } } @@ -549,10 +570,10 @@ public class TileHyperCube extends TileEntity implements IInternalPowerReceptor, } static class Receptor { - IPowerReceptor receptor; + PowerInterface receptor; ForgeDirection fromDir; - private Receptor(IPowerReceptor rec, ForgeDirection fromDir) { + private Receptor(PowerInterface rec, ForgeDirection fromDir) { this.receptor = rec; this.fromDir = fromDir; } diff --git a/common/crazypants/enderio/machine/light/TileElectricLight.java b/common/crazypants/enderio/machine/light/TileElectricLight.java index f46c8a1f..0695cf07 100644 --- a/common/crazypants/enderio/machine/light/TileElectricLight.java +++ b/common/crazypants/enderio/machine/light/TileElectricLight.java @@ -53,7 +53,7 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep } public void nodeRemoved(TileLightNode tileLightNode) { - if(!updatingLightNodes) { + if (!updatingLightNodes) { init = true; } } @@ -68,7 +68,7 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep @Override public void updateEntity() { - if(worldObj.isRemote) { + if (worldObj.isRemote) { return; } @@ -77,19 +77,19 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep powerHandler.update(); powerHandler.setEnergy(stored); - if(hasRedstone) { + if (hasRedstone) { powerHandler.setEnergy(Math.max(0, powerHandler.getEnergyStored() - MJ_USE_PER_TICK)); } boolean isActivated = hasPower() && hasRedstone; - if(init) { + if (init) { updateLightNodes(); } - if(isActivated != lastActive || init) { + if (isActivated != lastActive || init) { worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, isActivated ? 1 : 0, 2); for (TileLightNode ln : lightNodes) { - if(ln != null) { + if (ln != null) { worldObj.setBlockMetadataWithNotify(ln.xCoord, ln.yCoord, ln.zCoord, isActivated ? 1 : 0, 2); worldObj.markBlockForUpdate(ln.xCoord, ln.yCoord, ln.zCoord); worldObj.updateLightByType(EnumSkyBlock.Block, ln.xCoord, ln.yCoord, ln.zCoord); @@ -114,34 +114,34 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep private void updateLightNodes() { updatingLightNodes = true; List before = new ArrayList(17); - if(lightNodes != null) { + if (lightNodes != null) { for (TileLightNode node : lightNodes) { before.add(new NodeEntry(node)); } } List after = new ArrayList(17); try { - if(lightNodeCoords != null) { + if (lightNodeCoords != null) { // just loaded lightNodes = new ArrayList(); for (int i = 0; i < lightNodeCoords.length; i += 3) { TileEntity te = worldObj.getBlockTileEntity(lightNodeCoords[i], lightNodeCoords[i + 1], lightNodeCoords[i + 2]); - if(te instanceof TileLightNode) { + if (te instanceof TileLightNode) { lightNodes.add((TileLightNode) te); } } lightNodeCoords = null; - } else if(lightNodes == null) { // just created + } else if (lightNodes == null) { // just created lightNodes = new ArrayList(); } for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { - if(dir != face && dir != face.getOpposite()) { // don't project behind - // us + if (dir != face && dir != face.getOpposite()) { // don't project behind + // us Vector3d offset = ForgeDirectionOffsets.forDirCopy(dir); addNodeInDirection(new Vector3d(offset), after); addNodeInDirection(offset.add(ForgeDirectionOffsets.forDirCopy(face.getOpposite())), after); @@ -151,10 +151,10 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep addNodeInDirection(ForgeDirectionOffsets.forDirCopy(face.getOpposite()), after); Vector3d[] diags = new Vector3d[2]; - if(face.offsetX != 0) { + if (face.offsetX != 0) { diags[0] = ForgeDirectionOffsets.forDirCopy(ForgeDirection.UP); diags[1] = ForgeDirectionOffsets.forDirCopy(ForgeDirection.SOUTH); - } else if(face.offsetY != 0) { + } else if (face.offsetY != 0) { diags[0] = ForgeDirectionOffsets.forDirCopy(ForgeDirection.EAST); diags[1] = ForgeDirectionOffsets.forDirCopy(ForgeDirection.SOUTH); } else { @@ -164,14 +164,14 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep addDiaganals(diags, new Vector3d(), after); addDiaganals(diags, ForgeDirectionOffsets.forDirCopy(face.getOpposite()), after); - if(!areEqual(before, after)) { + if (!areEqual(before, after)) { clearLightNodes(); for (NodeEntry entry : after) { worldObj.setBlock(entry.coord.x, entry.coord.y, entry.coord.z, ModObject.blockLightNode.actualId); TileEntity te = worldObj.getBlockTileEntity(entry.coord.x, entry.coord.y, entry.coord.z); - if(te instanceof TileLightNode) { + if (te instanceof TileLightNode) { TileLightNode ln = (TileLightNode) te; ln.parentX = xCoord; ln.parentY = yCoord; @@ -191,11 +191,11 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep } private boolean areEqual(List before, List after) { - if(before.size() != after.size()) { + if (before.size() != after.size()) { return false; } for (NodeEntry entry : before) { - if(!after.contains(entry)) { + if (!after.contains(entry)) { return false; } } @@ -229,11 +229,11 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep boolean isAir = isAir(offset); boolean isTransp = isTranparent(offset); - if(isAir || isTransp) { + if (isAir || isTransp) { offset.scale(2); - if(isAir(offset)) { + if (isAir(offset)) { addLightNode(offset, diagnal, result); - } else if(isAir) { + } else if (isAir) { offset.scale(0.5); addLightNode(offset, diagnal, result); } @@ -245,9 +245,9 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep } private void clearLightNodes() { - if(lightNodes != null) { + if (lightNodes != null) { for (TileLightNode ln : lightNodes) { - if(worldObj.getBlockId(ln.xCoord, ln.yCoord, ln.zCoord) == ModObject.blockLightNode.actualId) { + if (worldObj.getBlockId(ln.xCoord, ln.yCoord, ln.zCoord) == ModObject.blockLightNode.actualId) { worldObj.setBlockToAir(ln.xCoord, ln.yCoord, ln.zCoord); } } @@ -261,9 +261,9 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep int y = yCoord + (int) offset.y; int z = zCoord + (int) offset.z; - if(isLightNode(offset)) { + if (isLightNode(offset)) { TileLightNode te = (TileLightNode) worldObj.getBlockTileEntity(x, y, z); - if(te.parentX != xCoord || te.parentY != yCoord || te.parentZ != zCoord) { + if (te.parentX != xCoord || te.parentY != yCoord || te.parentZ != zCoord) { // its somebody else's so leave it alone return; } @@ -272,11 +272,11 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep } private boolean isRailcraftException(int id) { - if(id > 0 && Block.blocksList[id] != null) { + if (id > 0 && Block.blocksList[id] != null) { // Pretty bad hack, by only feasable way I can think of to prevent our // light nodes getting placed inside railcraft tanks. String className = Block.blocksList[id].getClass().getName(); - if(className.equals("mods.railcraft.common.blocks.machine.BlockMachine")) { + if (className.equals("mods.railcraft.common.blocks.machine.BlockMachine")) { return true; } } @@ -285,7 +285,7 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep private boolean isTranparent(Vector3d offset) { int id = worldObj.getBlockId(xCoord + (int) offset.x, yCoord + (int) offset.y, zCoord + (int) offset.z); - if(isRailcraftException(id)) { + if (isRailcraftException(id)) { return false; } return worldObj.getBlockLightOpacity(xCoord + (int) offset.x, yCoord + (int) offset.y, zCoord + (int) offset.z) == 0; @@ -311,7 +311,7 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep root.setShort("face", (short) face.ordinal()); root.setFloat("storedEnergy", powerHandler.getEnergyStored()); - if(lightNodes != null) { + if (lightNodes != null) { int[] lnLoc = new int[lightNodes.size() * 3]; int index = 0; for (TileLightNode ln : lightNodes) { @@ -359,6 +359,33 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep public void applyPerdition() { } + // RF Power + + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + return PowerHandlerUtil.recieveRedstoneFlux(from, powerHandler, maxReceive, simulate); + } + + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + return 0; + } + + @Override + public boolean canInterface(ForgeDirection from) { + return true; + } + + @Override + public int getEnergyStored(ForgeDirection from) { + return (int) (powerHandler.getEnergyStored() * 10); + } + + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return (int) (powerHandler.getMaxEnergyStored() * 10); + } + static class NodeEntry { final BlockCoord coord; final boolean isDiagnal; @@ -384,24 +411,24 @@ public class TileElectricLight extends TileEntity implements IInternalPowerRecep @Override public boolean equals(Object obj) { - if(this == obj) { + if (this == obj) { return true; } - if(obj == null) { + if (obj == null) { return false; } - if(getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } NodeEntry other = (NodeEntry) obj; - if(coord == null) { - if(other.coord != null) { + if (coord == null) { + if (other.coord != null) { return false; } - } else if(!coord.equals(other.coord)) { + } else if (!coord.equals(other.coord)) { return false; } - if(isDiagnal != other.isDiagnal) { + if (isDiagnal != other.isDiagnal) { return false; } return true; diff --git a/common/crazypants/enderio/machine/power/TileCapacitorBank.java b/common/crazypants/enderio/machine/power/TileCapacitorBank.java index 89cb86e7..0bac0bd6 100644 --- a/common/crazypants/enderio/machine/power/TileCapacitorBank.java +++ b/common/crazypants/enderio/machine/power/TileCapacitorBank.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import java.util.List; import java.util.ListIterator; +import cofh.api.energy.IEnergyHandler; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -27,6 +29,7 @@ import crazypants.enderio.machine.RedstoneControlMode; import crazypants.enderio.power.BasicCapacitor; import crazypants.enderio.power.IInternalPowerReceptor; import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.enderio.power.PowerInterface; import crazypants.util.BlockCoord; import crazypants.util.Util; import crazypants.vecmath.VecmathUtil; @@ -84,20 +87,20 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep @Override public void updateEntity() { - if(worldObj == null) { // sanity check + if (worldObj == null) { // sanity check return; } - if(worldObj.isRemote) { + if (worldObj.isRemote) { return; } // else is server, do all logic only on the server - if(multiblockDirty) { + if (multiblockDirty) { formMultiblock(); multiblockDirty = false; } - if(!isContoller()) { + if (!isContoller()) { return; } @@ -114,22 +117,22 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep requiresClientSync = chargeItems(stored); boolean hasSignal = isRecievingRedstoneSignal(); - if(inputControlMode == RedstoneControlMode.IGNORE) { + if (inputControlMode == RedstoneControlMode.IGNORE) { inputEnabled = true; - } else if(inputControlMode == RedstoneControlMode.NEVER) { + } else if (inputControlMode == RedstoneControlMode.NEVER) { inputEnabled = false; } else { inputEnabled = (inputControlMode == RedstoneControlMode.ON && hasSignal) || (inputControlMode == RedstoneControlMode.OFF && !hasSignal); } - if(outputControlMode == RedstoneControlMode.IGNORE) { + if (outputControlMode == RedstoneControlMode.IGNORE) { outputEnabled = true; - } else if(outputControlMode == RedstoneControlMode.NEVER) { + } else if (outputControlMode == RedstoneControlMode.NEVER) { outputEnabled = false; } else { outputEnabled = (outputControlMode == RedstoneControlMode.ON && hasSignal) || (outputControlMode == RedstoneControlMode.OFF && !hasSignal); } - if(outputEnabled) { + if (outputEnabled) { transmitEnergy(); } @@ -138,7 +141,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep // Update if our power has changed by more than 0.5% requiresClientSync |= lastSyncPowerStored != storedEnergy && worldObj.getTotalWorldTime() % 21 == 0; - if(requiresClientSync) { + if (requiresClientSync) { lastSyncPowerStored = storedEnergy; // this will cause 'getPacketDescription()' to be called and its result @@ -154,20 +157,20 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep boolean chargedItem = false; float available = Math.min(maxIO, stored); for (ItemStack item : inventory) { - if(item != null && item.getItem() instanceof IChargeableItem && available > 0) { + if (item != null && item.getItem() instanceof IChargeableItem && available > 0) { IChargeableItem chargable = (IChargeableItem) item.getItem(); float max = chargable.getMaxEnergyStored(item); float cur = chargable.getEnergyStored(item); float canUse = Math.min(available, max - cur); - if(cur < max) { + if (cur < max) { float used = 0; - if(chargable.getClass().getName().startsWith("appeng") || "appeng.common.base.AppEngMultiChargeable".equals(chargable.getClass().getName())) { - //256 max limit + if (chargable.getClass().getName().startsWith("appeng") || "appeng.common.base.AppEngMultiChargeable".equals(chargable.getClass().getName())) { + // 256 max limit canUse = Math.min(canUse, 256); NBTTagCompound tc = item.getTagCompound(); - if(tc == null) { + if (tc == null) { item.setTagCompound(tc = new NBTTagCompound()); } double newVal = (cur + canUse) * 5.0; @@ -177,7 +180,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } else { used = chargable.receiveEnergy(item, canUse, true); } - if(used > 0) { + if (used > 0) { powerHandler.setEnergy(stored - used); chargedItem = true; available -= used; @@ -198,7 +201,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep private boolean transmitEnergy() { - if(powerHandler.getEnergyStored() <= 0) { + if (powerHandler.getEnergyStored() <= 0) { return false; } float canTransmit = Math.min(storedEnergy, maxOutput); @@ -206,7 +209,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep checkReceptors(); - if(!receptors.isEmpty() && !receptorIterator.hasNext()) { + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = receptors.listIterator(); } @@ -215,33 +218,39 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep while (receptorIterator.hasNext() && canTransmit > 0 && appliedCount < numReceptors) { Receptor receptor = receptorIterator.next(); - PowerReceiver pp = receptor.receptor.getPowerReceiver(receptor.fromDir.getOpposite()); - if(pp != null && pp.getMinEnergyReceived() <= canTransmit && pp.getType() != Type.ENGINE && !powerHandler.isPowerSource(receptor.fromDir)) { + PowerInterface powerInterface = receptor.receptor; + if (powerInterface != null && powerInterface.getMinEnergyReceived(receptor.fromDir.getOpposite()) <= canTransmit && !powerHandler.isPowerSource(receptor.fromDir)) { + float used; - if(receptor.receptor instanceof IInternalPowerReceptor) { - if(!(receptor.receptor instanceof IConduitBundle)) { //power conduits manage the exchange between them an the cap bank - used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) receptor.receptor, pp, canTransmit, Type.STORAGE, receptor.fromDir.getOpposite()); + if (receptor.receptor.getDelegate() instanceof IInternalPowerReceptor) { + IInternalPowerReceptor internalRec = (IInternalPowerReceptor) receptor.receptor.getDelegate(); + if (!(internalRec instanceof IConduitBundle)) { + // power conduits manage the exchange between them an the cap bank + used = PowerHandlerUtil.transmitInternal(internalRec, internalRec.getPowerReceiver(receptor.fromDir.getOpposite()), canTransmit, Type.STORAGE, + receptor.fromDir.getOpposite()); } else { - IConduitBundle bundle = (IConduitBundle) receptor.receptor; + IConduitBundle bundle = (IConduitBundle) internalRec; IPowerConduit conduit = bundle.getConduit(IPowerConduit.class); - if(conduit != null && conduit.getConectionMode(receptor.fromDir.getOpposite()) == ConnectionMode.INPUT) { - used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) receptor.receptor, pp, canTransmit, Type.STORAGE, + if (conduit != null && conduit.getConectionMode(receptor.fromDir.getOpposite()) == ConnectionMode.INPUT) { + used = PowerHandlerUtil.transmitInternal(internalRec, internalRec.getPowerReceiver(receptor.fromDir.getOpposite()), canTransmit, Type.STORAGE, receptor.fromDir.getOpposite()); } else { used = 0; } } } else { - used = pp.receiveEnergy(Type.STORAGE, canTransmit, receptor.fromDir.getOpposite()); + used = powerInterface.recieveEnergy(receptor.fromDir.getOpposite(), canTransmit); } + transmitted += used; canTransmit -= used; } - if(canTransmit <= 0) { + + if (canTransmit <= 0) { break; } - if(!receptors.isEmpty() && !receptorIterator.hasNext()) { + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = receptors.listIterator(); } appliedCount++; @@ -253,13 +262,13 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } private void checkReceptors() { - if(!receptorsDirty) { + if (!receptorsDirty) { return; } receptors.clear(); BlockCoord[] coords; - if(isMultiblock()) { + if (isMultiblock()) { coords = multiblock; } else { coords = new BlockCoord[] { new BlockCoord(this) }; @@ -270,12 +279,13 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { BlockCoord checkLoc = bc.getLocation(dir); TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); - if(te instanceof IPowerReceptor) { + if (te instanceof IPowerReceptor) { IPowerReceptor rec = (IPowerReceptor) te; - if(!(te instanceof TileCapacitorBank) && PowerHandlerUtil.canConnectRecievePower(rec)) { - receptors.add(new Receptor((IPowerReceptor) te, dir)); - } - + if (!(te instanceof TileCapacitorBank) && PowerHandlerUtil.canConnectRecievePower(rec)) { + receptors.add(new Receptor(new PowerInterface((IPowerReceptor) te), dir)); + } + } else if (te instanceof IEnergyHandler) { + receptors.add(new Receptor(new PowerInterface((IEnergyHandler) te), dir)); } } } @@ -331,16 +341,57 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep return getPowerHandler().getPowerReceiver(); } + // RF Power + + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + return 0; + } + + @Override + public boolean canInterface(ForgeDirection from) { + return true; + } + + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + return getController().doReceiveEnergy(from, maxReceive, simulate); + } + + @Override + public int getEnergyStored(ForgeDirection from) { + return getController().doGetEnergyStored(from); + } + + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return getController().doGetMaxEnergyStored(); + } + + public int doReceiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + return PowerHandlerUtil.recieveRedstoneFlux(from, powerHandler, maxReceive, simulate); + } + + public int doGetEnergyStored(ForgeDirection from) { + return (int) (powerHandler.getEnergyStored() * 10); + } + + public int doGetMaxEnergyStored(ForgeDirection from) { + return (int) (powerHandler.getMaxEnergyStored() * 10); + } + + // end rf power + public void addEnergy(float add) { getController().doAddEnergy(add); } private boolean isRecievingRedstoneSignal() { - if(!isMultiblock()) { + if (!isMultiblock()) { return worldObj.getStrongestIndirectPower(xCoord, yCoord, zCoord) > 0; } for (BlockCoord bc : multiblock) { - if(worldObj.getStrongestIndirectPower(bc.x, bc.y, bc.z) > 0) { + if (worldObj.getStrongestIndirectPower(bc.x, bc.y, bc.z) > 0) { return true; } } @@ -352,12 +403,12 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } public void setInputControlMode(RedstoneControlMode inputControlMode) { - if(!isMultiblock()) { + if (!isMultiblock()) { this.inputControlMode = inputControlMode; } else { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); - if(cp != null) { + if (cp != null) { cp.inputControlMode = inputControlMode; } } @@ -369,12 +420,12 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } public void setOutputControlMode(RedstoneControlMode outputControlMode) { - if(!isMultiblock()) { + if (!isMultiblock()) { this.outputControlMode = outputControlMode; } else { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); - if(cp != null) { + if (cp != null) { cp.outputControlMode = outputControlMode; } } @@ -392,14 +443,14 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } PowerHandler doGetPowerHandler() { - if(inputEnabled) { + if (inputEnabled) { return powerHandler; } return getDisabledPowerHandler(); } private PowerHandler getDisabledPowerHandler() { - if(disabledPowerHandler == null) { + if (disabledPowerHandler == null) { disabledPowerHandler = PowerHandlerUtil.createHandler(new BasicCapacitor(0, 0), this, Type.STORAGE); } return disabledPowerHandler; @@ -426,10 +477,10 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep void doSetMaxInput(int in) { maxInput = Math.min(in, maxIO); maxInput = Math.max(0, maxInput); - if(isMultiblock()) { + if (isMultiblock()) { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); - if(cp != null) { + if (cp != null) { cp.maxInput = maxInput; } } @@ -440,10 +491,10 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep void doSetMaxOutput(int out) { maxOutput = Math.min(out, maxIO); maxOutput = Math.max(0, maxOutput); - if(isMultiblock()) { + if (isMultiblock()) { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); - if(cp != null) { + if (cp != null) { cp.maxOutput = maxOutput; } } @@ -469,7 +520,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep private void updatePowerHandler() { powerHandler = PowerHandlerUtil.createHandler(new BasicCapacitor(maxInput, maxStoredEnergy, maxOutput), this, Type.STORAGE); - if(storedEnergy > maxStoredEnergy) { + if (storedEnergy > maxStoredEnergy) { storedEnergy = maxStoredEnergy; } powerHandler.setEnergy(storedEnergy); @@ -483,7 +534,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } public void onNeighborBlockChange(int blockId) { - if(blockId != ModObject.blockCapacitorBank.actualId) { + if (blockId != ModObject.blockCapacitorBank.actualId) { getController().receptorsDirty = true; } } @@ -494,12 +545,12 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } private void clearCurrentMultiblock() { - if(multiblock == null) { + if (multiblock == null) { return; } for (BlockCoord bc : multiblock) { TileCapacitorBank res = getCapBank(bc); - if(res != null) { + if (res != null) { res.setMultiblock(null); } @@ -512,7 +563,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep blocks.add(this); findNighbouringBanks(this, blocks); - if(blocks.size() < 2) { + if (blocks.size() < 2) { return; } for (TileCapacitorBank cb : blocks) { @@ -534,7 +585,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep BlockCoord bc = new BlockCoord(tileCapacitorBank); for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { TileCapacitorBank cb = getCapBank(bc.getLocation(dir)); - if(cb != null && !blocks.contains(cb)) { + if (cb != null && !blocks.contains(cb)) { blocks.add(cb); findNighbouringBanks(cb, blocks); } @@ -543,12 +594,12 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep private void setMultiblock(BlockCoord[] mb) { - if(multiblock != null && isMaster()) { + if (multiblock != null && isMaster()) { // split up current multiblock and reconfigure all the internal capacitors float powerPerBlock = storedEnergy / multiblock.length; for (BlockCoord bc : multiblock) { TileCapacitorBank cb = getCapBank(bc); - if(cb != null) { + if (cb != null) { cb.maxStoredEnergy = BASE_CAP.getMaxEnergyStored(); cb.maxIO = BASE_CAP.getMaxEnergyExtracted(); cb.maxInput = cb.maxIO; @@ -561,7 +612,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } multiblock = mb; - if(isMaster()) { + if (isMaster()) { List invItems = new ArrayList(); @@ -570,12 +621,12 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep int totalIO = multiblock.length * BASE_CAP.getMaxEnergyExtracted(); for (BlockCoord bc : multiblock) { TileCapacitorBank cb = getCapBank(bc); - if(cb != null) { + if (cb != null) { totalStored += cb.storedEnergy; } ItemStack[] inv = cb.inventory; for (int i = 0; i < inv.length; i++) { - if(inv[i] != null) { + if (inv[i] != null) { invItems.add(inv[i]); inv[i] = null; } @@ -588,7 +639,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep maxInput = maxIO; maxOutput = maxIO; - if(invItems.size() > inventory.length) { + if (invItems.size() > inventory.length) { for (int i = inventory.length; i < invItems.size(); i++) { Util.dropItems(worldObj, invItems.get(i), xCoord, yCoord, zCoord, true); } @@ -607,7 +658,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } TileCapacitorBank getController() { - if(isMaster() || !isMultiblock()) { + if (isMaster() || !isMultiblock()) { return this; } TileCapacitorBank res = getCapBank(multiblock[0]); @@ -619,7 +670,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } boolean isMaster() { - if(multiblock != null) { + if (multiblock != null) { return multiblock[0].equals(xCoord, yCoord, zCoord); } return false; @@ -630,12 +681,12 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } private boolean isCurrentMultiblockValid() { - if(multiblock == null) { + if (multiblock == null) { return false; } for (BlockCoord bc : multiblock) { TileCapacitorBank res = getCapBank(bc); - if(res == null || !res.isMultiblock()) { + if (res == null || !res.isMultiblock()) { return false; } } @@ -648,13 +699,13 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep private TileCapacitorBank getCapBank(int x, int y, int z) { TileEntity te = worldObj.getBlockTileEntity(x, y, z); - if(te instanceof TileCapacitorBank) { + if (te instanceof TileCapacitorBank) { return (TileCapacitorBank) te; } return null; } - //------------- Inventory + // ------------- Inventory @Override public int getSizeInventory() { @@ -663,7 +714,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep @Override public ItemStack getStackInSlot(int i) { - if(i < 0 || i >= inventory.length) { + if (i < 0 || i >= inventory.length) { return null; } return inventory[i]; @@ -671,14 +722,14 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep @Override public ItemStack decrStackSize(int fromSlot, int amount) { - if(fromSlot < 0 || fromSlot >= inventory.length) { + if (fromSlot < 0 || fromSlot >= inventory.length) { return null; } ItemStack item = inventory[fromSlot]; - if(item == null) { + if (item == null) { return null; } - if(item.stackSize <= amount) { + if (item.stackSize <= amount) { ItemStack result = item.copy(); inventory[fromSlot] = null; return result; @@ -694,7 +745,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep @Override public void setInventorySlotContents(int i, ItemStack itemstack) { - if(i < 0 || i >= inventory.length) { + if (i < 0 || i >= inventory.length) { return; } inventory[i] = itemstack; @@ -730,7 +781,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { - if(itemstack == null) { + if (itemstack == null) { return false; } return itemstack.getItem() instanceof IChargeableItem; @@ -743,7 +794,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep storedEnergy = nbtRoot.getFloat("storedEnergy"); maxStoredEnergy = nbtRoot.getInteger("maxStoredEnergy"); maxIO = nbtRoot.getInteger("maxIO"); - if(nbtRoot.hasKey("maxInput")) { + if (nbtRoot.hasKey("maxInput")) { maxInput = nbtRoot.getInteger("maxInput"); maxOutput = nbtRoot.getInteger("maxOutput"); } else { @@ -757,7 +808,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep updatePowerHandler(); boolean wasMulti = isMultiblock(); - if(nbtRoot.getBoolean("isMultiblock")) { + if (nbtRoot.getBoolean("isMultiblock")) { int[] coords = nbtRoot.getIntArray("multiblock"); multiblock = new BlockCoord[coords.length / 3]; int c = 0; @@ -777,7 +828,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep for (int i = 0; i < itemList.tagCount(); i++) { NBTTagCompound itemStack = (NBTTagCompound) itemList.tagAt(i); byte slot = itemStack.getByte("Slot"); - if(slot >= 0 && slot < inventory.length) { + if (slot >= 0 && slot < inventory.length) { inventory[slot] = ItemStack.loadItemStackFromNBT(itemStack); } } @@ -796,7 +847,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep nbtRoot.setShort("outputControlMode", (short) outputControlMode.ordinal()); nbtRoot.setBoolean("isMultiblock", isMultiblock()); - if(isMultiblock()) { + if (isMultiblock()) { int[] vals = new int[multiblock.length * 3]; int i = 0; for (BlockCoord bc : multiblock) { @@ -810,7 +861,7 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep // write inventory list NBTTagList itemList = new NBTTagList(); for (int i = 0; i < inventory.length; i++) { - if(inventory[i] != null) { + if (inventory[i] != null) { NBTTagCompound itemStackNBT = new NBTTagCompound(); itemStackNBT.setByte("Slot", (byte) i); inventory[i].writeToNBT(itemStackNBT); @@ -826,11 +877,10 @@ public class TileCapacitorBank extends TileEntity implements IInternalPowerRecep } static class Receptor { - IPowerReceptor receptor; + PowerInterface receptor; ForgeDirection fromDir; - private Receptor(IPowerReceptor rec, ForgeDirection fromDir) { - super(); + private Receptor(PowerInterface rec, ForgeDirection fromDir) { this.receptor = rec; this.fromDir = fromDir; } diff --git a/common/crazypants/enderio/machine/solar/TileEntitySolarPanel.java b/common/crazypants/enderio/machine/solar/TileEntitySolarPanel.java index 3ae69d65..7a2d10ab 100644 --- a/common/crazypants/enderio/machine/solar/TileEntitySolarPanel.java +++ b/common/crazypants/enderio/machine/solar/TileEntitySolarPanel.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import java.util.List; import java.util.ListIterator; +import cofh.api.energy.IEnergyHandler; + import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.world.EnumSkyBlock; @@ -18,6 +20,7 @@ import crazypants.enderio.Config; import crazypants.enderio.power.BasicCapacitor; import crazypants.enderio.power.IInternalPowerReceptor; import crazypants.enderio.power.PowerHandlerUtil; +import crazypants.enderio.power.PowerInterface; import crazypants.util.BlockCoord; public class TileEntitySolarPanel extends TileEntity implements IInternalPowerReceptor, IPowerEmitter { @@ -68,9 +71,36 @@ public class TileEntitySolarPanel extends TileEntity implements IInternalPowerRe return powerHandler; } + // RF Power + + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + return PowerHandlerUtil.recieveRedstoneFlux(from, powerHandler, maxReceive, simulate); + } + + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + return 0; + } + + @Override + public boolean canInterface(ForgeDirection from) { + return true; + } + + @Override + public int getEnergyStored(ForgeDirection from) { + return (int) (powerHandler.getEnergyStored() * 10); + } + + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return (int) (powerHandler.getMaxEnergyStored() * 10); + } + @Override public void updateEntity() { - if(worldObj == null || worldObj.isRemote) { + if (worldObj == null || worldObj.isRemote) { return; } collectEnergy(); @@ -78,7 +108,7 @@ public class TileEntitySolarPanel extends TileEntity implements IInternalPowerRe } private void collectEnergy() { - if(!worldObj.canBlockSeeTheSky(xCoord, yCoord, zCoord)) { + if (!worldObj.canBlockSeeTheSky(xCoord, yCoord, zCoord)) { return; } float fromSun = calculateLightRatio(); @@ -91,7 +121,7 @@ public class TileEntitySolarPanel extends TileEntity implements IInternalPowerRe int lightValue = worldObj.getSavedLightValue(EnumSkyBlock.Sky, xCoord, yCoord, zCoord) - worldObj.skylightSubtracted; float sunAngle = worldObj.getCelestialAngleRadians(1.0F); - if(sunAngle < (float) Math.PI) { + if (sunAngle < (float) Math.PI) { sunAngle += (0.0F - sunAngle) * 0.2F; } else { sunAngle += (((float) Math.PI * 2F) - sunAngle) * 0.2F; @@ -105,7 +135,7 @@ public class TileEntitySolarPanel extends TileEntity implements IInternalPowerRe private boolean transmitEnergy() { - if(powerHandler.getEnergyStored() <= 0) { + if (powerHandler.getEnergyStored() <= 0) { powerHandler.update(); return false; } @@ -120,7 +150,7 @@ public class TileEntitySolarPanel extends TileEntity implements IInternalPowerRe checkReceptors(); - if(!receptors.isEmpty() && !receptorIterator.hasNext()) { + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = receptors.listIterator(); } @@ -129,22 +159,18 @@ public class TileEntitySolarPanel extends TileEntity implements IInternalPowerRe while (receptorIterator.hasNext() && canTransmit > 0 && appliedCount < numReceptors) { Receptor receptor = receptorIterator.next(); - PowerReceiver pp = receptor.receptor.getPowerReceiver(receptor.fromDir.getOpposite()); - if(pp != null && pp.getMinEnergyReceived() <= canTransmit && pp.getType() != Type.ENGINE) { - float used; - if(receptor.receptor instanceof IInternalPowerReceptor) { - used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) receptor.receptor, pp, canTransmit, Type.ENGINE, receptor.fromDir.getOpposite()); - } else { - used = pp.receiveEnergy(Type.ENGINE, canTransmit, receptor.fromDir.getOpposite()); - } + PowerInterface pp = receptor.receptor; + if (pp != null && pp.getMinEnergyReceived(receptor.fromDir.getOpposite()) <= canTransmit) { + float used = pp.recieveEnergy(receptor.fromDir.getOpposite(), canTransmit); transmitted += used; canTransmit -= used; } - if(canTransmit <= 0) { + + if (canTransmit <= 0) { break; } - if(!receptors.isEmpty() && !receptorIterator.hasNext()) { + if (!receptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = receptors.listIterator(); } appliedCount++; @@ -157,46 +183,28 @@ public class TileEntitySolarPanel extends TileEntity implements IInternalPowerRe } private void checkReceptors() { - if(!receptorsDirty) { + if (!receptorsDirty) { return; } receptors.clear(); - BlockCoord bc = new BlockCoord(xCoord, yCoord, zCoord); ForgeDirection dir = ForgeDirection.DOWN; BlockCoord checkLoc = bc.getLocation(dir); TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); - if(te instanceof IPowerReceptor) { - IPowerReceptor rec = (IPowerReceptor) te; - PowerReceiver reciever = rec.getPowerReceiver(dir.getOpposite()); - if(reciever != null) { - receptors.add(new Receptor((IPowerReceptor) te, dir)); - } - } - - // NB: This is to supports connections from any direction - // BlockCoord bc = new BlockCoord(xCoord, yCoord, zCoord); - // for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { - // BlockCoord checkLoc = bc.getLocation(dir); - // TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, - // checkLoc.z); - // if (te instanceof IPowerReceptor) { - // IPowerReceptor rec = (IPowerReceptor) te; - // PowerReceiver reciever = rec.getPowerReceiver(dir.getOpposite()); - // receptors.add(new Receptor((IPowerReceptor) te, dir.getOpposite())); - // } - // } + PowerInterface pi = PowerInterface.create(te); + if(pi != null) { + receptors.add(new Receptor(pi, dir)); + } receptorIterator = receptors.listIterator(); receptorsDirty = false; } static class Receptor { - IPowerReceptor receptor; + PowerInterface receptor; ForgeDirection fromDir; - private Receptor(IPowerReceptor rec, ForgeDirection fromDir) { - super(); + private Receptor(PowerInterface rec, ForgeDirection fromDir) { this.receptor = rec; this.fromDir = fromDir; } diff --git a/common/crazypants/enderio/power/IInternalPowerReceptor.java b/common/crazypants/enderio/power/IInternalPowerReceptor.java index e1fa09d6..e958b984 100644 --- a/common/crazypants/enderio/power/IInternalPowerReceptor.java +++ b/common/crazypants/enderio/power/IInternalPowerReceptor.java @@ -1,9 +1,10 @@ package crazypants.enderio.power; +import cofh.api.energy.IEnergyHandler; import buildcraft.api.power.IPowerReceptor; import buildcraft.api.power.PowerHandler; -public interface IInternalPowerReceptor extends IPowerReceptor { +public interface IInternalPowerReceptor extends IPowerReceptor, IEnergyHandler { PowerHandler getPowerHandler(); diff --git a/common/crazypants/enderio/power/PowerHandlerUtil.java b/common/crazypants/enderio/power/PowerHandlerUtil.java index 7e704729..c0eaa901 100644 --- a/common/crazypants/enderio/power/PowerHandlerUtil.java +++ b/common/crazypants/enderio/power/PowerHandlerUtil.java @@ -14,10 +14,10 @@ import buildcraft.api.transport.IPipeTile.PipeType; public class PowerHandlerUtil { public static boolean canConnectRecievePower(IPowerReceptor rec) { - if(rec == null) { + if (rec == null) { return false; } - if(rec instanceof IPipeTile) { + if (rec instanceof IPipeTile) { IPipeTile pipeTile = (IPipeTile) rec; return pipeTile.getPipeType() == PipeType.POWER; } @@ -27,7 +27,7 @@ public class PowerHandlerUtil { public static float getStoredEnergyForItem(ItemStack item) { NBTTagCompound tag = item.getTagCompound(); - if(tag == null) { + if (tag == null) { return 0; } return tag.getFloat("storedEnergy"); @@ -35,7 +35,7 @@ public class PowerHandlerUtil { public static void setStoredEnergyForItem(ItemStack item, float storedEnergy) { NBTTagCompound tag = item.getTagCompound(); - if(tag == null) { + if (tag == null) { tag = new NBTTagCompound(); } tag.setFloat("storedEnergy", storedEnergy); @@ -52,7 +52,7 @@ public class PowerHandlerUtil { public static void configure(PowerHandler ph, ICapacitor capacitor) { ph.configure(capacitor.getMinEnergyReceived(), capacitor.getMaxEnergyReceived(), capacitor.getMinActivationEnergy(), capacitor.getMaxEnergyStored()); - if(ph.getEnergyStored() > ph.getMaxEnergyStored()) { + if (ph.getEnergyStored() > ph.getMaxEnergyStored()) { ph.setEnergy(ph.getMaxEnergyStored()); } ph.configurePowerPerdition(0, 0); @@ -62,16 +62,16 @@ public class PowerHandlerUtil { public static float transmitInternal(IInternalPowerReceptor receptor, PowerReceiver pp, float quantity, Type type, ForgeDirection from) { PowerHandler ph = receptor.getPowerHandler(); - if(ph == null) { + if (ph == null) { return 0; } float energyStored = pp.getEnergyStored(); float canUse = quantity; canUse = Math.min(canUse, pp.getMaxEnergyReceived()); - //Don't overflow it + // Don't overflow it canUse = Math.min(canUse, pp.getMaxEnergyStored() - energyStored); - if(canUse <= pp.getMinEnergyReceived()) { + if (canUse <= pp.getMinEnergyReceived()) { pp.receiveEnergy(type, 0, null); ph.setEnergy(energyStored); return 0; @@ -80,21 +80,56 @@ public class PowerHandlerUtil { // Do all required functions except: // - We will handle perd'n ourselves and there is not need to drain excess // from our engines as they are self regulating - // - Also not making use of the doWork calls. + // - Also not making use of the doWork calls. pp.receiveEnergy(type, 0, from); ph.setEnergy(energyStored); - ph.setEnergy(energyStored + canUse); + ph.setEnergy(ph.getEnergyStored() + canUse); receptor.applyPerdition(); return canUse; } + public static int recieveRedstoneFlux(ForgeDirection from, PowerHandler powerHandler, int maxReceive, boolean simulate) { + int canRecieve = (int)getMaxEnergyRecievedMj(powerHandler, maxReceive/10, from); + if (!simulate) { + doBuildCraftEnergyTick(powerHandler, from); + powerHandler.setEnergy(powerHandler.getEnergyStored() + canRecieve); + } + return canRecieve * 10; + } + + public static float getMaxEnergyRecievedMj(PowerHandler ph, float max, ForgeDirection from) { + if (ph == null) { + return 0; + } + float canRecieve = max; + canRecieve = Math.min(canRecieve, ph.getMaxEnergyReceived()); + canRecieve = Math.min(canRecieve, ph.getMaxEnergyStored() - ph.getEnergyStored()); + if (canRecieve <= ph.getMinEnergyReceived()) { + return 0; + } + return canRecieve; + } + + public static void doBuildCraftEnergyTick(PowerHandler ph, ForgeDirection from) { + if (ph == null) { + return; + } + PowerReceiver pp = ph.getPowerReceiver(); + if (pp == null) { + return; + } + float stored = ph.getEnergyStored(); + pp.receiveEnergy(Type.PIPE, 0, from); + ph.setEnergy(stored); + } + private static class NullPerditionCalculator extends PerditionCalculator { @Override public float applyPerdition(PowerHandler powerHandler, float current, long ticksPassed) { - if(current <= 0) { + if (current <= 0) { return 0; } float decAmount = 0.001f; diff --git a/common/crazypants/enderio/power/PowerInterface.java b/common/crazypants/enderio/power/PowerInterface.java new file mode 100644 index 00000000..ece59c64 --- /dev/null +++ b/common/crazypants/enderio/power/PowerInterface.java @@ -0,0 +1,145 @@ +package crazypants.enderio.power; + +import net.minecraftforge.common.ForgeDirection; +import cofh.api.energy.IEnergyHandler; +import crazypants.enderio.machine.power.TileCapacitorBank; +import buildcraft.api.power.IPowerEmitter; +import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; + +public class PowerInterface { + + public static PowerInterface create(Object o) { + if(o instanceof IEnergyHandler) { + return new PowerInterface((IEnergyHandler)o); + } else if(o instanceof IPowerReceptor) { + return new PowerInterface((IPowerReceptor)o); + } + return null; + } + + private IPowerReceptor bcPower; + + private IEnergyHandler rfPower; + + public PowerInterface(IPowerReceptor powerReceptor) { + bcPower = powerReceptor; + } + + public PowerInterface(IEnergyHandler powerReceptor) { + rfPower = powerReceptor; + } + + public Object getDelegate() { + if (bcPower != null) { + return bcPower; + } + return rfPower; + } + + public boolean canConduitConnect(ForgeDirection direction) { + if (rfPower != null) { + return rfPower.canInterface(direction.getOpposite()); + } + + // bc + if (bcPower != null) { + if (bcPower instanceof IPowerEmitter) { + return ((IPowerEmitter) bcPower).canEmitPowerFrom(direction.getOpposite()); + } + return PowerHandlerUtil.canConnectRecievePower(bcPower); + } + return false; + } + + public float getEnergyStored(ForgeDirection dir) { + if (rfPower != null) { + return rfPower.getEnergyStored(dir); + } + + // bc + float result = 0; + if (bcPower instanceof IInternalPowerReceptor) { + result = ((IInternalPowerReceptor) bcPower).getPowerHandler().getEnergyStored(); + } else if (bcPower != null && !(bcPower instanceof IPowerEmitter)) { + PowerReceiver pr = bcPower.getPowerReceiver(dir); + if (pr != null) { + result += pr.getEnergyStored(); + } + } + return result; + } + + public float getMaxEnergyStored(ForgeDirection dir) { + if (rfPower != null) { + return rfPower.getMaxEnergyStored(dir); + } + + // bc + float result = 0; + if (bcPower instanceof IInternalPowerReceptor) { + result = ((IInternalPowerReceptor) bcPower).getPowerHandler().getMaxEnergyStored(); + } else if (bcPower != null && !(bcPower instanceof IPowerEmitter)) { + PowerReceiver pr = bcPower.getPowerReceiver(dir); + if (pr != null) { + result += pr.getMaxEnergyStored(); + } + } + return result; + } + + public float getPowerRequest(ForgeDirection dir) { + if (rfPower != null) { + if (rfPower.canInterface(dir)) { + return rfPower.extractEnergy(dir, rfPower.getMaxEnergyStored(dir), true); + } + return 0; + } + + // bc + if (bcPower != null) { + PowerReceiver pr = bcPower.getPowerReceiver(dir); + if (pr == null || pr.getType() == Type.ENGINE) { + return 0; + } + return pr.powerRequest(); + } + + return 0; + } + + public float getMinEnergyReceived(ForgeDirection dir) { + if (rfPower != null) { + return 0; + } + + if(bcPower != null) { + PowerReceiver pr = bcPower.getPowerReceiver(dir); + if (pr == null) { + return 0; + } + return pr.getMinEnergyReceived(); + } + return 0; + } + + public float recieveEnergy(ForgeDirection opposite, float canOffer) { + if(rfPower != null) { + return rfPower.receiveEnergy(opposite, (int)(canOffer * 10), false) / 10; + } + + if(bcPower != null) { + if(bcPower instanceof IInternalPowerReceptor) { + return PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) bcPower, bcPower.getPowerReceiver(opposite), canOffer, Type.PIPE, opposite); + } + PowerReceiver pr = bcPower.getPowerReceiver(opposite); + if(pr == null) { + return 0; + } + float offer = Math.min(pr.powerRequest(), canOffer); + return pr.receiveEnergy(Type.PIPE, offer, opposite); + } + return 0; + } +} diff --git a/common/crazypants/enderio/power/RedstoneFluxPowerReceptor.java b/common/crazypants/enderio/power/RedstoneFluxPowerReceptor.java new file mode 100644 index 00000000..8fa32dde --- /dev/null +++ b/common/crazypants/enderio/power/RedstoneFluxPowerReceptor.java @@ -0,0 +1,5 @@ +package crazypants.enderio.power; + +public class RedstoneFluxPowerReceptor { + +}