Moved sources and reverted mappings

This commit is contained in:
Johann Bernhardt committed 2021-11-22 09:55:45 +01:00
1 parent eca0729231
commit 12a0722e28
106 files changed
+29 -29

No files matched your search

+120
View File
@@ -0,0 +1,120 @@
package mantle;
import static mantle.lib.CoreRepo.logger;
import static mantle.lib.CoreRepo.modId;
import static mantle.lib.CoreRepo.modName;
import static mantle.lib.CoreRepo.modVersion;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import mantle.books.BookData;
import mantle.books.BookDataStore;
import mantle.common.IDDumps;
import mantle.common.MProxyCommon;
import mantle.items.Manual;
import mantle.lib.CoreConfig;
import mantle.lib.CoreRepo;
import mantle.lib.environment.EnvironmentChecks;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import mantle.utils.CraftingHandler;
import java.io.File;
/**
* Mantle
*
* Central mod object for Mantle
*
* @author Sunstrike <[email protected]>
*/
@Mod(modid = modId, name = modName, version = modVersion, dependencies = "required-after:Forge@[10.13,)")
public class 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 = "mantle.client.MProxyClient", serverSide = "mantle.common.MProxyCommon")
public static MProxyCommon proxy;
public static Manual mantleBook;
/**
* Constructor
*
* EnvChecks invoked here so they run as soon as possible to enhance crash reports that may happen in preinit.
*/
public Mantle()
{
EnvironmentChecks.verifyEnvironmentSanity();
}
/**
* FML preinitialisation handler
*
* This is where we load our configs and related data, preparing for main load.
*
* @param evt The FMLPreInitializationEvent from FML
*/
@EventHandler
public void preInit (FMLPreInitializationEvent evt)
{
logger.info("Mantle (" + modVersion + ") -- Preparing for launch.");
logger.info("Entering preinitialization phase.");
CoreConfig.loadConfiguration(evt.getModConfigurationDirectory());
NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy);
mantleBook = (Manual) new Manual().setUnlocalizedName("mantle.manual");
GameRegistry.registerItem(mantleBook, "mantleBook");
}
/**
* FML initialisation handler
*
* This is where we handle basic loading and populating any missing data in the Repo
*
* @param evt The FMLInitializationEvent from FML
*/
@EventHandler
public void Init (FMLInitializationEvent evt)
{
logger.info("Entering initialization phase.");
proxy.registerRenderer();
}
/**
* FML postinitialisation handler
*
* Final chance for cleanup before main game launch
*
* @param evt The FMLPostInitializationEvent from FML
*/
@EventHandler
public void postInit (FMLPostInitializationEvent evt)
{
logger.info("Entering postinitialization phase.");
proxy.readManuals();
BookData data = new BookData();
data.unlocalizedName = "item.mantle.manual.test";
data.toolTip = "Test Book";
data.modID = CoreRepo.modId;
BookDataStore.addBook(data);
mantleBook.updateManual();
CoreConfig.loadBookLocations();
IDDumps.dump();
}
@EventHandler
public void serverStart(FMLServerStartedEvent evt)
{
CraftingHandler.logConflicts();
}
}
@@ -0,0 +1,31 @@
package mantle.blocks;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameData;
public class BlockUtils
{
public static Block getBlockFromItem (Item item)
{
return Block.getBlockFromItem(item);
}
@SuppressWarnings("unused")
public static Block getBlockFromItemStack (ItemStack itemStack)
{
return getBlockFromItem(itemStack.getItem());
}
public static String getUniqueName (Block block)
{
return GameData.getBlockRegistry().getNameForObject(block);
}
public static Block getBlockFromUniqueName (String uniqueName)
{
return GameData.getBlockRegistry().getObject(uniqueName);
}
}
@@ -0,0 +1,43 @@
package mantle.blocks;
import mantle.debug.DebugHelper;
import mantle.debug.IDebuggable;
import mantle.items.iface.IDebugItem;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
/**
* Root class for inheriting the Minecraft Block.
*
* @author Sunstrike <[email protected]>
*/
public abstract class MantleBlock extends Block
{
public MantleBlock(Material material)
{
super(material);
}
// IDebuggable support - Uses a stick for debug purposes.
@Override
public void onBlockClicked (World world, int x, int y, int z, EntityPlayer player)
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER && player.getHeldItem() != null
&& (player.getHeldItem().getItem() == Items.stick || player.getHeldItem().getItem() instanceof IDebugItem))
{
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof IDebuggable)
DebugHelper.handleDebugData(((IDebuggable) te).getDebugInfo(player));
}
super.onBlockClicked(world, x, y, z, player);
}
}
@@ -0,0 +1,102 @@
package mantle.blocks.abstracts;
import java.util.Random;
import mantle.blocks.iface.IFacingLogic;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import cpw.mods.fml.common.FMLCommonHandler;
public abstract class AdaptiveInventoryLogic extends InventoryLogic implements IFacingLogic
{
Random random = new Random();
protected int inventorySize;
public AdaptiveInventoryLogic()
{
super(0);
}
protected void adjustInventory (int size, boolean forceAdjust)
{
if (size != inventorySize || forceAdjust)
{
inventorySize = size;
ItemStack[] tempInv = inventory;
inventory = new ItemStack[size];
int invLength = tempInv.length > inventory.length ? inventory.length : tempInv.length;
System.arraycopy(tempInv, 0, inventory, 0, invLength);
if (tempInv.length > inventory.length)
{
for (int i = inventory.length; i < tempInv.length; i++)
{
ItemStack stack = tempInv[i];
if (stack != null)
{
float jumpX = random.nextFloat() * 0.8F + 0.1F;
float jumpY = random.nextFloat() * 0.8F + 0.1F;
float jumpZ = random.nextFloat() * 0.8F + 0.1F;
int offsetX = 0;
int offsetY = 0;
int offsetZ = 0;
switch (getTossDirection())
{
case 0: // -y
offsetY--;
break;
case 1: // +y
offsetY++;
break;
case 2: // +z
offsetZ--;
break;
case 3: // -z
offsetZ++;
break;
case 4: // +x
offsetX--;
break;
case 5: // -x
offsetX++;
break;
}
while (stack.stackSize > 0)
{
int itemSize = random.nextInt(21) + 10;
if (itemSize > stack.stackSize)
{
itemSize = stack.stackSize;
}
stack.stackSize -= itemSize;
EntityItem entityitem = new EntityItem(worldObj, (double) ((float) xCoord + jumpX + offsetX), (double) ((float) yCoord + jumpY),
(double) ((float) zCoord + jumpZ + offsetZ), new ItemStack(stack.getItem(), itemSize, stack.getItemDamage()));
if (stack.hasTagCompound())
{
entityitem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy());
}
float offset = 0.05F;
entityitem.motionX = (double) ((float) random.nextGaussian() * offset);
entityitem.motionY = (double) ((float) random.nextGaussian() * offset + 0.2F);
entityitem.motionZ = (double) ((float) random.nextGaussian() * offset);
worldObj.spawnEntityInWorld(entityitem);
}
}
}
}
}
}
public int getTossDirection ()
{
return getRenderDirection();
}
}
@@ -0,0 +1,217 @@
package mantle.blocks.abstracts;
import java.util.*;
import net.minecraft.entity.player.*;
import net.minecraft.inventory.*;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.*;
import net.minecraft.world.World;
public abstract class ExpandableInventoryLogic extends InventoryLogic implements IInventory
{
public ExpandableInventoryLogic()
{
super(0);
}
protected ArrayList<ItemStack> inventory = new ArrayList<ItemStack>();
protected String invName;
@Override
public ItemStack getStackInSlot (int slot)
{
return slot < inventory.size() ? inventory.get(slot) : null;
}
public boolean isStackInSlot (int slot)
{
return slot < inventory.size() && inventory.get(slot) != null;
}
@Override
public int getSizeInventory ()
{
return inventory.size();
}
public int getMaxSize ()
{
return 64;
}
@Override
public int getInventoryStackLimit ()
{
return 64;
}
public boolean canDropInventorySlot (int slot)
{
return true;
}
@Override
public void setInventorySlotContents (int slot, ItemStack itemstack)
{
if (slot < inventory.size())
{
inventory.set(slot, itemstack);
}
else if (slot == inventory.size())
{
inventory.add(itemstack);
}
else if (slot < getMaxSize())
{
inventory.ensureCapacity(slot);
inventory.set(slot, itemstack);
}
else
{
return;
}
if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
{
itemstack.stackSize = getInventoryStackLimit();
}
}
@Override
public ItemStack decrStackSize (int slot, int quantity)
{
if (slot < inventory.size() && inventory.get(slot) != null)
{
if (inventory.get(slot).stackSize <= quantity)
{
ItemStack stack = inventory.get(slot);
inventory.set(slot, null);
return stack;
}
ItemStack split = inventory.get(slot).splitStack(quantity);
if (inventory.get(slot).stackSize == 0)
{
inventory.set(slot, null);
}
return split;
}
else
{
return null;
}
}
/* Supporting methods */
@Override
public boolean isUseableByPlayer (EntityPlayer entityplayer)
{
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
return false;
else
return entityplayer.getDistance((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
public abstract Container getGuiContainer (InventoryPlayer inventoryplayer, World world, int x, int y, int z);
/* NBT */
@Override
public void readFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
this.invName = tags.getString("InvName");
NBTTagList nbttaglist = tags.getTagList("Items", 9);
inventory = new ArrayList<ItemStack>();
inventory.ensureCapacity(nbttaglist.tagCount() > getMaxSize() ? getMaxSize() : nbttaglist.tagCount());
for (int iter = 0; iter < nbttaglist.tagCount(); iter++)
{
NBTTagCompound tagList = nbttaglist.getCompoundTagAt(iter);
byte slotID = tagList.getByte("Slot");
if (slotID >= 0 && slotID < inventory.size())
{
inventory.set(slotID, ItemStack.loadItemStackFromNBT(tagList));
}
}
}
@Override
public void writeToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
if (invName != null)
tags.setString("InvName", invName);
NBTTagList nbttaglist = new NBTTagList();
for (int iter = 0; iter < inventory.size(); iter++)
{
if (inventory.get(iter) != null)
{
NBTTagCompound tagList = new NBTTagCompound();
tagList.setByte("Slot", (byte) iter);
inventory.get(iter).writeToNBT(tagList);
nbttaglist.appendTag(tagList);
}
}
tags.setTag("Items", nbttaglist);
}
/* Default implementations of hardly used methods */
public ItemStack getStackInSlotOnClosing (int slot)
{
return null;
}
public void openChest ()
{
}
public void closeChest ()
{
}
protected abstract String getDefaultName ();
public void setInvName (String name)
{
this.invName = name;
}
public String getInvName ()
{
return this.isInvNameLocalized() ? this.invName : getDefaultName();
}
public boolean isInvNameLocalized ()
{
return this.invName != null && this.invName.length() > 0;
}
public void cleanInventory ()
{
Iterator<ItemStack> i1 = inventory.iterator();
while (i1.hasNext())
{
if (i1.next() == null)
{
i1.remove();
}
}
}
@Override
public boolean isItemValidForSlot (int slot, ItemStack itemstack)
{
if (slot < getSizeInventory())
{
if (inventory.get(slot) == null || itemstack.stackSize + inventory.get(slot).stackSize <= getInventoryStackLimit())
return true;
}
else
{
return slot < getMaxSize();
}
return false;
}
}
@@ -0,0 +1,217 @@
package mantle.blocks.abstracts;
import java.util.Random;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import mantle.blocks.iface.IActiveLogic;
import mantle.blocks.iface.IFacingLogic;
import mantle.debug.DebugHelper;
import mantle.debug.IDebuggable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public abstract class InventoryBlock extends BlockContainer
{
protected Random rand = new Random();
protected InventoryBlock(Material material)
{
super(material);
}
/* Logic backend */
public TileEntity createNewTileEntity (World var1)
{
return null;
}
public abstract TileEntity createNewTileEntity (World world, int metadata);
public abstract Integer getGui (World world, int x, int y, int z, EntityPlayer entityplayer);
public abstract Object getModInstance ();
@Override
public boolean onBlockActivated (World world, int x, int y, int z, EntityPlayer player, int side, float clickX, float clickY, float clickZ)
{
if (player.isSneaking())
return false;
Integer integer = getGui(world, x, y, z, player);
if (integer == null || integer == -1)
{
return false;
}
else
{
if (!world.isRemote)
player.openGui(getModInstance(), integer, world, x, y, z);
return true;
}
}
/* Inventory */
@Override
public void breakBlock (World par1World, int x, int y, int z, Block blockID, int meta)
{
TileEntity te = par1World.getTileEntity(x, y, z);
if (te != null && te instanceof InventoryLogic)
{
InventoryLogic logic = (InventoryLogic) te;
logic.removeBlock();
for (int iter = 0; iter < logic.getSizeInventory(); ++iter)
{
ItemStack stack = logic.getStackInSlot(iter);
if (stack != null && logic.canDropInventorySlot(iter))
{
float jumpX = rand.nextFloat() * 0.8F + 0.1F;
float jumpY = rand.nextFloat() * 0.8F + 0.1F;
float jumpZ = rand.nextFloat() * 0.8F + 0.1F;
while (stack.stackSize > 0)
{
int itemSize = rand.nextInt(21) + 10;
if (itemSize > stack.stackSize)
{
itemSize = stack.stackSize;
}
stack.stackSize -= itemSize;
EntityItem entityitem = new EntityItem(par1World, (double) ((float) x + jumpX), (double) ((float) y + jumpY), (double) ((float) z + jumpZ), new ItemStack(stack.getItem(),
itemSize, stack.getItemDamage()));
if (stack.hasTagCompound())
{
entityitem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy());
}
float offset = 0.05F;
entityitem.motionX = (double) ((float) rand.nextGaussian() * offset);
entityitem.motionY = (double) ((float) rand.nextGaussian() * offset + 0.2F);
entityitem.motionZ = (double) ((float) rand.nextGaussian() * offset);
par1World.spawnEntityInWorld(entityitem);
}
}
}
}
super.breakBlock(par1World, x, y, z, blockID, meta);
}
/* Placement */
int side = -1;
//This class does not have an actual block placed in the world
@Override
public int onBlockPlaced (World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int meta)
{
this.side = side;
return meta;
}
@Override
@SuppressWarnings("deprecation") // TODO: Remove this when setDirection calls updated.
public void onBlockPlacedBy (World world, int x, int y, int z, EntityLivingBase entityliving, ItemStack stack)
{
TileEntity logic = world.getTileEntity(x, y, z);
if (logic instanceof IFacingLogic)
{
IFacingLogic direction = (IFacingLogic) logic;
// TODO: Convert all setDirection calls to modern invokation, when that's ready.
if (side != -1)
{
direction.setDirection(side);
side = -1;
}
if (entityliving == null)
{
direction.setDirection(0F, 0F, null);
}
else
{
direction.setDirection(entityliving.rotationYaw * 4F, entityliving.rotationPitch, entityliving);
}
}
if (logic instanceof InventoryLogic)
{
InventoryLogic inv = (InventoryLogic) logic;
inv.placeBlock(entityliving, stack);
if (stack.hasDisplayName())
{
inv.setInvName(stack.getDisplayName());
}
}
}
@SuppressWarnings("unused")
public static boolean isActive (IBlockAccess world, int x, int y, int z)
{
TileEntity logic = world.getTileEntity(x, y, z);
if (logic instanceof IActiveLogic)
{
return ((IActiveLogic) logic).getActive();
}
return false;
}
public int damageDropped (int meta)
{
return meta;
}
/* Textures */
public IIcon[] icons;
public abstract String[] getTextureNames ();
public abstract String getTextureDomain (int textureNameIndex);
@Override
public void registerBlockIcons (IIconRegister iconRegister)
{
String[] textureNames = getTextureNames();
this.icons = new IIcon[textureNames.length];
for (int i = 0; i < this.icons.length; ++i)
{
this.icons[i] = iconRegister.registerIcon(getTextureDomain(i) + ":" + textureNames[i]);
}
}
/* IDebuggable */
@Override
public void onBlockClicked (World world, int x, int y, int z, EntityPlayer player)
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER && player.getHeldItem() != null && player.getHeldItem().getItem() != null && player.getHeldItem().getItem() == Items.stick)
{
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof IDebuggable)
{
DebugHelper.handleDebugData(((IDebuggable) te).getDebugInfo(player));
}
}
super.onBlockClicked(world, x, y, z, player);
}
}
@@ -0,0 +1,286 @@
package mantle.blocks.abstracts;
import mantle.debug.DebugData;
import mantle.debug.IDebuggable;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
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.world.World;
/*
* A simple logic class for storing items
* Abstract to avoid instantiation
*/
public abstract class InventoryLogic extends TileEntity implements IInventory, IDebuggable
{
protected ItemStack[] inventory;
protected String invName;
protected int stackSizeLimit;
public InventoryLogic(int invSize)
{
this(invSize, 64);
}
public InventoryLogic(int invSize, int maxStackSize)
{
inventory = new ItemStack[invSize];
stackSizeLimit = maxStackSize;
}
/* Inventory management */
@Override
public ItemStack getStackInSlot (int slot)
{
return slot < inventory.length ? inventory[slot] : null;
}
public boolean isStackInSlot (int slot)
{
return slot < inventory.length && inventory[slot] != null;
}
@Override
public int getSizeInventory ()
{
return inventory.length;
}
@Override
public int getInventoryStackLimit ()
{
return stackSizeLimit;
}
public boolean canDropInventorySlot (int slot)
{
return true;
}
@Override
public void setInventorySlotContents (int slot, ItemStack itemstack)
{
inventory[slot] = itemstack;
if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
{
itemstack.stackSize = getInventoryStackLimit();
}
}
@Override
public ItemStack decrStackSize (int slot, int quantity)
{
if (inventory[slot] != null)
{
if (inventory[slot].stackSize <= quantity)
{
ItemStack stack = inventory[slot];
inventory[slot] = null;
return stack;
}
ItemStack split = inventory[slot].splitStack(quantity);
if (inventory[slot].stackSize == 0)
{
inventory[slot] = null;
}
return split;
}
else
{
return null;
}
}
/* Supporting methods */
@Override
public boolean isUseableByPlayer (EntityPlayer entityplayer)
{
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
return false;
else
return entityplayer.getDistance((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
public abstract Container getGuiContainer (InventoryPlayer inventoryplayer, World world, int x, int y, int z);
/* NBT */
@Override
public void readFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
readInventoryFromNBT(tags);
}
public void readInventoryFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
NBTTagList nbttaglist = tags.getTagList("Items", 10);
this.inventory = new ItemStack[this.getSizeInventory()];
if (tags.hasKey("CustomName", 8))
{
this.invName = tags.getString("CustomName");
}
for (int i = 0; i < nbttaglist.tagCount(); ++i)
{
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
int j = nbttagcompound1.getByte("Slot") & 255;
if (j >= 0 && j < this.inventory.length)
{
this.inventory[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
}
}
//Not removed in case of things going terribly wrong
// super.readFromNBT(tags);
// this.invName = tags.getString("InvName");
// NBTTagList nbttaglist = tags.getTagList("Items", 9);
// inventory = new ItemStack[getSizeInventory()];
// for (int iter = 0; iter < nbttaglist.tagCount(); iter++)
// {
// NBTTagCompound tagList = (NBTTagCompound) nbttaglist.getCompoundTagAt(iter);
// byte slotID = tagList.getByte("Slot");
// if (slotID >= 0 && slotID < inventory.length)
// {
// inventory[slotID] = ItemStack.loadItemStackFromNBT(tagList);
// }
// }
}
@Override
public void writeToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
writeInventoryToNBT(tags);
}
public void writeInventoryToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < this.inventory.length; ++i)
{
if (this.inventory[i] != null)
{
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
this.inventory[i].writeToNBT(nbttagcompound1);
nbttaglist.appendTag(nbttagcompound1);
}
}
tags.setTag("Items", nbttaglist);
if (this.isInvNameLocalized())
{
tags.setString("CustomName", this.invName);
}
//Not removed in case of things going terribly wrong
// if (invName != null)
// tags.setString("InvName", invName);
// NBTTagList nbttaglist = new NBTTagList();
// for (int iter = 0; iter < inventory.length; iter++)
// {
// if (inventory[iter] != null)
// {
// NBTTagCompound tagList = new NBTTagCompound();
// tagList.setByte("Slot", (byte) iter);
// inventory[iter].writeToNBT(tagList);
// nbttaglist.appendTag(tagList);
// }
// }
//
// tags.setTag("Items", nbttaglist);
}
/* Cause of the heisenbug. Do not uncomment! */
/*public void superReadFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
}
public void superWriteToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
}*/
/* Default implementations of hardly used methods */
public ItemStack getStackInSlotOnClosing (int slot)
{
return null;
}
public void openChest ()
{
}
public void closeChest ()
{
}
protected abstract String getDefaultName ();
public void setInvName (String name)
{
this.invName = name;
}
public String getInvName ()
{
return this.isInvNameLocalized() ? this.invName : getDefaultName();
}
public boolean hasCustomInventoryName()
{
return isInvNameLocalized();
}
public boolean isInvNameLocalized ()
{
return this.invName != null && this.invName.length() > 0;
}
@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;
}
public void placeBlock (EntityLivingBase entity, ItemStack stack)
{
}
public void removeBlock ()
{
}
/* IDebuggable */
@Override
public DebugData getDebugInfo (EntityPlayer player)
{
String[] strs = new String[1];
strs[0] = "invName: " + invName + ", inventory.length: " + inventory.length + ", stackSizeLimit: " + stackSizeLimit;
return new DebugData(player, getClass(), strs);
}
}
@@ -0,0 +1,90 @@
package mantle.blocks.abstracts;
import java.util.List;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
/**
* Slab version of InventoryBlock.
*
* @author mDiyo
*/
public abstract class InventorySlab extends InventoryBlock
{
public InventorySlab(Material material)
{
super(material);
}
/* Rendering */
@Override
//TODO: renderAsNormalBlock()
public boolean renderAsNormalBlock ()
{
return false;
}
//TODO: isOpaqueCube()
@Override
public boolean isOpaqueCube ()
{
return false;
}
//TODO shouldSideBeRendered
@Override
public boolean shouldSideBeRendered (IBlockAccess world, int x, int y, int z, int side)
{
if (side > 1)
return super.shouldSideBeRendered(world, x, y, z, side);
int meta = world.getBlockMetadata(x, y, z);
boolean top = (meta | 8) == 1;
if ((top && side == 0) || (!top && side == 1))
return true;
return super.shouldSideBeRendered(world, x, y, z, side);
}
//TODO: addCollisionBoxesToList()
@Override
@SuppressWarnings("rawtypes")
public void addCollisionBoxesToList (World world, int x, int y, int z, AxisAlignedBB axisalignedbb, List arraylist, Entity entity)
{
setBlockBoundsBasedOnState(world, x, y, z);
super.addCollisionBoxesToList(world, x, y, z, axisalignedbb, arraylist, entity);
}
public void setBlockBoundsForItemRender ()
{
//TODO: setBlockBounds
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F);
}
public void setBlockBoundsBasedOnState (IBlockAccess world, int x, int y, int z)
{
int meta = world.getBlockMetadata(x, y, z) / 8;
float minY = meta == 1 ? 0.5F : 0.0F;
float maxY = meta == 1 ? 1.0F : 0.5F;
setBlockBounds(0.0F, minY, 0F, 1.0F, maxY, 1.0F);
}
public int onBlockPlaced (World par1World, int blockX, int blockY, int blockZ, int side, float clickX, float clickY, float clickZ, int metadata)
{
if (side == 1)
return metadata;
if (side == 0 || clickY >= 0.5F)
return metadata | 8;
return metadata;
}
public int damageDropped (int meta)
{
return meta % 8;
}
}
@@ -0,0 +1,71 @@
package mantle.blocks.abstracts;
import static mantle.lib.CoreRepo.logger;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
/**
*
* @author progwml6
* base class for itemBlocks with different unlocalized names based on metadata
*/
public class MultiItemBlock extends ItemBlock
{
private String blockType[];
private String unlocalizedName;
private String append;
private int specialIndex[] = { -1, -1 };
public MultiItemBlock(Block b, String itemBlockUnlocalizedName, String[] blockTypes)
{
super(b);
if (itemBlockUnlocalizedName.isEmpty())
this.unlocalizedName = super.getUnlocalizedName();
else
this.unlocalizedName = itemBlockUnlocalizedName;
this.blockType = blockTypes;
this.append = "";
}
public MultiItemBlock(Block b, String itemBlockUnlocalizedName, String appendToEnd, String[] blockTypes)
{
super(b);
this.unlocalizedName = itemBlockUnlocalizedName;
this.blockType = blockTypes;
this.append = "." + appendToEnd;
}
public void setSpecialIndex (int clampIndex, int stringBuilderIndex)
{
specialIndex[0] = clampIndex;
specialIndex[1] = stringBuilderIndex;
}
public int getMetadata (int meta)
{
return meta;
}
public String getUnlocalizedName (ItemStack itemstack)
{
int pos = MathHelper.clamp_int(itemstack.getItemDamage(), 0, (specialIndex[0] > -1) ? specialIndex[0] : (blockType.length - 1));
int sbIndex = (specialIndex[1] > -1) ? pos : (specialIndex[1] - pos);
if (sbIndex < 0)
sbIndex = -1 * sbIndex;
try
{
return (new StringBuilder()).append(unlocalizedName).append(".").append(blockType[sbIndex - 1]).append(append).toString();
}
catch (ArrayIndexOutOfBoundsException ex)
{
logger.warn("[MultiItemBlock] Caught array index error in getUnlocalizedName: " + ex.getMessage());
logger.warn("[MultiItemBlock] Returning unlocalized name: " + getUnlocalizedName());
return getUnlocalizedName();
}
}
}
@@ -0,0 +1,212 @@
package mantle.blocks.abstracts;
import mantle.blocks.BlockUtils;
import mantle.blocks.iface.IMasterLogic;
import mantle.blocks.iface.IServantLogic;
import mantle.debug.DebugData;
import mantle.debug.IDebuggable;
import mantle.world.CoordTuple;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
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.world.World;
import cpw.mods.fml.common.registry.GameRegistry;
public class MultiServantLogic extends TileEntity implements IServantLogic, IDebuggable
{
boolean hasMaster;
CoordTuple master;
Block masterBlock;
byte masterMeat; //Typo, it stays!
public boolean canUpdate ()
{
return false;
}
public boolean getHasMaster ()
{
return hasMaster;
}
public boolean hasValidMaster ()
{
if (!hasMaster)
return false;
if (worldObj.getBlock(master.x, master.y, master.z) == masterBlock && worldObj.getBlockMetadata(master.x, master.y, master.z) == masterMeat)
return true;
else
{
hasMaster = false;
master = null;
return false;
}
}
public CoordTuple getMasterPosition ()
{
return master;
}
public void overrideMaster (int x, int y, int z)
{
hasMaster = true;
master = new CoordTuple(x, y, z);
masterBlock = worldObj.getBlock(x, y, z);
masterMeat = (byte) worldObj.getBlockMetadata(x, y, z);
}
public void removeMaster ()
{
hasMaster = false;
master = null;
masterBlock = null;
masterMeat = 0;
}
@Override
public boolean setPotentialMaster (IMasterLogic master, World w, int x, int y, int z)
{
return !hasMaster;
}
@Deprecated
public boolean verifyMaster (IMasterLogic logic, int x, int y, int z)
{
if (master.equalCoords(x, y, z) && worldObj.getBlock(x, y, z) == masterBlock && worldObj.getBlockMetadata(x, y, z) == masterMeat)
return true;
else
return false;
}
@Override
public boolean verifyMaster (IMasterLogic logic, World world, int x, int y, int z)
{
if (hasMaster)
{
return hasValidMaster();
}
else
{
overrideMaster(x, y, z);
return true;
}
}
@Override
public void invalidateMaster (IMasterLogic master, World w, int x, int y, int z)
{
hasMaster = false;
master = null;
}
public void notifyMasterOfChange ()
{
if (hasValidMaster())
{
IMasterLogic logic = (IMasterLogic) worldObj.getTileEntity(master.x, master.y, master.z);
logic.notifyChange(this, xCoord, yCoord, zCoord);
}
}
public void readCustomNBT (NBTTagCompound tags)
{
hasMaster = tags.getBoolean("TiedToMaster");
if (hasMaster)
{
int xCenter = tags.getInteger("xCenter");
int yCenter = tags.getInteger("yCenter");
int zCenter = tags.getInteger("zCenter");
master = new CoordTuple(xCenter, yCenter, zCenter);
masterBlock = BlockUtils.getBlockFromUniqueName(tags.getString("MasterBlockName"));
masterMeat = tags.getByte("masterMeat");
}
}
public void writeCustomNBT (NBTTagCompound tags)
{
tags.setBoolean("TiedToMaster", hasMaster);
if (hasMaster)
{
tags.setInteger("xCenter", master.x);
tags.setInteger("yCenter", master.y);
tags.setInteger("zCenter", master.z);
tags.setString("MasterBlockName", BlockUtils.getUniqueName(masterBlock));
tags.setByte("masterMeat", masterMeat);
}
}
@Override
public void readFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
readCustomNBT(tags);
}
@Override
public void writeToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
writeCustomNBT(tags);
}
/* Packets */
@Override
public Packet getDescriptionPacket ()
{
NBTTagCompound tag = new NBTTagCompound();
writeCustomNBT(tag);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tag);
}
@Override
public void onDataPacket (NetworkManager net, S35PacketUpdateTileEntity packet)
{
readCustomNBT(packet.func_148857_g());
worldObj.func_147479_m(xCoord, yCoord, zCoord);
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
/* IDebuggable */
@Override
public DebugData getDebugInfo (EntityPlayer player)
{
String[] strs = new String[2];
strs[0] = "Location: x" + xCoord + ", y" + yCoord + ", z" + zCoord;
if (hasMaster)
{
strs[1] = "masterBlock: " + masterBlock.toString() + ", masterMeat: " + masterMeat;
}
else
{
strs[1] = "No active master.";
}
return new DebugData(player, getClass(), strs);
}
public World getWorld ()
{
return super.getWorldObj();
}
@Deprecated
public boolean setMaster (int x, int y, int z)
{
if (!hasMaster || worldObj.getBlock(master.x, master.y, master.z) != masterBlock || (worldObj.getBlockMetadata(master.x, master.y, master.z) != masterMeat))
{
overrideMaster(x, y, z);
return true;
}
else
{
return false;
}
}
}
@@ -0,0 +1,13 @@
package mantle.blocks.iface;
/**
* Marks blocks that can be active and inactive.
*
* @author mDiyo
*/
public interface IActiveLogic
{
public boolean getActive ();
public void setActive (boolean flag);
}
@@ -0,0 +1,27 @@
package mantle.blocks.iface;
import net.minecraft.entity.EntityLivingBase;
import net.minecraftforge.common.util.ForgeDirection;
/**
* Logic for blocks which have a specific direction facing.
*
* @author mDiyo
*/
public interface IFacingLogic
{
public byte getRenderDirection ();
public ForgeDirection getForgeDirection ();
@Deprecated
public void setDirection (int side);
@Deprecated
public void setDirection (float yaw, float pitch, EntityLivingBase player);
/** This will be added next version
* public void setDirection(int side, float yaw, float pitch, EntityLivingBase player); */
}
@@ -0,0 +1,12 @@
package mantle.blocks.iface;
public interface IMasterLogic
{
/** Called when servants change their state
*
* @param x Servant X
* @param y Servant Y
* @param z Servant Z
*/
public void notifyChange (IServantLogic servant, int x, int y, int z);
}
@@ -0,0 +1,8 @@
package mantle.blocks.iface;
public interface IMasterNode extends IMasterLogic, IServantLogic
{
public boolean isCurrentlyMaster ();
public boolean isEquivalentMaster (IMasterLogic master);
}
@@ -0,0 +1,47 @@
package mantle.blocks.iface;
import mantle.world.CoordTuple;
import net.minecraft.world.World;
public interface IServantLogic
{
public CoordTuple 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 x xCoord of master
* @param y yCoord of master
* @param z zCoord of master
* @return whether the servant can be tied to this master
*/
public boolean setPotentialMaster (IMasterLogic master, World world, int xMaster, int yMaster, int zMaster);
/** Used to set and verify that this is the block's master
*
* @param master
* @param world
* @param x xCoord of master
* @param y yCoord of master
* @param z zCoord of master
* @return Is this block tied to this master?
*/
public boolean verifyMaster (IMasterLogic master, World world, int xMaster, int yMaster, int zMaster);
/** Exactly what it says on the tin
*
* @param master
* @param world
* @param x xCoord of master
* @param y yCoord of master
* @param z zCoord of master
*/
public void invalidateMaster (IMasterLogic master, World world, int xMaster, int yMaster, int zMaster);
}
+32
View File
@@ -0,0 +1,32 @@
package mantle.books;
import mantle.client.SmallFontRenderer;
import net.minecraft.util.ResourceLocation;
import org.w3c.dom.Document;
public class BookData
{
public String unlocalizedName = new String();
public String toolTip = new String();
public String modID = new String();
public ResourceLocation leftImage = new ResourceLocation("mantle", "textures/gui/bookleft.png");
public ResourceLocation rightImage = new ResourceLocation("mantle", "textures/gui/bookright.png");
public ResourceLocation itemImage = new ResourceLocation("mantle", "textures/items/mantlebook_blue.png");
public Document doc = ManualReader.readManual("/assets/mantle/manuals/test.xml");
//font can be left null if so, the default from mantle will be used
public SmallFontRenderer font;
public Boolean isTranslatable = false;
public boolean isFromZip = false;
public Document getDoc ()
{
return this.doc;
}
public String getFullUnlocalizedName ()
{
return this.modID + ":" + this.unlocalizedName;
}
}
@@ -0,0 +1,51 @@
package mantle.books;
import java.util.List;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Lists;
public class BookDataStore
{
private static HashBiMap<String, BookData> data = HashBiMap.create();
private static HashBiMap<Integer, String> intMap = HashBiMap.create();
private static List<String> zipBooks= Lists.newArrayList();
public static void addBook (BookData bd)
{
int insertOrder = data.size();
data.put(bd.getFullUnlocalizedName(), bd);
intMap.put(insertOrder, bd.getFullUnlocalizedName());
if(bd.isFromZip)
zipBooks.add(bd.getFullUnlocalizedName());
}
public static BookData getBookfromName (String ModID, String unlocalizedName)
{
return getBookFromName(ModID + ":" + unlocalizedName);
}
public static BookData getBookFromName (String fullBookName)
{
return data.get(fullBookName);
}
public static BookData getBookfromID (int bookIDNum)
{
return data.get(intMap.get(bookIDNum));
}
public static int getIDFromName (String FullUnlocalizedName)
{
return intMap.inverse().get(FullUnlocalizedName);
}
public static int getIDFromBook (BookData b)
{
return getIDFromName(data.inverse().get(b));
}
public static List<String> getZipBooks(){
return zipBooks;
}
}
@@ -0,0 +1,50 @@
package mantle.books;
import static mantle.lib.CoreRepo.logger;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import mantle.Mantle;
import org.w3c.dom.Document;
public class ManualReader
{
public static Document readManual (String location)
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try
{
logger.info("Loading Manual XML from: " + location);
InputStream stream = Mantle.class.getResourceAsStream(location);
return readManual(stream, location);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public static Document readManual (InputStream is, String filenameOrLocation)
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
return doc;
}
catch (Exception e)
{
logger.error("Failed to Load Manual XML from: " + filenameOrLocation);
e.printStackTrace();
return null;
}
}
}
@@ -0,0 +1,17 @@
package mantle.books.client;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.util.ResourceLocation;
public class BookImage {
public int height, width;
public DynamicTexture texture;
public ResourceLocation resource;
public BookImage(int width, int height, DynamicTexture texture, ResourceLocation resource) {
this.width = width;
this.height = height;
this.texture = texture;
this.resource = resource;
}
}
+22
View File
@@ -0,0 +1,22 @@
package mantle.books.external;
public class BookIS
{
//users chosen nickname for this specific itemstack
public String cname;
//fully qualified name from the game registry for the item/block in question
public String fullISName;
public int metadata;
public String tags;
public int stackSize;
public int getStackSize ()
{
return stackSize >= 0 ? stackSize : 1;
}
}
+20
View File
@@ -0,0 +1,20 @@
package mantle.books.external;
import com.google.gson.JsonObject;
public class BookLoad
{
public String unlocalizedName;
public String tooltip;
public boolean translatable;
public String BookIcon;
public String LeftImage;
public String rightImage;
public BookIS[] registerItemStacks;
public JsonObject[] smallRecipes;
public JsonObject[] largeRecipes;
public JsonObject[] furnaceRecipes;
public JsonObject[] manualIcons;
}
+259
View File
@@ -0,0 +1,259 @@
package mantle.books.external;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Enumeration;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.imageio.ImageIO;
import static mantle.lib.CoreRepo.logger;
import mantle.books.BookData;
import mantle.books.BookDataStore;
import mantle.books.ManualReader;
import mantle.books.client.BookImage;
import mantle.lib.client.MantleClientRegistry;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
public class ZipLoader
{
public static Map<String, ItemStack> loadedIS = Maps.newHashMap();
public static BookData loadZip (File f)
{
BookLoad bl;
String flName = new String();
String flExt = new String();
String lImg = new String();
String rImg = new String();
String bIcon = new String();
String unlocName = new String();
String toolTip = new String();
Boolean translatable = false;
BookData b = new BookData();
boolean isClient = FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT;
if (f.exists())
{
if (FilenameUtils.getExtension(f.getPath()).equalsIgnoreCase("zip"))
{
try
{
logger.info("Loading book zip " + f.getName());
ZipFile zipfile = new ZipFile(f);
Enumeration<? extends ZipEntry> e = zipfile.entries();
while (e.hasMoreElements())
{
ZipEntry entry = e.nextElement();
flName = entry.getName();
flExt = FilenameUtils.getExtension(flName);
if (!entry.isDirectory())
{
if (isClient && isImage(flExt))
{
String id = FilenameUtils.getBaseName(flName);
BufferedImage img = ImageIO.read(zipfile.getInputStream(entry));
DynamicTexture dynTexture = new DynamicTexture(img);
ResourceLocation rsLoc = Minecraft.getMinecraft().getTextureManager().getDynamicTextureLocation(id, dynTexture);
BookImage bI = new BookImage(img.getWidth(), img.getHeight(), dynTexture, rsLoc);
MantleClientRegistry.imageCache.put(id, bI);
}
if (flExt.equalsIgnoreCase("xml"))
{
b.doc = ManualReader.readManual(zipfile.getInputStream(entry), flName);
}
if (flExt.equalsIgnoreCase("lang"))
{
//TODO 1.7 put this data into the vanilla lang stuffs
}
if (flExt.equalsIgnoreCase("json"))
{
Gson g = new Gson();
bl = g.fromJson(IOUtils.toString(zipfile.getInputStream(entry), Charsets.UTF_8), BookLoad.class);
for (BookIS bis : bl.registerItemStacks)
{
try
{
ItemStack is = loadedIS.get(bis.cname);
if (is == null)
{
Block blok = (Block) Block.blockRegistry.getObject(bis.cname);
Item it = (Item) Item.itemRegistry.getObject(bis.cname);
if (it != null)
{
is = new ItemStack(it, bis.getStackSize(), bis.metadata);
}
else if (bl != null)
{
is = new ItemStack(blok, bis.getStackSize(), bis.metadata);
}
if (is != null)
{
if (bis.tags != null && !bis.tags.isEmpty())
{
try
{
is.stackTagCompound = (NBTTagCompound) JsonToNBT.func_150315_a(bis.tags);
}
catch (Exception e1)
{
}
}
loadedIS.put(bis.cname, is);
}
}
}
catch (Exception e1)
{
}
}
if (isClient)
{
for (JsonObject jso : bl.smallRecipes)
{
if (jso != null)
{
ItemStack out = loadedIS.get(jso.get("out").getAsString());
ItemStack in[] = getISArray(jso.getAsJsonArray("in"));
String name = jso.get("name").getAsString();
if (out != null && in != null && in.length <= 4 && name != null && !name.isEmpty())
{
MantleClientRegistry.registerManualSmallRecipe(name, out, in);
}
}
}
for (JsonObject jso : bl.largeRecipes)
{
if (jso != null)
{
ItemStack out = loadedIS.get(jso.get("out").getAsString());
ItemStack in[] = getISArray(jso.getAsJsonArray("in"));
String name = jso.get("name").getAsString();
if (out != null && in != null && in.length <= 9 && name != null && !name.isEmpty())
{
MantleClientRegistry.registerManualLargeRecipe(name, out, in);
}
}
}
for (JsonObject jso : bl.furnaceRecipes)
{
if (jso != null)
{
ItemStack out = loadedIS.get(jso.get("out").getAsString());
ItemStack in = loadedIS.get(jso.get("in").getAsString());
String name = jso.get("name").getAsString();
if (out != null && in != null && name != null && !name.isEmpty())
{
MantleClientRegistry.registerManualFurnaceRecipe(name, out, in);
}
}
}
for (JsonObject jso : bl.manualIcons)
{
if (jso != null)
{
ItemStack in = loadedIS.get(jso.get("stack").getAsString());
String name = jso.get("name").getAsString();
if (in != null && name != null && !name.isEmpty())
{
MantleClientRegistry.registerManualIcon(name, in);
}
}
}
}
b.unlocalizedName = bl.unlocalizedName;
b.toolTip = bl.tooltip;
b.isTranslatable = bl.translatable;
b.leftImage = bl.LeftImage == null ? new ResourceLocation("mantle", "textures/gui/bookleft.png") : MantleClientRegistry.getBookImageFromCache(bl.LeftImage).resource;
b.rightImage = bl.rightImage == null ? new ResourceLocation("mantle", "textures/gui/bookright.png")
: MantleClientRegistry.getBookImageFromCache(bl.rightImage).resource;
b.itemImage = bl.BookIcon == null ? new ResourceLocation("mantle", "textures/items/mantlebook_blue.png")
: MantleClientRegistry.getBookImageFromCache(bl.BookIcon).resource;
b.isFromZip = true;
BookDataStore.addBook(b);
}
}
}
zipfile.close();
b.unlocalizedName = unlocName;
b.toolTip = toolTip;
b.isTranslatable = translatable;
b.leftImage = lImg == null ? new ResourceLocation("mantle", "textures/gui/bookleft.png") : MantleClientRegistry.getBookImageFromCache(lImg).resource;
b.rightImage = rImg == null ? new ResourceLocation("mantle", "textures/gui/bookright.png") : MantleClientRegistry.getBookImageFromCache(rImg).resource;
b.itemImage = bIcon == null ? new ResourceLocation("mantle", "textures/items/mantlebook_blue.png") : MantleClientRegistry.getBookImageFromCache(bIcon).resource;
b.isFromZip = true;
BookDataStore.addBook(b);
}
catch (Exception e)
{
logger.info(" Error Loading book zip " + f.getName());
}
return null;
}
else
{
logger.error("Attempted to load non-zip file for mantle book. File " + f.getName() + " will be skipped");
}
}
else
{
logger.error("Attempted to load non-existant file for mantle book. File will be skipped");
}
return null;
}
public static boolean isImage (String ext)
{
if (ext.equalsIgnoreCase("png"))
return true;
return false;
}
public static ItemStack[] getISArray (JsonArray a)
{
ItemStack[] is = new ItemStack[a.size()];
ItemStack loadedStack;
for (int i = 0; i < a.size(); i++)
{
if (a.get(i).getAsString() != null && !a.get(i).getAsString().isEmpty() && a.get(i).getAsString().equals("none"))
{
is[i] = null;
}
else
{
loadedStack = loadedIS.get(a.get(i).getAsString());
if (loadedStack == null)
{
is = null;
return is;
}
is[i] = loadedStack;
}
}
return is;
}
}
@@ -0,0 +1,101 @@
package mantle.client;
import static mantle.lib.CoreRepo.logger;
import java.util.HashMap;
import java.util.Map;
import mantle.books.BookData;
import mantle.books.BookDataStore;
import mantle.client.gui.GuiManual;
import mantle.client.pages.BlankPage;
import mantle.client.pages.BookPage;
import mantle.client.pages.ContentsTablePage;
import mantle.client.pages.CraftingPage;
import mantle.client.pages.FurnacePage;
import mantle.client.pages.PicturePage;
import mantle.client.pages.SectionPage;
import mantle.client.pages.SidebarPage;
import mantle.client.pages.TextPage;
import mantle.client.pages.TitlePage;
import mantle.common.MProxyCommon;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
public class MProxyClient extends MProxyCommon
{
public static final String MINECRAFT_ASCII_PATH = "minecraft:textures/font/ascii.png";
public static SmallFontRenderer smallFontRenderer;
/* Registers any rendering code. */
public void registerRenderer ()
{
Minecraft mc = Minecraft.getMinecraft();
if (mc.getTextureManager() == null)
logger.error("Vanilla texture manager is null!");
if (mc.renderEngine == null)
logger.error("Vanilla render engine is null!");
smallFontRenderer = new SmallFontRenderer(mc.gameSettings, new ResourceLocation(MINECRAFT_ASCII_PATH), mc.renderEngine, false);
}
public static Map<String, Class<? extends BookPage>> pageClasses = new HashMap<String, Class<? extends BookPage>>();
public static void registerManualPage (String type, Class<? extends BookPage> clazz)
{
pageClasses.put(type, clazz);
}
public static Class<? extends BookPage> getPageClass (String type)
{
return pageClasses.get(type);
}
public void readManuals ()
{
initManualPages();
}
void initManualPages ()
{
MProxyClient.registerManualPage("crafting", CraftingPage.class);
MProxyClient.registerManualPage("picture", PicturePage.class);
MProxyClient.registerManualPage("text", TextPage.class);
MProxyClient.registerManualPage("intro", TextPage.class);
MProxyClient.registerManualPage("sectionpage", SectionPage.class);
MProxyClient.registerManualPage("intro", TitlePage.class);
MProxyClient.registerManualPage("contents", ContentsTablePage.class);
MProxyClient.registerManualPage("furnace", FurnacePage.class);
MProxyClient.registerManualPage("sidebar", SidebarPage.class);
MProxyClient.registerManualPage("blank", BlankPage.class);
}
@Override
public Object getClientGuiElement (int ID, EntityPlayer player, World world, int x, int y, int z)
{
if (ID == manualGuiID)
{
ItemStack stack = player.getCurrentEquippedItem();
if (stack == null)
logger.error("Null stack in book.");
if (stack != null && stack.getItem() == null)
logger.error("Null item in book.");
if (stack != null && stack.getItem() != null && stack.getItem().getUnlocalizedName() == null)
logger.error("Null unlocalized name in book.");
else
{
return new GuiManual(stack, MProxyClient.getBookDataFromStack(stack));
}
}
return null;
}
private static BookData getBookDataFromStack (ItemStack stack)
{
return BookDataStore.getBookFromName(stack.getItem().getUnlocalizedName(stack));
}
}
@@ -0,0 +1,679 @@
package mantle.client;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.ForgeHooksClient;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class RenderItemCopy extends Render
{
private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png");
private RenderBlocks itemRenderBlocks = new RenderBlocks();
/** The RNG used in RenderItem (for bobbing itemstacks on the ground) */
private Random random = new Random();
public boolean renderWithColor = true;
/** Defines the zLevel of rendering of item on GUI. */
public float zLevel;
public static boolean renderInFrame;
public RenderItemCopy()
{
this.shadowSize = 0.15F;
this.shadowOpaque = 0.75F;
}
/**
* Renders the item
*/
public void doRenderItem (EntityItem par1EntityItem, double par2, double par4, double par6, float par8, float par9)
{
this.bindEntityTexture(par1EntityItem);
this.random.setSeed(187L);
ItemStack itemstack = par1EntityItem.getEntityItem();
if (itemstack.getItem() != null)
{
GL11.glPushMatrix();
float f2 = shouldBob() ? MathHelper.sin(((float) par1EntityItem.age + par9) / 10.0F + par1EntityItem.hoverStart) * 0.1F + 0.1F : 0F;
float f3 = (((float) par1EntityItem.age + par9) / 20.0F + par1EntityItem.hoverStart) * (180F / (float) Math.PI);
byte b0 = getMiniBlockCount(itemstack);
GL11.glTranslatef((float) par2, (float) par4 + f2, (float) par6);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
float f4;
float f5;
float f6;
int i;
Block block = null;
block = Block.getBlockFromItem(itemstack.getItem());
if (ForgeHooksClient.renderEntityItem(par1EntityItem, itemstack, f2, f3, random, renderManager.renderEngine, new RenderBlocks(), 000)) // TODO what goes here not 000
{
;
}
else if (itemstack.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d(block.getRenderType()))
{
GL11.glRotatef(f3, 0.0F, 1.0F, 0.0F);
if (renderInFrame)
{
GL11.glScalef(1.25F, 1.25F, 1.25F);
GL11.glTranslatef(0.0F, 0.05F, 0.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
}
float f7 = 0.25F;
int j = block.getRenderType();
if (j == 1 || j == 19 || j == 12 || j == 2)
{
f7 = 0.5F;
}
GL11.glScalef(f7, f7, f7);
for (i = 0; i < b0; ++i)
{
GL11.glPushMatrix();
if (i > 0)
{
f5 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / f7;
f4 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / f7;
f6 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / f7;
GL11.glTranslatef(f5, f4, f6);
}
f5 = 1.0F;
//TODO renderBlockAsItem
this.itemRenderBlocks.renderBlockAsItem(block, itemstack.getItemDamage(), f5);
GL11.glPopMatrix();
}
}
else
{
float f8;
if (itemstack.getItemSpriteNumber() == 1 && itemstack.getItem().requiresMultipleRenderPasses())
{
if (renderInFrame)
{
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
}
else
{
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
for (int k = 0; k < itemstack.getItem().getRenderPasses(itemstack.getItemDamage()); ++k)
{
this.random.setSeed(187L);
IIcon icon = itemstack.getItem().getIcon(itemstack, k);
f8 = 1.0F;
if (this.renderWithColor)
{
i = itemstack.getItem().getColorFromItemStack(itemstack, k);
f5 = (float) (i >> 16 & 255) / 255.0F;
f4 = (float) (i >> 8 & 255) / 255.0F;
f6 = (float) (i & 255) / 255.0F;
GL11.glColor4f(f5 * f8, f4 * f8, f6 * f8, 1.0F);
this.renderDroppedItem(par1EntityItem, icon, b0, par9, f5 * f8, f4 * f8, f6 * f8, k);
}
else
{
this.renderDroppedItem(par1EntityItem, icon, b0, par9, 1.0F, 1.0F, 1.0F, k);
}
}
}
else
{
if (renderInFrame)
{
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
}
else
{
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
IIcon icon1 = itemstack.getIconIndex();
if (this.renderWithColor)
{
int l = itemstack.getItem().getColorFromItemStack(itemstack, 0);
f8 = (float) (l >> 16 & 255) / 255.0F;
float f9 = (float) (l >> 8 & 255) / 255.0F;
f5 = (float) (l & 255) / 255.0F;
f4 = 1.0F;
this.renderDroppedItem(par1EntityItem, icon1, b0, par9, f8 * f4, f9 * f4, f5 * f4);
}
else
{
this.renderDroppedItem(par1EntityItem, icon1, b0, par9, 1.0F, 1.0F, 1.0F);
}
}
}
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glPopMatrix();
}
}
protected ResourceLocation func_110796_a (EntityItem par1EntityItem)
{
return this.renderManager.renderEngine.getResourceLocation(par1EntityItem.getEntityItem().getItemSpriteNumber());
}
/**
* Renders a dropped item
*/
private void renderDroppedItem (EntityItem par1EntityItem, IIcon par2Icon, int par3, float par4, float par5, float par6, float par7)
{
renderDroppedItem(par1EntityItem, par2Icon, par3, par4, par5, par6, par7, 0);
}
private void renderDroppedItem (EntityItem par1EntityItem, IIcon par2Icon, int par3, float par4, float par5, float par6, float par7, int pass)
{
Tessellator tessellator = Tessellator.instance;
if (par2Icon == null)
{
TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager();
ResourceLocation resourcelocation = texturemanager.getResourceLocation(par1EntityItem.getEntityItem().getItemSpriteNumber());
par2Icon = ((TextureMap) texturemanager.getTexture(resourcelocation)).getAtlasSprite("missingno");
}
float f4 = par2Icon.getMinU();
float f5 = par2Icon.getMaxU();
float f6 = par2Icon.getMinV();
float f7 = par2Icon.getMaxV();
float f8 = 1.0F;
float f9 = 0.5F;
float f10 = 0.25F;
float f11;
if (this.renderManager.options.fancyGraphics)
{
GL11.glPushMatrix();
if (renderInFrame)
{
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
}
else
{
GL11.glRotatef((((float) par1EntityItem.age + par4) / 20.0F + par1EntityItem.hoverStart) * (180F / (float) Math.PI), 0.0F, 1.0F, 0.0F);
}
float f12 = 0.0625F;
f11 = 0.021875F;
ItemStack itemstack = par1EntityItem.getEntityItem();
int j = itemstack.stackSize;
byte b0 = getMiniItemCount(itemstack);
GL11.glTranslatef(-f9, -f10, -((f12 + f11) * (float) b0 / 2.0F));
for (int k = 0; k < b0; ++k)
{
// Makes items offset when in 3D, like when in 2D, looks much better. Considered a vanilla bug...
if (k > 0 && shouldSpreadItems())
{
float x = (random.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F;
float y = (random.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F;
float z = (random.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F;
GL11.glTranslatef(x, y, f12 + f11);
}
else
{
GL11.glTranslatef(0f, 0f, f12 + f11);
}
if (itemstack.getItemSpriteNumber() == 0)
{
this.bindTexture(TextureMap.locationBlocksTexture);
}
else
{
this.bindTexture(TextureMap.locationItemsTexture);
}
GL11.glColor4f(par5, par6, par7, 1.0F);
ItemRenderer.renderItemIn2D(tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12);
if (itemstack.hasEffect(pass))
{
GL11.glDepthFunc(GL11.GL_EQUAL);
GL11.glDisable(GL11.GL_LIGHTING);
this.renderManager.renderEngine.bindTexture(RES_ITEM_GLINT);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE);
float f13 = 0.76F;
GL11.glColor4f(0.5F * f13, 0.25F * f13, 0.8F * f13, 1.0F);
GL11.glMatrixMode(GL11.GL_TEXTURE);
GL11.glPushMatrix();
float f14 = 0.125F;
GL11.glScalef(f14, f14, f14);
float f15 = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F * 8.0F;
GL11.glTranslatef(f15, 0.0F, 0.0F);
GL11.glRotatef(-50.0F, 0.0F, 0.0F, 1.0F);
ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, f12);
GL11.glPopMatrix();
GL11.glPushMatrix();
GL11.glScalef(f14, f14, f14);
f15 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F * 8.0F;
GL11.glTranslatef(-f15, 0.0F, 0.0F);
GL11.glRotatef(10.0F, 0.0F, 0.0F, 1.0F);
ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, f12);
GL11.glPopMatrix();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDepthFunc(GL11.GL_LEQUAL);
}
}
GL11.glPopMatrix();
}
else
{
for (int l = 0; l < par3; ++l)
{
GL11.glPushMatrix();
if (l > 0)
{
f11 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F;
float f16 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F;
float f17 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F;
GL11.glTranslatef(f11, f16, f17);
}
if (!renderInFrame)
{
GL11.glRotatef(180.0F - this.renderManager.playerViewY, 0.0F, 1.0F, 0.0F);
}
GL11.glColor4f(par5, par6, par7, 1.0F);
tessellator.startDrawingQuads();
tessellator.setNormal(0.0F, 1.0F, 0.0F);
tessellator.addVertexWithUV((double) (0.0F - f9), (double) (0.0F - f10), 0.0D, (double) f4, (double) f7);
tessellator.addVertexWithUV((double) (f8 - f9), (double) (0.0F - f10), 0.0D, (double) f5, (double) f7);
tessellator.addVertexWithUV((double) (f8 - f9), (double) (1.0F - f10), 0.0D, (double) f5, (double) f6);
tessellator.addVertexWithUV((double) (0.0F - f9), (double) (1.0F - f10), 0.0D, (double) f4, (double) f6);
tessellator.draw();
GL11.glPopMatrix();
}
}
}
/**
* Renders the item's icon or block into the UI at the specified position.
*/
public void renderItemIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5)
{
renderItemIntoGUI(par1FontRenderer, par2TextureManager, par3ItemStack, par4, par5, false);
}
public void renderItemIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5, boolean renderEffect)
{
Item k = par3ItemStack.getItem();
int l;
if(k == null)
{
k = Items.iron_pickaxe;
l = 0;
}
else
{
l = par3ItemStack.getItemDamage();
}
Object object = par3ItemStack.getItem() == null ? null : par3ItemStack.getIconIndex();
float f;
int i1;
float f1;
float f2;
Block block = Block.getBlockFromItem(k);
//TODO renderItemIn3d
if (block != null && par3ItemStack.getItemSpriteNumber() == 0 && RenderBlocks.renderItemIn3d(block.getRenderType()))
{
par2TextureManager.bindTexture(TextureMap.locationBlocksTexture);
GL11.glPushMatrix();
GL11.glTranslatef((float) (par4 - 2), (float) (par5 + 3), -3.0F + this.zLevel);
GL11.glScalef(10.0F, 10.0F, 10.0F);
GL11.glTranslatef(1.0F, 0.5F, 1.0F);
GL11.glScalef(1.0F, 1.0F, -1.0F);
GL11.glRotatef(210.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);
i1 = par3ItemStack.getItem().getColorFromItemStack(par3ItemStack, 0);
f = (float) (i1 >> 16 & 255) / 255.0F;
f1 = (float) (i1 >> 8 & 255) / 255.0F;
f2 = (float) (i1 & 255) / 255.0F;
if (this.renderWithColor)
{
GL11.glColor4f(f, f1, f2, 1.0F);
}
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
//TODO FIX THESE
//this.itemRenderBlocks.useInventoryTint = this.renderWithColor;
this.itemRenderBlocks.renderBlockAsItem(block, l, 1.0F);
//TODO FIX THESE
//this.itemRenderBlocks.useInventoryTint = true;
GL11.glPopMatrix();
}
else if (k != null && k.requiresMultipleRenderPasses())
{
GL11.glDisable(GL11.GL_LIGHTING);
for (int j1 = 0; j1 < k.getRenderPasses(l); ++j1)
{
par2TextureManager.bindTexture(par3ItemStack.getItemSpriteNumber() == 0 ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture);
IIcon icon = k.getIcon(par3ItemStack, j1);
int k1 = k.getColorFromItemStack(par3ItemStack, j1);
f1 = (float) (k1 >> 16 & 255) / 255.0F;
f2 = (float) (k1 >> 8 & 255) / 255.0F;
float f3 = (float) (k1 & 255) / 255.0F;
if (this.renderWithColor)
{
GL11.glColor4f(f1, f2, f3, 1.0F);
}
this.renderIcon(par4, par5, icon, 16, 16);
if (par3ItemStack.hasEffect(j1))
{
renderEffect(par2TextureManager, par4, par5);
}
}
GL11.glEnable(GL11.GL_LIGHTING);
}
else
{
GL11.glDisable(GL11.GL_LIGHTING);
ResourceLocation resourcelocation = par2TextureManager.getResourceLocation(par3ItemStack.getItemSpriteNumber());
par2TextureManager.bindTexture(resourcelocation);
if (object == null)
{
object = ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture(resourcelocation)).getAtlasSprite("missingno");
}
i1 = k.getColorFromItemStack(par3ItemStack, 0);
f = (float) (i1 >> 16 & 255) / 255.0F;
f1 = (float) (i1 >> 8 & 255) / 255.0F;
f2 = (float) (i1 & 255) / 255.0F;
if (this.renderWithColor)
{
GL11.glColor4f(f, f1, f2, 1.0F);
}
this.renderIcon(par4, par5, (IIcon) object, 16, 16);
GL11.glEnable(GL11.GL_LIGHTING);
if (par3ItemStack.hasEffect(0))
{
renderEffect(par2TextureManager, par4, par5);
}
}
GL11.glEnable(GL11.GL_CULL_FACE);
}
private void renderEffect (TextureManager manager, int x, int y)
{
GL11.glDepthFunc(GL11.GL_GREATER);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDepthMask(false);
manager.bindTexture(RES_ITEM_GLINT);
this.zLevel -= 50.0F;
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_DST_COLOR);
GL11.glColor4f(0.5F, 0.25F, 0.8F, 1.0F);
this.renderGlint(x * 431278612 + y * 32178161, x - 2, y - 2, 20, 20);
GL11.glDisable(GL11.GL_BLEND);
GL11.glDepthMask(true);
this.zLevel += 50.0F;
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDepthFunc(GL11.GL_LEQUAL);
}
/**
* Render the item's icon or block into the GUI, including the glint effect.
*/
public void renderItemAndEffectIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5)
{
if (par3ItemStack != null)
{
if (!ForgeHooksClient.renderInventoryItem(new RenderBlocks(), par2TextureManager, par3ItemStack, renderWithColor, zLevel, (float) par4, (float) par5))
{
this.renderItemIntoGUI(par1FontRenderer, par2TextureManager, par3ItemStack, par4, par5, true);
}
/* Modders must handle this themselves if they use custom renderers!
if (par3ItemStack.hasEffect())
{
GL11.glDepthFunc(GL11.GL_GREATER);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDepthMask(false);
par2TextureManager.bindTexture(RES_ITEM_GLINT);
this.zLevel -= 50.0F;
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_DST_COLOR);
GL11.glColor4f(0.5F, 0.25F, 0.8F, 1.0F);
this.renderGlint(par4 * 431278612 + par5 * 32178161, par4 - 2, par5 - 2, 20, 20);
GL11.glDisable(GL11.GL_BLEND);
GL11.glDepthMask(true);
this.zLevel += 50.0F;
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDepthFunc(GL11.GL_LEQUAL);
}
*/
}
}
private void renderGlint (int par1, int par2, int par3, int par4, int par5)
{
for (int j1 = 0; j1 < 2; ++j1)
{
if (j1 == 0)
{
GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE);
}
if (j1 == 1)
{
GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE);
}
float f = 0.00390625F;
float f1 = 0.00390625F;
float f2 = (float) (Minecraft.getSystemTime() % (long) (3000 + j1 * 1873)) / (3000.0F + (float) (j1 * 1873)) * 256.0F;
float f3 = 0.0F;
Tessellator tessellator = Tessellator.instance;
float f4 = 4.0F;
if (j1 == 1)
{
f4 = -1.0F;
}
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double) (par2 + 0), (double) (par3 + par5), (double) this.zLevel, (double) ((f2 + (float) par5 * f4) * f), (double) ((f3 + (float) par5) * f1));
tessellator.addVertexWithUV((double) (par2 + par4), (double) (par3 + par5), (double) this.zLevel, (double) ((f2 + (float) par4 + (float) par5 * f4) * f),
(double) ((f3 + (float) par5) * f1));
tessellator.addVertexWithUV((double) (par2 + par4), (double) (par3 + 0), (double) this.zLevel, (double) ((f2 + (float) par4) * f), (double) ((f3 + 0.0F) * f1));
tessellator.addVertexWithUV((double) (par2 + 0), (double) (par3 + 0), (double) this.zLevel, (double) ((f2 + 0.0F) * f), (double) ((f3 + 0.0F) * f1));
tessellator.draw();
}
}
/**
* Renders the item's overlay information. Examples being stack count or damage on top of the item's image at the
* specified position.
*/
public void renderItemOverlayIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5)
{
this.renderItemOverlayIntoGUI(par1FontRenderer, par2TextureManager, par3ItemStack, par4, par5, (String) null);
}
public void renderItemOverlayIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5, String par6Str)
{
if (par3ItemStack != null)
{
if (par3ItemStack.stackSize > 1 || par6Str != null)
{
String s1 = par6Str == null ? String.valueOf(par3ItemStack.stackSize) : par6Str;
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
par1FontRenderer.drawStringWithShadow(s1, par4 + 19 - 2 - par1FontRenderer.getStringWidth(s1), par5 + 6 + 3, 16777215);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
if (par3ItemStack.isItemDamaged())
{
int k = (int) Math.round(13.0D - (double) par3ItemStack.getItemDamageForDisplay() * 13.0D / (double) par3ItemStack.getMaxDamage());
int l = (int) Math.round(255.0D - (double) par3ItemStack.getItemDamageForDisplay() * 255.0D / (double) par3ItemStack.getMaxDamage());
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_TEXTURE_2D);
Tessellator tessellator = Tessellator.instance;
int i1 = 255 - l << 16 | l << 8;
int j1 = (255 - l) / 4 << 16 | 16128;
this.renderQuad(tessellator, par4 + 2, par5 + 13, 13, 2, 0);
this.renderQuad(tessellator, par4 + 2, par5 + 13, 12, 1, j1);
this.renderQuad(tessellator, par4 + 2, par5 + 13, k, 1, i1);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
}
}
/**
* Adds a quad to the tesselator at the specified position with the set width and height and color. Args:
* tessellator, x, y, width, height, color
*/
private void renderQuad (Tessellator par1Tessellator, int par2, int par3, int par4, int par5, int par6)
{
par1Tessellator.startDrawingQuads();
par1Tessellator.setColorOpaque_I(par6);
par1Tessellator.addVertex((double) (par2 + 0), (double) (par3 + 0), 0.0D);
par1Tessellator.addVertex((double) (par2 + 0), (double) (par3 + par5), 0.0D);
par1Tessellator.addVertex((double) (par2 + par4), (double) (par3 + par5), 0.0D);
par1Tessellator.addVertex((double) (par2 + par4), (double) (par3 + 0), 0.0D);
par1Tessellator.draw();
}
public void renderIcon (int par1, int par2, IIcon par3Icon, int par4, int par5)
{
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double) (par1 + 0), (double) (par2 + par5), (double) this.zLevel, (double) par3Icon.getMinU(), (double) par3Icon.getMaxV());
tessellator.addVertexWithUV((double) (par1 + par4), (double) (par2 + par5), (double) this.zLevel, (double) par3Icon.getMaxU(), (double) par3Icon.getMaxV());
tessellator.addVertexWithUV((double) (par1 + par4), (double) (par2 + 0), (double) this.zLevel, (double) par3Icon.getMaxU(), (double) par3Icon.getMinV());
tessellator.addVertexWithUV((double) (par1 + 0), (double) (par2 + 0), (double) this.zLevel, (double) par3Icon.getMinU(), (double) par3Icon.getMinV());
tessellator.draw();
}
protected ResourceLocation getEntityTexture (Entity par1Entity)
{
return this.func_110796_a((EntityItem) par1Entity);
}
/**
* Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
* handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic
* (Render<T extends Entity) and this method has signature public void doRender(T entity, double d, double d1,
* double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
*/
public void doRender (Entity par1Entity, double par2, double par4, double par6, float par8, float par9)
{
this.doRenderItem((EntityItem) par1Entity, par2, par4, par6, par8, par9);
}
/**
* Items should spread out when rendered in 3d?
* @return
*/
public boolean shouldSpreadItems ()
{
return true;
}
/**
* Items should have a bob effect
* @return
*/
public boolean shouldBob ()
{
return true;
}
public byte getMiniBlockCount (ItemStack stack)
{
byte ret = 1;
if (stack.stackSize > 1)
ret = 2;
if (stack.stackSize > 5)
ret = 3;
if (stack.stackSize > 20)
ret = 4;
if (stack.stackSize > 40)
ret = 5;
return ret;
}
/**
* Allows for a subclass to override how many rendered items appear in a
* "mini item 3d stack"
* @param stack
* @return
*/
public byte getMiniItemCount (ItemStack stack)
{
byte ret = 1;
if (stack.stackSize > 1)
ret = 2;
if (stack.stackSize > 15)
ret = 3;
if (stack.stackSize > 31)
ret = 4;
return ret;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,201 @@
package mantle.client.gui;
import mantle.books.BookData;
import mantle.client.MProxyClient;
import mantle.client.RenderItemCopy;
import mantle.client.SmallFontRenderer;
import mantle.client.pages.BookPage;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiManual extends GuiScreen
{
ItemStack itemstackBook;
Document manual;
public RenderItemCopy renderitem = new RenderItemCopy();
int bookImageWidth = 206;
int bookImageHeight = 200;
int bookTotalPages = 1;
int currentPage;
int maxPages;
BookData bData;
private TurnPageButton buttonNextPage;
private TurnPageButton buttonPreviousPage;
private static ResourceLocation bookRight;// = new ResourceLocation("mantle", "textures/gui/bookright.png");
private static ResourceLocation bookLeft;// = new ResourceLocation("mantle", "textures/gui/bookleft.png");
BookPage pageLeft;
BookPage pageRight;
public SmallFontRenderer fonts = MProxyClient.smallFontRenderer;
public GuiManual(ItemStack stack, BookData data)
{
this.mc = Minecraft.getMinecraft();
this.itemstackBook = stack;
currentPage = 0; //Stack page
manual = data.getDoc();
if (data.font != null)
this.fonts = data.font;
bookLeft = data.leftImage;
bookRight = data.rightImage;
this.bData = data;
//renderitem.renderInFrame = true;
}
/*@Override
public void setWorldAndResolution (Minecraft minecraft, int w, int h)
{
this.guiParticles = new GuiParticle(minecraft);
this.mc = minecraft;
this.width = w;
this.height = h;
this.buttonList.clear();
this.initGui();
}*/
@SuppressWarnings("unchecked")
public void initGui ()
{
maxPages = manual.getElementsByTagName("page").getLength();
updateText();
int xPos = (this.width) / 2; //TODO Width?
//TODO buttonList
this.buttonList.add(this.buttonNextPage = new TurnPageButton(1, xPos + bookImageWidth - 50, 180, true, bData));
this.buttonList.add(this.buttonPreviousPage = new TurnPageButton(2, xPos - bookImageWidth + 24, 180, false, bData));
}
protected void actionPerformed (GuiButton button)
{
if (button.enabled)
{
if (button.id == 1)
currentPage += 2;
if (button.id == 2)
currentPage -= 2;
updateText();
}
}
void updateText ()
{
if (maxPages % 2 == 1)
{
if (currentPage > maxPages)
currentPage = maxPages;
}
else
{
if (currentPage >= maxPages)
currentPage = maxPages - 2;
}
if (currentPage % 2 == 1)
currentPage--;
if (currentPage < 0)
currentPage = 0;
NodeList nList = manual.getElementsByTagName("page");
Node node = nList.item(currentPage);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
Class<? extends BookPage> clazz = MProxyClient.getPageClass(element.getAttribute("type"));
if (clazz != null)
{
try
{
pageLeft = clazz.newInstance();
pageLeft.init(this, 0);
pageLeft.readPageFromXML(element);
}
catch (Exception e)
{
}
}
else
{
pageLeft = null;
}
}
node = nList.item(currentPage + 1);
if (node != null && node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
Class<? extends BookPage> clazz = MProxyClient.getPageClass(element.getAttribute("type"));
if (clazz != null)
{
try
{
pageRight = clazz.newInstance();
pageRight.init(this, 1);
pageRight.readPageFromXML(element);
}
catch (Exception e)
{
}
}
else
{
pageLeft = null;
}
}
else
{
pageRight = null;
}
}
public void drawScreen (int par1, int par2, float par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(bookRight);
int localWidth = (this.width / 2);
byte localHeight = 8;
this.drawTexturedModalRect(localWidth, localHeight, 0, 0, this.bookImageWidth, this.bookImageHeight);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(bookLeft);
localWidth = localWidth - this.bookImageWidth;
this.drawTexturedModalRect(localWidth, localHeight, 256 - this.bookImageWidth, 0, this.bookImageWidth, this.bookImageHeight);
super.drawScreen(par1, par2, par3); //16, 12, 220, 12
if (pageLeft != null)
pageLeft.renderBackgroundLayer(localWidth + 16, localHeight + 12);
if (pageRight != null)
pageRight.renderBackgroundLayer(localWidth + 220, localHeight + 12);
if (pageLeft != null)
pageLeft.renderContentLayer(localWidth + 16, localHeight + 12, bData.isTranslatable);
if (pageRight != null)
pageRight.renderContentLayer(localWidth + 220, localHeight + 12, bData.isTranslatable);
}
public Minecraft getMC ()
{
return mc;
}
public boolean doesGuiPauseGame ()
{
return false;
}
}
@@ -0,0 +1,56 @@
package mantle.client.gui;
import static mantle.lib.CoreRepo.logger;
import mantle.books.BookData;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class TurnPageButton extends GuiButton
{
/**
* True for pointing right (next page), false for pointing left (previous page).
*/
private final boolean nextPage;
private static ResourceLocation background;// = new ResourceLocation("tinker", "textures/gui/bookleft.png");
public TurnPageButton(int par1, int par2, int par3, boolean par4, BookData data)
{
super(par1, par2, par3, 23, 13, "");
this.nextPage = par4;
background = data.leftImage;
}
/**
* Draws this button to the screen.
*/
public void drawButton (Minecraft par1Minecraft, int par2, int par3)
{
if (this.visible)
{
boolean var4 = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
par1Minecraft.getTextureManager().bindTexture(background);
int var5 = 0;
int var6 = 192;
if (var4)
{
var5 += 23;
}
if (!this.nextPage)
{
var6 += 13;
}
this.drawTexturedModalRect(this.xPosition, this.yPosition, var5, var6, 23, 13);
}
}
}
@@ -0,0 +1,18 @@
package mantle.client.pages;
import org.w3c.dom.Element;
public class BlankPage extends BookPage
{
@Override
public void readPageFromXML (Element element)
{
}
@Override
public void renderContentLayer (int localwidth, int localheight, boolean isTranslatable)
{
}
}
@@ -0,0 +1,25 @@
package mantle.client.pages;
import mantle.client.gui.GuiManual;
import org.w3c.dom.Element;
public abstract class BookPage
{
protected GuiManual manual;
protected int side;
public void init (GuiManual manual, int side)
{
this.manual = manual;
this.side = side;
}
public abstract void readPageFromXML (Element element);
public void renderBackgroundLayer (int localwidth, int localheight)
{
}
public abstract void renderContentLayer (int localwidth, int localheight, boolean isTranslatable);
}
@@ -0,0 +1,64 @@
package mantle.client.pages;
import mantle.lib.client.MantleClientRegistry;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class ContentsTablePage extends BookPage
{
String text;
String[] iconText;
ItemStack[] icons;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("text");
if (nodes != null)
text = nodes.item(0).getTextContent();
nodes = element.getElementsByTagName("link");
iconText = new String[nodes.getLength()];
icons = new ItemStack[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++)
{
NodeList children = nodes.item(i).getChildNodes();
iconText[i] = children.item(1).getTextContent();
icons[i] = MantleClientRegistry.getManualIcon(children.item(3).getTextContent());
}
}
@Override
public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable)
{
if (text != null)
{
if (isTranslatable)
text = StatCollector.translateToLocal(text);
manual.fonts.drawString("\u00a7n" + text, localWidth + 25 + manual.fonts.getStringWidth(text) / 2, localHeight + 4, 0);
}
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
manual.renderitem.zLevel = 100;
for (int i = 0; i < icons.length; i++)
{
manual.renderitem.renderItemIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[i], localWidth + 16, localHeight + 18 * i + 18);
int yOffset = 18;
if (isTranslatable)
iconText[i] = StatCollector.translateToLocal(iconText[i]);
if (iconText[i].length() > 40)
yOffset = 13;
manual.fonts.drawString(iconText[i], localWidth + 38, localHeight + 18 * i + yOffset, 0);
}
manual.renderitem.zLevel = 0;
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
}
}
@@ -0,0 +1,107 @@
package mantle.client.pages;
import mantle.lib.client.MantleClientRegistry;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class CraftingPage extends BookPage
{
String text;
String size;
ItemStack[] icons;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("text");
if (nodes != null)
text = nodes.item(0).getTextContent();
nodes = element.getElementsByTagName("name");
if (nodes != null)
icons = MantleClientRegistry.getRecipeIcons(nodes.item(0).getTextContent());
nodes = element.getElementsByTagName("size");
if (nodes != null)
size = nodes.item(0).getTextContent();
}
@Override
public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable)
{
if (isTranslatable)
text = StatCollector.translateToLocal(text);
if (size.equals("two"))
drawCraftingPage(text, icons, 2, localWidth, localHeight + 12);
if (size.equals("three"))
drawCraftingPage(text, icons, 3, localWidth + (side != 1 ? 6 : 0), localHeight + 12);
}
public void drawCraftingPage (String info, ItemStack[] icons, int recipeSize, int localWidth, int localHeight)
{
if (info != null)
manual.fonts.drawString("\u00a7n" + info, localWidth + 50, localHeight + 4, 0);
GL11.glScalef(2f, 2f, 2f);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
manual.renderitem.zLevel = 100;
if (recipeSize == 2)
{
manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 126) / 2, (localHeight + 68) / 2);
if (icons[0].stackSize > 1)
manual.renderitem.renderItemOverlayIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 126) / 2, (localHeight + 68) / 2, String.valueOf(icons[0].stackSize));
for (int i = 0; i < icons.length - 1; i++)
{
if (icons[i + 1] != null)
manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[i + 1], (localWidth + 14 + 36 * (i % 2)) / 2, (localHeight + 36 * (i / 2) + 52) / 2);
}
}
if (recipeSize == 3)
{
manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 138) / 2, (localHeight + 70) / 2);
if (icons[0].stackSize > 1)
manual.renderitem.renderItemOverlayIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 126) / 2, (localHeight + 68) / 2, String.valueOf(icons[0].stackSize));
for (int i = 0; i < icons.length - 1; i++)
{
if (icons[i + 1] != null)
manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[i + 1], (localWidth - 2 + 36 * (i % 3)) / 2, (localHeight + 36 * (i / 3) + 34) / 2);
}
}
manual.renderitem.zLevel = 0;
GL11.glScalef(0.5F, 0.5F, 0.5F);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
}
public void renderBackgroundLayer (int localwidth, int localheight)
{
if (size.equals("two"))
drawBackground(2, localwidth, localheight + 12);
if (size.equals("three"))
drawBackground(3, localwidth + (side != 1 ? 6 : 0), localheight + 12);
}
private static final ResourceLocation background = new ResourceLocation("mantle", "textures/gui/bookcrafting.png");
public void drawBackground (int size, int localWidth, int localHeight)
{
manual.getMC().getTextureManager().bindTexture(background);
if (size == 2)
manual.drawTexturedModalRect(localWidth + 8, localHeight + 46, 0, 116, 154, 78);
if (size == 3)
manual.drawTexturedModalRect(localWidth - 8, localHeight + 28, 0, 0, 183, 114);
}
}
@@ -0,0 +1,65 @@
package mantle.client.pages;
import mantle.lib.client.MantleClientRegistry;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class FurnacePage extends BookPage
{
String text;
ItemStack[] icons;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("text");
if (nodes != null)
text = nodes.item(0).getTextContent();
nodes = element.getElementsByTagName("recipe");
if (nodes != null)
icons = MantleClientRegistry.getRecipeIcons(nodes.item(0).getTextContent());
}
@Override
public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable)
{
if (text != null)
{
if (isTranslatable)
text = StatCollector.translateToLocal(text);
manual.fonts.drawString("\u00a7n" + text, localWidth + 50, localHeight + 4, 0);
}
GL11.glScalef(2f, 2f, 2f);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
manual.renderitem.zLevel = 100;
manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, MantleClientRegistry.getManualIcon("coal"), (localWidth + 38) / 2, (localHeight + 110) / 2);
manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 106) / 2, (localHeight + 74) / 2);
manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[1], (localWidth + 38) / 2, (localHeight + 38) / 2);
if (icons[0].stackSize > 1)
manual.renderitem.renderItemOverlayIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 106) / 2, (localHeight + 74) / 2, String.valueOf(icons[0].stackSize));
manual.renderitem.zLevel = 0;
GL11.glScalef(0.5F, 0.5F, 0.5F);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
}
private static final ResourceLocation background = new ResourceLocation("mantle", "textures/gui/bookfurnace.png");
public void renderBackgroundLayer (int localWidth, int localHeight)
{
manual.getMC().getTextureManager().bindTexture(background);
manual.drawTexturedModalRect(localWidth + 32, localHeight + 32, 0, 0, 111, 114);
}
}
@@ -0,0 +1,63 @@
package mantle.client.pages;
import mantle.lib.client.MantleClientRegistry;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import static mantle.lib.CoreRepo.logger;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class PicturePage extends BookPage
{
String text;
String location;
ResourceLocation background;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("text");
if (nodes != null)
text = nodes.item(0).getTextContent();
nodes = element.getElementsByTagName("location");
if (nodes != null)
{
location = nodes.item(0).getTextContent();
background = new ResourceLocation(location);
if(background == null)
{
logger.warn(nodes.item(0).getTextContent() + " could not be found in the image cache(location)!");
}
}
//this borked stuffs somehow unless someone is interested in using it this stays disabled for now
/* nodes = element.getElementsByTagName("bookImage");
if (nodes != null)
{
//TODO 1.7 null check all of this
background = MantleClientRegistry.imageCache.get(nodes.item(0).getTextContent()).resource;
if(background == null){
logger.warn(nodes.item(0).getTextContent() + " could not be found in the image cache(bookimage)!");
}
}*/
}
@Override
public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable)
{
if (isTranslatable)
text = StatCollector.translateToLocal(text);
manual.fonts.drawSplitString(text, localWidth + 8, localHeight, 178, 0);
}
public void renderBackgroundLayer (int localWidth, int localHeight)
{
if (background != null)
{
manual.getMC().getTextureManager().bindTexture(background);
}
//manual.getMC().renderEngine.bindTexture(location);
manual.drawTexturedModalRect(localWidth, localHeight + 12, 0, 0, 170, 144);
}
}
@@ -0,0 +1,36 @@
package mantle.client.pages;
import net.minecraft.util.StatCollector;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class SectionPage extends BookPage
{
String title;
String body;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("title");
if (nodes != null)
title = nodes.item(0).getTextContent();
nodes = element.getElementsByTagName("text");
if (nodes != null)
body = nodes.item(0).getTextContent();
}
@Override
public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable)
{
if (isTranslatable)
{
title = StatCollector.translateToLocal(title);
body = StatCollector.translateToLocal(body);
}
manual.fonts.drawSplitString("\u00a7n" + title, localWidth + 70, localHeight + 4, 178, 0);
manual.fonts.drawSplitString(body, localWidth, localHeight + 16, 190, 0);
}
}
@@ -0,0 +1,65 @@
package mantle.client.pages;
import mantle.lib.client.MantleClientRegistry;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class SidebarPage extends BookPage
{
String text;
String[] iconText;
ItemStack[] icons;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("text");
if (nodes != null)
text = nodes.item(0).getTextContent();
nodes = element.getElementsByTagName("item");
iconText = new String[nodes.getLength()];
icons = new ItemStack[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++)
{
NodeList children = nodes.item(i).getChildNodes();
iconText[i] = children.item(1).getTextContent();
icons[i] = MantleClientRegistry.getManualIcon(children.item(3).getTextContent());
}
}
@Override
public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable)
{
if (isTranslatable)
{
text = StatCollector.translateToLocal(text);
}
manual.fonts.drawSplitString(text, localWidth, localHeight, 178, 0);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
manual.renderitem.zLevel = 100;
int offset = text.length() / 4 + 10;
for (int i = 0; i < icons.length; i++)
{
if (isTranslatable)
{
iconText[i] = StatCollector.translateToLocal(iconText[i]);
}
manual.renderitem.renderItemIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[i], localWidth + 8, localHeight + 18 * i + offset);
int yOffset = 39;
if (iconText[i].length() > 40)
yOffset = 34;
manual.fonts.drawSplitString(iconText[i], localWidth + 30, localHeight + 18 * i + offset, 140, 0);
}
manual.renderitem.zLevel = 0;
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
}
}
@@ -0,0 +1,27 @@
package mantle.client.pages;
import net.minecraft.util.StatCollector;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class TextPage extends BookPage
{
String text;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("text");
if (nodes != null)
text = nodes.item(0).getTextContent();
}
@Override
public void renderContentLayer (int localWidth, int localHeight, boolean IsTranslatable)
{
if (IsTranslatable)
text = StatCollector.translateToLocal(text);
manual.fonts.drawSplitString(text, localWidth, localHeight, 178, 0);
}
}
@@ -0,0 +1,27 @@
package mantle.client.pages;
import net.minecraft.util.StatCollector;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class TitlePage extends BookPage
{
String text;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("text");
if (nodes != null)
text = nodes.item(0).getTextContent();
}
@Override
public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable)
{
if (isTranslatable)
text = StatCollector.translateToLocal(text);
manual.fonts.drawSplitString(text, localWidth, localHeight, 178, 0);
}
}
@@ -0,0 +1,28 @@
package mantle.common;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class ComparisonHelper
{
public static boolean areEquivalent (Item item, Block block)
{
return item == Item.getItemFromBlock(block);
}
public static boolean areEquivalent (Block block1, Block block2)
{
return block1 == block2;
}
public static boolean areEquivalent (Item item1, Item item2)
{
return item1.equals(item2);
}
public static boolean areEquivalent (ItemStack is1, ItemStack is2)
{
return is1.getItem() == is2.getItem();
}
}
+46
View File
@@ -0,0 +1,46 @@
package mantle.common;
import static mantle.lib.CoreRepo.logger;
import mantle.lib.CoreConfig;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.potion.Potion;
import net.minecraft.world.biome.BiomeGenBase;
public class IDDumps
{
public static void dump(){
if (CoreConfig.dumpBiomeIDs)
{
for (BiomeGenBase b : BiomeGenBase.getBiomeGenArray())
{
if (b != null && b.biomeName != null)
{
logger.info("Biome ID & Name: " + b.biomeID + " " + b.biomeName);
}
}
}
if (CoreConfig.dumpPotionIDs)
{
for (Potion p : Potion.potionTypes)
{
if (p != null && p.getName() != null)
{
logger.info("Potion ID & name: " + p.getId() + " " + p.getName());
}
}
}
if (CoreConfig.dumpEnchantIDs)
{
for (Enchantment e : Enchantment.enchantmentsList)
{
if (e != null && e.getName() != null)
{
logger.info("Enchantment ID & name: " + e.effectId + " " + e.getName());
}
}
}
}
}
@@ -0,0 +1,32 @@
package mantle.common;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.IGuiHandler;
public class MProxyCommon implements IGuiHandler
{
public static int manualGuiID = -1;
@Override
public Object getServerGuiElement (int ID, EntityPlayer player, World world, int x, int y, int z)
{
if (ID < 0)
return null;
return null;
}
@Override
public Object getClientGuiElement (int ID, EntityPlayer player, World world, int x, int y, int z)
{
return null;
}
public void registerRenderer ()
{
}
public void readManuals ()
{
}
}
@@ -0,0 +1,57 @@
package mantle.common.network;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
/**
* AbstractPacket class. Should be the parent of all packets wishing to use the
* PacketPipeline.
*
* @author sirgingalot
*/
public abstract class AbstractPacket
{
/**
* Encode the packet data into the ByteBuf stream. Complex data sets may
* need specific data handlers (See
* @link{cpw.mods.fml.common.network.ByteBuffUtils})
*
* @param ctx
* channel context
* @param buffer
* the buffer to encode into
*/
public abstract void encodeInto (ChannelHandlerContext ctx, ByteBuf buffer);
/**
* Decode the packet data from the ByteBuf stream. Complex data sets may
* need specific data handlers (See
* @link{cpw.mods.fml.common.network.ByteBuffUtils})
*
* @param ctx
* channel context
* @param buffer
* the buffer to decode from
*/
public abstract void decodeInto (ChannelHandlerContext ctx, ByteBuf buffer);
/**
* Handle a packet on the client side. Note this occurs after decoding has
* completed.
*
* @param player
* the player reference
*/
public abstract void handleClientSide (EntityPlayer player);
/**
* Handle a packet on the server side. Note this occurs after decoding has
* completed.
*
* @param player
* the player reference
*/
public abstract void handleServerSide (EntityPlayer player);
}
@@ -0,0 +1,78 @@
package mantle.common.network;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tileentity.TileEntity;
public class PacketUpdateTE extends AbstractPacket
{
private int x, y, z;
private NBTTagCompound data;
public PacketUpdateTE()
{
}
public PacketUpdateTE(int x, int y, int z, NBTTagCompound data)
{
this.x = x;
this.y = y;
this.z = z;
this.data = data;
}
@Override
public void encodeInto (ChannelHandlerContext ctx, ByteBuf buffer)
{
PacketBuffer pbuff = new PacketBuffer(buffer);
pbuff.writeInt(x);
pbuff.writeShort(y);
pbuff.writeInt(z);
try
{
pbuff.writeNBTTagCompoundToBuffer(data);
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void decodeInto (ChannelHandlerContext ctx, ByteBuf buffer)
{
PacketBuffer pbuff = new PacketBuffer(buffer);
x = pbuff.readInt();
y = pbuff.readShort();
z = pbuff.readInt();
try
{
data = pbuff.readNBTTagCompoundFromBuffer();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void handleClientSide (EntityPlayer player)
{
TileEntity te = player.worldObj.getTileEntity(x, y, z);
if (te != null)
{
te.readFromNBT(data);
}
}
@Override
public void handleServerSide (EntityPlayer player)
{
}
}
@@ -0,0 +1,32 @@
package mantle.crash;
import cpw.mods.fml.common.ICrashCallable;
/**
* Crash Callable for supported environments.
*
* @author Sunstrike <[email protected]>
*/
public class CallableSuppConfig implements ICrashCallable
{
private String modId;
public CallableSuppConfig(String modId)
{
this.modId = modId;
}
@Override
public String call () throws Exception
{
return "Environment healthy.";
}
@Override
public String getLabel ()
{
return modId + " Environment";
}
}
@@ -0,0 +1,40 @@
package mantle.crash;
import java.util.List;
import cpw.mods.fml.common.ICrashCallable;
// Crash handler for when an unsupported mod is running alongside us
public class CallableUnsuppConfig implements ICrashCallable
{
private String modId;
private List<String> modIds;
public CallableUnsuppConfig(String modId, List<String> modIds)
{
this.modId = modId;
this.modIds = modIds;
}
@Override
public String getLabel ()
{
return modId + " Environment";
}
@Override
public String call () throws Exception
{
String str = "DO NOT REPORT THIS CRASH! Unsupported mods in environment: ";
Boolean firstEntry = true;
for (String id : modIds)
{
str = str + (firstEntry ? id : ", " + id);
firstEntry = false;
}
return str;
}
}
+25
View File
@@ -0,0 +1,25 @@
package mantle.debug;
import net.minecraft.entity.player.EntityPlayer;
/**
* Encapsulation for debug information
*
* @author Sunstrike <[email protected]>
*/
public class DebugData
{
public final EntityPlayer player;
@SuppressWarnings("rawtypes") public final Class cl;
public final String[] strings;
@SuppressWarnings("rawtypes")
public DebugData(EntityPlayer player, Class cl, String[] strings)
{
this.player = player;
this.cl = cl;
this.strings = strings;
}
}
@@ -0,0 +1,50 @@
package mantle.debug;
import static mantle.lib.CoreConfig.debug_enableChat;
import static mantle.lib.CoreConfig.debug_enableConsole;
import static mantle.lib.CoreRepo.logger;
import mantle.player.PlayerUtils;
import net.minecraft.entity.player.EntityPlayer;
/**
* IDebuggable helper
*
* @author Sunstrike <[email protected]>
*/
public class DebugHelper
{
private DebugHelper()
{
// No instantiation
}
public static void handleDebugData (DebugData data)
{
if (debug_enableChat)
handleChatDebug(data);
if (debug_enableConsole)
handleConsoleDebug(data);
}
private static void handleChatDebug (DebugData data)
{
EntityPlayer player = data.player;
String prefix = "[" + data.cl.getSimpleName() + "] ";
for (String str : data.strings)
{
PlayerUtils.sendChatMessage(player, prefix + str);
}
}
private static void handleConsoleDebug (DebugData data)
{
String player = data.player.getGameProfile().getName();
String prefix = "[" + player + ":" + data.cl.getSimpleName() + "] ";
for (String str : data.strings)
{
logger.info(prefix + str);
}
}
}
@@ -0,0 +1,17 @@
package mantle.debug;
import net.minecraft.entity.player.EntityPlayer;
/**
* Interface for TEs which can be whacked with debug tools (sticks normally) for information.
*
* This is automatically used if the block containing the TE is a subclass of MantleBlock.
*
* @author Sunstrike <[email protected]>
*/
public interface IDebuggable
{
public DebugData getDebugInfo (EntityPlayer player);
}
@@ -0,0 +1,28 @@
package mantle.event;
import cpw.mods.fml.common.eventhandler.Event;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public abstract class ManualOpenEvent extends Event {
public ItemStack bookStack;
public EntityPlayer player;
public ManualOpenEvent(ItemStack book, EntityPlayer player) {
this.bookStack = book;
this.player = player;
}
public static class Pre extends ManualOpenEvent {
public Pre(ItemStack book, EntityPlayer player) {
super(book, player);
}
}
public static class Post extends ManualOpenEvent {
public Post(ItemStack book, EntityPlayer player) {
super(book, player);
}
}
}
+88
View File
@@ -0,0 +1,88 @@
package mantle.event;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.event.FMLMissingMappingsEvent;
import cpw.mods.fml.common.event.FMLMissingMappingsEvent.MissingMapping;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import static mantle.lib.CoreRepo.logger;
import java.util.List;
import java.util.Map;
public abstract class Migration
{
Map<String, Item> remapItem = Maps.newHashMap();
Map<String, Block> remapBlock = Maps.newHashMap();
List<String> ignore = Lists.newArrayList();
private ModContainer mod;
private String modID;
/*
* Store the mod ID so we can convert e.g "item" to "mod:item" later.
*/
public Migration(ModContainer m)
{
mod = m;
modID = m.getModId();
}
/*
* Add a new migration to the internal replacement map e.g. "olditem" -> "newitem" (without ID prefix!).
* Use an encapsulated object of form Map<String,Item> to store this.
* The prefix will be created using the ID given during construction during processing.
*/
public void addMigration (String old, Item newItem)
{
remapItem.put(modID + ":" + old, newItem);
}
/*
* Add a new migration to the internal replacement map e.g. "olditem" -> "newitem" (without ID prefix!).
* Use an encapsulated object of form Map<String,Block> to store this.
* The prefix will be created using the ID given during construction during processing.
*/
public void addMigration (String old, Block newBlock)
{
remapBlock.put(modID + ":" + old, newBlock);
}
/*
* Register an old ID that's been removed entirely. This isn't suitable for renaming operations!
* Store this in a List<String> seperate to the rename mapping.
* @param id ID to be removed (without ID prefix!).
*/
public void addRemoval (String id)
{
ignore.add(modID + ":" + id);
};
/*
* This must be called from your mod's main class as it requires @EventHandler notation
* This works on the assumption the FML event will have a list of string IDs that are missing.
* During this phase, check for old IDs and remap as needed, or destroy ones marked for removal.
*/
public void processMigrationEvent (FMLMissingMappingsEvent event) {
if ((!remapBlock.isEmpty() || !remapItem.isEmpty())) {
event.applyModContainer(mod);
List<MissingMapping> l = event.get();
if(l != null)
{
for (MissingMapping miss : event.get()) {
if (remapItem.containsKey(miss.name))
miss.remap(remapItem.get(miss.name));
else if (remapBlock.containsKey(miss.name))
miss.remap(remapBlock.get(miss.name));
else if (ignore.contains(miss.name))
miss.ignore();
}
}
else
{
logger.error("migration list from FML empty for mod " + modID);
}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
package mantle.items;
import net.minecraft.item.Item;
import cpw.mods.fml.common.registry.GameData;
public class ItemUtils
{
public static String getUniqueName (Item item)
{
return GameData.getItemRegistry().getNameForObject(item);
}
public static Item getItemFromUniqueName (String uniqueName)
{
return GameData.getItemRegistry().getObject(uniqueName);
}
}
+77
View File
@@ -0,0 +1,77 @@
package mantle.items;
import net.minecraftforge.common.MinecraftForge;
import mantle.event.ManualOpenEvent;
import java.util.List;
import mantle.Mantle;
import mantle.books.BookDataStore;
import mantle.items.abstracts.CraftingItem;
import mantle.lib.CoreRepo;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class Manual extends CraftingItem
{
public final String modID;
static String[] name = new String[] { "beginner", "toolstation", "smeltery", "diary" };
static String[] textureName = new String[] { "tinkerbook_diary", "tinkerbook_toolstation", "tinkerbook_smeltery", "tinkerbook_blue" };
public Manual()
{
super(name, textureName, "", "mantle", null);
modID = CoreRepo.modId;
}
public void updateManual ()
{
updateData(new String[] { "test" }, new String[] { "mantlebook_blue" }, "", "mantle");
}
public Manual(String[] name, String[] textureName, String folder, String modTexturePrefix, CreativeTabs tab, String modID)
{
super(name, textureName, "", "mantle", tab);
this.modID = modID;
}
@Override
public ItemStack onItemRightClick (ItemStack stack, World world, EntityPlayer player)
{
ManualOpenEvent.Pre preOpenEvent = new ManualOpenEvent.Pre(stack, player);
MinecraftForge.EVENT_BUS.post(preOpenEvent);
player.openGui(Mantle.instance, mantle.client.MProxyClient.manualGuiID, world, 0, 0, 0);
ManualOpenEvent.Post postOpenEvent = new ManualOpenEvent.Post(stack, player);
MinecraftForge.EVENT_BUS.post(postOpenEvent);
return stack;
}
@Override
@SideOnly(Side.CLIENT)
@SuppressWarnings({"unchecked", "rawtypes"})
public void addInformation (ItemStack stack, EntityPlayer player, List list, boolean par4)
{
list.add("\u00a7o" + StatCollector.translateToLocal(BookDataStore.getBookfromID(stack.getItemDamage()).toolTip));
}
@Override
public String getUnlocalizedName ()
{
return modID + ":" + super.getUnlocalizedName();
}
@Override
public String getUnlocalizedName (ItemStack par1ItemStack)
{
return super.getUnlocalizedName(par1ItemStack);
}
}
@@ -0,0 +1,81 @@
package mantle.items.abstracts;
import java.util.List;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class CraftingItem extends Item
{
public String modTexPrefix;
public String[] textureNames;
public String[] unlocalizedNames;
public String folder;
public IIcon[] icons;
public CraftingItem(String[] names, String[] tex, String folder, String modTexturePrefix, CreativeTabs tab)
{
super();
this.modTexPrefix = modTexturePrefix;
if (tab != null)
{
this.setCreativeTab(tab);
}
this.setMaxDamage(0);
this.setHasSubtypes(true);
this.textureNames = tex;
this.unlocalizedNames = names;
this.folder = folder;
}
public void updateData (String[] names, String[] tex, String folder, String modTexturePrefix)
{
this.modTexPrefix = modTexturePrefix;
this.textureNames = tex;
this.unlocalizedNames = names;
this.folder = folder;
}
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage (int meta)
{
int arr = MathHelper.clamp_int(meta, 0, unlocalizedNames.length);
if(arr >= icons.length)
return icons[0];
return icons[arr];
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons (IIconRegister iconRegister)
{
this.icons = new IIcon[textureNames.length];
for (int i = 0; i < this.icons.length; ++i)
{
if (!(textureNames[i].equals("")))
this.icons[i] = iconRegister.registerIcon(modTexPrefix + ":" + folder + textureNames[i]);
}
}
public String getUnlocalizedName (ItemStack stack)
{
int arr = MathHelper.clamp_int(stack.getItemDamage(), 0, unlocalizedNames.length);
return getUnlocalizedName() + "." + unlocalizedNames[arr];
}
@SuppressWarnings({"unchecked","rawtypes"})
public void getSubItems (Item b, CreativeTabs tab, List list)
{
for (int i = 0; i < unlocalizedNames.length; i++)
if (!(textureNames[i].equals("")))
list.add(new ItemStack(b, 1, i));
}
}
@@ -0,0 +1,6 @@
package mantle.items.iface;
public interface IDebugItem
{
// Will do more later; this is here for now to enable mods to use the debug stick functionality with their own debug items/tools.
}
+104
View File
@@ -0,0 +1,104 @@
package mantle.lib;
import static mantle.lib.CoreRepo.logger;
import static mantle.lib.CoreRepo.modId;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
import mantle.books.external.ZipLoader;
import net.minecraftforge.common.config.Configuration;
/**
* Mantle configuration handler
*
* Stores configuration data for Mantle, and handles save/load.
*
* @author Sunstrike <[email protected]>
*/
public class CoreConfig
{
static Configuration config;
public static File configFolder;
/**
* Loads state from the configuration folder.
*
* @param mainConfigFolder Configuration folder (as a Java File)
*/
public static void loadConfiguration (File mainConfigFolder)
{
logger.info("Loading configuration from disk.");
try
{
configFolder = new File(mainConfigFolder.getCanonicalPath(), "SlimeKnights");
if (!configFolder.exists())
configFolder.mkdirs();
}
catch (IOException e)
{
logger.error("Error getting/creating Mantle configuration directory: " + e.getMessage());
}
config = new Configuration(new File(configFolder, (modId + ".cfg")));
config.load();
silenceEnvChecks = config.get("Environment", "unsupportedLogging", silenceEnvChecks).getBoolean(silenceEnvChecks);
debug_enableConsole = config.get("DebugHelpers", "enableConsole", debug_enableConsole).getBoolean(debug_enableConsole);
debug_enableChat = config.get("DebugHelpers", "enableChat", debug_enableChat).getBoolean(debug_enableChat);
dumpBiomeIDs = config.get("DebugHelpers", "Dump BIOME ID's in log", dumpBiomeIDs).getBoolean(dumpBiomeIDs);
dumpPotionIDs = config.get("DebugHelpers", "Dump POTION ID's in log", dumpPotionIDs).getBoolean(dumpPotionIDs);
dumpEnchantIDs = config.get("DebugHelpers", "Dump ENCHANT ID's in log", dumpEnchantIDs).getBoolean(dumpEnchantIDs);
dumpRecipeConflicts = config.get("DebugHelpers", "Dump Recipe Conflicts in log when server starts",dumpRecipeConflicts).getBoolean(dumpRecipeConflicts);
//check for debugging overrides in system environment
checkSysOverrides();
if(config.hasChanged())
config.save();
logger.info("Configuration load completed.");
}
/**
* Checks for MANTLE_DBGCONSOLE/CHAT config overrides in system environment for compile time testing, and other dev work.
**/
private static void checkSysOverrides ()
{
if (System.getenv("MANTLE_DBGCONSOLE") != null)
{
debug_enableConsole = true;
logger.info("Mantle Console debugging override enabled via system properties.");
}
if (System.getenv("MANTLE_DBGCHAT") != null)
{
debug_enableChat = true;
logger.info("Mantle Chat debugging override enabled via system properties.");
}
}
public static void loadBookLocations ()
{
for (File f : configFolder.listFiles())
{
if(f.isFile() && FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase("zip"))
ZipLoader.loadZip(f);
}
}
// BEGIN CONFIG VARS
// Env Checks
public static boolean silenceEnvChecks = false;
// Debug Helpers
public static boolean debug_enableConsole = false;
public static boolean debug_enableChat = false;
public static boolean dumpBiomeIDs = false;
public static boolean dumpPotionIDs = false;
public static boolean dumpEnchantIDs = false;
public static boolean dumpRecipeConflicts = false;
}
+22
View File
@@ -0,0 +1,22 @@
package mantle.lib;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Mantle object repository
*
* Storage area for objects accessible throughout Mantle, such as loggers
*
* @author Sunstrike <[email protected]>
*/
public final class CoreRepo
{
public static final String modId = "GRADLETOKEN_MODID";
public static final String modName = "GRADLETOKEN_MODNAME";
public static final String modVersion = "GRADLETOKEN_VERSION";
public static final Logger logger = LogManager.getLogger(modName);
}
+30
View File
@@ -0,0 +1,30 @@
package mantle.lib;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class TabTools extends CreativeTabs
{
ItemStack display;
public TabTools(String label)
{
super(label);
}
public void init (ItemStack stack)
{
display = stack;
}
public ItemStack getIconItemStack ()
{
return display;
}
public Item getTabIconItem ()
{
return display.getItem();
}
}
@@ -0,0 +1,67 @@
package mantle.lib.client;
import java.util.HashMap;
import java.util.Map;
import com.google.common.collect.Maps;
import mantle.books.client.BookImage;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
public class MantleClientRegistry
{
public static Map<String, ItemStack> manualIcons = Maps.newHashMap();
public static Map<String, ItemStack[]> recipeIcons = Maps.newHashMap();
public static HashMap<String, BookImage> imageCache = Maps.newHashMap();
public static ItemStack defaultStack = new ItemStack(Items.iron_ingot);
public static BookImage getBookImageFromCache (String s)
{
return imageCache.get(s);
}
public static void registerManualIcon (String name, ItemStack stack)
{
manualIcons.put(name, stack);
}
public static ItemStack getManualIcon (String textContent)
{
ItemStack stack = manualIcons.get(textContent);
if (stack != null)
return stack;
return defaultStack;
}
public static void registerManualSmallRecipe (String name, ItemStack output, ItemStack... stacks)
{
ItemStack[] recipe = new ItemStack[5];
recipe[0] = output;
System.arraycopy(stacks, 0, recipe, 1, 4);
recipeIcons.put(name, recipe);
}
public static void registerManualLargeRecipe (String name, ItemStack output, ItemStack... stacks)
{
ItemStack[] recipe = new ItemStack[10];
recipe[0] = output;
System.arraycopy(stacks, 0, recipe, 1, 9);
recipeIcons.put(name, recipe);
}
public static void registerManualFurnaceRecipe (String name, ItemStack output, ItemStack input)
{
ItemStack[] recipe = new ItemStack[2];
recipe[0] = output;
recipe[1] = input;
recipeIcons.put(name, recipe);
}
public static ItemStack[] getRecipeIcons (String recipeName)
{
return recipeIcons.get(recipeName);
}
}
@@ -0,0 +1,79 @@
package mantle.lib.environment;
import static mantle.lib.CoreRepo.logger;
import static mantle.lib.CoreRepo.modId;
import java.util.ArrayList;
import java.util.List;
import mantle.crash.CallableSuppConfig;
import mantle.crash.CallableUnsuppConfig;
import mantle.lib.CoreConfig;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ICrashCallable;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.relauncher.Side;
/**
* Environment Checks
*
* Checks the runtime environment is safe for use. If not, registers warnings and adds a suitable crash callable.
*
* @author Sunstrike <[email protected]>
*/
public class EnvironmentChecks
{
private EnvironmentChecks()
{
} // Singleton
// Usable by other mods to detect Optifine.
public static boolean hasOptifine = false;
/**
* Checks for conflicting stuff in environment; adds callable to any crash logs if so.
* Note: This code adds additional data to crashlogs. It does not trigger any crashes.
*/
@SuppressWarnings("rawtypes")
public static void verifyEnvironmentSanity ()
{
List<String> modIds = new ArrayList<String>();
if (FMLCommonHandler.instance().getSide() == Side.CLIENT && FMLClientHandler.instance().hasOptifine() || Loader.isModLoaded("optifine"))
{
if (!CoreConfig.silenceEnvChecks)
logger.error("[Environment Checks] Optifine detected. This may cause issues due to base edits or ASM usage.");
hasOptifine = true;
modIds.add("optifine");
}
try
{
Class cl = Class.forName("org.bukkit.Bukkit");
if (cl != null)
{
if (!CoreConfig.silenceEnvChecks)
logger.error("[Environment Checks] Bukkit implementation detected. This may cause issues. Bukkit implementations include Craftbukkit and Cauldron(MCPC+).");
modIds.add("bukkit");
}
}
catch (Exception ex)
{
// No Bukkit in environment.
}
if (modIds.size() == 0)
{
ICrashCallable callable = new CallableSuppConfig(modId);
FMLCommonHandler.instance().registerCrashCallable(callable);
}
else
{
ICrashCallable callable = new CallableUnsuppConfig(modId, modIds);
FMLCommonHandler.instance().registerCrashCallable(callable);
}
}
}
+85
View File
@@ -0,0 +1,85 @@
package mantle.math;
/**
* Dozenal Converter
*
* Converts decimals into dozenal.
*
* @author mDiyo
*/
import java.util.LinkedList;
public class Dozenal
{
@SuppressWarnings("unused")
public static String convertToDozenal (byte i)
{
return convertDecimal(i);
}
@SuppressWarnings("unused")
public static String convertToDozenal (short i)
{
return convertDecimal(i);
}
@SuppressWarnings("unused")
public static String convertToDozenal (int i)
{
return convertDecimal(i);
}
public static String convertDecimal (int i)
{
int num = i;
LinkedList<Character> list = new LinkedList<Character>();
while (num > 0)
{
list.add(getDozenalCharacter(num % 12));
num /= 12;
}
StringBuilder builder = new StringBuilder();
for (int iter = list.size() - 1; iter > 0; iter--)
{
builder.append(list.get(iter));
}
return builder.toString();
}
public static char getDozenalCharacter (int i)
{
assert i < 12 : "Base 10 number should be less than 12";
switch (i)
{
case 0:
return '0'; //Zero
case 1:
return '1'; //One
case 2:
return '2'; //Two
case 3:
return '3'; //Three
case 4:
return '4'; //Four
case 5:
return '5'; //Five
case 6:
return '6'; //Six
case 7:
return '7'; //Seven
case 8:
return '8'; //Eight
case 9:
return '9'; //Nine
case 10:
return 'X'; //Dec
case 11:
return 'E'; //El
}
return 'Q';
}
}
@@ -0,0 +1,26 @@
package mantle.module;
/**
* Interface for modules for dealing with other mods.
*
* Note that all ILoadableModule's should have a static String field "modId" which contains the mod ID of the mod it supports.
* This is accessed by reflection because Java is dumb and has no statics in interfaces.
*
* @author Arkan <[email protected]>
*/
@Deprecated //See Pulsar package for replacement
public interface ILoadableModule {
// Example modId field
//public static String modId = "ExampleMod";
// Called during PreInit
public abstract void preInit();
// Called during Init
public abstract void init();
// Called during PostInit
public abstract void postInit();
}
@@ -0,0 +1,180 @@
package mantle.module;
import cpw.mods.fml.common.Loader;
import net.minecraftforge.common.config.Configuration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.util.ArrayList;
/**
* Controller for mod compat modules.
*
* @author Sunstrike <[email protected]>
* @author Arkan Emberwalker <[email protected]>
*/
@Deprecated //See PulseManager for replacement
public class ModuleController {
private enum State {
WAITING, PREINIT, INIT, POSTINIT, DONE
}
private ArrayList<ILoadableModule> modules = new ArrayList<ILoadableModule>();
private State currentState = State.WAITING;
private Logger logger;
private Configuration config;
/**
* Constructor for a config-less plugin loader
*
* @param modName The human-readable name of the invoking mod. Used for logger construction.
*/
@SuppressWarnings("unused")
public ModuleController(String modName) {
this.logger = LogManager.getLogger(modName + "-ModuleController");
this.config = null;
}
/**
* Constructor for a config-using plugin loader
*
* @param confName The name for the configuration file (should end in .cfg)
* @param modName The human-readable name of the invoking mod. Used for logger construction.
*/
public ModuleController(String confName, String modName) {
this.logger = LogManager.getLogger(modName + "-ModuleController");
this.config = new Configuration(new File(Loader.instance().getConfigDir().toString() + File.separator + confName));
}
/**
* The host mod should invoke this when it receives the FML PreInitialization event.
*/
public void preInit() {
currentState = State.PREINIT;
for (ILoadableModule m : modules) m.preInit();
}
/**
* The host mod should invoke this when it receives the FML Initialization event.
*/
public void init() {
currentState = State.INIT;
for (ILoadableModule m : modules) m.init();
}
/**
* The host mod should invoke this when it receives the FML PostInitialization event.
*/
public void postInit() {
currentState = State.POSTINIT;
for (ILoadableModule m : modules) m.postInit();
currentState = State.DONE;
}
/**
* Main registration point for modules.
*
* This version will always check the configuration, if one is defined, before attempting to load a plugin. This is
* the preferred entry point. To bypass the config test, use registerUncheckedModule().
*
* @param mod The module to attempt to register.
* @return True on success, false on error or rejection.
*/
@SuppressWarnings("unused")
public boolean registerModule(Class<? extends ILoadableModule> mod) {
String mID = getModId(mod);
if (mID == null) return false;
boolean allowedByConf = true;
if (config != null) {
config.load();
allowedByConf = config.get("Modules", mID, true).getBoolean(true);
config.save();
}
if (!allowedByConf || !Loader.isModLoaded(mID)) return false;
return doSetup(mod, mID);
}
/**
* Unchecked handler for registering a module forcefully.
*
* This version bypasses any config test; use registerModule where possible. This is only intended for modules
* the user is not allowed to configure (e.g. Mystcraft blacklist plugins).
*
* @param mod The module to attempt to register.
* @return True on success, false on error.
*/
@SuppressWarnings("unused")
public boolean registerUncheckedModule(Class<? extends ILoadableModule> mod) {
String mID = getModId(mod);
if (mID == null || !Loader.isModLoaded(mID)) return false;
return doSetup(mod, mID);
}
private String getModId(Class<? extends ILoadableModule> mod) {
String mID;
try {
mID = (String)mod.getField("modId").get(null);
} catch (Exception e) {
logger.error("Module loading failed for class " + mod + "; modId field may be missing.");
return null;
} catch (NoClassDefFoundError ncdf) { // NOTE: Catching Errors is usually bad practice, but we need to here.
logger.error("Module loading failed for class " + mod + "; a referenced class is missing.");
return null;
}
return mID;
}
/**
* Internal handler which actually does the heavy lifting with loading.
*
* @param mod Module class to setup
* @return True on success, else false.
*/
private boolean doSetup(Class<? extends ILoadableModule> mod, String mID) {
ILoadableModule module;
try {
module = mod.newInstance();
modules.add(module);
} catch (Exception e) {
logger.error("Could not construct module for " + mID);
logger.error(e.getMessage());
logger.error(e.getStackTrace());
return false;
}
logger.info("Module for " + mID + " loaded successfully.");
boolean caughtUp = false;
switch (currentState) {
case DONE:
case POSTINIT:
module.preInit();
module.init();
module.postInit();
caughtUp = true;
break;
case INIT:
module.preInit();
module.init();
caughtUp = true;
break;
case PREINIT:
module.preInit();
caughtUp = true;
break;
default:
break;
}
if (caughtUp) logger.info("Completed catch-up for " + mID + " module.");
return true;
}
}
@@ -0,0 +1,23 @@
package mantle.player;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentText;
/**
* Misc utils for dealing with players.
*
* @author progwml6
*/
public class PlayerUtils
{
/**
* Sends a given message to a specific player (due to 1.7 axing addChatMessage())
*/
public static void sendChatMessage (EntityPlayer p, String message)
{
if (p != null && message != null && !message.isEmpty())
p.addChatComponentMessage(new ChatComponentText(message));
}
}
@@ -0,0 +1,49 @@
package mantle.pulsar.config;
import cpw.mods.fml.common.Loader;
import mantle.pulsar.pulse.PulseMeta;
import net.minecraftforge.common.config.Configuration;
import java.io.*;
/**
* Mantle specific pulsar addon class to support using the forge CFG format for configurations
* @author progwml6
*/
public class ForgeCFG implements IConfiguration{
private static Configuration config;
private final String confPath;
private final String description;
/**
* Creates a new Configuration object.
*
* Do NOT make this the same as the overall mod configuration; it will clobber it!
*
* @param confName The config file name (without path or .cfg suffix)
* @param description The description for the group that the config entries will be placed in.
*/
public ForgeCFG(String confName, String description) {
this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".cfg";
this.description = description;
}
@Override
public void load() {
config = new Configuration(new File(confPath));
config.load();
}
@Override
public boolean isModuleEnabled(PulseMeta meta) {
return config.get(description, meta.getId(), meta.isEnabled(), meta.getDescription()).getBoolean(meta.isEnabled());
}
@Override
public void flush() {
if(config.hasChanged())
config.save();
}
}
@@ -0,0 +1,30 @@
package mantle.pulsar.config;
import mantle.pulsar.pulse.PulseMeta;
/**
* Interface for config handlers.
*
* @author Arkan <[email protected]>
*/
public interface IConfiguration {
/**
* Perform any configuration loading required.
*/
public void load();
/**
* Gets whether the given module is enabled in the config.
*
* @param meta The pulse metadata.
* @return Whether the module is enabled.
*/
public boolean isModuleEnabled(PulseMeta meta);
/**
* Flush configuration to disk/database/whatever.
*/
public void flush();
}
@@ -0,0 +1,266 @@
package mantle.pulsar.control;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import mantle.pulsar.config.IConfiguration;
import mantle.pulsar.internal.Configuration;
import mantle.pulsar.pulse.PulseMeta;
import mantle.pulsar.internal.logging.ILogger;
import mantle.pulsar.internal.logging.LogManager;
import mantle.pulsar.pulse.Handler;
import mantle.pulsar.pulse.IPulse;
import mantle.pulsar.pulse.Pulse;
import mantle.pulsar.pulse.PulseProxy;
/**
* Manager class for a given mods Pulses.
*
* Each Pulsar-enabled mod should create one and only one of these to manage its Pulses.
*
* @author Arkan <[email protected]>
*/
@SuppressWarnings({"unused", "deprecated"})
public class PulseManager {
private final ILogger log;
private final boolean useConfig;
private final LinkedHashMap<Object, PulseMeta> pulses = new LinkedHashMap<Object, PulseMeta>();
private boolean blockNewRegistrations = false;
private boolean configLoaded = false;
private IConfiguration conf;
/**
* Configuration-less constructor.
*
* PulseManagers created this way ignore configurability on child Pulses. This is not recommended.
*
* @param modId The parents ModID.
*/
@Deprecated
public PulseManager(String modId) {
log = LogManager.getLogger("PulseManager-" + modId);
useConfig = false;
conf = null;
}
/**
* Configuration-using constructor.
*
* This form creates a PulseManager that supports configuration of Pulses by file. Recommended approach.
*
* @param modId The parents ModID.
* @param configName The config file name.
*/
public PulseManager(String modId, String configName) {
log = LogManager.getLogger("PulseManager-" + modId);
useConfig = true;
conf = new Configuration(configName, log);
}
/**
* Custom configuration-using constructor.
*
* Don't like JSON? Heathen. Lets you handle configuration, to whatever media you like - File, database, death star.
* Whatever really. See {@link mantle.pulsar.config.IConfiguration}.
*
* @param modId The parents ModID.
* @param config Configuration handler.
*/
public PulseManager(String modId, IConfiguration config) {
log = LogManager.getLogger("PulseManager-" + modId);
useConfig = true;
conf = config;
}
/**
* Register a new Pulse with the manager.
*
* This CANNOT be done after preInit() has been invoked.
*
* @param pulse The Pulse to register.
*/
public void registerPulse(Object pulse) {
if (blockNewRegistrations) throw new RuntimeException("A mod tried to register a plugin after preinit! Pulse: "
+ pulse);
if (!configLoaded) {
conf.load();
configLoaded = true;
}
String id, description, deps;
boolean forced, enabled, missingDeps = false;
try {
Pulse p = pulse.getClass().getAnnotation(Pulse.class);
id = p.id();
description = p.description();
deps = p.modsRequired();
forced = p.forced();
enabled = p.defaultEnable();
} catch (NullPointerException ex) {
throw new RuntimeException("Could not parse @Pulse annotation for Pulse: " + pulse);
}
// Work around Java not allowing default-null fields.
if (description.equals("")) description = null;
if (!deps.equals("")) {
String[] parsedDeps = deps.split(";");
for (String s : parsedDeps) {
if (!Loader.isModLoaded(s)) {
log.info("Skipping Pulse " + id + "; missing dependency: " + s);
missingDeps = true;
enabled = false;
break;
}
}
}
PulseMeta meta = new PulseMeta(id, description, forced, enabled);
meta.setEnabled(!missingDeps && getEnabledFromConfig(meta));
if (meta.isEnabled()) {
parseAndAddProxies(pulse);
pulses.put(pulse, meta);
}
}
private boolean getEnabledFromConfig(PulseMeta meta) {
if (meta.isForced() || !useConfig) return true; // Forced or no config set.
return conf.isModuleEnabled(meta);
}
/**
* @deprecated FML handles proxies now.
*
* @param pulse Pulse to parse for proxy annotations.
*/
@Deprecated
private void parseAndAddProxies(Object pulse) {
try {
for (Field f : pulse.getClass().getDeclaredFields()) {
log.debug("Parsing field: " + f);
PulseProxy p = f.getAnnotation(PulseProxy.class);
if (p != null) { // Support for deprecated PulseProxy annotation
log.warn("Pulse " + pulse + " used the deprecated PulseProxy annotation. As of Pulsar 0.1.0, it's now preferred to use FML's SidedProxy annotation.");
log.warn("The old PulseProxy parsing will be removed in the next breaking update (Pulsar 1.x).");
setProxyField(pulse, f, p.clientSide(), p.serverSide());
}
}
} catch (Exception ex) {
throw new RuntimeException("Pulse annotation parsing failed for Pulse " + pulse + "; " + ex);
}
}
@Deprecated
private void setProxyField(Object pulse, Field f, String client, String server) throws Exception {
boolean accessible = f.isAccessible();
f.setAccessible(true);
switch (FMLCommonHandler.instance().getSide()) {
case CLIENT:
f.set(pulse, Class.forName(client).newInstance());
break;
default:
f.set(pulse, Class.forName(server).newInstance());
}
f.setAccessible(accessible);
}
public void preInit(FMLPreInitializationEvent evt) {
if (!blockNewRegistrations) conf.flush(); // First preInit call, so flush config
blockNewRegistrations = true;
for (Map.Entry<Object, PulseMeta> e : pulses.entrySet()) {
if(hasRequiredPulses(e)) {
log.debug("Preinitialising Pulse " + e.getValue().getId() + "...");
if (e.getKey() instanceof IPulse) { // Deprecated IPulse handling
IPulse ip = (IPulse)e.getKey();
ip.preInit(evt);
} else findAndInvokeHandlers(e.getKey(), evt);
}
}
}
public void init(FMLInitializationEvent evt) {
for (Map.Entry<Object, PulseMeta> e : pulses.entrySet()) {
log.debug("Initialising Pulse " + e.getValue().getId() + "...");
if (e.getKey() instanceof IPulse) { // Deprecated IPulse handling
IPulse ip = (IPulse)e.getKey();
ip.init(evt);
log.warn("Pulse " + e.getValue().getId() + " is using the deprecated IPulse interface.");
log.warn("This will be removed in the next major version (Pulsar 1.x) - Please switch to @Handler!");
} else findAndInvokeHandlers(e.getKey(), evt);
}
}
public void postInit(FMLPostInitializationEvent evt) {
for (Map.Entry<Object, PulseMeta> e : pulses.entrySet()) {
log.debug("Postinitialising Pulse " + e.getValue().getId() + "...");
if (e.getKey() instanceof IPulse) { // Deprecated IPulse handling
IPulse ip = (IPulse)e.getKey();
ip.postInit(evt);
} else findAndInvokeHandlers(e.getKey(), evt);
}
}
/**
* Parse an object for a matching handler for the given object.
*
* @param pulse Object to inspect for Handlers
* @param evt The event object
*/
@SuppressWarnings("unchecked")
private void findAndInvokeHandlers(Object pulse, Object evt) {
for (Method m : pulse.getClass().getDeclaredMethods()) {
try {
if (m.getAnnotation(Handler.class) == null) continue; // Ignore non-@Handler methods
Class[] pTypes = m.getParameterTypes();
if (pTypes.length != 1) continue;
Class pt = pTypes[0];
if (pt.isAssignableFrom(evt.getClass())) {
m.invoke(pulse, evt);
}
} catch (Exception ex) {
log.warn("Caught exception in findAndInvokeHandlers: " + ex);
ex.printStackTrace();
}
}
}
private boolean hasRequiredPulses(Map.Entry<Object, PulseMeta> entry) {
String deps = entry.getKey().getClass().getAnnotation(Pulse.class).pulsesRequired();
if (!deps.equals("")) {
String[] parsedDeps = deps.split(";");
for (String s : parsedDeps) {
if (!isPulseLoaded(s)) {
log.info("Skipping Pulse " + entry.getValue().getId() + "; missing pulse: " + s);
return false;
}
}
}
return true;
}
public boolean isPulseLoaded(String pulseId) {
for(Map.Entry<Object, PulseMeta> entry : pulses.entrySet()) {
if(entry.getValue().getId().equals(pulseId)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,202 @@
package mantle.pulsar.internal;
import java.io.*;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import cpw.mods.fml.common.Loader;
import mantle.pulsar.config.IConfiguration;
import mantle.pulsar.internal.logging.ILogger;
import mantle.pulsar.pulse.PulseMeta;
/**
* Default Gson Configuration helper.
*
* @author Arkan <[email protected]>
*/
public class Configuration implements IConfiguration {
private static final int CONFIG_LEVEL = 1;
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private final String confPath;
private final ILogger logger;
private Map<String, ConfigEntry> modules;
/**
* Creates a new Configuration object.
*
* Do NOT make this the same as the overall mod configuration; it will clobber it!
*
* @param confName The config file name (without path or .json suffix)
* @param logger The logger to send debug info to.
*/
public Configuration(String confName, ILogger logger) {
this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".json";
this.logger = logger;
}
@Override
public void load() {
getModulesFromJson();
}
@Override
public boolean isModuleEnabled(PulseMeta meta) {
ConfigEntry entry = modules.get(meta.getId());
if (entry == null) {
modules.put(meta.getId(), new ConfigEntry(meta.isEnabled(), meta.getDescription()));
return meta.isEnabled();
} else {
return entry.getEnabled();
}
}
@Override
public void flush() {
writeModulesToJson();
}
private void getModulesFromJson() {
// Step 1: Does the file exist?
File f = new File(confPath);
if (!f.exists()) {
logger.info("Couldn't find config file; will generate a new one later.");
modules = new HashMap<String, ConfigEntry>();
return;
}
// Step 2: File exists. Let's make sure it's usable.
if (!(f.canRead() && f.canWrite())) {
throw new FileNotReadWritableException("Could not read/write Pulsar config: " + confPath);
}
// Step 3: Good enough. Read it.
try {
try {
modules = parseV1Config(f);
} catch (Exception ex) {
logger.warn("Failed to parse " + f.getName() + " using the v1 parser; trying the v0 parser.");
Map<String, ConfigEntry> conf = parseV0Config(f);
logger.info("Found valid v0 configuration. Upgrading it.");
modules = conf;
writeModulesToJson();
logger.info("Upgrade complete! Config is now in v1 format.");
}
} catch (Exception ex) {
logger.warn("Invalid config file. Discarding.");
ex.printStackTrace();
modules = new HashMap<String, ConfigEntry>();
}
}
private Map<String, ConfigEntry> parseV0Config(File f) throws Exception {
try {
JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f)));
Map<String, Boolean> m = gson.fromJson(reader, new TypeToken<HashMap<String, Boolean>>(){}.getType()); // NASTY!
if (m == null) {
throw new NullPointerException("Gson returned null.");
}
Map<String, ConfigEntry> out = new HashMap<String, ConfigEntry>();
for (Map.Entry<String, Boolean> e : m.entrySet()) {
out.put(e.getKey(), new ConfigEntry(e.getValue()));
}
return out;
} catch (FileNotFoundException fnfe) {
throw new RuntimeException("This shouldn't be possible... " + fnfe);
}
}
private Map<String, ConfigEntry> parseV1Config(File f) throws Exception {
try {
JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f)));
GsonConfig c = gson.fromJson(reader, GsonConfig.class);
if (c.getConfigVersion() > 1) throw new RuntimeException("Pulsar config is from a newer version! Remove it! " + f.getAbsolutePath());
if (c.getModules() == null) throw new IllegalArgumentException("Not a valid GsonConfig. Try v0 parsing.");
return c.getModules();
} catch (FileNotFoundException fnfe) {
throw new RuntimeException("This shouldn't be possible... " + fnfe);
}
}
private void writeModulesToJson() {
try {
JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(new File(confPath))));
writer.setIndent(" ");
GsonConfig out = new GsonConfig(CONFIG_LEVEL, modules);
gson.toJson(out, GsonConfig.class, writer);
writer.close();
} catch (Exception ex) {
logger.warn("Could not write config? " + confPath);
}
}
/**
* Internal exception for an unreadable/unwritable config.
*/
private static class FileNotReadWritableException extends RuntimeException {
public FileNotReadWritableException(String message) {
super(message);
}
}
/**
* Internal data holder, for use in the map and JSON.
*/
private static class ConfigEntry {
private Boolean enabled;
private String description = null;
public ConfigEntry(Boolean enabled) {
this.enabled = enabled;
}
public ConfigEntry(Boolean enabled, String description) {
this(enabled);
this.description = description;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String getDescription() {
return description;
}
}
/**
* Internal representation of a version 1+ config file.
*/
private static class GsonConfig {
private int CONFIG_VERSION = 0;
private Map<String, ConfigEntry> modules;
public GsonConfig(int version, Map<String, ConfigEntry> modules) {
this.CONFIG_VERSION = version;
this.modules = modules;
}
public int getConfigVersion() {
return CONFIG_VERSION;
}
public Map<String, ConfigEntry> getModules() {
return modules;
}
}
}
@@ -0,0 +1,23 @@
package mantle.pulsar.internal.logging;
/**
* Interface for log wrappers.
*
* @author Arkan <[email protected]>
*/
@SuppressWarnings("unused")
public interface ILogger {
public void fatal(String msg);
public void severe(String msg);
public void warn(String msg);
public void info(String msg);
public void debug(String msg);
public void trace(String msg);
}
@@ -0,0 +1,48 @@
package mantle.pulsar.internal.logging;
import java.util.logging.Logger;
/**
* Java logger wrapper.
*
* @author Arkan <[email protected]>
*/
public class JULLogger implements ILogger {
private final Logger log;
public JULLogger(String name) {
log = Logger.getLogger(name);
}
@Override
public void fatal(String msg) {
log.severe(msg); // JUL doesn't -have- fatal...
}
@Override
public void severe(String msg) {
log.severe(msg);
}
@Override
public void warn(String msg) {
log.warning(msg);
}
@Override
public void info(String msg) {
log.info(msg);
}
@Override
public void debug(String msg) {
log.fine(msg); // Good enough.
}
@Override
public void trace(String msg) {
log.finest(msg); // Closest we'll get.
}
}
@@ -0,0 +1,48 @@
package mantle.pulsar.internal.logging;
import org.apache.logging.log4j.Logger;
/**
* Log4j log wrapper.
*
* @author Arkan <[email protected]>
*/
public class Log4jLogger implements ILogger {
private final Logger log;
public Log4jLogger(String name) {
log = org.apache.logging.log4j.LogManager.getLogger(name);
}
@Override
public void fatal(String msg) {
log.fatal(msg);
}
@Override
public void severe(String msg) {
log.error(msg);
}
@Override
public void warn(String msg) {
log.warn(msg);
}
@Override
public void info(String msg) {
log.info(msg);
}
@Override
public void debug(String msg) {
log.debug(msg);
}
@Override
public void trace(String msg) {
log.trace(msg);
}
}
@@ -0,0 +1,39 @@
package mantle.pulsar.internal.logging;
/**
* Static class for getting generic loggers.
*
* @author Arkan <[email protected]>
*/
public class LogManager {
private LogManager() {} // Singleton.
private static final boolean useLog4j2;
/*
* Detect the presence of log4j2.
*
* If it's present, we can assume we should be using the damn thing.
*/
static {
boolean l4j = false;
try {
Class cl = Class.forName("org.apache.logging.log4j.LogManager");
if (cl == null) throw new ClassNotFoundException("This should never happen...");
l4j = true;
} catch (ClassNotFoundException cnfe) {
// Ignore
}
useLog4j2 = l4j;
}
public static ILogger getLogger(String name) {
if (useLog4j2) {
return new Log4jLogger(name);
} else {
return new JULLogger(name);
}
}
}
@@ -0,0 +1,36 @@
/**
* Project Pulsar
*
* This is a repackaged copy of the Pulsar project, an open source library for internal module loading.
* The upstream repository is at https://github.com/Emberwalker/Pulsar
*
* This code package is licensed under the MIT License, as below.
*
* -----
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Arkan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* -----
*
* @author Arkan <[email protected]>
*/
package mantle.pulsar;
@@ -0,0 +1,14 @@
package mantle.pulsar.pulse;
import java.lang.annotation.*;
/**
* Annotates methods to be used for event handling.
*
* @author Arkan <[email protected]>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Handler
{}
@@ -0,0 +1,38 @@
package mantle.pulsar.pulse;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
/**
* Base interface for all Pulsar modules ("pulses").
*
* @deprecated Use the new {@link Handler} annotation.
*
* @author Arkan <[email protected]>
*/
@Deprecated
public interface IPulse {
/**
* FML preinit from the parent mod.
*
* @param evt The FML event inherited from this Pulses parent.
*/
public void preInit(FMLPreInitializationEvent evt);
/**
* FML init from the parent mod.
*
* @param evt The FML event inherited from this Pulses parent.
*/
public void init(FMLInitializationEvent evt);
/**
* FML postinit from the parent mod.
*
* @param evt The FML event inherited from this Pulses parent.
*/
public void postInit(FMLPostInitializationEvent evt);
}
@@ -0,0 +1,45 @@
package mantle.pulsar.pulse;
import java.lang.annotation.*;
/**
* Metadata annotation for IPulse implementations.
*
* @author Arkan <[email protected]>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface Pulse {
/**
* @return This Pulses UID - Much like FML mods have mod IDs.
*/
public String id();
/**
* @return This Pulses description, human-readable for config files. Can be blank.
*/
public String description() default "";
/**
* @return Dependant mod IDs, seperated by ; as in FML. Skips checks when undefined.
*/
public String modsRequired() default "";
/**
* @return Dependeant Pulse IDs, seperated by ; . Skips checks when undefined.
*/
public String pulsesRequired() default "";
/**
* @return Whether this Pulse is mandatory or not (true -> mandatory).
*/
public boolean forced() default false;
/**
* @return Whether a configurable Pulse should be enabled by default. Ignored where forced = true.
*/
public boolean defaultEnable() default true;
}
@@ -0,0 +1,39 @@
package mantle.pulsar.pulse;
/**
* Metadata wrapper for parsed @Pulse metadata.
*
* @author Arkan <[email protected]>
*/
public class PulseMeta {
private String id, description;
private boolean forced, enabled;
public PulseMeta(String id, String description, boolean forced, boolean enabled) {
this.id = id;
this.description = description;
this.forced = forced;
this.enabled = enabled;
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
public boolean isForced() {
return forced;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
@@ -0,0 +1,28 @@
package mantle.pulsar.pulse;
import java.lang.annotation.*;
/**
* Annotation to denote a field that should be populated by a side-specific proxy.
*
* @deprecated Use FML's @SidedProxy instead.
*
* @author Arkan <[email protected]>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@Documented
@Deprecated
public @interface PulseProxy {
/**
* @return The FQCN of the client proxy.
*/
public String clientSide();
/**
* @return The FQCN of the server proxy.
*/
public String serverSide();
}
@@ -0,0 +1,329 @@
package mantle.utils;
import static mantle.lib.CoreRepo.logger;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import cpw.mods.fml.common.registry.GameRegistry;
import mantle.lib.CoreConfig;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraft.item.crafting.ShapelessRecipes;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class CraftingHandler {
private static boolean ia1NG;
public static void logConflicts () {
//GameRegistry.addShapelessRecipe(new ItemStack(Items.diamond_hoe), Blocks.planks, Items.stick, Items.chainmail_boots);
//GameRegistry.addShapelessRecipe(new ItemStack(Items.apple), Blocks.planks, Items.stick, Items.chainmail_boots);
if (CoreConfig.dumpRecipeConflicts) {
for (Map.Entry<IRecipe, List<IRecipe>> me : getPotentialConflicts().entrySet()) {
String s = "";
for (IRecipe i : me.getValue()) {
s += print(i);
}
logger.error("found conflict: \n" + s);
}
}
}
public static Map<IRecipe, List<IRecipe>> getPotentialConflicts () {
logger.info("dumping recipe conflicts to log this can take a while");
Map<IRecipe, List<IRecipe>> conflicts = Maps.newHashMap();
CraftingManager inst = CraftingManager.getInstance();
List<IRecipe> recipes = inst.getRecipeList();
for (IRecipe i : recipes) {
for (int r = 0; r < recipes.size(); r++) {
IRecipe rc = recipes.get(r);
if (i != null && rc != null) {
boolean comp = compare(i, rc);
if (comp && !areItemStacksEqual(i.getRecipeOutput(), rc.getRecipeOutput())) {
if (conflicts.containsKey(i)) {
List<IRecipe> l = conflicts.get(i);
conflicts.remove(i);
if (!l.contains(r)) {
l.add(recipes.get(r));
}
conflicts.put(i, l);
} else if (conflicts.containsKey(rc)) {
List<IRecipe> l = conflicts.get(rc);
conflicts.remove(rc);
if (!l.contains(i)) {
l.add(i);
}
conflicts.put(rc, l);
} else {
List<IRecipe> l = Lists.newArrayList(i, rc);
conflicts.put(i, l);
}
if (ia1NG) {
ia1NG = false;
break;
}
}
}
}
}
return conflicts;
}
private static boolean compare (IRecipe i1, IRecipe i2) {
if (areItemStacksEqual(i1.getRecipeOutput(), i2.getRecipeOutput())) {
return false;
}
boolean is1l = false;
boolean is2l = false;
List<ItemStack> il1 = Lists.newArrayList();
List<ItemStack> il2 = Lists.newArrayList();
ItemStack[] ia1 = null;
boolean invalid = false;
ItemStack[] ia2 = null;
if (i1 instanceof ShapedRecipes) {
ia1 = ((ShapedRecipes) i1).recipeItems.clone();
} else if (i1 instanceof ShapelessRecipes) {
il1 = new ArrayList<ItemStack>(((ShapelessRecipes) i1).recipeItems);
//logger.error("SL Recipe: \n" + print(i1));
is1l = true;
} else if (i1 instanceof ShapedOreRecipe) {
Object[] o = ((ShapedOreRecipe) i1).getInput();
ia1 = new ItemStack[o.length];
for (int in = 0; in < o.length; in++) {
if (o[in] != null && o[in] instanceof ItemStack) {
ia1[in] = (ItemStack) o[in];
} else if (o[in] != null) {
ia1[in] = ((ArrayList<ItemStack>) o[in]).get(0);
} else {
ia1[in] = null;
}
}
} else if (i1 instanceof ShapelessOreRecipe) {
il1 = new ArrayList<ItemStack>();
for (Object o : ((ShapelessOreRecipe) i1).getInput()) {
if (o != null && o instanceof ItemStack) {
ItemStack is = (ItemStack) o;
il1.add(is);
} else if (o != null) {
ItemStack is = ((ArrayList<ItemStack>) o).get(0);
il1.add(is);
} else {
il1.add(null);
}
}
is1l = true;
} else {
ia1NG = true;
invalid = true;
}
if (i2 instanceof ShapedRecipes) {
ia2 = ((ShapedRecipes) i2).recipeItems.clone();
} else if (i2 instanceof ShapelessRecipes) {
il2 = new ArrayList<ItemStack>(((ShapelessRecipes) i2).recipeItems);
is2l = true;
} else if (i2 instanceof ShapedOreRecipe) {
Object[] o = ((ShapedOreRecipe) i2).getInput();
ia2 = new ItemStack[o.length];
for (int in = 0; in < o.length; in++) {
if (o.length == 6) {
print(i2);
}
if (o[in] != null && o[in] instanceof ItemStack) {
ia2[in] = (ItemStack) o[in];
} else if (o[in] != null) {
ItemStack is = ((ArrayList<ItemStack>) o[in]).get(0);
ia2[in] = is;
} else {
ia2[in] = null;
}
}
} else if (i2 instanceof ShapelessOreRecipe) {
il2 = new ArrayList<ItemStack>();
for (Object o : ((ShapelessOreRecipe) i2).getInput()) {
if (o != null && o instanceof ItemStack) {
ItemStack is = (ItemStack) o;
il2.add(is);
} else if (o != null) {
ItemStack is = ((ArrayList<ItemStack>) o).get(0);
il2.add(is);
} else {
il2.add(null);
}
}
is2l = true;
} else {
invalid = true;
}
if (!invalid) {
if (!is1l && !is2l) {
if (ia1 == null) {
logger.error("ia1 null");
}
if (ia2 == null) {
logger.error("ia2 null");
}
if (ia1.length != ia2.length) {
return false;
}
for (int i = 0; i < ia1.length; i++) {
if (ia1[i] != null && ia2[i] != null) {
if (!areItemStacksEqual(ia1[i], ia2[i])) {
return false;
}
} else {
return false;
}
}
} else if (is1l && is2l) {
if (il1.size() == il2.size()) {
boolean has = false;
for (int i = 0; i < il1.size(); i++) {
ItemStack ti1 = il1.get(i);
for (int j = 0; j < il2.size(); j++) {
if (areItemStacksEqual(ti1, il2.get(j))) {
il2.remove(j);
has = true;
break;
}
}
}
if (!has) {
return false;
}
if (il2.size() != 0) {
return false;
}
} else {
return false;
}
} else {
List<ItemStack> stacks = is1l ? il1 : il2;
ItemStack[] stcks = is2l ? ia1 : ia2;
for (ItemStack i : stcks) {
if (!stacks.contains(i)) {
return false;
} else {
stacks.remove(i);
}
}
}
} else {
return false;
}
if (i1 instanceof ShapedOreRecipe && i2 instanceof ShapedOreRecipe) {
int i1w, i2w, i1h, i2h;
try {
Class cl = ShapedOreRecipe.class;
Field w = cl.getDeclaredField("width");
w.setAccessible(true);
Field h = cl.getDeclaredField("height");
h.setAccessible(true);
i1w = (Integer) w.get((ShapedOreRecipe) i1);
i2w = (Integer) w.get((ShapedOreRecipe) i2);
i1h = (Integer) h.get((ShapedOreRecipe) i1);
i2h = (Integer) h.get((ShapedOreRecipe) i2);
if (i1w != i2w || i1h != i2h) {
return false;
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
//logger.error("CONFLICT SET: \n" + print(i1) + print(i2));
return true;
}
private static String print (IRecipe i1) {
String out = "";
if (i1 instanceof ShapedRecipes) {
out += "SHAPED " + toStr(i1.getRecipeOutput()) + "\n";
for (ItemStack i : ((ShapedRecipes) i1).recipeItems) {
if (i != null && i.getItem() != null) {
out += toStr((ItemStack) i) + "\n";
} else {
out += "null \n";
}
}
} else if (i1 instanceof ShapelessRecipes) {
out += "SHAPELESS " + toStr(i1.getRecipeOutput()) + "\n";
for (Object i : ((ShapelessRecipes) i1).recipeItems) {
if ((ItemStack) i != null && ((ItemStack) i).getItem() != null) {
out += toStr((ItemStack) i) + "\n";
} else {
out += "null \n";
}
}
} else if (i1 instanceof ShapedOreRecipe) {
out += "SHAPED ORE " + toStr(i1.getRecipeOutput()) + "\n";
Object[] o = ((ShapedOreRecipe) i1).getInput();
ItemStack[] ia1 = new ItemStack[o.length];
for (int in = 0; in < o.length; in++) {
if (o[in] != null && o[in] instanceof ItemStack) {
ia1[in] = (ItemStack) o[in];
} else if (o[in] != null) {
ia1[in] = ((ArrayList<ItemStack>) o[in]).get(0);
} else {
ia1[in] = null;
}
}
for (Object i : ia1) {
if (i != null && ((ItemStack) i).getItem() != null) {
out += toStr((ItemStack) i) + "\n";
} else {
out += "null \n";
}
}
} else if (i1 instanceof ShapelessOreRecipe) {
out += "SHAPELESS ORE " + toStr(i1.getRecipeOutput()) + "\n";
ItemStack i;
for (Object ob : ((ShapelessOreRecipe) i1).getInput()) {
if (ob instanceof ItemStack) {
i = (ItemStack) ob;
} else {
i = ((ArrayList<ItemStack>) ob).get(0);
}
if ((ItemStack) i != null && ((ItemStack) i).getItem() != null) {
out += toStr((ItemStack) i) + "\n";
} else {
out += "null \n";
}
}
}
return out;
}
private static String toStr (ItemStack is) {
return GameRegistry.findUniqueIdentifierFor(((ItemStack) is).getItem()) + " " + ((ItemStack) is).toString();
}
public static boolean areItemStacksEqual (ItemStack a, ItemStack b) {
if ((a == null || b == null) && !(a == null && b == null)) {
return false;
}
if ((a == null && b == null)) {
return true;
}
return a.stackSize != b.stackSize
? false
: (a.getItem() != b.getItem()
? false
: (compdamage(a, b)
? false
: (a.stackTagCompound == null && b.stackTagCompound != null ? false : a.stackTagCompound == null || a.stackTagCompound.equals(b.stackTagCompound))));
}
public static boolean compdamage (ItemStack a, ItemStack b) {
return a.getItemDamage() != b.getItemDamage() || a.getItemDamage() == OreDictionary.WILDCARD_VALUE || b.getItemDamage() == OreDictionary.WILDCARD_VALUE;
}
}
@@ -0,0 +1,40 @@
package mantle.utils;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class ItemMetaWrapper {
public final Item item;
public final Integer meta;
public ItemMetaWrapper(Item item, Integer meta) {
this.item = item;
this.meta = meta;
}
public ItemMetaWrapper(ItemStack stack)
{
this.item = stack.getItem();
this.meta = stack.getItemDamage();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ItemMetaWrapper itemMeta = (ItemMetaWrapper) o;
if (item != null ? !(item == itemMeta.item) : itemMeta.item != null) return false;
if (meta != null ? !meta.equals(itemMeta.meta) : itemMeta.meta != null) return false;
return true;
}
@Override
public int hashCode() {
int result = item != null ? item.hashCode() : 0;
result = 31 * result + (meta != null ? meta.hashCode() : 0);
return result;
}
}
@@ -0,0 +1,30 @@
package mantle.utils;
import net.minecraft.item.ItemStack;
public class ItemStackNBTWrapper {
public final ItemStack stack;
public ItemStackNBTWrapper(ItemStack stack) {
this.stack = stack;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ItemStackNBTWrapper that = (ItemStackNBTWrapper) o;
return ItemStack.areItemStacksEqual(this.stack, that.stack);
}
@Override
public int hashCode() {
int result = stack.getItem() != null ? stack.getItem().hashCode() : 0;
result = 31 * result + stack.getItemDamage();
result = 31 * result + (stack.getTagCompound() != null ? stack.getTagCompound().hashCode() : 0);
result = 31 * result + stack.stackSize;
return result;
}
}
@@ -0,0 +1,38 @@
package mantle.utils;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class ItemStackWrapper extends ItemMetaWrapper {
public final Integer stacksize;
public ItemStackWrapper(Item item, Integer meta, Integer stacksize) {
super(item, meta);
this.stacksize = stacksize;
}
public ItemStackWrapper(ItemStack stack, Integer stacksize) {
super(stack);
this.stacksize = stacksize;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
ItemStackWrapper that = (ItemStackWrapper) o;
if (stacksize != null ? !stacksize.equals(that.stacksize) : that.stacksize != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (stacksize != null ? stacksize.hashCode() : 0);
return result;
}
}
@@ -0,0 +1,107 @@
package mantle.utils;
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.smelting().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,94 @@
package mantle.world;
import java.io.Serializable;
import mantle.world.CoordTuple;
import net.minecraft.world.chunk.Chunk;
/**
* Standardized implementation for representing and manipulating Chunk Coordinates. Provides standard Java Collection interaction.
* From COFH LIB(modified to use mantle's coordtuple instead)
* @author King Lemming
*
*/
public final class ChunkCoord implements Comparable<ChunkCoord>, Serializable
{
public int chunkX;
public int chunkZ;
public ChunkCoord(Chunk chunk)
{
this.chunkX = chunk.xPosition;
this.chunkZ = chunk.zPosition;
}
public ChunkCoord(CoordTuple c)
{
this(c.x >> 4, c.z >> 4);
}
public ChunkCoord(int x, int z)
{
this.chunkX = x;
this.chunkZ = z;
}
public int getCenterX ()
{
return (this.chunkX << 4) + 8;
}
public int getCenterZ ()
{
return (this.chunkZ << 4) + 8;
}
public ChunkCoord copy ()
{
return new ChunkCoord(chunkX, chunkZ);
}
@Override
public boolean equals (Object obj)
{
if (!(obj instanceof ChunkCoord))
{
return false;
}
ChunkCoord other = (ChunkCoord) obj;
return this.chunkX == other.chunkX && this.chunkZ == other.chunkZ;
}
@Override
public int hashCode ()
{
int hash = chunkX;
hash *= 31 + this.chunkZ;
return hash;
}
@Override
public String toString ()
{
return "[" + this.chunkX + ", " + this.chunkZ + "]";
}
/* Comparable */
@Override
public int compareTo (ChunkCoord other)
{
return this.chunkX == other.chunkX ? this.chunkZ - other.chunkZ : this.chunkX - other.chunkX;
}
}
+175
View File
@@ -0,0 +1,175 @@
package mantle.world;
/**
* CoordTuple
*
* @author mDiyo
*/
@SuppressWarnings("rawtypes")
public class CoordTuple implements Comparable
{
public final int x;
public final int y;
public final int z;
public CoordTuple(double posX, double posY, double posZ)
{
x = (int) Math.floor(posX);
y = (int) Math.floor(posY);
z = (int) Math.floor(posZ);
}
public boolean equalCoords (int posX, int posY, int posZ)
{
if (this.x == posX && this.y == posY && this.z == posZ)
return true;
else
return false;
}
public boolean equals (Object obj) {
if (!(obj instanceof CoordTuple)) {
return false;
}
CoordTuple that = (CoordTuple)obj;
return this.x == that.x && this.y == that.y && this.z == that.z;
}
@Override
public int hashCode ()
{
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
result = prime * result + z;
return result;
}
public String toString ()
{
return "X: " + x + ", Y: " + y + ", Z: " + z;
}
@Override
public int compareTo (Object o)
{
if (o == null)
throw new NullPointerException("Object cannot be null");
CoordTuple coord = (CoordTuple) o;
if (x < coord.x)
{
return -1;
}
if (x > coord.x)
{
return 1;
}
if (y < coord.y)
{
return -1;
}
if (y > coord.y)
{
return 1;
}
if (z < coord.z)
{
return -1;
}
if (z > coord.z)
{
return 1;
}
return 0;
}
public static CoordTuple up (int x, int y, int z)
{
return new CoordTuple(x, y + 1, z);
}
public static CoordTuple down (int x, int y, int z)
{
return new CoordTuple(x, y - 1, z);
}
public static CoordTuple north (int x, int y, int z)
{
return new CoordTuple(x, y, z - 1);
}
public static CoordTuple south (int x, int y, int z)
{
return new CoordTuple(x, y, z + 1);
}
public static CoordTuple east (int x, int y, int z)
{
return new CoordTuple(x + 1, y, z);
}
public static CoordTuple west (int x, int y, int z)
{
return new CoordTuple(x - 1, y, z);
}
public static CoordTuple inFront (int x, int y, int z, int meta)
{
switch (meta)
{
case 0:
return down(x, y, z);
case 1:
return up(x, y, z);
case 2:
return north(x, y, z);
case 3:
return south(x, y, z);
case 4:
return west(x, y, z);
case 5:
return east(x, y, z);
default:
return new CoordTuple(x, y, z);
}
}
public static CoordTuple behind (int x, int y, int z, int meta)
{
switch (meta)
{
case 1:
return down(x, y, z);
case 0:
return up(x, y, z);
case 3:
return north(x, y, z);
case 2:
return south(x, y, z);
case 5:
return west(x, y, z);
case 4:
return east(x, y, z);
default:
return new CoordTuple(x, y, z);
}
}
public int getDistanceFrom (CoordTuple tuple)
{
return getDistanceFrom(tuple.x, tuple.y, tuple.z);
}
public int getDistanceFrom (int x1, int y1, int z1)
{
int xPos = x - x1;
int yPos = y - y1;
int zPos = z - z1;
return xPos * xPos + yPos * yPos + zPos * zPos;
}
}
@@ -0,0 +1,24 @@
package mantle.world;
/**
* CoordTuplePair
*
* @author mDiyo
*/
public class CoordTuplePair
{
public CoordTuple a;
public CoordTuple b;
public CoordTuplePair(CoordTuple a, CoordTuple b)
{
this.a = a;
this.b = b;
}
public CoordTuplePair(int aX, int aY, int aZ, int bX, int bY, int bZ)
{
this.a = new CoordTuple(aX, aY, aZ);
this.b = new CoordTuple(bX, bY, bZ);
}
}
@@ -0,0 +1,31 @@
package mantle.world;
import java.util.Comparator;
/**
* CoordTupleSort
*
* @author mDiyo
*/
@SuppressWarnings("rawtypes")
public class CoordTupleSort implements Comparator
{
@Override
public int compare (Object o1, Object o2)
{
CoordTuple c1 = (CoordTuple) o1;
CoordTuple c2 = (CoordTuple) o2;
//Sort by y, then x, then z
if (c1.y != c2.y)
return c1.y - c2.y;
if (c1.x != c2.x)
return c1.x - c2.x;
if (c1.z != c2.z)
return c1.z - c2.z;
return 0;
}
}
@@ -0,0 +1,59 @@
package mantle.world;
/**
* DimensionCoordPair
*
* @author mDiyo
*/
public class DimensionCoordPair
{
public final int dim;
public final int x;
public final int z;
public DimensionCoordPair(int worldID, int posX, int posZ)
{
dim = worldID;
x = posX;
z = posZ;
}
public boolean equalCoords (int worldID, int posX, int posZ)
{
if (this.dim == posX && this.x == posX && this.z == posZ)
return true;
else
return false;
}
@Override
public boolean equals (Object obj)
{
if (obj == null)
return false;
if (getClass() == obj.getClass())
{
DimensionCoordPair coord = (DimensionCoordPair) obj;
if (this.dim == coord.dim && this.x == coord.x && this.z == coord.z)
return true;
}
return false;
}
@Override
public int hashCode ()
{
final int prime = 37;
int result = 1;
result = prime * result + dim;
result = prime * result + x;
result = prime * result + z;
return result;
}
public String toString ()
{
return "Dim: " + dim + ", X: " + x + ", Z: " + z;
}
}
@@ -0,0 +1,62 @@
package mantle.world;
/**
* DimensionCoordTuple
*
* @author mDiyo
* @author Sunstrike <[email protected]>
*/
public class DimensionCoordTuple
{
public final int dim;
public final int x;
public final int y;
public final int z;
public DimensionCoordTuple(int worldID, int posX, int posY, int posZ)
{
dim = worldID;
y = posY;
x = posX;
z = posZ;
}
public boolean equalCoords (int worldID, int posX, int posY, int posZ)
{
if (this.dim == worldID && this.x == posX && this.y == posY && this.z == posZ)
return true;
else
return false;
}
@Override
public boolean equals (Object obj)
{
if (obj == null)
return false;
if (getClass() == obj.getClass())
{
DimensionCoordTuple coord = (DimensionCoordTuple) obj;
return equalCoords(coord.dim, coord.x, coord.y, coord.z);
}
return false;
}
@Override
public int hashCode ()
{
final int prime = 37;
int result = 1;
result = prime * result + dim;
result = prime * result + x;
result = prime * result + y;
result = prime * result + z;
return result;
}
public String toString ()
{
return "Dim: " + dim + ", X: " + x + ", Y: " + y + ", Z: " + z;
}
}
@@ -0,0 +1,29 @@
package mantle.world;
import net.minecraftforge.common.util.ForgeDirection;
/**
* Helper functions for dealing with ForgeDirection
*
* @author Sunstrike <[email protected]>
*/
@SuppressWarnings("unused")
public class DirectionUtils
{
private DirectionUtils()
{
// No instantiation
}
public static boolean isRightAngles (ForgeDirection a, ForgeDirection b)
{
return a != b && a != b.getOpposite() && a != ForgeDirection.UNKNOWN && b != ForgeDirection.UNKNOWN;
}
public static boolean isHorizontal (ForgeDirection a)
{
return a == ForgeDirection.EAST || a == ForgeDirection.NORTH || a == ForgeDirection.SOUTH || a == ForgeDirection.WEST;
}
}
@@ -0,0 +1,31 @@
package mantle.world;
import mantle.common.ComparisonHelper;
import net.minecraft.init.Blocks;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class WorldHelper
{
@Deprecated
public static boolean setBlockToAirBool (World w, int x, int y, int z)
{
return setBlockToAir(w, x, y, z);
}
public static boolean setBlockToAir (World w, int x, int y, int z)
{
return w.setBlockToAir(x, y, z);
}
public static boolean isAirBlock (IBlockAccess access, int x, int y, int z)
{
return access.getBlock(x,y,z).isAir(access, x,y,z);
}
public static boolean isAirBlock (World access, int x, int y, int z)
{
return access.isAirBlock(x,y,z);
}
}