diff --git a/.gitignore b/.gitignore index 0cacaee..248f529 100644 --- a/.gitignore +++ b/.gitignore @@ -27,4 +27,5 @@ version.properties /*.classpath /*.project /.settings/ -/*.launch \ No newline at end of file +/*.launch +/out \ No newline at end of file diff --git a/build.gradle b/build.gradle index be35c95..162ddf1 100644 --- a/build.gradle +++ b/build.gradle @@ -32,6 +32,14 @@ repositories { name 'ForgeFS' url 'http://files.minecraftforge.net/maven' } + maven { + name 'CB Maven FS' + url "http://chickenbones.net/maven/" + } + maven { + name 'forge' + url 'http://files.minecraftforge.net/maven' + } } group = 'mantle' @@ -82,6 +90,12 @@ minecraft { replace '${version}', project.version } +dependencies { + compile "codechicken:CodeChickenLib:${config.minecraft_version}-${config.CCLIB_version}:dev" + compile "codechicken:CodeChickenCore:${config.minecraft_version}-${config.ccc_version}:dev" + compile "codechicken:NotEnoughItems:${config.minecraft_version}-${config.NEI_version}:dev" +} + processResources { inputs.property "version", artifact_version diff --git a/build.properties b/build.properties index 30fae23..330a922 100644 --- a/build.properties +++ b/build.properties @@ -1,5 +1,8 @@ -mod_version=0.4 +mod_version=0.5 minecraft_version=1.8 forge_version=11.14.3.1514 mappings=snapshot_20150918 +CCLIB_version=1.1.2.133 +ccc_version=1.0.5.36 +NEI_version=1.0.5.104 \ No newline at end of file diff --git a/src/main/java/mantle/Mantle.java b/src/main/java/mantle/Mantle.java deleted file mode 100644 index 34ab38f..0000000 --- a/src/main/java/mantle/Mantle.java +++ /dev/null @@ -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 - */ -@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(); - } - -} diff --git a/src/main/java/mantle/blocks/BlockUtils.java b/src/main/java/mantle/blocks/BlockUtils.java deleted file mode 100644 index b6c0523..0000000 --- a/src/main/java/mantle/blocks/BlockUtils.java +++ /dev/null @@ -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); - } - -} diff --git a/src/main/java/mantle/blocks/MantleBlock.java b/src/main/java/mantle/blocks/MantleBlock.java deleted file mode 100644 index 552909e..0000000 --- a/src/main/java/mantle/blocks/MantleBlock.java +++ /dev/null @@ -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 - */ -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); - } - -} diff --git a/src/main/java/mantle/blocks/abstracts/AdaptiveInventoryLogic.java b/src/main/java/mantle/blocks/abstracts/AdaptiveInventoryLogic.java deleted file mode 100644 index 3f91f76..0000000 --- a/src/main/java/mantle/blocks/abstracts/AdaptiveInventoryLogic.java +++ /dev/null @@ -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(); - } -} diff --git a/src/main/java/mantle/blocks/abstracts/ExpandableInventoryLogic.java b/src/main/java/mantle/blocks/abstracts/ExpandableInventoryLogic.java deleted file mode 100644 index 33e46db..0000000 --- a/src/main/java/mantle/blocks/abstracts/ExpandableInventoryLogic.java +++ /dev/null @@ -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 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(); - 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 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; - } - -} diff --git a/src/main/java/mantle/blocks/abstracts/InventoryBlock.java b/src/main/java/mantle/blocks/abstracts/InventoryBlock.java deleted file mode 100644 index 140f2f8..0000000 --- a/src/main/java/mantle/blocks/abstracts/InventoryBlock.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/blocks/abstracts/InventoryLogic.java b/src/main/java/mantle/blocks/abstracts/InventoryLogic.java deleted file mode 100644 index 9bc1099..0000000 --- a/src/main/java/mantle/blocks/abstracts/InventoryLogic.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/blocks/abstracts/InventorySlab.java b/src/main/java/mantle/blocks/abstracts/InventorySlab.java deleted file mode 100644 index 47869dd..0000000 --- a/src/main/java/mantle/blocks/abstracts/InventorySlab.java +++ /dev/null @@ -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; - } -} diff --git a/src/main/java/mantle/blocks/abstracts/MultiItemBlock.java b/src/main/java/mantle/blocks/abstracts/MultiItemBlock.java deleted file mode 100644 index e515bf6..0000000 --- a/src/main/java/mantle/blocks/abstracts/MultiItemBlock.java +++ /dev/null @@ -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(); - } - } - -} diff --git a/src/main/java/mantle/blocks/iface/IActiveLogic.java b/src/main/java/mantle/blocks/iface/IActiveLogic.java deleted file mode 100644 index 51e7e5c..0000000 --- a/src/main/java/mantle/blocks/iface/IActiveLogic.java +++ /dev/null @@ -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); -} diff --git a/src/main/java/mantle/blocks/iface/ICrop.java b/src/main/java/mantle/blocks/iface/ICrop.java deleted file mode 100644 index 9473de2..0000000 --- a/src/main/java/mantle/blocks/iface/ICrop.java +++ /dev/null @@ -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 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 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); -} diff --git a/src/main/java/mantle/blocks/iface/IFacingLogic.java b/src/main/java/mantle/blocks/iface/IFacingLogic.java deleted file mode 100644 index ae1c76d..0000000 --- a/src/main/java/mantle/blocks/iface/IFacingLogic.java +++ /dev/null @@ -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); - -} diff --git a/src/main/java/mantle/blocks/util/IBlockWithVariants.java b/src/main/java/mantle/blocks/util/IBlockWithVariants.java deleted file mode 100644 index 4c56312..0000000 --- a/src/main/java/mantle/blocks/util/IBlockWithVariants.java +++ /dev/null @@ -1,8 +0,0 @@ -package mantle.blocks.util; - -import net.minecraft.item.ItemStack; - -public interface IBlockWithVariants -{ - String getVariantNameFromStack(ItemStack stack); -} diff --git a/src/main/java/mantle/blocks/util/ItemBlockVariants.java b/src/main/java/mantle/blocks/util/ItemBlockVariants.java deleted file mode 100644 index eff4004..0000000 --- a/src/main/java/mantle/blocks/util/ItemBlockVariants.java +++ /dev/null @@ -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); - } - -} diff --git a/src/main/java/mantle/blocks/util/blockstates/BlockVariant.java b/src/main/java/mantle/blocks/util/blockstates/BlockVariant.java deleted file mode 100644 index 83b01a7..0000000 --- a/src/main/java/mantle/blocks/util/blockstates/BlockVariant.java +++ /dev/null @@ -1,36 +0,0 @@ -package mantle.blocks.util.blockstates; - -public class BlockVariant implements Comparable -{ - 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(); - } -} diff --git a/src/main/java/mantle/blocks/util/blockstates/PropertyVariant.java b/src/main/java/mantle/blocks/util/blockstates/PropertyVariant.java deleted file mode 100644 index 8e9570a..0000000 --- a/src/main/java/mantle/blocks/util/blockstates/PropertyVariant.java +++ /dev/null @@ -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 metaMap; - - protected PropertyVariant(String name, BlockVariant... variants) - { - this.name = name; - this.metaMap = new HashMap(); - - 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 getAllowedValues() - { - return this.metaMap.values(); - } - - @Override - public Class 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; - } - -} diff --git a/src/main/java/mantle/books/BookData.java b/src/main/java/mantle/books/BookData.java deleted file mode 100644 index 09fa53e..0000000 --- a/src/main/java/mantle/books/BookData.java +++ /dev/null @@ -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; - } - -} diff --git a/src/main/java/mantle/books/BookDataStore.java b/src/main/java/mantle/books/BookDataStore.java deleted file mode 100644 index 7129607..0000000 --- a/src/main/java/mantle/books/BookDataStore.java +++ /dev/null @@ -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 data = HashBiMap.create(); - - private static HashBiMap intMap = HashBiMap.create(); - - private static List 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 getZipBooks() - { - return zipBooks; - } -} diff --git a/src/main/java/mantle/books/ManualReader.java b/src/main/java/mantle/books/ManualReader.java deleted file mode 100644 index 6b2ac49..0000000 --- a/src/main/java/mantle/books/ManualReader.java +++ /dev/null @@ -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; - } - } -} diff --git a/src/main/java/mantle/books/client/BookImage.java b/src/main/java/mantle/books/client/BookImage.java deleted file mode 100644 index 62c42b4..0000000 --- a/src/main/java/mantle/books/client/BookImage.java +++ /dev/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; - } -} diff --git a/src/main/java/mantle/books/external/BookIS.java b/src/main/java/mantle/books/external/BookIS.java deleted file mode 100644 index e38af7f..0000000 --- a/src/main/java/mantle/books/external/BookIS.java +++ /dev/null @@ -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; - } - -} diff --git a/src/main/java/mantle/books/external/BookLoad.java b/src/main/java/mantle/books/external/BookLoad.java deleted file mode 100644 index 6ef315c..0000000 --- a/src/main/java/mantle/books/external/BookLoad.java +++ /dev/null @@ -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; - -} diff --git a/src/main/java/mantle/books/external/ZipLoader.java b/src/main/java/mantle/books/external/ZipLoader.java deleted file mode 100644 index 3bc19bb..0000000 --- a/src/main/java/mantle/books/external/ZipLoader.java +++ /dev/null @@ -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 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 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; - } -} diff --git a/src/main/java/mantle/client/MProxyClient.java b/src/main/java/mantle/client/MProxyClient.java deleted file mode 100644 index dc13871..0000000 --- a/src/main/java/mantle/client/MProxyClient.java +++ /dev/null @@ -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> pageClasses = new HashMap>(); - - public static void registerManualPage(String type, Class clazz) - { - pageClasses.put(type, clazz); - } - - public static Class 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)); - } -} diff --git a/src/main/java/mantle/client/ModelHelper.java b/src/main/java/mantle/client/ModelHelper.java deleted file mode 100644 index aca485c..0000000 --- a/src/main/java/mantle/client/ModelHelper.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/client/ModelVariant.java b/src/main/java/mantle/client/ModelVariant.java deleted file mode 100644 index 7a4c4a4..0000000 --- a/src/main/java/mantle/client/ModelVariant.java +++ /dev/null @@ -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 list = new ArrayList(); - item.getSubItems(item, tab, list); - for (ItemStack i : list) - { - this.registerItemModel(item, i.getItemDamage(), item.getUnlocalizedName().substring(5)); - } - } -} diff --git a/src/main/java/mantle/client/gui/GuiManual.java b/src/main/java/mantle/client/gui/GuiManual.java deleted file mode 100644 index b3f8aa1..0000000 --- a/src/main/java/mantle/client/gui/GuiManual.java +++ /dev/null @@ -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 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 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; - } -} diff --git a/src/main/java/mantle/client/gui/TurnPageButton.java b/src/main/java/mantle/client/gui/TurnPageButton.java deleted file mode 100644 index f5a7fb2..0000000 --- a/src/main/java/mantle/client/gui/TurnPageButton.java +++ /dev/null @@ -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); - } - } -} diff --git a/src/main/java/mantle/client/pages/BlankPage.java b/src/main/java/mantle/client/pages/BlankPage.java deleted file mode 100644 index 8815653..0000000 --- a/src/main/java/mantle/client/pages/BlankPage.java +++ /dev/null @@ -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) - { - } - -} diff --git a/src/main/java/mantle/client/pages/BookPage.java b/src/main/java/mantle/client/pages/BookPage.java deleted file mode 100644 index 8667107..0000000 --- a/src/main/java/mantle/client/pages/BookPage.java +++ /dev/null @@ -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); -} diff --git a/src/main/java/mantle/client/pages/ContentsTablePage.java b/src/main/java/mantle/client/pages/ContentsTablePage.java deleted file mode 100644 index a27f39f..0000000 --- a/src/main/java/mantle/client/pages/ContentsTablePage.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/client/pages/CraftingPage.java b/src/main/java/mantle/client/pages/CraftingPage.java deleted file mode 100644 index 0af7be8..0000000 --- a/src/main/java/mantle/client/pages/CraftingPage.java +++ /dev/null @@ -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); - } - } - -} diff --git a/src/main/java/mantle/client/pages/FurnacePage.java b/src/main/java/mantle/client/pages/FurnacePage.java deleted file mode 100644 index e58ec75..0000000 --- a/src/main/java/mantle/client/pages/FurnacePage.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/client/pages/PicturePage.java b/src/main/java/mantle/client/pages/PicturePage.java deleted file mode 100644 index b63edc8..0000000 --- a/src/main/java/mantle/client/pages/PicturePage.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/client/pages/SectionPage.java b/src/main/java/mantle/client/pages/SectionPage.java deleted file mode 100644 index 972f580..0000000 --- a/src/main/java/mantle/client/pages/SectionPage.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/client/pages/SidebarPage.java b/src/main/java/mantle/client/pages/SidebarPage.java deleted file mode 100644 index adb4ad6..0000000 --- a/src/main/java/mantle/client/pages/SidebarPage.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/client/pages/TextPage.java b/src/main/java/mantle/client/pages/TextPage.java deleted file mode 100644 index 09e7fbe..0000000 --- a/src/main/java/mantle/client/pages/TextPage.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/client/pages/TitlePage.java b/src/main/java/mantle/client/pages/TitlePage.java deleted file mode 100644 index fdc9590..0000000 --- a/src/main/java/mantle/client/pages/TitlePage.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/common/ComparisonHelper.java b/src/main/java/mantle/common/ComparisonHelper.java deleted file mode 100644 index 55a8fba..0000000 --- a/src/main/java/mantle/common/ComparisonHelper.java +++ /dev/null @@ -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(); - } -} diff --git a/src/main/java/mantle/common/IDDumps.java b/src/main/java/mantle/common/IDDumps.java deleted file mode 100644 index 4e9da89..0000000 --- a/src/main/java/mantle/common/IDDumps.java +++ /dev/null @@ -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()); - } - } - } - } - -} diff --git a/src/main/java/mantle/common/MProxyCommon.java b/src/main/java/mantle/common/MProxyCommon.java deleted file mode 100644 index 5efc875..0000000 --- a/src/main/java/mantle/common/MProxyCommon.java +++ /dev/null @@ -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() - { - } -} diff --git a/src/main/java/mantle/common/network/AbstractPacket.java b/src/main/java/mantle/common/network/AbstractPacket.java deleted file mode 100644 index 39d0151..0000000 --- a/src/main/java/mantle/common/network/AbstractPacket.java +++ /dev/null @@ -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); -} diff --git a/src/main/java/mantle/common/network/PacketUpdateTE.java b/src/main/java/mantle/common/network/PacketUpdateTE.java deleted file mode 100644 index 18ecd13..0000000 --- a/src/main/java/mantle/common/network/PacketUpdateTE.java +++ /dev/null @@ -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) - { - } - -} diff --git a/src/main/java/mantle/crash/CallableSuppConfig.java b/src/main/java/mantle/crash/CallableSuppConfig.java deleted file mode 100644 index 089033c..0000000 --- a/src/main/java/mantle/crash/CallableSuppConfig.java +++ /dev/null @@ -1,32 +0,0 @@ -package mantle.crash; - -import net.minecraftforge.fml.common.ICrashCallable; - -/** - * Crash Callable for supported environments. - * - * @author Sunstrike - */ -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"; - } - -} diff --git a/src/main/java/mantle/crash/CallableUnsuppConfig.java b/src/main/java/mantle/crash/CallableUnsuppConfig.java deleted file mode 100644 index 5e0b0bb..0000000 --- a/src/main/java/mantle/crash/CallableUnsuppConfig.java +++ /dev/null @@ -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 modIds; - - public CallableUnsuppConfig(String modId, List 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; - } - -} diff --git a/src/main/java/mantle/debug/DebugData.java b/src/main/java/mantle/debug/DebugData.java deleted file mode 100644 index 94b6a4c..0000000 --- a/src/main/java/mantle/debug/DebugData.java +++ /dev/null @@ -1,28 +0,0 @@ -package mantle.debug; - -import net.minecraft.entity.player.EntityPlayer; - -/** - * Encapsulation for debug information - * - * @author Sunstrike - */ -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; - } - -} diff --git a/src/main/java/mantle/debug/DebugHelper.java b/src/main/java/mantle/debug/DebugHelper.java deleted file mode 100644 index 88c4c30..0000000 --- a/src/main/java/mantle/debug/DebugHelper.java +++ /dev/null @@ -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 - */ -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); - } - } - -} diff --git a/src/main/java/mantle/debug/IDebuggable.java b/src/main/java/mantle/debug/IDebuggable.java deleted file mode 100644 index 8f3fee9..0000000 --- a/src/main/java/mantle/debug/IDebuggable.java +++ /dev/null @@ -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 - */ -public interface IDebuggable -{ - - public DebugData getDebugInfo(EntityPlayer player); - -} diff --git a/src/main/java/mantle/event/ManualOpenEvent.java b/src/main/java/mantle/event/ManualOpenEvent.java deleted file mode 100644 index 8c3bf34..0000000 --- a/src/main/java/mantle/event/ManualOpenEvent.java +++ /dev/null @@ -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); - } - } -} diff --git a/src/main/java/mantle/event/Migration.java b/src/main/java/mantle/event/Migration.java deleted file mode 100644 index 699dfa4..0000000 --- a/src/main/java/mantle/event/Migration.java +++ /dev/null @@ -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 remapItem = Maps.newHashMap(); - - Map remapBlock = Maps.newHashMap(); - - List 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 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 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 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 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); - } - - } - } -} diff --git a/src/main/java/mantle/items/ItemUtils.java b/src/main/java/mantle/items/ItemUtils.java deleted file mode 100644 index c8ac743..0000000 --- a/src/main/java/mantle/items/ItemUtils.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/items/Manual.java b/src/main/java/mantle/items/Manual.java deleted file mode 100644 index 84194cb..0000000 --- a/src/main/java/mantle/items/Manual.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/items/abstracts/CraftingItem.java b/src/main/java/mantle/items/abstracts/CraftingItem.java deleted file mode 100644 index c54d848..0000000 --- a/src/main/java/mantle/items/abstracts/CraftingItem.java +++ /dev/null @@ -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)); - } - } - } - -} diff --git a/src/main/java/mantle/items/iface/IDebugItem.java b/src/main/java/mantle/items/iface/IDebugItem.java deleted file mode 100644 index bfb30fa..0000000 --- a/src/main/java/mantle/items/iface/IDebugItem.java +++ /dev/null @@ -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. -} diff --git a/src/main/java/mantle/lib/CoreConfig.java b/src/main/java/mantle/lib/CoreConfig.java deleted file mode 100644 index e0e5d20..0000000 --- a/src/main/java/mantle/lib/CoreConfig.java +++ /dev/null @@ -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 - */ -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; - -} diff --git a/src/main/java/mantle/lib/CoreRepo.java b/src/main/java/mantle/lib/CoreRepo.java deleted file mode 100644 index 7419f54..0000000 --- a/src/main/java/mantle/lib/CoreRepo.java +++ /dev/null @@ -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 - */ -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"); - -} diff --git a/src/main/java/mantle/lib/TabTools.java b/src/main/java/mantle/lib/TabTools.java deleted file mode 100644 index fe93f97..0000000 --- a/src/main/java/mantle/lib/TabTools.java +++ /dev/null @@ -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(); - } -} diff --git a/src/main/java/mantle/lib/client/MantleClientRegistry.java b/src/main/java/mantle/lib/client/MantleClientRegistry.java deleted file mode 100644 index e8b1e9b..0000000 --- a/src/main/java/mantle/lib/client/MantleClientRegistry.java +++ /dev/null @@ -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 manualIcons = Maps.newHashMap(); - - public static Map recipeIcons = Maps.newHashMap(); - - public static HashMap 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); - } - -} diff --git a/src/main/java/mantle/lib/environment/EnvironmentChecks.java b/src/main/java/mantle/lib/environment/EnvironmentChecks.java deleted file mode 100644 index 1ad9f01..0000000 --- a/src/main/java/mantle/lib/environment/EnvironmentChecks.java +++ /dev/null @@ -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 - */ -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 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); - } - } - -} diff --git a/src/main/java/mantle/math/Dozenal.java b/src/main/java/mantle/math/Dozenal.java deleted file mode 100644 index ea8ec13..0000000 --- a/src/main/java/mantle/math/Dozenal.java +++ /dev/null @@ -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 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'; - } -} diff --git a/src/main/java/mantle/player/PlayerUtils.java b/src/main/java/mantle/player/PlayerUtils.java deleted file mode 100644 index e97ffa4..0000000 --- a/src/main/java/mantle/player/PlayerUtils.java +++ /dev/null @@ -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)); - } - } - -} diff --git a/src/main/java/mantle/pulsar/config/ForgeCFG.java b/src/main/java/mantle/pulsar/config/ForgeCFG.java deleted file mode 100644 index c75e344..0000000 --- a/src/main/java/mantle/pulsar/config/ForgeCFG.java +++ /dev/null @@ -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(); - } - } - -} diff --git a/src/main/java/mantle/pulsar/config/IConfiguration.java b/src/main/java/mantle/pulsar/config/IConfiguration.java deleted file mode 100644 index cf14e24..0000000 --- a/src/main/java/mantle/pulsar/config/IConfiguration.java +++ /dev/null @@ -1,31 +0,0 @@ -package mantle.pulsar.config; - -import mantle.pulsar.pulse.PulseMeta; - -/** - * Interface for config handlers. - * - * @author Arkan - */ -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(); - -} diff --git a/src/main/java/mantle/pulsar/control/PulseManager.java b/src/main/java/mantle/pulsar/control/PulseManager.java deleted file mode 100644 index 08e512a..0000000 --- a/src/main/java/mantle/pulsar/control/PulseManager.java +++ /dev/null @@ -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 - */ -@SuppressWarnings("unused") -public class PulseManager -{ - - private ILogger log; - - private final boolean useConfig; - - private final LinkedHashMap pulses = new LinkedHashMap(); - - 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 entry : this.pulses.entrySet()) - { - if (entry.getValue().getId().equals(pulseId)) - { - return true; - } - } - return false; - } - - public Collection 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 + "]"; - } -} diff --git a/src/main/java/mantle/pulsar/debug/EventSpy.java b/src/main/java/mantle/pulsar/debug/EventSpy.java deleted file mode 100644 index 36d11aa..0000000 --- a/src/main/java/mantle/pulsar/debug/EventSpy.java +++ /dev/null @@ -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 - */ -@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); - } - -} diff --git a/src/main/java/mantle/pulsar/internal/Configuration.java b/src/main/java/mantle/pulsar/internal/Configuration.java deleted file mode 100644 index 44769e9..0000000 --- a/src/main/java/mantle/pulsar/internal/Configuration.java +++ /dev/null @@ -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 - */ -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 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(); - 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 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(); - } - } - - private Map parseV0Config(File f) throws Exception - { - try - { - JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f))); - Map m = gson.fromJson(reader, new TypeToken>() - { - }.getType()); // NASTY! - if (m == null) - { - throw new NullPointerException("Gson returned null."); - } - Map out = new HashMap(); - for (Map.Entry 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 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 modules; - - public GsonConfig(int version, Map modules) - { - this.CONFIG_VERSION = version; - this.modules = modules; - } - - public int getConfigVersion() - { - return this.CONFIG_VERSION; - } - - public Map getModules() - { - return this.modules; - } - - } - -} diff --git a/src/main/java/mantle/pulsar/internal/CrashHandler.java b/src/main/java/mantle/pulsar/internal/CrashHandler.java deleted file mode 100644 index aa9233d..0000000 --- a/src/main/java/mantle/pulsar/internal/CrashHandler.java +++ /dev/null @@ -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 - */ -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"; - } - } - } - -} diff --git a/src/main/java/mantle/pulsar/internal/logging/ILogger.java b/src/main/java/mantle/pulsar/internal/logging/ILogger.java deleted file mode 100644 index d1b38d6..0000000 --- a/src/main/java/mantle/pulsar/internal/logging/ILogger.java +++ /dev/null @@ -1,24 +0,0 @@ -package mantle.pulsar.internal.logging; - -/** - * Interface for log wrappers. - * - * @author Arkan - */ -@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); - -} diff --git a/src/main/java/mantle/pulsar/internal/logging/JULLogger.java b/src/main/java/mantle/pulsar/internal/logging/JULLogger.java deleted file mode 100644 index b632936..0000000 --- a/src/main/java/mantle/pulsar/internal/logging/JULLogger.java +++ /dev/null @@ -1,56 +0,0 @@ -package mantle.pulsar.internal.logging; - -import java.util.logging.Logger; - -/** - * Java logger wrapper. - * - * @author Arkan - */ -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. - } - -} diff --git a/src/main/java/mantle/pulsar/internal/logging/Log4jLogger.java b/src/main/java/mantle/pulsar/internal/logging/Log4jLogger.java deleted file mode 100644 index ab6c80d..0000000 --- a/src/main/java/mantle/pulsar/internal/logging/Log4jLogger.java +++ /dev/null @@ -1,56 +0,0 @@ -package mantle.pulsar.internal.logging; - -import org.apache.logging.log4j.Logger; - -/** - * Log4j log wrapper. - * - * @author Arkan - */ -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); - } - -} diff --git a/src/main/java/mantle/pulsar/internal/logging/LogManager.java b/src/main/java/mantle/pulsar/internal/logging/LogManager.java deleted file mode 100644 index 16b2ba9..0000000 --- a/src/main/java/mantle/pulsar/internal/logging/LogManager.java +++ /dev/null @@ -1,53 +0,0 @@ -package mantle.pulsar.internal.logging; - -/** - * Static class for getting generic loggers. - * - * @author Arkan - */ -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); - } - } - -} diff --git a/src/main/java/mantle/pulsar/package-info.java b/src/main/java/mantle/pulsar/package-info.java deleted file mode 100644 index 8c4fa42..0000000 --- a/src/main/java/mantle/pulsar/package-info.java +++ /dev/null @@ -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 - */ -package mantle.pulsar; \ No newline at end of file diff --git a/src/main/java/mantle/pulsar/pulse/Pulse.java b/src/main/java/mantle/pulsar/pulse/Pulse.java deleted file mode 100644 index ad9366c..0000000 --- a/src/main/java/mantle/pulsar/pulse/Pulse.java +++ /dev/null @@ -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 - */ -@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; - -} diff --git a/src/main/java/mantle/pulsar/pulse/PulseMeta.java b/src/main/java/mantle/pulsar/pulse/PulseMeta.java deleted file mode 100644 index c1ef504..0000000 --- a/src/main/java/mantle/pulsar/pulse/PulseMeta.java +++ /dev/null @@ -1,53 +0,0 @@ -package mantle.pulsar.pulse; - -/** - * Metadata wrapper for parsed @Pulse metadata. - * - * @author Arkan - */ -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; - } -} diff --git a/src/main/java/mantle/utils/ItemMetaWrapper.java b/src/main/java/mantle/utils/ItemMetaWrapper.java deleted file mode 100644 index 36df03e..0000000 --- a/src/main/java/mantle/utils/ItemMetaWrapper.java +++ /dev/null @@ -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; - } -} diff --git a/src/main/java/mantle/utils/ItemStackNBTWrapper.java b/src/main/java/mantle/utils/ItemStackNBTWrapper.java deleted file mode 100644 index bd78329..0000000 --- a/src/main/java/mantle/utils/ItemStackNBTWrapper.java +++ /dev/null @@ -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; - } -} diff --git a/src/main/java/mantle/utils/ItemStackWrapper.java b/src/main/java/mantle/utils/ItemStackWrapper.java deleted file mode 100644 index b8eb378..0000000 --- a/src/main/java/mantle/utils/ItemStackWrapper.java +++ /dev/null @@ -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; - } -} diff --git a/src/main/java/mantle/world/ChunkCoord.java b/src/main/java/mantle/world/ChunkCoord.java deleted file mode 100644 index 30bbfff..0000000 --- a/src/main/java/mantle/world/ChunkCoord.java +++ /dev/null @@ -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, 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; - } - -} diff --git a/src/main/java/mantle/world/CoordTuplePair.java b/src/main/java/mantle/world/CoordTuplePair.java deleted file mode 100644 index 5a59570..0000000 --- a/src/main/java/mantle/world/CoordTuplePair.java +++ /dev/null @@ -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); - } -} diff --git a/src/main/java/mantle/world/DimensionCoordPair.java b/src/main/java/mantle/world/DimensionCoordPair.java deleted file mode 100644 index 8f8a8f6..0000000 --- a/src/main/java/mantle/world/DimensionCoordPair.java +++ /dev/null @@ -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; - } -} diff --git a/src/main/java/mantle/world/DimensionCoordTuple.java b/src/main/java/mantle/world/DimensionCoordTuple.java deleted file mode 100644 index b35fe04..0000000 --- a/src/main/java/mantle/world/DimensionCoordTuple.java +++ /dev/null @@ -1,65 +0,0 @@ -package mantle.world; - -/** - * DimensionCoordTuple - * - * @author mDiyo - * @author Sunstrike - */ -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; - } -} diff --git a/src/main/java/mantle/world/DirectionUtils.java b/src/main/java/mantle/world/DirectionUtils.java deleted file mode 100644 index 5b4aa20..0000000 --- a/src/main/java/mantle/world/DirectionUtils.java +++ /dev/null @@ -1,29 +0,0 @@ -package mantle.world; - -import net.minecraft.util.EnumFacing; - -/** - * Helper functions for dealing with ForgeDirection - * - * @author Sunstrike - */ -@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; - } - -} diff --git a/src/main/java/slimeknights/mantle/Mantle.java b/src/main/java/slimeknights/mantle/Mantle.java new file mode 100644 index 0000000..c3bd726 --- /dev/null +++ b/src/main/java/slimeknights/mantle/Mantle.java @@ -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 + */ +@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; +} diff --git a/src/main/java/slimeknights/mantle/block/BlockInventory.java b/src/main/java/slimeknights/mantle/block/BlockInventory.java new file mode 100644 index 0000000..4c5e173 --- /dev/null +++ b/src/main/java/slimeknights/mantle/block/BlockInventory.java @@ -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; + } +} diff --git a/src/main/java/mantle/blocks/iface/IMasterLogic.java b/src/main/java/slimeknights/mantle/block/IMasterLogic.java similarity index 87% rename from src/main/java/mantle/blocks/iface/IMasterLogic.java rename to src/main/java/slimeknights/mantle/block/IMasterLogic.java index 9a9e690..92d7357 100644 --- a/src/main/java/mantle/blocks/iface/IMasterLogic.java +++ b/src/main/java/slimeknights/mantle/block/IMasterLogic.java @@ -1,4 +1,4 @@ -package mantle.blocks.iface; +package slimeknights.mantle.block; import net.minecraft.util.BlockPos; diff --git a/src/main/java/mantle/blocks/iface/IMasterNode.java b/src/main/java/slimeknights/mantle/block/IMasterNode.java similarity index 83% rename from src/main/java/mantle/blocks/iface/IMasterNode.java rename to src/main/java/slimeknights/mantle/block/IMasterNode.java index f33b884..1a49c0c 100644 --- a/src/main/java/mantle/blocks/iface/IMasterNode.java +++ b/src/main/java/slimeknights/mantle/block/IMasterNode.java @@ -1,4 +1,4 @@ -package mantle.blocks.iface; +package slimeknights.mantle.block; public interface IMasterNode extends IMasterLogic, IServantLogic { diff --git a/src/main/java/mantle/blocks/iface/IServantLogic.java b/src/main/java/slimeknights/mantle/block/IServantLogic.java similarity index 96% rename from src/main/java/mantle/blocks/iface/IServantLogic.java rename to src/main/java/slimeknights/mantle/block/IServantLogic.java index aeaf726..3adebea 100644 --- a/src/main/java/mantle/blocks/iface/IServantLogic.java +++ b/src/main/java/slimeknights/mantle/block/IServantLogic.java @@ -1,4 +1,4 @@ -package mantle.blocks.iface; +package slimeknights.mantle.block; import net.minecraft.util.BlockPos; import net.minecraft.world.World; diff --git a/src/main/java/mantle/blocks/abstracts/MultiServantLogic.java b/src/main/java/slimeknights/mantle/block/MultiServantLogic.java similarity index 79% rename from src/main/java/mantle/blocks/abstracts/MultiServantLogic.java rename to src/main/java/slimeknights/mantle/block/MultiServantLogic.java index c157281..66eb098 100644 --- a/src/main/java/mantle/blocks/abstracts/MultiServantLogic.java +++ b/src/main/java/slimeknights/mantle/block/MultiServantLogic.java @@ -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() { diff --git a/src/main/java/slimeknights/mantle/client/ClientProxy.java b/src/main/java/slimeknights/mantle/client/ClientProxy.java new file mode 100644 index 0000000..fb018d3 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/ClientProxy.java @@ -0,0 +1,6 @@ +package slimeknights.mantle.client; + +import slimeknights.mantle.common.CommonProxy; + +public class ClientProxy extends CommonProxy { +} diff --git a/src/main/java/slimeknights/mantle/client/CreativeTab.java b/src/main/java/slimeknights/mantle/client/CreativeTab.java new file mode 100644 index 0000000..0e56380 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/CreativeTab.java @@ -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(); + } +} diff --git a/src/main/java/slimeknights/mantle/client/ModelHelper.java b/src/main/java/slimeknights/mantle/client/ModelHelper.java new file mode 100644 index 0000000..b375511 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/ModelHelper.java @@ -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>() {}.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 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 loadTextureListFromJson(ResourceLocation location) throws IOException { + ImmutableList.Builder 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 getTransformsFromState(IModelState state, IModelPart part) { + if(state instanceof IPerspectiveState) { + IPerspectiveState ps = (IPerspectiveState) state; + Map 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> { + + public static final ModelTextureDeserializer INSTANCE = new ModelTextureDeserializer(); + + private static final Gson GSON = new Gson(); + + @Override + public Map 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); + } + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiElement.java b/src/main/java/slimeknights/mantle/client/gui/GuiElement.java new file mode 100644 index 0000000..908aee9 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiElement.java @@ -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); + } + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiElementScalable.java b/src/main/java/slimeknights/mantle/client/gui/GuiElementScalable.java new file mode 100644 index 0000000..b676242 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiElementScalable.java @@ -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; + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiModule.java b/src/main/java/slimeknights/mantle/client/gui/GuiModule.java new file mode 100644 index 0000000..3880520 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiModule.java @@ -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; + } + +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiMultiModule.java b/src/main/java/slimeknights/mantle/client/gui/GuiMultiModule.java new file mode 100644 index 0000000..52049de --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiMultiModule.java @@ -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 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 getItemSpawnSlots(GuiContainer guiContainer, ItemStack itemStack) { + return null; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public List 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; + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiWidget.java b/src/main/java/slimeknights/mantle/client/gui/GuiWidget.java new file mode 100644 index 0000000..7600d74 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiWidget.java @@ -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; + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiWidgetSlider.java b/src/main/java/slimeknights/mantle/client/gui/GuiWidgetSlider.java new file mode 100644 index 0000000..227695d --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiWidgetSlider.java @@ -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; + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiWidgetTabs.java b/src/main/java/slimeknights/mantle/client/gui/GuiWidgetTabs.java new file mode 100644 index 0000000..be8c438 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiWidgetTabs.java @@ -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 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; + } +} diff --git a/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java b/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java new file mode 100644 index 0000000..690ea6f --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java @@ -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 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(); + } +} diff --git a/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java b/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java new file mode 100644 index 0000000..b524870 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java @@ -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 general; + protected final ImmutableMap> 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 builder; + builder = ImmutableList.builder(); + + transform = TRSRTransformation.blockCenterToCorner(transform); + + // face quads + EnumMap> 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.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) 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 getFaceQuads(EnumFacing side) { + return faces.get(side); + } + + @Override + public List 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(); + } +} diff --git a/src/main/java/slimeknights/mantle/common/CommonProxy.java b/src/main/java/slimeknights/mantle/common/CommonProxy.java new file mode 100644 index 0000000..e2dd4a7 --- /dev/null +++ b/src/main/java/slimeknights/mantle/common/CommonProxy.java @@ -0,0 +1,4 @@ +package slimeknights.mantle.common; + +public class CommonProxy { +} diff --git a/src/main/java/slimeknights/mantle/common/GuiHandler.java b/src/main/java/slimeknights/mantle/common/GuiHandler.java new file mode 100644 index 0000000..22bb260 --- /dev/null +++ b/src/main/java/slimeknights/mantle/common/GuiHandler.java @@ -0,0 +1,31 @@ +package slimeknights.mantle.common; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.common.network.IGuiHandler; + +/** + * A GuiHandler implementation that forwards the container/gui creation to the TEs, eliminating the need for GUI IDs. + */ +public class GuiHandler implements IGuiHandler { + + @Override + public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + TileEntity te = world.getTileEntity(new BlockPos(x, y, z)); + if(te instanceof IInventoryGui) { + return ((IInventoryGui) te).createContainer(player.inventory, world, new BlockPos(x, y, z)); + } + return null; + } + + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + TileEntity te = world.getTileEntity(new BlockPos(x, y, z)); + if(te instanceof IInventoryGui) { + return ((IInventoryGui) te).createGui(player.inventory, world, new BlockPos(x, y, z)); + } + return null; + } +} diff --git a/src/main/java/slimeknights/mantle/common/IInventoryGui.java b/src/main/java/slimeknights/mantle/common/IInventoryGui.java new file mode 100644 index 0000000..c4cea7d --- /dev/null +++ b/src/main/java/slimeknights/mantle/common/IInventoryGui.java @@ -0,0 +1,20 @@ +package slimeknights.mantle.common; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.util.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +/** + * Used in conjunction with GuiHandler. Implement in a TE to have it open its GUI/Container. + */ +public interface IInventoryGui { + + Container createContainer(InventoryPlayer inventoryplayer, World world, BlockPos pos); + + @SideOnly(Side.CLIENT) + GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos); +} diff --git a/src/main/java/slimeknights/mantle/inventory/BaseContainer.java b/src/main/java/slimeknights/mantle/inventory/BaseContainer.java new file mode 100644 index 0000000..e6cb89f --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/BaseContainer.java @@ -0,0 +1,297 @@ +package slimeknights.mantle.inventory; + +import com.google.common.collect.Lists; + +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.util.IChatComponent; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; + +import java.util.List; + +import slimeknights.mantle.util.SlimeknightException; + +/** Same as Container but provides some extra functionality to simplify things */ +public abstract class BaseContainer extends Container { + + protected double maxDist = 8 * 8; // 8 blocks + protected T tile; + protected final Block originalBlock; // used to check if the block we interacted with got broken + protected final BlockPos pos; + protected final World world; + + public List subContainers = Lists.newArrayList(); + + public BaseContainer(T tile) { + this.tile = tile; + + this.world = tile.getWorld(); + this.pos = tile.getPos(); + this.originalBlock = world.getBlockState(pos).getBlock(); + } + + public void syncOnOpen(EntityPlayerMP playerOpened) { + // find another player that already has the gui for this tile open + WorldServer server = playerOpened.getServerForPlayer(); + for(EntityPlayer player : (List) server.playerEntities) { + if(player == playerOpened) { + continue; + } + if(player.openContainer instanceof BaseContainer) { + if(this.sameGui((BaseContainer) player.openContainer)) { + syncWithOtherContainer((BaseContainer) player.openContainer, playerOpened); + return; + } + } + } + + // no player has a container open for the tile + syncNewContainer(playerOpened); + } + + /** + * Called when the container is opened and another player already has a container for this tile open + * Sync to the same state here. + */ + protected void syncWithOtherContainer(BaseContainer otherContainer, EntityPlayerMP player) { + } + + /** + * Called when the container is opened and no other player has it open. + * Set the default state here. + */ + protected void syncNewContainer(EntityPlayerMP player) { + } + + public boolean sameGui(BaseContainer otherContainer) { + return this.tile == otherContainer.tile; + } + + @Override + public boolean canInteractWith(EntityPlayer playerIn) { + Block block = world.getBlockState(pos).getBlock(); + // does the block we interacted with still exist? + if(block == Blocks.air || block != originalBlock) { + return false; + } + + // too far away from block? + return playerIn.getDistanceSq((double) pos.getX() + 0.5d, + (double) pos.getY() + 0.5d, + (double) pos.getZ() + 0.5d) <= maxDist; + } + + @SuppressWarnings("unchecked") + public List getInventory() { + return (List) super.getInventory(); + } + + public IChatComponent getInventoryDisplayName() { + if(tile instanceof IInventory) { + return ((IInventory) tile).getDisplayName(); + } + return null; + } + + // standard yOffset calculation for chestlike inventories: + // yOffset = (numRows - 4) * 18; (the -4 because of the 3 rows of inventory + 1 row of hotbar) + + protected int playerInventoryStart = -1; + + /** + * Draws the player inventory starting at the given position + * + * @param playerInventory The players inventory + * @param xCorner Default Value: 8 + * @param yCorner Default Value: (rows - 4) * 18 + 103 + */ + protected void addPlayerInventory(InventoryPlayer playerInventory, int xCorner, int yCorner) { + int index = 9; + + int start = this.inventorySlots.size(); + + for(int row = 0; row < 3; row++) { + for(int col = 0; col < 9; col++) { + this.addSlotToContainer(new Slot(playerInventory, index, xCorner + col * 18, yCorner + row * 18)); + index++; + } + } + + index = 0; + for(int col = 0; col < 9; col++) { + this.addSlotToContainer(new Slot(playerInventory, index, xCorner + col * 18, yCorner + 58)); + index++; + } + + playerInventoryStart = start; + } + + @Override + protected Slot addSlotToContainer(Slot slotIn) { + if(playerInventoryStart >= 0) { + throw new SlimeknightException("BaseContainer: Player inventory has to be last slots. Add all slots before adding the player inventory."); + } + return super.addSlotToContainer(slotIn); + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) { + // we can only support inventory <-> playerInventory + if(playerInventoryStart < 0) { + // so we don't do anything if no player inventory is present because we don't know what to do + return null; + } + + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(index); + + // slot that was clicked on not empty? + if(slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + int end = this.inventorySlots.size(); + + // Is it a slot in the main inventory? (aka not player inventory) + if(index < playerInventoryStart) { + // try to put it into the player inventory (if we have a player inventory) + if(!this.mergeItemStack(itemstack1, playerInventoryStart, end, true)) { + return null; + } + } + // Slot is in the player inventory (if it exists), transfer to main inventory + else if(!this.mergeItemStack(itemstack1, 0, playerInventoryStart, false)) { + return null; + } + + if(itemstack1.stackSize == 0) { + slot.putStack(null); + } + else { + slot.onSlotChanged(); + } + } + + return itemstack; + } + + // Fix for a vanilla bug: doesn't take Slot.getMaxStackSize into account + protected boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) { + return mergeItemStackRefill(stack, startIndex, endIndex, useEndIndex) + || mergeItemStackMove(stack, startIndex, endIndex, useEndIndex); + } + + // only refills items that are already present + protected boolean mergeItemStackRefill(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) { + if(stack.stackSize <= 0) { + return false; + } + + boolean flag1 = false; + int k = startIndex; + + if(useEndIndex) { + k = endIndex - 1; + } + + Slot slot; + ItemStack itemstack1; + + if(stack.isStackable()) { + while(stack.stackSize > 0 && (!useEndIndex && k < endIndex || useEndIndex && k >= startIndex)) { + slot = (Slot) this.inventorySlots.get(k); + itemstack1 = slot.getStack(); + + if(itemstack1 != null && itemstack1.getItem() == stack.getItem() && (!stack.getHasSubtypes() + || stack.getMetadata() == itemstack1 + .getMetadata()) && ItemStack.areItemStackTagsEqual(stack, itemstack1)) { + int l = itemstack1.stackSize + stack.stackSize; + int limit = Math.min(stack.getMaxStackSize(), slot.getItemStackLimit(stack)); + + if(l <= limit) { + stack.stackSize = 0; + itemstack1.stackSize = l; + slot.onSlotChanged(); + flag1 = true; + } + else if(itemstack1.stackSize < limit) { + stack.stackSize -= limit - itemstack1.stackSize; + itemstack1.stackSize = limit; + slot.onSlotChanged(); + flag1 = true; + } + } + + if(useEndIndex) { + --k; + } + else { + ++k; + } + } + } + + return flag1; + } + + // only moves items into empty slots + protected boolean mergeItemStackMove(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) { + if(stack.stackSize <= 0) { + return false; + } + + boolean flag1 = false; + int k; + + if(useEndIndex) { + k = endIndex - 1; + } + else { + k = startIndex; + } + + while(!useEndIndex && k < endIndex || useEndIndex && k >= startIndex) { + Slot slot = (Slot) this.inventorySlots.get(k); + ItemStack itemstack1 = slot.getStack(); + + if(itemstack1 == null && slot.isItemValid(stack)) // Forge: Make sure to respect isItemValid in the slot. + { + int limit = slot.getItemStackLimit(stack); + ItemStack stack2 = stack.copy(); + if(stack2.stackSize > limit) { + stack2.stackSize = limit; + stack.stackSize -= limit; + } + else { + stack.stackSize = 0; + } + slot.putStack(stack2); + slot.onSlotChanged(); + flag1 = true; + + if(stack.stackSize == 0) { + break; + } + } + + if(useEndIndex) { + --k; + } + else { + ++k; + } + } + + + return flag1; + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/ContainerMultiModule.java b/src/main/java/slimeknights/mantle/inventory/ContainerMultiModule.java new file mode 100644 index 0000000..8abfcf2 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/ContainerMultiModule.java @@ -0,0 +1,284 @@ +package slimeknights.mantle.inventory; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; + +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.tuple.Pair; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class ContainerMultiModule extends BaseContainer { + + public List subContainers = Lists.newArrayList(); + + // lookup used to redirect slot specific things to the appropriate container + protected Map slotContainerMap = Maps.newHashMap(); + protected Map> subContainerSlotRanges = Maps.newHashMap(); + protected int subContainerSlotStart = -1; + protected Set shiftClickContainers = Sets.newHashSet(); + + public ContainerMultiModule(T tile) { + super(tile); + } + + + /** + * @param subcontainer The container to add + * @param preferForShiftClick If true shift clicking on slots of the main-container will try to move to this module before the player inventory + */ + public void addSubContainer(Container subcontainer, boolean preferForShiftClick) { + if(subContainers.isEmpty()) { + subContainerSlotStart = inventorySlots.size(); + } + subContainers.add(subcontainer); + + if(preferForShiftClick) { + shiftClickContainers.add(subcontainer); + } + + int begin = inventorySlots.size(); + for(Object slot : subcontainer.inventorySlots) { + SlotWrapper wrapper = new SlotWrapper((Slot) slot); + addSlotToContainer(wrapper); + slotContainerMap.put(wrapper.slotNumber, subcontainer); + } + int end = inventorySlots.size(); + subContainerSlotRanges.put(subcontainer, Pair.of(begin, end)); + } + + public TC getSubContainer(Class clazz) { + return getSubContainer(clazz, 0); + } + + public TC getSubContainer(Class clazz, int index) { + for(Container sub : subContainers) { + if(clazz.isAssignableFrom(sub.getClass())) { + index--; + } + if(index < 0) { + return (TC) sub; + } + } + + return null; + } + + public Container getSlotContainer(int slotNumber) { + if(slotContainerMap.containsKey(slotNumber)) { + return slotContainerMap.get(slotNumber); + } + + return this; + } + + @Override + public boolean canInteractWith(EntityPlayer playerIn) { + // check if subcontainers are valid + for(Container sub : subContainers) { + if(!sub.canInteractWith(playerIn)) { + return false; + } + } + + return super.canInteractWith(playerIn); + } + + + @Override + public void onContainerClosed(EntityPlayer playerIn) { + for(Container sub : subContainers) { + sub.onContainerClosed(playerIn); + } + + super.onContainerClosed(playerIn); + } + + @Override + public ItemStack slotClick(int slotId, int clickedButton, int mode, EntityPlayer playerIn) { + if(slotId == -999 && mode == 5) { + for(Container container : subContainers) { + container.slotClick(slotId, clickedButton, mode, playerIn); + } + } +/* + if(slotContainerMap.containsKey(slotId)) { + int actualId = slotId; + if(this.inventorySlots.get(slotId) instanceof SlotWrapper) { + actualId = ((SlotWrapper) this.inventorySlots.get(slotId)).parent.slotNumber; + } + return slotContainerMap.get(slotId).slotClick(actualId, clickedButton, mode, playerIn); + }*/ + + return super.slotClick(slotId, clickedButton, mode, playerIn); + } + + // More sophisticated version of the one in BaseContainer + // Takes submodules into account when shiftclicking! + @Override + public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) { + Slot slot = (Slot) this.inventorySlots.get(index); + + if(slot == null || !slot.getHasStack()) { + return null; + } + + ItemStack ret = slot.getStack().copy(); + ItemStack itemstack = slot.getStack().copy(); + + Container container = getSlotContainer(index); + + // Is the slot from a module? + if(container != this) { + // Try moving module -> tile inventory + moveToTileInventory(itemstack); + + // Try moving module -> player inventory + if(moveToPlayerInventory(itemstack)) { + return null; + } + } + // Is the slot from the tile? + else if(index < subContainerSlotStart || (index < playerInventoryStart && subContainerSlotStart < 0)) { + // Try moving tile -> preferred modules + refillAnyContainer(itemstack, subContainers); + + // Try moving module -> player inventory + moveToPlayerInventory(itemstack); + + // Try moving module -> all submodules + if(moveToAnyContainer(itemstack, subContainers)) { + return null; + } + } + // Slot is from the player inventory (if present) + else if(index >= playerInventoryStart && playerInventoryStart >= 0) { + // Try moving player -> tile inventory + moveToTileInventory(itemstack); + + // try moving player -> modules + if(moveToAnyContainer(itemstack, subContainers)) { + return null; + } + } + // you violated some assumption or something. Shame on you. + else { + return null; + } + + return notifySlotAfterTransfer(playerIn, itemstack, ret, slot); + } + + protected ItemStack notifySlotAfterTransfer(EntityPlayer player, ItemStack stack, ItemStack original, Slot slot) { + // notify slot + slot.onSlotChange(stack, original); + + if(stack.stackSize == original.stackSize) { + return null; + } + + // update slot we pulled from + slot.putStack(stack); + slot.onPickupFromSlot(player, stack); + + if(slot.getHasStack() && slot.getStack().stackSize == 0) { + slot.putStack(null); + } + + return original; + } + + protected boolean moveToTileInventory(ItemStack itemstack) { + if(itemstack == null || itemstack.stackSize == 0) { + return false; + } + + int end = subContainerSlotStart; + if(end < 0) { + end = playerInventoryStart; + } + return !this.mergeItemStack(itemstack, 0, end, false); + } + + protected boolean moveToPlayerInventory(ItemStack itemstack) { + if(itemstack == null || itemstack.stackSize == 0) { + return false; + } + + return playerInventoryStart > 0 && !this + .mergeItemStack(itemstack, playerInventoryStart, this.inventorySlots.size(), true); + } + + protected boolean moveToAnyContainer(ItemStack itemstack, Collection containers) { + if(itemstack == null || itemstack.stackSize == 0) { + return false; + } + + for(Container submodule : containers) { + if(moveToContainer(itemstack, submodule)) { + return true; + } + } + + return false; + } + + protected boolean moveToContainer(ItemStack itemstack, Container container) { + Pair range = subContainerSlotRanges.get(container); + if(!this.mergeItemStack(itemstack, range.getLeft(), range.getRight(), false)) { + return true; + } + return false; + } + + + protected boolean refillAnyContainer(ItemStack itemstack, Collection containers) { + if(itemstack == null || itemstack.stackSize == 0) { + return false; + } + + for(Container submodule : containers) { + if(refillContainer(itemstack, submodule)) { + return true; + } + } + + return false; + } + + protected boolean refillContainer(ItemStack itemstack, Container container) { + Pair range = subContainerSlotRanges.get(container); + if(!this.mergeItemStackRefill(itemstack, range.getLeft(), range.getRight(), false)) { + return true; + } + return false; + } + + /** Searches for a sidechest to display in the UI */ + public TE detectTE(Class clazz) { + return ObjectUtils.firstNonNull(detectChest(this.pos.north(), clazz), + detectChest(this.pos.east(), clazz), + detectChest(this.pos.south(), clazz), + detectChest(this.pos.west(), clazz)); + } + + private TE detectChest(BlockPos pos, Class clazz) { + TileEntity te = this.world.getTileEntity(pos); + + if(te != null && clazz.isAssignableFrom(te.getClass())) { + return (TE) te; + } + return null; + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/ContainerSimpleChest.java b/src/main/java/slimeknights/mantle/inventory/ContainerSimpleChest.java new file mode 100644 index 0000000..abaee40 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/ContainerSimpleChest.java @@ -0,0 +1,36 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; + +import slimeknights.mantle.tileentity.TileInventory; + +public class ContainerSimpleChest extends BaseContainer { + + public ContainerSimpleChest(TileInventory tile, int rows, int columns, InventoryPlayer playerInventory) { + super(tile); + + int index = 0; + + // chest inventory + for(int i = 0; i < rows; ++i) { + for(int j = 0; j < columns; ++j) { + // safety + if(index > tile.getSizeInventory()) { + break; + } + + this.addSlotToContainer(createSlot(tile, index, 8 + j * 18, 18 + i * 18)); + index++; + } + } + + // player inventory + addPlayerInventory(playerInventory, 17, 86); + } + + protected Slot createSlot(IInventory inventory, int index, int x, int y) { + return new Slot(inventory, index, x, y); + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/IContainerCraftingCustom.java b/src/main/java/slimeknights/mantle/inventory/IContainerCraftingCustom.java new file mode 100644 index 0000000..fa97dac --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/IContainerCraftingCustom.java @@ -0,0 +1,10 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +public interface IContainerCraftingCustom { + + void onCrafting(EntityPlayer player, ItemStack output, IInventory craftMatrix); +} diff --git a/src/main/java/slimeknights/mantle/inventory/SlotCraftingCustom.java b/src/main/java/slimeknights/mantle/inventory/SlotCraftingCustom.java new file mode 100644 index 0000000..162162b --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/SlotCraftingCustom.java @@ -0,0 +1,34 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.inventory.SlotCrafting; +import net.minecraft.item.ItemStack; + +public class SlotCraftingCustom extends SlotCrafting { + + private final InventoryCrafting craftMatrix; + private final IContainerCraftingCustom callback; + + /** + * @param callback Container that gets the crafting call on crafting + * @param player Player that does the crafting + * @param craftingInventory Inventory where the ingredients are taken from + * @param craftResult Inventory where the result is put + */ + public SlotCraftingCustom(IContainerCraftingCustom callback, EntityPlayer player, InventoryCrafting craftingInventory, IInventory craftResult, int slotIndex, int xPosition, int yPosition) { + super(player, craftingInventory, craftResult, slotIndex, xPosition, yPosition); + + this.craftMatrix = craftingInventory; + this.callback = callback; + } + + @Override + public void onPickupFromSlot(EntityPlayer playerIn, ItemStack stack) { + net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerCraftingEvent(playerIn, stack, craftMatrix); + this.onCrafting(stack); + + callback.onCrafting(playerIn, stack, craftMatrix); + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/SlotOut.java b/src/main/java/slimeknights/mantle/inventory/SlotOut.java new file mode 100644 index 0000000..03764b9 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/SlotOut.java @@ -0,0 +1,18 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +/** Slot that can only be taken out of */ +public class SlotOut extends Slot { + + public SlotOut(IInventory inventoryIn, int index, int xPosition, int yPosition) { + super(inventoryIn, index, xPosition, yPosition); + } + + @Override + public boolean isItemValid(ItemStack stack) { + return false; + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/SlotRestrictedItem.java b/src/main/java/slimeknights/mantle/inventory/SlotRestrictedItem.java new file mode 100644 index 0000000..29cf460 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/SlotRestrictedItem.java @@ -0,0 +1,21 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class SlotRestrictedItem extends Slot { + + private final Item allowedItem; + + public SlotRestrictedItem(Item item, IInventory inventoryIn, int index, int xPosition, int yPosition) { + super(inventoryIn, index, xPosition, yPosition); + allowedItem = item; + } + + @Override + public boolean isItemValid(ItemStack stack) { + return stack != null && stack.getItem() == allowedItem; + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/SlotWrapper.java b/src/main/java/slimeknights/mantle/inventory/SlotWrapper.java new file mode 100644 index 0000000..3dc9d29 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/SlotWrapper.java @@ -0,0 +1,41 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +/** + * Used to wrap the slots inside Modules/Subcontainers + */ +public class SlotWrapper extends Slot { + + public final Slot parent; + + public SlotWrapper(Slot slot) { + super(slot.inventory, slot.getSlotIndex(), slot.xDisplayPosition, slot.yDisplayPosition); + this.parent = slot; + } + + @Override + public void onSlotChange(ItemStack p_75220_1_, ItemStack p_75220_2_) { + parent.onSlotChange(p_75220_1_, p_75220_2_); + } + + @Override + public boolean isItemValid(ItemStack stack) { + return parent.isItemValid(stack); + } + + @Override + public boolean canTakeStack(EntityPlayer playerIn) { + return parent.canTakeStack(playerIn); + } + + @SideOnly(Side.CLIENT) + @Override + public boolean canBeHovered() { + return parent.canBeHovered(); + } +} diff --git a/src/main/java/slimeknights/mantle/item/ItemBlockMeta.java b/src/main/java/slimeknights/mantle/item/ItemBlockMeta.java new file mode 100644 index 0000000..bdcdeb6 --- /dev/null +++ b/src/main/java/slimeknights/mantle/item/ItemBlockMeta.java @@ -0,0 +1,11 @@ +package slimeknights.mantle.item; + +import net.minecraft.block.Block; +import net.minecraft.item.ItemColored; + +public class ItemBlockMeta extends ItemColored { + + public ItemBlockMeta(Block block) { + super(block, true); + } +} diff --git a/src/main/java/slimeknights/mantle/item/ItemMeta.java b/src/main/java/slimeknights/mantle/item/ItemMeta.java new file mode 100644 index 0000000..4d26058 --- /dev/null +++ b/src/main/java/slimeknights/mantle/item/ItemMeta.java @@ -0,0 +1,36 @@ +package slimeknights.mantle.item; + +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +import java.util.List; + +/** + * Item representing a fixed amount of different items represented by meta. + */ +public class ItemMeta extends Item { + + protected int maxMeta; + + public ItemMeta(int maxMeta) { + setHasSubtypes(true); + this.maxMeta = maxMeta; + } + + @Override + public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) { + for(int i = 0; i <= maxMeta; i++) { + subItems.add(new ItemStack(itemIn, 1, i)); + } + } + + @Override + public int getMetadata(int damage) { + if(damage < 0 || damage > maxMeta) { + return 0; + } + + return damage; + } +} diff --git a/src/main/java/slimeknights/mantle/item/ItemMetaDynamic.java b/src/main/java/slimeknights/mantle/item/ItemMetaDynamic.java new file mode 100644 index 0000000..79eb9e7 --- /dev/null +++ b/src/main/java/slimeknights/mantle/item/ItemMetaDynamic.java @@ -0,0 +1,62 @@ +package slimeknights.mantle.item; + +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +import java.util.List; + +/** + * Item representing a dynamic amount of different items represented by meta. + * Only returns valid metadatas. The validity is determined by a bitmask. + * Current maximum is 64 metas - that should suffice for most applications. + */ +public class ItemMetaDynamic extends ItemMeta { + + private static int MAX = Long.SIZE; + + protected long availabilityMask; + + public ItemMetaDynamic() { + super(-1); + + } + + public ItemStack addMeta(int meta) { + if(meta > MAX) { + throw new IllegalArgumentException(String + .format("Metadata too high, highest supported value is %d. Meta was %d", MAX, meta)); + } + if(meta > maxMeta) { + maxMeta = meta; + setValid(meta); + } + return new ItemStack(this, 1, meta); + } + + @Override + public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) { + for(int i = 0; i <= maxMeta; i++) { + if(isValid(i)) { + subItems.add(new ItemStack(itemIn, 1, i)); + } + } + } + + @Override + public int getMetadata(int damage) { + int meta = super.getMetadata(damage); + return isValid(meta) ? meta : 0; + } + + protected void setValid(int meta) { + availabilityMask |= 1 << meta; + } + + protected boolean isValid(int meta) { + if(meta > MAX) { + return false; + } + return ((availabilityMask >> meta) & 1) == 1; + } +} diff --git a/src/main/java/slimeknights/mantle/network/AbstractPacket.java b/src/main/java/slimeknights/mantle/network/AbstractPacket.java new file mode 100644 index 0000000..dd9bd46 --- /dev/null +++ b/src/main/java/slimeknights/mantle/network/AbstractPacket.java @@ -0,0 +1,47 @@ +package slimeknights.mantle.network; + +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.util.BlockPos; +import net.minecraftforge.fml.common.network.simpleimpl.IMessage; +import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; +import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraftforge.fml.relauncher.Side; + +import io.netty.buffer.ByteBuf; + +public abstract class AbstractPacket implements IMessage, IMessageHandler { + + @Override + public IMessage onMessage(IMessage message, MessageContext ctx) { + if(!(message instanceof AbstractPacket)) { + return null; + } + + AbstractPacket packet = (AbstractPacket) message; + + if(ctx.side == Side.SERVER) { + return packet.handleServer(ctx.getServerHandler()); + } + else { + return packet.handleClient(ctx.getClientHandler()); + } + } + + public abstract IMessage handleClient(NetHandlerPlayClient netHandler); + + public abstract IMessage handleServer(NetHandlerPlayServer netHandler); + + protected void writePos(BlockPos pos, ByteBuf buf) { + buf.writeInt(pos.getX()); + buf.writeInt(pos.getY()); + buf.writeInt(pos.getZ()); + } + + protected BlockPos readPos(ByteBuf buf) { + int x = buf.readInt(); + int y = buf.readInt(); + int z = buf.readInt(); + return new BlockPos(x, y, z); + } +} diff --git a/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java b/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java new file mode 100644 index 0000000..d055113 --- /dev/null +++ b/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java @@ -0,0 +1,41 @@ +package slimeknights.mantle.network; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.server.MinecraftServer; +import net.minecraftforge.fml.common.network.simpleimpl.IMessage; + +/** + * Threadsafe integration of the abstract packet. + * Basically if you're doing something that has any influence on the world you should use this. + * (That's ~everything) + */ +public abstract class AbstractPacketThreadsafe extends AbstractPacket { + + @Override + public final IMessage handleClient(final NetHandlerPlayClient netHandler) { + Minecraft.getMinecraft().addScheduledTask(new Runnable() { + @Override + public void run() { + handleClientSafe(netHandler); + } + }); + return null; + } + + @Override + public final IMessage handleServer(final NetHandlerPlayServer netHandler) { + MinecraftServer.getServer().addScheduledTask(new Runnable() { + @Override + public void run() { + handleServerSafe(netHandler); + } + }); + return null; + } + + public abstract void handleClientSafe(NetHandlerPlayClient netHandler); + + public abstract void handleServerSafe(NetHandlerPlayServer netHandler); +} diff --git a/src/main/java/slimeknights/mantle/network/NetworkWrapper.java b/src/main/java/slimeknights/mantle/network/NetworkWrapper.java new file mode 100644 index 0000000..b3423e5 --- /dev/null +++ b/src/main/java/slimeknights/mantle/network/NetworkWrapper.java @@ -0,0 +1,55 @@ +package slimeknights.mantle.network; + +import com.google.common.base.Throwables; + +import net.minecraftforge.fml.common.network.NetworkRegistry; +import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; +import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; +import net.minecraftforge.fml.relauncher.Side; + +/** + * A small network implementation/wrapper using AbstractPackets instead of IMessages. + * Instantiate in your mod class and register your packets accordingly. + */ +public class NetworkWrapper { + + public final SimpleNetworkWrapper network; + private int id = 0; + + public NetworkWrapper(String channelName) { + network = NetworkRegistry.INSTANCE.newSimpleChannel(channelName); + } + + /** + * Packet will be received on both cliend and server side. + */ + public void registerPacket(Class packetClazz) { + registerPacketClient(packetClazz); + registerPacketServer(packetClazz); + } + + /** + * Packet will only be received on the client side + */ + public void registerPacketClient(Class packetClazz) { + registerPacketImpl(packetClazz, Side.CLIENT); + } + + /** + * Packet will only be received on the server side + */ + public void registerPacketServer(Class packetClazz) { + registerPacketImpl(packetClazz, Side.SERVER); + } + + private void registerPacketImpl(Class packetClazz, Side side) { + IMessageHandler handler; + try { + handler = packetClazz.newInstance(); + } catch(Exception e) { + throw Throwables.propagate(e); + } + + network.registerMessage(handler, packetClazz, id++, side); + } +} diff --git a/src/main/java/slimeknights/mantle/property/PropertyString.java b/src/main/java/slimeknights/mantle/property/PropertyString.java new file mode 100644 index 0000000..4fc3f20 --- /dev/null +++ b/src/main/java/slimeknights/mantle/property/PropertyString.java @@ -0,0 +1,32 @@ +package slimeknights.mantle.property; + +import net.minecraftforge.common.property.IUnlistedProperty; + +public class PropertyString implements IUnlistedProperty { + + private final String name; + + public PropertyString(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isValid(String value) { + return !value.isEmpty(); + } + + @Override + public Class getType() { + return String.class; + } + + @Override + public String valueToString(String value) { + return value; + } +} diff --git a/src/main/java/slimeknights/mantle/tileentity/TileInventory.java b/src/main/java/slimeknights/mantle/tileentity/TileInventory.java new file mode 100644 index 0000000..d291f3d --- /dev/null +++ b/src/main/java/slimeknights/mantle/tileentity/TileInventory.java @@ -0,0 +1,242 @@ +package slimeknights.mantle.tileentity; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.util.IChatComponent; + +// Updated version of InventoryLogic in Mantle. Also contains a few bugfixes +public class TileInventory extends TileEntity implements IInventory { + + private ItemStack[] inventory; + protected String inventoryTitle; + protected boolean hasCustomName; + protected int stackSizeLimit; + + /** + * @param name Localization String for the inventory title. Can be overridden through setCustomName + */ + public TileInventory(String name, int inventorySize) { + this(name, inventorySize, 64); + } + + /** + * @param name Localization String for the inventory title. Can be overridden through setCustomName + */ + public TileInventory(String name, int inventorySize, int maxStackSize) { + this.inventory = new ItemStack[inventorySize]; + this.stackSizeLimit = maxStackSize; + this.inventoryTitle = name; + } + + /* Inventory management */ + + @Override + public ItemStack getStackInSlot(int slot) { + if(slot < 0 || slot >= inventory.length) { + return null; + } + + return inventory[slot]; + } + + public boolean isStackInSlot(int slot) { + return getStackInSlot(slot) != null; + } + + @Override + public int getSizeInventory() { + return inventory.length; + } + + @Override + public int getInventoryStackLimit() { + return stackSizeLimit; + } + + @Override + public void setInventorySlotContents(int slot, ItemStack itemstack) { + if(slot < 0 || slot >= inventory.length) { + return; + } + + inventory[slot] = itemstack; + if(itemstack != null && itemstack.stackSize > getInventoryStackLimit()) { + itemstack.stackSize = getInventoryStackLimit(); + } + } + + @Override + public ItemStack decrStackSize(int slot, int quantity) { + ItemStack itemStack = getStackInSlot(slot); + + if(itemStack == null) { + return null; + } + + // whole itemstack taken out + if(itemStack.stackSize <= quantity) { + setInventorySlotContents(slot, null); + this.markDirty(); + return itemStack; + } + + // split itemstack + itemStack = itemStack.splitStack(quantity); + // slot is empty, set to null + if(getStackInSlot(slot).stackSize == 0) { + setInventorySlotContents(slot, null); + } + + this.markDirty(); + // return remainder + return itemStack; + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack itemstack) { + if(slot < getSizeInventory()) { + if(inventory[slot] == null || itemstack.stackSize + inventory[slot].stackSize <= getInventoryStackLimit()) { + return true; + } + } + return false; + } + + @Override + public void clear() { + for(int i = 0; i < inventory.length; i++) { + inventory[i] = null; + } + } + + @Override + public String getCommandSenderName() { + return this.inventoryTitle; + } + + @Override + public boolean hasCustomName() { + return this.hasCustomName; + } + + public void setCustomName(String customName) { + this.hasCustomName = true; + this.inventoryTitle = customName; + } + + @Override + public IChatComponent getDisplayName() { + if(hasCustomName()) { + return new ChatComponentText(getCommandSenderName()); + } + + return new ChatComponentTranslation(getCommandSenderName()); + } + + + /* Supporting methods */ + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + // block changed/got broken? + if(worldObj.getTileEntity(pos) != this || worldObj.getBlockState(pos).getBlock() == Blocks.air) { + return false; + } + + return + entityplayer.getDistanceSq((double) pos.getX() + 0.5D, (double) pos.getY() + 0.5D, (double) pos.getZ() + 0.5D) + <= 64D; + } + + @Override + public void openInventory(EntityPlayer player) { + + } + + @Override + public void closeInventory(EntityPlayer player) { + + } + + /* NBT */ + @Override + public void readFromNBT(NBTTagCompound tags) { + super.readFromNBT(tags); + readInventoryFromNBT(tags); + } + + public void readInventoryFromNBT(NBTTagCompound tags) { + super.readFromNBT(tags); + readInventoryFromNBT(this, tags); + + if(tags.hasKey("CustomName", 8)) { + this.inventoryTitle = tags.getString("CustomName"); + } + } + + @Override + public void writeToNBT(NBTTagCompound tags) { + super.writeToNBT(tags); + writeInventoryToNBT(this, tags); + + if(this.hasCustomName()) { + tags.setString("CustomName", this.inventoryTitle); + } + } + + /** Writes the contents of the inventory to the tag */ + public static void writeInventoryToNBT(IInventory inventory, NBTTagCompound tag) { + NBTTagList nbttaglist = new NBTTagList(); + + for(int i = 0; i < inventory.getSizeInventory(); i++) { + if(inventory.getStackInSlot(i) != null) { + NBTTagCompound itemTag = new NBTTagCompound(); + itemTag.setByte("Slot", (byte) i); + inventory.getStackInSlot(i).writeToNBT(itemTag); + nbttaglist.appendTag(itemTag); + } + } + + tag.setTag("Items", nbttaglist); + } + + /** Reads a an inventory from the tag. Overwrites current content */ + public static void readInventoryFromNBT(IInventory inventory, NBTTagCompound tag) { + NBTTagList nbttaglist = tag.getTagList("Items", 10); + + for(int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound itemTag = nbttaglist.getCompoundTagAt(i); + int slot = itemTag.getByte("Slot") & 255; + + if(slot >= 0 && slot < inventory.getSizeInventory()) { + inventory.setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(itemTag)); + } + } + } + + /* Default implementations of hardly used methods */ + public ItemStack getStackInSlotOnClosing(int slot) { + return null; + } + + @Override + public int getField(int id) { + return 0; + } + + @Override + public void setField(int id, int value) { + + } + + @Override + public int getFieldCount() { + return 0; + } +} diff --git a/src/main/java/slimeknights/mantle/util/RecipeMatch.java b/src/main/java/slimeknights/mantle/util/RecipeMatch.java new file mode 100644 index 0000000..0f8d937 --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/RecipeMatch.java @@ -0,0 +1,205 @@ +package slimeknights.mantle.util; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; + +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import slimeknights.mantle.Mantle; + +/** + * Utility class that allows to find a specific subset of items in a list of itemstacks. + * Matches can be found through oredictionary, simple nbt-independant item-meta combinations etc. + * + * The match returned by this class can then be used to remove the found recipe match from the items. + */ +public abstract class RecipeMatch { + + + + protected final int amountNeeded; + protected final int amountMatched; + + /** + * @param amountNeeded How many of the itemstack are needed for the match + * @param amountMatched If amount needed itemstacks are present, as how many matches does this count? + */ + public RecipeMatch(int amountMatched, int amountNeeded) { + this.amountMatched = amountMatched; + this.amountNeeded = amountNeeded; + } + + public abstract Match matches(ItemStack[] stacks); + + /** Removes the match from the stacks */ + public static void removeMatch(ItemStack[] stacks, Match match) { + for(ItemStack stack : match.stacks) { + for(int i = 0; i < stacks.length; i++) { + // nbt sensitive since toolparts etc. use nbt + if(ItemStack.areItemsEqual(stack, stacks[i]) && ItemStack.areItemStackTagsEqual(stack, stacks[i])) { + if(stacks[i].stackSize < stack.stackSize) { + Mantle.logger.error("RecipeMatch has incorrect stacksize! {}", stacks[i].toString()); + } + else { + stacks[i].stackSize -= stack.stackSize; + if(stacks[i].stackSize == 0) { + stacks[i] = null; + } + } + break; + } + } + } + } + + /** A specific amount of a certain item is needed. Supports wildcard-metadata. Not NBT sensitive. */ + public static class Item extends RecipeMatch { + + private final ItemStack template; + + public Item(ItemStack template, int amountNeeded) { + this(template, amountNeeded, 1); + } + + /** + * @param template The itemstack to match + * @param amountNeeded How many of the itemstack are needed for the match + * @param amountMatched If amountneeded itemstacks are present, as how many matches does this count? + */ + public Item(ItemStack template, int amountNeeded, int amountMatched) { + super(amountMatched, amountNeeded); + this.template = template; + } + + @Override + public Match matches(ItemStack[] stacks) { + List found = Lists.newLinkedList(); + int stillNeeded = amountNeeded; + + for(ItemStack stack : stacks) { + if(OreDictionary.itemMatches(template, stack, false)) { + // add the amount found to the list + ItemStack copy = stack.copy(); + copy.stackSize = Math.min(copy.stackSize, stillNeeded); + found.add(copy); + stillNeeded -= copy.stackSize; + + // we found enough + if(stillNeeded <= 0) { + return new Match(found, amountMatched); + } + } + } + + return null; + } + } + + /** A combination of multiple items. NBT SENSITIVE! */ + public static class ItemCombination extends RecipeMatch { + + protected final ItemStack[] itemStacks; + + /** + * @param amountMatched If amount needed itemstacks are present, as how many matches does this count? + */ + public ItemCombination(int amountMatched, ItemStack... stacks) { + super(amountMatched, 0); + + this.itemStacks = stacks; + } + + @Override + public Match matches(ItemStack[] stacks) { + List found = Lists.newLinkedList(); + Set needed = Sets.newHashSet(); + + for(int i = 0; i < itemStacks.length; i++) { + if(itemStacks[i] != null) { + needed.add(i); + } + } + + for(ItemStack stack : stacks) { + Iterator iter = needed.iterator(); + while(iter.hasNext()) { + int index = iter.next(); + ItemStack template = itemStacks[index]; + if(ItemStack.areItemsEqual(template, stack) && ItemStack.areItemStackTagsEqual(template, stack)) { + // add the amount found to the list + ItemStack copy = stack.copy(); + copy.stackSize = 1; + found.add(copy); + iter.remove(); + break; + } + } + } + + if(needed.isEmpty()) { + return new Match(found, amountMatched); + } + return null; + } + } + + /** A specific amount of an oredicted material is needed to match. */ + public static class Oredict extends RecipeMatch { + + private final List oredictEntry; // todo: change this to the actual list in the oredict + + public Oredict(String oredictEntry, int amountNeeded) { + this(oredictEntry, amountNeeded, 1); + } + + public Oredict(String oredictEntry, int amountNeeded, int amountMatched) { + super(amountNeeded, amountMatched); + this.oredictEntry = OreDictionary.getOres(oredictEntry); + } + + @Override + public Match matches(ItemStack[] stacks) { + List found = Lists.newLinkedList(); + int stillNeeded = amountNeeded; + + for(ItemStack ore : oredictEntry) { + for(ItemStack stack : stacks) { + if(OreDictionary.itemMatches(ore, stack, false)) { + // add the amount found to the list + ItemStack copy = stack.copy(); + copy.stackSize = Math.min(copy.stackSize, stillNeeded); + found.add(copy); + stillNeeded -= copy.stackSize; + + // we found enough + if(stillNeeded <= 0) { + return new Match(found, amountMatched); + } + } + } + } + + return null; + } + } + + /** Represents a collection of items that match the recipies */ + public static class Match { + + /** The stacks that have to be removed to apply this match */ + public List stacks; + + /** How often the recipe is found within this match */ + public int amount; + + public Match(List stacks, int amount) { + this.stacks = stacks; + this.amount = amount; + } + } +} diff --git a/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java b/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java new file mode 100644 index 0000000..8d8daf6 --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java @@ -0,0 +1,133 @@ +package slimeknights.mantle.util; + +import com.google.common.collect.Lists; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +import java.util.Collection; +import java.util.List; + +/** + * Contains a set of matches. Allows you to easily find if a set of itemstacks matches one of them. + */ +// MANTLE +public class RecipeMatchRegistry { + + protected final List items = Lists.newArrayList(); + + public RecipeMatch.Match matches(Collection stacks) { + return matches(stacks.toArray(new ItemStack[stacks.size()])); + } + + // looks for a match in the given itemstacks + public RecipeMatch.Match matches(ItemStack... stacks) { + for(RecipeMatch recipe : items) { + RecipeMatch.Match match = recipe.matches(stacks); + if(match != null) { + return match; + } + } + + return null; + } + + // looks for a match with at least the given amount in the given itemstacks + public RecipeMatch.Match matches(ItemStack[] stacks, int minAmount) { + stacks = copyItemStackArray(stacks); // copy so we don't modify original + + List matches = Lists.newLinkedList(); + + RecipeMatch.Match match; + int sum = 0; + while(sum < minAmount && (match = matches(stacks)) != null) { + matches.add(match); + RecipeMatch.removeMatch(stacks, match); + + sum += match.amount; + } + + // not enough found + if(sum < minAmount) { + return null; + } + + // merge all found matches into one match + List foundStacks = Lists.newLinkedList(); + for(RecipeMatch.Match m : matches) { + foundStacks.addAll(m.stacks); + } + + return new RecipeMatch.Match(foundStacks, sum); + } + + /** + * Associates an oredict entry with this material. Used for repairing and other. + * + * @param oredictItem Oredict-String + * @param amountNeeded How many of this item are needed to count as one full material item. + * @param amountMatched If both item and amount are present, how often did they match? + */ + public void addItem(String oredictItem, int amountNeeded, int amountMatched) { + items.add(new RecipeMatch.Oredict(oredictItem, amountNeeded, amountMatched)); + } + + public void addItem(String oredictItem) { + addItem(oredictItem, 1, 1); + } + + /** + * Associates a block with this material. Used for repairing and other. + * + * @param amountMatched For how many matches the block counts (e.g. redstone dust = 1 match, Redstone block = 9) + */ + public void addItem(Block block, int amountMatched) { + items.add(new RecipeMatch.Item(new ItemStack(block), 1, amountMatched)); + } + + /** + * Associates an item entry with this material. Used for repairing and other. + * + * @param item The item + * @param amountNeeded How many of this item are needed to count as one full material item. + * @param amountMatched If both item and amount are present, how often did they match? + */ + public void addItem(Item item, int amountNeeded, int amountMatched) { + items.add(new RecipeMatch.Item(new ItemStack(item), amountNeeded, amountMatched)); + } + + /** + * Associates an item entry with this material. Used for repairing and other. + * + * @param item The item + * @param amountNeeded How many of this item are needed to count as one full material item. + * @param amountMatched If both item and amount are present, how often did they match? + */ + public void addItem(ItemStack item, int amountNeeded, int amountMatched) { + items.add(new RecipeMatch.Item(item, amountNeeded, amountMatched)); + } + + /** + * Associates an item with this material. Used for repairing and other. + */ + public void addItem(Item item) { + addItem(item, 1, 1); + } + + public void addRecipeMatch(RecipeMatch match) { + items.add(match); + } + + + public static ItemStack[] copyItemStackArray(ItemStack[] in) { + ItemStack[] stacksCopy = new ItemStack[in.length]; + for(int i = 0; i < in.length; i++) { + if(in[i] != null) { + stacksCopy[i] = in[i].copy(); + } + } + + return stacksCopy; + } +} diff --git a/src/main/java/mantle/utils/RecipeRemover.java b/src/main/java/slimeknights/mantle/util/RecipeRemover.java similarity index 99% rename from src/main/java/mantle/utils/RecipeRemover.java rename to src/main/java/slimeknights/mantle/util/RecipeRemover.java index 8da1de6..c681589 100644 --- a/src/main/java/mantle/utils/RecipeRemover.java +++ b/src/main/java/slimeknights/mantle/util/RecipeRemover.java @@ -1,4 +1,4 @@ -package mantle.utils; +package slimeknights.mantle.util; import java.util.List; import java.util.Map; diff --git a/src/main/java/slimeknights/mantle/util/SlimeknightException.java b/src/main/java/slimeknights/mantle/util/SlimeknightException.java new file mode 100644 index 0000000..58b35ca --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/SlimeknightException.java @@ -0,0 +1,27 @@ +package slimeknights.mantle.util; + +public class SlimeknightException extends RuntimeException { + + public SlimeknightException() { + } + + public SlimeknightException(String message) { + super(message); + } + + public SlimeknightException(String message, Object... params) { + super(String.format(message, params)); + } + + public SlimeknightException(String message, Throwable cause) { + super(message, cause); + } + + public SlimeknightException(Throwable cause) { + super(cause); + } + + public SlimeknightException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/src/main/java/slimeknights/mantle/util/TagHelper.java b/src/main/java/slimeknights/mantle/util/TagHelper.java new file mode 100644 index 0000000..3151e53 --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/TagHelper.java @@ -0,0 +1,40 @@ +package slimeknights.mantle.util; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagString; + +public class TagHelper { + public static int TAG_TYPE_STRING = (new NBTTagString()).getId(); + public static int TAG_TYPE_COMPOUND = (new NBTTagCompound()).getId(); + + private TagHelper() { + } + + /* Generic Tag Operations */ + public static NBTTagCompound getTagSafe(ItemStack stack) { + if(stack == null || stack.getItem() == null || !stack.hasTagCompound()) { + return new NBTTagCompound(); + } + + return stack.getTagCompound(); + } + + public static NBTTagCompound getTagSafe(NBTTagCompound tag, String key) { + if(tag == null || !tag.hasKey(key)) { + return new NBTTagCompound(); + } + + return tag.getCompoundTag(key); + } + + public static NBTTagList getTagListSafe(NBTTagCompound tag, String key, int type) { + if(tag == null || !tag.hasKey(key)) { + return new NBTTagList(); + } + + return tag.getTagList(key, type); + } + +} diff --git a/src/main/resources/META-INF/Mantle_at.cfg b/src/main/resources/META-INF/Mantle_at.cfg new file mode 100644 index 0000000..c92f814 --- /dev/null +++ b/src/main/resources/META-INF/Mantle_at.cfg @@ -0,0 +1,11 @@ +# Mantle -- Access Transformer + +# GuiContainer +public net.minecraft.client.gui.inventory.GuiContainer field_146999_f #xSize +public net.minecraft.client.gui.inventory.GuiContainer field_147000_g #ySize +public net.minecraft.client.gui.inventory.GuiContainer field_147009_r #guiTop +public net.minecraft.client.gui.inventory.GuiContainer field_147003_i #guiLeft +public net.minecraft.client.gui.inventory.GuiContainer func_146977_a(Lnet/minecraft/inventory/Slot;)V #renderSlot +public net.minecraft.client.gui.inventory.GuiContainer func_146981_a(Lnet/minecraft/inventory/Slot;II)Z #isMouseOverSlot +# GuiScreen +public net.minecraft.client.gui.GuiScreen field_146292_n #buttonList