A new start. Clean out mantle and copy in stuff from tcon and whatever made sense from the old version

This commit is contained in:
Bernhard Bonigl committed 2015-09-27 22:07:13 +02:00
1 parent dd29c42654
commit bf8988ec62
128 files changed
+3389 -5654

No files matched your search

@@ -0,0 +1,34 @@
package slimeknights.mantle;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import slimeknights.mantle.common.CommonProxy;
/**
* Mantle
*
* Central mod object for Mantle
*
* @author Sunstrike <[email protected]>
*/
@Mod(modid = Mantle.modId, name = Mantle.modName, version = Mantle.modVersion, dependencies = "required-after:Forge@[11.14,)")
public class Mantle {
public static final String modId = "mantle";
public static final String modName = "Mantle";
public static final String modVersion = "${version}";
public static final Logger logger = LogManager.getLogger("Mantle");
/* Instance of this mod, used for grabbing prototype fields */
@Instance("mantle")
public static Mantle instance;
/* Proxies for sides, used for graphics processing */
@SidedProxy(clientSide = "slimeknights.mantle.client.ClientProxy", serverSide = "slimeknights.mantle.common.CommonProxy")
public static CommonProxy proxy;
}
@@ -0,0 +1,91 @@
package slimeknights.mantle.block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import slimeknights.mantle.tileentity.TileInventory;
// Updated Version of InventoryBlock in Mantle
public abstract class BlockInventory extends BlockContainer {
protected BlockInventory(Material material) {
super(material);
}
// inventories usually need a tileEntity
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Override
public abstract TileEntity createNewTileEntity(World worldIn, int meta);
/**
* Called when the block is activated. Return true if a GUI is opened, false if the block has no GUI.
*/
protected abstract boolean openGui(EntityPlayer player, World world, BlockPos pos);
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumFacing side,
float clickX, float clickY, float clickZ) {
if(player.isSneaking()) {
return false;
}
if(!world.isRemote) {
return this.openGui(player, world, pos);
}
return true;
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer,
ItemStack stack) {
super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
// set custom name from named stack
if(stack.hasDisplayName()) {
TileEntity tileentity = worldIn.getTileEntity(pos);
if(tileentity instanceof TileInventory) {
((TileInventory) tileentity).setCustomName(stack.getDisplayName());
}
}
}
public void breakBlock(World worldIn, BlockPos pos, IBlockState state) {
TileEntity tileentity = worldIn.getTileEntity(pos);
if(tileentity instanceof TileInventory) {
InventoryHelper.dropInventoryItems(worldIn, pos, (IInventory) tileentity);
worldIn.updateComparatorOutputLevel(pos, this);
}
super.breakBlock(worldIn, pos, state);
}
@Override
public int damageDropped(IBlockState state) {
return getMetaFromState(state);
}
// BlockContainer sets this to -1, which equals invisible
// we need 3 for standard forge rendering
@Override
public int getRenderType() {
return 3;
}
}
@@ -0,0 +1,12 @@
package slimeknights.mantle.block;
import net.minecraft.util.BlockPos;
public interface IMasterLogic
{
/** Called when servants change their state
*
* @param pos servant position
*/
public void notifyChange(IServantLogic servant, BlockPos pos);
}
@@ -0,0 +1,8 @@
package slimeknights.mantle.block;
public interface IMasterNode extends IMasterLogic, IServantLogic
{
public boolean isCurrentlyMaster();
public boolean isEquivalentMaster(IMasterLogic master);
}
@@ -0,0 +1,41 @@
package slimeknights.mantle.block;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
public interface IServantLogic
{
public BlockPos getMasterPosition();
/** The block should already have a valid master */
public void notifyMasterOfChange();
/** Checks if this block can be tied to this master
*
* @param master
* @param world the world of master
* @param pos position of master
* @return whether the servant can be tied to this master
*/
public boolean setPotentialMaster(IMasterLogic master, World world, BlockPos pos);
/** Used to set and verify that this is the block's master
*
* @param master
* @param world
* @param pos position of master
* @return Is this block tied to this master?
*/
public boolean verifyMaster(IMasterLogic master, World world, BlockPos pos);
/** Exactly what it says on the tin
*
* @param master
* @param world
* @param pos position of master
*/
public void invalidateMaster(IMasterLogic master, World world, BlockPos pos);
}
@@ -0,0 +1,196 @@
package slimeknights.mantle.block;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameData;
public class MultiServantLogic extends TileEntity implements IServantLogic
{
boolean hasMaster;
BlockPos master;
Block masterBlock;
IBlockState state;
public boolean canUpdate()
{
return false;
}
public boolean getHasMaster()
{
return this.hasMaster;
}
public boolean hasValidMaster()
{
if (!this.hasMaster)
{
return false;
}
if (this.worldObj.getBlockState(this.master).getBlock() == this.masterBlock && this.worldObj.getBlockState(this.master) == this.state)
{
return true;
}
else
{
this.hasMaster = false;
this.master = null;
return false;
}
}
@Override
public BlockPos getMasterPosition()
{
return this.master;
}
public void overrideMaster(BlockPos pos)
{
this.hasMaster = true;
this.master = pos;
this.state = this.worldObj.getBlockState(this.master);
this.masterBlock = this.state.getBlock();
}
public void removeMaster()
{
this.hasMaster = false;
this.master = null;
this.masterBlock = null;
this.state = null;
}
@Override
public boolean setPotentialMaster(IMasterLogic master, World w, BlockPos pos)
{
return !this.hasMaster;
}
@Deprecated
public boolean verifyMaster(IMasterLogic logic, BlockPos pos)
{
return this.master.equals(pos) && this.worldObj.getBlockState(pos) == this.state && this.worldObj.getBlockState(pos).getBlock() == this.masterBlock;
}
@Override
public boolean verifyMaster(IMasterLogic logic, World world, BlockPos pos)
{
if (this.hasMaster)
{
return this.hasValidMaster();
}
else
{
this.overrideMaster(pos);
return true;
}
}
@Override
public void invalidateMaster(IMasterLogic master, World w, BlockPos pos)
{
this.hasMaster = false;
master = null;
}
@Override
public void notifyMasterOfChange()
{
if (this.hasValidMaster())
{
IMasterLogic logic = (IMasterLogic) this.worldObj.getTileEntity(this.pos);
logic.notifyChange(this, this.pos);
}
}
public void readCustomNBT(NBTTagCompound tags)
{
this.hasMaster = tags.getBoolean("hasMaster");
if (this.hasMaster)
{
int xCenter = tags.getInteger("xCenter");
int yCenter = tags.getInteger("yCenter");
int zCenter = tags.getInteger("zCenter");
this.master = new BlockPos(xCenter, yCenter, zCenter);
this.masterBlock = GameData.getBlockRegistry().getObject(tags.getString("MasterBlockName"));
this.state = Block.getStateById(tags.getInteger("masterState"));
}
}
public void writeCustomNBT(NBTTagCompound tags)
{
tags.setBoolean("hasMaster", this.hasMaster);
if (this.hasMaster)
{
tags.setInteger("xCenter", this.master.getX());
tags.setInteger("yCenter", this.master.getY());
tags.setInteger("zCenter", this.master.getZ());
tags.setString("MasterBlockName", (String) GameData.getBlockRegistry().getNameForObject(this.masterBlock));
tags.setInteger("masterState", Block.getStateId(this.state));
}
}
@Override
public void readFromNBT(NBTTagCompound tags)
{
super.readFromNBT(tags);
this.readCustomNBT(tags);
}
@Override
public void writeToNBT(NBTTagCompound tags)
{
super.writeToNBT(tags);
this.writeCustomNBT(tags);
}
/* Packets */
@Override
public Packet getDescriptionPacket()
{
NBTTagCompound tag = new NBTTagCompound();
this.writeCustomNBT(tag);
return new S35PacketUpdateTileEntity(this.pos, 1, tag);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet)
{
this.readCustomNBT(packet.getNbtCompound());
this.worldObj.notifyLightSet(this.pos);
this.worldObj.markBlockForUpdate(this.pos);
}
@Override
public World getWorld()
{
return this.worldObj;
}
@Deprecated
public boolean setMaster(BlockPos pos)
{
if (!this.hasMaster || this.worldObj.getBlockState(this.master) != this.state || (this.worldObj.getBlockState(this.master).getBlock() != this.masterBlock))
{
this.overrideMaster(pos);
return true;
}
else
{
return false;
}
}
}
@@ -0,0 +1,6 @@
package slimeknights.mantle.client;
import slimeknights.mantle.common.CommonProxy;
public class ClientProxy extends CommonProxy {
}
@@ -0,0 +1,43 @@
package slimeknights.mantle.client;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class CreativeTab extends CreativeTabs {
private ItemStack icon;
// a vanilla icon in case the other one isn't present
public CreativeTab(String label, ItemStack backupIcon) {
super(label);
this.icon = backupIcon;
}
public void setDisplayIcon(ItemStack displayIcon) {
if(displayIcon != null && displayIcon.getItem() != null) {
this.icon = displayIcon;
}
}
@SideOnly(Side.CLIENT)
@Override
public ItemStack getIconItemStack() {
return icon;
}
@SideOnly(Side.CLIENT)
@Override
public int getIconItemDamage() {
return icon.getItemDamage();
}
@SideOnly(Side.CLIENT)
@Override
public Item getTabIconItem() {
return icon.getItem();
}
}
@@ -0,0 +1,170 @@
package slimeknights.mantle.client;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.IColoredBakedQuad;
import net.minecraftforge.client.model.IModelPart;
import net.minecraftforge.client.model.IModelState;
import net.minecraftforge.client.model.IPerspectiveState;
import net.minecraftforge.client.model.TRSRTransformation;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.Map;
import javax.vecmath.Vector3f;
public class ModelHelper {
static final Type maptype = new TypeToken<Map<String, String>>() {}.getType();
private static final Gson
GSON =
new GsonBuilder().registerTypeAdapter(maptype, ModelTextureDeserializer.INSTANCE).create();
public static final IPerspectiveState DEFAULT_ITEM_STATE;
public static final IPerspectiveState DEFAULT_TOOL_STATE;
public static TextureAtlasSprite getTextureFromBlock(Block block, int meta) {
IBlockState state = block.getStateFromMeta(meta);
return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state);
}
public static TextureAtlasSprite getTextureFromBlockstate(IBlockState state) {
return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state);
}
public static BakedQuad colorQuad(int color, BakedQuad quad) {
int[] data = quad.getVertexData();
int a = (color >> 24);
if(a == 0) {
a = 255;
}
int c = 0;
c |= ((color >> 16) & 0xFF) << 0; // red
c |= ((color >> 8) & 0xFF) << 8; // green
c |= ((color >> 0) & 0xFF) << 16; // blue
c |= (a & 0xFF) << 24; // alpha
// update color in the data. all 4 Vertices.
for(int i = 0; i < 4; i++) {
data[i * 7 + 3] = c;
}
return new IColoredBakedQuad.ColoredBakedQuad(data, -1, quad.getFace());
}
public static Map<String, String> loadTexturesFromJson(ResourceLocation location) throws IOException {
// get the json
IResource
iresource =
Minecraft.getMinecraft().getResourceManager()
.getResource(new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + ".json"));
Reader reader = new InputStreamReader(iresource.getInputStream(), Charsets.UTF_8);
return GSON.fromJson(reader, maptype);
}
public static ImmutableList<ResourceLocation> loadTextureListFromJson(ResourceLocation location) throws IOException {
ImmutableList.Builder<ResourceLocation> builder = ImmutableList.builder();
for(String s : loadTexturesFromJson(location).values()) {
builder.add(new ResourceLocation(s));
}
return builder.build();
}
public static ResourceLocation getModelLocation(ResourceLocation location) {
return new ResourceLocation(location.getResourceDomain(), "models/" + location.getResourcePath() + ".json");
}
public static ImmutableMap<ItemCameraTransforms.TransformType, TRSRTransformation> getTransformsFromState(IModelState state, IModelPart part) {
if(state instanceof IPerspectiveState) {
IPerspectiveState ps = (IPerspectiveState) state;
Map<ItemCameraTransforms.TransformType, TRSRTransformation> map = Maps.newHashMap();
for(ItemCameraTransforms.TransformType type : ItemCameraTransforms.TransformType.values()) {
map.put(type, ps.forPerspective(type).apply(part));
}
return Maps.immutableEnumMap(map);
}
return ImmutableMap.of();
}
static {
// equals forge:default-item
IModelState thirdperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 1f / 16, -3f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(-90, 0, 0)),
new Vector3f(0.55f, 0.55f, 0.55f),
null));
IModelState firstperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 4f / 16, 2f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, -135, 25)),
new Vector3f(1.7f, 1.7f, 1.7f),
null));
DEFAULT_ITEM_STATE = new IPerspectiveState.Impl(TRSRTransformation.identity(), ImmutableMap
.of(ItemCameraTransforms.TransformType.THIRD_PERSON, thirdperson,
ItemCameraTransforms.TransformType.FIRST_PERSON, firstperson));
thirdperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 1.25f / 16, -3.5f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, 90, -35)),
new Vector3f(0.85f, 0.85f, 0.85f),
null));
firstperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 4f / 16, 2f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, -135, 25)),
new Vector3f(1.7f, 1.7f, 1.7f),
null));
DEFAULT_TOOL_STATE = new IPerspectiveState.Impl(TRSRTransformation.identity(), ImmutableMap
.of(ItemCameraTransforms.TransformType.THIRD_PERSON, thirdperson,
ItemCameraTransforms.TransformType.FIRST_PERSON, firstperson));
}
/**
* Deseralizes a json in the format of { "textures": { "foo": "texture",... }}
* Ignores all invalid json
*/
public static class ModelTextureDeserializer implements JsonDeserializer<Map<String, String>> {
public static final ModelTextureDeserializer INSTANCE = new ModelTextureDeserializer();
private static final Gson GSON = new Gson();
@Override
public Map<String, String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
JsonElement texElem = obj.get("textures");
if(texElem == null) {
throw new JsonParseException("Missing textures entry in json");
}
return GSON.fromJson(texElem, maptype);
}
}
}
@@ -0,0 +1,78 @@
package slimeknights.mantle.client.gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Represents a GUI element INSIDE the graphics file.
* The coordinates all refer to the coordinates inside the graphics!
*/
@SideOnly(Side.CLIENT)
public class GuiElement {
// this is totally completely ugly but it's a simple solution that doesn't clutter everything too much >_>
public static int defaultTexW = 256;
public static int defaultTexH = 256;
public final int x;
public final int y;
public final int w;
public final int h;
public int texW;
public int texH;
public GuiElement(int x, int y, int w, int h, int texW, int texH) {
this(x, y, w, h);
setTextureSize(texW, texH);
defaultTexW = texW;
defaultTexH = texH;
}
public GuiElement(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
setTextureSize(defaultTexW, defaultTexH);
}
public GuiElement setTextureSize(int w, int h) {
texW = w;
texH = h;
return this;
}
public GuiElement shift(int xd, int yd) {
return new GuiElement(this.x + xd, this.y + yd, this.w, this.h, this.texW, this.texH);
}
/**
* Draws the element at the given x/y coordinates
*
* @param xPos X-Coordinate on the screen
* @param yPos Y-Coordinate on the screen
*/
public int draw(int xPos, int yPos) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos, yPos, x, y, w, h, texW, texH);
return w;
}
public static class Builder {
public int w;
public int h;
public Builder(int w, int h) {
this.w = w;
this.h = h;
}
public GuiElement get(int x, int y, int w, int h) {
return new GuiElement(x, y, w, h, this.w, this.h);
}
}
}
@@ -0,0 +1,69 @@
package slimeknights.mantle.client.gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiElementScalable extends GuiElement {
public GuiElementScalable(int x, int y, int w, int h) {
super(x, y, w, h);
}
public int drawScaledX(int xPos, int yPos, int width) {
for(int i = 0; i < width / w; i++) {
draw(xPos + i * w, yPos);
}
// remainder that doesn't fit total width
int remainder = width % w;
if(remainder > 0) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos + width - remainder, yPos, x, y, remainder, h, texW, texH);
}
return width;
}
public int drawScaledY(int xPos, int yPos, int height) {
for(int i = 0; i < height / h; i++) {
draw(xPos, yPos + i * h);
}
// remainder that doesn't fit total width
int remainder = height % h;
if(remainder > 0) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos, yPos + height - remainder, x, y, w, remainder, texW, texH);
}
return w;
}
public int drawScaled(int xPos, int yPos, int width, int height) {
// we draw full height row-wise
int full = height / this.h;
for(int i = 0; i < full; i++) {
drawScaledX(xPos, yPos + i * this.h, width);
}
yPos += full * this.h;
// and the remainder is drawn manually
int yRest = height % this.h;
// the same as drawScaledX but with the remaining height
for(int i = 0; i < width / w; i++) {
drawScaledY(xPos + i * w, yPos, yRest);
}
// remainder that doesn't fit total width
int remainder = width % w;
if(remainder > 0) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos + width - remainder, yPos, x, y, remainder, yRest, texW, texH);
}
return width;
}
public GuiElementScalable shift(int xd, int yd) {
GuiElementScalable element = new GuiElementScalable(this.x + xd, this.y + yd, this.w, this.h);
element.setTextureSize(this.texW, texH);
return element;
}
}
@@ -0,0 +1,118 @@
package slimeknights.mantle.client.gui;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.io.IOException;
// a sub-gui. Mostly the same as a separate GuiContainer, but doesn't do the calls that affect the game as if this were the only gui
@SideOnly(Side.CLIENT)
public abstract class GuiModule extends GuiContainer {
protected final GuiMultiModule parent;
// left or right of the parent
protected final boolean right;
// top or bottom of the parent
protected final boolean bottom;
public int yOffset = 0;
public int xOffset = 0;
public GuiModule(GuiMultiModule parent, Container container, boolean right, boolean bottom) {
super(container);
this.parent = parent;
this.right = right;
this.bottom = bottom;
}
public int guiRight() {
return guiLeft + xSize;
}
public int guiBottom() {
return guiTop + ySize;
}
@Override
public void initGui() {
this.guiLeft = (this.width - this.xSize) / 2;
this.guiTop = (this.height - this.ySize) / 2;
}
public void updatePosition(int parentX, int parentY, int parentSizeX, int parentSizeY) {
if(right) {
this.guiLeft = parentX + parentSizeX;
}
else {
this.guiLeft = parentX - this.xSize;
}
if(bottom) {
this.guiTop = parentY + parentSizeY - this.ySize;
}
else {
this.guiTop = parentY;
}
this.guiLeft += xOffset;
this.guiTop += yOffset;
}
public boolean shouldDrawSlot(Slot slot) {
return true;
}
/*
public void updateDragged(boolean dragSplitting, Set draggedSlots) {
this.dragSplitting = dragSplitting;
this.dragSplittingSlots.clear();
for(Object o : draggedSlots) {
if(o instanceof SlotWrapper)
this.dragSplittingSlots.add(((SlotWrapper) o).parent);
else
this.dragSplittingSlots.add(o);
}
}
*/
public void handleDrawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
this.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
public void handleDrawGuiContainerForegroundLayer(int mouseX, int mouseY) {
this.drawGuiContainerForegroundLayer(mouseX, mouseY);
}
/**
* Custom mouse click handling.
*
* @return True to prevent the main container handling the mouseclick
*/
public boolean handleMouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
return false;
}
/**
* Custom mouse click handling.
*
* @return True to prevent the main container handling the mouseclick
*/
public boolean handleMouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
return false;
}
/**
* Custom mouse click handling.
*
* @return True to prevent the main container handling the mouseclick
*/
public boolean handleMouseReleased(int mouseX, int mouseY, int state) {
return false;
}
}
@@ -0,0 +1,356 @@
package slimeknights.mantle.client.gui;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import codechicken.nei.LayoutManager;
import codechicken.nei.VisiblityData;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.TaggedInventoryArea;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.inventory.ContainerMultiModule;
import slimeknights.mantle.inventory.SlotWrapper;
@SideOnly(Side.CLIENT)
@Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems")
public class GuiMultiModule extends GuiContainer implements INEIGuiHandler {
// NEI-stuff >:(
private static Field NEI_Manager;
static {
try {
NEI_Manager = GuiContainer.class.getDeclaredField("manager");
} catch(NoSuchFieldException e) {
NEI_Manager = null;
}
}
protected List<GuiModule> modules = Lists.newArrayList();
public int cornerX;
public int cornerY;
public int realWidth;
public int realHeight;
public GuiMultiModule(ContainerMultiModule container) {
super(container);
realWidth = -1;
realHeight = -1;
}
protected void addModule(GuiModule module) {
modules.add(module);
}
@Override
public void initGui() {
if(realWidth > -1) {
// has to be reset before calling initGui so the position is getting retained
xSize = realWidth;
ySize = realHeight;
}
super.initGui();
this.cornerX = this.guiLeft;
this.cornerY = this.guiTop;
this.realWidth = xSize;
this.realHeight = ySize;
for(GuiModule module : modules) {
updateSubmodule(module);
}
//this.guiLeft = this.guiTop = 0;
//this.xSize = width;
//this.ySize = height;
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
for(GuiModule module : modules) {
module.handleDrawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
for(GuiModule module : modules) {
// set correct state for the module
GlStateManager.pushMatrix();
GlStateManager.translate(-this.guiLeft, -this.guiTop, 0.0F);
GlStateManager.translate(module.guiLeft, module.guiTop, 0.0F);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
module.handleDrawGuiContainerForegroundLayer(mouseX, mouseY);
GlStateManager.popMatrix();
}
drawContainerName();
drawPlayerInventoryName();
}
protected void drawContainerName() {
ContainerMultiModule multiContainer = (ContainerMultiModule) this.inventorySlots;
IChatComponent localizedName = multiContainer.getInventoryDisplayName();
if(localizedName != null) {
this.fontRendererObj.drawString(localizedName.getUnformattedText(), 8, 6, 0x404040);
}
}
protected void drawPlayerInventoryName() {
String localizedName = Minecraft.getMinecraft().thePlayer.inventory.getDisplayName().getUnformattedText();
this.fontRendererObj.drawString(localizedName, 8, this.ySize - 96 + 2, 0x404040);
}
@Override
public void setWorldAndResolution(Minecraft mc, int width, int height) {
super.setWorldAndResolution(mc, width, height);
// workaround for NEIs ASM hax. sigh.
try {
for(GuiModule module : modules) {
module.setWorldAndResolution(mc, width, height);
if(NEI_Manager != null) {
NEI_Manager.set(module, NEI_Manager.get(this));
}
updateSubmodule(module);
}
} catch(IllegalAccessException e) {
Mantle.logger.error(e);
}
}
@Override
public void onResize(Minecraft mc, int width, int height) {
super.onResize(mc, width, height);
for(GuiModule module : modules) {
module.onResize(mc, width, height);
updateSubmodule(module);
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
int oldX = guiLeft;
int oldY = guiTop;
int oldW = xSize;
int oldH = ySize;
guiLeft = cornerX;
guiTop = cornerY;
xSize = realWidth;
ySize = realHeight;
super.drawScreen(mouseX, mouseY, partialTicks);
guiLeft = oldX;
guiTop = oldY;
xSize = oldW;
ySize = oldH;
}
// needed to get the correct slot on clicking
@Override
protected boolean isPointInRegion(int left, int top, int right, int bottom, int pointX, int pointY) {
pointX -= this.cornerX;
pointY -= this.cornerY;
return pointX >= left - 1 && pointX < left + right + 1 && pointY >= top - 1 && pointY < top + bottom + 1;
}
protected void updateSubmodule(GuiModule module) {
module.updatePosition(this.cornerX, this.cornerY, this.realWidth, this.realHeight);
if(module.guiLeft < this.guiLeft) {
this.xSize += this.guiLeft - module.guiLeft;
this.guiLeft = module.guiLeft;
}
if(module.guiTop < this.guiTop) {
this.ySize += this.guiTop - module.guiTop;
this.guiTop = module.guiTop;
}
if(module.guiRight() > this.guiLeft + this.xSize) {
xSize = module.guiRight() - this.guiLeft;
}
if(module.guiBottom() > this.guiTop + this.ySize) {
ySize = module.guiBottom() - this.guiTop;
}
}
@Override
public void drawSlot(Slot slotIn) {
GuiModule module = getModuleForSlot(slotIn.slotNumber);
if(module != null) {
Slot slot = slotIn;
// unwrap for the call to the module
if(slotIn instanceof SlotWrapper) {
slot = ((SlotWrapper) slotIn).parent;
}
if(!module.shouldDrawSlot(slot)) {
return;
}
}
// update slot positions
if(slotIn instanceof SlotWrapper) {
slotIn.xDisplayPosition = ((SlotWrapper) slotIn).parent.xDisplayPosition;
slotIn.yDisplayPosition = ((SlotWrapper) slotIn).parent.yDisplayPosition;
}
super.drawSlot(slotIn);
}
@Override
public boolean isMouseOverSlot(Slot slotIn, int mouseX, int mouseY) {
GuiModule module = getModuleForSlot(slotIn.slotNumber);
// mouse inside the module of the slot?
if(module != null) {
Slot slot = slotIn;
// unwrap for the call to the module
if(slotIn instanceof SlotWrapper) {
slot = ((SlotWrapper) slotIn).parent;
}
if(!module.shouldDrawSlot(slot)) {
return false;
}
}
return super.isMouseOverSlot(slotIn, mouseX, mouseY);
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
GuiModule module = getModuleForPoint(mouseX, mouseY);
if(module != null) {
if(module.handleMouseClicked(mouseX, mouseY, mouseButton)) {
return;
}
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
GuiModule module = getModuleForPoint(mouseX, mouseY);
if(module != null) {
if(module.handleMouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick)) {
return;
}
}
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick);
}
@Override
protected void mouseReleased(int mouseX, int mouseY, int state) {
GuiModule module = getModuleForPoint(mouseX, mouseY);
if(module != null) {
if(module.handleMouseReleased(mouseX, mouseY, state)) {
return;
}
}
super.mouseReleased(mouseX, mouseY, state);
}
protected GuiModule getModuleForPoint(int x, int y) {
for(GuiModule module : modules) {
if(this.isPointInRegion(module.guiLeft, module.guiTop, module.guiRight(), module.guiBottom(),
x + this.cornerX, y + this.cornerY)) {
return module;
}
}
return null;
}
protected GuiModule getModuleForSlot(int slotNumber) {
return getModuleForContainer(getContainer().getSlotContainer(slotNumber));
}
protected GuiModule getModuleForContainer(Container container) {
for(GuiModule module : modules) {
if(module.inventorySlots == container) {
return module;
}
}
return null;
}
protected ContainerMultiModule getContainer() {
return (ContainerMultiModule) inventorySlots;
}
/* NEI INTEGRATION */
@Override
@Optional.Method(modid = "NotEnoughItems")
public VisiblityData modifyVisiblity(GuiContainer guiContainer, VisiblityData visiblityData) {
int x = LayoutManager.stateButtons[0].x + LayoutManager.stateButtons[0].w;
int x2 = LayoutManager.timeButtons[3].x + LayoutManager.timeButtons[3].w;
int y2 = LayoutManager.heal.y + LayoutManager.heal.h;
for(GuiModule module : modules) {
if(x > module.guiLeft) {
visiblityData.showStateButtons = false;
}
if(x2 > module.guiLeft && y2 > module.guiTop) {
visiblityData.showUtilityButtons = false;
}
}
return visiblityData;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public Iterable<Integer> getItemSpawnSlots(GuiContainer guiContainer, ItemStack itemStack) {
return null;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public List<TaggedInventoryArea> getInventoryAreas(GuiContainer guiContainer) {
return Collections.EMPTY_LIST;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public boolean handleDragNDrop(GuiContainer guiContainer, int x, int y, ItemStack itemStack, int k) {
return false;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public boolean hideItemPanelSlot(GuiContainer guiContainer, int x, int y, int w, int h) {
for(GuiModule module : modules) {
// check if the panel overlaps the module (check totally not stolen from stackoverflow)
if(module.guiLeft < x + w && module.guiRight() > x &&
module.guiTop < y + h && module.guiBottom() > y) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,26 @@
package slimeknights.mantle.client.gui;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public abstract class GuiWidget {
public int xPos;
public int yPos;
public int height;
public int width;
public abstract void draw();
/** Where the part will be drawn. Upper left corner. */
public void setPosition(int x, int y) {
this.xPos = x;
this.yPos = y;
}
public void setSize(int width, int height) {
this.width = width;
this.height = height;
}
}
@@ -0,0 +1,232 @@
package slimeknights.mantle.client.gui;
import net.minecraft.util.MathHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Mouse;
// a vertical slider!
@SideOnly(Side.CLIENT)
public class GuiWidgetSlider extends GuiWidget {
// gui info
public final GuiElement slider;
public final GuiElement sliderHighlighted;
public final GuiElement sliderDisabled;
public final GuiElement slideBarTop;
public final GuiElement slideBarBottom;
public final GuiElementScalable slideBar;
// slider info
protected int minValue;
protected int maxValue;
protected int increment;
// positioning info
protected int currentValue;
public int sliderOffset; // x-offset of the slider to the left edge of the slideBar
protected boolean enabled;
protected boolean hidden;
protected boolean isScrolling;
protected boolean isHighlighted;
// where the slider was clicked on the slider itself (not on the bar, on the thing that slides)
private int clickX;
private int clickY;
private boolean clickedBar; // if the bar has already been clicked and not released
public GuiWidgetSlider(GuiElement slider, GuiElement sliderHighlighted, GuiElement sliderDisabled, GuiElement slideBarTop, GuiElement slideBarBottom, GuiElementScalable slideBar) {
this.slider = slider;
this.sliderHighlighted = sliderHighlighted;
this.sliderDisabled = sliderDisabled;
this.slideBar = slideBar;
this.slideBarTop = slideBarTop;
this.slideBarBottom = slideBarBottom;
height = slideBar.h;
width = slideBar.w;
currentValue = minValue = 0;
maxValue = slideBar.h;
increment = 1;
sliderOffset = MathHelper.abs_int(slideBar.w - slider.w) / 2;
isScrolling = false;
isHighlighted = false;
enabled = true;
hidden = false;
}
/** Sets the height of the whole slider and slidebar */
public void setSize(int height) {
this.height = height;
}
/** specifies the values that the slider represents */
public void setSliderParameters(int min, int max, int stepsize) {
this.minValue = min;
this.maxValue = max;
this.increment = stepsize;
// just in case
setSliderValue(currentValue);
}
public int getValue() {
return currentValue;
}
public void enable() {
this.enabled = true;
}
public void disable() {
this.enabled = false;
}
public boolean isEnabled() {
return this.enabled;
}
public void hide() {
this.hidden = true;
}
public void show() {
this.hidden = false;
}
public boolean isHidden() {
return this.hidden;
}
public void draw() {
if(hidden) {
return;
}
// slidebar background
slideBarTop.draw(xPos, yPos);
slideBar.drawScaledY(xPos, yPos + slideBarTop.h, getUsableSlidebarHeight());
slideBarBottom.draw(xPos, yPos + height - slideBarBottom.h);
int x = xPos + sliderOffset;
int y = yPos + getSliderTop();
// the slider depending on state
if(enabled) {
if(isScrolling) {
sliderDisabled.draw(x, y);
}
else if(isHighlighted) {
sliderHighlighted.draw(x, y);
}
else {
slider.draw(x, y);
}
}
}
public void update(int mouseX, int mouseY) {
if(!enabled || hidden) {
return;
}
boolean mouseDown = Mouse.isButtonDown(0); // left mouse button
// relative position inside the widget
int x = mouseX - xPos;
int y = mouseY - yPos;
// reset click data
if(!mouseDown && clickedBar) {
clickedBar = false;
}
// button not pressed and scrolling -> stop scrolling
if(!mouseDown && isScrolling) {
isScrolling = false;
}
// button pressed and scrolling -> update position of slider
else if(isScrolling) {
float d = maxValue - minValue;
float val = (float) (y - clickY) / (float) (getUsableSlidebarHeight() - slider.h);
val *= d;
if(val < (float) increment / 2f) {
// < 1/2 increment
setSliderValue(minValue);
}
else if(val > maxValue - ((float) increment / 2f)) {
// > max-1/2 increment
setSliderValue(maxValue);
}
else {
// in between
setSliderValue((int) (minValue + (float) increment * Math.round(val)));
}
}
// not scrolling yet but possibly inside the slider
else if(x >= 0 && y >= getSliderTop() &&
x - sliderOffset <= slider.w && y <= getSliderTop() + slider.h) {
isHighlighted = true;
if(mouseDown) {
isScrolling = true;
clickX = x - sliderOffset;
clickY = y - getSliderTop();
}
}
// not on the slider but clicked on the bar
else if(mouseDown && !clickedBar &&
x >= 0 && y >= 0 &&
x <= slideBar.w && y <= height) {
if(y < getSliderTop()) {
decrement();
}
else {
increment();
}
clickedBar = true;
}
else {
isHighlighted = false;
}
}
public int increment() {
setSliderValue(currentValue + increment);
return currentValue;
}
public int decrement() {
setSliderValue(currentValue - increment);
return currentValue;
}
public int setSliderValue(int val) {
if(val > maxValue) {
val = maxValue;
}
else if(val < minValue) {
val = minValue;
}
currentValue = val;
return currentValue;
}
private int getSliderTop() {
float d = maxValue - minValue;
d = (float) (currentValue - minValue) / d;
d *= getUsableSlidebarHeight() - slider.h;
return (int) d + slideBarTop.h;
}
private int getUsableSlidebarHeight() {
return height - slideBarTop.h - slideBarBottom.h;
}
}
@@ -0,0 +1,171 @@
package slimeknights.mantle.client.gui;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Mouse;
import java.util.List;
@SideOnly(Side.CLIENT)
public class GuiWidgetTabs extends GuiWidget {
private static final ResourceLocation
creativeInventoryTabs = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png");
private final GuiElement[] tabActive = new GuiElement[3];
private final GuiElement[] tab = new GuiElement[3];
// change this if you need different tabs
public ResourceLocation tabsResource = creativeInventoryTabs;
// changes the y-offset of the tab row
public int yOffset = 4;
// space between 2 tabs
public int spacing = 2;
public int selected;
public int highlighted;
protected List<ItemStack> icons = Lists.newArrayList();
private final GuiMultiModule parent;
private boolean clicked = false;
public GuiWidgetTabs(GuiMultiModule parent, GuiElement tabLeft, GuiElement tabCenter, GuiElement tabRight, GuiElement activeLeft, GuiElement activeCenter, GuiElement activeRight) {
this.parent = parent;
this.tab[0] = tabLeft;
this.tab[1] = tabCenter;
this.tab[2] = tabRight;
this.tabActive[0] = activeLeft;
this.tabActive[1] = activeCenter;
this.tabActive[2] = activeRight;
selected = 0;
}
public void addTab(ItemStack icon) {
icons.add(icon);
}
public void clear() {
selected = 0;
icons.clear();
}
public void update(int mouseX, int mouseY) {
boolean mouseDown = Mouse.isButtonDown(0); // left mouse button
// did we click on a tab?
mouseX -= this.xPos;
mouseY -= this.yPos;
// update highlighted
highlighted = -1;
if(mouseY >= 0 && mouseY <= tab[1].h) {
// which one did we click?
int x = 0;
for(int i = 0; i < icons.size(); i++) {
// clicking on spacing has no effect
if(mouseX >= x && mouseX < x + tab[1].w) {
highlighted = i;
break;
}
x += tab[1].w;
x += spacing;
}
}
// already clicked
if(clicked) {
// still clicking
if(mouseDown) {
return;
}
// release click
else {
clicked = false;
return;
}
}
// new click
else if(mouseDown) {
clicked = true;
}
// no click - do nothing
else {
return;
}
// was new click, select highlighted
if(highlighted > -1) {
selected = highlighted;
}
}
@Override
public void draw() {
int y = yPos + yOffset;
for(int i = 0; i < icons.size(); i++) {
int x = xPos + i * tab[0].w;
if(i > 0) {
x += i * spacing;
}
GuiElement[] toDraw;
if(i == selected) {
toDraw = tabActive;
}
else {
toDraw = tab;
}
GuiElement actualTab;
if(i == 0 && x == parent.cornerX) {
actualTab = toDraw[0];
}
else if(x == parent.cornerX + parent.width) {
actualTab = toDraw[2];
}
else {
actualTab = toDraw[1];
}
// todo: draw all the tabs first and then all the itemstacks so it doesn't have to switch texture in between all the time
// rebind texture from drawing an itemstack
Minecraft.getMinecraft().getTextureManager().bindTexture(tabsResource);
actualTab.draw(x, y);
ItemStack icon = icons.get(i);
if(icon != null) {
RenderHelper.enableGUIStandardItemLighting();
drawItemStack(icon, x + (actualTab.w - 16) / 2, y + (actualTab.h - 16) / 2);
RenderHelper.disableStandardItemLighting();
//RenderHelper.enableStandardItemLighting();
}
}
}
// guiContainer.drawItemStack
private void drawItemStack(ItemStack stack, int x, int y) {
RenderItem itemRender = Minecraft.getMinecraft().getRenderItem();
GlStateManager.translate(0.0F, 0.0F, 32.0F);
itemRender.zLevel = 200;
//FontRenderer font = stack.getItem().getFontRenderer(stack);
itemRender.renderItemAndEffectIntoGUI(stack, x, y);
//this.itemRender.renderItemOverlayIntoGUI(font, stack, x, y - (this.draggedStack == null ? 0 : 8), altText);
//this.zLevel = 0.0F;
itemRender.zLevel = 0.0F;
}
}
@@ -0,0 +1,87 @@
package slimeknights.mantle.client.model;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.IFlexibleBakedModel;
import net.minecraftforge.client.model.IPerspectiveAwareModel;
import net.minecraftforge.client.model.TRSRTransformation;
import org.apache.commons.lang3.tuple.Pair;
import java.util.List;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
/**
* Takes a blockmodel and applies the standard-block-perspective for third_person to it
*/
public class BlockItemModelWrapper implements IPerspectiveAwareModel, IFlexibleBakedModel {
// copied from the forge variants V1 default-block transform
public static final Matrix4f THIRD_PERSON_BLOCK_TRANSFORM = new TRSRTransformation(
new Vector3f(0, 1.5f / 16, -2.75f / 16), // translation
TRSRTransformation.quatFromYXZDegrees(new Vector3f(10, -45, 170)), // rotation
new Vector3f(0.375f, 0.375f, 0.375f), // scale
null).getMatrix();
private final IFlexibleBakedModel parent;
public BlockItemModelWrapper(IFlexibleBakedModel parent) {
this.parent = parent;
}
@Override
public Pair<IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) {
Matrix4f matrix = null;
// fix transformation in hand
if(cameraTransformType == ItemCameraTransforms.TransformType.THIRD_PERSON) {
matrix = THIRD_PERSON_BLOCK_TRANSFORM;
}
return Pair.of((IBakedModel) this, matrix);
}
@Override
public List getFaceQuads(EnumFacing p_177551_1_) {
return parent.getFaceQuads(p_177551_1_);
}
@Override
public List getGeneralQuads() {
return parent.getGeneralQuads();
}
@Override
public VertexFormat getFormat() {
return parent.getFormat();
}
@Override
public boolean isAmbientOcclusion() {
return false;
}
@Override
public boolean isGui3d() {
return parent.isGui3d();
}
@Override
public boolean isBuiltInRenderer() {
return parent.isBuiltInRenderer();
}
@Override
public TextureAtlasSprite getTexture() {
return parent.getTexture();
}
@Override
public ItemCameraTransforms getItemCameraTransforms() {
return parent.getItemCameraTransforms();
}
}
@@ -0,0 +1,139 @@
package slimeknights.mantle.client.model;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.IFlexibleBakedModel;
import net.minecraftforge.client.model.TRSRTransformation;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
// for those wondering TRSR stands for Translation Rotation Scale Rotation
public class TRSRBakedModel implements IFlexibleBakedModel {
protected final ImmutableList<BakedQuad> general;
protected final ImmutableMap<EnumFacing, ImmutableList<BakedQuad>> faces;
protected final IFlexibleBakedModel original;
public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float scale) {
this(original, x, y, z, 0, 0, 0, scale, scale, scale);
}
public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scale) {
this(original, x, y, z, rotX, rotY, rotZ, scale, scale, scale);
}
public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scaleX, float scaleY, float scaleZ) {
this(original, new TRSRTransformation(new Vector3f(x, y, z),
null,
new Vector3f(scaleX, scaleY, scaleZ),
TRSRTransformation.quatFromYXZ(rotY, rotX, rotZ)));
}
public TRSRBakedModel(IFlexibleBakedModel original, TRSRTransformation transform) {
this.original = original;
ImmutableList.Builder<BakedQuad> builder;
builder = ImmutableList.builder();
transform = TRSRTransformation.blockCenterToCorner(transform);
// face quads
EnumMap<EnumFacing, ImmutableList<BakedQuad>> faces = Maps.newEnumMap(EnumFacing.class);
for(EnumFacing face : EnumFacing.values()) {
for(BakedQuad quad : original.getFaceQuads(face)) {
builder.add(transform(transform, quad, original.getFormat()));
}
//faces.put(face, builder.build());
faces.put(face, ImmutableList.<BakedQuad>of());
}
// general quads
//builder = ImmutableList.builder();
for(BakedQuad quad : original.getGeneralQuads()) {
builder.add(transform(transform, quad, original.getFormat()));
}
this.general = builder.build();
this.faces = Maps.immutableEnumMap(faces);
}
public static BakedQuad transform(TRSRTransformation transform, BakedQuad quad, VertexFormat format) {
for(VertexFormatElement e : (List<VertexFormatElement>) format.getElements()) {
if(e.getUsage() == VertexFormatElement.EnumUsage.POSITION) {
if(e.getType() != VertexFormatElement.EnumType.FLOAT) {
throw new IllegalArgumentException("can only transform float position");
}
int[] data = Arrays.copyOf(quad.getVertexData(), quad.getVertexData().length);
// once for each vertex
for(int j = 0; j < 4; j++) {
int v = j * format.getNextOffset() / 4;
float[] pos = new float[]{0f, 0f, 0f, 1f};
for(int i = 0; i < Math.min(4, e.getElementCount()); i++) {
pos[i] = Float.intBitsToFloat(data[v + e.getOffset() / 4 + i]);
}
Vector4f vec = new Vector4f(pos);
transform.getMatrix().transform(vec);
vec.get(pos);
for(int i = 0; i < Math.min(4, e.getElementCount()); i++) {
data[v + e.getOffset() / 4 + i] = Float.floatToRawIntBits(pos[i]);
}
}
return new BakedQuad(data, quad.getTintIndex(), quad.getFace());
}
}
return quad;
}
@Override
public List<BakedQuad> getFaceQuads(EnumFacing side) {
return faces.get(side);
}
@Override
public List<BakedQuad> getGeneralQuads() {
return general;
}
@Override
public boolean isAmbientOcclusion() {
return false;
}
@Override
public boolean isGui3d() {
return original.isGui3d();
}
@Override
public boolean isBuiltInRenderer() {
return original.isBuiltInRenderer();
}
@Override
public TextureAtlasSprite getTexture() {
return original.getTexture();
}
@Override
public ItemCameraTransforms getItemCameraTransforms() {
return original.getItemCameraTransforms();
}
@Override
public VertexFormat getFormat() {
return original.getFormat();
}
}
@@ -0,0 +1,4 @@
package slimeknights.mantle.common;
public class CommonProxy {
}
@@ -0,0 +1,31 @@
package slimeknights.mantle.common;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
/**
* A GuiHandler implementation that forwards the container/gui creation to the TEs, eliminating the need for GUI IDs.
*/
public class GuiHandler implements IGuiHandler {
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
if(te instanceof IInventoryGui) {
return ((IInventoryGui) te).createContainer(player.inventory, world, new BlockPos(x, y, z));
}
return null;
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
if(te instanceof IInventoryGui) {
return ((IInventoryGui) te).createGui(player.inventory, world, new BlockPos(x, y, z));
}
return null;
}
}
@@ -0,0 +1,20 @@
package slimeknights.mantle.common;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Used in conjunction with GuiHandler. Implement in a TE to have it open its GUI/Container.
*/
public interface IInventoryGui {
Container createContainer(InventoryPlayer inventoryplayer, World world, BlockPos pos);
@SideOnly(Side.CLIENT)
GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos);
}
@@ -0,0 +1,297 @@
package slimeknights.mantle.inventory;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import java.util.List;
import slimeknights.mantle.util.SlimeknightException;
/** Same as Container but provides some extra functionality to simplify things */
public abstract class BaseContainer<T extends TileEntity> extends Container {
protected double maxDist = 8 * 8; // 8 blocks
protected T tile;
protected final Block originalBlock; // used to check if the block we interacted with got broken
protected final BlockPos pos;
protected final World world;
public List<Container> subContainers = Lists.newArrayList();
public BaseContainer(T tile) {
this.tile = tile;
this.world = tile.getWorld();
this.pos = tile.getPos();
this.originalBlock = world.getBlockState(pos).getBlock();
}
public void syncOnOpen(EntityPlayerMP playerOpened) {
// find another player that already has the gui for this tile open
WorldServer server = playerOpened.getServerForPlayer();
for(EntityPlayer player : (List<EntityPlayer>) server.playerEntities) {
if(player == playerOpened) {
continue;
}
if(player.openContainer instanceof BaseContainer) {
if(this.sameGui((BaseContainer<T>) player.openContainer)) {
syncWithOtherContainer((BaseContainer<T>) player.openContainer, playerOpened);
return;
}
}
}
// no player has a container open for the tile
syncNewContainer(playerOpened);
}
/**
* Called when the container is opened and another player already has a container for this tile open
* Sync to the same state here.
*/
protected void syncWithOtherContainer(BaseContainer<T> otherContainer, EntityPlayerMP player) {
}
/**
* Called when the container is opened and no other player has it open.
* Set the default state here.
*/
protected void syncNewContainer(EntityPlayerMP player) {
}
public boolean sameGui(BaseContainer otherContainer) {
return this.tile == otherContainer.tile;
}
@Override
public boolean canInteractWith(EntityPlayer playerIn) {
Block block = world.getBlockState(pos).getBlock();
// does the block we interacted with still exist?
if(block == Blocks.air || block != originalBlock) {
return false;
}
// too far away from block?
return playerIn.getDistanceSq((double) pos.getX() + 0.5d,
(double) pos.getY() + 0.5d,
(double) pos.getZ() + 0.5d) <= maxDist;
}
@SuppressWarnings("unchecked")
public List<ItemStack> getInventory() {
return (List<ItemStack>) super.getInventory();
}
public IChatComponent getInventoryDisplayName() {
if(tile instanceof IInventory) {
return ((IInventory) tile).getDisplayName();
}
return null;
}
// standard yOffset calculation for chestlike inventories:
// yOffset = (numRows - 4) * 18; (the -4 because of the 3 rows of inventory + 1 row of hotbar)
protected int playerInventoryStart = -1;
/**
* Draws the player inventory starting at the given position
*
* @param playerInventory The players inventory
* @param xCorner Default Value: 8
* @param yCorner Default Value: (rows - 4) * 18 + 103
*/
protected void addPlayerInventory(InventoryPlayer playerInventory, int xCorner, int yCorner) {
int index = 9;
int start = this.inventorySlots.size();
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 9; col++) {
this.addSlotToContainer(new Slot(playerInventory, index, xCorner + col * 18, yCorner + row * 18));
index++;
}
}
index = 0;
for(int col = 0; col < 9; col++) {
this.addSlotToContainer(new Slot(playerInventory, index, xCorner + col * 18, yCorner + 58));
index++;
}
playerInventoryStart = start;
}
@Override
protected Slot addSlotToContainer(Slot slotIn) {
if(playerInventoryStart >= 0) {
throw new SlimeknightException("BaseContainer: Player inventory has to be last slots. Add all slots before adding the player inventory.");
}
return super.addSlotToContainer(slotIn);
}
@Override
public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) {
// we can only support inventory <-> playerInventory
if(playerInventoryStart < 0) {
// so we don't do anything if no player inventory is present because we don't know what to do
return null;
}
ItemStack itemstack = null;
Slot slot = (Slot) this.inventorySlots.get(index);
// slot that was clicked on not empty?
if(slot != null && slot.getHasStack()) {
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
int end = this.inventorySlots.size();
// Is it a slot in the main inventory? (aka not player inventory)
if(index < playerInventoryStart) {
// try to put it into the player inventory (if we have a player inventory)
if(!this.mergeItemStack(itemstack1, playerInventoryStart, end, true)) {
return null;
}
}
// Slot is in the player inventory (if it exists), transfer to main inventory
else if(!this.mergeItemStack(itemstack1, 0, playerInventoryStart, false)) {
return null;
}
if(itemstack1.stackSize == 0) {
slot.putStack(null);
}
else {
slot.onSlotChanged();
}
}
return itemstack;
}
// Fix for a vanilla bug: doesn't take Slot.getMaxStackSize into account
protected boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) {
return mergeItemStackRefill(stack, startIndex, endIndex, useEndIndex)
|| mergeItemStackMove(stack, startIndex, endIndex, useEndIndex);
}
// only refills items that are already present
protected boolean mergeItemStackRefill(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) {
if(stack.stackSize <= 0) {
return false;
}
boolean flag1 = false;
int k = startIndex;
if(useEndIndex) {
k = endIndex - 1;
}
Slot slot;
ItemStack itemstack1;
if(stack.isStackable()) {
while(stack.stackSize > 0 && (!useEndIndex && k < endIndex || useEndIndex && k >= startIndex)) {
slot = (Slot) this.inventorySlots.get(k);
itemstack1 = slot.getStack();
if(itemstack1 != null && itemstack1.getItem() == stack.getItem() && (!stack.getHasSubtypes()
|| stack.getMetadata() == itemstack1
.getMetadata()) && ItemStack.areItemStackTagsEqual(stack, itemstack1)) {
int l = itemstack1.stackSize + stack.stackSize;
int limit = Math.min(stack.getMaxStackSize(), slot.getItemStackLimit(stack));
if(l <= limit) {
stack.stackSize = 0;
itemstack1.stackSize = l;
slot.onSlotChanged();
flag1 = true;
}
else if(itemstack1.stackSize < limit) {
stack.stackSize -= limit - itemstack1.stackSize;
itemstack1.stackSize = limit;
slot.onSlotChanged();
flag1 = true;
}
}
if(useEndIndex) {
--k;
}
else {
++k;
}
}
}
return flag1;
}
// only moves items into empty slots
protected boolean mergeItemStackMove(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) {
if(stack.stackSize <= 0) {
return false;
}
boolean flag1 = false;
int k;
if(useEndIndex) {
k = endIndex - 1;
}
else {
k = startIndex;
}
while(!useEndIndex && k < endIndex || useEndIndex && k >= startIndex) {
Slot slot = (Slot) this.inventorySlots.get(k);
ItemStack itemstack1 = slot.getStack();
if(itemstack1 == null && slot.isItemValid(stack)) // Forge: Make sure to respect isItemValid in the slot.
{
int limit = slot.getItemStackLimit(stack);
ItemStack stack2 = stack.copy();
if(stack2.stackSize > limit) {
stack2.stackSize = limit;
stack.stackSize -= limit;
}
else {
stack.stackSize = 0;
}
slot.putStack(stack2);
slot.onSlotChanged();
flag1 = true;
if(stack.stackSize == 0) {
break;
}
}
if(useEndIndex) {
--k;
}
else {
++k;
}
}
return flag1;
}
}
@@ -0,0 +1,284 @@
package slimeknights.mantle.inventory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.tuple.Pair;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ContainerMultiModule<T extends TileEntity> extends BaseContainer<T> {
public List<Container> subContainers = Lists.newArrayList();
// lookup used to redirect slot specific things to the appropriate container
protected Map<Integer, Container> slotContainerMap = Maps.newHashMap();
protected Map<Container, Pair<Integer, Integer>> subContainerSlotRanges = Maps.newHashMap();
protected int subContainerSlotStart = -1;
protected Set<Container> shiftClickContainers = Sets.newHashSet();
public ContainerMultiModule(T tile) {
super(tile);
}
/**
* @param subcontainer The container to add
* @param preferForShiftClick If true shift clicking on slots of the main-container will try to move to this module before the player inventory
*/
public void addSubContainer(Container subcontainer, boolean preferForShiftClick) {
if(subContainers.isEmpty()) {
subContainerSlotStart = inventorySlots.size();
}
subContainers.add(subcontainer);
if(preferForShiftClick) {
shiftClickContainers.add(subcontainer);
}
int begin = inventorySlots.size();
for(Object slot : subcontainer.inventorySlots) {
SlotWrapper wrapper = new SlotWrapper((Slot) slot);
addSlotToContainer(wrapper);
slotContainerMap.put(wrapper.slotNumber, subcontainer);
}
int end = inventorySlots.size();
subContainerSlotRanges.put(subcontainer, Pair.of(begin, end));
}
public <TC extends Container> TC getSubContainer(Class<TC> clazz) {
return getSubContainer(clazz, 0);
}
public <TC extends Container> TC getSubContainer(Class<TC> clazz, int index) {
for(Container sub : subContainers) {
if(clazz.isAssignableFrom(sub.getClass())) {
index--;
}
if(index < 0) {
return (TC) sub;
}
}
return null;
}
public Container getSlotContainer(int slotNumber) {
if(slotContainerMap.containsKey(slotNumber)) {
return slotContainerMap.get(slotNumber);
}
return this;
}
@Override
public boolean canInteractWith(EntityPlayer playerIn) {
// check if subcontainers are valid
for(Container sub : subContainers) {
if(!sub.canInteractWith(playerIn)) {
return false;
}
}
return super.canInteractWith(playerIn);
}
@Override
public void onContainerClosed(EntityPlayer playerIn) {
for(Container sub : subContainers) {
sub.onContainerClosed(playerIn);
}
super.onContainerClosed(playerIn);
}
@Override
public ItemStack slotClick(int slotId, int clickedButton, int mode, EntityPlayer playerIn) {
if(slotId == -999 && mode == 5) {
for(Container container : subContainers) {
container.slotClick(slotId, clickedButton, mode, playerIn);
}
}
/*
if(slotContainerMap.containsKey(slotId)) {
int actualId = slotId;
if(this.inventorySlots.get(slotId) instanceof SlotWrapper) {
actualId = ((SlotWrapper) this.inventorySlots.get(slotId)).parent.slotNumber;
}
return slotContainerMap.get(slotId).slotClick(actualId, clickedButton, mode, playerIn);
}*/
return super.slotClick(slotId, clickedButton, mode, playerIn);
}
// More sophisticated version of the one in BaseContainer
// Takes submodules into account when shiftclicking!
@Override
public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) {
Slot slot = (Slot) this.inventorySlots.get(index);
if(slot == null || !slot.getHasStack()) {
return null;
}
ItemStack ret = slot.getStack().copy();
ItemStack itemstack = slot.getStack().copy();
Container container = getSlotContainer(index);
// Is the slot from a module?
if(container != this) {
// Try moving module -> tile inventory
moveToTileInventory(itemstack);
// Try moving module -> player inventory
if(moveToPlayerInventory(itemstack)) {
return null;
}
}
// Is the slot from the tile?
else if(index < subContainerSlotStart || (index < playerInventoryStart && subContainerSlotStart < 0)) {
// Try moving tile -> preferred modules
refillAnyContainer(itemstack, subContainers);
// Try moving module -> player inventory
moveToPlayerInventory(itemstack);
// Try moving module -> all submodules
if(moveToAnyContainer(itemstack, subContainers)) {
return null;
}
}
// Slot is from the player inventory (if present)
else if(index >= playerInventoryStart && playerInventoryStart >= 0) {
// Try moving player -> tile inventory
moveToTileInventory(itemstack);
// try moving player -> modules
if(moveToAnyContainer(itemstack, subContainers)) {
return null;
}
}
// you violated some assumption or something. Shame on you.
else {
return null;
}
return notifySlotAfterTransfer(playerIn, itemstack, ret, slot);
}
protected ItemStack notifySlotAfterTransfer(EntityPlayer player, ItemStack stack, ItemStack original, Slot slot) {
// notify slot
slot.onSlotChange(stack, original);
if(stack.stackSize == original.stackSize) {
return null;
}
// update slot we pulled from
slot.putStack(stack);
slot.onPickupFromSlot(player, stack);
if(slot.getHasStack() && slot.getStack().stackSize == 0) {
slot.putStack(null);
}
return original;
}
protected boolean moveToTileInventory(ItemStack itemstack) {
if(itemstack == null || itemstack.stackSize == 0) {
return false;
}
int end = subContainerSlotStart;
if(end < 0) {
end = playerInventoryStart;
}
return !this.mergeItemStack(itemstack, 0, end, false);
}
protected boolean moveToPlayerInventory(ItemStack itemstack) {
if(itemstack == null || itemstack.stackSize == 0) {
return false;
}
return playerInventoryStart > 0 && !this
.mergeItemStack(itemstack, playerInventoryStart, this.inventorySlots.size(), true);
}
protected boolean moveToAnyContainer(ItemStack itemstack, Collection<Container> containers) {
if(itemstack == null || itemstack.stackSize == 0) {
return false;
}
for(Container submodule : containers) {
if(moveToContainer(itemstack, submodule)) {
return true;
}
}
return false;
}
protected boolean moveToContainer(ItemStack itemstack, Container container) {
Pair<Integer, Integer> range = subContainerSlotRanges.get(container);
if(!this.mergeItemStack(itemstack, range.getLeft(), range.getRight(), false)) {
return true;
}
return false;
}
protected boolean refillAnyContainer(ItemStack itemstack, Collection<Container> containers) {
if(itemstack == null || itemstack.stackSize == 0) {
return false;
}
for(Container submodule : containers) {
if(refillContainer(itemstack, submodule)) {
return true;
}
}
return false;
}
protected boolean refillContainer(ItemStack itemstack, Container container) {
Pair<Integer, Integer> range = subContainerSlotRanges.get(container);
if(!this.mergeItemStackRefill(itemstack, range.getLeft(), range.getRight(), false)) {
return true;
}
return false;
}
/** Searches for a sidechest to display in the UI */
public <TE extends TileEntity> TE detectTE(Class<TE> clazz) {
return ObjectUtils.firstNonNull(detectChest(this.pos.north(), clazz),
detectChest(this.pos.east(), clazz),
detectChest(this.pos.south(), clazz),
detectChest(this.pos.west(), clazz));
}
private <TE extends TileEntity> TE detectChest(BlockPos pos, Class<TE> clazz) {
TileEntity te = this.world.getTileEntity(pos);
if(te != null && clazz.isAssignableFrom(te.getClass())) {
return (TE) te;
}
return null;
}
}
@@ -0,0 +1,36 @@
package slimeknights.mantle.inventory;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import slimeknights.mantle.tileentity.TileInventory;
public class ContainerSimpleChest extends BaseContainer<TileInventory> {
public ContainerSimpleChest(TileInventory tile, int rows, int columns, InventoryPlayer playerInventory) {
super(tile);
int index = 0;
// chest inventory
for(int i = 0; i < rows; ++i) {
for(int j = 0; j < columns; ++j) {
// safety
if(index > tile.getSizeInventory()) {
break;
}
this.addSlotToContainer(createSlot(tile, index, 8 + j * 18, 18 + i * 18));
index++;
}
}
// player inventory
addPlayerInventory(playerInventory, 17, 86);
}
protected Slot createSlot(IInventory inventory, int index, int x, int y) {
return new Slot(inventory, index, x, y);
}
}
@@ -0,0 +1,10 @@
package slimeknights.mantle.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
public interface IContainerCraftingCustom {
void onCrafting(EntityPlayer player, ItemStack output, IInventory craftMatrix);
}
@@ -0,0 +1,34 @@
package slimeknights.mantle.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.ItemStack;
public class SlotCraftingCustom extends SlotCrafting {
private final InventoryCrafting craftMatrix;
private final IContainerCraftingCustom callback;
/**
* @param callback Container that gets the crafting call on crafting
* @param player Player that does the crafting
* @param craftingInventory Inventory where the ingredients are taken from
* @param craftResult Inventory where the result is put
*/
public SlotCraftingCustom(IContainerCraftingCustom callback, EntityPlayer player, InventoryCrafting craftingInventory, IInventory craftResult, int slotIndex, int xPosition, int yPosition) {
super(player, craftingInventory, craftResult, slotIndex, xPosition, yPosition);
this.craftMatrix = craftingInventory;
this.callback = callback;
}
@Override
public void onPickupFromSlot(EntityPlayer playerIn, ItemStack stack) {
net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerCraftingEvent(playerIn, stack, craftMatrix);
this.onCrafting(stack);
callback.onCrafting(playerIn, stack, craftMatrix);
}
}
@@ -0,0 +1,18 @@
package slimeknights.mantle.inventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
/** Slot that can only be taken out of */
public class SlotOut extends Slot {
public SlotOut(IInventory inventoryIn, int index, int xPosition, int yPosition) {
super(inventoryIn, index, xPosition, yPosition);
}
@Override
public boolean isItemValid(ItemStack stack) {
return false;
}
}
@@ -0,0 +1,21 @@
package slimeknights.mantle.inventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class SlotRestrictedItem extends Slot {
private final Item allowedItem;
public SlotRestrictedItem(Item item, IInventory inventoryIn, int index, int xPosition, int yPosition) {
super(inventoryIn, index, xPosition, yPosition);
allowedItem = item;
}
@Override
public boolean isItemValid(ItemStack stack) {
return stack != null && stack.getItem() == allowedItem;
}
}
@@ -0,0 +1,41 @@
package slimeknights.mantle.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Used to wrap the slots inside Modules/Subcontainers
*/
public class SlotWrapper extends Slot {
public final Slot parent;
public SlotWrapper(Slot slot) {
super(slot.inventory, slot.getSlotIndex(), slot.xDisplayPosition, slot.yDisplayPosition);
this.parent = slot;
}
@Override
public void onSlotChange(ItemStack p_75220_1_, ItemStack p_75220_2_) {
parent.onSlotChange(p_75220_1_, p_75220_2_);
}
@Override
public boolean isItemValid(ItemStack stack) {
return parent.isItemValid(stack);
}
@Override
public boolean canTakeStack(EntityPlayer playerIn) {
return parent.canTakeStack(playerIn);
}
@SideOnly(Side.CLIENT)
@Override
public boolean canBeHovered() {
return parent.canBeHovered();
}
}
@@ -0,0 +1,11 @@
package slimeknights.mantle.item;
import net.minecraft.block.Block;
import net.minecraft.item.ItemColored;
public class ItemBlockMeta extends ItemColored {
public ItemBlockMeta(Block block) {
super(block, true);
}
}
@@ -0,0 +1,36 @@
package slimeknights.mantle.item;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import java.util.List;
/**
* Item representing a fixed amount of different items represented by meta.
*/
public class ItemMeta extends Item {
protected int maxMeta;
public ItemMeta(int maxMeta) {
setHasSubtypes(true);
this.maxMeta = maxMeta;
}
@Override
public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) {
for(int i = 0; i <= maxMeta; i++) {
subItems.add(new ItemStack(itemIn, 1, i));
}
}
@Override
public int getMetadata(int damage) {
if(damage < 0 || damage > maxMeta) {
return 0;
}
return damage;
}
}
@@ -0,0 +1,62 @@
package slimeknights.mantle.item;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import java.util.List;
/**
* Item representing a dynamic amount of different items represented by meta.
* Only returns valid metadatas. The validity is determined by a bitmask.
* Current maximum is 64 metas - that should suffice for most applications.
*/
public class ItemMetaDynamic extends ItemMeta {
private static int MAX = Long.SIZE;
protected long availabilityMask;
public ItemMetaDynamic() {
super(-1);
}
public ItemStack addMeta(int meta) {
if(meta > MAX) {
throw new IllegalArgumentException(String
.format("Metadata too high, highest supported value is %d. Meta was %d", MAX, meta));
}
if(meta > maxMeta) {
maxMeta = meta;
setValid(meta);
}
return new ItemStack(this, 1, meta);
}
@Override
public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) {
for(int i = 0; i <= maxMeta; i++) {
if(isValid(i)) {
subItems.add(new ItemStack(itemIn, 1, i));
}
}
}
@Override
public int getMetadata(int damage) {
int meta = super.getMetadata(damage);
return isValid(meta) ? meta : 0;
}
protected void setValid(int meta) {
availabilityMask |= 1 << meta;
}
protected boolean isValid(int meta) {
if(meta > MAX) {
return false;
}
return ((availabilityMask >> meta) & 1) == 1;
}
}
@@ -0,0 +1,47 @@
package slimeknights.mantle.network;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.util.BlockPos;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import io.netty.buffer.ByteBuf;
public abstract class AbstractPacket implements IMessage, IMessageHandler {
@Override
public IMessage onMessage(IMessage message, MessageContext ctx) {
if(!(message instanceof AbstractPacket)) {
return null;
}
AbstractPacket packet = (AbstractPacket) message;
if(ctx.side == Side.SERVER) {
return packet.handleServer(ctx.getServerHandler());
}
else {
return packet.handleClient(ctx.getClientHandler());
}
}
public abstract IMessage handleClient(NetHandlerPlayClient netHandler);
public abstract IMessage handleServer(NetHandlerPlayServer netHandler);
protected void writePos(BlockPos pos, ByteBuf buf) {
buf.writeInt(pos.getX());
buf.writeInt(pos.getY());
buf.writeInt(pos.getZ());
}
protected BlockPos readPos(ByteBuf buf) {
int x = buf.readInt();
int y = buf.readInt();
int z = buf.readInt();
return new BlockPos(x, y, z);
}
}
@@ -0,0 +1,41 @@
package slimeknights.mantle.network;
import net.minecraft.client.Minecraft;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
/**
* Threadsafe integration of the abstract packet.
* Basically if you're doing something that has any influence on the world you should use this.
* (That's ~everything)
*/
public abstract class AbstractPacketThreadsafe extends AbstractPacket {
@Override
public final IMessage handleClient(final NetHandlerPlayClient netHandler) {
Minecraft.getMinecraft().addScheduledTask(new Runnable() {
@Override
public void run() {
handleClientSafe(netHandler);
}
});
return null;
}
@Override
public final IMessage handleServer(final NetHandlerPlayServer netHandler) {
MinecraftServer.getServer().addScheduledTask(new Runnable() {
@Override
public void run() {
handleServerSafe(netHandler);
}
});
return null;
}
public abstract void handleClientSafe(NetHandlerPlayClient netHandler);
public abstract void handleServerSafe(NetHandlerPlayServer netHandler);
}
@@ -0,0 +1,55 @@
package slimeknights.mantle.network;
import com.google.common.base.Throwables;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
/**
* A small network implementation/wrapper using AbstractPackets instead of IMessages.
* Instantiate in your mod class and register your packets accordingly.
*/
public class NetworkWrapper {
public final SimpleNetworkWrapper network;
private int id = 0;
public NetworkWrapper(String channelName) {
network = NetworkRegistry.INSTANCE.newSimpleChannel(channelName);
}
/**
* Packet will be received on both cliend and server side.
*/
public void registerPacket(Class<? extends AbstractPacket> packetClazz) {
registerPacketClient(packetClazz);
registerPacketServer(packetClazz);
}
/**
* Packet will only be received on the client side
*/
public void registerPacketClient(Class<? extends AbstractPacket> packetClazz) {
registerPacketImpl(packetClazz, Side.CLIENT);
}
/**
* Packet will only be received on the server side
*/
public void registerPacketServer(Class<? extends AbstractPacket> packetClazz) {
registerPacketImpl(packetClazz, Side.SERVER);
}
private void registerPacketImpl(Class<? extends AbstractPacket> packetClazz, Side side) {
IMessageHandler<AbstractPacket, AbstractPacket> handler;
try {
handler = packetClazz.newInstance();
} catch(Exception e) {
throw Throwables.propagate(e);
}
network.registerMessage(handler, packetClazz, id++, side);
}
}
@@ -0,0 +1,32 @@
package slimeknights.mantle.property;
import net.minecraftforge.common.property.IUnlistedProperty;
public class PropertyString implements IUnlistedProperty<String> {
private final String name;
public PropertyString(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isValid(String value) {
return !value.isEmpty();
}
@Override
public Class<String> getType() {
return String.class;
}
@Override
public String valueToString(String value) {
return value;
}
}
@@ -0,0 +1,242 @@
package slimeknights.mantle.tileentity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
// Updated version of InventoryLogic in Mantle. Also contains a few bugfixes
public class TileInventory extends TileEntity implements IInventory {
private ItemStack[] inventory;
protected String inventoryTitle;
protected boolean hasCustomName;
protected int stackSizeLimit;
/**
* @param name Localization String for the inventory title. Can be overridden through setCustomName
*/
public TileInventory(String name, int inventorySize) {
this(name, inventorySize, 64);
}
/**
* @param name Localization String for the inventory title. Can be overridden through setCustomName
*/
public TileInventory(String name, int inventorySize, int maxStackSize) {
this.inventory = new ItemStack[inventorySize];
this.stackSizeLimit = maxStackSize;
this.inventoryTitle = name;
}
/* Inventory management */
@Override
public ItemStack getStackInSlot(int slot) {
if(slot < 0 || slot >= inventory.length) {
return null;
}
return inventory[slot];
}
public boolean isStackInSlot(int slot) {
return getStackInSlot(slot) != null;
}
@Override
public int getSizeInventory() {
return inventory.length;
}
@Override
public int getInventoryStackLimit() {
return stackSizeLimit;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
if(slot < 0 || slot >= inventory.length) {
return;
}
inventory[slot] = itemstack;
if(itemstack != null && itemstack.stackSize > getInventoryStackLimit()) {
itemstack.stackSize = getInventoryStackLimit();
}
}
@Override
public ItemStack decrStackSize(int slot, int quantity) {
ItemStack itemStack = getStackInSlot(slot);
if(itemStack == null) {
return null;
}
// whole itemstack taken out
if(itemStack.stackSize <= quantity) {
setInventorySlotContents(slot, null);
this.markDirty();
return itemStack;
}
// split itemstack
itemStack = itemStack.splitStack(quantity);
// slot is empty, set to null
if(getStackInSlot(slot).stackSize == 0) {
setInventorySlotContents(slot, null);
}
this.markDirty();
// return remainder
return itemStack;
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack itemstack) {
if(slot < getSizeInventory()) {
if(inventory[slot] == null || itemstack.stackSize + inventory[slot].stackSize <= getInventoryStackLimit()) {
return true;
}
}
return false;
}
@Override
public void clear() {
for(int i = 0; i < inventory.length; i++) {
inventory[i] = null;
}
}
@Override
public String getCommandSenderName() {
return this.inventoryTitle;
}
@Override
public boolean hasCustomName() {
return this.hasCustomName;
}
public void setCustomName(String customName) {
this.hasCustomName = true;
this.inventoryTitle = customName;
}
@Override
public IChatComponent getDisplayName() {
if(hasCustomName()) {
return new ChatComponentText(getCommandSenderName());
}
return new ChatComponentTranslation(getCommandSenderName());
}
/* Supporting methods */
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
// block changed/got broken?
if(worldObj.getTileEntity(pos) != this || worldObj.getBlockState(pos).getBlock() == Blocks.air) {
return false;
}
return
entityplayer.getDistanceSq((double) pos.getX() + 0.5D, (double) pos.getY() + 0.5D, (double) pos.getZ() + 0.5D)
<= 64D;
}
@Override
public void openInventory(EntityPlayer player) {
}
@Override
public void closeInventory(EntityPlayer player) {
}
/* NBT */
@Override
public void readFromNBT(NBTTagCompound tags) {
super.readFromNBT(tags);
readInventoryFromNBT(tags);
}
public void readInventoryFromNBT(NBTTagCompound tags) {
super.readFromNBT(tags);
readInventoryFromNBT(this, tags);
if(tags.hasKey("CustomName", 8)) {
this.inventoryTitle = tags.getString("CustomName");
}
}
@Override
public void writeToNBT(NBTTagCompound tags) {
super.writeToNBT(tags);
writeInventoryToNBT(this, tags);
if(this.hasCustomName()) {
tags.setString("CustomName", this.inventoryTitle);
}
}
/** Writes the contents of the inventory to the tag */
public static void writeInventoryToNBT(IInventory inventory, NBTTagCompound tag) {
NBTTagList nbttaglist = new NBTTagList();
for(int i = 0; i < inventory.getSizeInventory(); i++) {
if(inventory.getStackInSlot(i) != null) {
NBTTagCompound itemTag = new NBTTagCompound();
itemTag.setByte("Slot", (byte) i);
inventory.getStackInSlot(i).writeToNBT(itemTag);
nbttaglist.appendTag(itemTag);
}
}
tag.setTag("Items", nbttaglist);
}
/** Reads a an inventory from the tag. Overwrites current content */
public static void readInventoryFromNBT(IInventory inventory, NBTTagCompound tag) {
NBTTagList nbttaglist = tag.getTagList("Items", 10);
for(int i = 0; i < nbttaglist.tagCount(); ++i) {
NBTTagCompound itemTag = nbttaglist.getCompoundTagAt(i);
int slot = itemTag.getByte("Slot") & 255;
if(slot >= 0 && slot < inventory.getSizeInventory()) {
inventory.setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(itemTag));
}
}
}
/* Default implementations of hardly used methods */
public ItemStack getStackInSlotOnClosing(int slot) {
return null;
}
@Override
public int getField(int id) {
return 0;
}
@Override
public void setField(int id, int value) {
}
@Override
public int getFieldCount() {
return 0;
}
}
@@ -0,0 +1,205 @@
package slimeknights.mantle.util;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import slimeknights.mantle.Mantle;
/**
* Utility class that allows to find a specific subset of items in a list of itemstacks.
* Matches can be found through oredictionary, simple nbt-independant item-meta combinations etc.
*
* The match returned by this class can then be used to remove the found recipe match from the items.
*/
public abstract class RecipeMatch {
protected final int amountNeeded;
protected final int amountMatched;
/**
* @param amountNeeded How many of the itemstack are needed for the match
* @param amountMatched If amount needed itemstacks are present, as how many matches does this count?
*/
public RecipeMatch(int amountMatched, int amountNeeded) {
this.amountMatched = amountMatched;
this.amountNeeded = amountNeeded;
}
public abstract Match matches(ItemStack[] stacks);
/** Removes the match from the stacks */
public static void removeMatch(ItemStack[] stacks, Match match) {
for(ItemStack stack : match.stacks) {
for(int i = 0; i < stacks.length; i++) {
// nbt sensitive since toolparts etc. use nbt
if(ItemStack.areItemsEqual(stack, stacks[i]) && ItemStack.areItemStackTagsEqual(stack, stacks[i])) {
if(stacks[i].stackSize < stack.stackSize) {
Mantle.logger.error("RecipeMatch has incorrect stacksize! {}", stacks[i].toString());
}
else {
stacks[i].stackSize -= stack.stackSize;
if(stacks[i].stackSize == 0) {
stacks[i] = null;
}
}
break;
}
}
}
}
/** A specific amount of a certain item is needed. Supports wildcard-metadata. Not NBT sensitive. */
public static class Item extends RecipeMatch {
private final ItemStack template;
public Item(ItemStack template, int amountNeeded) {
this(template, amountNeeded, 1);
}
/**
* @param template The itemstack to match
* @param amountNeeded How many of the itemstack are needed for the match
* @param amountMatched If amountneeded itemstacks are present, as how many matches does this count?
*/
public Item(ItemStack template, int amountNeeded, int amountMatched) {
super(amountMatched, amountNeeded);
this.template = template;
}
@Override
public Match matches(ItemStack[] stacks) {
List<ItemStack> found = Lists.newLinkedList();
int stillNeeded = amountNeeded;
for(ItemStack stack : stacks) {
if(OreDictionary.itemMatches(template, stack, false)) {
// add the amount found to the list
ItemStack copy = stack.copy();
copy.stackSize = Math.min(copy.stackSize, stillNeeded);
found.add(copy);
stillNeeded -= copy.stackSize;
// we found enough
if(stillNeeded <= 0) {
return new Match(found, amountMatched);
}
}
}
return null;
}
}
/** A combination of multiple items. NBT SENSITIVE! */
public static class ItemCombination extends RecipeMatch {
protected final ItemStack[] itemStacks;
/**
* @param amountMatched If amount needed itemstacks are present, as how many matches does this count?
*/
public ItemCombination(int amountMatched, ItemStack... stacks) {
super(amountMatched, 0);
this.itemStacks = stacks;
}
@Override
public Match matches(ItemStack[] stacks) {
List<ItemStack> found = Lists.newLinkedList();
Set<Integer> needed = Sets.newHashSet();
for(int i = 0; i < itemStacks.length; i++) {
if(itemStacks[i] != null) {
needed.add(i);
}
}
for(ItemStack stack : stacks) {
Iterator<Integer> iter = needed.iterator();
while(iter.hasNext()) {
int index = iter.next();
ItemStack template = itemStacks[index];
if(ItemStack.areItemsEqual(template, stack) && ItemStack.areItemStackTagsEqual(template, stack)) {
// add the amount found to the list
ItemStack copy = stack.copy();
copy.stackSize = 1;
found.add(copy);
iter.remove();
break;
}
}
}
if(needed.isEmpty()) {
return new Match(found, amountMatched);
}
return null;
}
}
/** A specific amount of an oredicted material is needed to match. */
public static class Oredict extends RecipeMatch {
private final List<ItemStack> oredictEntry; // todo: change this to the actual list in the oredict
public Oredict(String oredictEntry, int amountNeeded) {
this(oredictEntry, amountNeeded, 1);
}
public Oredict(String oredictEntry, int amountNeeded, int amountMatched) {
super(amountNeeded, amountMatched);
this.oredictEntry = OreDictionary.getOres(oredictEntry);
}
@Override
public Match matches(ItemStack[] stacks) {
List<ItemStack> found = Lists.newLinkedList();
int stillNeeded = amountNeeded;
for(ItemStack ore : oredictEntry) {
for(ItemStack stack : stacks) {
if(OreDictionary.itemMatches(ore, stack, false)) {
// add the amount found to the list
ItemStack copy = stack.copy();
copy.stackSize = Math.min(copy.stackSize, stillNeeded);
found.add(copy);
stillNeeded -= copy.stackSize;
// we found enough
if(stillNeeded <= 0) {
return new Match(found, amountMatched);
}
}
}
}
return null;
}
}
/** Represents a collection of items that match the recipies */
public static class Match {
/** The stacks that have to be removed to apply this match */
public List<ItemStack> stacks;
/** How often the recipe is found within this match */
public int amount;
public Match(List<ItemStack> stacks, int amount) {
this.stacks = stacks;
this.amount = amount;
}
}
}
@@ -0,0 +1,133 @@
package slimeknights.mantle.util;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import java.util.Collection;
import java.util.List;
/**
* Contains a set of matches. Allows you to easily find if a set of itemstacks matches one of them.
*/
// MANTLE
public class RecipeMatchRegistry {
protected final List<RecipeMatch> items = Lists.newArrayList();
public RecipeMatch.Match matches(Collection<ItemStack> stacks) {
return matches(stacks.toArray(new ItemStack[stacks.size()]));
}
// looks for a match in the given itemstacks
public RecipeMatch.Match matches(ItemStack... stacks) {
for(RecipeMatch recipe : items) {
RecipeMatch.Match match = recipe.matches(stacks);
if(match != null) {
return match;
}
}
return null;
}
// looks for a match with at least the given amount in the given itemstacks
public RecipeMatch.Match matches(ItemStack[] stacks, int minAmount) {
stacks = copyItemStackArray(stacks); // copy so we don't modify original
List<RecipeMatch.Match> matches = Lists.newLinkedList();
RecipeMatch.Match match;
int sum = 0;
while(sum < minAmount && (match = matches(stacks)) != null) {
matches.add(match);
RecipeMatch.removeMatch(stacks, match);
sum += match.amount;
}
// not enough found
if(sum < minAmount) {
return null;
}
// merge all found matches into one match
List<ItemStack> foundStacks = Lists.newLinkedList();
for(RecipeMatch.Match m : matches) {
foundStacks.addAll(m.stacks);
}
return new RecipeMatch.Match(foundStacks, sum);
}
/**
* Associates an oredict entry with this material. Used for repairing and other.
*
* @param oredictItem Oredict-String
* @param amountNeeded How many of this item are needed to count as one full material item.
* @param amountMatched If both item and amount are present, how often did they match?
*/
public void addItem(String oredictItem, int amountNeeded, int amountMatched) {
items.add(new RecipeMatch.Oredict(oredictItem, amountNeeded, amountMatched));
}
public void addItem(String oredictItem) {
addItem(oredictItem, 1, 1);
}
/**
* Associates a block with this material. Used for repairing and other.
*
* @param amountMatched For how many matches the block counts (e.g. redstone dust = 1 match, Redstone block = 9)
*/
public void addItem(Block block, int amountMatched) {
items.add(new RecipeMatch.Item(new ItemStack(block), 1, amountMatched));
}
/**
* Associates an item entry with this material. Used for repairing and other.
*
* @param item The item
* @param amountNeeded How many of this item are needed to count as one full material item.
* @param amountMatched If both item and amount are present, how often did they match?
*/
public void addItem(Item item, int amountNeeded, int amountMatched) {
items.add(new RecipeMatch.Item(new ItemStack(item), amountNeeded, amountMatched));
}
/**
* Associates an item entry with this material. Used for repairing and other.
*
* @param item The item
* @param amountNeeded How many of this item are needed to count as one full material item.
* @param amountMatched If both item and amount are present, how often did they match?
*/
public void addItem(ItemStack item, int amountNeeded, int amountMatched) {
items.add(new RecipeMatch.Item(item, amountNeeded, amountMatched));
}
/**
* Associates an item with this material. Used for repairing and other.
*/
public void addItem(Item item) {
addItem(item, 1, 1);
}
public void addRecipeMatch(RecipeMatch match) {
items.add(match);
}
public static ItemStack[] copyItemStackArray(ItemStack[] in) {
ItemStack[] stacksCopy = new ItemStack[in.length];
for(int i = 0; i < in.length; i++) {
if(in[i] != null) {
stacksCopy[i] = in[i].copy();
}
}
return stacksCopy;
}
}
@@ -0,0 +1,109 @@
package slimeknights.mantle.util;
import java.util.List;
import java.util.Map;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraft.item.crafting.ShapelessRecipes;
import net.minecraftforge.common.ChestGenHooks;
@SuppressWarnings("unchecked")
public class RecipeRemover
{
public static void removeShapedRecipes(List<ItemStack> removelist)
{
for (ItemStack stack : removelist)
{
removeShapedRecipe(stack);
}
}
public static void removeAnyRecipe(ItemStack resultItem)
{
List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList();
for (int i = 0; i < recipes.size(); i++)
{
IRecipe tmpRecipe = recipes.get(i);
ItemStack recipeResult = tmpRecipe.getRecipeOutput();
if (ItemStack.areItemStacksEqual(resultItem, recipeResult))
{
recipes.remove(i--);
}
}
}
public static void removeShapedRecipe(ItemStack resultItem)
{
List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList();
for (int i = 0; i < recipes.size(); i++)
{
IRecipe tmpRecipe = recipes.get(i);
if (tmpRecipe instanceof ShapedRecipes)
{
ShapedRecipes recipe = (ShapedRecipes) tmpRecipe;
ItemStack recipeResult = recipe.getRecipeOutput();
if (ItemStack.areItemStacksEqual(resultItem, recipeResult))
{
recipes.remove(i--);
}
}
}
}
public static void removeShapelessRecipe(ItemStack resultItem)
{
List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList();
for (int i = 0; i < recipes.size(); i++)
{
IRecipe tmpRecipe = recipes.get(i);
if (tmpRecipe instanceof ShapelessRecipes)
{
ShapelessRecipes recipe = (ShapelessRecipes) tmpRecipe;
ItemStack recipeResult = recipe.getRecipeOutput();
if (ItemStack.areItemStacksEqual(resultItem, recipeResult))
{
recipes.remove(i--);
}
}
}
}
public static void removeFurnaceRecipe(ItemStack resultItem)
{
Map<ItemStack, ItemStack> recipes = FurnaceRecipes.instance().getSmeltingList();
recipes.remove(resultItem);
}
public static void removeFurnaceRecipe(Item i, int metadata)
{
removeFurnaceRecipe(new ItemStack(i, 1, metadata));
}
public static void removeFurnaceRecipe(Item i)
{
removeFurnaceRecipe(new ItemStack(i, 1, 32767));
}
//removes from all vanilla worldgen chests :D
public static void removeFromChests(ItemStack resultItem)
{
ChestGenHooks.getInfo(ChestGenHooks.BONUS_CHEST).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.VILLAGE_BLACKSMITH).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_DISPENSER).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.STRONGHOLD_CORRIDOR).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.STRONGHOLD_CROSSING).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.STRONGHOLD_LIBRARY).removeItem(resultItem);
}
}
@@ -0,0 +1,27 @@
package slimeknights.mantle.util;
public class SlimeknightException extends RuntimeException {
public SlimeknightException() {
}
public SlimeknightException(String message) {
super(message);
}
public SlimeknightException(String message, Object... params) {
super(String.format(message, params));
}
public SlimeknightException(String message, Throwable cause) {
super(message, cause);
}
public SlimeknightException(Throwable cause) {
super(cause);
}
public SlimeknightException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -0,0 +1,40 @@
package slimeknights.mantle.util;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
public class TagHelper {
public static int TAG_TYPE_STRING = (new NBTTagString()).getId();
public static int TAG_TYPE_COMPOUND = (new NBTTagCompound()).getId();
private TagHelper() {
}
/* Generic Tag Operations */
public static NBTTagCompound getTagSafe(ItemStack stack) {
if(stack == null || stack.getItem() == null || !stack.hasTagCompound()) {
return new NBTTagCompound();
}
return stack.getTagCompound();
}
public static NBTTagCompound getTagSafe(NBTTagCompound tag, String key) {
if(tag == null || !tag.hasKey(key)) {
return new NBTTagCompound();
}
return tag.getCompoundTag(key);
}
public static NBTTagList getTagListSafe(NBTTagCompound tag, String key, int type) {
if(tag == null || !tag.hasKey(key)) {
return new NBTTagList();
}
return tag.getTagList(key, type);
}
}