Jump to content

Minothor

Members
  • Posts

    63
  • Joined

Everything posted by Minothor

  1. I'm currently working on a power system for a friend's mod, however I'm hitting a bit of a snag. So far the cables only seem to be connecting successfully in the vertical (y) direction and transferring MF power packets accordingly. Visually, connections will only show up once the chunk has been reloaded so I'm guessing I'm failing with the update packet somewhere. Does anyone have any idea what I'm doing wrong here? package net.RPower.RPowermod.machines.power.cable; import RPower.api.power.E_MFPacketType; import RPower.api.power.MFPacket; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.RPower.RPowermod.machines.power.MFHelper; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockFluxCableBasic extends BlockContainer{ public BlockFluxCableBasic(Material p_i45394_1_) { super(p_i45394_1_); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int metaD, float hitX, float hitY, float hitZ) { MFPacket temp = new MFPacket(E_MFPacketType.REQUEST); ((TileEntityFluxCable)world.getTileEntity(x, y, z)).takePacket(temp); return false; } @Override public void onNeighborBlockChange(World world, int x,int y, int z, Block block) { if((world.getBlock(x, y, z).hasTileEntity(0) && MFHelper.checkConnectable(world.getTileEntity(x, y, z)))) { ((TileEntityFluxCable)world.getTileEntity(x, y, z)).checkConnections(); } } @Override public int onBlockPlaced(World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metaD) { if((world.getBlock(x, y, z).hasTileEntity(0) && MFHelper.checkConnectable(world.getTileEntity(x, y, z)))) ((TileEntityFluxCable)world.getTileEntity(x, y, z)).connections[(5-side)]=true; System.out.println("set block at ["+x+","+y+","+z+"] to: "+side); return super.onBlockPlaced(world, x, y, z,side, hitX, hitY, hitZ, metaD); } @Override public TileEntity createNewTileEntity(World world, int metadata) { TileEntity cable = new TileEntityFluxCable(32); return cable; } @Override public boolean isAir(IBlockAccess world, int x, int y, int z) { return false; } @Override protected boolean canSilkHarvest() { return false; }; @Override public boolean canSilkHarvest(World world, EntityPlayer player, int x, int y, int z, int metadata) { return false; }; @Override public boolean canBeReplacedByLeaves(IBlockAccess world, int x, int y, int z) { return false; } @SideOnly(Side.CLIENT) @Override public boolean renderAsNormalBlock() { return false; } @Override @SideOnly(Side.CLIENT) public boolean shouldSideBeRendered(IBlockAccess blockAccess, int x, int y, int z, int side) { return false; }; @SideOnly(Side.CLIENT) @Override public boolean isOpaqueCube() { return false; } @Override public int getRenderType() { return -1; } } this is the basic block class, the right-click spawned packet is purely for testing connections. package net.RPower.RPowermod.machines.power.cable; import java.util.LinkedList; import java.util.Queue; import RPower.api.power.E_MFPacketType; import RPower.api.power.I_MFSink; import RPower.api.power.MFPacket; import RPower.api.power.cable.I_MFCable; import net.RPower.RPowermod.machines.power.MFHelper; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; public class TileEntityFluxCable extends TileEntity implements I_MFCable { //Connections are an array of [up, Down, North, East, West, South] public boolean[] connections = {false, false, false, false, false, false}; //whether or not the cable is lossy public boolean insulatedCable; //maximum limit the cable can carry public double packetSizeLimit; //Packets awaiting processing public Queue<MFPacket> internalBuffer; //automatically calculated. public double percentageLoss; //transfer mode, unbridged connections can only cross an intersection in straight lines (may be reserved for advanced cabling) public boolean bridgeConnections; public TileEntityFluxCable() { this(32); } public TileEntityFluxCable(double packetSize) { this(packetSize,false); } public TileEntityFluxCable(double packetSize, boolean insulated) { this(packetSize,insulated,true); } public TileEntityFluxCable(double packetSize, boolean insulated,boolean bridged) { packetSizeLimit= packetSize; insulatedCable=insulated; bridgeConnections=bridged; internalBuffer=new LinkedList<MFPacket>(); checkLoss(insulated); } private void checkLoss(boolean insulated) { if(!insulated) { percentageLoss=(packetSizeLimit/MFPacket.POWERLIMIT); } } @Override public boolean takePacket(MFPacket packet) { double excess=0; if(!insulatedCable) { excess+=(percentageLoss*packet.getBuffer()); packet.setBuffer(packet.getBuffer()-excess); } if(packet.getBuffer()>packetSizeLimit) { excess += packet.getBuffer()-packetSizeLimit; packet.setBuffer(packetSizeLimit); } powerBleed(excess); boolean result=false; result=internalBuffer.add(packet); return result; } @Override public void writeToNBT(NBTTagCompound nbtTag) { int[] connectionsInt = new int[6]; int i = 0; for (boolean side : connections) { connectionsInt[i]=connections[i]?1:0; i++; } nbtTag.setIntArray("connections", connectionsInt); nbtTag.setBoolean("insulated", insulatedCable); nbtTag.setBoolean("bridged", bridgeConnections); nbtTag.setDouble("packetLimit", packetSizeLimit); super.writeToNBT(nbtTag); }; @Override public void readFromNBT(NBTTagCompound nbtTag) { int[] connectionsInt = nbtTag.getIntArray("connections"); int i = 0; for (boolean side : connections) { connections[i]=(connectionsInt[i]==1); i++; } insulatedCable=nbtTag.getBoolean("insulated"); bridgeConnections=nbtTag.getBoolean("bridged"); packetSizeLimit=nbtTag.getDouble("packetLimit"); checkLoss(insulatedCable); super.readFromNBT(nbtTag); }; @Override public Packet getDescriptionPacket() { NBTTagCompound nbtTag = new NBTTagCompound(); this.writeToNBT(nbtTag); //TODO: Get this damn working! return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 1, nbtTag); } @Override public void onDataPacket(NetworkManager networkManager, S35PacketUpdateTileEntity packet) { readFromNBT(packet.func_148857_g()); } @Override public void updateEntity() { if(!internalBuffer.isEmpty()) { MFPacket packet = internalBuffer.remove(); boolean result=false; byte direction; for(int i=0; i<59;i++) { int posNeg = ((int)(Math.random()*%2==0)?1:-1; double randXvel=Math.random()*(2*posNeg); double randYvel=Math.random()*(2*posNeg); double randZvel=Math.random()*(2*posNeg); this.worldObj.spawnParticle("magicCrit", xCoord, yCoord, zCoord, randXvel, randYvel, randZvel); } switch(packet.getType()) { case RESPOND: direction = packet.getOrigin().peek(); result = (direction!=-1); result = pushPacket(packet); break; default: direction = packet.getOrigin().peek(); packet.getOrigin().add(randDir(direction)); result=pushPacket(packet); break; } } super.updateEntity(); } private byte randDir(byte initDirection) { byte result = -1; while((connectionNum()>=2)&&(result==-1||!connections[result])&&result!=initDirection) { result=(byte)(Math.random()*5); } return result; } public byte connectionNum() { byte result=0; for (Boolean connection : connections) { if(connection) result++; } return result; } public boolean checkConnections() { boolean result=false; int xDir=0, yDir=0, zDir=0; for(int dir=0; dir<=5; dir++) { int modifier=(dir%2==1)?1:-1; System.err.println("test vars: dir="+dir+", TestCase="+(dir/2)+", modifier="+modifier+","); switch(dir/2) { case 2: xDir=modifier; break; case 1: zDir=modifier; break; case 0: yDir=modifier; break; } System.out.println("testing ["+xDir+","+yDir+","+zDir+"]"); result = this.worldObj.getBlock(xCoord+xDir, yCoord+yDir, zCoord+zDir).hasTileEntity(0); if(result) result = MFHelper.checkConnectable(this.worldObj.getTileEntity(xCoord+xDir, yCoord+yDir, zCoord+zDir)); System.out.println("result of MF test was: "+result); int conDir = dir-modifier; System.err.println("conDir="+conDir); connections[conDir]=result; if(connections[conDir]) { System.out.println("Connection found!"); } } return result; } @Override public boolean pushPacket(MFPacket packet) { byte direction = packet.getOrigin().peek(); if(packet.getType()==E_MFPacketType.RESPOND) packet.getOrigin().pop(); boolean result= false; int xDir=0, yDir=0, zDir=0; int modifier=(direction%2==1)?-1:1; //up:1, down:0, x+:5, x-:4, z+:3,z-2; switch(direction/2) { case 2: xDir=modifier; break; case 1: zDir=modifier; break; case 0: yDir=modifier; break; } result = this.worldObj.getBlock(xCoord+xDir, yCoord+yDir, zCoord+zDir).hasTileEntity(0); if(result) result=this.worldObj.getTileEntity(xCoord+xDir, yCoord+yDir, zCoord+zDir)instanceof I_MFSink; if(result) result=((I_MFSink)this.worldObj.getTileEntity(xCoord+xDir, yCoord+yDir, zCoord+zDir)).takePacket(packet); if(!result) powerBleed(packet.getBuffer()); return result; } @Override public boolean canUpdate() { return true; } @Override public double flowLimit() { return packetSizeLimit; } @Override public void powerBleed(double excess) { //add power bleed to chunk atmosphere -> own effects + taint if Thaumcraft installed if(excess>0) System.err.println(""+excess+" MF bled off into atmosphere!\n"); } @Override public double getPacketLimit() { return packetSizeLimit; } @Override public boolean isInsulated() { return insulatedCable; } @Override public boolean isBridged() { return bridgeConnections; } @Override public boolean canDeBridge() { return insulatedCable; } @Override public boolean[] getConnections() { return connections; } } The Actual TileEntity and source of the stress here, it's meant to keep an array of connected sides and update it when neighbours change. package net.RPower.RPowermod.machines.power; import RPower.api.power.I_MFSink; import RPower.api.power.I_MFSource; import RPower.api.power.cable.I_MFCable; import net.RPower.RPowermod.machines.power.cable.TileEntityFluxCable; import net.minecraft.tileentity.TileEntity; public class MFHelper { public static boolean checkConnectable(TileEntity tileEntity) { boolean result = (tileEntity instanceof I_MFSink || tileEntity instanceof I_MFSource); if (result) System.out.println("Success!"); System.out.println(tileEntity.toString()); return result; } } Anything I need to handle frequently will be offloaded into this class for neatness. Currently it only checks if a tileEntity implements either of the interfaces for MFcables to connect to. (I_MFCable extends both I_MFSink and I_MFSource) Cheers in advance and sorry about the code flood, the full source is on this branch: https://github.com/BackSpace47/main/tree/PowerSystem
  2. Cheers all, and grey, I have a little question about the GL11 translate and rotate functions. I've been trying with modifying invidual parametres, but the translation along the X,Y&Z axes seems totally arbitrary. as far as I can tell, the Y value if how close or far from the player it's rendered towards the centre of the screen, but the other two seem to lack consistency in their translations, usually some variation of off the top of the screen or some vertical change, regardless of the value changed being X or Z. This has been compounded by the fact that so far, even the documentation I've found so far is suggesting that the function should work as expected. Could you possibly shed any light on the matter? Many Thanks in advance. (p.s. asking here rather than in PM in case others happen to be searching the forums for a similar issue)
  3. I think your best bet may be through the itemstack's NBT tag, have the item load it's durability/max damage from an NBT integer value and keep a static hashmap somewhere for what material to damage values you want to set.
  4. Ah.. Cheers! That leaves me with the initial problem I was trying to overcome (and led to this one) of how you get the partialTickTime parameter for the first person view. I'd mistakenly believed that Minecraft itself would call the function with that parameter since the only details I could find in the forums here and Forums mentioned rendering being derpy if you pass a random value in that function instead of the actual time elapsed between ticks. (it was post dieselieben made that explained most.) but I couldn't find the pTT in entity, the minecraft instance or the RenderManager. If you're able to point me in the right direction, you have no bloody idea how grateful I'd be even for the name of Tue class.
  5. Hi Grey, I'm expecting it to be called when I have the card hand equipped in first person mode. oddly enough, it renders a blank item in my hand in 3rd person view, which is expected, I leave that to the vanilla code, but in first person, I'm trying to have the map's two handed rendering come up, akin to Azanor's thaumometer rendering. I'll admit that I'm glad you replied, it's been between vanilla code and your blog that I've made the little progress I have so far.
  6. When does your init phase tell the proxy to register the renderers? As far as I can see, it's empty, so although you have a renderer coded, it's never registered.
  7. It looks like it's expecting a resource location instance rather than a string. Try putting the string inside 'new ResourceLocation("your path string here")' Edit: Ninja'd by Kriki, but yeah, the resource location class is what handles most files as far as I can tell.
  8. Sorry for possibly another newbie question, but I'm having a little trouble with the first person rendering GL code. The view below is largely lifted from the vanilla renderer's first person map section (needed for the arms). However, when I run it, it renders no arms in the game view (screencap attached below.) I've tried registering it at the same time as the item in preinit and at the same time as the tileentity renderer (visible in the screenshots) in init. Neither way appears to work. I've check through the code and it's not coughing up any errors or warnings, so I'm getting more than a tad confused. Is anything obviously wrong to anyone? package emeraldCasino.renderers.items; import static net.minecraftforge.client.IItemRenderer.ItemRenderType.EQUIPPED_FIRST_PERSON; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import emeraldCasino.items.itemCardHand; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.entity.RenderPlayer; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Items; import net.minecraft.item.ItemMap; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.MapData; import net.minecraftforge.client.IItemRenderer; import net.minecraftforge.client.MinecraftForgeClient; @SideOnly(Side.CLIENT) public class ItemCardHandRenderer implements IItemRenderer { int itemRenderId; public ItemCardHandRenderer() { itemRenderId = RenderingRegistry.getNextAvailableRenderId(); } @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { return (type==EQUIPPED_FIRST_PERSON); } public void renderItemInFirstPerson(float par1) { /* * Vanilla Map Rendering -- to Modify */ float f1 = 1.0F; Minecraft minecraft = Minecraft.getMinecraft(); EntityClientPlayerMP entityclientplayermp = minecraft.thePlayer; ResourceLocation deckTexture = new ResourceLocation(emeraldCasino.EmeraldCasino.MODID,"textures/cardDecks/deck_standard.png"); float f2 = entityclientplayermp.prevRotationPitch + (entityclientplayermp.rotationPitch - entityclientplayermp.prevRotationPitch) * par1; //GET PARENT GAME FROM HAND //GET DECK TEXTURE FROM GAME //BIND DECK TEXTURE FROM GAME //GET CARDS & CARD DATA FROM HAND GL11.glPushMatrix(); float f13 = 0.8F; float swingProgress = entityclientplayermp.getSwingProgress(par1); float f6 = MathHelper.sin(swingProgress * (float)Math.PI); float f7 = MathHelper.sin(MathHelper.sqrt_float(swingProgress) * (float)Math.PI); GL11.glTranslatef(-f7 * 0.4F, MathHelper.sin(MathHelper.sqrt_float(swingProgress) * (float)Math.PI * 2.0F) * 0.2F, -f6 * 0.2F); swingProgress = 1.0F - f2 / 45.0F + 0.1F; if (swingProgress < 0.0F) { swingProgress = 0.0F; } if (swingProgress > 1.0F) { swingProgress = 1.0F; } swingProgress = -MathHelper.cos(swingProgress * (float)Math.PI) * 0.5F + 0.5F; GL11.glTranslatef(0.0F, 0.0F * f13 - (1.0F - f1) * 1.2F - swingProgress * 0.5F + 0.04F, -0.9F * f13); GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(swingProgress * -85.0F, 0.0F, 0.0F, 1.0F); GL11.glEnable(GL12.GL_RESCALE_NORMAL); minecraft.getTextureManager().bindTexture(entityclientplayermp.getLocationSkin()); //RENDER CARD RECTS IN ARC -- INCREASE DISTANCE FROM ORIGIN FOR ACTIVE CARDS for (int i1 = 0; i1 < 2; ++i1) { int j1 = i1 * 2 - 1; GL11.glPushMatrix(); GL11.glTranslatef(-0.0F, -0.6F, 1.1F * (float)j1); GL11.glRotatef((float)(-45 * j1), 1.0F, 0.0F, 0.0F); GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F); GL11.glRotatef(59.0F, 0.0F, 0.0F, 1.0F); GL11.glRotatef((float)(-65 * j1), 0.0F, 1.0F, 0.0F); Render render = RenderManager.instance.getEntityRenderObject(entityclientplayermp); RenderPlayer renderplayer = (RenderPlayer)render; float f10 = 1.0F; GL11.glScalef(f10, f10, f10); renderplayer.renderFirstPersonArm(entityclientplayermp); GL11.glPopMatrix(); } f6 = entityclientplayermp.getSwingProgress(par1); f7 = MathHelper.sin(f6 * f6 * (float)Math.PI); float f8 = MathHelper.sin(MathHelper.sqrt_float(f6) * (float)Math.PI); GL11.glRotatef(-f7 * 20.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(-f8 * 20.0F, 0.0F, 0.0F, 1.0F); GL11.glRotatef(-f8 * 80.0F, 1.0F, 0.0F, 0.0F); float f9 = 0.38F; GL11.glScalef(f9, f9, f9); GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(180.0F, 0.0F, 0.0F, 1.0F); GL11.glTranslatef(-1.0F, -1.0F, 0.0F); float f10 = 0.015625F; GL11.glScalef(f10, f10, f10); minecraft.getTextureManager().bindTexture(deckTexture); Tessellator tessellator = Tessellator.instance; GL11.glNormal3f(0.0F, 0.0F, -1.0F); tessellator.startDrawingQuads(); byte b0 = 7; tessellator.addVertexWithUV((double)(0 - b0), (double)(128 + b0), 0.0D, 0.0D, 1.0D); tessellator.addVertexWithUV((double)(128 + b0), (double)(128 + b0), 0.0D, 1.0D, 1.0D); tessellator.addVertexWithUV((double)(128 + b0), (double)(0 - b0), 0.0D, 1.0D, 0.0D); tessellator.addVertexWithUV((double)(0 - b0), (double)(0 - b0), 0.0D, 0.0D, 0.0D); tessellator.draw(); GL11.glPopMatrix(); } @Override public boolean shouldUseRenderHelper(ItemRenderType arg0, ItemStack arg1, ItemRendererHelper arg2) { // TODO Auto-generated method stub return false; } @Override public void renderItem(ItemRenderType type, ItemStack item, Object... data) { // TODO Auto-generated method stub } } Holding vanilla map: Holding card hand item: Console output: (Note: the missing textures relate to the block and item assets, there's nothing in there about the player skin nor the deck_standard.png called in the renderer)
  9. cheers for the reply and the easy player method, don't worry, I'll side it appropiately. Concerning GUIs, simply put, no it's not a necessity and it would help with things like locking the player in place. My main issue is that GUIs can be unplayably small. I also quite liked the visual aesthetic of first person view and people swinging their arm to play their chosen cards. I'll revert to a GUI if there's no other way, but I'll try the cardHand item's left/right click functions with a sneaking toggle first.
  10. Ok, I've managed to get a somewhat hacky solution going, but I'm struggling to stop the hotbar from switching item slot. Could anyone shed any light on how best to tackle this please? (also, suggestions on optimising are more than welcome!) package EmeraldCasino.events; import java.awt.Event; import org.lwjgl.input.Keyboard; import net.minecraft.entity.player.*; import cpw.mods.fml.client.registry.ClientRegistry; import net.minecraft.client.settings.KeyBinding; import net.minecraft.world.World; import cpw.mods.fml.common.gameevent.InputEvent; import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent; import cpw.mods.fml.common.event.FMLEvent; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent.KeyInputEvent; public class cardHandHandler { private boolean sneaky=false; private EntityPlayer localPlayer; @SubscribeEvent(priority=EventPriority.HIGH, receiveCanceled=true) public void onEvent(PlayerTickEvent e){ if(e.player.isSneaking()){ sneaky=true; if(localPlayer==null) localPlayer=e.player; } else { sneaky = false; } } @SubscribeEvent(priority=EventPriority.HIGHEST, receiveCanceled=true) public void onEvent(InputEvent.KeyInputEvent e) { if(sneaky){ int index=-1; int invSlot=localPlayer.inventory.currentItem; switch(Keyboard.getEventKey()){ case Keyboard.KEY_1: index = 1; break; case Keyboard.KEY_2: index = 2; break; } if(index>=0){ System.out.println(""+index+" Pressed"); } localPlayer.inventory.changeCurrentItem(invSlot); } } }
  11. cheers Jabelar, I'll try that now (and yes, I am using 1.7.2, sorry, updated the title now) ((EDIT: ADDENDUM: Also, sorry, but is there any simple way of getting the local client's player when the keyevent is fired or am I stuck with using a player tickhandler to listen for the relevant keys?))
  12. First off, sorry for the rather obscure title. Secondly, does anyone know what would be the best way of achieving the following? Handling a "hand" of cards rendered in first person view, making the active card switchable with keys 1-0 or with the mouse scroll. The two major complications are these: I want to allow players to quit the card game (and return shortcuts to normal) with escape. I would also like to allow players to hit their chat key and type in a message to talk while playing. The idea I'm toying with at the moment is using a custom Map renderer to render the cards held in the player's hands but how to selectively override hotbar keys is something I'm not quite sure off. it also feels a horrendously messy approach to GUI-less play. If anyone has any suggestions as to a solution or a better method of play, I'm all ears! Thanks in Advance.
  13. would the more generic "entityLivingDeath" event suit your needs? net.minecraftforge.event.entity.living.LivingDeathEvent;
  14. looks like it's just returning the string referencing the memory address. Try retrieving the string via getContents() http://devlazy.com/java-coding-examples/get-system-clipboard-content/
  15. good practice in case a parameter name conflicts with an attribute (in which case it'd only set the variable in the scope of the function itself). if the variable names are different then it's not technically necessary but it still helps with remembering which scope you're dealing with (class or function)
  16. Cheers Sequiturian, I'll test it via a temporary block in game later today. Also, simply put Sieben, it never even crossed my mind that I was referencing constants in the first place, which, in hindsight, was pretty stupid, you're right. I'll fix that when I get home. Edit: cheers all, I tested it in the PostInit phase and it's working fine! A big thanks to everyone who responded!
  17. Sorry to bump this up so soon, but having swapped around the if() tests for emerald blocks and nuggets, it's become clear that it is just executing the first if(), whichever it is. The actual class that it's testing for doesn't seem to matter and using the .getClass() inherited from Object only results in a NullPointer, I'm getting really, really confused now.. Is ItemStack.getItem() unused or am I using it wrong?
  18. I'm using Final and Static because the Financial package is aimed at being a helper library that shouldn't have multiple instances. It's use is purely to perform operations on nonary integers and convert between Itemstacks and a nonary representation of the item values. the piece that's calling both functions is in the temporary Main() function at the bottom of ItemHandler.java (in-class testing, will be removed) System.out.println("Returned Nonary: "+depositItems(withdrawItems(62001)));
  19. if you're going to be using it a lot, you could extract the checks to a method: private static boolean requiredMob(Entity testEntity){ return (testEntity instanceof EntityZombie || testEntity instanceof EntitySkeleton || testEntity instanceof EntityCreeper); } if(requiredMob(event.entity)){ //do code }
  20. I'm afraid it's still not working, sorry. Here's the full code (now that I'm back at home (it's an uncommitted change at the moment): package EmeraldCasino.financial; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public final class ItemHandler { private static final Block BLOCKEMERALD = Blocks.emerald_block; private static final Item EMERALD = Items.emerald; private static final Block BLOCKGOLD = Blocks.gold_block; private static final Item GOLD = Items.gold_ingot; private static final Item NUGGETGOLD = Items.gold_nugget; private ItemHandler() { } public static int depositItems(List<ItemStack> inputItems) { int result = 0; int emBlocks = 0; int emItems = 0; int goBlocks = 0; int goItems = 0; int goNuggets = 0; // TODO Verify Item types from the list. for (ItemStack itemStack : inputItems) { Item itemType = itemStack.getItem(); int itemNum = itemStack.stackSize; if(itemType == Item.getItemFromBlock(BLOCKEMERALD)){ emBlocks+=itemNum; System.out.println("Added "+itemNum+" Emerald Blocks"); } else if(itemType == EMERALD){ emItems+=itemNum; System.out.println("Added "+itemNum+" Emeralds"); } else if(itemType == Item.getItemFromBlock(BLOCKGOLD)){ goBlocks+=itemNum; System.out.println("Added "+itemNum+" Gold Blocks"); } else if(itemType == GOLD){ goItems+=itemNum; System.out.println("Added "+itemNum+" Gold Ingots"); } else if(itemType == NUGGETGOLD){ goNuggets+=itemNum; System.out.println("Added "+itemNum+" Gold Nuggets"); } } //CleanUp time: //Checking if Emeralds can be compressed into one stack if (emItems>{ emBlocks+=(emItems/9); emItems%=9; } //Checking if Gold Nuggets can be compressed into Blocks if (goNuggets>{ goItems+=(goNuggets/9); goNuggets%=9; } //Checking if Gold can be compressed into one stack if (goItems>{ goBlocks+=(goItems/9); goItems%=9; } result=Nonary.toNonary(emBlocks*6561); result=Nonary.add(result, Nonary.toNonary(emItems*729)); result=Nonary.add(result, Nonary.toNonary(goBlocks*81)); result=Nonary.add(result, Nonary.toNonary(goItems*9)); result=Nonary.add(result, Nonary.toNonary(goNuggets)); return result; } /** * * @param inputNonary The Nonary value of items being withdrawn. * @return List of ItemStacks */ public static List<ItemStack> withdrawItems(int inputNonary) { System.out.println("Integer "+inputNonary+" Translates into:"); List<ItemStack> ReturnItems = new ArrayList<>(5); //safety checks int emBlocks = (inputNonary/10000); if(emBlocks<0) emBlocks=0; int emItems = (inputNonary-=(emBlocks*10000))/1000; if(emItems<0) emItems=0; int goBlocks = (inputNonary-=(emItems*1000))/100; if(goBlocks<0) goBlocks=0; int goItems = (inputNonary-=(goBlocks*100))/10; if(goItems<0) goItems=0; int goNuggets = (inputNonary-=(goItems*10)); if(goNuggets<0) goNuggets=0; //CleanUp time: //Checking if Emeralds can be compressed into one stack if (((emBlocks*9)+emItems)<=64){ emItems+=(emBlocks*9); emBlocks=0; } //Checking if Gold can be compressed into one stack if (((goBlocks*9)+goItems)<=64){ goItems+=(goBlocks*9); goBlocks=0; } System.out.println("Emeralds:\nBlocks: "+emBlocks+"\nItems: "+emItems); System.out.println("Gold:\nBlocks: "+goBlocks+"\nIngots: "+goItems+"\nNuggets: "+goNuggets); while(emBlocks>64){ ReturnItems.add(new ItemStack(BLOCKEMERALD, 64)); emBlocks-=64; } if(emBlocks>0) ReturnItems.add(new ItemStack(BLOCKEMERALD, emBlocks)); if(emItems>0) ReturnItems.add(new ItemStack(EMERALD, emItems)); if(goBlocks>0) ReturnItems.add(new ItemStack(BLOCKGOLD, goBlocks)); if(goItems>0) ReturnItems.add(new ItemStack(GOLD, goItems)); if(goNuggets>0) ReturnItems.add(new ItemStack(NUGGETGOLD, goNuggets)); return ReturnItems; } public static void main(String[] args) { long start = System.currentTimeMillis(); System.out.println("Returned Nonary: "+depositItems(withdrawItems(62001))); long end = System.currentTimeMillis(); System.out.println((end - start) + " ms"); } } package EmeraldCasino.financial; /** * Base-9 calculations library for working with values based off gold and emerald items. * @author Minothor * @version 1.0 */ public final class Nonary { private Nonary() {} private static int changeBase (int value, int base1, int base2){ /* * Credit for this simple function goes to http://professorjava.weebly.com/ * for their easy to follow base conversion calculator. */ int intermediary = Integer.parseInt(""+value, base1); int result = Integer.valueOf(Integer.toString(intermediary, base2)); return result; } /** * converts a Decimal integer into it's equivalent Nonary form. * @param decimal Integer to convert. * @return returns the Nonary equivalent. */ public static int toNonary(int decimal){ return changeBase(decimal, 10, 9); } /** * converts a Nonary integer into it's equivalent Decimal form. * @param nonary Integer to convert. * @return the Decimal equivalent. */ public static int toDecimal(int nonary){ return changeBase(nonary, 9, 10); } /** * Adds the second value to the first. * (done since operand overloading isn't possible in Java) * @param value1 Nonary integer. * @param value2 Nonary integer. * @return Integer sum of inputs. */ public static int add(int value1, int value2){ int result = toDecimal(value1)+toDecimal(value2); return toNonary(result); } /** * Substracts the second value from the first. * (done since operand overloading isn't possible in Java) * @param value1 Nonary integer. * @param value2 Nonary integer. * @return Integer result of subtraction. */ public static int subtract(int value1, int value2){ int result = toDecimal(value1)-toDecimal(value2); return toNonary(result); } /** * Multiplies first value by the second. * (done since operand overloading isn't possible in Java) * @param value1 Nonary integer. * @param value2 Nonary integer. * @return Integer product of multiplication. */ public static int multiply(int value1, int value2){ int result = toDecimal(value1)*toDecimal(value2); return toNonary(result); } /** * Divides first value by the second. * (done since operand overloading isn't possible in Java) * @param value1 Nonary integer. * @param value2 Nonary integer. * @return Integer result of division. */ public static int divide(int value1, int value2){ int result = toDecimal(value1)/toDecimal(value2); return toNonary(result); } /** * Remainder of dividing the first value by the second. * (done since operand overloading isn't possible in Java) * @param value1 Nonary integer. * @param value2 Nonary integer. * @return Integer result of modulo. */ public static int modulo(int value1, int value2){ int result = toDecimal(value1)%toDecimal(value2); return toNonary(result); } } the console output it from ItemHandler's main is as follows: This output remains the same whether I use the constants declared at the top or "Items.emerald" etc declared directly after the "==" Any idea what I'm screwing up here?
  21. Hey all, I'm having a little trouble getting the unlocalised name of an itemstack passed in to a function. I've tried a few methods like: String itemName = inputStack.getItem().getUnlocalizedName(); and String itemName = GameData.getItemRegistry().getItemName(inputStack.getItem()); but the most I have had is a NullPointer exception for the former and "item.null" for the latter. I've been testing it with: public static String getItemType(ItemStack inputStack) { //see examples above return itemName; } and System.out.println(getItemType(new ItemStack(Items.emerald,64))); Any ideas what's going on? I'm a little bit baffled.. For more information: I need to be able to identify the string of what the itemstack contains and I'll be using a switch case to select which offset to apply to the nonary integer, corresponding to Emerald blocks, items, Gold blocks, ingots or nuggets, as laid out here: https://github.com/Minothor/EmeraldCasino/wiki/Financial Many thanks in advance! -Mino
  22. Wrestled with this myself, but the tutorials were pretty clear once I got my head round the git system. Here's what I did man, hope it helps: First of all, I copied the basic forge source folder and renamed the copy with my Mod's name. Then, having set up the environment and eclipse: I added a new local repository in GitHub for Windows.. https://lh6.googleusercontent.com/-9FOv41msAGw/U29njR_LtmI/AAAAAAAABqw/qx18NVXE-18/w833-h458-no/Capture2.JPG[/img] but before pushing it to GitHub, I edited the .gitignore File so that it ignored all the files added by forge, including the example mod (although, it's simpler to just delete that). https://lh5.googleusercontent.com/-CsZkpdp-uhM/U29njV-EgtI/AAAAAAAABqo/hoq8nl_Cll0/w833-h629-no/Capture3.JPG[/img] ################# ## Eclipse ################# *.pydevproject .project .metadata bin/ tmp/ *.tmp *.bak *.swp *~.nib local.properties .classpath .settings/ .loadpath .gradle/ gradle/ build/ build.gradle eclipse/ CREDITS-fml.txt forge-1.7.2-10.12.1.1060-changelog.txt gradlew gradlew.bat LICENSE-fml.txt MinecraftForge-Credits.txt MinecraftForge-License.txt README.txt /src/main/java/com/ # External tool builders .externalToolBuilders/ # Locally stored "Eclipse launch configurations" *.launch # CDT-specific .cproject # PDT-specific .buildpath ################# ## Visual Studio ################# ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. # User-specific files *.suo *.user *.sln.docstates # Build results [Dd]ebug/ [Rr]elease/ x64/ build/ [bb]in/ [Oo]bj/ # MSTest test Results [Tt]est[Rr]esult*/ [bb]uild[Ll]og.* *_i.c *_p.c *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.log *.scc # Visual C++ cache files ipch/ *.aps *.ncb *.opensdf *.sdf *.cachefile # Visual Studio profiler *.psess *.vsp *.vspx # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[ss]harper # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # NCrunch *.ncrunch* .*crunch*.local.xml # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.Publish.xml *.pubxml # NuGet Packages Directory ## TODO: If you have NuGet Package Restore enabled, uncomment the next line #packages/ # Windows Azure Build Output csx *.build.csdef # Windows Store app package directory AppPackages/ # Others sql/ *.Cache ClientBin/ [ss]tyle[Cc]op.* ~$* *~ *.dbmdl *.[Pp]ublish.xml *.pfx *.publishsettings # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file to a newer # Visual Studio version. Backup files are not needed, because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files App_Data/*.mdf App_Data/*.ldf ############# ## Windows detritus ############# # Windows image file caches Thumbs.db ehthumbs.db # Folder config file Desktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Mac crap .DS_Store ############# ## Python ############# *.py[co] # Packages *.egg *.egg-info dist/ build/ eggs/ parts/ var/ sdist/ develop-eggs/ .installed.cfg # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox #Translations *.mo #Mr Developer .mr.developer.cfg if you save that as your .gitignore file it should work fine. Then Push to gitHub and you should be good to go! e.g. : https://github.com/Minothor/EmeraldCasino
  23. Ok, I've decided that the easiest way to support all axes and those from other mods would probably be to register them with the oreDict under "toolAxe". That said, I'm really struggling with the event handling, I've look up what documentation I can from the Wiki's reference, searching the forums and AtomicStryker's post here: http://www.minecraftforum.net/topic/1419836- ) Currently the only thing that Eclipse is being a bit iffy about is the @ForgeSubscribe annotation before the function. Can anyone shed any light on how and where I'm mucking up here please? Thanks in Advance, -Mino Event Handling class: package minothor.bab.events.EventHandlers; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.*; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; import net.minecraftforge.oredict.OreDictionary; public class CentEventHandler { public CentEventHandler(){ MinecraftForge.EVENT_BUS.register(this); } @ForgeSubscribe public void playerInteract(PlayerInteractEvent event) { Action eventAction = event.action; World currentWorld = event.entityPlayer.worldObj; Block blockAffected = currentWorld.getBlock(event.x, event.y, event.z); ItemStack currentTool = event.entityPlayer.getCurrentEquippedItem(); if(eventAction.RIGHT_CLICK_BLOCK != null){ System.out.println("Yes, You're Richtclicking"); if(currentWorld.getBlock(event.x, event.y, event.z) == Blocks.log){ System.out.println("a Log"); } if (OreDictionary.getOreName(OreDictionary.getOreID(currentTool)).equals("toolAxe")){ System.out.println("with an Axe!"); } } } } Main Class: package minothor.bab; import java.util.logging.Logger; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.event.ForgeEventFactory; import minothor.bab.proxy.*; import minothor.bab.items.*; import minothor.bab.blocks.*; import minothor.bab.events.EventHandlers.*; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; @Mod(modid="BigAssBarrels", name="Big Ass Barrels", version="1.7.2 - Alpha 0.0.1") public class bab { public static final String modid = "BigAssBarrels"; public static final String name = "Bigass Barrels"; public static final String version = "1.7.2 - Alpha 0.0.1"; @Instance(value = "BigAssBarrels") public static bab instance; @SidedProxy(clientSide="minothor.bab.proxy.clientProxy", serverSide="minothor.bab.proxy.commonProxy") public static commonProxy proxy; //Declare Tab //Set Creative Tab Icon public static CreativeTabs tabBAB; //public static CreativeTabs tabBAB; //Declare Items public static Item itemBark; public static Item itemCork; //Declare Blocks public static Block blockCork; public static Block blockStrippedOak; //Declare Tools public static Item itemMallet; //Declare Event Handler used public static CentEventHandler CentralHandler; //public static logger; @EventHandler public void preInit(FMLPreInitializationEvent event) { Configuration config = new Configuration(event.getSuggestedConfigurationFile()); config.load(); //config stuff here config.save(); tabBAB = new CreativeTabs("tabBAB"){ public Item getTabIconItem() { return itemCork; } }; itemBark = new Item().setUnlocalizedName("StrippedBark").setCreativeTab(tabBAB).setTextureName(modid + ":" + "StrippedBark"); GameRegistry.registerItem(itemBark, "StrippedBark"); itemCork= new Item().setUnlocalizedName("BottleCork").setCreativeTab(tabBAB).setTextureName(modid + ":" + "BottleCork"); GameRegistry.registerItem(itemCork, "BottleCork"); itemMallet = new itemMallet().setCreativeTab(tabBAB).setTextureName(modid + ":" + "WoodenMallet"); GameRegistry.registerItem(itemMallet, "WoodenMallet"); blockCork = new blockCork().setCreativeTab(tabBAB).setBlockTextureName(modid + ":" + "BlockCork"); GameRegistry.registerBlock(blockCork, "BlockCork"); blockStrippedOak = new blockStrippedOak().setCreativeTab(tabBAB); GameRegistry.registerBlock(blockStrippedOak, "BlockStrippedOak"); GameRegistry.addRecipe(new ItemStack(Item.getItemFromBlock(blockCork)), "XXX", "XYX", "XXX", 'X', new ItemStack(itemBark), 'Y', new ItemStack(itemCork)); GameRegistry.addRecipe(new ShapedOreRecipe( new ItemStack(itemMallet), "-X", "Y-", 'X', "logWood", 'Y', new ItemStack(Items.stick))); OreDictionary.registerOre("logWood", blockStrippedOak); GameRegistry.addRecipe(new ItemStack(Blocks.planks,4), "X", 'X', new ItemStack(Item.getItemFromBlock(blockStrippedOak))); GameRegistry.addRecipe(new ItemStack(itemCork), "X", "X", 'X', new ItemStack(itemBark)); //Creating toolAxe Oredictionary Section OreDictionary.registerOre("toolAxe", Items.wooden_axe); OreDictionary.registerOre("toolAxe", Items.stone_axe); OreDictionary.registerOre("toolAxe", Items.iron_axe); OreDictionary.registerOre("toolAxe", Items.golden_axe); OreDictionary.registerOre("toolAxe", Items.diamond_axe); //System.out.println(OreDictionary.getOres("toolAxe")); //Registering Events Handlers CentralHandler = new CentEventHandler(); } @EventHandler public void load(FMLInitializationEvent event) { proxy.registerRenderers(); } @EventHandler public void postInit(FMLPostInitializationEvent event) { // Stub Method } }
  24. Corrected: "minecraft:log_oak_top" instead of "minecraft:tree_top" Cheers All!
  25. Cheers Sequiturian! That explanation of what the parameters are was the final piece of the puzzle for me! I've now got the custom texture icon working and I've changed the block to extend BlockLog. All I need to do now is work out how to correctly reference the vanilla tree_top.png texture. I'll see if I can dig the original out of the TextureAtlas. blockStrippedOak class now: package minothor.bab.blocks; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.util.IIcon; import net.minecraft.block.*; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.world.World; public class blockStrippedOak extends BlockLog{ public blockStrippedOak() { super(); setBlockName("BlockStrippedOak"); setHarvestLevel("axe",0); setHardness(0.5F); setStepSound(Block.soundTypeWood); } @SideOnly(Side.CLIENT) protected IIcon[] icons; @SideOnly(Side.CLIENT) @Override public void registerBlockIcons(IIconRegister par1IconRegister) { this.icons = new IIcon[2]; //System.out.println("Icon Array Length: "+ icons.length); this.icons[0] = par1IconRegister.registerIcon("minecraft:Tree_Top"); System.out.println("icons 0 :" + icons[0]); this.icons[1] = par1IconRegister.registerIcon("bigassbarrels:StrippedLog"); //System.out.println("icons 1 :" + icons[1]); } @SideOnly(Side.CLIENT) @Override public IIcon getSideIcon(int metaD) { return this.icons[1]; } @SideOnly(Side.CLIENT) @Override public IIcon getTopIcon(int metaD) { return this.icons[0]; } public int onBlockPlaced (World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metaD) { /*int j1 = par9 & 3; byte b0 = 0; switch (par5) { case 0: case 1: b0 = 0; break; case 2: case 3: b0 = 8; break; case 4: case 5: b0 = 4; } return j1 | b0; */ System.out.println("Placed against side: " + side); System.out.println("Side / 2: " + (side/2)); System.out.println("Side % 2: " + (side%2)); return metaD; } } Console Log:
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.