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

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

No files matched your search

-111
View File
@@ -1,111 +0,0 @@
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 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 net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
/**
* 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();
}
}
@@ -1,31 +0,0 @@
package mantle.blocks;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.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).toString();
}
public static Block getBlockFromUniqueName(String uniqueName)
{
return GameData.getBlockRegistry().getObject(uniqueName);
}
}
@@ -1,45 +0,0 @@
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.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.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, BlockPos pos, 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(pos);
if (te instanceof IDebuggable)
{
DebugHelper.handleDebugData(((IDebuggable) te).getDebugInfo(player));
}
}
super.onBlockClicked(world, pos, player);
}
}
@@ -1,102 +0,0 @@
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;
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 != this.inventorySize || forceAdjust)
{
this.inventorySize = size;
ItemStack[] tempInv = this.inventory;
this.inventory = new ItemStack[size];
int invLength = tempInv.length > this.inventory.length ? this.inventory.length : tempInv.length;
System.arraycopy(tempInv, 0, this.inventory, 0, invLength);
if (tempInv.length > this.inventory.length)
{
for (int i = this.inventory.length; i < tempInv.length; i++)
{
ItemStack stack = tempInv[i];
if (stack != null)
{
float jumpX = this.random.nextFloat() * 0.8F + 0.1F;
float jumpY = this.random.nextFloat() * 0.8F + 0.1F;
float jumpZ = this.random.nextFloat() * 0.8F + 0.1F;
int offsetX = 0;
int offsetY = 0;
int offsetZ = 0;
switch (this.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 = this.random.nextInt(21) + 10;
if (itemSize > stack.stackSize)
{
itemSize = stack.stackSize;
}
stack.stackSize -= itemSize;
EntityItem entityitem = new EntityItem(this.worldObj, (double) ((float) this.pos.getX() + jumpX + offsetX), (double) ((float) this.pos.getY() + jumpY),
(double) ((float) this.pos.getZ() + 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) this.random.nextGaussian() * offset);
entityitem.motionY = (double) ((float) this.random.nextGaussian() * offset + 0.2F);
entityitem.motionZ = (double) ((float) this.random.nextGaussian() * offset);
this.worldObj.spawnEntityInWorld(entityitem);
}
}
}
}
}
}
public int getTossDirection()
{
return this.getRenderDirection();
}
}
@@ -1,242 +0,0 @@
package mantle.blocks.abstracts;
import java.util.ArrayList;
import java.util.Iterator;
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.world.World;
import com.google.common.collect.Lists;
public abstract class ExpandableInventoryLogic extends InventoryLogic implements IInventory
{
public ExpandableInventoryLogic()
{
super(0);
}
protected ArrayList<ItemStack> inventory = Lists.newArrayList();
protected String invName;
@Override
public ItemStack getStackInSlot(int slot)
{
return slot < this.inventory.size() ? this.inventory.get(slot) : null;
}
@Override
public boolean isStackInSlot(int slot)
{
return slot < this.inventory.size() && this.inventory.get(slot) != null;
}
@Override
public int getSizeInventory()
{
return this.inventory.size();
}
public int getMaxSize()
{
return 64;
}
@Override
public int getInventoryStackLimit()
{
return 64;
}
@Override
public boolean canDropInventorySlot(int slot)
{
return true;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack)
{
if (slot < this.inventory.size())
{
this.inventory.set(slot, itemstack);
}
else if (slot == this.inventory.size())
{
this.inventory.add(itemstack);
}
else if (slot < this.getMaxSize())
{
this.inventory.ensureCapacity(slot);
this.inventory.set(slot, itemstack);
}
else
{
return;
}
if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit())
{
itemstack.stackSize = this.getInventoryStackLimit();
}
}
@Override
public ItemStack decrStackSize(int slot, int quantity)
{
if (slot < this.inventory.size() && this.inventory.get(slot) != null)
{
if (this.inventory.get(slot).stackSize <= quantity)
{
ItemStack stack = this.inventory.get(slot);
this.inventory.set(slot, null);
return stack;
}
ItemStack split = this.inventory.get(slot).splitStack(quantity);
if (this.inventory.get(slot).stackSize == 0)
{
this.inventory.set(slot, null);
}
return split;
}
else
{
return null;
}
}
/* Supporting methods */
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
if (this.worldObj.getTileEntity(this.pos) != this)
{
return false;
}
else
{
return entityplayer.getDistance((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, (double) this.pos.getZ() + 0.5D) <= 64D;
}
}
@Override
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);
this.inventory = new ArrayList<ItemStack>();
this.inventory.ensureCapacity(nbttaglist.tagCount() > this.getMaxSize() ? this.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 < this.inventory.size())
{
this.inventory.set(slotID, ItemStack.loadItemStackFromNBT(tagList));
}
}
}
@Override
public void writeToNBT(NBTTagCompound tags)
{
super.writeToNBT(tags);
if (this.invName != null)
{
tags.setString("InvName", this.invName);
}
NBTTagList nbttaglist = new NBTTagList();
for (int iter = 0; iter < this.inventory.size(); iter++)
{
if (this.inventory.get(iter) != null)
{
NBTTagCompound tagList = new NBTTagCompound();
tagList.setByte("Slot", (byte) iter);
this.inventory.get(iter).writeToNBT(tagList);
nbttaglist.appendTag(tagList);
}
}
tags.setTag("Items", nbttaglist);
}
/* Default implementations of hardly used methods */
@Override
public ItemStack getStackInSlotOnClosing(int slot)
{
return null;
}
@Override
public void openChest()
{
}
@Override
public void closeChest()
{
}
@Override
protected abstract String getDefaultName();
@Override
public void setInvName(String name)
{
this.invName = name;
}
@Override
public String getInvName()
{
return this.isInvNameLocalized() ? this.invName : this.getDefaultName();
}
@Override
public boolean isInvNameLocalized()
{
return this.invName != null && this.invName.length() > 0;
}
public void cleanInventory()
{
Iterator<ItemStack> i1 = this.inventory.iterator();
while (i1.hasNext())
{
if (i1.next() == null)
{
i1.remove();
}
}
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack itemstack)
{
if (slot < this.getSizeInventory())
{
if (this.inventory.get(slot) == null || itemstack.stackSize + this.inventory.get(slot).stackSize <= this.getInventoryStackLimit())
{
return true;
}
}
else
{
return slot < this.getMaxSize();
}
return false;
}
}
@@ -1,201 +0,0 @@
package mantle.blocks.abstracts;
import java.util.Random;
import mantle.blocks.iface.IActiveLogic;
import mantle.blocks.iface.IFacingLogic;
import mantle.debug.DebugHelper;
import mantle.debug.IDebuggable;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
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;
}
@Override
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, BlockPos pos, IBlockState state, EntityPlayer player, EnumFacing side, float clickX, float clickY, float clickZ)
{
if (player.isSneaking())
{
return false;
}
Integer integer = this.getGui(world, pos.getX(), pos.getY(), pos.getZ(), player);
if (integer == null || integer == -1)
{
return false;
}
else
{
if (!world.isRemote)
{
player.openGui(this.getModInstance(), integer, world, pos.getX(), pos.getY(), pos.getZ());
}
return true;
}
}
/* Inventory */
@Override
public void breakBlock(World par1World, BlockPos pos, IBlockState meta)
{
TileEntity te = par1World.getTileEntity(pos);
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 = this.rand.nextFloat() * 0.8F + 0.1F;
float jumpY = this.rand.nextFloat() * 0.8F + 0.1F;
float jumpZ = this.rand.nextFloat() * 0.8F + 0.1F;
while (stack.stackSize > 0)
{
int itemSize = this.rand.nextInt(21) + 10;
if (itemSize > stack.stackSize)
{
itemSize = stack.stackSize;
}
stack.stackSize -= itemSize;
EntityItem entityitem = new EntityItem(par1World, (double) ((float) pos.getX() + jumpX), (double) ((float) pos.getY() + jumpY), (double) ((float) pos.getZ() + 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) this.rand.nextGaussian() * offset);
entityitem.motionY = (double) ((float) this.rand.nextGaussian() * offset + 0.2F);
entityitem.motionZ = (double) ((float) this.rand.nextGaussian() * offset);
par1World.spawnEntityInWorld(entityitem);
}
}
}
}
super.breakBlock(par1World, pos, meta);
}
/* Placement */
EnumFacing side;
//This class does not have an actual block placed in the world
@Override
public IBlockState onBlockPlaced(World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
{
this.side = side;
return world.getBlockState(pos).getBlock().getStateFromMeta(meta);
}
@Override
@SuppressWarnings("deprecation")
// TODO: Remove this when setDirection calls updated.
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase entityliving, ItemStack stack)
{
TileEntity logic = world.getTileEntity(pos);
if (logic instanceof IFacingLogic)
{
IFacingLogic direction = (IFacingLogic) logic;
// TODO: Convert all setDirection calls to modern invokation, when that's ready.
if (this.side != null)
{
direction.setDirection(this.side, 0F, 0F, null);
this.side = null;
}
if (entityliving == null)
{
direction.setDirection(null, 0F, 0F, null);
}
else
{
direction.setDirection(null, 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, BlockPos pos)
{
TileEntity logic = world.getTileEntity(pos);
if (logic instanceof IActiveLogic)
{
return ((IActiveLogic) logic).getActive();
}
return false;
}
public int damageDropped(int meta)
{
return meta;
}
/* IDebuggable */
@Override
public void onBlockClicked(World world, BlockPos pos, EntityPlayer player)
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER && player.getHeldItem() != null && player.getHeldItem().getItem() != null && player.getHeldItem().getItem() == Items.stick)
{
TileEntity te = world.getTileEntity(pos);
if (te instanceof IDebuggable)
{
DebugHelper.handleDebugData(((IDebuggable) te).getDebugInfo(player));
}
}
super.onBlockClicked(world, pos, player);
}
}
@@ -1,294 +0,0 @@
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)
{
this.inventory = new ItemStack[invSize];
this.stackSizeLimit = maxStackSize;
}
/* Inventory management */
@Override
public ItemStack getStackInSlot(int slot)
{
return slot < this.inventory.length ? this.inventory[slot] : null;
}
public boolean isStackInSlot(int slot)
{
return slot < this.inventory.length && this.inventory[slot] != null;
}
@Override
public int getSizeInventory()
{
return this.inventory.length;
}
@Override
public int getInventoryStackLimit()
{
return this.stackSizeLimit;
}
public boolean canDropInventorySlot(int slot)
{
return true;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack)
{
this.inventory[slot] = itemstack;
if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit())
{
itemstack.stackSize = this.getInventoryStackLimit();
}
}
@Override
public ItemStack decrStackSize(int slot, int quantity)
{
if (this.inventory[slot] != null)
{
if (this.inventory[slot].stackSize <= quantity)
{
ItemStack stack = this.inventory[slot];
this.inventory[slot] = null;
return stack;
}
ItemStack split = this.inventory[slot].splitStack(quantity);
if (this.inventory[slot].stackSize == 0)
{
this.inventory[slot] = null;
}
return split;
}
else
{
return null;
}
}
/* Supporting methods */
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
if (this.worldObj.getTileEntity(this.pos) != this)
{
return false;
}
else
{
return entityplayer.getDistance((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, (double) this.pos.getZ() + 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.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);
this.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 */
@Override
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 : this.getDefaultName();
}
public boolean hasCustomInventoryName()
{
return this.isInvNameLocalized();
}
public boolean isInvNameLocalized()
{
return this.invName != null && this.invName.length() > 0;
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack itemstack)
{
if (slot < this.getSizeInventory())
{
if (this.inventory[slot] == null || itemstack.stackSize + this.inventory[slot].stackSize <= this.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: " + this.invName + ", inventory.length: " + this.inventory.length + ", stackSizeLimit: " + this.stackSizeLimit;
return new DebugData(player, this.getClass(), strs);
}
}
@@ -1,100 +0,0 @@
package mantle.blocks.abstracts;
import java.util.List;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
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
public boolean isFullCube()
{
return false;
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean shouldSideBeRendered(IBlockAccess world, BlockPos pos, EnumFacing side)
{
if (side.getHorizontalIndex() > 1)
{
return super.shouldSideBeRendered(world, pos, side);
}
IBlockState iblockstate = world.getBlockState(pos);
int meta = iblockstate.getBlock().getMetaFromState(iblockstate);
boolean top = (meta | 8) == 1;
if ((top && side == side.DOWN) || (!top && side == side.UP))
{
return true;
}
return super.shouldSideBeRendered(world, pos, side);
}
@Override
@SuppressWarnings("rawtypes")
public void addCollisionBoxesToList(World world, BlockPos pos, IBlockState state, AxisAlignedBB axisalignedbb, List arraylist, Entity entity)
{
this.setBlockBoundsBasedOnState(world, pos);
super.addCollisionBoxesToList(world, pos, state, axisalignedbb, arraylist, entity);
}
@Override
public void setBlockBoundsForItemRender()
{
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F);
}
public void setBlockBoundsBasedOnState(IBlockAccess world, BlockPos pos, IBlockState state)
{
IBlockState iblockstate = world.getBlockState(pos);
int meta = iblockstate.getBlock().getMetaFromState(iblockstate) / 8;
float minY = meta == 1 ? 0.5F : 0.0F;
float maxY = meta == 1 ? 1.0F : 0.5F;
this.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;
}
@Override
public int damageDropped(int meta)
{
return meta % 8;
}
}
@@ -1,82 +0,0 @@
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)
{
this.specialIndex[0] = clampIndex;
this.specialIndex[1] = stringBuilderIndex;
}
@Override
public int getMetadata(int meta)
{
return meta;
}
@Override
public String getUnlocalizedName(ItemStack itemstack)
{
int pos = MathHelper.clamp_int(itemstack.getItemDamage(), 0, (this.specialIndex[0] > -1) ? this.specialIndex[0] : (this.blockType.length - 1));
int sbIndex = (this.specialIndex[1] > -1) ? pos : (this.specialIndex[1] - pos);
if (sbIndex < 0)
{
sbIndex = -1 * sbIndex;
}
try
{
return (new StringBuilder()).append(this.unlocalizedName).append(".").append(this.blockType[sbIndex - 1]).append(this.append).toString();
}
catch (ArrayIndexOutOfBoundsException ex)
{
logger.warn("[MultiItemBlock] Caught array index error in getUnlocalizedName: " + ex.getMessage());
logger.warn("[MultiItemBlock] Returning unlocalized name: " + this.getUnlocalizedName());
return this.getUnlocalizedName();
}
}
}
@@ -1,13 +0,0 @@
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);
}
@@ -1,33 +0,0 @@
package mantle.blocks.iface;
import java.util.Collections;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.world.IBlockAccess;
public interface ICrop
{
public enum HarvestType
{
BREAK, USE, MACHINE
}
public static final List<ItemStack> NO_YIELD = Collections.emptyList();
/**
*
* @param world
* @param pos
* @param type
* @return A list of items harvested. If no items are returned, NO_YIELD should be passed.
*/
public List<ItemStack> harvestCrop(IBlockAccess world, BlockPos pos, HarvestType type);
public boolean isFullyGrown(IBlockAccess world, BlockPos pos);
public boolean hasYield(IBlockAccess world, BlockPos pos);
public void growthTick(IBlockAccess world, BlockPos pos);
}
@@ -1,20 +0,0 @@
package mantle.blocks.iface;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.EnumFacing;
/**
* Logic for blocks which have a specific direction facing.
*
* @author mDiyo
*/
public interface IFacingLogic
{
public byte getRenderDirection();
public EnumFacing getForgeDirection();
public void setDirection(EnumFacing facing, float yaw, float pitch, EntityLivingBase player);
}
@@ -1,8 +0,0 @@
package mantle.blocks.util;
import net.minecraft.item.ItemStack;
public interface IBlockWithVariants
{
String getVariantNameFromStack(ItemStack stack);
}
@@ -1,33 +0,0 @@
package mantle.blocks.util;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class ItemBlockVariants extends ItemBlock
{
private final IBlockWithVariants blockWithVariants;
public ItemBlockVariants(Block block)
{
super(block);
this.blockWithVariants = (IBlockWithVariants) block;
this.setMaxDamage(0);
this.setHasSubtypes(true);
}
@Override
public int getMetadata(int damage)
{
return damage;
}
@Override
public String getUnlocalizedName(ItemStack stack)
{
return super.getUnlocalizedName() + "." + this.blockWithVariants.getVariantNameFromStack(stack);
}
}
@@ -1,36 +0,0 @@
package mantle.blocks.util.blockstates;
public class BlockVariant implements Comparable<BlockVariant>
{
private int meta;
private String name;
public BlockVariant(int meta, String name)
{
this.meta = meta;
this.name = name;
}
public int getMeta()
{
return this.meta;
}
public String getName()
{
return this.name;
}
@Override
public int compareTo(BlockVariant variant)
{
return this.meta;
}
@Override
public String toString()
{
return this.getName();
}
}
@@ -1,65 +0,0 @@
package mantle.blocks.util.blockstates;
import net.minecraft.block.properties.IProperty;
import java.util.Collection;
import java.util.HashMap;
public class PropertyVariant implements IProperty
{
private String name;
private BlockVariant defaultVariant;
private HashMap<Integer, BlockVariant> metaMap;
protected PropertyVariant(String name, BlockVariant... variants)
{
this.name = name;
this.metaMap = new HashMap<Integer, BlockVariant>();
this.defaultVariant = variants[0];
for (BlockVariant variant : variants)
{
this.metaMap.put(variant.getMeta(), variant);
}
}
public static PropertyVariant create(String name, BlockVariant... variants)
{
return new PropertyVariant(name, variants);
}
@Override
public String getName()
{
return this.name;
}
@Override
public Collection<BlockVariant> getAllowedValues()
{
return this.metaMap.values();
}
@Override
public Class<BlockVariant> getValueClass()
{
return BlockVariant.class;
}
@Override
public String getName(Comparable value)
{
return ((BlockVariant) value).getName();
}
public BlockVariant fromMeta(int meta)
{
BlockVariant variant = this.metaMap.get(meta);
return variant != null ? variant : this.defaultVariant;
}
}
-41
View File
@@ -1,41 +0,0 @@
package mantle.books;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.util.ResourceLocation;
import org.w3c.dom.Document;
public class BookData
{
public String unlocalizedName = "";
public String toolTip = "";
public String modID = "";
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 FontRenderer font;
public Boolean isTranslatable = false;
public boolean isFromZip = false;
public Document getDoc()
{
return this.doc;
}
public String getFullUnlocalizedName()
{
return this.modID + ":" + this.unlocalizedName;
}
}
@@ -1,57 +0,0 @@
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;
}
}
@@ -1,51 +0,0 @@
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;
}
}
}
@@ -1,21 +0,0 @@
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
@@ -1,22 +0,0 @@
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 this.stackSize >= 0 ? this.stackSize : 1;
}
}
-29
View File
@@ -1,29 +0,0 @@
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;
}
-256
View File
@@ -1,256 +0,0 @@
package mantle.books.external;
import static mantle.lib.CoreRepo.logger;
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 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.util.ResourceLocation;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
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;
public class ZipLoader
{
public static Map<String, ItemStack> loadedIS = Maps.newHashMap();
public static BookData loadZip(File f)
{
BookLoad bl;
String flName = "";
String flExt = "";
String lImg = "";
String rImg = "";
String bIcon = "";
String unlocName = "";
String toolTip = "";
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.setTagCompound(JsonToNBT.getTagFromJson(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)
{
return ext.equalsIgnoreCase("png");
}
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;
}
}
@@ -1,101 +0,0 @@
package mantle.client;
import static mantle.lib.CoreRepo.logger;
import java.util.HashMap;
import java.util.Map;
import mantle.Mantle;
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.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class MProxyClient extends MProxyCommon
{
public static final String MINECRAFT_ASCII_PATH = "minecraft:textures/font/ascii.png";
/* Registers any rendering code. */
@Override
public void registerRenderer()
{
ModelHelper.registerItem(Mantle.mantleBook, "mantleBook");
}
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);
}
@Override
public void readManuals()
{
this.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));
}
}
@@ -1,34 +0,0 @@
package mantle.client;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemModelMesher;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class ModelHelper
{
public static void registerItem(Item item, int metadata, String itemName)
{
ItemModelMesher mesher = Minecraft.getMinecraft().getRenderItem().getItemModelMesher();
mesher.register(item, metadata, new ModelResourceLocation(itemName, "inventory"));
}
public static void registerBlock(Block block, int metadata, String blockName)
{
registerItem(Item.getItemFromBlock(block), metadata, blockName);
}
public static void registerBlock(Block block, String blockName)
{
registerBlock(block, 0, blockName);
}
public static void registerItem(Item item, String itemName)
{
registerItem(item, 0, itemName);
}
}
@@ -1,89 +0,0 @@
package mantle.client;
import java.util.ArrayList;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class ModelVariant
{
private String MOD_ID;
private Minecraft mc;
public ModelVariant(String modId, Minecraft mc)
{
this.MOD_ID = modId;
this.mc = mc;
}
public String getResource(String resource)
{
return (MOD_ID + ":") + resource;
}
public void addVariantNames(Block block, String... names)
{
for (int i = 0; i < names.length; i++)
{
names[i] = getResource(names[i]);
}
ModelBakery.addVariantName(Item.getItemFromBlock(block), names);
}
public void addVariantNames(Item item, String... names)
{
for (int i = 0; i < names.length; i++)
{
names[i] = getResource(names[i]);
}
ModelBakery.addVariantName(item, names);
}
public void registerBlockModel(Block block)
{
ResourceLocation resourceLocation = (ResourceLocation) Block.blockRegistry.getNameForObject(block);
registerBlockModel(block, 0, resourceLocation.toString());
}
public void registerItemModel(Item item)
{
ResourceLocation resourceLocation = (ResourceLocation) Item.itemRegistry.getNameForObject(item);
registerItemModel(item, 0, resourceLocation.toString());
}
public void registerBlockModel(Block block, int meta, String modelName)
{
registerItemModel(Item.getItemFromBlock(block), meta, modelName);
}
public void registerItemModel(Item item, int meta, String resourcePath)
{
ModelResourceLocation modelResourceLocation = new ModelResourceLocation(resourcePath, "inventory");
mc.getRenderItem().getItemModelMesher().register(item, meta, modelResourceLocation);
}
public void registerItemSubTypesModel(Item item, CreativeTabs tab)
{
ArrayList<ItemStack> list = new ArrayList<ItemStack>();
item.getSubItems(item, tab, list);
for (ItemStack i : list)
{
this.registerItemModel(item, i.getItemDamage(), item.getUnlocalizedName().substring(5));
}
}
}
@@ -1,238 +0,0 @@
package mantle.client.gui;
import mantle.books.BookData;
import mantle.client.MProxyClient;
import mantle.client.pages.BookPage;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@SideOnly(Side.CLIENT)
public class GuiManual extends GuiScreen
{
ItemStack itemstackBook;
Document manual;
public RenderItem renderitem = Minecraft.getMinecraft().getRenderItem();
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 FontRenderer fonts = Minecraft.getMinecraft().fontRendererObj;
public GuiManual(ItemStack stack, BookData data)
{
this.mc = Minecraft.getMinecraft();
this.itemstackBook = stack;
this.currentPage = 0; //Stack page
this.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();
}*/
@Override
@SuppressWarnings("unchecked")
public void initGui()
{
this.maxPages = this.manual.getElementsByTagName("page").getLength();
this.updateText();
int xPos = (this.width) / 2; //TODO Width?
//TODO buttonList
this.buttonList.add(this.buttonNextPage = new TurnPageButton(1, xPos + this.bookImageWidth - 50, 180, true, this.bData));
this.buttonList.add(this.buttonPreviousPage = new TurnPageButton(2, xPos - this.bookImageWidth + 24, 180, false, this.bData));
}
@Override
protected void actionPerformed(GuiButton button)
{
if (button.enabled)
{
if (button.id == 1)
{
this.currentPage += 2;
}
if (button.id == 2)
{
this.currentPage -= 2;
}
this.updateText();
}
}
void updateText()
{
if (this.maxPages % 2 == 1)
{
if (this.currentPage > this.maxPages)
{
this.currentPage = this.maxPages;
}
}
else
{
if (this.currentPage >= this.maxPages)
{
this.currentPage = this.maxPages - 2;
}
}
if (this.currentPage % 2 == 1)
{
this.currentPage--;
}
if (this.currentPage < 0)
{
this.currentPage = 0;
}
NodeList nList = this.manual.getElementsByTagName("page");
Node node = nList.item(this.currentPage);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
Class<? extends BookPage> clazz = MProxyClient.getPageClass(element.getAttribute("type"));
if (clazz != null)
{
try
{
this.pageLeft = clazz.newInstance();
this.pageLeft.init(this, 0);
this.pageLeft.readPageFromXML(element);
}
catch (Exception e)
{
}
}
else
{
this.pageLeft = null;
}
}
node = nList.item(this.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
{
this.pageRight = clazz.newInstance();
this.pageRight.init(this, 1);
this.pageRight.readPageFromXML(element);
}
catch (Exception e)
{
}
}
else
{
this.pageLeft = null;
}
}
else
{
this.pageRight = null;
}
}
@Override
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 (this.pageLeft != null)
{
this.pageLeft.renderBackgroundLayer(localWidth + 16, localHeight + 12);
}
if (this.pageRight != null)
{
this.pageRight.renderBackgroundLayer(localWidth + 220, localHeight + 12);
}
if (this.pageLeft != null)
{
this.pageLeft.renderContentLayer(localWidth + 16, localHeight + 12, this.bData.isTranslatable);
}
if (this.pageRight != null)
{
this.pageRight.renderContentLayer(localWidth + 220, localHeight + 12, this.bData.isTranslatable);
}
}
public Minecraft getMC()
{
return this.mc;
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
}
@@ -1,56 +0,0 @@
package mantle.client.gui;
import mantle.books.BookData;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
@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.
*/
@Override
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);
}
}
}
@@ -1,18 +0,0 @@
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)
{
}
}
@@ -1,26 +0,0 @@
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);
}
@@ -1,74 +0,0 @@
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)
{
this.text = nodes.item(0).getTextContent();
}
nodes = element.getElementsByTagName("link");
this.iconText = new String[nodes.getLength()];
this.icons = new ItemStack[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++)
{
NodeList children = nodes.item(i).getChildNodes();
this.iconText[i] = children.item(1).getTextContent();
this.icons[i] = MantleClientRegistry.getManualIcon(children.item(3).getTextContent());
}
}
@Override
public void renderContentLayer(int localWidth, int localHeight, boolean isTranslatable)
{
if (this.text != null)
{
if (isTranslatable)
{
this.text = StatCollector.translateToLocal(this.text);
}
this.manual.fonts.drawString("\u00a7n" + this.text, localWidth + 25 + this.manual.fonts.getStringWidth(this.text) / 2, localHeight + 4, 0);
}
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
this.manual.renderitem.zLevel = 100;
for (int i = 0; i < this.icons.length; i++)
{
this.manual.renderitem.renderItemIntoGUI(this.icons[i], localWidth + 16, localHeight + 18 * i + 18);
int yOffset = 18;
if (isTranslatable)
{
this.iconText[i] = StatCollector.translateToLocal(this.iconText[i]);
}
if (this.iconText[i].length() > 40)
{
yOffset = 13;
}
this.manual.fonts.drawString(this.iconText[i], localWidth + 38, localHeight + 18 * i + yOffset, 0);
}
this.manual.renderitem.zLevel = 0;
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
}
}
@@ -1,140 +0,0 @@
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)
{
this.text = nodes.item(0).getTextContent();
}
nodes = element.getElementsByTagName("name");
if (nodes != null)
{
this.icons = MantleClientRegistry.getRecipeIcons(nodes.item(0).getTextContent());
}
nodes = element.getElementsByTagName("size");
if (nodes != null)
{
this.size = nodes.item(0).getTextContent();
}
}
@Override
public void renderContentLayer(int localWidth, int localHeight, boolean isTranslatable)
{
if (isTranslatable)
{
this.text = StatCollector.translateToLocal(this.text);
}
if (this.size.equals("two"))
{
this.drawCraftingPage(this.text, this.icons, 2, localWidth, localHeight + 12);
}
if (this.size.equals("three"))
{
this.drawCraftingPage(this.text, this.icons, 3, localWidth + (this.side != 1 ? 6 : 0), localHeight + 12);
}
}
public void drawCraftingPage(String info, ItemStack[] icons, int recipeSize, int localWidth, int localHeight)
{
if (info != null)
{
this.manual.fonts.drawString("\u00a7n" + info, localWidth + 50, localHeight + 4, 0);
}
GL11.glScalef(2f, 2f, 2f);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
this.manual.renderitem.zLevel = 100;
if (recipeSize == 2)
{
this.manual.renderitem.renderItemAndEffectIntoGUI(icons[0], (localWidth + 126) / 2, (localHeight + 68) / 2);
if (icons[0].stackSize > 1)
{
this.manual.renderitem.renderItemOverlayIntoGUI(this.manual.fonts, 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)
{
this.manual.renderitem.renderItemAndEffectIntoGUI(icons[i + 1], (localWidth + 14 + 36 * (i % 2)) / 2, (localHeight + 36 * (i / 2) + 52) / 2);
}
}
}
if (recipeSize == 3)
{
this.manual.renderitem.renderItemAndEffectIntoGUI(icons[0], (localWidth + 138) / 2, (localHeight + 70) / 2);
if (icons[0].stackSize > 1)
{
this.manual.renderitem.renderItemOverlayIntoGUI(this.manual.fonts, 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)
{
this.manual.renderitem.renderItemAndEffectIntoGUI(icons[i + 1], (localWidth - 2 + 36 * (i % 3)) / 2, (localHeight + 36 * (i / 3) + 34) / 2);
}
}
}
this.manual.renderitem.zLevel = 0;
GL11.glScalef(0.5F, 0.5F, 0.5F);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
}
@Override
public void renderBackgroundLayer(int localwidth, int localheight)
{
if (this.size.equals("two"))
{
this.drawBackground(2, localwidth, localheight + 12);
}
if (this.size.equals("three"))
{
this.drawBackground(3, localwidth + (this.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)
{
this.manual.getMC().getTextureManager().bindTexture(background);
if (size == 2)
{
this.manual.drawTexturedModalRect(localWidth + 8, localHeight + 46, 0, 116, 154, 78);
}
if (size == 3)
{
this.manual.drawTexturedModalRect(localWidth - 8, localHeight + 28, 0, 0, 183, 114);
}
}
}
@@ -1,75 +0,0 @@
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)
{
this.text = nodes.item(0).getTextContent();
}
nodes = element.getElementsByTagName("recipe");
if (nodes != null)
{
this.icons = MantleClientRegistry.getRecipeIcons(nodes.item(0).getTextContent());
}
}
@Override
public void renderContentLayer(int localWidth, int localHeight, boolean isTranslatable)
{
if (this.text != null)
{
if (isTranslatable)
{
this.text = StatCollector.translateToLocal(this.text);
}
this.manual.fonts.drawString("\u00a7n" + this.text, localWidth + 50, localHeight + 4, 0);
}
GL11.glScalef(2f, 2f, 2f);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
this.manual.renderitem.zLevel = 100;
this.manual.renderitem.renderItemAndEffectIntoGUI(MantleClientRegistry.getManualIcon("coal"), (localWidth + 38) / 2, (localHeight + 110) / 2);
this.manual.renderitem.renderItemAndEffectIntoGUI(this.icons[0], (localWidth + 106) / 2, (localHeight + 74) / 2);
this.manual.renderitem.renderItemAndEffectIntoGUI(this.icons[1], (localWidth + 38) / 2, (localHeight + 38) / 2);
if (this.icons[0].stackSize > 1)
{
this.manual.renderitem.renderItemOverlayIntoGUI(this.manual.fonts, this.icons[0], (localWidth + 106) / 2, (localHeight + 74) / 2, String.valueOf(this.icons[0].stackSize));
}
this.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");
@Override
public void renderBackgroundLayer(int localWidth, int localHeight)
{
this.manual.getMC().getTextureManager().bindTexture(background);
this.manual.drawTexturedModalRect(localWidth + 32, localHeight + 32, 0, 0, 111, 114);
}
}
@@ -1,70 +0,0 @@
package mantle.client.pages;
import static mantle.lib.CoreRepo.logger;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
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)
{
this.text = nodes.item(0).getTextContent();
}
nodes = element.getElementsByTagName("location");
if (nodes != null)
{
this.location = nodes.item(0).getTextContent();
this.background = new ResourceLocation(this.location);
if (this.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)
{
this.text = StatCollector.translateToLocal(this.text);
}
this.manual.fonts.drawSplitString(this.text, localWidth + 8, localHeight, 178, 0);
}
@Override
public void renderBackgroundLayer(int localWidth, int localHeight)
{
if (this.background != null)
{
this.manual.getMC().getTextureManager().bindTexture(this.background);
}
//manual.getMC().renderEngine.bindTexture(location);
this.manual.drawTexturedModalRect(localWidth, localHeight + 12, 0, 0, 170, 144);
}
}
@@ -1,41 +0,0 @@
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)
{
this.title = nodes.item(0).getTextContent();
}
nodes = element.getElementsByTagName("text");
if (nodes != null)
{
this.body = nodes.item(0).getTextContent();
}
}
@Override
public void renderContentLayer(int localWidth, int localHeight, boolean isTranslatable)
{
if (isTranslatable)
{
this.title = StatCollector.translateToLocal(this.title);
this.body = StatCollector.translateToLocal(this.body);
}
this.manual.fonts.drawSplitString("\u00a7n" + this.title, localWidth + 70, localHeight + 4, 178, 0);
this.manual.fonts.drawSplitString(this.body, localWidth, localHeight + 16, 190, 0);
}
}
@@ -1,71 +0,0 @@
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)
{
this.text = nodes.item(0).getTextContent();
}
nodes = element.getElementsByTagName("item");
this.iconText = new String[nodes.getLength()];
this.icons = new ItemStack[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++)
{
NodeList children = nodes.item(i).getChildNodes();
this.iconText[i] = children.item(1).getTextContent();
this.icons[i] = MantleClientRegistry.getManualIcon(children.item(3).getTextContent());
}
}
@Override
public void renderContentLayer(int localWidth, int localHeight, boolean isTranslatable)
{
if (isTranslatable)
{
this.text = StatCollector.translateToLocal(this.text);
}
this.manual.fonts.drawSplitString(this.text, localWidth, localHeight, 178, 0);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
this.manual.renderitem.zLevel = 100;
int offset = this.text.length() / 4 + 10;
for (int i = 0; i < this.icons.length; i++)
{
if (isTranslatable)
{
this.iconText[i] = StatCollector.translateToLocal(this.iconText[i]);
}
this.manual.renderitem.renderItemIntoGUI(this.icons[i], localWidth + 8, localHeight + 18 * i + offset);
int yOffset = 39;
if (this.iconText[i].length() > 40)
{
yOffset = 34;
}
this.manual.fonts.drawSplitString(this.iconText[i], localWidth + 30, localHeight + 18 * i + offset, 140, 0);
}
this.manual.renderitem.zLevel = 0;
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
}
}
@@ -1,31 +0,0 @@
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)
{
this.text = nodes.item(0).getTextContent();
}
}
@Override
public void renderContentLayer(int localWidth, int localHeight, boolean IsTranslatable)
{
if (IsTranslatable)
{
this.text = StatCollector.translateToLocal(this.text);
}
this.manual.fonts.drawSplitString(this.text, localWidth, localHeight, 178, 0);
}
}
@@ -1,31 +0,0 @@
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)
{
this.text = nodes.item(0).getTextContent();
}
}
@Override
public void renderContentLayer(int localWidth, int localHeight, boolean isTranslatable)
{
if (isTranslatable)
{
this.text = StatCollector.translateToLocal(this.text);
}
this.manual.fonts.drawSplitString(this.text, localWidth, localHeight, 178, 0);
}
}
@@ -1,29 +0,0 @@
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 == item2;
}
//@TODO make this a more verbose comparison
public static boolean areEquivalent(ItemStack is1, ItemStack is2)
{
return is1.getItem() == is2.getItem();
}
}
-47
View File
@@ -1,47 +0,0 @@
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.enchantmentsBookList)
{
if (e != null && e.getName() != null)
{
logger.info("Enchantment ID & name: " + e.effectId + " " + e.getName());
}
}
}
}
}
@@ -1,34 +0,0 @@
package mantle.common;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.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()
{
}
}
@@ -1,57 +0,0 @@
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);
}
@@ -1,76 +0,0 @@
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;
import net.minecraft.util.BlockPos;
public class PacketUpdateTE extends AbstractPacket
{
private BlockPos pos;
private NBTTagCompound data;
public PacketUpdateTE()
{
}
public PacketUpdateTE(BlockPos pos, NBTTagCompound data)
{
this.pos = pos;
this.data = data;
}
@Override
public void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer)
{
PacketBuffer pbuff = new PacketBuffer(buffer);
pbuff.writeInt(this.pos.getX());
pbuff.writeShort(this.pos.getY());
pbuff.writeInt(this.pos.getZ());
try
{
pbuff.writeNBTTagCompoundToBuffer(this.data);
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer)
{
PacketBuffer pbuff = new PacketBuffer(buffer);
this.pos = new BlockPos(pbuff.readInt(), pbuff.readShort(), pbuff.readInt());
try
{
this.data = pbuff.readNBTTagCompoundFromBuffer();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void handleClientSide(EntityPlayer player)
{
TileEntity te = player.worldObj.getTileEntity(this.pos);
if (te != null)
{
te.readFromNBT(this.data);
}
}
@Override
public void handleServerSide(EntityPlayer player)
{
}
}
@@ -1,32 +0,0 @@
package mantle.crash;
import net.minecraftforge.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 this.modId + " Environment";
}
}
@@ -1,41 +0,0 @@
package mantle.crash;
import java.util.List;
import net.minecraftforge.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 this.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 : this.modIds)
{
str = str + (firstEntry ? id : ", " + id);
firstEntry = false;
}
return str;
}
}
-28
View File
@@ -1,28 +0,0 @@
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;
}
}
@@ -1,54 +0,0 @@
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);
}
}
}
@@ -1,17 +0,0 @@
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);
}
@@ -1,35 +0,0 @@
package mantle.event;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.eventhandler.Event;
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);
}
}
}
-104
View File
@@ -1,104 +0,0 @@
package mantle.event;
import static mantle.lib.CoreRepo.logger;
import java.util.List;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.event.FMLMissingMappingsEvent;
import net.minecraftforge.fml.common.event.FMLMissingMappingsEvent.MissingMapping;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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)
{
this.mod = m;
this.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)
{
this.remapItem.put(this.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)
{
this.remapBlock.put(this.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)
{
this.ignore.add(this.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 ((!this.remapBlock.isEmpty() || !this.remapItem.isEmpty()))
{
event.applyModContainer(this.mod);
List<MissingMapping> l = event.get();
if (l != null)
{
for (MissingMapping miss : event.get())
{
if (this.remapItem.containsKey(miss.name))
{
miss.remap(this.remapItem.get(miss.name));
}
else if (this.remapBlock.containsKey(miss.name))
{
miss.remap(this.remapBlock.get(miss.name));
}
else if (this.ignore.contains(miss.name))
{
miss.ignore();
}
}
}
else
{
logger.error("migration list from FML empty for mod " + this.modID);
}
}
}
}
-17
View File
@@ -1,17 +0,0 @@
package mantle.items;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.registry.GameData;
public class ItemUtils
{
public static String getUniqueName(Item item)
{
return (String) GameData.getItemRegistry().getNameForObject(item);
}
public static Item getItemFromUniqueName(String uniqueName)
{
return GameData.getItemRegistry().getObject(uniqueName);
}
}
-77
View File
@@ -1,77 +0,0 @@
package mantle.items;
import java.util.List;
import mantle.Mantle;
import mantle.books.BookDataStore;
import mantle.event.ManualOpenEvent;
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 net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.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);
this.modID = CoreRepo.modId;
}
public void updateManual()
{
this.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 this.modID + ":" + super.getUnlocalizedName();
}
@Override
public String getUnlocalizedName(ItemStack par1ItemStack)
{
return super.getUnlocalizedName(par1ItemStack);
}
}
@@ -1,63 +0,0 @@
package mantle.items.abstracts;
import java.util.List;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
public class CraftingItem extends Item
{
public String modTexPrefix;
public String[] textureNames;
public String[] unlocalizedNames;
public String folder;
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;
}
@Override
public String getUnlocalizedName(ItemStack stack)
{
int arr = MathHelper.clamp_int(stack.getItemDamage(), 0, this.unlocalizedNames.length);
return this.getUnlocalizedName() + "." + this.unlocalizedNames[arr];
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void getSubItems(Item b, CreativeTabs tab, List list)
{
for (int i = 0; i < this.unlocalizedNames.length; i++)
{
if (!(this.textureNames[i].equals("")))
{
list.add(new ItemStack(b, 1, i));
}
}
}
}
@@ -1,6 +0,0 @@
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.
}
-109
View File
@@ -1,109 +0,0 @@
package mantle.lib;
import static mantle.lib.CoreRepo.logger;
import static mantle.lib.CoreRepo.modId;
import java.io.File;
import java.io.IOException;
import mantle.books.external.ZipLoader;
import net.minecraftforge.common.config.Configuration;
import org.apache.commons.io.FilenameUtils;
/**
* 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);
//check for debugging overrides in system environment
checkSysOverrides();
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;
}
-24
View File
@@ -1,24 +0,0 @@
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 = "mantle";
public static final String modName = "Mantle";
public static final String modVersion = "${version}";
public static final Logger logger = LogManager.getLogger("Mantle");
}
-32
View File
@@ -1,32 +0,0 @@
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)
{
this.display = stack;
}
@Override
public ItemStack getIconItemStack()
{
return this.display;
}
@Override
public Item getTabIconItem()
{
return this.display.getItem();
}
}
@@ -1,71 +0,0 @@
package mantle.lib.client;
import java.util.HashMap;
import java.util.Map;
import mantle.books.client.BookImage;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import com.google.common.collect.Maps;
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);
}
}
@@ -1,84 +0,0 @@
package mantle.lib.environment;
import static mantle.lib.CoreRepo.logger;
import static mantle.lib.CoreRepo.modId;
import java.util.List;
import mantle.crash.CallableSuppConfig;
import mantle.crash.CallableUnsuppConfig;
import mantle.lib.CoreConfig;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.ICrashCallable;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.relauncher.Side;
import com.google.common.collect.Lists;
/**
* 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 = Lists.newArrayList();
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 spigot. Please try Sponge instead");
}
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);
}
}
}
-87
View File
@@ -1,87 +0,0 @@
package mantle.math;
/**
* Dozenal Converter
*
* Converts decimals into dozenal.
*
* @author mDiyo
*/
import java.util.LinkedList;
import com.google.common.collect.Lists;
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 = Lists.newLinkedList();
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';
}
}
@@ -1,25 +0,0 @@
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));
}
}
}
@@ -1,58 +0,0 @@
package mantle.pulsar.config;
import java.io.File;
import mantle.pulsar.pulse.PulseMeta;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.Loader;
/**
* 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(this.confPath));
config.load();
}
@Override
public boolean isModuleEnabled(PulseMeta meta)
{
return config.get(this.description, meta.getId(), meta.isEnabled(), meta.getDescription()).getBoolean(meta.isEnabled());
}
@Override
public void flush()
{
if (config.hasChanged())
{
config.save();
}
}
}
@@ -1,31 +0,0 @@
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();
}
@@ -1,294 +0,0 @@
package mantle.pulsar.control;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import mantle.pulsar.config.IConfiguration;
import mantle.pulsar.internal.Configuration;
import mantle.pulsar.internal.CrashHandler;
import mantle.pulsar.internal.logging.ILogger;
import mantle.pulsar.internal.logging.LogManager;
import mantle.pulsar.pulse.Pulse;
import mantle.pulsar.pulse.PulseMeta;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.FMLModContainer;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.event.FMLEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.common.eventbus.SubscriberExceptionContext;
import com.google.common.eventbus.SubscriberExceptionHandler;
/**
* Manager class for a given mods Pulses.
*
* This MUST be constructed by a mod BEFORE preinit as it registers on to the mod event bus - a static block would serve
* for this. No more Pulses can be registered after preinit has been caught, so assume preinit is too late to register
* new Pulses.
*
* Each Pulsar-enabled mod should create one and only one of these to manage its Pulses.
*
* @author Arkan <[email protected]>
*/
@SuppressWarnings("unused")
public class PulseManager
{
private 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;
private EventBus bus;
private String id;
/**
* Configuration-using constructor.
*
* This form creates a PulseManager that supports configuration of Pulses by file.
*
* @param configName The config file name.
*/
public PulseManager(String configName)
{
this.init();
this.useConfig = true;
this.conf = new Configuration(configName, this.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 config Configuration handler.
*/
public PulseManager(IConfiguration config)
{
this.init();
this.useConfig = true;
this.conf = config;
}
/**
* Shared initialiser code between all the constructors.
*/
private void init()
{
String modId = Loader.instance().activeModContainer().getModId();
this.id = modId;
this.log = LogManager.getLogger("Pulsar-" + modId);
FMLCommonHandler.instance().registerCrashCallable(new CrashHandler(modId, this));
// Attach us to the mods FML bus and setup our own bus
this.bus = new EventBus(new BusExceptionHandler(modId));
this.attachToContainerEventBus(this);
}
/**
* 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 (this.blockNewRegistrations)
{
throw new RuntimeException("A mod tried to register a plugin after preinit! Pulse: "
+ pulse);
}
if (!this.configLoaded)
{
this.conf.load();
this.configLoaded = true;
}
String id, description, deps;
boolean forced, enabled, defaultEnabled, 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();
defaultEnabled = 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))
{
this.log.info("Skipping Pulse " + id + "; missing dependency: " + s);
missingDeps = true;
enabled = false;
break;
}
}
}
PulseMeta meta = new PulseMeta(id, description, forced, enabled, defaultEnabled);
meta.setEnabled(!missingDeps && this.getEnabledFromConfig(meta));
if (meta.isEnabled())
{
this.pulses.put(pulse, meta);
// Attach Pulse to internal event bus
this.bus.register(pulse);
}
}
/**
* Helper to attach a given object to the modcontainer event bus.
*
* @param obj Object to register.
*/
private void attachToContainerEventBus(Object obj)
{
ModContainer cnt = Loader.instance().activeModContainer();
this.log.debug("Attaching [" + obj + "] to event bus for container [" + cnt + "]");
try
{
FMLModContainer mc = (FMLModContainer) cnt;
Field ebf = mc.getClass().getDeclaredField("eventBus");
boolean access = ebf.isAccessible();
ebf.setAccessible(true);
EventBus eb = (EventBus) ebf.get(mc);
ebf.setAccessible(access);
eb.register(obj);
}
catch (NoSuchFieldException nsfe)
{
throw new RuntimeException("Pulsar >> Incompatible FML mod container (missing eventBus field) - wrong Forge version?");
}
catch (IllegalAccessException iae)
{
throw new RuntimeException("Pulsar >> Security Manager blocked access to eventBus on mod container. Cannot continue.");
}
catch (ClassCastException cce)
{
throw new RuntimeException("Pulsar >> Something in the mod container had the wrong type? " + cce.getMessage());
}
}
/**
* Internal (but public for EventBus use) handler for events.
*
* DO NOT CALL THIS DIRECTLY! Let EventBus handle it.
*
* @param evt An event object.
*/
@Subscribe
public void propagateEvent(FMLEvent evt)
{
if (evt instanceof FMLPreInitializationEvent)
{
this.preInit((FMLPreInitializationEvent) evt);
}
this.bus.post(evt);
}
private boolean getEnabledFromConfig(PulseMeta meta)
{
if (meta.isForced() || !this.useConfig)
{
return true; // Forced or no config set.
}
return this.conf.isModuleEnabled(meta);
}
public void preInit(FMLPreInitializationEvent evt)
{
if (!this.blockNewRegistrations)
{
this.conf.flush(); // First preInit call, so flush config
}
this.blockNewRegistrations = true;
}
/**
* Check if a given Pulse ID is loaded in this manager.
*
* @param pulseId The ID to check.
* @return Whether the ID was present.
*/
public boolean isPulseLoaded(String pulseId)
{
for (Map.Entry<Object, PulseMeta> entry : this.pulses.entrySet())
{
if (entry.getValue().getId().equals(pulseId))
{
return true;
}
}
return false;
}
public Collection<PulseMeta> getAllPulseMetadata()
{
return this.pulses.values();
}
/**
* Needed because Google EventBus is a derp and by default swallows exceptions (dafuq guys?)
*/
private class BusExceptionHandler implements SubscriberExceptionHandler
{
private final String id;
/**
* @param id Mod ID to include in exception raises.
*/
public BusExceptionHandler(String id)
{
this.id = id;
}
@Override
public void handleException(Throwable exception, SubscriberExceptionContext ctx)
{
FMLCommonHandler.instance().raiseException(exception, "Pulsar/" + this.id + " >> Exception uncaught in ["
+ ctx.getSubscriber().getClass().getName() + ":" + ctx.getSubscriberMethod().getName()
+ "] for event [" + ctx.getEvent().getClass().getSimpleName() + "]", true);
}
}
@Override
public String toString()
{
return "PulseManager[" + this.id + "]";
}
}
@@ -1,28 +0,0 @@
package mantle.pulsar.debug;
import mantle.pulsar.internal.logging.ILogger;
import mantle.pulsar.internal.logging.LogManager;
import mantle.pulsar.pulse.Pulse;
import net.minecraftforge.fml.common.Loader;
import com.google.common.eventbus.Subscribe;
/**
* Debug Pulse to 'eavesdrop' on the PulseManager event bus traffic.
*
* @author Arkan <[email protected]>
*/
@SuppressWarnings("unused")
@Pulse(id = "EventSpy", description = "we iz in ur buses, monitorin ur eventz", forced = true)
public class EventSpy
{
private final ILogger log = LogManager.getLogger("EventSpy/" + Loader.instance().activeModContainer().getModId());
@Subscribe
public void receive(Object evt)
{
this.log.info("Received event: " + evt);
}
}
@@ -1,253 +0,0 @@
package mantle.pulsar.internal;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import mantle.pulsar.config.IConfiguration;
import mantle.pulsar.internal.logging.ILogger;
import mantle.pulsar.pulse.PulseMeta;
import net.minecraftforge.fml.common.Loader;
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;
/**
* 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()
{
this.getModulesFromJson();
}
@Override
public boolean isModuleEnabled(PulseMeta meta)
{
ConfigEntry entry = this.modules.get(meta.getId());
if (entry == null)
{
this.modules.put(meta.getId(), new ConfigEntry(meta.isDefaultEnabled(), meta.getDescription()));
return meta.isEnabled();
}
else
{
return entry.getEnabled();
}
}
@Override
public void flush()
{
this.writeModulesToJson();
}
private void getModulesFromJson()
{
// Step 1: Does the file exist?
File f = new File(this.confPath);
if (!f.exists())
{
this.logger.info("Couldn't find config file; will generate a new one later.");
this.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: " + this.confPath);
}
// Step 3: Good enough. Read it.
try
{
try
{
this.modules = this.parseV1Config(f);
}
catch (Exception ex)
{
this.logger.warn("Failed to parse " + f.getName() + " using the v1 parser; trying the v0 parser.");
Map<String, ConfigEntry> conf = this.parseV0Config(f);
this.logger.info("Found valid v0 configuration. Upgrading it.");
this.modules = conf;
this.writeModulesToJson();
this.logger.info("Upgrade complete! Config is now in v1 format.");
}
}
catch (Exception ex)
{
this.logger.warn("Invalid config file. Discarding.");
ex.printStackTrace();
this.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(this.confPath))));
writer.setIndent(" ");
GsonConfig out = new GsonConfig(CONFIG_LEVEL, this.modules);
gson.toJson(out, GsonConfig.class, writer);
writer.close();
}
catch (Exception ex)
{
this.logger.warn("Could not write config? " + this.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 this.enabled;
}
}
/**
* 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 this.CONFIG_VERSION;
}
public Map<String, ConfigEntry> getModules()
{
return this.modules;
}
}
}
@@ -1,62 +0,0 @@
package mantle.pulsar.internal;
import mantle.pulsar.control.PulseManager;
import mantle.pulsar.pulse.PulseMeta;
import net.minecraftforge.fml.common.ICrashCallable;
/**
* FML crash callable for Pulse Managers; dumps a list of loaded pulses to the error log.
*
* @author Arkan <[email protected]>
*/
public class CrashHandler implements ICrashCallable
{
private String id;
private PulseManager manager;
public CrashHandler(String modId, PulseManager manager)
{
this.id = "Pulsar/" + modId + " loaded Pulses";
this.manager = manager;
}
@Override
public String getLabel()
{
return this.id;
}
@Override
public String call() throws Exception
{
String out = "\n";
for (PulseMeta meta : this.manager.getAllPulseMetadata())
{
String state = getStateFromMeta(meta);
out += "\t\t- " + meta.getId() + " (" + state + ")\n"; // Yes, yes, manual indenting, I know...
}
return out;
}
private static String getStateFromMeta(PulseMeta meta)
{
if (meta.isForced())
{
return "Enabled/Forced";
}
else
{
if (meta.isEnabled())
{
return "Enabled/Not Forced";
}
else
{
return "Disabled/Not Forced";
}
}
}
}
@@ -1,24 +0,0 @@
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);
}
@@ -1,56 +0,0 @@
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)
{
this.log = Logger.getLogger(name);
}
@Override
public void fatal(String msg)
{
this.log.severe(msg); // JUL doesn't -have- fatal...
}
@Override
public void severe(String msg)
{
this.log.severe(msg);
}
@Override
public void warn(String msg)
{
this.log.warning(msg);
}
@Override
public void info(String msg)
{
this.log.info(msg);
}
@Override
public void debug(String msg)
{
this.log.fine(msg); // Good enough.
}
@Override
public void trace(String msg)
{
this.log.finest(msg); // Closest we'll get.
}
}
@@ -1,56 +0,0 @@
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)
{
this.log = org.apache.logging.log4j.LogManager.getLogger(name);
}
@Override
public void fatal(String msg)
{
this.log.fatal(msg);
}
@Override
public void severe(String msg)
{
this.log.error(msg);
}
@Override
public void warn(String msg)
{
this.log.warn(msg);
}
@Override
public void info(String msg)
{
this.log.info(msg);
}
@Override
public void debug(String msg)
{
this.log.debug(msg);
}
@Override
public void trace(String msg)
{
this.log.trace(msg);
}
}
@@ -1,53 +0,0 @@
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);
}
}
}
@@ -1,36 +0,0 @@
/**
* 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;
@@ -1,53 +0,0 @@
package mantle.pulsar.pulse;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Metadata annotation for IPulse implementations.
*
* Pulses should use the standard Google Event Bus @Subscribe annotation to catch FML events, which are forwarded from
* the current mod container (including Pre/Init/Post events).
*
* @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;
}
@@ -1,53 +0,0 @@
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, defaultEnabled;
public PulseMeta(String id, String description, boolean forced, boolean enabled, boolean defaultEnabled)
{
this.id = id;
this.description = description;
this.forced = forced;
this.enabled = enabled;
this.defaultEnabled = defaultEnabled;
}
public String getId()
{
return this.id;
}
public String getDescription()
{
return this.description;
}
public boolean isForced()
{
return this.forced;
}
public boolean isEnabled()
{
return this.enabled;
}
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public boolean isDefaultEnabled()
{
return this.defaultEnabled;
}
}
@@ -1,53 +0,0 @@
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 || this.getClass() != o.getClass())
{
return false;
}
ItemMetaWrapper itemMeta = (ItemMetaWrapper) o;
if (this.item != null ? !(this.item == itemMeta.item) : itemMeta.item != null)
{
return false;
}
return !(this.meta != null ? !this.meta.equals(itemMeta.meta) : itemMeta.meta != null);
}
@Override
public int hashCode()
{
int result = this.item != null ? this.item.hashCode() : 0;
result = 31 * result + (this.meta != null ? this.meta.hashCode() : 0);
return result;
}
}
@@ -1,40 +0,0 @@
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 || this.getClass() != o.getClass())
{
return false;
}
ItemStackNBTWrapper that = (ItemStackNBTWrapper) o;
return ItemStack.areItemStacksEqual(this.stack, that.stack);
}
@Override
public int hashCode()
{
int result = this.stack.getItem() != null ? this.stack.getItem().hashCode() : 0;
result = 31 * result + this.stack.getItemDamage();
result = 31 * result + (this.stack.getTagCompound() != null ? this.stack.getTagCompound().hashCode() : 0);
result = 31 * result + this.stack.stackSize;
return result;
}
}
@@ -1,51 +0,0 @@
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 || this.getClass() != o.getClass())
{
return false;
}
if (!super.equals(o))
{
return false;
}
ItemStackWrapper that = (ItemStackWrapper) o;
return !(this.stacksize != null ? !this.stacksize.equals(that.stacksize) : that.stacksize != null);
}
@Override
public int hashCode()
{
int result = super.hashCode();
result = 31 * result + (this.stacksize != null ? this.stacksize.hashCode() : 0);
return result;
}
}
@@ -1,95 +0,0 @@
package mantle.world;
import java.io.Serializable;
import net.minecraft.util.BlockPos;
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(BlockPos pos)
{
this(pos.getX() >> 4, pos.getZ() >> 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(this.chunkX, this.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 = this.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;
}
}
@@ -1,27 +0,0 @@
package mantle.world;
import net.minecraft.util.BlockPos;
/**
* CoordTuplePair
*
* @author mDiyo
*/
public class CoordTuplePair
{
public BlockPos a;
public BlockPos b;
public CoordTuplePair(BlockPos a, BlockPos b)
{
this.a = a;
this.b = b;
}
public CoordTuplePair(int aX, int aY, int aZ, int bX, int bY, int bZ)
{
this.a = new BlockPos(aX, aY, aZ);
this.b = new BlockPos(bX, bY, bZ);
}
}
@@ -1,63 +0,0 @@
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)
{
this.dim = worldID;
this.x = posX;
this.z = posZ;
}
public boolean equalCoords(int worldID, int posX, int posZ)
{
return this.dim == posX && this.x == posX && this.z == posZ;
}
@Override
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if (this.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 + this.dim;
result = prime * result + this.x;
result = prime * result + this.z;
return result;
}
@Override
public String toString()
{
return "Dim: " + this.dim + ", X: " + this.x + ", Z: " + this.z;
}
}
@@ -1,65 +0,0 @@
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)
{
this.dim = worldID;
this.y = posY;
this.x = posX;
this.z = posZ;
}
public boolean equalCoords(int worldID, int posX, int posY, int posZ)
{
return this.dim == worldID && this.x == posX && this.y == posY && this.z == posZ;
}
@Override
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if (this.getClass() == obj.getClass())
{
DimensionCoordTuple coord = (DimensionCoordTuple) obj;
return this.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 + this.dim;
result = prime * result + this.x;
result = prime * result + this.y;
result = prime * result + this.z;
return result;
}
@Override
public String toString()
{
return "Dim: " + this.dim + ", X: " + this.x + ", Y: " + this.y + ", Z: " + this.z;
}
}
@@ -1,29 +0,0 @@
package mantle.world;
import net.minecraft.util.EnumFacing;
/**
* Helper functions for dealing with ForgeDirection
*
* @author Sunstrike <[email protected]>
*/
@SuppressWarnings("unused")
public class DirectionUtils
{
private DirectionUtils()
{
// No instantiation
}
public static boolean isRightAngles(EnumFacing a, EnumFacing b)
{
return a != b && a != b.getOpposite();
}
public static boolean isHorizontal(EnumFacing a)
{
return a == EnumFacing.EAST || a == EnumFacing.NORTH || a == EnumFacing.SOUTH || a == EnumFacing.WEST;
}
}
@@ -0,0 +1,34 @@
package slimeknights.mantle;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import slimeknights.mantle.common.CommonProxy;
/**
* Mantle
*
* Central mod object for Mantle
*
* @author Sunstrike <[email protected]>
*/
@Mod(modid = Mantle.modId, name = Mantle.modName, version = Mantle.modVersion, dependencies = "required-after:Forge@[11.14,)")
public class Mantle {
public static final String modId = "mantle";
public static final String modName = "Mantle";
public static final String modVersion = "${version}";
public static final Logger logger = LogManager.getLogger("Mantle");
/* Instance of this mod, used for grabbing prototype fields */
@Instance("mantle")
public static Mantle instance;
/* Proxies for sides, used for graphics processing */
@SidedProxy(clientSide = "slimeknights.mantle.client.ClientProxy", serverSide = "slimeknights.mantle.common.CommonProxy")
public static CommonProxy proxy;
}
@@ -0,0 +1,91 @@
package slimeknights.mantle.block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import slimeknights.mantle.tileentity.TileInventory;
// Updated Version of InventoryBlock in Mantle
public abstract class BlockInventory extends BlockContainer {
protected BlockInventory(Material material) {
super(material);
}
// inventories usually need a tileEntity
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Override
public abstract TileEntity createNewTileEntity(World worldIn, int meta);
/**
* Called when the block is activated. Return true if a GUI is opened, false if the block has no GUI.
*/
protected abstract boolean openGui(EntityPlayer player, World world, BlockPos pos);
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumFacing side,
float clickX, float clickY, float clickZ) {
if(player.isSneaking()) {
return false;
}
if(!world.isRemote) {
return this.openGui(player, world, pos);
}
return true;
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer,
ItemStack stack) {
super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
// set custom name from named stack
if(stack.hasDisplayName()) {
TileEntity tileentity = worldIn.getTileEntity(pos);
if(tileentity instanceof TileInventory) {
((TileInventory) tileentity).setCustomName(stack.getDisplayName());
}
}
}
public void breakBlock(World worldIn, BlockPos pos, IBlockState state) {
TileEntity tileentity = worldIn.getTileEntity(pos);
if(tileentity instanceof TileInventory) {
InventoryHelper.dropInventoryItems(worldIn, pos, (IInventory) tileentity);
worldIn.updateComparatorOutputLevel(pos, this);
}
super.breakBlock(worldIn, pos, state);
}
@Override
public int damageDropped(IBlockState state) {
return getMetaFromState(state);
}
// BlockContainer sets this to -1, which equals invisible
// we need 3 for standard forge rendering
@Override
public int getRenderType() {
return 3;
}
}
@@ -1,4 +1,4 @@
package mantle.blocks.iface;
package slimeknights.mantle.block;
import net.minecraft.util.BlockPos;
@@ -1,4 +1,4 @@
package mantle.blocks.iface;
package slimeknights.mantle.block;
public interface IMasterNode extends IMasterLogic, IServantLogic
{
@@ -1,4 +1,4 @@
package mantle.blocks.iface;
package slimeknights.mantle.block;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
@@ -1,13 +1,7 @@
package mantle.blocks.abstracts;
package slimeknights.mantle.block;
import mantle.blocks.BlockUtils;
import mantle.blocks.iface.IMasterLogic;
import mantle.blocks.iface.IServantLogic;
import mantle.debug.DebugData;
import mantle.debug.IDebuggable;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
@@ -15,8 +9,9 @@ import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameData;
public class MultiServantLogic extends TileEntity implements IServantLogic, IDebuggable
public class MultiServantLogic extends TileEntity implements IServantLogic
{
boolean hasMaster;
@@ -122,29 +117,27 @@ public class MultiServantLogic extends TileEntity implements IServantLogic, IDeb
public void readCustomNBT(NBTTagCompound tags)
{
this.hasMaster = tags.getBoolean("TiedToMaster");
this.hasMaster = tags.getBoolean("hasMaster");
if (this.hasMaster)
{
int xCenter = tags.getInteger("xCenter");
int yCenter = tags.getInteger("yCenter");
int zCenter = tags.getInteger("zCenter");
this.master = new BlockPos(xCenter, yCenter, zCenter);
this.masterBlock = BlockUtils.getBlockFromUniqueName(tags.getString("MasterBlockName"));
// TODO: Make this a byte.
this.masterBlock = GameData.getBlockRegistry().getObject(tags.getString("MasterBlockName"));
this.state = Block.getStateById(tags.getInteger("masterState"));
}
}
public void writeCustomNBT(NBTTagCompound tags)
{
tags.setBoolean("TiedToMaster", this.hasMaster);
tags.setBoolean("hasMaster", this.hasMaster);
if (this.hasMaster)
{
tags.setInteger("xCenter", this.master.getX());
tags.setInteger("yCenter", this.master.getY());
tags.setInteger("zCenter", this.master.getZ());
tags.setString("MasterBlockName", BlockUtils.getUniqueName(this.masterBlock));
// TODO: Make this a byte.
tags.setString("MasterBlockName", (String) GameData.getBlockRegistry().getNameForObject(this.masterBlock));
tags.setInteger("masterState", Block.getStateId(this.state));
}
}
@@ -180,23 +173,6 @@ public class MultiServantLogic extends TileEntity implements IServantLogic, IDeb
this.worldObj.markBlockForUpdate(this.pos);
}
/* IDebuggable */
@Override
public DebugData getDebugInfo(EntityPlayer player)
{
String[] strs = new String[2];
strs[0] = "Location: x" + this.pos.getX() + ", y" + this.pos.getY() + ", z" + this.pos.getZ();
if (this.hasMaster)
{
strs[1] = "masterBlock: " + this.masterBlock.toString() + ", masterMeat: " + this.state.toString();
}
else
{
strs[1] = "No active master.";
}
return new DebugData(player, this.getClass(), strs);
}
@Override
public World getWorld()
{
@@ -0,0 +1,6 @@
package slimeknights.mantle.client;
import slimeknights.mantle.common.CommonProxy;
public class ClientProxy extends CommonProxy {
}
@@ -0,0 +1,43 @@
package slimeknights.mantle.client;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class CreativeTab extends CreativeTabs {
private ItemStack icon;
// a vanilla icon in case the other one isn't present
public CreativeTab(String label, ItemStack backupIcon) {
super(label);
this.icon = backupIcon;
}
public void setDisplayIcon(ItemStack displayIcon) {
if(displayIcon != null && displayIcon.getItem() != null) {
this.icon = displayIcon;
}
}
@SideOnly(Side.CLIENT)
@Override
public ItemStack getIconItemStack() {
return icon;
}
@SideOnly(Side.CLIENT)
@Override
public int getIconItemDamage() {
return icon.getItemDamage();
}
@SideOnly(Side.CLIENT)
@Override
public Item getTabIconItem() {
return icon.getItem();
}
}
@@ -0,0 +1,170 @@
package slimeknights.mantle.client;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.IColoredBakedQuad;
import net.minecraftforge.client.model.IModelPart;
import net.minecraftforge.client.model.IModelState;
import net.minecraftforge.client.model.IPerspectiveState;
import net.minecraftforge.client.model.TRSRTransformation;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.Map;
import javax.vecmath.Vector3f;
public class ModelHelper {
static final Type maptype = new TypeToken<Map<String, String>>() {}.getType();
private static final Gson
GSON =
new GsonBuilder().registerTypeAdapter(maptype, ModelTextureDeserializer.INSTANCE).create();
public static final IPerspectiveState DEFAULT_ITEM_STATE;
public static final IPerspectiveState DEFAULT_TOOL_STATE;
public static TextureAtlasSprite getTextureFromBlock(Block block, int meta) {
IBlockState state = block.getStateFromMeta(meta);
return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state);
}
public static TextureAtlasSprite getTextureFromBlockstate(IBlockState state) {
return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state);
}
public static BakedQuad colorQuad(int color, BakedQuad quad) {
int[] data = quad.getVertexData();
int a = (color >> 24);
if(a == 0) {
a = 255;
}
int c = 0;
c |= ((color >> 16) & 0xFF) << 0; // red
c |= ((color >> 8) & 0xFF) << 8; // green
c |= ((color >> 0) & 0xFF) << 16; // blue
c |= (a & 0xFF) << 24; // alpha
// update color in the data. all 4 Vertices.
for(int i = 0; i < 4; i++) {
data[i * 7 + 3] = c;
}
return new IColoredBakedQuad.ColoredBakedQuad(data, -1, quad.getFace());
}
public static Map<String, String> loadTexturesFromJson(ResourceLocation location) throws IOException {
// get the json
IResource
iresource =
Minecraft.getMinecraft().getResourceManager()
.getResource(new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + ".json"));
Reader reader = new InputStreamReader(iresource.getInputStream(), Charsets.UTF_8);
return GSON.fromJson(reader, maptype);
}
public static ImmutableList<ResourceLocation> loadTextureListFromJson(ResourceLocation location) throws IOException {
ImmutableList.Builder<ResourceLocation> builder = ImmutableList.builder();
for(String s : loadTexturesFromJson(location).values()) {
builder.add(new ResourceLocation(s));
}
return builder.build();
}
public static ResourceLocation getModelLocation(ResourceLocation location) {
return new ResourceLocation(location.getResourceDomain(), "models/" + location.getResourcePath() + ".json");
}
public static ImmutableMap<ItemCameraTransforms.TransformType, TRSRTransformation> getTransformsFromState(IModelState state, IModelPart part) {
if(state instanceof IPerspectiveState) {
IPerspectiveState ps = (IPerspectiveState) state;
Map<ItemCameraTransforms.TransformType, TRSRTransformation> map = Maps.newHashMap();
for(ItemCameraTransforms.TransformType type : ItemCameraTransforms.TransformType.values()) {
map.put(type, ps.forPerspective(type).apply(part));
}
return Maps.immutableEnumMap(map);
}
return ImmutableMap.of();
}
static {
// equals forge:default-item
IModelState thirdperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 1f / 16, -3f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(-90, 0, 0)),
new Vector3f(0.55f, 0.55f, 0.55f),
null));
IModelState firstperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 4f / 16, 2f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, -135, 25)),
new Vector3f(1.7f, 1.7f, 1.7f),
null));
DEFAULT_ITEM_STATE = new IPerspectiveState.Impl(TRSRTransformation.identity(), ImmutableMap
.of(ItemCameraTransforms.TransformType.THIRD_PERSON, thirdperson,
ItemCameraTransforms.TransformType.FIRST_PERSON, firstperson));
thirdperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 1.25f / 16, -3.5f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, 90, -35)),
new Vector3f(0.85f, 0.85f, 0.85f),
null));
firstperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 4f / 16, 2f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, -135, 25)),
new Vector3f(1.7f, 1.7f, 1.7f),
null));
DEFAULT_TOOL_STATE = new IPerspectiveState.Impl(TRSRTransformation.identity(), ImmutableMap
.of(ItemCameraTransforms.TransformType.THIRD_PERSON, thirdperson,
ItemCameraTransforms.TransformType.FIRST_PERSON, firstperson));
}
/**
* Deseralizes a json in the format of { "textures": { "foo": "texture",... }}
* Ignores all invalid json
*/
public static class ModelTextureDeserializer implements JsonDeserializer<Map<String, String>> {
public static final ModelTextureDeserializer INSTANCE = new ModelTextureDeserializer();
private static final Gson GSON = new Gson();
@Override
public Map<String, String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
JsonElement texElem = obj.get("textures");
if(texElem == null) {
throw new JsonParseException("Missing textures entry in json");
}
return GSON.fromJson(texElem, maptype);
}
}
}
@@ -0,0 +1,78 @@
package slimeknights.mantle.client.gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Represents a GUI element INSIDE the graphics file.
* The coordinates all refer to the coordinates inside the graphics!
*/
@SideOnly(Side.CLIENT)
public class GuiElement {
// this is totally completely ugly but it's a simple solution that doesn't clutter everything too much >_>
public static int defaultTexW = 256;
public static int defaultTexH = 256;
public final int x;
public final int y;
public final int w;
public final int h;
public int texW;
public int texH;
public GuiElement(int x, int y, int w, int h, int texW, int texH) {
this(x, y, w, h);
setTextureSize(texW, texH);
defaultTexW = texW;
defaultTexH = texH;
}
public GuiElement(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
setTextureSize(defaultTexW, defaultTexH);
}
public GuiElement setTextureSize(int w, int h) {
texW = w;
texH = h;
return this;
}
public GuiElement shift(int xd, int yd) {
return new GuiElement(this.x + xd, this.y + yd, this.w, this.h, this.texW, this.texH);
}
/**
* Draws the element at the given x/y coordinates
*
* @param xPos X-Coordinate on the screen
* @param yPos Y-Coordinate on the screen
*/
public int draw(int xPos, int yPos) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos, yPos, x, y, w, h, texW, texH);
return w;
}
public static class Builder {
public int w;
public int h;
public Builder(int w, int h) {
this.w = w;
this.h = h;
}
public GuiElement get(int x, int y, int w, int h) {
return new GuiElement(x, y, w, h, this.w, this.h);
}
}
}
@@ -0,0 +1,69 @@
package slimeknights.mantle.client.gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiElementScalable extends GuiElement {
public GuiElementScalable(int x, int y, int w, int h) {
super(x, y, w, h);
}
public int drawScaledX(int xPos, int yPos, int width) {
for(int i = 0; i < width / w; i++) {
draw(xPos + i * w, yPos);
}
// remainder that doesn't fit total width
int remainder = width % w;
if(remainder > 0) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos + width - remainder, yPos, x, y, remainder, h, texW, texH);
}
return width;
}
public int drawScaledY(int xPos, int yPos, int height) {
for(int i = 0; i < height / h; i++) {
draw(xPos, yPos + i * h);
}
// remainder that doesn't fit total width
int remainder = height % h;
if(remainder > 0) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos, yPos + height - remainder, x, y, w, remainder, texW, texH);
}
return w;
}
public int drawScaled(int xPos, int yPos, int width, int height) {
// we draw full height row-wise
int full = height / this.h;
for(int i = 0; i < full; i++) {
drawScaledX(xPos, yPos + i * this.h, width);
}
yPos += full * this.h;
// and the remainder is drawn manually
int yRest = height % this.h;
// the same as drawScaledX but with the remaining height
for(int i = 0; i < width / w; i++) {
drawScaledY(xPos + i * w, yPos, yRest);
}
// remainder that doesn't fit total width
int remainder = width % w;
if(remainder > 0) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos + width - remainder, yPos, x, y, remainder, yRest, texW, texH);
}
return width;
}
public GuiElementScalable shift(int xd, int yd) {
GuiElementScalable element = new GuiElementScalable(this.x + xd, this.y + yd, this.w, this.h);
element.setTextureSize(this.texW, texH);
return element;
}
}
@@ -0,0 +1,118 @@
package slimeknights.mantle.client.gui;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.io.IOException;
// a sub-gui. Mostly the same as a separate GuiContainer, but doesn't do the calls that affect the game as if this were the only gui
@SideOnly(Side.CLIENT)
public abstract class GuiModule extends GuiContainer {
protected final GuiMultiModule parent;
// left or right of the parent
protected final boolean right;
// top or bottom of the parent
protected final boolean bottom;
public int yOffset = 0;
public int xOffset = 0;
public GuiModule(GuiMultiModule parent, Container container, boolean right, boolean bottom) {
super(container);
this.parent = parent;
this.right = right;
this.bottom = bottom;
}
public int guiRight() {
return guiLeft + xSize;
}
public int guiBottom() {
return guiTop + ySize;
}
@Override
public void initGui() {
this.guiLeft = (this.width - this.xSize) / 2;
this.guiTop = (this.height - this.ySize) / 2;
}
public void updatePosition(int parentX, int parentY, int parentSizeX, int parentSizeY) {
if(right) {
this.guiLeft = parentX + parentSizeX;
}
else {
this.guiLeft = parentX - this.xSize;
}
if(bottom) {
this.guiTop = parentY + parentSizeY - this.ySize;
}
else {
this.guiTop = parentY;
}
this.guiLeft += xOffset;
this.guiTop += yOffset;
}
public boolean shouldDrawSlot(Slot slot) {
return true;
}
/*
public void updateDragged(boolean dragSplitting, Set draggedSlots) {
this.dragSplitting = dragSplitting;
this.dragSplittingSlots.clear();
for(Object o : draggedSlots) {
if(o instanceof SlotWrapper)
this.dragSplittingSlots.add(((SlotWrapper) o).parent);
else
this.dragSplittingSlots.add(o);
}
}
*/
public void handleDrawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
this.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
public void handleDrawGuiContainerForegroundLayer(int mouseX, int mouseY) {
this.drawGuiContainerForegroundLayer(mouseX, mouseY);
}
/**
* Custom mouse click handling.
*
* @return True to prevent the main container handling the mouseclick
*/
public boolean handleMouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
return false;
}
/**
* Custom mouse click handling.
*
* @return True to prevent the main container handling the mouseclick
*/
public boolean handleMouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
return false;
}
/**
* Custom mouse click handling.
*
* @return True to prevent the main container handling the mouseclick
*/
public boolean handleMouseReleased(int mouseX, int mouseY, int state) {
return false;
}
}
@@ -0,0 +1,356 @@
package slimeknights.mantle.client.gui;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import codechicken.nei.LayoutManager;
import codechicken.nei.VisiblityData;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.TaggedInventoryArea;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.inventory.ContainerMultiModule;
import slimeknights.mantle.inventory.SlotWrapper;
@SideOnly(Side.CLIENT)
@Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems")
public class GuiMultiModule extends GuiContainer implements INEIGuiHandler {
// NEI-stuff >:(
private static Field NEI_Manager;
static {
try {
NEI_Manager = GuiContainer.class.getDeclaredField("manager");
} catch(NoSuchFieldException e) {
NEI_Manager = null;
}
}
protected List<GuiModule> modules = Lists.newArrayList();
public int cornerX;
public int cornerY;
public int realWidth;
public int realHeight;
public GuiMultiModule(ContainerMultiModule container) {
super(container);
realWidth = -1;
realHeight = -1;
}
protected void addModule(GuiModule module) {
modules.add(module);
}
@Override
public void initGui() {
if(realWidth > -1) {
// has to be reset before calling initGui so the position is getting retained
xSize = realWidth;
ySize = realHeight;
}
super.initGui();
this.cornerX = this.guiLeft;
this.cornerY = this.guiTop;
this.realWidth = xSize;
this.realHeight = ySize;
for(GuiModule module : modules) {
updateSubmodule(module);
}
//this.guiLeft = this.guiTop = 0;
//this.xSize = width;
//this.ySize = height;
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
for(GuiModule module : modules) {
module.handleDrawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
for(GuiModule module : modules) {
// set correct state for the module
GlStateManager.pushMatrix();
GlStateManager.translate(-this.guiLeft, -this.guiTop, 0.0F);
GlStateManager.translate(module.guiLeft, module.guiTop, 0.0F);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
module.handleDrawGuiContainerForegroundLayer(mouseX, mouseY);
GlStateManager.popMatrix();
}
drawContainerName();
drawPlayerInventoryName();
}
protected void drawContainerName() {
ContainerMultiModule multiContainer = (ContainerMultiModule) this.inventorySlots;
IChatComponent localizedName = multiContainer.getInventoryDisplayName();
if(localizedName != null) {
this.fontRendererObj.drawString(localizedName.getUnformattedText(), 8, 6, 0x404040);
}
}
protected void drawPlayerInventoryName() {
String localizedName = Minecraft.getMinecraft().thePlayer.inventory.getDisplayName().getUnformattedText();
this.fontRendererObj.drawString(localizedName, 8, this.ySize - 96 + 2, 0x404040);
}
@Override
public void setWorldAndResolution(Minecraft mc, int width, int height) {
super.setWorldAndResolution(mc, width, height);
// workaround for NEIs ASM hax. sigh.
try {
for(GuiModule module : modules) {
module.setWorldAndResolution(mc, width, height);
if(NEI_Manager != null) {
NEI_Manager.set(module, NEI_Manager.get(this));
}
updateSubmodule(module);
}
} catch(IllegalAccessException e) {
Mantle.logger.error(e);
}
}
@Override
public void onResize(Minecraft mc, int width, int height) {
super.onResize(mc, width, height);
for(GuiModule module : modules) {
module.onResize(mc, width, height);
updateSubmodule(module);
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
int oldX = guiLeft;
int oldY = guiTop;
int oldW = xSize;
int oldH = ySize;
guiLeft = cornerX;
guiTop = cornerY;
xSize = realWidth;
ySize = realHeight;
super.drawScreen(mouseX, mouseY, partialTicks);
guiLeft = oldX;
guiTop = oldY;
xSize = oldW;
ySize = oldH;
}
// needed to get the correct slot on clicking
@Override
protected boolean isPointInRegion(int left, int top, int right, int bottom, int pointX, int pointY) {
pointX -= this.cornerX;
pointY -= this.cornerY;
return pointX >= left - 1 && pointX < left + right + 1 && pointY >= top - 1 && pointY < top + bottom + 1;
}
protected void updateSubmodule(GuiModule module) {
module.updatePosition(this.cornerX, this.cornerY, this.realWidth, this.realHeight);
if(module.guiLeft < this.guiLeft) {
this.xSize += this.guiLeft - module.guiLeft;
this.guiLeft = module.guiLeft;
}
if(module.guiTop < this.guiTop) {
this.ySize += this.guiTop - module.guiTop;
this.guiTop = module.guiTop;
}
if(module.guiRight() > this.guiLeft + this.xSize) {
xSize = module.guiRight() - this.guiLeft;
}
if(module.guiBottom() > this.guiTop + this.ySize) {
ySize = module.guiBottom() - this.guiTop;
}
}
@Override
public void drawSlot(Slot slotIn) {
GuiModule module = getModuleForSlot(slotIn.slotNumber);
if(module != null) {
Slot slot = slotIn;
// unwrap for the call to the module
if(slotIn instanceof SlotWrapper) {
slot = ((SlotWrapper) slotIn).parent;
}
if(!module.shouldDrawSlot(slot)) {
return;
}
}
// update slot positions
if(slotIn instanceof SlotWrapper) {
slotIn.xDisplayPosition = ((SlotWrapper) slotIn).parent.xDisplayPosition;
slotIn.yDisplayPosition = ((SlotWrapper) slotIn).parent.yDisplayPosition;
}
super.drawSlot(slotIn);
}
@Override
public boolean isMouseOverSlot(Slot slotIn, int mouseX, int mouseY) {
GuiModule module = getModuleForSlot(slotIn.slotNumber);
// mouse inside the module of the slot?
if(module != null) {
Slot slot = slotIn;
// unwrap for the call to the module
if(slotIn instanceof SlotWrapper) {
slot = ((SlotWrapper) slotIn).parent;
}
if(!module.shouldDrawSlot(slot)) {
return false;
}
}
return super.isMouseOverSlot(slotIn, mouseX, mouseY);
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
GuiModule module = getModuleForPoint(mouseX, mouseY);
if(module != null) {
if(module.handleMouseClicked(mouseX, mouseY, mouseButton)) {
return;
}
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
GuiModule module = getModuleForPoint(mouseX, mouseY);
if(module != null) {
if(module.handleMouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick)) {
return;
}
}
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick);
}
@Override
protected void mouseReleased(int mouseX, int mouseY, int state) {
GuiModule module = getModuleForPoint(mouseX, mouseY);
if(module != null) {
if(module.handleMouseReleased(mouseX, mouseY, state)) {
return;
}
}
super.mouseReleased(mouseX, mouseY, state);
}
protected GuiModule getModuleForPoint(int x, int y) {
for(GuiModule module : modules) {
if(this.isPointInRegion(module.guiLeft, module.guiTop, module.guiRight(), module.guiBottom(),
x + this.cornerX, y + this.cornerY)) {
return module;
}
}
return null;
}
protected GuiModule getModuleForSlot(int slotNumber) {
return getModuleForContainer(getContainer().getSlotContainer(slotNumber));
}
protected GuiModule getModuleForContainer(Container container) {
for(GuiModule module : modules) {
if(module.inventorySlots == container) {
return module;
}
}
return null;
}
protected ContainerMultiModule getContainer() {
return (ContainerMultiModule) inventorySlots;
}
/* NEI INTEGRATION */
@Override
@Optional.Method(modid = "NotEnoughItems")
public VisiblityData modifyVisiblity(GuiContainer guiContainer, VisiblityData visiblityData) {
int x = LayoutManager.stateButtons[0].x + LayoutManager.stateButtons[0].w;
int x2 = LayoutManager.timeButtons[3].x + LayoutManager.timeButtons[3].w;
int y2 = LayoutManager.heal.y + LayoutManager.heal.h;
for(GuiModule module : modules) {
if(x > module.guiLeft) {
visiblityData.showStateButtons = false;
}
if(x2 > module.guiLeft && y2 > module.guiTop) {
visiblityData.showUtilityButtons = false;
}
}
return visiblityData;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public Iterable<Integer> getItemSpawnSlots(GuiContainer guiContainer, ItemStack itemStack) {
return null;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public List<TaggedInventoryArea> getInventoryAreas(GuiContainer guiContainer) {
return Collections.EMPTY_LIST;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public boolean handleDragNDrop(GuiContainer guiContainer, int x, int y, ItemStack itemStack, int k) {
return false;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public boolean hideItemPanelSlot(GuiContainer guiContainer, int x, int y, int w, int h) {
for(GuiModule module : modules) {
// check if the panel overlaps the module (check totally not stolen from stackoverflow)
if(module.guiLeft < x + w && module.guiRight() > x &&
module.guiTop < y + h && module.guiBottom() > y) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,26 @@
package slimeknights.mantle.client.gui;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public abstract class GuiWidget {
public int xPos;
public int yPos;
public int height;
public int width;
public abstract void draw();
/** Where the part will be drawn. Upper left corner. */
public void setPosition(int x, int y) {
this.xPos = x;
this.yPos = y;
}
public void setSize(int width, int height) {
this.width = width;
this.height = height;
}
}
@@ -0,0 +1,232 @@
package slimeknights.mantle.client.gui;
import net.minecraft.util.MathHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Mouse;
// a vertical slider!
@SideOnly(Side.CLIENT)
public class GuiWidgetSlider extends GuiWidget {
// gui info
public final GuiElement slider;
public final GuiElement sliderHighlighted;
public final GuiElement sliderDisabled;
public final GuiElement slideBarTop;
public final GuiElement slideBarBottom;
public final GuiElementScalable slideBar;
// slider info
protected int minValue;
protected int maxValue;
protected int increment;
// positioning info
protected int currentValue;
public int sliderOffset; // x-offset of the slider to the left edge of the slideBar
protected boolean enabled;
protected boolean hidden;
protected boolean isScrolling;
protected boolean isHighlighted;
// where the slider was clicked on the slider itself (not on the bar, on the thing that slides)
private int clickX;
private int clickY;
private boolean clickedBar; // if the bar has already been clicked and not released
public GuiWidgetSlider(GuiElement slider, GuiElement sliderHighlighted, GuiElement sliderDisabled, GuiElement slideBarTop, GuiElement slideBarBottom, GuiElementScalable slideBar) {
this.slider = slider;
this.sliderHighlighted = sliderHighlighted;
this.sliderDisabled = sliderDisabled;
this.slideBar = slideBar;
this.slideBarTop = slideBarTop;
this.slideBarBottom = slideBarBottom;
height = slideBar.h;
width = slideBar.w;
currentValue = minValue = 0;
maxValue = slideBar.h;
increment = 1;
sliderOffset = MathHelper.abs_int(slideBar.w - slider.w) / 2;
isScrolling = false;
isHighlighted = false;
enabled = true;
hidden = false;
}
/** Sets the height of the whole slider and slidebar */
public void setSize(int height) {
this.height = height;
}
/** specifies the values that the slider represents */
public void setSliderParameters(int min, int max, int stepsize) {
this.minValue = min;
this.maxValue = max;
this.increment = stepsize;
// just in case
setSliderValue(currentValue);
}
public int getValue() {
return currentValue;
}
public void enable() {
this.enabled = true;
}
public void disable() {
this.enabled = false;
}
public boolean isEnabled() {
return this.enabled;
}
public void hide() {
this.hidden = true;
}
public void show() {
this.hidden = false;
}
public boolean isHidden() {
return this.hidden;
}
public void draw() {
if(hidden) {
return;
}
// slidebar background
slideBarTop.draw(xPos, yPos);
slideBar.drawScaledY(xPos, yPos + slideBarTop.h, getUsableSlidebarHeight());
slideBarBottom.draw(xPos, yPos + height - slideBarBottom.h);
int x = xPos + sliderOffset;
int y = yPos + getSliderTop();
// the slider depending on state
if(enabled) {
if(isScrolling) {
sliderDisabled.draw(x, y);
}
else if(isHighlighted) {
sliderHighlighted.draw(x, y);
}
else {
slider.draw(x, y);
}
}
}
public void update(int mouseX, int mouseY) {
if(!enabled || hidden) {
return;
}
boolean mouseDown = Mouse.isButtonDown(0); // left mouse button
// relative position inside the widget
int x = mouseX - xPos;
int y = mouseY - yPos;
// reset click data
if(!mouseDown && clickedBar) {
clickedBar = false;
}
// button not pressed and scrolling -> stop scrolling
if(!mouseDown && isScrolling) {
isScrolling = false;
}
// button pressed and scrolling -> update position of slider
else if(isScrolling) {
float d = maxValue - minValue;
float val = (float) (y - clickY) / (float) (getUsableSlidebarHeight() - slider.h);
val *= d;
if(val < (float) increment / 2f) {
// < 1/2 increment
setSliderValue(minValue);
}
else if(val > maxValue - ((float) increment / 2f)) {
// > max-1/2 increment
setSliderValue(maxValue);
}
else {
// in between
setSliderValue((int) (minValue + (float) increment * Math.round(val)));
}
}
// not scrolling yet but possibly inside the slider
else if(x >= 0 && y >= getSliderTop() &&
x - sliderOffset <= slider.w && y <= getSliderTop() + slider.h) {
isHighlighted = true;
if(mouseDown) {
isScrolling = true;
clickX = x - sliderOffset;
clickY = y - getSliderTop();
}
}
// not on the slider but clicked on the bar
else if(mouseDown && !clickedBar &&
x >= 0 && y >= 0 &&
x <= slideBar.w && y <= height) {
if(y < getSliderTop()) {
decrement();
}
else {
increment();
}
clickedBar = true;
}
else {
isHighlighted = false;
}
}
public int increment() {
setSliderValue(currentValue + increment);
return currentValue;
}
public int decrement() {
setSliderValue(currentValue - increment);
return currentValue;
}
public int setSliderValue(int val) {
if(val > maxValue) {
val = maxValue;
}
else if(val < minValue) {
val = minValue;
}
currentValue = val;
return currentValue;
}
private int getSliderTop() {
float d = maxValue - minValue;
d = (float) (currentValue - minValue) / d;
d *= getUsableSlidebarHeight() - slider.h;
return (int) d + slideBarTop.h;
}
private int getUsableSlidebarHeight() {
return height - slideBarTop.h - slideBarBottom.h;
}
}
@@ -0,0 +1,171 @@
package slimeknights.mantle.client.gui;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Mouse;
import java.util.List;
@SideOnly(Side.CLIENT)
public class GuiWidgetTabs extends GuiWidget {
private static final ResourceLocation
creativeInventoryTabs = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png");
private final GuiElement[] tabActive = new GuiElement[3];
private final GuiElement[] tab = new GuiElement[3];
// change this if you need different tabs
public ResourceLocation tabsResource = creativeInventoryTabs;
// changes the y-offset of the tab row
public int yOffset = 4;
// space between 2 tabs
public int spacing = 2;
public int selected;
public int highlighted;
protected List<ItemStack> icons = Lists.newArrayList();
private final GuiMultiModule parent;
private boolean clicked = false;
public GuiWidgetTabs(GuiMultiModule parent, GuiElement tabLeft, GuiElement tabCenter, GuiElement tabRight, GuiElement activeLeft, GuiElement activeCenter, GuiElement activeRight) {
this.parent = parent;
this.tab[0] = tabLeft;
this.tab[1] = tabCenter;
this.tab[2] = tabRight;
this.tabActive[0] = activeLeft;
this.tabActive[1] = activeCenter;
this.tabActive[2] = activeRight;
selected = 0;
}
public void addTab(ItemStack icon) {
icons.add(icon);
}
public void clear() {
selected = 0;
icons.clear();
}
public void update(int mouseX, int mouseY) {
boolean mouseDown = Mouse.isButtonDown(0); // left mouse button
// did we click on a tab?
mouseX -= this.xPos;
mouseY -= this.yPos;
// update highlighted
highlighted = -1;
if(mouseY >= 0 && mouseY <= tab[1].h) {
// which one did we click?
int x = 0;
for(int i = 0; i < icons.size(); i++) {
// clicking on spacing has no effect
if(mouseX >= x && mouseX < x + tab[1].w) {
highlighted = i;
break;
}
x += tab[1].w;
x += spacing;
}
}
// already clicked
if(clicked) {
// still clicking
if(mouseDown) {
return;
}
// release click
else {
clicked = false;
return;
}
}
// new click
else if(mouseDown) {
clicked = true;
}
// no click - do nothing
else {
return;
}
// was new click, select highlighted
if(highlighted > -1) {
selected = highlighted;
}
}
@Override
public void draw() {
int y = yPos + yOffset;
for(int i = 0; i < icons.size(); i++) {
int x = xPos + i * tab[0].w;
if(i > 0) {
x += i * spacing;
}
GuiElement[] toDraw;
if(i == selected) {
toDraw = tabActive;
}
else {
toDraw = tab;
}
GuiElement actualTab;
if(i == 0 && x == parent.cornerX) {
actualTab = toDraw[0];
}
else if(x == parent.cornerX + parent.width) {
actualTab = toDraw[2];
}
else {
actualTab = toDraw[1];
}
// todo: draw all the tabs first and then all the itemstacks so it doesn't have to switch texture in between all the time
// rebind texture from drawing an itemstack
Minecraft.getMinecraft().getTextureManager().bindTexture(tabsResource);
actualTab.draw(x, y);
ItemStack icon = icons.get(i);
if(icon != null) {
RenderHelper.enableGUIStandardItemLighting();
drawItemStack(icon, x + (actualTab.w - 16) / 2, y + (actualTab.h - 16) / 2);
RenderHelper.disableStandardItemLighting();
//RenderHelper.enableStandardItemLighting();
}
}
}
// guiContainer.drawItemStack
private void drawItemStack(ItemStack stack, int x, int y) {
RenderItem itemRender = Minecraft.getMinecraft().getRenderItem();
GlStateManager.translate(0.0F, 0.0F, 32.0F);
itemRender.zLevel = 200;
//FontRenderer font = stack.getItem().getFontRenderer(stack);
itemRender.renderItemAndEffectIntoGUI(stack, x, y);
//this.itemRender.renderItemOverlayIntoGUI(font, stack, x, y - (this.draggedStack == null ? 0 : 8), altText);
//this.zLevel = 0.0F;
itemRender.zLevel = 0.0F;
}
}
@@ -0,0 +1,87 @@
package slimeknights.mantle.client.model;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.IFlexibleBakedModel;
import net.minecraftforge.client.model.IPerspectiveAwareModel;
import net.minecraftforge.client.model.TRSRTransformation;
import org.apache.commons.lang3.tuple.Pair;
import java.util.List;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
/**
* Takes a blockmodel and applies the standard-block-perspective for third_person to it
*/
public class BlockItemModelWrapper implements IPerspectiveAwareModel, IFlexibleBakedModel {
// copied from the forge variants V1 default-block transform
public static final Matrix4f THIRD_PERSON_BLOCK_TRANSFORM = new TRSRTransformation(
new Vector3f(0, 1.5f / 16, -2.75f / 16), // translation
TRSRTransformation.quatFromYXZDegrees(new Vector3f(10, -45, 170)), // rotation
new Vector3f(0.375f, 0.375f, 0.375f), // scale
null).getMatrix();
private final IFlexibleBakedModel parent;
public BlockItemModelWrapper(IFlexibleBakedModel parent) {
this.parent = parent;
}
@Override
public Pair<IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) {
Matrix4f matrix = null;
// fix transformation in hand
if(cameraTransformType == ItemCameraTransforms.TransformType.THIRD_PERSON) {
matrix = THIRD_PERSON_BLOCK_TRANSFORM;
}
return Pair.of((IBakedModel) this, matrix);
}
@Override
public List getFaceQuads(EnumFacing p_177551_1_) {
return parent.getFaceQuads(p_177551_1_);
}
@Override
public List getGeneralQuads() {
return parent.getGeneralQuads();
}
@Override
public VertexFormat getFormat() {
return parent.getFormat();
}
@Override
public boolean isAmbientOcclusion() {
return false;
}
@Override
public boolean isGui3d() {
return parent.isGui3d();
}
@Override
public boolean isBuiltInRenderer() {
return parent.isBuiltInRenderer();
}
@Override
public TextureAtlasSprite getTexture() {
return parent.getTexture();
}
@Override
public ItemCameraTransforms getItemCameraTransforms() {
return parent.getItemCameraTransforms();
}
}
@@ -0,0 +1,139 @@
package slimeknights.mantle.client.model;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.IFlexibleBakedModel;
import net.minecraftforge.client.model.TRSRTransformation;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
// for those wondering TRSR stands for Translation Rotation Scale Rotation
public class TRSRBakedModel implements IFlexibleBakedModel {
protected final ImmutableList<BakedQuad> general;
protected final ImmutableMap<EnumFacing, ImmutableList<BakedQuad>> faces;
protected final IFlexibleBakedModel original;
public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float scale) {
this(original, x, y, z, 0, 0, 0, scale, scale, scale);
}
public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scale) {
this(original, x, y, z, rotX, rotY, rotZ, scale, scale, scale);
}
public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scaleX, float scaleY, float scaleZ) {
this(original, new TRSRTransformation(new Vector3f(x, y, z),
null,
new Vector3f(scaleX, scaleY, scaleZ),
TRSRTransformation.quatFromYXZ(rotY, rotX, rotZ)));
}
public TRSRBakedModel(IFlexibleBakedModel original, TRSRTransformation transform) {
this.original = original;
ImmutableList.Builder<BakedQuad> builder;
builder = ImmutableList.builder();
transform = TRSRTransformation.blockCenterToCorner(transform);
// face quads
EnumMap<EnumFacing, ImmutableList<BakedQuad>> faces = Maps.newEnumMap(EnumFacing.class);
for(EnumFacing face : EnumFacing.values()) {
for(BakedQuad quad : original.getFaceQuads(face)) {
builder.add(transform(transform, quad, original.getFormat()));
}
//faces.put(face, builder.build());
faces.put(face, ImmutableList.<BakedQuad>of());
}
// general quads
//builder = ImmutableList.builder();
for(BakedQuad quad : original.getGeneralQuads()) {
builder.add(transform(transform, quad, original.getFormat()));
}
this.general = builder.build();
this.faces = Maps.immutableEnumMap(faces);
}
public static BakedQuad transform(TRSRTransformation transform, BakedQuad quad, VertexFormat format) {
for(VertexFormatElement e : (List<VertexFormatElement>) format.getElements()) {
if(e.getUsage() == VertexFormatElement.EnumUsage.POSITION) {
if(e.getType() != VertexFormatElement.EnumType.FLOAT) {
throw new IllegalArgumentException("can only transform float position");
}
int[] data = Arrays.copyOf(quad.getVertexData(), quad.getVertexData().length);
// once for each vertex
for(int j = 0; j < 4; j++) {
int v = j * format.getNextOffset() / 4;
float[] pos = new float[]{0f, 0f, 0f, 1f};
for(int i = 0; i < Math.min(4, e.getElementCount()); i++) {
pos[i] = Float.intBitsToFloat(data[v + e.getOffset() / 4 + i]);
}
Vector4f vec = new Vector4f(pos);
transform.getMatrix().transform(vec);
vec.get(pos);
for(int i = 0; i < Math.min(4, e.getElementCount()); i++) {
data[v + e.getOffset() / 4 + i] = Float.floatToRawIntBits(pos[i]);
}
}
return new BakedQuad(data, quad.getTintIndex(), quad.getFace());
}
}
return quad;
}
@Override
public List<BakedQuad> getFaceQuads(EnumFacing side) {
return faces.get(side);
}
@Override
public List<BakedQuad> getGeneralQuads() {
return general;
}
@Override
public boolean isAmbientOcclusion() {
return false;
}
@Override
public boolean isGui3d() {
return original.isGui3d();
}
@Override
public boolean isBuiltInRenderer() {
return original.isBuiltInRenderer();
}
@Override
public TextureAtlasSprite getTexture() {
return original.getTexture();
}
@Override
public ItemCameraTransforms getItemCameraTransforms() {
return original.getItemCameraTransforms();
}
@Override
public VertexFormat getFormat() {
return original.getFormat();
}
}
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more