This commit is contained in:
nekosune committed 2014-05-05 21:49:33 +01:00
1 parent 3efdf93073
commit 17aca3eeb8
113 files changed
+2452 -1999

No files matched your search

@@ -0,0 +1,47 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.io.File;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
/**
* This class is provided as a utility class for third-party mods that would
* like to easily deploy structures that are written in blueprints. It does
* not offer control on material that needs to get in, or how the structure
* is deployed, but allows to create contents of a blueprint in one cycle.
* Note that these functionalities will only work if BuildCraft is installed.
*/
public abstract class BlueprintDeployer {
/**
* The deployed instantiated by BuildCraft. This is set by the BuildCraft
* builder mod. Mods that want to work with BuildCraft not installed should
* check for this value to be not null.
*/
public static BlueprintDeployer instance;
/**
* Deploy the contents of the blueprints as if the builder was located at
* {x, y, z} facing the direction dir.
*/
public abstract void deployBlueprint(World world, int x, int y, int z,
ForgeDirection dir, File file);
/**
*Deploy the contents of the byte array as if the builder was located at
*{x, y, z} facing the direction dir.
*/
public abstract void deployBlueprintFromFileStream(World world, int x, int y,
int z, ForgeDirection dir, byte [] data);
}
@@ -0,0 +1,38 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
/**
* Schematics recorded in the blueprints can restrict situations where a
* blueprint can be used. A same schematic class can have different
* permissions depending on its contents. It's particularly useful when
* fixing a schematic, if blueprints that saved the previous version should
* not be built because of a bug (such as dupe bug on inventories).
*/
public enum BuildingPermission {
/**
* No restrictions, blueprints using this schematic are good in all
* contexts.
*/
ALL,
/**
* This blueprints containing this schematic can only be used in
* creative. Maybe the block can't be crafted in survival in the first
* place, or the content of the schematic is known to have dupe bugs.
*/
CREATIVE_ONLY,
/**
* Blueprints containing this schematic should not be built. This is
* typically used when a critical problems have been fixed, but older
* versions of the schematic are too badly broken to be retreived.
*/
NONE,
}
@@ -0,0 +1,29 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import net.minecraft.world.World;
import buildcraft.api.core.IBox;
import buildcraft.api.core.Position;
/**
* This interface provide contextual information when building or initializing
* blueprint slots.
*/
public interface IBuilderContext {
Position rotatePositionLeft(Position pos);
IBox surroundingBox();
World world();
MappingRegistry getMappingRegistry();
}
@@ -0,0 +1,15 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import net.minecraft.inventory.IInventory;
public interface ITileBuilder extends IInventory {
boolean isBuildingMaterialSlot(int i);
}
@@ -0,0 +1,174 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.util.ArrayList;
import java.util.HashMap;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.item.Item;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
public class MappingRegistry {
public HashMap<Block, Integer> blockToId = new HashMap<Block, Integer>();
public ArrayList<Block> idToBlock = new ArrayList<Block>();
public HashMap<Item, Integer> itemToId = new HashMap<Item, Integer>();
public ArrayList<Item> idToItem = new ArrayList<Item>();
public HashMap<Class<? extends Entity>, Integer> entityToId = new HashMap<Class<? extends Entity>, Integer>();
public ArrayList<Class<? extends Entity>> idToEntity = new ArrayList<Class<? extends Entity>>();
private void registerItem (Item item) {
if (!itemToId.containsKey(item)) {
idToItem.add(item);
itemToId.put(item, idToItem.size() - 1);
}
}
private void registerBlock (Block block) {
if (!blockToId.containsKey(block)) {
idToBlock.add(block);
blockToId.put(block, idToBlock.size() - 1);
}
}
private void registerEntity(Class<? extends Entity> entityClass) {
if (!entityToId.containsKey(entityClass)) {
idToEntity.add(entityClass);
entityToId.put(entityClass, idToEntity.size() - 1);
}
}
public Item getItemForId(int id) {
if (id >= idToItem.size()) {
return null;
}
return idToItem.get(id);
}
public int getIdForItem(Item item) {
if (!itemToId.containsKey(item)) {
registerItem(item);
}
return itemToId.get(item);
}
public Block getBlockForId(int id) {
if (id >= idToBlock.size()) {
return null;
}
return idToBlock.get(id);
}
public int getIdForBlock(Block block) {
if (!blockToId.containsKey(block)) {
registerBlock (block);
}
return blockToId.get(block);
}
public Class<? extends Entity> getEntityForId(int id) {
if (id >= idToEntity.size()) {
return null;
}
return idToEntity.get(id);
}
public int getIdForEntity(Class<? extends Entity> entity) {
if (!entityToId.containsKey(entity)) {
registerEntity (entity);
}
return entityToId.get(entity);
}
public void write (NBTTagCompound nbt) {
NBTTagList blocksMapping = new NBTTagList();
for (Block b : idToBlock) {
NBTTagCompound sub = new NBTTagCompound();
sub.setString("name",
Block.blockRegistry.getNameForObject(b));
blocksMapping.appendTag(sub);
}
nbt.setTag("blocksMapping", blocksMapping);
NBTTagList itemsMapping = new NBTTagList();
for (Item i : idToItem) {
NBTTagCompound sub = new NBTTagCompound();
sub.setString("name",
Item.itemRegistry.getNameForObject(i));
itemsMapping.appendTag(sub);
}
nbt.setTag("itemsMapping", itemsMapping);
NBTTagList entitiesMapping = new NBTTagList();
for (Class<? extends Entity> e : idToEntity) {
NBTTagCompound sub = new NBTTagCompound();
sub.setString("name", e.getCanonicalName());
entitiesMapping.appendTag(sub);
}
nbt.setTag("entitiesMapping", entitiesMapping);
}
public void read (NBTTagCompound nbt) {
NBTTagList blocksMapping = nbt.getTagList("blocksMapping",
Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < blocksMapping.tagCount(); ++i) {
NBTTagCompound sub = blocksMapping.getCompoundTagAt(i);
String name = sub.getString("name");
Block b = (Block) Block.blockRegistry.getObject(name);
registerBlock (b);
}
NBTTagList itemsMapping = nbt.getTagList("itemsMapping",
Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < itemsMapping.tagCount(); ++i) {
NBTTagCompound sub = itemsMapping.getCompoundTagAt(i);
String name = sub.getString("name");
Item item = (Item) Item.itemRegistry.getObject(name);
registerItem (item);
}
NBTTagList entitiesMapping = nbt.getTagList("entitiesMapping",
Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < entitiesMapping.tagCount(); ++i) {
NBTTagCompound sub = entitiesMapping.getCompoundTagAt(i);
String name = sub.getString("name");
Class<? extends Entity> e = null;
try {
e = (Class<? extends Entity>) Class.forName(name);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
registerEntity (e);
}
}
}
@@ -0,0 +1,291 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.util.LinkedList;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
import buildcraft.api.core.IInvSlot;
/**
* This class allow to specify specific behavior for blocks stored in
* blueprints:
*
* - what items needs to be used to create that block - how the block has to be
* built on the world - how to rotate the block - what extra data to store /
* load in the blueprint
*
* Default implementations of this can be seen in the package
* buildcraft.api.schematics. The class SchematicUtils provide some additional
* utilities.
*
* Blueprints perform "id translation" in case the block ids between a blueprint
* and the world installation are different. Mapping is done through the
* builder context.
*
* At blueprint load time, BuildCraft will check that each block id of the
* blueprint corresponds to the block id in the installation. If not, it will
* perform a search through the block list, and upon matching signature, it will
* translate all blocks ids of the blueprint to the installation ones. If no
* such block id is found, BuildCraft will assume that the block is not
* installed and will not load the blueprint.
*/
public abstract class Schematic {
/**
* Blocks are build in various stages, in order to make sure that a block
* can indeed be placed, and that it's unlikely to disturb other blocks.
*/
public static enum BuildingStage {
/**
* Standalone blocks can be placed in the air, and they don't change
* once placed.
*/
STANDALONE,
/**
* Supported blocks may require to be placed on a standalone block,
* e.g. a torch.
*/
SUPPORTED,
/**
* Expanding blocks will grow and may disturb other block locations,
* like e.g. water
*/
EXPANDING
}
/**
* Return true if the block on the world correspond to the block stored in
* the blueprint at the location given by the slot. By default, this
* subprogram is permissive and doesn't take into account metadata.
*/
public boolean isAlreadyBuilt(IBuilderContext context, int x, int y, int z) {
return true;
}
/**
* Return true if the block should not be placed to the world. Requirements
* will not be asked on such a block, and building will not be called. Post
* processing will still be called on these blocks though.
*/
public boolean doNotBuild() {
return false;
}
/**
* This is called each time an item matches a reqquirement, that is: (req id
* == stack id) for damageable items (req id == stack id && req dmg == stack
* dmg) for other items by default, it will increase damage of damageable
* items by the amount of damage of the requirement, and remove the intended
* amount of non damageable item.
*
* Client may override this behavior for default items. Note that this
* subprogram may be called twice with the same parameters, once with a copy
* of requirements and stack to check if the entire requirements can be
* fullfilled, and once with the real inventory. Implementer is responsible
* for updating req (with the remaining requirements if any) and stack
* (after usage)
*
* returns: what was used (similer to req, but created from stack, so that
* any NBT based differences are drawn from the correct source)
*/
public ItemStack useItem(IBuilderContext context, ItemStack req, IInvSlot slot) {
ItemStack stack = slot.getStackInSlot();
ItemStack result = stack.copy();
if (stack.isItemStackDamageable()) {
if (req.getItemDamage() + stack.getItemDamage() <= stack.getMaxDamage()) {
stack.setItemDamage(req.getItemDamage() + stack.getItemDamage());
result.setItemDamage(req.getItemDamage());
req.stackSize = 0;
}
if (stack.getItemDamage() >= stack.getMaxDamage()) {
slot.decreaseStackInSlot();
}
} else {
if (stack.stackSize >= req.stackSize) {
result.stackSize = req.stackSize;
stack.stackSize -= req.stackSize;
req.stackSize = 0;
} else {
req.stackSize -= stack.stackSize;
stack.stackSize = 0;
}
}
if (stack.stackSize == 0 && stack.getItem().getContainerItem() != null) {
Item container = stack.getItem().getContainerItem();
ItemStack newStack = new ItemStack(container);
slot.setStackInSlot(newStack);
} else if (stack.stackSize == 0) {
slot.setStackInSlot(null);
}
return result;
}
/**
* Perform a 90 degree rotation to the slot.
*/
public void rotateLeft(IBuilderContext context) {
}
/**
* Performs a transformations from world to blueprints. In particular, it should:
* - use the registry to map ids from world to blueprints
* - apply translations to all positions in the schematic to center in the
* blueprint referencial
*/
public void transformToBlueprint(MappingRegistry registry, Translation transform) {
}
/**
* Performs a transformations from blueprints to worlds. In particular, it should:
* - use the registry to map ids from blueprints to world
* - apply translations to all positions in the schematic to center in the
* builder referencial
*/
public void transformToWorld(MappingRegistry registry, Translation transform) {
}
/**
* Places the block in the world, at the location specified in the slot,
* using the stack in parameters
*/
public void writeToWorld(IBuilderContext context, int x, int y, int z, LinkedList<ItemStack> stacks) {
}
/**
* Initializes a slot from the blueprint according to an objet placed on {x,
* y, z} on the world. This typically means adding entries in slot.cpt. Note
* that "id" and "meta" will be set automatically, corresponding to the
* block id and meta.
*
* By default, if the block is a BlockContainer, tile information will be to
* save / load the block.
*/
public void readFromWorld(IBuilderContext context, int x, int y, int z) {
}
/**
* Called on a block when the blueprint has finished to place all the
* blocks. This may be useful to adjust variable depending on surrounding
* blocks that may not be there already at initial building.
*/
public void postProcessing(IBuilderContext context, int x, int y, int z) {
}
public void readRequirementsFromWorld(IBuilderContext context, int x, int y, int z) {
}
/**
* Returns the requirements needed to build this block. When the
* requirements are met, they will be removed all at once from the builder,
* before calling buildBlock.
*/
public void writeRequirementsToBuilder(IBuilderContext context, LinkedList<ItemStack> requirements) {
}
public void writeToNBT(NBTTagCompound nbt, MappingRegistry registry) {
}
public void readFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
}
public void inventorySlotsToBlueprint (MappingRegistry registry, NBTTagCompound nbt) {
inventorySlotsToBlueprint(registry, nbt, "Items");
}
public void inventorySlotsToBlueprint (MappingRegistry registry, NBTTagCompound nbt, String nbtName) {
if (!nbt.hasKey(nbtName)) {
return;
}
NBTTagList list = nbt.getTagList(nbtName,
Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < list.tagCount(); ++i) {
NBTTagCompound invSlot = list.getCompoundTagAt(i);
Item item = Item.getItemById(invSlot.getInteger ("id"));
invSlot.setInteger("id", registry.getIdForItem(item));
}
}
public void inventorySlotsToWorld (MappingRegistry registry, NBTTagCompound nbt) {
inventorySlotsToWorld (registry, nbt, "Items");
}
public void inventorySlotsToWorld (MappingRegistry registry, NBTTagCompound nbt, String nbtName) {
if (!nbt.hasKey(nbtName)) {
return;
}
NBTTagList list = nbt.getTagList(nbtName,
Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < list.tagCount(); ++i) {
NBTTagCompound invSlot = list.getCompoundTagAt(i);
Item item = registry.getItemForId(invSlot.getInteger ("id"));
invSlot.setInteger("id", Item.getIdFromItem(item));
}
}
public LinkedList<ItemStack> getStacksToDisplay(
LinkedList<ItemStack> stackConsumed) {
return stackConsumed;
}
/**
* Return the stage where this schematic has to be built.
*/
public BuildingStage getBuildStage () {
return BuildingStage.STANDALONE;
}
/**
* Return the building permission for blueprint containing this schematic.
*/
public BuildingPermission getBuildingPermission () {
return BuildingPermission.ALL;
}
/**
* Returns the amount of energy required to build this slot, depends on the
* stacks selected for the build.
*/
public double getEnergyRequirement(LinkedList<ItemStack> stacksUsed) {
double result = 0;
for (ItemStack s : stacksUsed) {
result += s.stackSize * SchematicRegistry.BUILD_ENERGY;
}
return result;
}
}
@@ -0,0 +1,165 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.util.ArrayList;
import java.util.LinkedList;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.BlockLiquid;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.BlockFluidBase;
public class SchematicBlock extends SchematicBlockBase {
public Block block = null;
public int meta = 0;
public BuildingPermission defaultPermission = BuildingPermission.ALL;
/**
* This field contains requirements for a given block when stored in the
* blueprint. Modders can either rely on this list or compute their own int
* Schematic.
*/
public ItemStack [] storedRequirements = new ItemStack [0];
@Override
public void writeRequirementsToBuilder(IBuilderContext context, LinkedList<ItemStack> requirements) {
if (block != null) {
if (storedRequirements.length != 0) {
for (ItemStack s : storedRequirements) {
requirements.add(s);
}
} else {
requirements.add(new ItemStack(block, 1, meta));
}
}
}
@Override
public boolean isAlreadyBuilt(IBuilderContext context, int x, int y, int z) {
return block == context.world().getBlock(x, y, z) && meta == context.world().getBlockMetadata(x, y, z);
}
@Override
public void rotateLeft(IBuilderContext context) {
}
@Override
public void writeToWorld(IBuilderContext context, int x, int y, int z, LinkedList<ItemStack> stacks) {
// Meta needs to be specified twice, depending on the block behavior
context.world().setBlock(x, y, z, block, meta, 3);
context.world().setBlockMetadataWithNotify(x, y, z, meta, 3);
}
@Override
public boolean doNotBuild() {
return false;
}
@Override
public void readFromWorld(IBuilderContext context, int x, int y, int z) {
}
@Override
public void readRequirementsFromWorld(IBuilderContext context, int x, int y, int z) {
super.readRequirementsFromWorld(context, x, y, z);
if (block != null) {
ArrayList<ItemStack> req = block.getDrops(context.world(), x,
y, z, context.world().getBlockMetadata(x, y, z), 0);
if (req != null) {
storedRequirements = new ItemStack [req.size()];
req.toArray(storedRequirements);
}
}
}
@Override
public void writeToNBT(NBTTagCompound nbt, MappingRegistry registry) {
nbt.setInteger("blockId", registry.getIdForBlock(block));
nbt.setInteger("blockMeta", meta);
if (storedRequirements.length > 0) {
NBTTagList rq = new NBTTagList();
for (ItemStack stack : storedRequirements) {
NBTTagCompound sub = new NBTTagCompound();
stack.writeToNBT(stack.writeToNBT(sub));
sub.setInteger("id", registry.getIdForItem(stack.getItem()));
rq.appendTag(sub);
}
nbt.setTag("rq", rq);
}
}
@Override
public void readFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
block = registry.getBlockForId(nbt.getInteger("blockId"));
meta = nbt.getInteger("blockMeta");
if (nbt.hasKey("rq")) {
NBTTagList rq = nbt.getTagList("rq", Constants.NBT.TAG_COMPOUND);
ArrayList<ItemStack> rqs = new ArrayList<ItemStack>();
for (int i = 0; i < rq.tagCount(); ++i) {
try {
NBTTagCompound sub = rq.getCompoundTagAt(i);
if (sub.getInteger("id") >= 0) {
// Maps the id in the blueprint to the id in the world
sub.setInteger("id", Item.itemRegistry
.getIDForObject(registry.getItemForId(sub
.getInteger("id"))));
rqs.add(ItemStack.loadItemStackFromNBT(sub));
} else {
defaultPermission = BuildingPermission.CREATIVE_ONLY;
}
} catch (Throwable t) {
t.printStackTrace();
defaultPermission = BuildingPermission.CREATIVE_ONLY;
}
}
storedRequirements = rqs.toArray(new ItemStack[rqs.size()]);
} else {
storedRequirements = new ItemStack[0];
}
}
@Override
public BuildingStage getBuildStage () {
if (block instanceof BlockFalling) {
return BuildingStage.SUPPORTED;
} else if (block instanceof BlockFluidBase || block instanceof BlockLiquid) {
return BuildingStage.EXPANDING;
} else if (block.isOpaqueCube()) {
return BuildingStage.STANDALONE;
} else {
return BuildingStage.SUPPORTED;
}
}
@Override
public BuildingPermission getBuildingPermission() {
return defaultPermission;
}
}
@@ -0,0 +1,37 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
/**
* This class allow to specify specific behavior for blocks stored in
* blueprints:
*
* - what items needs to be used to create that block - how the block has to be
* built on the world - how to rotate the block - what extra data to store /
* load in the blueprint
*
* Default implementations of this can be seen in the package
* buildcraft.api.schematics. The class SchematicUtils provide some additional
* utilities.
*
* Blueprints perform "id translation" in case the block ids between a blueprint
* and the world installation are different. Mapping is done through the
* builder context.
*
* At blueprint load time, BuildCraft will check that each block id of the
* blueprint corresponds to the block id in the installation. If not, it will
* perform a search through the block list, and upon matching signature, it will
* translate all blocks ids of the blueprint to the installation ones. If no
* such block id is found, BuildCraft will assume that the block is not
* installed and will not load the blueprint.
*/
public abstract class SchematicBlockBase extends Schematic {
}
@@ -0,0 +1,198 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.util.ArrayList;
import java.util.LinkedList;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagFloat;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
import buildcraft.api.core.Position;
public class SchematicEntity extends Schematic {
public Class<? extends Entity> entity;
public NBTTagCompound cpt = new NBTTagCompound();
/**
* This field contains requirements for a given block when stored in the
* blueprint. Modders can either rely on this list or compute their own int
* Schematic.
*/
public ItemStack[] storedRequirements = new ItemStack[0];
@Override
public void writeRequirementsToBuilder(IBuilderContext context, LinkedList<ItemStack> requirements) {
for (ItemStack s : storedRequirements) {
requirements.add(s);
}
}
public void writeToWorld(IBuilderContext context) {
Entity e = EntityList.createEntityFromNBT(cpt, context.world());
context.world().spawnEntityInWorld(e);
}
public void readFromWorld(IBuilderContext context, Entity entity) {
entity.writeToNBTOptional(cpt);
}
@Override
public void transformToBlueprint(MappingRegistry registry,
Translation transform) {
NBTTagList nbttaglist = cpt.getTagList("Pos", 6);
Position pos = new Position(nbttaglist.func_150309_d(0),
nbttaglist.func_150309_d(1), nbttaglist.func_150309_d(2));
pos = transform.translate(pos);
cpt.setTag("Pos",
this.newDoubleNBTList(pos.x, pos.y, pos.z));
inventorySlotsToBlueprint(registry, cpt);
}
@Override
public void transformToWorld(MappingRegistry registry, Translation transform) {
NBTTagList nbttaglist = cpt.getTagList("Pos", 6);
Position pos = new Position(nbttaglist.func_150309_d(0),
nbttaglist.func_150309_d(1), nbttaglist.func_150309_d(2));
pos = transform.translate(pos);
cpt.setTag("Pos",
this.newDoubleNBTList(pos.x, pos.y, pos.z));
inventorySlotsToWorld(registry, cpt);
}
@Override
public void rotateLeft(IBuilderContext context) {
NBTTagList nbttaglist = cpt.getTagList("Pos", 6);
Position pos = new Position(nbttaglist.func_150309_d(0),
nbttaglist.func_150309_d(1), nbttaglist.func_150309_d(2));
pos = context.rotatePositionLeft(pos);
cpt.setTag("Pos",
this.newDoubleNBTList(pos.x, pos.y, pos.z));
nbttaglist = cpt.getTagList("Rotation", 5);
float yaw = nbttaglist.func_150308_e(0);
yaw += 90;
cpt.setTag(
"Rotation",
this.newFloatNBTList(yaw,
nbttaglist.func_150308_e(1)));
}
@Override
public void writeToNBT(NBTTagCompound nbt, MappingRegistry registry) {
NBTTagList nbttaglist = cpt.getTagList("Pos", 6);
nbt.setInteger("entityId", registry.getIdForEntity(entity));
nbt.setTag("entity", cpt);
NBTTagList rq = new NBTTagList();
for (ItemStack stack : storedRequirements) {
NBTTagCompound sub = new NBTTagCompound();
stack.writeToNBT(stack.writeToNBT(sub));
sub.setInteger("id", registry.getIdForItem(stack.getItem()));
rq.appendTag(sub);
}
nbt.setTag("rq", rq);
}
@Override
public void readFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
cpt = nbt.getCompoundTag("entity");
NBTTagList rq = nbt.getTagList("rq",
Constants.NBT.TAG_COMPOUND);
ArrayList<ItemStack> rqs = new ArrayList<ItemStack>();
for (int i = 0; i < rq.tagCount(); ++i) {
try {
NBTTagCompound sub = rq.getCompoundTagAt(i);
if (sub.getInteger("id") >= 0) {
// Maps the id in the blueprint to the id in the world
sub.setInteger("id", Item.itemRegistry
.getIDForObject(registry.getItemForId(sub
.getInteger("id"))));
rqs.add(ItemStack.loadItemStackFromNBT(sub));
} else {
// TODO: requirement can't be retreived, this blueprint is
// only useable in creative
}
} catch (Throwable t) {
t.printStackTrace();
// TODO: requirement can't be retreived, this blueprint is
// only useable in creative
}
}
storedRequirements = rqs.toArray(new ItemStack[rqs.size()]);
}
protected NBTTagList newDoubleNBTList(double... par1ArrayOfDouble) {
NBTTagList nbttaglist = new NBTTagList();
double[] adouble = par1ArrayOfDouble;
int i = par1ArrayOfDouble.length;
for (int j = 0; j < i; ++j) {
double d1 = adouble[j];
nbttaglist.appendTag(new NBTTagDouble(d1));
}
return nbttaglist;
}
protected NBTTagList newFloatNBTList(float... par1ArrayOfFloat) {
NBTTagList nbttaglist = new NBTTagList();
float[] afloat = par1ArrayOfFloat;
int i = par1ArrayOfFloat.length;
for (int j = 0; j < i; ++j) {
float f1 = afloat[j];
nbttaglist.appendTag(new NBTTagFloat(f1));
}
return nbttaglist;
}
public boolean isAlreadyBuilt(IBuilderContext context) {
NBTTagList nbttaglist = cpt.getTagList("Pos", 6);
Position newPosition = new Position(nbttaglist.func_150309_d(0),
nbttaglist.func_150309_d(1), nbttaglist.func_150309_d(2));
for (Object o : context.world().loadedEntityList) {
Entity e = (Entity) o;
Position existingPositon = new Position(e.posX, e.posY, e.posZ);
if (existingPositon.isClose(newPosition, 0.1F)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,54 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.util.HashMap;
import net.minecraft.nbt.NBTTagCompound;
public abstract class SchematicFactory<S extends Schematic> {
private static final HashMap<String, SchematicFactory> factories = new HashMap<String, SchematicFactory>();
private static final HashMap<Class<? extends Schematic>, SchematicFactory> schematicToFactory = new HashMap<Class<? extends Schematic>, SchematicFactory>();
protected abstract S loadSchematicFromWorldNBT (NBTTagCompound nbt, MappingRegistry registry);
public void saveSchematicToWorldNBT (NBTTagCompound nbt, S object, MappingRegistry registry) {
nbt.setString("factoryID", getClass().getCanonicalName());
}
public static Schematic createSchematicFromWorldNBT (NBTTagCompound nbt, MappingRegistry registry) {
String factoryName = nbt.getString("factoryID");
if (factories.containsKey(factoryName)) {
return factories.get(factoryName).loadSchematicFromWorldNBT(nbt, registry);
} else {
return null;
}
}
public static void registerSchematicFactory(Class<? extends Schematic> clas, SchematicFactory factory) {
schematicToFactory.put(clas, factory);
factories.put(factory.getClass().getCanonicalName(), factory);
}
public static SchematicFactory getFactory(Class<? extends Schematic> clas) {
Class superClass = clas.getSuperclass();
if (schematicToFactory.containsKey(clas)) {
return schematicToFactory.get(clas);
} else if (superClass != null) {
return getFactory(superClass);
} else {
return null;
}
}
}
@@ -0,0 +1,70 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.util.LinkedList;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import buildcraft.api.core.BuildCraftAPI;
public class SchematicMask extends SchematicBlockBase {
public boolean isConcrete = true;
public SchematicMask () {
}
public SchematicMask (boolean isConcrete) {
this.isConcrete = isConcrete;
}
@Override
public void writeToWorld(IBuilderContext context, int x, int y, int z, LinkedList<ItemStack> stacks) {
if (isConcrete) {
if (stacks.size() == 0 || !BuildCraftAPI.isSoftBlock(context.world(), x, y, z)) {
return;
} else {
ItemStack stack = stacks.getFirst();
// force the block to be air block, in case it's just a soft
// block which replacement is not straightforward
context.world().setBlock(x, y, z, Blocks.air, 0, 3);
stack.tryPlaceItemIntoWorld(
BuildCraftAPI.proxy.getBuildCraftPlayer(context.world()),
context.world(), x, y, z, 1, 0.0f, 0.0f, 0.0f);
}
} else {
context.world().setBlock(x, y, z, Blocks.air, 0, 3);
}
}
@Override
public boolean isAlreadyBuilt(IBuilderContext context, int x, int y, int z) {
if (isConcrete) {
return !BuildCraftAPI.isSoftBlock(context.world(), x, y, z);
} else {
return BuildCraftAPI.isSoftBlock(context.world(), x, y, z);
}
}
@Override
public void writeToNBT(NBTTagCompound nbt, MappingRegistry registry) {
nbt.setBoolean("isConcrete", isConcrete);
}
@Override
public void readFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
isConcrete = nbt.getBoolean("isConcrete");
}
}
@@ -0,0 +1,177 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.HashSet;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import buildcraft.api.core.JavaTools;
public final class SchematicRegistry {
public static double BREAK_ENERGY = 10;
public static final double BUILD_ENERGY = 20;
private static final HashSet<Block> explicitSchematicBlocks = new HashSet<Block>();
private static final HashMap<Block, SchematicConstructor> schematicBlocks =
new HashMap<Block, SchematicConstructor>();
private static final HashMap<Class<? extends Entity>, SchematicConstructor> schematicEntities = new HashMap<Class<? extends Entity>, SchematicConstructor>();
private static final HashSet<String> modsSupporting = new HashSet<String>();
private static final HashSet<String> modsForbidden = new HashSet<String>();
private static final HashSet<String> blocksForbidden = new HashSet<String>();
/**
* Deactivate constructor
*/
private SchematicRegistry() {
}
private static class SchematicConstructor {
Class<? extends SchematicEntity> clas;
Object [] params;
}
public static void registerSchematicBlock (Block block, Class clas, Object ... params) {
explicitSchematicBlocks.add(block);
internalRegisterSchematicBlock(block, clas, params);
}
private static void internalRegisterSchematicBlock (Block block, Class clas, Object ... params) {
SchematicConstructor c = new SchematicConstructor ();
c.clas = clas;
c.params = params;
schematicBlocks.put(block, c);
}
public static void registerSchematicEntity(
Class<? extends Entity> entityClass,
Class<? extends SchematicEntity> schematicClass, Object... params) {
SchematicConstructor c = new SchematicConstructor ();
c.clas = schematicClass;
c.params = params;
schematicEntities.put(entityClass, c);
}
public static SchematicBlock newSchematicBlock (Block block) {
if (block == Blocks.air) {
return null;
}
if (!schematicBlocks.containsKey(block)) {
if (block instanceof ITileEntityProvider) {
internalRegisterSchematicBlock(block, SchematicTile.class);
} else {
internalRegisterSchematicBlock(block, SchematicBlock.class);
}
}
try {
SchematicConstructor c = schematicBlocks.get(block);
SchematicBlock s = (SchematicBlock) c.clas.getConstructors() [0].newInstance(c.params);
s.block = block;
return s;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return null;
}
public static SchematicEntity newSchematicEntity(Class<? extends Entity> entityClass) {
if (!schematicEntities.containsKey(entityClass)) {
return null;
}
try {
SchematicConstructor c = schematicEntities.get(entityClass);
SchematicEntity s = (SchematicEntity) c.clas.getConstructors() [0].newInstance(c.params);
s.entity = entityClass;
return s;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return null;
}
public static void declareBlueprintSupport (String modid) {
modsSupporting.add(modid);
}
public static boolean isExplicitlySupported (Block block) {
String modid = Block.blockRegistry.getNameForObject(block).split(":") [0];
return explicitSchematicBlocks.contains(block) || modsSupporting.contains(modid);
}
public static boolean isAllowedForBuilding (Block block) {
String name = Block.blockRegistry.getNameForObject(block);
String modid = name.split(":") [0];
return !modsForbidden.contains(modid) && !blocksForbidden.contains(name);
}
public static void readConfiguration (Configuration conf) {
Property excludedMods = conf.get(Configuration.CATEGORY_GENERAL, "builder.excludedMods", new String [0],
"mods that should be excluded from the builder.");
Property excludedBlocks = conf.get(Configuration.CATEGORY_GENERAL, "builder.excludedBlocks", new String [0],
"blocks that should be excluded from the builder.");
for (String id : excludedMods.getStringList()) {
String strippedId = JavaTools.stripSurroundingQuotes(id.trim());
if (strippedId.length() > 0) {
modsForbidden.add(strippedId);
}
}
for (String id : excludedBlocks.getStringList()) {
String strippedId = JavaTools.stripSurroundingQuotes(id.trim());
if (strippedId.length() > 0) {
blocksForbidden.add(strippedId);
}
}
}
static {
modsSupporting.add ("minecraft");
}
}
@@ -0,0 +1,111 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.util.ArrayList;
import java.util.LinkedList;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import buildcraft.api.core.JavaTools;
public class SchematicTile extends SchematicBlock {
/**
* This tree contains additional data to be stored in the blueprint. By
* default, it will be initialized from Schematic.readFromWord with
* the standard readNBT function of the corresponding tile (if any) and will
* be loaded from BptBlock.buildBlock using the standard writeNBT function.
*/
public NBTTagCompound cpt = new NBTTagCompound();
@Override
public void transformToBlueprint(MappingRegistry registry, Translation transform) {
inventorySlotsToBlueprint(registry, cpt);
}
@Override
public void transformToWorld(MappingRegistry registry, Translation transform) {
inventorySlotsToWorld(registry, cpt);
}
/**
* Places the block in the world, at the location specified in the slot.
*/
@Override
public void writeToWorld(IBuilderContext context, int x, int y, int z, LinkedList<ItemStack> stacks) {
super.writeToWorld(context, x, y, z, stacks);
if (block.hasTileEntity(meta)) {
TileEntity tile = context.world().getTileEntity(x, y, z);
cpt.setInteger("x", x);
cpt.setInteger("y", y);
cpt.setInteger("z", z);
if (tile != null) {
tile.readFromNBT(cpt);
}
}
}
@Override
public void readFromWorld(IBuilderContext context, int x, int y, int z) {
super.readFromWorld(context, x, y, z);
if (block.hasTileEntity(meta)) {
TileEntity tile = context.world().getTileEntity(x, y, z);
if (tile != null) {
tile.writeToNBT(cpt);
}
}
}
@Override
public void readRequirementsFromWorld(IBuilderContext context, int x, int y, int z) {
super.readRequirementsFromWorld(context, x, y, z);
if (block.hasTileEntity(meta)) {
TileEntity tile = context.world().getTileEntity(x, y, z);
if (tile instanceof IInventory) {
IInventory inv = (IInventory) tile;
ArrayList<ItemStack> rqs = new ArrayList<ItemStack>();
for (int i = 0; i < inv.getSizeInventory(); ++i) {
if (inv.getStackInSlot(i) != null) {
rqs.add(inv.getStackInSlot(i));
}
}
storedRequirements = JavaTools.concat(storedRequirements,
rqs.toArray(new ItemStack[rqs.size()]));
}
}
}
@Override
public void writeToNBT(NBTTagCompound nbt, MappingRegistry registry) {
super.writeToNBT(nbt, registry);
nbt.setTag("blockCpt", cpt);
}
@Override
public void readFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
super.readFromNBT(nbt, registry);
cpt = nbt.getCompoundTag("blockCpt");
}
}
@@ -0,0 +1,34 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import buildcraft.api.core.Position;
public class Translation {
public double x = 0;
public double y = 0;
public double z = 0;
public Position translate (Position p) {
Position p2 = new Position (p);
p2.x = p.x + x;
p2.y = p.y + y;
p2.z = p.z + z;
return p2;
}
@Override
public String toString () {
return "{" + x + ", " + y + ", " + z + "}";
}
}
@@ -0,0 +1,11 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "1.0", owner = "BuildCraftAPI|core", provides = "BuildCraftAPI|blueprints")
package buildcraft.api.blueprints;
import cpw.mods.fml.common.API;
@@ -0,0 +1,60 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class BCLog {
public static final Logger logger = Logger.getLogger("Buildcraft");
/**
* Deactivate constructor
*/
private BCLog() {
}
public static void initLog() {
// TODO: check if the code below is still useful and remove otherwise.
//logger.setParent(FMLLog.getLogger());
logger.info("Starting BuildCraft " + getVersion());
logger.info("Copyright (c) SpaceToad, 2011");
logger.info("http://www.mod-buildcraft.com");
}
public static void logErrorAPI(String mod, Throwable error, Class classFile) {
StringBuilder msg = new StringBuilder(mod);
msg.append(" API error, please update your mods. Error: ").append(error);
StackTraceElement[] stackTrace = error.getStackTrace();
if (stackTrace.length > 0) {
msg.append(", ").append(stackTrace[0]);
}
logger.log(Level.SEVERE, msg.toString());
if (classFile != null) {
msg = new StringBuilder(mod);
msg.append(" API error: ").append(classFile.getSimpleName()).append(" is loaded from ").append(classFile.getProtectionDomain().getCodeSource().getLocation());
logger.log(Level.SEVERE, msg.toString());
}
}
public static String getVersion() {
try {
Class<?> clazz = Class.forName("buildcraft.core.Version");
Method method = clazz.getDeclaredMethod("getVersion");
return String.valueOf(method.invoke(null));
} catch (Exception e) {
return "UNKNOWN VERSION";
}
}
}
@@ -0,0 +1,37 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
public final class BuildCraftAPI {
public static ICoreProxy proxy;
public static final Set<Block> softBlocks = new HashSet<Block>();
/**
* Deactivate constructor
*/
private BuildCraftAPI() {
}
public static boolean isSoftBlock(IBlockAccess world, int x, int y, int z) {
return isSoftBlock(world.getBlock(x, y, z), world, x, y, z);
}
public static boolean isSoftBlock(Block block, IBlockAccess world, int x, int y, int z) {
return block == null || BuildCraftAPI.softBlocks.contains(block) || block.isReplaceable(world, x, y, z) || block.isAir(world, x, y, z);
}
}
@@ -0,0 +1,33 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
/**
* To be implemented by TileEntities able to provide a square area on the world, typically BuildCraft markers.
*/
public interface IAreaProvider {
int xMin();
int yMin();
int zMin();
int xMax();
int yMax();
int zMax();
/**
* Remove from the world all objects used to define the area.
*/
void removeFromWorld();
}
@@ -0,0 +1,25 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
public interface IBox {
IBox expand(int amount);
IBox contract(int amount);
boolean contains(double x, double y, double z);
Position pMin();
Position pMax();
void createLaserData();
}
@@ -0,0 +1,16 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
public interface ICoreProxy {
EntityPlayer getBuildCraftPlayer(World world);
}
@@ -0,0 +1,32 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public interface IIconProvider {
/**
* @param iconIndex
*/
@SideOnly(Side.CLIENT)
IIcon getIcon(int iconIndex);
/**
* A call for the provider to register its Icons. This may be called multiple times but should only be executed once per provider
* @param iconRegister
*/
@SideOnly(Side.CLIENT)
void registerIcons(IIconRegister iconRegister);
}
@@ -0,0 +1,30 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import net.minecraft.item.ItemStack;
public interface IInvSlot {
/**
* Returns the slot number of the underlying Inventory.
*
* @return the slot number
*/
int getIndex();
boolean canPutStackInSlot(ItemStack stack);
boolean canTakeStackFromSlot(ItemStack stack);
ItemStack decreaseStackInSlot();
ItemStack getStackInSlot();
void setStackInSlot(ItemStack stack);
}
@@ -0,0 +1,89 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JavaTools {
public static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public static int[] concat(int[] first, int[] second) {
int[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public static float[] concat(float[] first, float[] second) {
float[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public <T> T[] concatenate (T[] a, T[] b) {
int aLen = a.length;
int bLen = b.length;
@SuppressWarnings("unchecked")
T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
public static List<Field> getAllFields(Class clas) {
List<Field> result = new ArrayList<Field>();
Class current = clas;
while (current != null && current != Object.class) {
for (Field f : current.getDeclaredFields()) {
result.add(f);
}
current = current.getSuperclass();
}
return result;
}
public static List<Method> getAllMethods(Class clas) {
List<Method> result = new ArrayList<Method>();
Class current = clas;
while (current != null && current != Object.class) {
for (Method m : current.getDeclaredMethods()) {
result.add(m);
}
current = current.getSuperclass();
}
return result;
}
public static String surroundWithQuotes(String stringToSurroundWithQuotes) {
return String.format("\"%s\"", stringToSurroundWithQuotes);
}
public static String stripSurroundingQuotes(String stringToStripQuotes) {
return stringToStripQuotes.replaceAll("^\"|\"$", "");
}
}
@@ -0,0 +1,19 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface NetworkData {
}
@@ -0,0 +1,166 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
public class Position {
@NetworkData
public double x, y, z;
@NetworkData
public ForgeDirection orientation;
public Position() {
x = 0;
y = 0;
z = 0;
orientation = ForgeDirection.UNKNOWN;
}
public Position(double ci, double cj, double ck) {
x = ci;
y = cj;
z = ck;
orientation = ForgeDirection.UNKNOWN;
}
public Position(double ci, double cj, double ck, ForgeDirection corientation) {
x = ci;
y = cj;
z = ck;
orientation = corientation;
}
public Position(Position p) {
x = p.x;
y = p.y;
z = p.z;
orientation = p.orientation;
}
public Position(NBTTagCompound nbttagcompound) {
readFromNBT(nbttagcompound);
}
public Position(TileEntity tile) {
x = tile.xCoord;
y = tile.yCoord;
z = tile.zCoord;
}
public void moveRight(double step) {
switch (orientation) {
case SOUTH:
x = x - step;
break;
case NORTH:
x = x + step;
break;
case EAST:
z = z + step;
break;
case WEST:
z = z - step;
break;
default:
}
}
public void moveLeft(double step) {
moveRight(-step);
}
public void moveForwards(double step) {
switch (orientation) {
case UP:
y = y + step;
break;
case DOWN:
y = y - step;
break;
case SOUTH:
z = z + step;
break;
case NORTH:
z = z - step;
break;
case EAST:
x = x + step;
break;
case WEST:
x = x - step;
break;
default:
}
}
public void moveBackwards(double step) {
moveForwards(-step);
}
public void moveUp(double step) {
switch (orientation) {
case SOUTH:
case NORTH:
case EAST:
case WEST:
y = y + step;
break;
default:
}
}
public void moveDown(double step) {
moveUp(-step);
}
public void writeToNBT(NBTTagCompound nbttagcompound) {
nbttagcompound.setDouble("i", x);
nbttagcompound.setDouble("j", y);
nbttagcompound.setDouble("k", z);
nbttagcompound.setByte("orientation", (byte) orientation.ordinal());
}
public void readFromNBT(NBTTagCompound nbttagcompound) {
x = nbttagcompound.getDouble("i");
y = nbttagcompound.getDouble("j");
z = nbttagcompound.getDouble("k");
orientation = ForgeDirection.values() [nbttagcompound.getByte("orientation")];
}
@Override
public String toString() {
return "{" + x + ", " + y + ", " + z + "}";
}
public Position min(Position p) {
return new Position(p.x > x ? x : p.x, p.y > y ? y : p.y, p.z > z ? z : p.z);
}
public Position max(Position p) {
return new Position(p.x < x ? x : p.x, p.y < y ? y : p.y, p.z < z ? z : p.z);
}
public boolean isClose(Position newPosition, float f) {
double dx = x - newPosition.x;
double dy = y - newPosition.y;
double dz = z - newPosition.z;
double sqrDis = dx * dx + dy * dy + dz * dz;
return !(sqrDis > f * f);
}
}
@@ -0,0 +1,85 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import net.minecraft.world.World;
public class SafeTimeTracker {
private long lastMark = Long.MIN_VALUE;
private long duration = -1;
private long randomRange = 0;
private long lastRandomDelay = 0;
private long internalDelay = 1;
/**
* @deprecated should use constructors with parameters instead
*/
public SafeTimeTracker () {
}
public SafeTimeTracker (long delay) {
internalDelay = delay;
}
/**
* In many situations, it is a bad idea to have all objects of the same
* kind to be waiting for the exact same amount of time, as that can lead
* to some situation where they're all synchronized and got to work all
* at the same time. When created with a random range, the mark that is set
* when reaching the expect delay will be added with a random number
* between [0, range[, meaning that the event will take between 0 and range
* more tick to run.
*/
public SafeTimeTracker (long delay, long random) {
internalDelay = delay;
randomRange = random;
}
public boolean markTimeIfDelay(World world) {
return markTimeIfDelay(world, internalDelay);
}
/**
* Return true if a given delay has passed since last time marked was called
* successfully.
*
* @deprecated should use the constructor with a delay instead, and call
* this function without a parameter
*/
public boolean markTimeIfDelay(World world, long delay) {
if (world == null) {
return false;
}
long currentTime = world.getTotalWorldTime();
if (currentTime < lastMark) {
lastMark = currentTime;
return false;
} else if (lastMark + delay + lastRandomDelay <= currentTime) {
duration = currentTime - lastMark;
lastMark = currentTime;
lastRandomDelay = (int) (Math.random() * randomRange);
return true;
} else {
return false;
}
}
public long durationOfLastDelay() {
return duration > 0 ? duration : 0;
}
public void markTime(World world) {
lastMark = world.getTotalWorldTime();
}
}
@@ -0,0 +1,56 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import net.minecraft.item.ItemStack;
/**
* This class is used whenever stacks needs to be stored as keys.
*/
public class StackKey {
public final ItemStack stack;
public StackKey(ItemStack stack) {
this.stack = stack;
}
@Override
public int hashCode() {
int hash = 5;
hash = 67 * hash + stack.getItem().hashCode();
hash = 67 * hash + stack.getItemDamage();
if (stack.stackTagCompound != null) {
hash = 67 * hash + stack.stackTagCompound.hashCode();
}
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (getClass() != obj.getClass()) {
return false;
}
final StackKey other = (StackKey) obj;
if (stack.getItem() != other.stack.getItem()) {
return false;
} else if (stack.getHasSubtypes() && stack.getItemDamage() != other.stack.getItemDamage()) {
return false;
} else {
return !(stack.stackTagCompound != null && !stack.stackTagCompound.equals(other.stack.stackTagCompound));
}
}
}
@@ -0,0 +1,11 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "1.0", owner = "BuildCraft|Core", provides = "BuildCraftAPI|core")
package buildcraft.api.core;
import cpw.mods.fml.common.API;
@@ -0,0 +1,20 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.filler;
public final class FillerManager {
public static IFillerRegistry registry;
/**
* Deactivate constructor
*/
private FillerManager() {
}
}
@@ -0,0 +1,24 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.filler;
import net.minecraft.util.IIcon;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public interface IFillerPattern {
String getUniqueTag();
@SideOnly(Side.CLIENT)
IIcon getIcon();
String getDisplayName();
}
@@ -0,0 +1,26 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.filler;
import java.util.Set;
import buildcraft.api.gates.IAction;
public interface IFillerRegistry {
void addPattern(IFillerPattern pattern);
IFillerPattern getPattern(String patternName);
IFillerPattern getNextPattern(IFillerPattern currentPattern);
IFillerPattern getPreviousPattern(IFillerPattern currentPattern);
Set<? extends IAction> getActions();
}
@@ -0,0 +1,11 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "2.0", owner = "BuildCraftAPI|core", provides = "BuildCraftAPI|filler")
package buildcraft.api.filler;
import cpw.mods.fml.common.API;
@@ -0,0 +1,92 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.fuels;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import buildcraft.api.core.StackKey;
public final class IronEngineCoolant {
public static Map<String, Coolant> liquidCoolants = new HashMap<String, Coolant>();
public static Map<StackKey, FluidStack> solidCoolants = new HashMap<StackKey, FluidStack>();
private IronEngineCoolant() {
}
public static FluidStack getFluidCoolant(ItemStack stack) {
return solidCoolants.get(new StackKey(stack));
}
public static Coolant getCoolant(ItemStack stack) {
return getCoolant(getFluidCoolant(stack));
}
public static Coolant getCoolant(FluidStack fluidStack) {
return fluidStack != null && fluidStack.getFluid() != null ? liquidCoolants.get(fluidStack.getFluid().getName()) : null;
}
public interface Coolant {
float getDegreesCoolingPerMB(float currentHeat);
}
public static void addCoolant(final Fluid fluid, final float degreesCoolingPerMB) {
if (fluid != null) {
liquidCoolants.put(fluid.getName(), new Coolant() {
@Override
public float getDegreesCoolingPerMB(float currentHeat) {
return degreesCoolingPerMB;
}
});
}
}
/**
* Adds a solid coolant like Ice Blocks. The FluidStack must contain a registered
* Coolant Fluid or nothing will happen. You do not need to call this for
* Fluid Containers.
*
* @param stack
* @param coolant
*/
public static void addCoolant(final ItemStack stack, final FluidStack coolant) {
if (stack != null && stack.getItem() != null && coolant != null) {
solidCoolants.put(new StackKey(stack), coolant);
}
}
/**
* Adds a solid coolant like Ice Blocks. The FluidStack must contain a
* registered Coolant Fluid or nothing will happen. You do not need to call
* this for Fluid Containers.
*
* @param item
* @param coolant
*/
public static void addCoolant(final Item item, final int metadata, final FluidStack coolant) {
addCoolant(new ItemStack(item, 1, metadata), coolant);
}
public static void addCoolant(final Block block, final int metadata, final FluidStack coolant) {
addCoolant(new ItemStack(block, 1, metadata), coolant);
}
public static boolean isCoolant(Fluid fluid) {
return liquidCoolants.containsKey(fluid.getName());
}
}
@@ -0,0 +1,52 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.fuels;
import java.util.HashMap;
import java.util.Map;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
public final class IronEngineFuel {
public static Map<String, Fuel> fuels = new HashMap<String, Fuel>();
private IronEngineFuel() {
}
public static Fuel getFuelForFluid(Fluid liquid) {
return liquid == null ? null : fuels.get(liquid.getName());
}
public static final class Fuel {
public final Fluid liquid;
public final float powerPerCycle;
public final int totalBurningTime;
private Fuel(String fluidName, float powerPerCycle, int totalBurningTime) {
this(FluidRegistry.getFluid(fluidName), powerPerCycle, totalBurningTime);
}
private Fuel(Fluid liquid, float powerPerCycle, int totalBurningTime) {
this.liquid = liquid;
this.powerPerCycle = powerPerCycle;
this.totalBurningTime = totalBurningTime;
}
}
public static void addFuel(Fluid fluid, float powerPerCycle, int totalBurningTime) {
fuels.put(fluid.getName(), new Fuel(fluid, powerPerCycle, totalBurningTime));
}
public static void addFuel(String fluidName, float powerPerCycle, int totalBurningTime) {
fuels.put(fluidName, new Fuel(fluidName, powerPerCycle, totalBurningTime));
}
}
@@ -0,0 +1,11 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "1.0", owner = "BuildCraftAPI|core", provides = "BuildCraftAPI|fuels")
package buildcraft.api.fuels;
import cpw.mods.fml.common.API;
@@ -0,0 +1,107 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import buildcraft.api.transport.IPipeTile;
public final class ActionManager {
public static Map<String, ITrigger> triggers = new HashMap<String, ITrigger>();
public static Map<String, IAction> actions = new HashMap<String, IAction>();
private static List<ITriggerProvider> triggerProviders = new LinkedList<ITriggerProvider>();
private static List<IActionProvider> actionProviders = new LinkedList<IActionProvider>();
/**
* Deactivate constructor
*/
private ActionManager() {
}
public static void registerTriggerProvider(ITriggerProvider provider) {
if (provider != null && !triggerProviders.contains(provider)) {
triggerProviders.add(provider);
}
}
public static void registerTrigger(ITrigger trigger) {
triggers.put(trigger.getUniqueTag(), trigger);
}
public static void registerAction(IAction action) {
actions.put(action.getUniqueTag(), action);
}
public static List<ITrigger> getNeighborTriggers(Block block, TileEntity entity) {
List<ITrigger> result = new LinkedList<ITrigger>();
for (ITriggerProvider provider : triggerProviders) {
List<ITrigger> toAdd = provider.getNeighborTriggers(block, entity);
if (toAdd != null) {
for (ITrigger t : toAdd) {
if (!result.contains(t)) {
result.add(t);
}
}
}
}
return result;
}
public static void registerActionProvider(IActionProvider provider) {
if (provider != null && !actionProviders.contains(provider)) {
actionProviders.add(provider);
}
}
public static List<IAction> getNeighborActions(Block block, TileEntity entity) {
List<IAction> result = new LinkedList<IAction>();
for (IActionProvider provider : actionProviders) {
List<IAction> toAdd = provider.getNeighborActions(block, entity);
if (toAdd != null) {
for (IAction t : toAdd) {
if (!result.contains(t)) {
result.add(t);
}
}
}
}
return result;
}
public static List<ITrigger> getPipeTriggers(IPipeTile pipe) {
List<ITrigger> result = new LinkedList<ITrigger>();
for (ITriggerProvider provider : triggerProviders) {
List<ITrigger> toAdd = provider.getPipeTriggers(pipe);
if (toAdd != null) {
for (ITrigger t : toAdd) {
if (!result.contains(t)) {
result.add(t);
}
}
}
}
return result;
}
}
@@ -0,0 +1,58 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import java.util.List;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
public abstract class GateExpansionController {
public final IGateExpansion type;
public final TileEntity pipeTile;
public GateExpansionController(IGateExpansion type, TileEntity pipeTile) {
this.pipeTile = pipeTile;
this.type = type;
}
public IGateExpansion getType() {
return type;
}
public boolean isActive() {
return false;
}
public void tick() {
}
public void startResolution() {
}
public boolean resolveAction(IAction action, int count) {
return false;
}
public boolean isTriggerActive(ITrigger trigger, ITriggerParameter parameter) {
return false;
}
public void addTriggers(List<ITrigger> list) {
}
public void addActions(List<IAction> list) {
}
public void writeToNBT(NBTTagCompound nbt) {
}
public void readFromNBT(NBTTagCompound nbt) {
}
}
@@ -0,0 +1,68 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public final class GateExpansions {
private static final Map<String, IGateExpansion> expansions = new HashMap<String, IGateExpansion>();
private static final BiMap<Byte, String> serverIDMap = HashBiMap.create();
private static final BiMap<Byte, String> clientIDMap = HashBiMap.create();
private static byte nextID = 0;
private GateExpansions() {
}
public static void registerExpansion(IGateExpansion expansion) {
registerExpansion(expansion.getUniqueIdentifier(), expansion);
}
public static void registerExpansion(String identifier, IGateExpansion expansion) {
expansions.put(identifier, expansion);
serverIDMap.put(nextID++, identifier);
}
public static IGateExpansion getExpansion(String identifier) {
return expansions.get(identifier);
}
public static IGateExpansion getExpansionClient(int id) {
if (id < 0 || id >= 128) {
return null;
} else {
return expansions.get(clientIDMap.get((byte) id));
}
}
public static byte getServerExpansionID(String identifier) {
return serverIDMap.inverse().get(identifier);
}
public static Set<IGateExpansion> getExpansions() {
Set<IGateExpansion> set = new HashSet<IGateExpansion>();
set.addAll(expansions.values());
return set;
}
public static BiMap<Byte, String> getServerMap() {
return serverIDMap;
}
public static void setClientMap(BiMap<Byte, String> map) {
clientIDMap.clear();
clientIDMap.putAll(map);
}
}
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public interface IAction {
String getUniqueTag();
@SideOnly(Side.CLIENT)
IIcon getIcon();
@SideOnly(Side.CLIENT)
void registerIcons(IIconRegister iconRegister);
boolean hasParameter();
String getDescription();
IAction rotateLeft();
}
@@ -0,0 +1,22 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import java.util.LinkedList;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
public interface IActionProvider {
/**
* Returns the list of actions available to a gate next to the given block.
*/
LinkedList<IAction> getNeighborActions(Block block, TileEntity tile);
}
@@ -0,0 +1,13 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
public interface IActionReceptor {
void actionActivated(IAction action);
}
@@ -0,0 +1,30 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
public interface IGateExpansion {
String getUniqueIdentifier();
String getDisplayName();
GateExpansionController makeController(TileEntity pipeTile);
void registerBlockOverlay(IIconRegister iconRegister);
void registerItemOverlay(IIconRegister iconRegister);
IIcon getOverlayBlock();
IIcon getOverlayItem();
}
@@ -0,0 +1,20 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import java.util.LinkedList;
/**
* This interface has to be implemented by a TileEntity or a Pipe that wants to provide triggers different from the ones installed by default with BuildCraft.
*/
public interface IOverrideDefaultTriggers {
LinkedList<ITrigger> getTriggers();
}
@@ -0,0 +1,21 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
public interface ITileTrigger extends ITrigger {
/**
* Return true if the tile given in parameter activates the trigger, given
* the parameters.
*/
boolean isTriggerActive(ForgeDirection side, TileEntity tile, ITriggerParameter parameter);
}
@@ -0,0 +1,58 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public interface ITrigger {
/**
* Every trigger needs a unique tag, it should be in the format of
* "<modid>:<name>".
*
* @return the unique id
*/
String getUniqueTag();
@SideOnly(Side.CLIENT)
IIcon getIcon();
@SideOnly(Side.CLIENT)
void registerIcons(IIconRegister iconRegister);
/**
* Return true if this trigger can accept parameters
*/
boolean hasParameter();
/**
* Return true if this trigger requires a parameter
*/
boolean requiresParameter();
/**
* Return the trigger description in the UI
*/
String getDescription();
/**
* Create parameters for the trigger. As for now, there is only one kind of
* trigger parameter available so this subprogram is final.
*/
ITriggerParameter createParameter();
/**
* This returns the trigger after a left rotation. Used in particular in
* blueprints orientation.
*/
ITrigger rotateLeft();
}
@@ -0,0 +1,27 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public interface ITriggerParameter {
ItemStack getItemStack();
void set(ItemStack stack);
void writeToNBT(NBTTagCompound compound);
void readFromNBT(NBTTagCompound compound);
@Deprecated
ItemStack getItem();
}
@@ -0,0 +1,30 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import java.util.LinkedList;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import buildcraft.api.transport.IPipeTile;
public interface ITriggerProvider {
/**
* Returns the list of triggers that are available from the pipe holding the gate.
*/
LinkedList<ITrigger> getPipeTriggers(IPipeTile pipe);
/**
* Returns the list of triggers available to a gate next to the given block.
*/
LinkedList<ITrigger> getNeighborTriggers(Block block, TileEntity tile);
}
@@ -0,0 +1,79 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.gates;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class TriggerParameter implements ITriggerParameter {
protected ItemStack stack;
/*
* (non-Javadoc)
*
* @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#getItemStack()
*/
@Override
public ItemStack getItemStack() {
return stack;
}
/*
* (non-Javadoc)
*
* @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#set(net.minecraft.src.ItemStack)
*/
@Override
public void set(ItemStack stack) {
if (stack != null) {
this.stack = stack.copy();
this.stack.stackSize = 1;
}
}
/*
* (non-Javadoc)
*
* @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#writeToNBT(net.minecraft.src.NBTTagCompound)
*/
@Override
public void writeToNBT(NBTTagCompound compound) {
if (stack != null) {
NBTTagCompound tagCompound = new NBTTagCompound();
stack.writeToNBT(tagCompound);
compound.setTag("stack", tagCompound);
}
}
/*
* (non-Javadoc)
*
* @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#readFromNBT(net.minecraft.src.NBTTagCompound)
*/
@Override
public void readFromNBT(NBTTagCompound compound) {
// Legacy code to prevent existing gates from losing their contents
int itemID = compound.getInteger("itemID");
if (itemID != 0) {
stack = new ItemStack((Item) Item.itemRegistry.getObject(itemID), 1, compound.getInteger("itemDMG"));
return;
}
stack = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("stack"));
}
@Override
@Deprecated
public ItemStack getItem() {
return stack;
}
}
@@ -0,0 +1,12 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "2.0", owner = "BuildCraftAPI|core", provides = "BuildCraftAPI|gates")
package buildcraft.api.gates;
import cpw.mods.fml.common.API;
+200
View File
@@ -0,0 +1,200 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.mj;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import buildcraft.api.core.JavaTools;
import buildcraft.api.power.PowerHandler;
public final class MjAPI {
static Map<Class, BatteryField> MjBatteries = new HashMap<Class, BatteryField>();
private enum BatteryKind {
Value, Container
}
private static class BatteryField {
public Field field;
public MjBattery battery;
public BatteryKind kind;
}
public static class BatteryObject {
Field f;
Object o;
MjBattery b;
public double getEnergyRequested() {
try {
double contained = f.getDouble(o);
double left = contained + b.maxReceivedPerCycle() > b
.maxCapacity() ? b.maxCapacity() - contained : b
.maxReceivedPerCycle();
if (left > 0) {
return left;
} else {
return b.minimumConsumption();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return 0;
}
public double addEnergy(double watts) {
try {
double e = f.getDouble(o);
double max = b.maxCapacity();
double used = e + watts <= max ? watts : max - e;
f.setDouble(o, e + used);
return used;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return 0;
}
public double getEnergyStored() {
try {
return f.getDouble(o);
} catch (IllegalAccessException e) {
e.printStackTrace();
return 0;
}
}
public void setEnergyStored(double watts) {
try {
f.setDouble(o, watts);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public double maxCapacity() {
return b.maxCapacity();
}
public double minimumConsumption() {
return b.minimumConsumption();
}
public double maxReceivedPerCycle() {
return b.maxReceivedPerCycle();
}
public BatteryObject reconfigure(final double maxCapacity, final double maxReceivedPerCycle, final double minimumConsumption) {
b = new MjBattery() {
@Override
public double maxCapacity() {
return maxCapacity;
}
@Override
public double maxReceivedPerCycle() {
return maxReceivedPerCycle;
}
@Override
public double minimumConsumption() {
return minimumConsumption;
}
@Override
public Class<? extends Annotation> annotationType() {
return MjBattery.class;
}
};
return this;
}
}
/**
* Deactivate constructor
*/
private MjAPI() {
}
public static BatteryObject getMjBattery(Object o) {
if (o == null) {
return null;
}
if (o.getClass() == PowerHandler.class) {
return ((PowerHandler) o).getMjBattery();
}
BatteryField f = getMjBattery(o.getClass());
if (f == null) {
return null;
} else if (f.kind == BatteryKind.Value) {
BatteryObject obj = new BatteryObject();
obj.o = o;
obj.f = f.field;
obj.b = f.battery;
return obj;
} else {
try {
return getMjBattery(f.field.get(o));
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
}
private static BatteryField getMjBattery(Class c) {
if (!MjBatteries.containsKey(c)) {
for (Field f : JavaTools.getAllFields(c)) {
MjBattery battery = f.getAnnotation(MjBattery.class);
if (battery != null) {
f.setAccessible(true);
BatteryField bField = new BatteryField();
bField.field = f;
bField.battery = battery;
if (double.class.equals(f.getType())) {
bField.kind = BatteryKind.Value;
} else if (f.getType().isPrimitive()) {
throw new RuntimeException(
"MJ battery needs to be object or double type");
} else {
bField.kind = BatteryKind.Container;
}
MjBatteries.put(c, bField);
return bField;
}
}
MjBatteries.put(c, null);
return null;
} else {
return MjBatteries.get(c);
}
}
}
@@ -0,0 +1,65 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.mj;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import buildcraft.api.power.IPowerReceptor;
import buildcraft.api.power.PowerHandler;
public class MjAPILegacy implements IPowerReceptor {
private final PowerHandler powerHandler;
private final World world;
protected MjAPILegacy(World world, MjAPI.BatteryObject battery, PowerHandler.Type type) {
if (battery == null) {
throw new NullPointerException();
}
this.world = world;
this.powerHandler = new PowerHandler(this, type, battery);
}
public static MjAPILegacy from(World world, MjAPI.BatteryObject battery, PowerHandler.Type type) {
return new MjAPILegacy(world, battery, type);
}
public static MjAPILegacy from(World world, Object object, PowerHandler.Type type) {
return new MjAPILegacy(world, battery(object), type);
}
public static MjAPILegacy from(TileEntity tileEntity, PowerHandler.Type type) {
return new MjAPILegacy(tileEntity.getWorldObj(), battery(tileEntity), type);
}
private static MjAPI.BatteryObject battery(Object object) {
MjAPI.BatteryObject battery = MjAPI.getMjBattery(object);
if (battery == null) {
throw new IllegalArgumentException(String.format("Object %s not using MjAPI, can't create legacy wrapper", object));
}
return battery;
}
@Override
public PowerHandler.PowerReceiver getPowerReceiver(ForgeDirection side) {
return powerHandler.getPowerReceiver();
}
@Override
public void doWork(PowerHandler workProvider) {
}
@Override
public World getWorld() {
return world;
}
}
@@ -0,0 +1,44 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.mj;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used for tiles that need to interface with BuildCraft
* energy framework, a.k.a MinecraftJoule or MJ. In order to receive power,
* tiles, need to declare a *public* double field, with the annotation
* MjBattery. BuildCraft machines able to provide power will then connect to
* these tiles, and feed energy up to max capacity. It's the responsibilty
* of the implementer to manually decrease the value of the energy, as he
* simulates energy consumption. On each cycle, per power input, machines can
* receive up to "maxReceivedPerCyle" units of energy. As an optional behavior,
* the system can have a minimum amount of energy consumed even if the system
* is at max capacity, modelized by the "minimumConsumption" value.
*
* If the field designated by MjBattery is an object, then BuildCraft will
* consider that this is a case of a nested battery, and will look for the
* field in the designated object.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
public @interface MjBattery {
double maxCapacity() default 100.0;
double maxReceivedPerCycle() default 10.0;
double minimumConsumption() default 0.1;
}
@@ -0,0 +1,11 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "1.0", owner = "BuildCraft|Core", provides = "BuildCraftAPI|core")
package buildcraft.api;
import cpw.mods.fml.common.API;
@@ -0,0 +1,41 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.power;
public interface ILaserTarget {
/**
* Returns true if the target currently needs power. For example, if the Advanced
* Crafting Table has work to do.
*
* @return true if needs power
*/
boolean requiresLaserEnergy();
/**
* Transfers energy from the laser to the target.
*
* @param energy
*/
void receiveLaserEnergy(double energy);
/**
* Return true if the Tile Entity object is no longer a valid target. For
* example, if its been invalidated.
*
* @return true if no longer a valid target object
*/
boolean isInvalidTarget();
int getXCoord();
int getYCoord();
int getZCoord();
}
@@ -0,0 +1,21 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.power;
import net.minecraftforge.common.util.ForgeDirection;
/**
* Essentially only used for Wooden Power Pipe connection rules.
*
* This Tile Entity interface allows you to indicate that a block can emit power
* from a specific side.
*/
public interface IPowerEmitter {
boolean canEmitPowerFrom(ForgeDirection side);
}
@@ -0,0 +1,45 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.power;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
/**
* This interface should be implemented by any Tile Entity that wishes to be
* able to receive power.
*/
public interface IPowerReceptor {
/**
* Get the PowerReceiver for this side of the block. You can return the same
* PowerReceiver for all sides or one for each side.
*
* You should NOT return null to this method unless you mean to NEVER
* receive power from that side. Returning null, after previous returning a
* PowerReceiver, will most likely cause pipe connections to derp out and
* engines to eventually explode.
*
* @param side
*/
PowerHandler.PowerReceiver getPowerReceiver(ForgeDirection side);
/**
* Call back from the PowerHandler that is called when the stored power
* exceeds the activation power.
*
* It can be triggered by update() calls or power modification calls.
*
* @param workProvider
*/
void doWork(PowerHandler workProvider);
World getWorld();
}
@@ -0,0 +1,506 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.power;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.ForgeDirection;
import buildcraft.api.core.SafeTimeTracker;
import buildcraft.api.mj.MjAPI;
import buildcraft.api.mj.MjBattery;
/**
* The PowerHandler is similar to FluidTank in that it holds your power and
* allows standardized interaction between machines.
* <p/>
* To receive power to your machine you needs create an instance of PowerHandler
* and implement IPowerReceptor on the TileEntity.
* <p/>
* If you plan emit power, you need only implement IPowerEmitter. You do not
* need a PowerHandler. Engines have a PowerHandler because they can also
* receive power from other Engines.
* <p/>
* See TileRefinery for a simple example of a power using machine.
*
* @see IPowerReceptor
* @see IPowerEmitter
*/
public final class PowerHandler {
public static enum Type {
ENGINE, GATE, MACHINE, PIPE, STORAGE;
public boolean canReceiveFromPipes() {
switch (this) {
case MACHINE:
case STORAGE:
return true;
default:
return false;
}
}
public boolean eatsEngineExcess() {
switch (this) {
case MACHINE:
case STORAGE:
return true;
default:
return false;
}
}
}
/**
* Extend this class to create custom Perdition algorithms (its not final).
* <p/>
* NOTE: It is not possible to create a Zero perdition algorithm.
*/
public static class PerditionCalculator {
public static final float DEFAULT_POWERLOSS = 1F;
public static final float MIN_POWERLOSS = 0.01F;
private final double powerLoss;
public PerditionCalculator() {
powerLoss = DEFAULT_POWERLOSS;
}
/**
* Simple constructor for simple Perdition per tick.
*
* @param powerLoss power loss per tick
*/
public PerditionCalculator(double powerLoss) {
if (powerLoss < MIN_POWERLOSS) {
this.powerLoss = MIN_POWERLOSS;
} else {
this.powerLoss = powerLoss;
}
}
/**
* Apply the perdition algorithm to the current stored energy. This
* function can only be called once per tick, but it might not be called
* every tick. It is triggered by any manipulation of the stored energy.
*
* @param powerHandler the PowerHandler requesting the perdition update
* @param current the current stored energy
* @param ticksPassed ticks since the last time this function was called
*/
public double applyPerdition(PowerHandler powerHandler, double current, long ticksPassed) {
double newPower = current - powerLoss * ticksPassed;
if (newPower < 0) {
newPower = 0;
}
return newPower;
}
/**
* Taxes a flat rate on all incoming power.
* <p/>
* Defaults to 0% tax rate.
*
* @return percent of input to tax
*/
public double getTaxPercent() {
return 0;
}
}
public static final PerditionCalculator DEFAULT_PERDITION = new PerditionCalculator();
public static final double ROLLING_AVERAGE_WEIGHT = 100.0;
public static final double ROLLING_AVERAGE_NUMERATOR = ROLLING_AVERAGE_WEIGHT - 1;
public static final double ROLLING_AVERAGE_DENOMINATOR = 1.0 / ROLLING_AVERAGE_WEIGHT;
public final int[] powerSources = new int[6];
public final IPowerReceptor receptor;
private double activationEnergy;
private final SafeTimeTracker doWorkTracker = new SafeTimeTracker();
private final SafeTimeTracker sourcesTracker = new SafeTimeTracker();
private final SafeTimeTracker perditionTracker = new SafeTimeTracker();
private PerditionCalculator perdition;
private final PowerReceiver receiver;
private final Type type;
private MjAPI.BatteryObject battery;
// Tracking
private double averageLostPower = 0;
private double averageReceivedPower = 0;
private double averageUsedPower = 0;
public PowerHandler(IPowerReceptor receptor, Type type) {
this(receptor, type, null);
}
public PowerHandler(IPowerReceptor receptor, Type type, Object battery) {
this.receptor = receptor;
this.type = type;
this.receiver = new PowerReceiver();
this.perdition = DEFAULT_PERDITION;
if (battery instanceof MjAPI.BatteryObject) {
this.battery = (MjAPI.BatteryObject) battery;
} else if (battery != null) {
this.battery = MjAPI.getMjBattery(battery);
} else {
this.battery = MjAPI.getMjBattery(new AnonymousBattery());
}
}
public PowerReceiver getPowerReceiver() {
return receiver;
}
public double getMinEnergyReceived() {
return battery.minimumConsumption();
}
public double getMaxEnergyReceived() {
return battery.getEnergyRequested();
}
public double getMaxEnergyStored() {
return battery.maxCapacity();
}
public double getActivationEnergy() {
return activationEnergy;
}
public double getEnergyStored() {
return battery.getEnergyStored();
}
public MjAPI.BatteryObject getMjBattery() {
return battery;
}
/**
* Setup your PowerHandler's settings.
*
* @param minEnergyReceived
* This is the minimum about of power that will be accepted by
* the PowerHandler. This should generally be greater than the
* activationEnergy if you plan to use the doWork() callback.
* Anything greater than 1 will prevent Redstone Engines from
* powering this Provider.
* @param maxEnergyReceived
* The maximum amount of power accepted by the PowerHandler. This
* should generally be less than 500. Too low and larger engines
* will overheat while trying to power the machine. Too high, and
* the engines will never warm up. Greater values also place
* greater strain on the power net.
* @param activationEnergy
* If the stored energy is greater than this value, the doWork()
* callback is called (once per tick).
* @param maxStoredEnergy
* The maximum amount of power this PowerHandler can store.
* Values tend to range between 100 and 5000. With 1000 and 1500
* being common.
*/
public void configure(double minEnergyReceived, double maxEnergyReceived, double activationEnergy,
double maxStoredEnergy) {
double localMaxEnergyReceived = maxEnergyReceived;
if (minEnergyReceived > localMaxEnergyReceived) {
localMaxEnergyReceived = minEnergyReceived;
}
this.activationEnergy = activationEnergy;
battery.reconfigure(maxStoredEnergy, localMaxEnergyReceived, minEnergyReceived);
}
/**
* Allows you define perdition in terms of loss/ticks.
* <p/>
* This function is mostly for legacy implementations. See
* PerditionCalculator for more complex perdition formulas.
*
* @param powerLoss
* @param powerLossRegularity
* @see PerditionCalculator
*/
public void configurePowerPerdition(int powerLoss, int powerLossRegularity) {
if (powerLoss == 0 || powerLossRegularity == 0) {
perdition = new PerditionCalculator(0);
return;
}
perdition = new PerditionCalculator((float) powerLoss / (float) powerLossRegularity);
}
/**
* Allows you to define a new PerditionCalculator class to handler perdition
* calculations.
* <p/>
* For example if you want exponentially increasing loss based on amount
* stored.
*
* @param perdition
*/
public void setPerdition(PerditionCalculator perdition) {
if (perdition == null) {
this.perdition = DEFAULT_PERDITION;
} else {
this.perdition = perdition;
}
}
public PerditionCalculator getPerdition() {
if (perdition == null) {
return DEFAULT_PERDITION;
} else {
return perdition;
}
}
/**
* Ticks the power handler. You should call this if you can, but its not
* required.
* <p/>
* If you don't call it, the possibility exists for some weirdness with the
* perdition algorithm and work callback as its possible they will not be
* called on every tick they otherwise would be. You should be able to
* design around this though if you are aware of the limitations.
*/
public void update() {
applyPerdition();
applyWork();
validateEnergy();
}
private void applyPerdition() {
double energyStored = getEnergyStored();
if (perditionTracker.markTimeIfDelay(receptor.getWorld(), 1) && energyStored > 0) {
double prev = energyStored;
double newEnergy = getPerdition().applyPerdition(this, energyStored, perditionTracker.durationOfLastDelay());
if (newEnergy == 0 || newEnergy < energyStored) {
battery.setEnergyStored(energyStored = newEnergy);
} else {
battery.setEnergyStored(energyStored = DEFAULT_PERDITION.applyPerdition(this, energyStored, perditionTracker.durationOfLastDelay()));
}
validateEnergy();
averageLostPower = (averageLostPower * ROLLING_AVERAGE_NUMERATOR + (prev - energyStored)) * ROLLING_AVERAGE_DENOMINATOR;
}
}
private void applyWork() {
if (getEnergyStored() >= activationEnergy) {
if (doWorkTracker.markTimeIfDelay(receptor.getWorld(), 1)) {
receptor.doWork(this);
}
}
}
private void updateSources(ForgeDirection source) {
if (sourcesTracker.markTimeIfDelay(receptor.getWorld(), 1)) {
for (int i = 0; i < 6; ++i) {
powerSources[i] -= sourcesTracker.durationOfLastDelay();
if (powerSources[i] < 0) {
powerSources[i] = 0;
}
}
}
if (source != null) {
powerSources[source.ordinal()] = 10;
}
}
/**
* Extract energy from the PowerHandler. You must call this even if doWork()
* triggers.
*
* @param min
* @param max
* @param doUse
* @return amount used
*/
public double useEnergy(double min, double max, boolean doUse) {
applyPerdition();
double result = 0;
double energyStored = getEnergyStored();
if (energyStored >= min) {
if (energyStored <= max) {
result = energyStored;
if (doUse) {
energyStored = 0;
}
} else {
result = max;
if (doUse) {
energyStored -= max;
}
}
}
if (energyStored != getEnergyStored()) {
battery.setEnergyStored(energyStored);
}
validateEnergy();
if (doUse) {
averageUsedPower = (averageUsedPower * ROLLING_AVERAGE_NUMERATOR + result) * ROLLING_AVERAGE_DENOMINATOR;
}
return result;
}
public void readFromNBT(NBTTagCompound data) {
readFromNBT(data, "powerProvider");
}
public void readFromNBT(NBTTagCompound data, String tag) {
NBTTagCompound nbt = data.getCompoundTag(tag);
battery.setEnergyStored(nbt.getDouble("energyStored"));
}
public void writeToNBT(NBTTagCompound data) {
writeToNBT(data, "powerProvider");
}
public void writeToNBT(NBTTagCompound data, String tag) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setDouble("energyStored", battery.getEnergyStored());
data.setTag(tag, nbt);
}
public final class PowerReceiver {
private PowerReceiver() {
}
public double getMinEnergyReceived() {
return PowerHandler.this.getMinEnergyReceived();
}
public double getMaxEnergyReceived() {
return PowerHandler.this.getMaxEnergyReceived();
}
public double getMaxEnergyStored() {
return PowerHandler.this.getMaxEnergyStored();
}
public double getActivationEnergy() {
return activationEnergy;
}
public double getEnergyStored() {
return PowerHandler.this.getEnergyStored();
}
public double getAveragePowerReceived() {
return averageReceivedPower;
}
public double getAveragePowerUsed() {
return averageUsedPower;
}
public double getAveragePowerLost() {
return averageLostPower;
}
public Type getType() {
return type;
}
public void update() {
PowerHandler.this.update();
}
/**
* The amount of power that this PowerHandler currently needs.
*/
public double powerRequest() {
update();
return battery.getEnergyRequested();
}
/**
* Add power to the PowerReceiver from an external source.
* <p/>
* IPowerEmitters are responsible for calling this themselves.
*
* @param quantity
* @param from
* @return the amount of power used
*/
public double receiveEnergy(Type source, final double quantity, ForgeDirection from) {
double used = quantity;
if (source == Type.ENGINE) {
if (used < getMinEnergyReceived()) {
return 0;
} else if (used > getMaxEnergyReceived()) {
used = getMaxEnergyReceived();
}
}
updateSources(from);
used -= used * getPerdition().getTaxPercent();
used = addEnergy(used);
applyWork();
if (source == Type.ENGINE && type.eatsEngineExcess()) {
used = Math.min(quantity, getMaxEnergyReceived());
}
averageReceivedPower = (averageReceivedPower * ROLLING_AVERAGE_NUMERATOR + used) * ROLLING_AVERAGE_DENOMINATOR;
return used;
}
}
/**
* @return the amount the power changed by
*/
public double addEnergy(double quantity) {
final double used = battery.addEnergy(quantity);
applyPerdition();
return used;
}
public void setEnergy(double quantity) {
battery.setEnergyStored(quantity);
validateEnergy();
}
public boolean isPowerSource(ForgeDirection from) {
return powerSources[from.ordinal()] != 0;
}
private void validateEnergy() {
double energyStored = getEnergyStored();
double maxEnergyStored = getMaxEnergyStored();
if (energyStored < 0) {
energyStored = 0;
}
if (energyStored > maxEnergyStored) {
energyStored = maxEnergyStored;
}
if (energyStored != battery.getEnergyStored()) {
battery.setEnergyStored(energyStored);
}
}
private static class AnonymousBattery {
@MjBattery
public double mjStored;
}
}
@@ -0,0 +1,11 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "1.1", owner = "BuildCraftAPI|core", provides = "BuildCraftAPI|power")
package buildcraft.api.power;
import cpw.mods.fml.common.API;
@@ -0,0 +1,19 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.recipes;
public final class BuildcraftRecipes {
public static IAssemblyRecipeManager assemblyTable;
public static IIntegrationRecipeManager integrationTable;
public static IRefineryRecipeManager refinery;
private BuildcraftRecipes() {
}
}
@@ -0,0 +1,40 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.recipes;
import java.util.List;
import net.minecraft.item.ItemStack;
public interface IAssemblyRecipeManager {
public interface IAssemblyRecipe {
ItemStack getOutput();
Object[] getInputs();
double getEnergyCost();
}
/**
* Add an Assembly Table recipe.
*
* @param input
* Object... containing either an ItemStack, or a paired string
* and integer(ex: "dyeBlue", 1)
* @param energyCost
* MJ cost to produce
* @param output
* resulting ItemStack
*/
void addRecipe(double energyCost, ItemStack output, Object... input);
List<? extends IAssemblyRecipe> getRecipes();
}
@@ -0,0 +1,46 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.recipes;
import java.util.List;
import net.minecraft.item.ItemStack;
/**
* The Integration Table's primary purpose is to modify an input item's NBT
* data. As such its not a "traditional" type of recipe. Rather than predefined
* inputs and outputs, it takes an input and transforms it.
*/
public interface IIntegrationRecipeManager {
public interface IIntegrationRecipe {
double getEnergyCost();
boolean isValidInputA(ItemStack inputA);
boolean isValidInputB(ItemStack inputB);
ItemStack getOutputForInputs(ItemStack inputA, ItemStack inputB, ItemStack[] components);
ItemStack[] getComponents();
ItemStack[] getExampleInputsA();
ItemStack[] getExampleInputsB();
}
/**
* Add an Integration Table recipe.
*
*/
void addRecipe(IIntegrationRecipe recipe);
List<? extends IIntegrationRecipe> getRecipes();
}
@@ -0,0 +1,37 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.recipes;
import java.util.SortedSet;
import net.minecraftforge.fluids.FluidStack;
public interface IRefineryRecipeManager {
void addRecipe(FluidStack ingredient, FluidStack result, int energy, int delay);
void addRecipe(FluidStack ingredient1, FluidStack ingredient2, FluidStack result, int energy, int delay);
SortedSet<? extends IRefineryRecipe> getRecipes();
IRefineryRecipe findRefineryRecipe(FluidStack ingredient1, FluidStack ingredient2);
public interface IRefineryRecipe {
FluidStack getIngredient1();
FluidStack getIngredient2();
FluidStack getResult();
int getEnergyCost();
int getTimeRequired();
}
}
@@ -0,0 +1,12 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "2.0", owner = "BuildCraftAPI|core", provides = "BuildCraftAPI|recipes")
package buildcraft.api.recipes;
import cpw.mods.fml.common.API;
@@ -0,0 +1,40 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.tools;
import net.minecraft.entity.player.EntityPlayer;
/***
* Implement this interface on subclasses of Item to have that item work as a wrench for buildcraft
*/
public interface IToolWrench {
/***
* Called to ensure that the wrench can be used. To get the ItemStack that is used, check player.inventory.getCurrentItem()
*
* @param player
* - The player doing the wrenching
* @param x
* ,y,z - The coordinates for the block being wrenched
*
* @return true if wrenching is allowed, false if not
*/
boolean canWrench(EntityPlayer player, int x, int y, int z);
/***
* Callback after the wrench has been used. This can be used to decrease durability or for other purposes. To get the ItemStack that was used, check
* player.inventory.getCurrentItem()
*
* @param player
* - The player doing the wrenching
* @param x
* ,y,z - The coordinates of the block being wrenched
*/
void wrenchUsed(EntityPlayer player, int x, int y, int z);
}
@@ -0,0 +1,11 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "1.0", owner = "BuildCraftAPI|core", provides = "BuildCraftAPI|tools")
package buildcraft.api.tools;
import cpw.mods.fml.common.API;
@@ -0,0 +1,29 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.transport;
import net.minecraft.world.World;
/**
* Implement and register with the PipeManager if you want to suppress connections from wooden pipes.
*/
public interface IExtractionHandler {
/**
* Can this pipe extract items from the block located at these coordinates?
* param extractor can be null
*/
boolean canExtractItems(Object extractor, World world, int i, int j, int k);
/**
* Can this pipe extract liquids from the block located at these coordinates?
* param extractor can be null
*/
boolean canExtractFluids(Object extractor, World world, int i, int j, int k);
}
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.transport;
import net.minecraftforge.common.util.ForgeDirection;
import buildcraft.api.transport.IPipeTile.PipeType;
public interface IPipeConnection {
enum ConnectOverride {
CONNECT, DISCONNECT, DEFAULT
};
/**
* Allows you to override pipe connection logic.
*
* @param type
* @param with
* @return CONNECT to force a connection, DISCONNECT to force no connection,
* and DEFAULT to let the pipe decide.
*/
ConnectOverride overridePipeConnection(PipeType type, ForgeDirection with);
}
@@ -0,0 +1,51 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.transport;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.ForgeDirection;
public interface IPipeTile {
public enum PipeType {
ITEM, FLUID, POWER, STRUCTURE;
}
PipeType getPipeType();
/**
* Offers an ItemStack for addition to the pipe. Will be rejected if the
* pipe doesn't accept items from that side.
*
* @param stack ItemStack offered for addition. Do not manipulate this!
* @param doAdd If false no actual addition should take place. Implementors
* should simulate.
* @param from Orientation the ItemStack is offered from.
* @return Amount of items used from the passed stack.
*/
int injectItem(ItemStack stack, boolean doAdd, ForgeDirection from);
/**
* True if the pipe is connected to the block/pipe in the specific direction
*
* @param with
* @return true if connect
*/
boolean isPipeConnected(ForgeDirection with);
/**
* True if the pipe has a powered wire of the specified color.
*
* @param wire
* @return true if powered
*/
boolean isWireActive(PipeWire wire);
}
@@ -0,0 +1,49 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.transport;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.world.World;
public abstract class PipeManager {
public static List<IExtractionHandler> extractionHandlers = new ArrayList<IExtractionHandler>();
public static void registerExtractionHandler(IExtractionHandler handler) {
extractionHandlers.add(handler);
}
/**
* param extractor can be null
*/
public static boolean canExtractItems(Object extractor, World world, int i, int j, int k) {
for (IExtractionHandler handler : extractionHandlers) {
if (!handler.canExtractItems(extractor, world, i, j, k)) {
return false;
}
}
return true;
}
/**
* param extractor can be null
*/
public static boolean canExtractFluids(Object extractor, World world, int i, int j, int k) {
for (IExtractionHandler handler : extractionHandlers) {
if (!handler.canExtractFluids(extractor, world, i, j, k)) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,74 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.transport;
import java.util.Locale;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public enum PipeWire {
RED, BLUE, GREEN, YELLOW;
public static Item item;
public static final PipeWire[] VALUES = values();
public PipeWire reverse() {
switch (this) {
case RED:
return YELLOW;
case BLUE:
return GREEN;
case GREEN:
return BLUE;
default:
return RED;
}
}
public String getTag() {
return name().toLowerCase(Locale.ENGLISH) + "PipeWire";
}
public String getColor() {
String name = this.toString().toLowerCase(Locale.ENGLISH);
char first = Character.toUpperCase(name.charAt(0));
return first + name.substring(1);
}
public ItemStack getStack() {
return getStack(1);
}
public ItemStack getStack(int qty) {
if (item == null) {
return null;
} else {
return new ItemStack(item, qty, ordinal());
}
}
public boolean isPipeWire(ItemStack stack) {
if (stack == null) {
return false;
} else if (stack.getItem() != item) {
return false;
} else {
return stack.getItemDamage() == ordinal();
}
}
public static PipeWire fromOrdinal(int ordinal) {
if (ordinal < 0 || ordinal >= VALUES.length) {
return RED;
} else {
return VALUES[ordinal];
}
}
}
@@ -0,0 +1,12 @@
/**
* Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
@API(apiVersion = "2.0", owner = "BuildCraftAPI|core", provides = "BuildCraftAPI|transport")
package buildcraft.api.transport;
import cpw.mods.fml.common.API;